qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
194,465 |
<p>What's the C++ way of parsing a string (given as char *) into an int? Robust and clear error handling is a plus (instead of <a href="http://en.cppreference.com/w/cpp/string/byte/atoi" rel="noreferrer">returning zero</a>).</p>
|
[
{
"answer_id": 194471,
"author": "Chris Arguin",
"author_id": 25704,
"author_profile": "https://Stackoverflow.com/users/25704",
"pm_score": 5,
"selected": false,
"text": "<p>The good 'old C way still works. I recommend strtol or strtoul. Between the return status and the 'endPtr', you can give good diagnostic output. It also handles multiple bases nicely.</p>\n"
},
{
"answer_id": 194478,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 3,
"selected": false,
"text": "<p>You can use <a href=\"http://www.cplusplus.com/reference/iostream/stringstream/\" rel=\"noreferrer\">stringstream's</a></p>\n\n<pre><code>int str2int (const string &str) {\n stringstream ss(str);\n int num;\n ss >> num;\n return num;\n}\n</code></pre>\n"
},
{
"answer_id": 194487,
"author": "jk.",
"author_id": 21284,
"author_profile": "https://Stackoverflow.com/users/21284",
"pm_score": 4,
"selected": false,
"text": "<p>You can use <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/conversion/lexical_cast.htm#lexical_cast\" rel=\"nofollow noreferrer\">Boost's <code>lexical_cast</code></a>, which <a href=\"https://stackoverflow.com/questions/194465/how-to-parse-a-string-to-an-int-in-c#194518\">wraps this</a> in a more generic interface.\n<code>lexical_cast<Target>(Source)</code> throws <code>bad_lexical_cast</code> on failure.</p>\n"
},
{
"answer_id": 194512,
"author": "Luka Marinko",
"author_id": 19814,
"author_profile": "https://Stackoverflow.com/users/19814",
"pm_score": 6,
"selected": false,
"text": "<p>This is a safer C way than atoi()</p>\n\n<pre><code>const char* str = \"123\";\nint i;\n\nif(sscanf(str, \"%d\", &i) == EOF )\n{\n /* error */\n}\n</code></pre>\n\n<p>C++ with standard library <a href=\"http://en.cppreference.com/w/cpp/io/basic_stringstream\" rel=\"noreferrer\">stringstream</a>: (thanks <a href=\"https://stackoverflow.com/questions/194465/how-to-parse-a-string-to-an-int-in-c#194478\">CMS</a> )</p>\n\n<pre><code>int str2int (const string &str) {\n stringstream ss(str);\n int num;\n if((ss >> num).fail())\n { \n //ERROR \n }\n return num;\n}\n</code></pre>\n\n<p>With <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/conversion/lexical_cast.htm#lexical_cast\" rel=\"noreferrer\">boost</a> library: (thanks <a href=\"https://stackoverflow.com/questions/194465/how-to-parse-a-string-to-an-int-in-c#194487\">jk</a>)</p>\n\n<pre><code>#include <boost/lexical_cast.hpp>\n#include <string>\n\ntry\n{\n std::string str = \"123\";\n int number = boost::lexical_cast< int >( str );\n}\ncatch( const boost::bad_lexical_cast & )\n{\n // Error\n}\n</code></pre>\n\n<p>Edit: Fixed the stringstream version so that it handles errors. (thanks to CMS's and jk's comment on original post)</p>\n"
},
{
"answer_id": 194518,
"author": "jk.",
"author_id": 21284,
"author_profile": "https://Stackoverflow.com/users/21284",
"pm_score": 4,
"selected": false,
"text": "<p>You can use the a stringstream from the C++ standard libraray:</p>\n\n<pre><code>stringstream ss(str);\nint x;\nss >> x;\n\nif(ss) { // <-- error handling\n // use x\n} else {\n // not a number\n}\n</code></pre>\n\n<blockquote>\n <p>The stream state will be set to fail\n if a non-digit is encountered when\n trying to read an integer.</p>\n</blockquote>\n\n<p>See <a href=\"http://www.horstmann.com/cpp/pitfalls.html\" rel=\"noreferrer\">Stream pitfalls</a> for pitfalls of errorhandling and streams in C++.</p>\n"
},
{
"answer_id": 1350601,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>The <a href=\"http://www.partow.net/programming/strtk/index.html\" rel=\"nofollow noreferrer\">C++ String Toolkit Library (StrTk)</a> has the following solution:</p>\n\n<pre><code>static const std::size_t digit_table_symbol_count = 256;\nstatic const unsigned char digit_table[digit_table_symbol_count] = {\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xFF - 0x07\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x08 - 0x0F\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x10 - 0x17\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x18 - 0x1F\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x20 - 0x27\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x28 - 0x2F\n 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, // 0x30 - 0x37\n 0x08, 0x09, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x38 - 0x3F\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x40 - 0x47\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x48 - 0x4F\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x50 - 0x57\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x58 - 0x5F\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x60 - 0x67\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x68 - 0x6F\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x70 - 0x77\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x78 - 0x7F\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x80 - 0x87\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x88 - 0x8F\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x90 - 0x97\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x98 - 0x9F\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xA0 - 0xA7\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xA8 - 0xAF\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xB0 - 0xB7\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xB8 - 0xBF\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xC0 - 0xC7\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xC8 - 0xCF\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xD0 - 0xD7\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xD8 - 0xDF\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xE0 - 0xE7\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xE8 - 0xEF\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xF0 - 0xF7\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF // 0xF8 - 0xFF\n };\n\ntemplate<typename InputIterator, typename T>\ninline bool string_to_signed_type_converter_impl_itr(InputIterator begin, InputIterator end, T& v)\n{\n if (0 == std::distance(begin,end))\n return false;\n v = 0;\n InputIterator it = begin;\n bool negative = false;\n if ('+' == *it)\n ++it;\n else if ('-' == *it)\n {\n ++it;\n negative = true;\n }\n if (end == it)\n return false;\n while(end != it)\n {\n const T digit = static_cast<T>(digit_table[static_cast<unsigned int>(*it++)]);\n if (0xFF == digit)\n return false;\n v = (10 * v) + digit;\n }\n if (negative)\n v *= -1;\n return true;\n}\n</code></pre>\n\n<p>The InputIterator can be of either unsigned char*, char* or std::string iterators, and T is expected to be a signed int, such as signed int, int, or long</p>\n"
},
{
"answer_id": 4328610,
"author": "caa",
"author_id": 527010,
"author_profile": "https://Stackoverflow.com/users/527010",
"pm_score": 3,
"selected": false,
"text": "<p>I think these three links sum it up:</p>\n\n<ul>\n<li><a href=\"http://tinodidriksen.com/2010/02/07/cpp-convert-int-to-string-speed/\">http://tinodidriksen.com/2010/02/07/cpp-convert-int-to-string-speed/</a></li>\n<li><em><strong><a href=\"http://tinodidriksen.com/2010/02/16/cpp-convert-string-to-int-speed/\">http://tinodidriksen.com/2010/02/16/cpp-convert-string-to-int-speed/</a></em></strong></li>\n<li><em><strong><a href=\"http://www.fastformat.org/performance.html\">http://www.fastformat.org/performance.html</a></em></strong></li>\n</ul>\n\n<p>stringstream and lexical_cast solutions are about the same as lexical cast is using stringstream.</p>\n\n<p>Some specializations of lexical cast use different approach see <strong><a href=\"http://www.boost.org/doc/libs/release/boost/lexical_cast.hpp\">http://www.boost.org/doc/libs/release/boost/lexical_cast.hpp</a></strong> for details. Integers and floats are now specialized for integer to string conversion. </p>\n\n<p>One can specialize lexical_cast for his/her own needs and make it fast. This would be the ultimate solution satisfying all parties, clean and simple.</p>\n\n<p>Articles already mentioned show comparison between different methods of converting integers <-> strings. Following approaches make sense: old c-way, spirit.karma, fastformat, simple naive loop. </p>\n\n<p>Lexical_cast is ok in some cases e.g. for int to string conversion.</p>\n\n<p>Converting string to int using lexical cast is not a good idea as it is 10-40 times slower than atoi depending on the platform/compiler used.</p>\n\n<p>Boost.Spirit.Karma seems to be the fastest library for converting integer to string.</p>\n\n<pre><code>ex.: generate(ptr_char, int_, integer_number);\n</code></pre>\n\n<p>and basic simple loop from the article mentioned above is a fastest way to convert string to int, obviously not the safest one, strtol() seems like a safer solution</p>\n\n<pre><code>int naive_char_2_int(const char *p) {\n int x = 0;\n bool neg = false;\n if (*p == '-') {\n neg = true;\n ++p;\n }\n while (*p >= '0' && *p <= '9') {\n x = (x*10) + (*p - '0');\n ++p;\n }\n if (neg) {\n x = -x;\n }\n return x;\n}\n</code></pre>\n"
},
{
"answer_id": 6154614,
"author": "Dan Moulding",
"author_id": 95706,
"author_profile": "https://Stackoverflow.com/users/95706",
"pm_score": 8,
"selected": false,
"text": "<h2>What not to do</h2>\n\n<p>Here is my first piece of advice: <strong>do not use stringstream for this</strong>. While at first it may seem simple to use, you'll find that you have to do a lot of extra work if you want robustness and good error handling.</p>\n\n<p>Here is an approach that intuitively seems like it should work:</p>\n\n<pre><code>bool str2int (int &i, char const *s)\n{\n std::stringstream ss(s);\n ss >> i;\n if (ss.fail()) {\n // not an integer\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>This has a major problem: <code>str2int(i, \"1337h4x0r\")</code> will happily return <code>true</code> and <code>i</code> will get the value <code>1337</code>. We can work around this problem by ensuring there are no more characters in the <code>stringstream</code> after the conversion:</p>\n\n<pre><code>bool str2int (int &i, char const *s)\n{\n char c;\n std::stringstream ss(s);\n ss >> i;\n if (ss.fail() || ss.get(c)) {\n // not an integer\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>We fixed one problem, but there are still a couple of other problems.</p>\n\n<p>What if the number in the string is not base 10? We can try to accommodate other bases by setting the stream to the correct mode (e.g. <code>ss << std::hex</code>) before trying the conversion. But this means the caller must know <em>a priori</em> what base the number is -- and how can the caller possibly know that? The caller doesn't know what the number is yet. They don't even know that it <em>is</em> a number! How can they be expected to know what base it is? We could just mandate that all numbers input to our programs must be base 10 and reject hexadecimal or octal input as invalid. But that is not very flexible or robust. There is no simple solution to this problem. You can't simply try the conversion once for each base, because the decimal conversion will always succeed for octal numbers (with a leading zero) and the octal conversion may succeed for some decimal numbers. So now you have to check for a leading zero. But wait! Hexadecimal numbers can start with a leading zero too (0x...). Sigh.</p>\n\n<p>Even if you succeed in dealing with the above problems, there is still another bigger problem: what if the caller needs to distinguish between bad input (e.g. \"123foo\") and a number that is out of the range of <code>int</code> (e.g. \"4000000000\" for 32-bit <code>int</code>)? With <code>stringstream</code>, there is no way to make this distinction. We only know whether the conversion succeeded or failed. If it fails, we have no way of knowing <em>why</em> it failed. As you can see, <code>stringstream</code> leaves much to be desired if you want robustness and clear error handling.</p>\n\n<p>This leads me to my second piece of advice: <strong>do no use Boost's <code>lexical_cast</code> for this</strong>. Consider what the <code>lexical_cast</code> documentation has to say:</p>\n\n<blockquote>\n <p>Where a higher degree of control is\n required over conversions,\n std::stringstream and\n std::wstringstream offer a more\n appropriate path. Where\n non-stream-based conversions are\n required, lexical_cast is the wrong\n tool for the job and is not\n special-cased for such scenarios.</p>\n</blockquote>\n\n<p>What?? We've already seen that <code>stringstream</code> has a poor level of control, and yet it says <code>stringstream</code> should be used instead of <code>lexical_cast</code> if you need \"a higher level of control\". Also, because <code>lexical_cast</code> is just a wrapper around <code>stringstream</code>, it suffers from the same problems that <code>stringstream</code> does: poor support for multiple number bases and poor error handling.</p>\n\n<h2>The best solution</h2>\n\n<p>Fortunately, somebody has already solved all of the above problems. The C standard library contains <code>strtol</code> and family which have none of these problems.</p>\n\n<pre><code>enum STR2INT_ERROR { SUCCESS, OVERFLOW, UNDERFLOW, INCONVERTIBLE };\n\nSTR2INT_ERROR str2int (int &i, char const *s, int base = 0)\n{\n char *end;\n long l;\n errno = 0;\n l = strtol(s, &end, base);\n if ((errno == ERANGE && l == LONG_MAX) || l > INT_MAX) {\n return OVERFLOW;\n }\n if ((errno == ERANGE && l == LONG_MIN) || l < INT_MIN) {\n return UNDERFLOW;\n }\n if (*s == '\\0' || *end != '\\0') {\n return INCONVERTIBLE;\n }\n i = l;\n return SUCCESS;\n}\n</code></pre>\n\n<p>Pretty simple for something that handles all the error cases and also supports any number base from 2 to 36. If <code>base</code> is zero (the default) it will try to convert from any base. Or the caller can supply the third argument and specify that the conversion should only be attempted for a particular base. It is robust and handles all errors with a minimal amount of effort.</p>\n\n<p>Other reasons to prefer <code>strtol</code> (and family):</p>\n\n<ul>\n<li>It exhibits much better <a href=\"http://tinodidriksen.com/2010/02/16/cpp-convert-string-to-int-speed/\" rel=\"noreferrer\">runtime performance</a></li>\n<li>It introduces less compile-time overhead (the others pull in nearly 20 times more SLOC from headers)</li>\n<li>It results in the smallest code size</li>\n</ul>\n\n<p>There is absolutely no good reason to use any other method.</p>\n"
},
{
"answer_id": 11354496,
"author": "CC.",
"author_id": 195527,
"author_profile": "https://Stackoverflow.com/users/195527",
"pm_score": 9,
"selected": true,
"text": "<p>In the new C++11 there are functions for that: stoi, stol, stoll, stoul and so on.</p>\n\n<pre><code>int myNr = std::stoi(myString);\n</code></pre>\n\n<p>It will throw an exception on conversion error.</p>\n\n<p>Even these new functions still have the <strong>same issue</strong> as noted by Dan: they will happily convert the string \"11x\" to integer \"11\".</p>\n\n<p>See more: <a href=\"http://en.cppreference.com/w/cpp/string/basic_string/stol\">http://en.cppreference.com/w/cpp/string/basic_string/stol</a></p>\n"
},
{
"answer_id": 17998820,
"author": "fuzzyTew",
"author_id": 129550,
"author_profile": "https://Stackoverflow.com/users/129550",
"pm_score": 3,
"selected": false,
"text": "<p>If you have C++11, the appropriate solutions nowadays are the C++ integer conversion functions in <code><string></code>: <code>stoi</code>, <code>stol</code>, <code>stoul</code>, <code>stoll</code>, <code>stoull</code>. They throw appropriate exceptions when given incorrect input and use the fast and small <code>strto*</code> functions under the hood.</p>\n\n<p>If you are stuck with an earlier revision of C++, it would be forward-portable of you to mimic these functions in your implementation.</p>\n"
},
{
"answer_id": 17999031,
"author": "BlackMamba",
"author_id": 2223579,
"author_profile": "https://Stackoverflow.com/users/2223579",
"pm_score": -1,
"selected": false,
"text": "<p>In C, you can use <code>int atoi (const char * str)</code>,</p>\n\n<p>Parses the C-string str interpreting its content as an integral number, which is returned as a value of type int.</p>\n"
},
{
"answer_id": 25223180,
"author": "user3925906",
"author_id": 3925906,
"author_profile": "https://Stackoverflow.com/users/3925906",
"pm_score": 2,
"selected": false,
"text": "<p>I like <a href=\"https://stackoverflow.com/a/6154614\">Dan Moulding's answer</a>, I'll just add a bit of C++ style to it:</p>\n\n<pre><code>#include <cstdlib>\n#include <cerrno>\n#include <climits>\n#include <stdexcept>\n\nint to_int(const std::string &s, int base = 0)\n{\n char *end;\n errno = 0;\n long result = std::strtol(s.c_str(), &end, base);\n if (errno == ERANGE || result > INT_MAX || result < INT_MIN)\n throw std::out_of_range(\"toint: string is out of range\");\n if (s.length() == 0 || *end != '\\0')\n throw std::invalid_argument(\"toint: invalid string\");\n return result;\n}\n</code></pre>\n\n<p>It works for both std::string and const char* through the implicit conversion. It's also useful for base conversion, e.g. all <code>to_int(\"0x7b\")</code> and <code>to_int(\"0173\")</code> and <code>to_int(\"01111011\", 2)</code> and <code>to_int(\"0000007B\", 16)</code> and <code>to_int(\"11120\", 3)</code> and <code>to_int(\"3L\", 34);</code> would return 123.</p>\n\n<p>Unlike <code>std::stoi</code> it works in pre-C++11. Also unlike <code>std::stoi</code>, <code>boost::lexical_cast</code> and <code>stringstream</code> it throws exceptions for weird strings like \"123hohoho\".</p>\n\n<p>NB: This function tolerates leading spaces but not trailing spaces, i.e. <code>to_int(\" 123\")</code> returns 123 while <code>to_int(\"123 \")</code> throws exception. Make sure this is acceptable for your use case or adjust the code.</p>\n\n<p>Such function could be part of STL...</p>\n"
},
{
"answer_id": 27724349,
"author": "Boris",
"author_id": 4403456,
"author_profile": "https://Stackoverflow.com/users/4403456",
"pm_score": 0,
"selected": false,
"text": "<p>You could use this defined method.</p>\n\n<pre><code>#define toInt(x) {atoi(x.c_str())};\n</code></pre>\n\n<p>And if you were to convert from String to an Integer, you would just do the following.</p>\n\n<pre><code>int main()\n{\nstring test = \"46\", test2 = \"56\";\nint a = toInt(test);\nint b = toInt(test2);\ncout<<a+b<<endl;\n}\n</code></pre>\n\n<p>The output would be 102.</p>\n"
},
{
"answer_id": 31196698,
"author": "DreamWarrior",
"author_id": 4995485,
"author_profile": "https://Stackoverflow.com/users/4995485",
"pm_score": 0,
"selected": false,
"text": "<p>I know this is an older question, but I've come across it so many times and, to date, have still not found a nicely templated solution having the following characteristics:</p>\n\n<ul>\n<li>Can convert any base (and detect base type)</li>\n<li>Will detect erroneous data (i.e. ensure the entire string, less leading/trailing whitespace, is consumed by the conversion)</li>\n<li>Will ensure that, regardless of the type converted to, the range of the string's value is acceptable.</li>\n</ul>\n\n<p>So, here is mine, with a test strap. Because it uses the C functions strtoull/strtoll under the hood, it always converts first to the largest type available. Then, if you are not using the largest type, it will perform additional range checks to verify your type was not over(under)flowed. For this, it is a little less performant than if one properly chose strtol/strtoul. However, it also works for shorts/chars and, to the best of my knowledge, there exists no standard library function that does that, too.</p>\n\n<p>Enjoy; hopefully someone finds it useful.</p>\n\n<pre><code>#include <cstdlib>\n#include <cerrno>\n#include <limits>\n#include <stdexcept>\n#include <sstream>\n\nstatic const int DefaultBase = 10;\n\ntemplate<typename T>\nstatic inline T CstrtoxllWrapper(const char *str, int base = DefaultBase)\n{\n while (isspace(*str)) str++; // remove leading spaces; verify there's data\n if (*str == '\\0') { throw std::invalid_argument(\"str; no data\"); } // nothing to convert\n\n // NOTE: for some reason strtoull allows a negative sign, we don't; if\n // converting to an unsigned then it must always be positive!\n if (!std::numeric_limits<T>::is_signed && *str == '-')\n { throw std::invalid_argument(\"str; negative\"); }\n\n // reset errno and call fn (either strtoll or strtoull)\n errno = 0;\n char *ePtr;\n T tmp = std::numeric_limits<T>::is_signed ? strtoll(str, &ePtr, base)\n : strtoull(str, &ePtr, base);\n\n // check for any C errors -- note these are range errors on T, which may\n // still be out of the range of the actual type we're using; the caller\n // may need to perform additional range checks.\n if (errno != 0) \n {\n if (errno == ERANGE) { throw std::range_error(\"str; out of range\"); }\n else if (errno == EINVAL) { throw std::invalid_argument(\"str; EINVAL\"); }\n else { throw std::invalid_argument(\"str; unknown errno\"); }\n }\n\n // verify everything converted -- extraneous spaces are allowed\n if (ePtr != NULL)\n {\n while (isspace(*ePtr)) ePtr++;\n if (*ePtr != '\\0') { throw std::invalid_argument(\"str; bad data\"); }\n }\n\n return tmp;\n}\n\ntemplate<typename T>\nT StringToSigned(const char *str, int base = DefaultBase)\n{\n static const long long max = std::numeric_limits<T>::max();\n static const long long min = std::numeric_limits<T>::min();\n\n long long tmp = CstrtoxllWrapper<typeof(tmp)>(str, base); // use largest type\n\n // final range check -- only needed if not long long type; a smart compiler\n // should optimize this whole thing out\n if (sizeof(T) == sizeof(tmp)) { return tmp; }\n\n if (tmp < min || tmp > max)\n {\n std::ostringstream err;\n err << \"str; value \" << tmp << \" out of \" << sizeof(T) * 8\n << \"-bit signed range (\";\n if (sizeof(T) != 1) err << min << \"..\" << max;\n else err << (int) min << \"..\" << (int) max; // don't print garbage chars\n err << \")\";\n throw std::range_error(err.str());\n }\n\n return tmp;\n}\n\ntemplate<typename T>\nT StringToUnsigned(const char *str, int base = DefaultBase)\n{\n static const unsigned long long max = std::numeric_limits<T>::max();\n\n unsigned long long tmp = CstrtoxllWrapper<typeof(tmp)>(str, base); // use largest type\n\n // final range check -- only needed if not long long type; a smart compiler\n // should optimize this whole thing out\n if (sizeof(T) == sizeof(tmp)) { return tmp; }\n\n if (tmp > max)\n {\n std::ostringstream err;\n err << \"str; value \" << tmp << \" out of \" << sizeof(T) * 8\n << \"-bit unsigned range (0..\";\n if (sizeof(T) != 1) err << max;\n else err << (int) max; // don't print garbage chars\n err << \")\";\n throw std::range_error(err.str());\n }\n\n return tmp;\n}\n\ntemplate<typename T>\ninline T\nStringToDecimal(const char *str, int base = DefaultBase)\n{\n return std::numeric_limits<T>::is_signed ? StringToSigned<T>(str, base)\n : StringToUnsigned<T>(str, base);\n}\n\ntemplate<typename T>\ninline T\nStringToDecimal(T &out_convertedVal, const char *str, int base = DefaultBase)\n{\n return out_convertedVal = StringToDecimal<T>(str, base);\n}\n\n/*============================== [ Test Strap ] ==============================*/ \n\n#include <inttypes.h>\n#include <iostream>\n\nstatic bool _g_anyFailed = false;\n\ntemplate<typename T>\nvoid TestIt(const char *tName,\n const char *s, int base,\n bool successExpected = false, T expectedValue = 0)\n{\n #define FAIL(s) { _g_anyFailed = true; std::cout << s; }\n\n T x;\n std::cout << \"converting<\" << tName << \">b:\" << base << \" [\" << s << \"]\";\n try\n {\n StringToDecimal<T>(x, s, base);\n // get here on success only\n if (!successExpected)\n {\n FAIL(\" -- TEST FAILED; SUCCESS NOT EXPECTED!\" << std::endl);\n }\n else\n {\n std::cout << \" -> \";\n if (sizeof(T) != 1) std::cout << x;\n else std::cout << (int) x; // don't print garbage chars\n if (x != expectedValue)\n {\n FAIL(\"; FAILED (expected value:\" << expectedValue << \")!\");\n }\n std::cout << std::endl;\n }\n }\n catch (std::exception &e)\n {\n if (successExpected)\n {\n FAIL( \" -- TEST FAILED; EXPECTED SUCCESS!\"\n << \" (got:\" << e.what() << \")\" << std::endl);\n }\n else\n {\n std::cout << \"; expected exception encounterd: [\" << e.what() << \"]\" << std::endl;\n }\n }\n}\n\n#define TEST(t, s, ...) \\\n TestIt<t>(#t, s, __VA_ARGS__);\n\nint main()\n{\n std::cout << \"============ variable base tests ============\" << std::endl;\n TEST(int, \"-0xF\", 0, true, -0xF);\n TEST(int, \"+0xF\", 0, true, 0xF);\n TEST(int, \"0xF\", 0, true, 0xF);\n TEST(int, \"-010\", 0, true, -010);\n TEST(int, \"+010\", 0, true, 010);\n TEST(int, \"010\", 0, true, 010);\n TEST(int, \"-10\", 0, true, -10);\n TEST(int, \"+10\", 0, true, 10);\n TEST(int, \"10\", 0, true, 10);\n\n std::cout << \"============ base-10 tests ============\" << std::endl;\n TEST(int, \"-010\", 10, true, -10);\n TEST(int, \"+010\", 10, true, 10);\n TEST(int, \"010\", 10, true, 10);\n TEST(int, \"-10\", 10, true, -10);\n TEST(int, \"+10\", 10, true, 10);\n TEST(int, \"10\", 10, true, 10);\n TEST(int, \"00010\", 10, true, 10);\n\n std::cout << \"============ base-8 tests ============\" << std::endl;\n TEST(int, \"777\", 8, true, 0777);\n TEST(int, \"-0111 \", 8, true, -0111);\n TEST(int, \"+0010 \", 8, true, 010);\n\n std::cout << \"============ base-16 tests ============\" << std::endl;\n TEST(int, \"DEAD\", 16, true, 0xDEAD);\n TEST(int, \"-BEEF\", 16, true, -0xBEEF);\n TEST(int, \"+C30\", 16, true, 0xC30);\n\n std::cout << \"============ base-2 tests ============\" << std::endl;\n TEST(int, \"-10011001\", 2, true, -153);\n TEST(int, \"10011001\", 2, true, 153);\n\n std::cout << \"============ irregular base tests ============\" << std::endl;\n TEST(int, \"Z\", 36, true, 35);\n TEST(int, \"ZZTOP\", 36, true, 60457993);\n TEST(int, \"G\", 17, true, 16);\n TEST(int, \"H\", 17);\n\n std::cout << \"============ space deliminated tests ============\" << std::endl;\n TEST(int, \"1337 \", 10, true, 1337);\n TEST(int, \" FEAD\", 16, true, 0xFEAD);\n TEST(int, \" 0711 \", 0, true, 0711);\n\n std::cout << \"============ bad data tests ============\" << std::endl;\n TEST(int, \"FEAD\", 10);\n TEST(int, \"1234 asdfklj\", 10);\n TEST(int, \"-0xF\", 10);\n TEST(int, \"+0xF\", 10);\n TEST(int, \"0xF\", 10);\n TEST(int, \"-F\", 10);\n TEST(int, \"+F\", 10);\n TEST(int, \"12.4\", 10);\n TEST(int, \"ABG\", 16);\n TEST(int, \"10011002\", 2);\n\n std::cout << \"============ int8_t range tests ============\" << std::endl;\n TEST(int8_t, \"7F\", 16, true, std::numeric_limits<int8_t>::max());\n TEST(int8_t, \"80\", 16);\n TEST(int8_t, \"-80\", 16, true, std::numeric_limits<int8_t>::min());\n TEST(int8_t, \"-81\", 16);\n TEST(int8_t, \"FF\", 16);\n TEST(int8_t, \"100\", 16);\n\n std::cout << \"============ uint8_t range tests ============\" << std::endl;\n TEST(uint8_t, \"7F\", 16, true, std::numeric_limits<int8_t>::max());\n TEST(uint8_t, \"80\", 16, true, std::numeric_limits<int8_t>::max()+1);\n TEST(uint8_t, \"-80\", 16);\n TEST(uint8_t, \"-81\", 16);\n TEST(uint8_t, \"FF\", 16, true, std::numeric_limits<uint8_t>::max());\n TEST(uint8_t, \"100\", 16);\n\n std::cout << \"============ int16_t range tests ============\" << std::endl;\n TEST(int16_t, \"7FFF\", 16, true, std::numeric_limits<int16_t>::max());\n TEST(int16_t, \"8000\", 16);\n TEST(int16_t, \"-8000\", 16, true, std::numeric_limits<int16_t>::min());\n TEST(int16_t, \"-8001\", 16);\n TEST(int16_t, \"FFFF\", 16);\n TEST(int16_t, \"10000\", 16);\n\n std::cout << \"============ uint16_t range tests ============\" << std::endl;\n TEST(uint16_t, \"7FFF\", 16, true, std::numeric_limits<int16_t>::max());\n TEST(uint16_t, \"8000\", 16, true, std::numeric_limits<int16_t>::max()+1);\n TEST(uint16_t, \"-8000\", 16);\n TEST(uint16_t, \"-8001\", 16);\n TEST(uint16_t, \"FFFF\", 16, true, std::numeric_limits<uint16_t>::max());\n TEST(uint16_t, \"10000\", 16);\n\n std::cout << \"============ int32_t range tests ============\" << std::endl;\n TEST(int32_t, \"7FFFFFFF\", 16, true, std::numeric_limits<int32_t>::max());\n TEST(int32_t, \"80000000\", 16);\n TEST(int32_t, \"-80000000\", 16, true, std::numeric_limits<int32_t>::min());\n TEST(int32_t, \"-80000001\", 16);\n TEST(int32_t, \"FFFFFFFF\", 16);\n TEST(int32_t, \"100000000\", 16);\n\n std::cout << \"============ uint32_t range tests ============\" << std::endl;\n TEST(uint32_t, \"7FFFFFFF\", 16, true, std::numeric_limits<int32_t>::max());\n TEST(uint32_t, \"80000000\", 16, true, std::numeric_limits<int32_t>::max()+1);\n TEST(uint32_t, \"-80000000\", 16);\n TEST(uint32_t, \"-80000001\", 16);\n TEST(uint32_t, \"FFFFFFFF\", 16, true, std::numeric_limits<uint32_t>::max());\n TEST(uint32_t, \"100000000\", 16);\n\n std::cout << \"============ int64_t range tests ============\" << std::endl;\n TEST(int64_t, \"7FFFFFFFFFFFFFFF\", 16, true, std::numeric_limits<int64_t>::max());\n TEST(int64_t, \"8000000000000000\", 16);\n TEST(int64_t, \"-8000000000000000\", 16, true, std::numeric_limits<int64_t>::min());\n TEST(int64_t, \"-8000000000000001\", 16);\n TEST(int64_t, \"FFFFFFFFFFFFFFFF\", 16);\n TEST(int64_t, \"10000000000000000\", 16);\n\n std::cout << \"============ uint64_t range tests ============\" << std::endl;\n TEST(uint64_t, \"7FFFFFFFFFFFFFFF\", 16, true, std::numeric_limits<int64_t>::max());\n TEST(uint64_t, \"8000000000000000\", 16, true, std::numeric_limits<int64_t>::max()+1);\n TEST(uint64_t, \"-8000000000000000\", 16);\n TEST(uint64_t, \"-8000000000000001\", 16);\n TEST(uint64_t, \"FFFFFFFFFFFFFFFF\", 16, true, std::numeric_limits<uint64_t>::max());\n TEST(uint64_t, \"10000000000000000\", 16);\n\n std::cout << std::endl << std::endl\n << (_g_anyFailed ? \"!! SOME TESTS FAILED !!\" : \"ALL TESTS PASSED\")\n << std::endl;\n\n return _g_anyFailed;\n}\n</code></pre>\n\n<p><code>StringToDecimal</code> is the user-land method; it is overloaded so it can be called either like this:</p>\n\n<pre><code>int a; a = StringToDecimal<int>(\"100\");\n</code></pre>\n\n<p>or this:</p>\n\n<pre><code>int a; StringToDecimal(a, \"100\");\n</code></pre>\n\n<p>I hate repeating the int type, so prefer the latter. This ensures that if the type of 'a' changes one does not get bad results. I wish the compiler could figure it out like:</p>\n\n<pre><code>int a; a = StringToDecimal(\"100\");\n</code></pre>\n\n<p>...but, C++ does not deduce template return types, so that's the best I can get.</p>\n\n<p>The implementation is pretty simple:</p>\n\n<p><code>CstrtoxllWrapper</code> wraps both <code>strtoull</code> and <code>strtoll</code>, calling whichever is necessary based on the template type's signed-ness and providing some additional guarantees (e.g. negative input is disallowed if unsigned and it ensures the entire string was converted).</p>\n\n<p><code>CstrtoxllWrapper</code> is used by <code>StringToSigned</code> and <code>StringToUnsigned</code> with the largest type (long long/unsigned long long) available to the compiler; this allows the maximal conversion to be performed. Then, if it is necessary, <code>StringToSigned</code>/<code>StringToUnsigned</code> performs the final range checks on the underlying type. Finally, the end-point method, <code>StringToDecimal</code>, decides which of the StringTo* template methods to call based on the underlying type's signed-ness.</p>\n\n<p>I think most of the junk can be optimized out by the compiler; just about everything should be compile-time deterministic. Any commentary on this aspect would be interesting to me!</p>\n"
},
{
"answer_id": 35204010,
"author": "pellucide",
"author_id": 892771,
"author_profile": "https://Stackoverflow.com/users/892771",
"pm_score": 1,
"selected": false,
"text": "<p>I like <a href=\"https://stackoverflow.com/a/6154614/892771\">Dan's answer</a>, esp because of the avoidance of exceptions. For embedded systems development and other low level system development, there may not be a proper Exception framework available. </p>\n\n<p>Added a check for white-space after a valid string...these three lines</p>\n\n<pre><code> while (isspace(*end)) {\n end++;\n }\n</code></pre>\n\n<p><br>\nAdded a check for parsing errors too.</p>\n\n<pre><code> if ((errno != 0) || (s == end)) {\n return INCONVERTIBLE;\n }\n</code></pre>\n\n<p><br>\nHere is the complete function..</p>\n\n<pre><code>#include <cstdlib>\n#include <cerrno>\n#include <climits>\n#include <stdexcept>\n\nenum STR2INT_ERROR { SUCCESS, OVERFLOW, UNDERFLOW, INCONVERTIBLE };\n\nSTR2INT_ERROR str2long (long &l, char const *s, int base = 0)\n{\n char *end = (char *)s;\n errno = 0;\n\n l = strtol(s, &end, base);\n\n if ((errno == ERANGE) && (l == LONG_MAX)) {\n return OVERFLOW;\n }\n if ((errno == ERANGE) && (l == LONG_MIN)) {\n return UNDERFLOW;\n }\n if ((errno != 0) || (s == end)) {\n return INCONVERTIBLE;\n } \n while (isspace((unsigned char)*end)) {\n end++;\n }\n\n if (*s == '\\0' || *end != '\\0') {\n return INCONVERTIBLE;\n }\n\n return SUCCESS;\n}\n</code></pre>\n"
},
{
"answer_id": 44275053,
"author": "Iqra.",
"author_id": 7596696,
"author_profile": "https://Stackoverflow.com/users/7596696",
"pm_score": 2,
"selected": false,
"text": "<p>I know three ways of converting String into int:</p>\n\n<p>Either use stoi(String to int) function or just go with Stringstream, the third way to go individual conversion, Code is below:</p>\n\n<p><strong>1st Method</strong></p>\n\n<pre><code>std::string s1 = \"4533\";\nstd::string s2 = \"3.010101\";\nstd::string s3 = \"31337 with some string\";\n\nint myint1 = std::stoi(s1);\nint myint2 = std::stoi(s2);\nint myint3 = std::stoi(s3);\n\nstd::cout << s1 <<\"=\" << myint1 << '\\n';\nstd::cout << s2 <<\"=\" << myint2 << '\\n';\nstd::cout << s3 <<\"=\" << myint3 << '\\n';\n</code></pre>\n\n<p><strong>2nd Method</strong></p>\n\n<pre><code>#include <string.h>\n#include <sstream>\n#include <iostream>\n#include <cstring>\nusing namespace std;\n\n\nint StringToInteger(string NumberAsString)\n{\n int NumberAsInteger;\n stringstream ss;\n ss << NumberAsString;\n ss >> NumberAsInteger;\n return NumberAsInteger;\n}\nint main()\n{\n string NumberAsString;\n cin >> NumberAsString;\n cout << StringToInteger(NumberAsString) << endl;\n return 0;\n} \n</code></pre>\n\n<p><strong>3rd Method - but not for an individual conversion</strong> </p>\n\n<pre><code>std::string str4 = \"453\";\nint i = 0, in=0; // 453 as on\nfor ( i = 0; i < str4.length(); i++)\n{\n\n in = str4[i];\n cout <<in-48 ;\n\n}\n</code></pre>\n"
},
{
"answer_id": 48917248,
"author": "Pharap",
"author_id": 1377706,
"author_profile": "https://Stackoverflow.com/users/1377706",
"pm_score": 4,
"selected": false,
"text": "<p>From C++17 onwards you can use <code>std::from_chars</code> from the <code><charconv></code> header as documented <a href=\"http://en.cppreference.com/w/cpp/utility/from_chars\" rel=\"noreferrer\">here</a>.</p>\n\n<p>For example:</p>\n\n<pre><code>#include <iostream>\n#include <charconv>\n#include <array>\n\nint main()\n{\n char const * str = \"42\";\n int value = 0;\n\n std::from_chars_result result = std::from_chars(std::begin(str), std::end(str), value);\n\n if(result.error == std::errc::invalid_argument)\n {\n std::cout << \"Error, invalid format\";\n }\n else if(result.error == std::errc::result_out_of_range)\n {\n std::cout << \"Error, value too big for int range\";\n }\n else\n {\n std::cout << \"Success: \" << result;\n }\n}\n</code></pre>\n\n<p>As a bonus, it can also handle other bases, like hexadecimal.</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3827/"
] |
What's the C++ way of parsing a string (given as char \*) into an int? Robust and clear error handling is a plus (instead of [returning zero](http://en.cppreference.com/w/cpp/string/byte/atoi)).
|
In the new C++11 there are functions for that: stoi, stol, stoll, stoul and so on.
```
int myNr = std::stoi(myString);
```
It will throw an exception on conversion error.
Even these new functions still have the **same issue** as noted by Dan: they will happily convert the string "11x" to integer "11".
See more: <http://en.cppreference.com/w/cpp/string/basic_string/stol>
|
194,484 |
<p>I collect a few corner cases and <a href="http://www.yoda.arachsys.com/csharp/teasers.html" rel="nofollow noreferrer">brain teasers</a> and would always like to hear more. The page only really covers C# language bits and bobs, but I also find core .NET things interesting too. For example, here's one which isn't on the page, but which I find incredible:</p>
<pre><code>string x = new string(new char[0]);
string y = new string(new char[0]);
Console.WriteLine(object.ReferenceEquals(x, y));
</code></pre>
<p>I'd expect that to print False - after all, "new" (with a reference type) <em>always</em> creates a new object, doesn't it? The specs for both C# and the CLI indicate that it should. Well, not in this particular case. It prints True, and has done on every version of the framework I've tested it with. (I haven't tried it on Mono, admittedly...)</p>
<p>Just to be clear, this is only an example of the kind of thing I'm looking for - I wasn't particularly looking for discussion/explanation of this oddity. (It's not the same as normal string interning; in particular, string interning doesn't normally happen when a constructor is called.) I was really asking for similar odd behaviour.</p>
<p>Any other gems lurking out there?</p>
|
[
{
"answer_id": 194671,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 10,
"selected": true,
"text": "<p>I think I showed you this one before, but I like the fun here - this took some debugging to track down! (the original code was obviously more complex and subtle...)</p>\n\n<pre><code> static void Foo<T>() where T : new()\n {\n T t = new T();\n Console.WriteLine(t.ToString()); // works fine\n Console.WriteLine(t.GetHashCode()); // works fine\n Console.WriteLine(t.Equals(t)); // works fine\n\n // so it looks like an object and smells like an object...\n\n // but this throws a NullReferenceException...\n Console.WriteLine(t.GetType());\n }\n</code></pre>\n\n<p>So what was T...</p>\n\n<p>Answer: any <code>Nullable<T></code> - such as <code>int?</code>. All the methods are overridden, except GetType() which can't be; so it is cast (boxed) to object (and hence to null) to call object.GetType()... which calls on null ;-p</p>\n\n<hr>\n\n<p>Update: the plot thickens... Ayende Rahien threw down a <a href=\"http://ayende.com/Blog/archive/2009/11/25/can-you-hack-this-out-hint-1.aspx\" rel=\"nofollow noreferrer\">similar challenge on his blog</a>, but with a <code>where T : class, new()</code>:</p>\n\n<pre><code>private static void Main() {\n CanThisHappen<MyFunnyType>();\n}\n\npublic static void CanThisHappen<T>() where T : class, new() {\n var instance = new T(); // new() on a ref-type; should be non-null, then\n Debug.Assert(instance != null, \"How did we break the CLR?\");\n}\n</code></pre>\n\n<p>But it can be defeated! Using the same indirection used by things like remoting; warning - the following is <strong>pure evil</strong>:</p>\n\n<pre><code>class MyFunnyProxyAttribute : ProxyAttribute {\n public override MarshalByRefObject CreateInstance(Type serverType) {\n return null;\n }\n}\n[MyFunnyProxy]\nclass MyFunnyType : ContextBoundObject { }\n</code></pre>\n\n<p>With this in place, the <code>new()</code> call is redirected to the proxy (<code>MyFunnyProxyAttribute</code>), which returns <code>null</code>. Now go and wash your eyes!</p>\n"
},
{
"answer_id": 194685,
"author": "Joshua",
"author_id": 14768,
"author_profile": "https://Stackoverflow.com/users/14768",
"pm_score": 3,
"selected": false,
"text": "<pre><code>Public Class Item\n Public ID As Guid\n Public Text As String\n\n Public Sub New(ByVal id As Guid, ByVal name As String)\n Me.ID = id\n Me.Text = name\n End Sub\nEnd Class\n\nPublic Sub Load(sender As Object, e As EventArgs) Handles Me.Load\n Dim box As New ComboBox\n Me.Controls.Add(box) 'Sorry I forgot this line the first time.'\n Dim h As IntPtr = box.Handle 'Im not sure you need this but you might.'\n Try\n box.Items.Add(New Item(Guid.Empty, Nothing))\n Catch ex As Exception\n MsgBox(ex.ToString())\n End Try\nEnd Sub\n</code></pre>\n\n<p>The output is \"Attempted to read protected memory. This is an indication that other memory is corrupt.\"</p>\n"
},
{
"answer_id": 195143,
"author": "Samuel Kim",
"author_id": 437435,
"author_profile": "https://Stackoverflow.com/users/437435",
"pm_score": 8,
"selected": false,
"text": "<p>Bankers' Rounding.</p>\n\n<p>This one is not so much a compiler bug or malfunction, but certainly a strange corner case...</p>\n\n<p>The .Net Framework employs a scheme or rounding known as Banker's Rounding.</p>\n\n<p>In Bankers' Rounding the 0.5 numbers are rounded to the nearest even number, so</p>\n\n<pre><code>Math.Round(-0.5) == 0\nMath.Round(0.5) == 0\nMath.Round(1.5) == 2\nMath.Round(2.5) == 2\netc...\n</code></pre>\n\n<p>This can lead to some unexpected bugs in financial calculations based on the more well known Round-Half-Up rounding.</p>\n\n<p>This is also true of Visual Basic.</p>\n"
},
{
"answer_id": 195611,
"author": "James Z",
"author_id": 26135,
"author_profile": "https://Stackoverflow.com/users/26135",
"pm_score": -1,
"selected": false,
"text": "<p>I think the answer to the question is because .net uses string interning something that might cause equal strings to point to the same object (since a strings are mutable this is not a problem)</p>\n\n<p>(I'm not talking about the overridden equality operator on the string class)</p>\n"
},
{
"answer_id": 195636,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 4,
"selected": false,
"text": "<p>Interesting - when I first looked at that I assumed it was something the C# compiler was checking for, but even if you emit the IL directly to remove any chance of interference it still happens, which means it really is the <code>newobj</code> op-code that's doing the checking.</p>\n\n<pre><code>var method = new DynamicMethod(\"Test\", null, null);\nvar il = method.GetILGenerator();\n\nil.Emit(OpCodes.Ldc_I4_0);\nil.Emit(OpCodes.Newarr, typeof(char));\nil.Emit(OpCodes.Newobj, typeof(string).GetConstructor(new[] { typeof(char[]) }));\n\nil.Emit(OpCodes.Ldc_I4_0);\nil.Emit(OpCodes.Newarr, typeof(char));\nil.Emit(OpCodes.Newobj, typeof(string).GetConstructor(new[] { typeof(char[]) }));\n\nil.Emit(OpCodes.Call, typeof(object).GetMethod(\"ReferenceEquals\"));\nil.Emit(OpCodes.Box, typeof(bool));\nil.Emit(OpCodes.Call, typeof(Console).GetMethod(\"WriteLine\", new[] { typeof(object) }));\n\nil.Emit(OpCodes.Ret);\n\nmethod.Invoke(null, null);\n</code></pre>\n\n<p>It also equates to <code>true</code> if you check against <code>string.Empty</code> which means this op-code must have special behaviour to intern empty strings.</p>\n"
},
{
"answer_id": 195808,
"author": "Jonathan Allen",
"author_id": 5274,
"author_profile": "https://Stackoverflow.com/users/5274",
"pm_score": 6,
"selected": false,
"text": "<p><strong>When is a Boolean neither True nor False?</strong></p>\n\n<p>Bill discovered that you can hack a boolean so that if A is True and B is True, (A and B) is False.</p>\n\n<p><a href=\"http://blogs.msmvps.com/bill/2004/06/22/a-hacked-boolean/\" rel=\"nofollow noreferrer\">Hacked Booleans</a></p>\n"
},
{
"answer_id": 195824,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 7,
"selected": false,
"text": "<p>What will this function do if called as <code>Rec(0)</code> (not under the debugger)?</p>\n\n<pre><code>static void Rec(int i)\n{\n Console.WriteLine(i);\n if (i < int.MaxValue)\n {\n Rec(i + 1);\n }\n}\n</code></pre>\n\n<p>Answer:</p>\n\n<ul>\n<li>On 32-bit JIT it should result in a StackOverflowException</li>\n<li>On 64-bit JIT it should print all the numbers to int.MaxValue</li>\n</ul>\n\n<p>This is because <a href=\"http://blogs.msdn.com/davbr/pages/tail-call-jit-conditions.aspx\" rel=\"noreferrer\">the 64-bit JIT compiler applies tail call optimisation</a>, whereas the 32-bit JIT does not. </p>\n\n<p>Unfortunately I haven't got a 64-bit machine to hand to verify this, but the method does meet all the conditions for tail-call optimisation. If anybody does have one I'd be interested to see if it's true.</p>\n"
},
{
"answer_id": 241451,
"author": "Craig Eddy",
"author_id": 5557,
"author_profile": "https://Stackoverflow.com/users/5557",
"pm_score": -1,
"selected": false,
"text": "<p>The following prints False instead of throwing an overflow exception:</p>\n\n<pre><code>Console.WriteLine(\"{0}\", yep(int.MaxValue ));\n\n\nprivate bool yep( int val )\n{\n return ( 0 < val * 2);\n}\n</code></pre>\n"
},
{
"answer_id": 241491,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": -1,
"selected": false,
"text": "<p>This one had me truly puzzled (I apologise for the length but it's WinForm). I posted it in the <a href=\"http://bytes.com/forum/thread615727.html\" rel=\"nofollow noreferrer\">newsgroups</a> a while back.</p>\n\n<blockquote>\n <p>I've come across an interesting bug. I\n have workarounds but i'd like to know\n the root of the problem. I've stripped\n it down into a short file and hope\n someone might have an idea about\n what's going on.</p>\n \n <p>It's a simple program that loads a\n control onto a form and binds \"Foo\"\n against a combobox (\"SelectedItem\")\n for it's \"Bar\" property and a\n datetimepicker (\"Value\") for it's\n \"DateTime\" property. The\n DateTimePicker.Visible value is set to\n false. Once it's loaded up, select the\n combobox and then attempt to deselect\n it by selecting the checkbox. This is\n rendered impossible by the combobox\n retaining the focus, you cannot even\n close the form, such is it's grasp on\n the focus.</p>\n \n <p>I have found three ways of fixing this\n problem.</p>\n \n <p>a) Remove the binding to Bar (a bit\n obvious) </p>\n \n <p>b) Remove the binding to\n DateTime </p>\n \n <p>c) Make the DateTimePicker\n visible !?!</p>\n \n <p>I'm currently running Win2k. And .NET\n 2.00, I think 1.1 has the same problem. Code is below.</p>\n</blockquote>\n\n<pre><code>using System;\nusing System.Collections;\nusing System.Windows.Forms;\n\nnamespace WindowsApplication6\n{\n public class Bar\n {\n public Bar()\n {\n }\n }\n\n public class Foo\n {\n private Bar m_Bar = new Bar();\n private DateTime m_DateTime = DateTime.Now;\n\n public Foo()\n {\n }\n\n public Bar Bar\n {\n get\n {\n return m_Bar;\n }\n set\n {\n m_Bar = value;\n }\n }\n\n public DateTime DateTime\n {\n get\n {\n return m_DateTime;\n }\n set\n {\n m_DateTime = value;\n }\n }\n }\n\n public class TestBugControl : UserControl\n {\n public TestBugControl()\n {\n InitializeComponent();\n }\n\n public void InitializeData(IList types)\n {\n this.cBoxType.DataSource = types;\n }\n\n public void BindFoo(Foo foo)\n {\n this.cBoxType.DataBindings.Add(\"SelectedItem\", foo, \"Bar\");\n this.dtStart.DataBindings.Add(\"Value\", foo, \"DateTime\");\n }\n\n /// <summary>\n /// Required designer variable.\n /// </summary>\n private System.ComponentModel.IContainer components = null;\n\n /// <summary>\n /// Clean up any resources being used.\n /// </summary>\n /// <param name=\"disposing\">true if managed resources should be disposed; otherwise, false.</param>\n protected override void Dispose(bool disposing)\n {\n if (disposing && (components != null))\n {\n components.Dispose();\n }\n base.Dispose(disposing);\n }\n\n #region Component Designer generated code\n\n /// <summary>\n /// Required method for Designer support - do not modify\n /// the contents of this method with the code editor.\n /// </summary>\n private void InitializeComponent()\n {\n this.checkBox1 = new System.Windows.Forms.CheckBox();\n this.cBoxType = new System.Windows.Forms.ComboBox();\n this.dtStart = new System.Windows.Forms.DateTimePicker();\n this.SuspendLayout();\n //\n // checkBox1\n //\n this.checkBox1.AutoSize = true;\n this.checkBox1.Location = new System.Drawing.Point(14, 5);\n this.checkBox1.Name = \"checkBox1\";\n this.checkBox1.Size = new System.Drawing.Size(97, 20);\n this.checkBox1.TabIndex = 0;\n this.checkBox1.Text = \"checkBox1\";\n this.checkBox1.UseVisualStyleBackColor = true;\n //\n // cBoxType\n //\n this.cBoxType.FormattingEnabled = true;\n this.cBoxType.Location = new System.Drawing.Point(117, 3);\n this.cBoxType.Name = \"cBoxType\";\n this.cBoxType.Size = new System.Drawing.Size(165, 24);\n this.cBoxType.TabIndex = 1;\n //\n // dtStart\n //\n this.dtStart.Location = new System.Drawing.Point(117, 40);\n this.dtStart.Name = \"dtStart\";\n this.dtStart.Size = new System.Drawing.Size(165, 23);\n this.dtStart.TabIndex = 2;\n this.dtStart.Visible = false;\n //\n // TestBugControl\n //\n this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);\n this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;\n this.Controls.Add(this.dtStart);\n this.Controls.Add(this.cBoxType);\n this.Controls.Add(this.checkBox1);\n this.Font = new System.Drawing.Font(\"Verdana\", 9.75F,\n System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point,\n ((byte)(0)));\n this.Margin = new System.Windows.Forms.Padding(4);\n this.Name = \"TestBugControl\";\n this.Size = new System.Drawing.Size(285, 66);\n this.ResumeLayout(false);\n this.PerformLayout();\n\n }\n\n #endregion\n\n private System.Windows.Forms.CheckBox checkBox1;\n private System.Windows.Forms.ComboBox cBoxType;\n private System.Windows.Forms.DateTimePicker dtStart;\n }\n\n public class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n this.Load += new EventHandler(Form1_Load);\n }\n\n void Form1_Load(object sender, EventArgs e)\n {\n InitializeControl();\n }\n\n public void InitializeControl()\n {\n TestBugControl control = new TestBugControl();\n IList list = new ArrayList();\n for (int i = 0; i < 10; i++)\n {\n list.Add(new Bar());\n }\n control.InitializeData(list);\n control.BindFoo(new Foo());\n this.Controls.Add(control);\n }\n\n /// <summary>\n /// Required designer variable.\n /// </summary>\n private System.ComponentModel.IContainer components = null;\n\n /// <summary>\n /// Clean up any resources being used.\n /// </summary>\n /// <param name=\"disposing\">true if managed resources should be disposed; otherwise, false.</param>\n protected override void Dispose(bool disposing)\n {\n if (disposing && (components != null))\n {\n components.Dispose();\n }\n base.Dispose(disposing);\n }\n\n #region Windows Form Designer generated code\n\n /// <summary>\n /// Required method for Designer support - do not modify\n /// the contents of this method with the code editor.\n /// </summary>\n private void InitializeComponent()\n {\n this.components = new System.ComponentModel.Container();\n this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;\n this.Text = \"Form1\";\n }\n\n #endregion\n }\n\n static class Program\n {\n /// <summary>\n /// The main entry point for the application.\n /// </summary>\n [STAThread]\n static void Main()\n {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Application.Run(new Form1());\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 242503,
"author": "heijp06",
"author_id": 1793417,
"author_profile": "https://Stackoverflow.com/users/1793417",
"pm_score": 4,
"selected": false,
"text": "<p>C# supports conversions between arrays and lists as long as the arrays are not multidimensional and there is an inheritance relation between the types and the types are reference types</p>\n\n<pre><code>object[] oArray = new string[] { \"one\", \"two\", \"three\" };\nstring[] sArray = (string[])oArray;\n\n// Also works for IList (and IEnumerable, ICollection)\nIList<string> sList = (IList<string>)oArray;\nIList<object> oList = new string[] { \"one\", \"two\", \"three\" };\n</code></pre>\n\n<p>Note that this does not work:</p>\n\n<pre><code>object[] oArray2 = new int[] { 1, 2, 3 }; // Error: Cannot implicitly convert type 'int[]' to 'object[]'\nint[] iArray = (int[])oArray2; // Error: Cannot convert type 'object[]' to 'int[]'\n</code></pre>\n"
},
{
"answer_id": 311831,
"author": "Benjol",
"author_id": 11410,
"author_profile": "https://Stackoverflow.com/users/11410",
"pm_score": 6,
"selected": false,
"text": "<p>I'm arriving a bit late to the party, but I've got <strike>three</strike> <strike>four</strike> five:</p>\n\n<ol>\n<li><p>If you poll InvokeRequired on a control that hasn't been loaded/shown, it will say false - and blow up in your face if you try to change it from another thread (<a href=\"https://stackoverflow.com/questions/246058/system-invalidoperationexception-the-object-is-currently-in-use-elsewhere-ho\">the solution</a> is to reference this.Handle in the creator of the control).</p></li>\n<li><p>Another one which tripped me up is that given an assembly with:</p>\n\n<pre><code>enum MyEnum\n{\n Red,\n Blue,\n}\n</code></pre>\n\n<p>if you calculate MyEnum.Red.ToString() in another assembly, and in between times someone has recompiled your enum to:</p>\n\n<pre><code>enum MyEnum\n{\n Black,\n Red,\n Blue,\n}\n</code></pre>\n\n<p>at runtime, you will get \"Black\".</p></li>\n<li><p>I had a shared assembly with some handy constants in. My predecessor had left a load of ugly-looking get-only properties, I thought I'd get rid of the clutter and just use public const. I was more than a little surprised when VS compiled them to their values, and not references.</p></li>\n<li><p>If you implement a new method of an interface from another assembly, but you rebuild referencing the old version of that assembly, you get a TypeLoadException (no implementation of 'NewMethod'), even though you <em>have</em> implemented it (see <a href=\"https://stackoverflow.com/questions/948785/typeloadexception-says-no-implementation-but-it-is-implemented\">here</a>).</p></li>\n<li><p>Dictionary<,>: \"The order in which the items are returned is undefined\". This is <em>horrible</em>, because it can bite you sometimes, but work others, and if you've just blindly assumed that Dictionary is going to play nice (\"why shouldn't it? I thought, List does\"), you really have to have your nose in it before you finally start to question your assumption.</p></li>\n</ol>\n"
},
{
"answer_id": 530988,
"author": "cbp",
"author_id": 21966,
"author_profile": "https://Stackoverflow.com/users/21966",
"pm_score": 4,
"selected": false,
"text": "<p>Here is an example of how you can create a struct that causes the error message \"Attempted to read or write protected memory. This is often an indication that other memory is corrupt\".\nThe difference between success and failure is very subtle.</p>\n\n<p>The following unit test demonstrates the problem.</p>\n\n<p>See if you can work out what went wrong.</p>\n\n<pre><code> [Test]\n public void Test()\n {\n var bar = new MyClass\n {\n Foo = 500\n };\n bar.Foo += 500;\n\n Assert.That(bar.Foo.Value.Amount, Is.EqualTo(1000));\n }\n\n private class MyClass\n {\n public MyStruct? Foo { get; set; }\n }\n\n private struct MyStruct\n {\n public decimal Amount { get; private set; }\n\n public MyStruct(decimal amount) : this()\n {\n Amount = amount;\n }\n\n public static MyStruct operator +(MyStruct x, MyStruct y)\n {\n return new MyStruct(x.Amount + y.Amount);\n }\n\n public static MyStruct operator +(MyStruct x, decimal y)\n {\n return new MyStruct(x.Amount + y);\n }\n\n public static implicit operator MyStruct(int value)\n {\n return new MyStruct(value);\n }\n\n public static implicit operator MyStruct(decimal value)\n {\n return new MyStruct(value);\n }\n }\n</code></pre>\n"
},
{
"answer_id": 840352,
"author": "Jarek Kardas",
"author_id": 1515181,
"author_profile": "https://Stackoverflow.com/users/1515181",
"pm_score": 7,
"selected": false,
"text": "<p>Few years ago, when working on loyality program, we had an issue with the amount of points given to customers. The issue was related to casting/converting double to int.</p>\n\n<p>In code below:</p>\n\n<pre><code>double d = 13.6;\n\nint i1 = Convert.ToInt32(d);\nint i2 = (int)d;\n</code></pre>\n\n<p><strong>does i1 == i2</strong> ?</p>\n\n<p>It turns out that i1 != i2.\nBecause of different rounding policies in Convert and cast operator the actual values are:</p>\n\n<pre><code>i1 == 14\ni2 == 13\n</code></pre>\n\n<p>It's always better to call Math.Ceiling() or Math.Floor() (or Math.Round with MidpointRounding that meets our requirements)</p>\n\n<pre><code>int i1 = Convert.ToInt32( Math.Ceiling(d) );\nint i2 = (int) Math.Ceiling(d);\n</code></pre>\n"
},
{
"answer_id": 847353,
"author": "Michael Buen",
"author_id": 11432,
"author_profile": "https://Stackoverflow.com/users/11432",
"pm_score": 6,
"selected": false,
"text": "<p>They should have made 0 an integer even when there's an enum function overload.</p>\n\n<p>I knew C# core team rationale for mapping 0 to enum, but still, it is not as orthogonal as it should be. Example from <a href=\"http://plus.kaist.ac.kr/~shoh/postgresql/Npgsql/apidocs/Npgsql.NpgsqlParameterCollection.Add_overload_3.html\" rel=\"nofollow noreferrer\">Npgsql</a>.</p>\n\n<p>Test example:</p>\n\n<pre><code>namespace Craft\n{\n enum Symbol { Alpha = 1, Beta = 2, Gamma = 3, Delta = 4 };\n\n\n class Mate\n {\n static void Main(string[] args)\n {\n\n JustTest(Symbol.Alpha); // enum\n JustTest(0); // why enum\n JustTest((int)0); // why still enum\n\n int i = 0;\n\n JustTest(Convert.ToInt32(0)); // have to use Convert.ToInt32 to convince the compiler to make the call site use the object version\n\n JustTest(i); // it's ok from down here and below\n JustTest(1);\n JustTest(\"string\");\n JustTest(Guid.NewGuid());\n JustTest(new DataTable());\n\n Console.ReadLine();\n }\n\n static void JustTest(Symbol a)\n {\n Console.WriteLine(\"Enum\");\n }\n\n static void JustTest(object o)\n {\n Console.WriteLine(\"Object\");\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1047948,
"author": "Anders Rune Jensen",
"author_id": 13995,
"author_profile": "https://Stackoverflow.com/users/13995",
"pm_score": 2,
"selected": false,
"text": "<p>The scoping in c# is truly bizarre at times. Lets me give you one example:</p>\n\n<pre><code>if (true)\n{\n OleDbCommand command = SQLServer.CreateCommand();\n}\n\nOleDbCommand command = SQLServer.CreateCommand();\n</code></pre>\n\n<p>This fails to compile, because command is redeclared? There are some interested guesswork as to why it works that way in this <a href=\"https://stackoverflow.com/questions/404899/scope-of-variables-in-a-delegate\">thread on stackoverflow</a> and in <a href=\"http://people.iola.dk/arj/2009/01/02/scoping-rules-in-c/\" rel=\"nofollow noreferrer\">my blog</a>.</p>\n"
},
{
"answer_id": 1281522,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 6,
"selected": false,
"text": "<p>Here's one I only found out about recently...</p>\n\n<pre><code>interface IFoo\n{\n string Message {get;}\n}\n...\nIFoo obj = new IFoo(\"abc\");\nConsole.WriteLine(obj.Message);\n</code></pre>\n\n<p>The above looks crazy at first glance, but is <strong>actually legal</strong>.No, really (although I've missed out a key part, but it <strong>isn't</strong> anything hacky like \"add a class called <code>IFoo</code>\" or \"add a <code>using</code> alias to point <code>IFoo</code> at a class\"). </p>\n\n<p>See if you can figure out why, then: <a href=\"http://marcgravell.blogspot.com/2009/08/who-says-you-cant-instantiate-interface.html\" rel=\"nofollow noreferrer\">Who says you can’t instantiate an interface?</a></p>\n"
},
{
"answer_id": 1332344,
"author": "RCIX",
"author_id": 117069,
"author_profile": "https://Stackoverflow.com/users/117069",
"pm_score": 6,
"selected": false,
"text": "<p>This is one of the most unusual i've seen so far (aside from the ones here of course!):</p>\n\n<pre><code>public class Turtle<T> where T : Turtle<T>\n{\n}\n</code></pre>\n\n<p>It lets you declare it but has no real use, since it will always ask you to wrap whatever class you stuff in the center with another Turtle.</p>\n\n<p>[joke] I guess it's turtles all the way down... [/joke]</p>\n"
},
{
"answer_id": 1481604,
"author": "Joshua",
"author_id": 14768,
"author_profile": "https://Stackoverflow.com/users/14768",
"pm_score": 5,
"selected": false,
"text": "<p>I found a second really strange corner case that beats my first one by a long shot.</p>\n\n<p>String.Equals Method (String, String, StringComparison) is not actually side effect free.</p>\n\n<p>I was working on a block of code that had this on a line by itself at the top of some function:</p>\n\n<pre><code>stringvariable1.Equals(stringvariable2, StringComparison.InvariantCultureIgnoreCase);\n</code></pre>\n\n<p>Removing that line lead to a stack overflow somewhere else in the program.</p>\n\n<p>The code turned out to be installing a handler for what was in essence a BeforeAssemblyLoad event and trying to do</p>\n\n<pre><code>if (assemblyfilename.EndsWith(\"someparticular.dll\", StringComparison.InvariantCultureIgnoreCase))\n{\n assemblyfilename = \"someparticular_modified.dll\";\n}\n</code></pre>\n\n<p>By now I shouldn't have to tell you. Using a culture that hasn't been used before in a string comparison causes an assembly load. InvariantCulture is not an exception to this.</p>\n"
},
{
"answer_id": 1672628,
"author": "Heinzi",
"author_id": 87698,
"author_profile": "https://Stackoverflow.com/users/87698",
"pm_score": 5,
"selected": false,
"text": "<p>VB.NET, nullables and the ternary operator:</p>\n\n<pre><code>Dim i As Integer? = If(True, Nothing, 5)\n</code></pre>\n\n<p>This took me some time to debug, since I expected <code>i</code> to contain <code>Nothing</code>.</p>\n\n<p>What does i really contain? <code>0</code>.</p>\n\n<p>This is surprising but actually \"correct\" behavior: <code>Nothing</code> in VB.NET is not exactly the same as <code>null</code> in CLR: <code>Nothing</code> can either mean <code>null</code> or <code>default(T)</code> for a value type <code>T</code>, depending on the context. In the above case, <code>If</code> infers <code>Integer</code> as the common type of <code>Nothing</code> and <code>5</code>, so, in this case, <code>Nothing</code> means <code>0</code>.</p>\n"
},
{
"answer_id": 1799153,
"author": "Anders Ivner",
"author_id": 218858,
"author_profile": "https://Stackoverflow.com/users/218858",
"pm_score": 3,
"selected": false,
"text": "<p>PropertyInfo.SetValue() can assign ints to enums, ints to nullable ints, enums to nullable enums, but not ints to nullable enums.</p>\n\n<pre><code>enumProperty.SetValue(obj, 1, null); //works\nnullableIntProperty.SetValue(obj, 1, null); //works\nnullableEnumProperty.SetValue(obj, MyEnum.Foo, null); //works\nnullableEnumProperty.SetValue(obj, 1, null); // throws an exception !!!\n</code></pre>\n\n<p>Full description <a href=\"http://andersivner.blogspot.com/2008/05/nullable-enums.html\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 1800162,
"author": "Omer Mor",
"author_id": 61061,
"author_profile": "https://Stackoverflow.com/users/61061",
"pm_score": 7,
"selected": false,
"text": "<h2>Assign This!</h2>\n\n<hr>\n\n<p>This is one that I like to ask at parties (which is probably why I don't get invited anymore):</p>\n\n<p>Can you make the following piece of code compile?</p>\n\n<pre><code> public void Foo()\n {\n this = new Teaser();\n }\n</code></pre>\n\n<p>An easy cheat could be:</p>\n\n<pre><code>string cheat = @\"\n public void Foo()\n {\n this = new Teaser();\n }\n\";\n</code></pre>\n\n<p>But the real solution is this:</p>\n\n<pre><code>public struct Teaser\n{\n public void Foo()\n {\n this = new Teaser();\n }\n}\n</code></pre>\n\n<p>So it's a little know fact that value types (structs) can reassign their <code>this</code> variable.</p>\n"
},
{
"answer_id": 2203280,
"author": "Dynami Le Savard",
"author_id": 208917,
"author_profile": "https://Stackoverflow.com/users/208917",
"pm_score": 3,
"selected": false,
"text": "<p>The following might be general knowledge I was just simply lacking, but eh. Some time ago, we had a bug case which included virtual properties. Abstracting the context a bit, consider the following code, and apply breakpoint to specified area :</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n Derived d = new Derived();\n d.Property = \"AWESOME\";\n }\n}\n\nclass Base\n{\n string _baseProp;\n public virtual string Property \n { \n get \n {\n return \"BASE_\" + _baseProp;\n }\n set\n {\n _baseProp = value;\n //do work with the base property which might \n //not be exposed to derived types\n //here\n Console.Out.WriteLine(\"_baseProp is BASE_\" + value.ToString());\n }\n }\n}\n\nclass Derived : Base\n{\n string _prop;\n public override string Property \n {\n get { return _prop; }\n set \n { \n _prop = value; \n base.Property = value;\n } //<- put a breakpoint here then mouse over BaseProperty, \n // and then mouse over the base.Property call inside it.\n }\n\n public string BaseProperty { get { return base.Property; } private set { } }\n}\n</code></pre>\n\n<p>While in the <code>Derived</code> object context, you can get the same behavior when adding <code>base.Property</code> as a watch, or typing <code>base.Property</code> into the quickwatch. </p>\n\n<p>Took me some time to realize what was going on. In the end I was enlightened by the Quickwatch. When going into the Quickwatch and exploring the <code>Derived</code> object d (or from the object's context, <code>this</code>) and selecting the field <code>base</code>, the edit field on top of the Quickwatch displays the following cast:</p>\n\n<pre><code>((TestProject1.Base)(d))\n</code></pre>\n\n<p>Which means that if base is replaced as such, the call would be</p>\n\n<pre><code>public string BaseProperty { get { return ((TestProject1.Base)(d)).Property; } private set { } }\n</code></pre>\n\n<p>for the Watches, Quickwatch and the debugging mouse-over tooltips, and it would then make sense for it to display <code>\"AWESOME\"</code> instead of <code>\"BASE_AWESOME\"</code> when considering polymorphism. I'm still unsure why it would transform it into a cast, one hypothesis is that <code>call</code> might not be available from those modules' context, and only <code>callvirt</code>.</p>\n\n<p>Anyhow, that obviously doesn't alter anything in terms of functionality, <code>Derived.BaseProperty</code> will still really return <code>\"BASE_AWESOME\"</code>, and thus this was not the root of our bug at work, simply a confusing component. I did however find it interesting how it could mislead developpers which would be unaware of that fact during their debug sessions, specially if <code>Base</code> is not exposed in your project but rather referenced as a 3rd party DLL, resulting in Devs just saying :</p>\n\n<blockquote>\n <p>\"Oi, wait..what ? omg that DLL is\n like, ..doing something funny\"</p>\n</blockquote>\n"
},
{
"answer_id": 2309473,
"author": "Spencer Ruport",
"author_id": 52551,
"author_profile": "https://Stackoverflow.com/users/52551",
"pm_score": 3,
"selected": false,
"text": "<p>I'm not sure if you'd say this is a Windows Vista/7 oddity or a .Net oddity but it had me scratching my head for a while.</p>\n\n<pre><code>string filename = @\"c:\\program files\\my folder\\test.txt\";\nSystem.IO.File.WriteAllText(filename, \"Hello world.\");\nbool exists = System.IO.File.Exists(filename); // returns true;\nstring text = System.IO.File.ReadAllText(filename); // Returns \"Hello world.\"\n</code></pre>\n\n<p>In Windows Vista/7 the file will actually be written to <code>C:\\Users\\<username>\\Virtual Store\\Program Files\\my folder\\test.txt</code></p>\n"
},
{
"answer_id": 2354325,
"author": "Sam Harwell",
"author_id": 138304,
"author_profile": "https://Stackoverflow.com/users/138304",
"pm_score": 4,
"selected": false,
"text": "<p>This is the strangest I've encountered by accident:</p>\n\n<pre><code>public class DummyObject\n{\n public override string ToString()\n {\n return null;\n }\n}\n</code></pre>\n\n<p>Used as follows:</p>\n\n<pre><code>DummyObject obj = new DummyObject();\nConsole.WriteLine(\"The text: \" + obj.GetType() + \" is \" + obj);\n</code></pre>\n\n<p>Will throw a <code>NullReferenceException</code>. Turns out the multiple additions are compiled by the C# compiler to a call to <code>String.Concat(object[])</code>. Prior to .NET 4, there is a bug in just that overload of Concat where the object is checked for null, but not the result of ToString():</p>\n\n<pre><code>object obj2 = args[i];\nstring text = (obj2 != null) ? obj2.ToString() : string.Empty;\n// if obj2 is non-null, but obj2.ToString() returns null, then text==null\nint length = text.Length;\n</code></pre>\n\n<p>This is a bug by ECMA-334 §14.7.4:</p>\n\n<blockquote>\n <p>The binary + operator performs string concatenation when one or both operands are of type <code>string</code>. If an operand of string concatenation is <code>null</code>, an empty string is substituted. Otherwise, any non-string operand is converted to its string representation by invoking the virtual <code>ToString</code> method inherited from type <code>object</code>. <strong>If <code>ToString</code> returns <code>null</code>, an empty string is substituted.</strong></p>\n</blockquote>\n"
},
{
"answer_id": 2374000,
"author": "Bubba88",
"author_id": 185430,
"author_profile": "https://Stackoverflow.com/users/185430",
"pm_score": 2,
"selected": false,
"text": "<p>There is something really exciting about C#, the way it handles closures.</p>\n\n<p>Instead of copying the stack variable values to the closure free variable, it does that preprocessor magic wrapping all occurences of the variable into an object and thus moves it out of stack - straight to the heap! :)</p>\n\n<p>I guess, that makes C# even more functionally-complete (or lambda-complete huh)) language than ML itself (which uses stack value copying AFAIK). F# has that feature too, as C# does. </p>\n\n<p>That does bring much delight to me, thank you MS guys!</p>\n\n<p>It's not an oddity or corner case though... but something really unexpected from a stack-based VM language :)</p>\n"
},
{
"answer_id": 2485589,
"author": "MPelletier",
"author_id": 210916,
"author_profile": "https://Stackoverflow.com/users/210916",
"pm_score": 2,
"selected": false,
"text": "<p>From a question I asked not long ago:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/2215745/conditional-operator-cannot-cast-implicitly\">Conditional operator cannot cast implicitly?</a></p>\n\n<p>Given:</p>\n\n<pre><code>Bool aBoolValue;\n</code></pre>\n\n<p>Where <code>aBoolValue</code> is assigned either True or False;</p>\n\n<p>The following will not compile:</p>\n\n<pre><code>Byte aByteValue = aBoolValue ? 1 : 0;\n</code></pre>\n\n<p>But this would:</p>\n\n<pre><code>Int anIntValue = aBoolValue ? 1 : 0;\n</code></pre>\n\n<p>The answer provided is pretty good too.</p>\n"
},
{
"answer_id": 2602423,
"author": "Jordão",
"author_id": 31158,
"author_profile": "https://Stackoverflow.com/users/31158",
"pm_score": 3,
"selected": false,
"text": "<p>Have you ever thought the C# compiler could generate invalid CIL? Run this and you'll get a <code>TypeLoadException</code>:</p>\n\n<pre><code>interface I<T> {\n T M(T p);\n}\nabstract class A<T> : I<T> {\n public abstract T M(T p);\n}\nabstract class B<T> : A<T>, I<int> {\n public override T M(T p) { return p; }\n public int M(int p) { return p * 2; }\n}\nclass C : B<int> { }\n\nclass Program {\n static void Main(string[] args) {\n Console.WriteLine(new C().M(42));\n }\n}\n</code></pre>\n\n<p>I don't know how it fares in the C# 4.0 compiler though.</p>\n\n<p><b>EDIT</b>: this is the output from my system:</p>\n\n<pre><code>C:\\Temp>type Program.cs\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ConsoleApplication1 {\n\n interface I<T> {\n T M(T p);\n }\n abstract class A<T> : I<T> {\n public abstract T M(T p);\n }\n abstract class B<T> : A<T>, I<int> {\n public override T M(T p) { return p; }\n public int M(int p) { return p * 2; }\n }\n class C : B<int> { }\n\n class Program {\n static void Main(string[] args) {\n Console.WriteLine(new C().M(11));\n }\n }\n\n}\nC:\\Temp>csc Program.cs\nMicrosoft (R) Visual C# 2008 Compiler version 3.5.30729.1\nfor Microsoft (R) .NET Framework version 3.5\nCopyright (C) Microsoft Corporation. All rights reserved.\n\n\nC:\\Temp>Program\n\nUnhandled Exception: System.TypeLoadException: Could not load type 'ConsoleAppli\ncation1.C' from assembly 'Program, Version=0.0.0.0, Culture=neutral, PublicKeyTo\nken=null'.\n at ConsoleApplication1.Program.Main(String[] args)\n\nC:\\Temp>peverify Program.exe\n\nMicrosoft (R) .NET Framework PE Verifier. Version 3.5.30729.1\nCopyright (c) Microsoft Corporation. All rights reserved.\n\n[token 0x02000005] Type load failed.\n[IL]: Error: [C:\\Temp\\Program.exe : ConsoleApplication1.Program::Main][offset 0x\n00000001] Unable to resolve token.\n2 Error(s) Verifying Program.exe\n\nC:\\Temp>ver\n\nMicrosoft Windows XP [Version 5.1.2600]\n</code></pre>\n"
},
{
"answer_id": 2915346,
"author": "tclem",
"author_id": 19688,
"author_profile": "https://Stackoverflow.com/users/19688",
"pm_score": 3,
"selected": false,
"text": "<p>What if you have a generic class that has methods that could be made ambiguous depending on the type arguments? I ran into this situation recently writing a two-way dictionary. I wanted to write symmetric <code>Get()</code> methods that would return the opposite of whatever argument was passed. Something like this:</p>\n\n<pre><code>class TwoWayRelationship<T1, T2>\n{\n public T2 Get(T1 key) { /* ... */ }\n public T1 Get(T2 key) { /* ... */ }\n}\n</code></pre>\n\n<p>All is well good if you make an instance where <code>T1</code> and <code>T2</code> are different types:</p>\n\n<pre><code>var r1 = new TwoWayRelationship<int, string>();\nr1.Get(1);\nr1.Get(\"a\");\n</code></pre>\n\n<p>But if <code>T1</code> and <code>T2</code> are the same (and probably if one was a subclass of another), it's a compiler error:</p>\n\n<pre><code>var r2 = new TwoWayRelationship<int, int>();\nr2.Get(1); // \"The call is ambiguous...\"\n</code></pre>\n\n<p>Interestingly, all other methods in the second case are still usable; it's only calls to the now-ambiguous method that causes a compiler error. Interesting case, if a little unlikely and obscure.</p>\n"
},
{
"answer_id": 3077238,
"author": "Tor Livar",
"author_id": 367665,
"author_profile": "https://Stackoverflow.com/users/367665",
"pm_score": 3,
"selected": false,
"text": "<p>In an API we're using, methods that return a domain object might return a special \"null object\". In the implementation of this, the comparison operator and the <code>Equals()</code> method are overridden to return <code>true</code> if it is compared with <code>null</code>.</p>\n\n<p>So a user of this API might have some code like this:</p>\n\n<pre><code>return test != null ? test : GetDefault();\n</code></pre>\n\n<p>or perhaps a bit more verbose, like this:</p>\n\n<pre><code>if (test == null)\n return GetDefault();\nreturn test;\n</code></pre>\n\n<p>where <code>GetDefault()</code> is a method returning some default value that we want to use instead of <code>null</code>. The surprise hit me when I was using ReSharper and following it's recommendation to rewrite either of this to the following:</p>\n\n<pre><code>return test ?? GetDefault();\n</code></pre>\n\n<p>If the test object is a null object returned from the API instead of a proper <code>null</code>, the behavior of the code has now changed, as the null coalescing operator actually checks for <code>null</code>, not running <code>operator=</code> or <code>Equals()</code>.</p>\n"
},
{
"answer_id": 3450711,
"author": "Anders Rune Jensen",
"author_id": 13995,
"author_profile": "https://Stackoverflow.com/users/13995",
"pm_score": 2,
"selected": false,
"text": "<p>The following doesn't work:</p>\n\n<pre><code>if (something)\n doit();\nelse\n var v = 1 + 2;\n</code></pre>\n\n<p>But this works:</p>\n\n<pre><code>if (something)\n doit();\nelse {\n var v = 1 + 2;\n}\n</code></pre>\n"
},
{
"answer_id": 3451958,
"author": "Omer Mor",
"author_id": 61061,
"author_profile": "https://Stackoverflow.com/users/61061",
"pm_score": 3,
"selected": false,
"text": "<h2>C# Accessibility Puzzler</h2>\n<hr />\n<p>The following derived class is accessing a <strong>private field</strong> from its base class, and the compiler silently looks to the other side:</p>\n<pre><code>public class Derived : Base\n{\n public int BrokenAccess()\n {\n return base.m_basePrivateField;\n }\n}\n</code></pre>\n<p>The field is indeed private:</p>\n<pre><code>private int m_basePrivateField = 0;\n</code></pre>\n<p>Care to guess how we can make such code compile?</p>\n<p>.</p>\n<p>.</p>\n<p>.</p>\n<p>.</p>\n<p>.</p>\n<p>.</p>\n<p>.</p>\n<h2>Answer</h2>\n<hr />\n<p>The trick is to declare <code>Derived</code> as an inner class of <code>Base</code>:</p>\n<pre><code>public class Base\n{\n private int m_basePrivateField = 0;\n\n public class Derived : Base\n {\n public int BrokenAccess()\n {\n return base.m_basePrivateField;\n }\n }\n}\n</code></pre>\n<p>Inner classes are given full access to the outer class members. In this case the inner class also happens to derive from the outer class. This allows us to "break" the encapsulation of private members.</p>\n"
},
{
"answer_id": 3535490,
"author": "Lasse Espeholt",
"author_id": 174574,
"author_profile": "https://Stackoverflow.com/users/174574",
"pm_score": 1,
"selected": false,
"text": "<p>If you have the extension method:</p>\n\n<pre><code>public static bool? ToBoolean(this string s)\n{\n bool result;\n\n if (bool.TryParse(s, out result))\n return result;\n else\n return null;\n}\n</code></pre>\n\n<p>and this code:</p>\n\n<pre><code>string nullStr = null;\nvar res = nullStr.ToBoolean();\n</code></pre>\n\n<p>This will not throw an exception because it is an extension method (and really <code>HelperClass.ToBoolean(null)</code>) and not an instance method. This can be confusing.</p>\n"
},
{
"answer_id": 3934725,
"author": "Rune FS",
"author_id": 112407,
"author_profile": "https://Stackoverflow.com/users/112407",
"pm_score": 2,
"selected": false,
"text": "<p>here are a few of mine:</p>\n\n<ol>\n<li>this can be null when calling an instance method with out a NullReferenceException being thrown</li>\n<li>a default enumeration value doesn't have to be defined for the enumeration</li>\n</ol>\n\n<p>Simple one first:\n enum NoZero\n {\n Number = 1\n }</p>\n\n<pre><code> public bool ReturnsFalse()\n {\n //The default value is not defined!\n return Enum.IsDefined(typeof (NoZero), default(NoZero));\n }\n</code></pre>\n\n<p>The below code can actually print true!</p>\n\n<pre><code> internal sealed class Strange\n{\n public void Foo()\n {\n Console.WriteLine(this == null);\n }\n}\n</code></pre>\n\n<p>A simple piece of client code that will result in that is\n delegate void HelloDelegate(Strange bar);</p>\n\n<pre><code>public class Program\n{\n [STAThread()]\n public static void Main(string[] args)\n {\n Strange bar = null;\n var hello = new DynamicMethod(\"ThisIsNull\",\n typeof(void), new[] { typeof(Strange) },\n typeof(Strange).Module);\n ILGenerator il = hello.GetILGenerator(256);\n il.Emit(OpCodes.Ldarg_0);\n var foo = typeof(Strange).GetMethod(\"Foo\");\n il.Emit(OpCodes.Call, foo);\n il.Emit(OpCodes.Ret);\n var print = (HelloDelegate)hello.CreateDelegate(typeof(HelloDelegate));\n print(bar);\n Console.ReadLine();\n }\n}\n</code></pre>\n\n<p>this is actually true in most languages as long as the instance method when called doesn't use the state of the object. this is only dereferenced when the state of the object is accessed</p>\n"
},
{
"answer_id": 4604818,
"author": "Jordão",
"author_id": 31158,
"author_profile": "https://Stackoverflow.com/users/31158",
"pm_score": 3,
"selected": false,
"text": "<p>Consider this weird case:</p>\n\n<pre><code>public interface MyInterface {\n void Method();\n}\npublic class Base {\n public void Method() { }\n}\npublic class Derived : Base, MyInterface { }\n</code></pre>\n\n<p>If <code>Base</code> and <code>Derived</code> are declared in the same assembly, the compiler will make <code>Base::Method</code> virtual and sealed (in the CIL), even though <code>Base</code> doesn't implement the interface. </p>\n\n<p>If <code>Base</code> and <code>Derived</code> are in different assemblies, when compiling the <code>Derived</code> assembly, the compiler won't change the other assembly, so it will introduce a member in <code>Derived</code> that will be an explicit implementation for <code>MyInterface::Method</code> that will just delegate the call to <code>Base::Method</code>.</p>\n\n<p>The compiler has to do this in order to support polymorphic dispatch with regards to the interface, i.e. it has to make that method virtual.</p>\n"
},
{
"answer_id": 4723038,
"author": "TDaver",
"author_id": 571536,
"author_profile": "https://Stackoverflow.com/users/571536",
"pm_score": 3,
"selected": false,
"text": "<p>Just found a nice little thing today:</p>\n\n<pre><code>public class Base\n{\n public virtual void Initialize(dynamic stuff) { \n //...\n }\n}\npublic class Derived:Base\n{\n public override void Initialize(dynamic stuff) {\n base.Initialize(stuff);\n //...\n }\n}\n</code></pre>\n\n<p>This throws compile error. </p>\n\n<p>The call to method 'Initialize' needs to be dynamically dispatched, but cannot be because it is part of a base access expression. Consider casting the dynamic arguments or eliminating the base access.</p>\n\n<p>If I write base.Initialize(stuff as object); it works perfectly, however this seems to be a \"magic word\" here, since it does exactly the same, everything is still recieved as dynamic...</p>\n"
},
{
"answer_id": 4941012,
"author": "Andrew Sevastian",
"author_id": 589340,
"author_profile": "https://Stackoverflow.com/users/589340",
"pm_score": 2,
"selected": false,
"text": "<p>This one is pretty straightforward but I still find it somewhat interesting. What would be the value of x after the call to Foo?</p>\n\n<pre><code>static int x = 0;\n\npublic static void Foo()\n{\n try { return; }\n finally { x = 1; }\n}\n\nstatic void Main() { Foo(); }\n</code></pre>\n"
},
{
"answer_id": 5113304,
"author": "Steve",
"author_id": 468666,
"author_profile": "https://Stackoverflow.com/users/468666",
"pm_score": 3,
"selected": false,
"text": "<p>This one's pretty hard to top. I ran into it while I was trying to build a RealProxy implementation that truly supports Begin/EndInvoke (thanks MS for making this impossible to do without horrible hacks). This example is basically a bug in the CLR, the unmanaged code path for BeginInvoke doesn't validate that the return message from RealProxy.PrivateInvoke (and my Invoke override) is returning an instance of an IAsyncResult. Once it's returned, the CLR gets incredibly confused and loses any idea of whats going on, as demonstrated by the tests at the bottom.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Runtime.Remoting.Proxies;\nusing System.Reflection;\nusing System.Runtime.Remoting.Messaging;\n\nnamespace BrokenProxy\n{\n class NotAnIAsyncResult\n {\n public string SomeProperty { get; set; }\n }\n\n class BrokenProxy : RealProxy\n {\n private void HackFlags()\n {\n var flagsField = typeof(RealProxy).GetField(\"_flags\", BindingFlags.NonPublic | BindingFlags.Instance);\n int val = (int)flagsField.GetValue(this);\n val |= 1; // 1 = RemotingProxy, check out System.Runtime.Remoting.Proxies.RealProxyFlags\n flagsField.SetValue(this, val);\n }\n\n public BrokenProxy(Type t)\n : base(t)\n {\n HackFlags();\n }\n\n public override IMessage Invoke(IMessage msg)\n {\n var naiar = new NotAnIAsyncResult();\n naiar.SomeProperty = \"o noes\";\n return new ReturnMessage(naiar, null, 0, null, (IMethodCallMessage)msg);\n }\n }\n\n interface IRandomInterface\n {\n int DoSomething();\n }\n\n class Program\n {\n static void Main(string[] args)\n {\n BrokenProxy bp = new BrokenProxy(typeof(IRandomInterface));\n var instance = (IRandomInterface)bp.GetTransparentProxy();\n Func<int> doSomethingDelegate = instance.DoSomething;\n IAsyncResult notAnIAsyncResult = doSomethingDelegate.BeginInvoke(null, null);\n\n var interfaces = notAnIAsyncResult.GetType().GetInterfaces();\n Console.WriteLine(!interfaces.Any() ? \"No interfaces on notAnIAsyncResult\" : \"Interfaces\");\n Console.WriteLine(notAnIAsyncResult is IAsyncResult); // Should be false, is it?!\n Console.WriteLine(((NotAnIAsyncResult)notAnIAsyncResult).SomeProperty);\n Console.WriteLine(((IAsyncResult)notAnIAsyncResult).IsCompleted); // No way this works.\n }\n }\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>No interfaces on notAnIAsyncResult\nTrue\no noes\n\nUnhandled Exception: System.EntryPointNotFoundException: Entry point was not found.\n at System.IAsyncResult.get_IsCompleted()\n at BrokenProxy.Program.Main(String[] args) \n</code></pre>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22656/"
] |
I collect a few corner cases and [brain teasers](http://www.yoda.arachsys.com/csharp/teasers.html) and would always like to hear more. The page only really covers C# language bits and bobs, but I also find core .NET things interesting too. For example, here's one which isn't on the page, but which I find incredible:
```
string x = new string(new char[0]);
string y = new string(new char[0]);
Console.WriteLine(object.ReferenceEquals(x, y));
```
I'd expect that to print False - after all, "new" (with a reference type) *always* creates a new object, doesn't it? The specs for both C# and the CLI indicate that it should. Well, not in this particular case. It prints True, and has done on every version of the framework I've tested it with. (I haven't tried it on Mono, admittedly...)
Just to be clear, this is only an example of the kind of thing I'm looking for - I wasn't particularly looking for discussion/explanation of this oddity. (It's not the same as normal string interning; in particular, string interning doesn't normally happen when a constructor is called.) I was really asking for similar odd behaviour.
Any other gems lurking out there?
|
I think I showed you this one before, but I like the fun here - this took some debugging to track down! (the original code was obviously more complex and subtle...)
```
static void Foo<T>() where T : new()
{
T t = new T();
Console.WriteLine(t.ToString()); // works fine
Console.WriteLine(t.GetHashCode()); // works fine
Console.WriteLine(t.Equals(t)); // works fine
// so it looks like an object and smells like an object...
// but this throws a NullReferenceException...
Console.WriteLine(t.GetType());
}
```
So what was T...
Answer: any `Nullable<T>` - such as `int?`. All the methods are overridden, except GetType() which can't be; so it is cast (boxed) to object (and hence to null) to call object.GetType()... which calls on null ;-p
---
Update: the plot thickens... Ayende Rahien threw down a [similar challenge on his blog](http://ayende.com/Blog/archive/2009/11/25/can-you-hack-this-out-hint-1.aspx), but with a `where T : class, new()`:
```
private static void Main() {
CanThisHappen<MyFunnyType>();
}
public static void CanThisHappen<T>() where T : class, new() {
var instance = new T(); // new() on a ref-type; should be non-null, then
Debug.Assert(instance != null, "How did we break the CLR?");
}
```
But it can be defeated! Using the same indirection used by things like remoting; warning - the following is **pure evil**:
```
class MyFunnyProxyAttribute : ProxyAttribute {
public override MarshalByRefObject CreateInstance(Type serverType) {
return null;
}
}
[MyFunnyProxy]
class MyFunnyType : ContextBoundObject { }
```
With this in place, the `new()` call is redirected to the proxy (`MyFunnyProxyAttribute`), which returns `null`. Now go and wash your eyes!
|
194,492 |
<p>In visual C++, I can do things like this:</p>
<pre><code>template <class T>
class A{
protected:
T i;
};
template <class T>
class B : public A<T>{
T geti() {return i;}
};
</code></pre>
<p>If I try to compile this in g++, I get an error. I have to do this:</p>
<pre><code>template <class T>
class B : public A<T>{
T geti() {return A<T>::i;}
};
</code></pre>
<p>Am I not supposed to do the former in standard C++? Or is something misconfigured with gcc that's giving me errors?</p>
|
[
{
"answer_id": 194640,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 4,
"selected": true,
"text": "<p>This used to be allowed, but changed in <a href=\"http://gcc.gnu.org/gcc-3.4/changes.html#cplusplus\" rel=\"noreferrer\">gcc 3.4</a>.</p>\n\n<p>In a template definition, unqualified names will no longer find members of a dependent base (as specified by [temp.dep]/3 in the C++ standard). For example,</p>\n\n<pre><code> template <typename T> struct B {\n int m;\n int n;\n int f ();\n int g ();\n };\n int n;\n int g ();\n template <typename T> struct C : B<T> {\n void h ()\n {\n m = 0; // error\n f (); // error\n n = 0; // ::n is modified\n g (); // ::g is called\n }\n };\n</code></pre>\n\n<p>You must make the names dependent, e.g. by prefixing them with this->. Here is the corrected definition of C::h,</p>\n\n<pre><code> template <typename T> void C<T>::h ()\n {\n this->m = 0;\n this->f ();\n this->n = 0\n this->g ();\n }\n</code></pre>\n"
},
{
"answer_id": 194641,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 2,
"selected": false,
"text": "<p>I figured this one out:</p>\n\n<ul>\n<li><a href=\"https://isocpp.org/wiki/faq/templates#nondependent-name-lookup-types\" rel=\"nofollow noreferrer\">C++ Super FAQ: \"Why am I getting errors when my template-derived-class uses a nested type it inherits from its template-base-class?\"</a></li>\n<li><a href=\"https://isocpp.org/wiki/faq/templates#nondependent-name-lookup-members\" rel=\"nofollow noreferrer\">C++ Super FAQ: \"Why am I getting errors when my template-derived-class uses a member it inherits from its template-base-class?\"</a></li>\n</ul>\n\n<p>Apparently, the first example ISN'T valid C++ and it's bad that msvc takes this. There are solutions posted on the C++ faq lite.</p>\n"
},
{
"answer_id": 195589,
"author": "Nemanja Trifunovic",
"author_id": 8899,
"author_profile": "https://Stackoverflow.com/users/8899",
"pm_score": 0,
"selected": false,
"text": "<p>You may want to read about <a href=\"http://www.codeproject.com/KB/cpp/TwoPhaseLookup.aspx\" rel=\"nofollow noreferrer\">two-phase name lookup</a></p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] |
In visual C++, I can do things like this:
```
template <class T>
class A{
protected:
T i;
};
template <class T>
class B : public A<T>{
T geti() {return i;}
};
```
If I try to compile this in g++, I get an error. I have to do this:
```
template <class T>
class B : public A<T>{
T geti() {return A<T>::i;}
};
```
Am I not supposed to do the former in standard C++? Or is something misconfigured with gcc that's giving me errors?
|
This used to be allowed, but changed in [gcc 3.4](http://gcc.gnu.org/gcc-3.4/changes.html#cplusplus).
In a template definition, unqualified names will no longer find members of a dependent base (as specified by [temp.dep]/3 in the C++ standard). For example,
```
template <typename T> struct B {
int m;
int n;
int f ();
int g ();
};
int n;
int g ();
template <typename T> struct C : B<T> {
void h ()
{
m = 0; // error
f (); // error
n = 0; // ::n is modified
g (); // ::g is called
}
};
```
You must make the names dependent, e.g. by prefixing them with this->. Here is the corrected definition of C::h,
```
template <typename T> void C<T>::h ()
{
this->m = 0;
this->f ();
this->n = 0
this->g ();
}
```
|
194,526 |
<p>I recently turned on Windows Firewall logging on my computer and started tracking incoming and outgoing connections. Something curious about the logfiles is that I have noticed numerous UDP packets (in fact, it constitutes basically all of my incoming traffic) that don't have my host as destination or source showing up in the logs.</p>
<p>I thought this might be a implementation detail for UDP (the packets are hopping over my computer in the subnet) but Wikipedia'ing UDP didn't enlighten me any more, and I don't see why my computer should be forwarding these packets in the first place.</p>
<p>Any ideas?</p>
<p><strong>Edit 1:</strong> Here is what a log file line with the mysterious UDP packet looks like:</p>
<pre><code>2008-10-11 16:04:31 ALLOW UDP 18.243.7.218 239.255.255.250 49152 3702 0 - - - - - - - RECEIVE
</code></pre>
<p>Is 239.255.255.250 a broadcast address? Now that you mention it, the UDP packets I'm seeing have very specific destinations, basically 224.0.0.252, 239.255.255.250, 18.243.255.255. I also get phantom ICMP pings addressed to 224.0.0.1.</p>
|
[
{
"answer_id": 194535,
"author": "Nick",
"author_id": 26240,
"author_profile": "https://Stackoverflow.com/users/26240",
"pm_score": -1,
"selected": false,
"text": "<p>Hard to say without analyzing the log data, but they could be broadcast packets on the segment, in which case you're system would listen to them. This is possible in IPv4 and IPv6.</p>\n\n<p>Your system should not be forwarding them unless it's set up to route, but it can certainly be listening to packets all the time (various network protocols use UDP).</p>\n"
},
{
"answer_id": 194536,
"author": "Luka Marinko",
"author_id": 19814,
"author_profile": "https://Stackoverflow.com/users/19814",
"pm_score": 1,
"selected": false,
"text": "<p>It depends on the type of connection you are on. \nOn most cable modem ISP's you are basicly on the same LAN as your neigburs, and can usualy see some of their traffic (like brodcast). </p>\n\n<p>Id recomend you install packet sniffer and see what is realy going on.\nGood multiplatform packet sniffer is <a href=\"http://www.wireshark.org/\" rel=\"nofollow noreferrer\">Wireshark</a></p>\n"
},
{
"answer_id": 194575,
"author": "Tim Farley",
"author_id": 4425,
"author_profile": "https://Stackoverflow.com/users/4425",
"pm_score": 4,
"selected": true,
"text": "<p>The packets addressed to IPs starting with 239 and 224 are <a href=\"http://en.wikipedia.org/wiki/Multicast\" rel=\"noreferrer\">multicast packets</a>. This is a way to address traffic to a group of computers without broadcasting it to an entire network. It is used by various legitimate protocols.</p>\n\n<p>224.0.0.252 is the address used by the <a href=\"http://en.wikipedia.org/wiki/Link-local_Multicast_Name_Resolution\" rel=\"noreferrer\">Link Local Name Resolution protocol</a>.</p>\n\n<p>239.255.255.250 is the address used by the <a href=\"http://en.wikipedia.org/wiki/Simple_Service_Discovery_Protocol\" rel=\"noreferrer\">Simple Service Discovery Protocol</a>.</p>\n\n<p>224.0.0.1 is the <a href=\"http://tldp.org/HOWTO/Multicast-HOWTO-2.html\" rel=\"noreferrer\">all hosts address</a>, used by your router to see who on your network is willing to participate in multicast conversations.</p>\n\n<p>The ones addressed to 18.243.255.255 look like broadcasts, again this is used by many legitimate protocols such as Bonjour.</p>\n\n<p>As recommended by Luka, a good protocol analyzer like <a href=\"http://www.wireshark.org/\" rel=\"noreferrer\">Wireshark</a> will tell you precisely what each of these packets are and what they contain.</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23845/"
] |
I recently turned on Windows Firewall logging on my computer and started tracking incoming and outgoing connections. Something curious about the logfiles is that I have noticed numerous UDP packets (in fact, it constitutes basically all of my incoming traffic) that don't have my host as destination or source showing up in the logs.
I thought this might be a implementation detail for UDP (the packets are hopping over my computer in the subnet) but Wikipedia'ing UDP didn't enlighten me any more, and I don't see why my computer should be forwarding these packets in the first place.
Any ideas?
**Edit 1:** Here is what a log file line with the mysterious UDP packet looks like:
```
2008-10-11 16:04:31 ALLOW UDP 18.243.7.218 239.255.255.250 49152 3702 0 - - - - - - - RECEIVE
```
Is 239.255.255.250 a broadcast address? Now that you mention it, the UDP packets I'm seeing have very specific destinations, basically 224.0.0.252, 239.255.255.250, 18.243.255.255. I also get phantom ICMP pings addressed to 224.0.0.1.
|
The packets addressed to IPs starting with 239 and 224 are [multicast packets](http://en.wikipedia.org/wiki/Multicast). This is a way to address traffic to a group of computers without broadcasting it to an entire network. It is used by various legitimate protocols.
224.0.0.252 is the address used by the [Link Local Name Resolution protocol](http://en.wikipedia.org/wiki/Link-local_Multicast_Name_Resolution).
239.255.255.250 is the address used by the [Simple Service Discovery Protocol](http://en.wikipedia.org/wiki/Simple_Service_Discovery_Protocol).
224.0.0.1 is the [all hosts address](http://tldp.org/HOWTO/Multicast-HOWTO-2.html), used by your router to see who on your network is willing to participate in multicast conversations.
The ones addressed to 18.243.255.255 look like broadcasts, again this is used by many legitimate protocols such as Bonjour.
As recommended by Luka, a good protocol analyzer like [Wireshark](http://www.wireshark.org/) will tell you precisely what each of these packets are and what they contain.
|
194,528 |
<p>I have a ASP.Net page using ADO to query MS access database and as a learning exercise i would like to incorporate LINQ. I have one simple table called Quotes.</p>
<p>The fields are: QuoteID, QuoteDescription, QuoteAuthor, QuoteDate. I would like to run simple queries like, "Give me all quotes after 1995". </p>
<p>How would i incorporate LINQ into this ASP.Net site (C#)</p>
<p>Basically, my question is does LINQ work for MS Access ??</p>
|
[
{
"answer_id": 194533,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "<p>I don't <em>think</em> LINQ to SQL supports Access. However, if your table is sufficiently small to fit into memory, LINQ to DataSet will let you query datatables etc pretty easily - especially strongly typed datasets.</p>\n"
},
{
"answer_id": 194651,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 5,
"selected": true,
"text": "<p>LINQ to SQL doesn't support Access (that is, there's no Access/Jet provider for LINQ), but you can query a DataSet with LINQ. This means that you fill your DataSet with any possible data from your database that you might need in your results, and then you filter on the client side. After you have a typed DataSet, and you Fill() it with a TableAdapter, you do something like this:</p>\n\n<pre><code>var year = 1995; // you can pass the year into a method so you can filter on any year\nvar results = from row in dsQuotes\n where row.QuoteDate > year\n select row;\n</code></pre>\n\n<p>You'll have to decide whether this is worth it. You'd have to fill your DataSet with <em>all</em> the quotes, then use LINQ to filter on just those quotes that are after 1995. For a small amount of data, sure, why not? But for a very large amount of data, you'll need to make sure it won't be too slow.</p>\n\n<p>If you're using a DataSet, though, you can write custom queries that become new TableAdapter methods. So you can put the correct SQL for your query in a FillByYear() method in your TableAdapter and use that to fill your typed DataTable. That way you're only getting back the data you need.</p>\n\n<p>If you go this route, remember that Access/Jet uses positional parameters, not named parameters. So instead of</p>\n\n<pre><code>SELECT * FROM Quotes WHERE Year(QuoteDate) > @Year\n</code></pre>\n\n<p>you'd use something like this:</p>\n\n<pre><code>SELECT * FROM Quotes WHERE Year(QuoteDate) > ?\n</code></pre>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
I have a ASP.Net page using ADO to query MS access database and as a learning exercise i would like to incorporate LINQ. I have one simple table called Quotes.
The fields are: QuoteID, QuoteDescription, QuoteAuthor, QuoteDate. I would like to run simple queries like, "Give me all quotes after 1995".
How would i incorporate LINQ into this ASP.Net site (C#)
Basically, my question is does LINQ work for MS Access ??
|
LINQ to SQL doesn't support Access (that is, there's no Access/Jet provider for LINQ), but you can query a DataSet with LINQ. This means that you fill your DataSet with any possible data from your database that you might need in your results, and then you filter on the client side. After you have a typed DataSet, and you Fill() it with a TableAdapter, you do something like this:
```
var year = 1995; // you can pass the year into a method so you can filter on any year
var results = from row in dsQuotes
where row.QuoteDate > year
select row;
```
You'll have to decide whether this is worth it. You'd have to fill your DataSet with *all* the quotes, then use LINQ to filter on just those quotes that are after 1995. For a small amount of data, sure, why not? But for a very large amount of data, you'll need to make sure it won't be too slow.
If you're using a DataSet, though, you can write custom queries that become new TableAdapter methods. So you can put the correct SQL for your query in a FillByYear() method in your TableAdapter and use that to fill your typed DataTable. That way you're only getting back the data you need.
If you go this route, remember that Access/Jet uses positional parameters, not named parameters. So instead of
```
SELECT * FROM Quotes WHERE Year(QuoteDate) > @Year
```
you'd use something like this:
```
SELECT * FROM Quotes WHERE Year(QuoteDate) > ?
```
|
194,534 |
<p>I have been looking at various dependency injection frameworks for .NET as I feel the project I am working on would greatly benefit from it. While I think I have a good grasp of the <em>capabilities</em> of these frameworks, I am still a little unclear on how best to introduce them into a large system. Most demos (understandably) tend to be of quite simple classes that have one or two dependencies. </p>
<p>I have three questions...</p>
<p><strong>First</strong>, how do you deal with those common but uninteresting dependencies, e.g. ILog, IApplicationSettings, IPermissions, IAudit. It seems overkill for every class to have these as parameters in their constructor. Would it be better to use a static instance of the DI container to get these when they are needed?</p>
<pre><code>MyClass(ILog log, IAudit audit, IPermissions permissions, IApplicationSettings settings)
// ... versus ...
ILog log = DIContainer.Get<ILog>();
</code></pre>
<p><strong>Second</strong>, how do you approach dependencies that <em>might</em> be used, but may be expensive to create. Example - a class might have a dependency on an ICDBurner interface but not want the concrete implementation to be created unless the CD Burning feature was actually used. Do you pass in interfaces to factories (e.g. ICDBurnerFactory) in the constructor, or do you again go with some static way of getting directly to the DI Container and ask for it at the point it is needed?</p>
<p><strong>Third</strong>, suppose you have a large Windows Forms application, in which the top level GUI component (e.g. MainForm) is the parent of potentially hundreds of sub-panels or modal forms, each of which may have several dependencies. Does this mean that MainForm should be set up to have as dependencies the superset of all the dependencies of its children? And if you did so, wouldn't this end up creating a huge self-inflating monster that constructs every single class it could ever need the moment you create MainForm, wasting time and memory in the process?</p>
|
[
{
"answer_id": 195411,
"author": "Peter Mounce",
"author_id": 20971,
"author_profile": "https://Stackoverflow.com/users/20971",
"pm_score": 2,
"selected": false,
"text": "<p><strong>First:</strong></p>\n\n<p>You might approach it by creating a container to hold your \"uninteresting\" dependencies (ILog, ICache, IApplicationSettings, etc), and use constructor injection to inject that, then internal to the constructor, hydrate the fields of the service from container.Resolve() ? I'm not sure I'd like that, but, well, it's a possibility.</p>\n\n<p>Alternatively, you might like to use the new IServiceLocator common interface (<a href=\"http://blogs.msdn.com/gblock/archive/2008/10/02/iservicelocator-a-step-toward-ioc-container-service-locator-detente.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/gblock/archive/2008/10/02/iservicelocator-a-step-toward-ioc-container-service-locator-detente.aspx</a>) instead of injecting the dependencies?</p>\n\n<p><strong>Second:</strong></p>\n\n<p>You could use setter injection for the optional/on-demand dependencies? I think I would go for injecting factories and new up from there on-demand.</p>\n"
},
{
"answer_id": 198762,
"author": "wsorenson",
"author_id": 27579,
"author_profile": "https://Stackoverflow.com/users/27579",
"pm_score": 2,
"selected": false,
"text": "<p><strong>First:</strong></p>\n\n<p>You could inject these objects, when needed, as members instead of in the constructor. That way you don't have to make changes to the constructor as your usage changes, and you also don't need to use a static.</p>\n\n<p><strong>Second:</strong></p>\n\n<p>Pass in some sort of builder or factory.</p>\n\n<p><strong>Third:</strong></p>\n\n<p>Any class should only have those dependencies that it itself requires. Subclasses should be injected with their own specific dependencies.</p>\n"
},
{
"answer_id": 198911,
"author": "Maurice",
"author_id": 19676,
"author_profile": "https://Stackoverflow.com/users/19676",
"pm_score": 4,
"selected": true,
"text": "<p><strong>First:</strong> Add the simple dependencies to your constructor as needed. There is no need to add every type to every constructor, just add the ones you need. Need another one, just expand the constructor. Performance should not be a big thing as most of these types are likely to be singletons so already created after the first call. Do not use a static DI Container to create other objects. Instead add the DI Container to itself so it can resolve itself as a dependency. So something like this (assuming Unity for the moment)</p>\n\n<pre><code>IUnityContainer container = new UnityContainer();\ncontainer.RegisterInstance<IUnityContainer>(container);\n</code></pre>\n\n<p>This way you can just add a dependency on IUnityContainer and use that to create expensive or seldom needed objects. The main advantage is that it is much easier when unit testing as there are no static dependencies.</p>\n\n<p><strong>Second:</strong> No need to pass in a factory class. Using the technique above you can use the DI container itself to create expensive objects when needed.</p>\n\n<p><strong>Three:</strong> Add the DI container and the light singleton dependencies to the main form and create the rest through the DI container as needed. Takes a little more code but as you said the startup cost and memory consumption of the mainform would go through the roof if you create everything at startup time.</p>\n"
},
{
"answer_id": 200401,
"author": "Mark Heath",
"author_id": 7532,
"author_profile": "https://Stackoverflow.com/users/7532",
"pm_score": 0,
"selected": false,
"text": "<p>To partially answer my <strong>first</strong> question, I've just found a <a href=\"http://codebetter.com/blogs/jeremy.miller/archive/2008/10/08/setter-injection-in-structuremap-2-5.aspx\" rel=\"nofollow noreferrer\">blog post</a> by Jeremy Miller, showing how Structure Map and setter injection can be used to auto-populate public properties of your objects. He uses ILogger as an example:</p>\n\n<pre><code>var container = new Container(r =>\n{\n r.FillAllPropertiesOfType<ILogger>().TheDefault.Is\n .ConstructedBy(context => new Logger(context.ParentType));\n});\n</code></pre>\n\n<p>This means that any classes with an ILogger property, e.g.:</p>\n\n<pre><code>public class ClassWithLogger\n{\n public ILogger Logger { get; set; }\n}\n\npublic class ClassWithLogger2\n{\n public ILogger Logger { get; set; }\n}\n</code></pre>\n\n<p>will have their Logger property automatically set up when constructed:</p>\n\n<pre><code>container.GetInstance<ClassWithLogger>();\n</code></pre>\n"
},
{
"answer_id": 1577026,
"author": "Nikola Malovic",
"author_id": 19934,
"author_profile": "https://Stackoverflow.com/users/19934",
"pm_score": 5,
"selected": false,
"text": "<p>Well, while you can do this as described in other answers I believe there is more important thing to be answered regarding your example and that is that you are probably violating SRP principle with class having many dependencies.</p>\n\n<p>What I would consider in your example is breaking up the class in couple of more coherent classes with focused concerns and thus the number of their dependencies would fall down.</p>\n\n<p>Nikola's law of SRP and DI</p>\n\n<blockquote>\n <p>\"Any class having more than 3\n dependencies should be questioned for\n SRP violation\"</p>\n</blockquote>\n\n<p>(To avoid lengthy answer, I posted in detail my answers on <a href=\"https://vuscode.wordpress.com/2009/10/16/inversion-of-control-single-responsibility-principle-and-nikola-s-laws-of-dependency-injection/\" rel=\"nofollow noreferrer\">IoC and SRP</a> blog post)</p>\n"
},
{
"answer_id": 1589582,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 2,
"selected": false,
"text": "<p>I have a similar case related to the \"expensive to create and <em>might</em> be used\", where in my own IoC implementation, I'm adding automagic support for factory services.</p>\n\n<p>Basically, instead of this:</p>\n\n<pre><code>public SomeService(ICDBurner burner)\n{\n}\n</code></pre>\n\n<p>you would do this:</p>\n\n<pre><code>public SomeService(IServiceFactory<ICDBurner> burnerFactory)\n{\n}\n\nICDBurner burner = burnerFactory.Create();\n</code></pre>\n\n<p>This has two advantages:</p>\n\n<ul>\n<li>Behind the scenes, the service container that resolved your service is also used to resolve the burner, if and when it is requested</li>\n<li>This alleviates the concerns I've seen before in this kind of case where the typical way would be to inject the service container itself as a parameter to your service, basically saying \"This service requires other services, but I'm not going to easily tell you which ones\"</li>\n</ul>\n\n<p>The factory object is rather easy to make, and solves a lot of problems.</p>\n\n<p>Here's my factory class:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing LVK.IoC.Interfaces;\nusing System.Diagnostics;\n\nnamespace LVK.IoC\n{\n /// <summary>\n /// This class is used to implement <see cref=\"IServiceFactory{T}\"/> for all\n /// services automatically.\n /// </summary>\n [DebuggerDisplay(\"AutoServiceFactory (Type={typeof(T)}, Policy={Policy})\")]\n internal class AutoServiceFactory<T> : ServiceBase, IServiceFactory<T>\n {\n #region Private Fields\n\n [DebuggerBrowsable(DebuggerBrowsableState.Never)]\n private readonly String _Policy;\n\n #endregion\n\n #region Construction & Destruction\n\n /// <summary>\n /// Initializes a new instance of the <see cref=\"AutoServiceFactory&lt;T&gt;\"/> class.\n /// </summary>\n /// <param name=\"serviceContainer\">The service container involved.</param>\n /// <param name=\"policy\">The policy to use when resolving the service.</param>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"serviceContainer\"/> is <c>null</c>.</exception>\n public AutoServiceFactory(IServiceContainer serviceContainer, String policy)\n : base(serviceContainer)\n {\n _Policy = policy;\n }\n\n /// <summary>\n /// Initializes a new instance of the <see cref=\"AutoServiceFactory&lt;T&gt;\"/> class.\n /// </summary>\n /// <param name=\"serviceContainer\">The service container involved.</param>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"serviceContainer\"/> is <c>null</c>.</exception>\n public AutoServiceFactory(IServiceContainer serviceContainer)\n : this(serviceContainer, null)\n {\n // Do nothing here\n }\n\n #endregion\n\n #region Public Properties\n\n /// <summary>\n /// Gets the policy that will be used when the service is resolved.\n /// </summary>\n public String Policy\n {\n get\n {\n return _Policy;\n }\n }\n\n #endregion\n\n #region IServiceFactory<T> Members\n\n /// <summary>\n /// Constructs a new service of the correct type and returns it.\n /// </summary>\n /// <returns>The created service.</returns>\n public IService<T> Create()\n {\n return MyServiceContainer.Resolve<T>(_Policy);\n }\n\n #endregion\n }\n}\n</code></pre>\n\n<p>Basically, when I build the service container from my service container builder class, all service registrations are automatically given another co-service, implementing IServiceFactory for that service, unless the programmer has explicitly registered on him/her-self for that service. The above service is then used, with one parameter specifying the policy (which can be null if policies aren't used).</p>\n\n<p>This allows me to do this:</p>\n\n<pre><code>var builder = new ServiceContainerBuilder();\nbuilder.Register<ISomeService>()\n .From.ConcreteType<SomeService>();\n\nusing (var container = builder.Build())\n{\n using (var factory = container.Resolve<IServiceFactory<ISomeService>>())\n {\n using (var service = factory.Instance.Create())\n {\n service.Instance.DoSomethingAwesomeHere();\n }\n }\n}\n</code></pre>\n\n<p>Of course, a more typical use would be with your CD Burner object. In the above code I would resolve the service instead of course, but it's an illustration of what happens.</p>\n\n<p>So with your cd burner service instead:</p>\n\n<pre><code>var builder = new ServiceContainerBuilder();\nbuilder.Register<ICDBurner>()\n .From.ConcreteType<CDBurner>();\nbuilder.Register<ISomeService>()\n .From.ConcreteType<SomeService>(); // constructor used in the top of answer\n\nusing (var container = builder.Build())\n{\n using (var service = container.Resolve<ISomeService>())\n {\n service.Instance.DoSomethingHere();\n }\n}\n</code></pre>\n\n<p>inside the service, you could now have a service, a factory service, which knows how to resolve your cd burner service upon request. This is useful for the following reasons:</p>\n\n<ul>\n<li>You might want to resolve more than one service at the same time (burn two discs simultaneously?)</li>\n<li>You might not need it, and it could be costly to create, so you only resolve it <em>if</em> needed</li>\n<li>You might need to resolve, dispose, resolve, dispose, multiple times, instead of hoping/trying to clean up an existing service instance</li>\n<li>You're also flagging in your constructor which services you <em>need</em> and which ones you <em>might need</em></li>\n</ul>\n\n<p>Here's two at the same time:</p>\n\n<pre><code>using (var service1 = container.Resolve<ISomeService>())\nusing (var service2 = container.Resolve<ISomeService>())\n{\n service1.Instance.DoSomethingHere();\n service2.Instance.DoSomethingHere();\n}\n</code></pre>\n\n<p>Here's two after each other, not reusing the same service:</p>\n\n<pre><code>using (var service = container.Resolve<ISomeService>())\n{\n service.Instance.DoSomethingHere();\n}\nusing (var service = container.Resolve<ISomeService>())\n{\n service.Instance.DoSomethingElseHere();\n}\n</code></pre>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7532/"
] |
I have been looking at various dependency injection frameworks for .NET as I feel the project I am working on would greatly benefit from it. While I think I have a good grasp of the *capabilities* of these frameworks, I am still a little unclear on how best to introduce them into a large system. Most demos (understandably) tend to be of quite simple classes that have one or two dependencies.
I have three questions...
**First**, how do you deal with those common but uninteresting dependencies, e.g. ILog, IApplicationSettings, IPermissions, IAudit. It seems overkill for every class to have these as parameters in their constructor. Would it be better to use a static instance of the DI container to get these when they are needed?
```
MyClass(ILog log, IAudit audit, IPermissions permissions, IApplicationSettings settings)
// ... versus ...
ILog log = DIContainer.Get<ILog>();
```
**Second**, how do you approach dependencies that *might* be used, but may be expensive to create. Example - a class might have a dependency on an ICDBurner interface but not want the concrete implementation to be created unless the CD Burning feature was actually used. Do you pass in interfaces to factories (e.g. ICDBurnerFactory) in the constructor, or do you again go with some static way of getting directly to the DI Container and ask for it at the point it is needed?
**Third**, suppose you have a large Windows Forms application, in which the top level GUI component (e.g. MainForm) is the parent of potentially hundreds of sub-panels or modal forms, each of which may have several dependencies. Does this mean that MainForm should be set up to have as dependencies the superset of all the dependencies of its children? And if you did so, wouldn't this end up creating a huge self-inflating monster that constructs every single class it could ever need the moment you create MainForm, wasting time and memory in the process?
|
**First:** Add the simple dependencies to your constructor as needed. There is no need to add every type to every constructor, just add the ones you need. Need another one, just expand the constructor. Performance should not be a big thing as most of these types are likely to be singletons so already created after the first call. Do not use a static DI Container to create other objects. Instead add the DI Container to itself so it can resolve itself as a dependency. So something like this (assuming Unity for the moment)
```
IUnityContainer container = new UnityContainer();
container.RegisterInstance<IUnityContainer>(container);
```
This way you can just add a dependency on IUnityContainer and use that to create expensive or seldom needed objects. The main advantage is that it is much easier when unit testing as there are no static dependencies.
**Second:** No need to pass in a factory class. Using the technique above you can use the DI container itself to create expensive objects when needed.
**Three:** Add the DI container and the light singleton dependencies to the main form and create the rest through the DI container as needed. Takes a little more code but as you said the startup cost and memory consumption of the mainform would go through the roof if you create everything at startup time.
|
194,565 |
<p>I have to implement the VinPower application. They offer a Java version, a C dll and an ActiveX dll, if anyone has an idea on where I could begin, I'd appreciate it.</p>
|
[
{
"answer_id": 194580,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 0,
"selected": false,
"text": "<p>A quick Google search shows that there is <a href=\"http://www.vinpowerdigital.com\" rel=\"nofollow noreferrer\">Vinpower</a> and there is <a href=\"http://www.vinpower.com\" rel=\"nofollow noreferrer\">VinPOWER</a>. To which one are you referring?</p>\n\n<p>When you say \"implement\", are you looking at writing your own library that does the same thing as an existing product? Or did you mean to say \"integrate\" where you need to use a third party library within your existing project?</p>\n\n<p>If your goal is to integrate, and the vendor supplies different versions of the library for different interfaces, I would pick the one that would be easiest to integrate with your existing project. For example, if your code is already in Java then I would pick the Java version of their library. If your code is in Visual Basic, then you might be best off with the ActiveX dll.</p>\n"
},
{
"answer_id": 194911,
"author": "Peter Boughton",
"author_id": 9360,
"author_profile": "https://Stackoverflow.com/users/9360",
"pm_score": 2,
"selected": true,
"text": "<p>First step would be to put the VinPOWER Jar file into your lib directory, then restart the server.<br/>(Or, you can put the file in a different directory and then add the path in CF Administrator)</p>\n\n<p>Then to use it... well, here is their Java sample in CFML:</p>\n\n<pre><code><cfset vp = createObject(\"java\",\"com.pki.vp4j.VinPower\") />\n\n<cfset rc = vp.decodeVIN(\"JTEDP21A650046919\") />\n\n<cfif rc>\n <cfoutput>#vp.getAsXML()#</cfoutput>\n</cfif>\n</code></pre>\n\n<p>Give that a try and see what you get?</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26121/"
] |
I have to implement the VinPower application. They offer a Java version, a C dll and an ActiveX dll, if anyone has an idea on where I could begin, I'd appreciate it.
|
First step would be to put the VinPOWER Jar file into your lib directory, then restart the server.
(Or, you can put the file in a different directory and then add the path in CF Administrator)
Then to use it... well, here is their Java sample in CFML:
```
<cfset vp = createObject("java","com.pki.vp4j.VinPower") />
<cfset rc = vp.decodeVIN("JTEDP21A650046919") />
<cfif rc>
<cfoutput>#vp.getAsXML()#</cfoutput>
</cfif>
```
Give that a try and see what you get?
|
194,574 |
<p>I was trying to insert new data into an existing XML file, but it's not working. Here's my xml file:</p>
<pre><code><list>
<activity>swimming</activity>
<activity>running</activity>
<list>
</code></pre>
<p>Now, my idea was making two files: an index page, where it displays what's on the file and provides a field for inserting new elements, and a php page which will insert the data into the XML file. Here's the code for index.php:</p>
<pre><code><html>
<head><title>test</title></head>
</head>
<?php
$xmldoc = new DOMDocument();
$xmldoc->load('sample.xml', LIBXML_NOBLANKS);
$activities = = $xmldoc->firstChild->firstChild;
if($activities!=null){
while(activities!=null){
echo $activities->textContent.'<br/>';
activities = activities->nextSibling.
}
}
?>
<form name='input' action='insert.php' method='post'>
insert activity:
<input type='text' name='activity'/>
<input type='submit' value='send'/>
</form>
</body>
</html
</code></pre>
<p>and here's the code for insert.php:</p>
<pre><code><?php
header('Location:index.php');
$xmldoc = new DOMDocument();
$xmldoc->load('sample.xml');
$newAct = $_POST['activity'];
$root = $xmldoc->firstChild;
$newElement = $xmldoc->createElement('activity');
$root->appendChild($newElement);
$newText = $xmldoc->createTextNode($newAct);
$newElement->appendChild($newText);
$xmldoc->save('sample.xml');
?>
</code></pre>
<p>The user is to access index.php, where he would see a list of the current activities present in the XML file, and a text field below where he can insert new activities. Upon clicking the send button, the page would call insert.php, which contains a code that opens the XML file in a DOM tree, inserts a new node under the root node and calls back the index.php page, where the user should be able to see the list of activities, his new activity there under the others. It is not working. When i click on the button to submit a new entry, the pages refreshes and apparently nothing happens, the XML is the same as before. What did i do wrong? Also, i'd like to know if there's a better way of doing it.</p>
|
[
{
"answer_id": 194637,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 4,
"selected": true,
"text": "<p>is your code block copy and pasted from your existing files? if so i see two potential issues:</p>\n\n<pre><code><form name='input' action'insert.php' method='post'> // should be:\n<form name=\"input\" action=\"insert.php\" method=\"post\">\n</code></pre>\n\n<p>note: you're missing <code>action</code><strong>=</strong><code>\"insert.php\"</code>, which would cause the form to just reload itself without submitting, which is the behaviour you describe.</p>\n\n<p>secondly, make sure you have write permission to \"sample.xml\". you can confirm if you're actually writing anything:</p>\n\n<pre><code>print 'I wrote '.$xmldoc->save('sample.xml').' bytes of data';\n</code></pre>\n"
},
{
"answer_id": 246802,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>$newText = $xmldoc->createTextNode($newActv);</p>\n\n<p>Change this line to </p>\n\n<p>$newText = $xmldoc->createTextNode($newAct);</p>\n"
},
{
"answer_id": 256662,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Actually you made mistakes in two places.</p>\n\n<p>\nThis line should be\n I think because of the typo, you missed an equal sign. Also</p>\n\n<p>\n\nThese lines should be\n\n</p>\n\n<p>Try now, it should work,\nHop this would make some sense</p>\n"
},
{
"answer_id": 676025,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I think I know what is the problem with your code. You should not write like that: <code><?xml-stylesheet type=\"text/xsl\" href=\"sample.xsl\" ?></code>\nThe right code is:</p>\n\n<pre><code><?xml:stylesheet type=\"text/xsl\" href=\"sample.xsl\" ?>\n</code></pre>\n"
},
{
"answer_id": 1585440,
"author": "wicho",
"author_id": 192066,
"author_profile": "https://Stackoverflow.com/users/192066",
"pm_score": 2,
"selected": false,
"text": "<p>this is the code i work for me.</p>\n\n<p>index.php</p>\n\n<pre><code><html>\n<head><title>test</title></head>\n</head>\n\n<?php\n $xmldoc = new DOMDocument();\n $xmldoc->load('sample.xml', LIBXML_NOBLANKS);\n\n $activities = $xmldoc->firstChild->firstChild;\n if($activities!=null){\n while($activities!=null){\n echo $activities->textContent.'<br/>';\n $activities = $activities->nextSibling;\n }\n }\n?>\n\n<form name='input' action='insert.php' method='post'>\n insert activity:\n <input type='text' name='activity'/>\n <input type='submit' value='send'/>\n</form>\n</body>\n</html>\n\n\n\n\ninsert.php\n\n\n<?php\n header('Location:index.php');\n $xmldoc = new DOMDocument();\n $xmldoc->load('sample.xml');\n\n $newAct = $_POST['activity'];\n\n $root = $xmldoc->firstChild;\n\n $newElement = $xmldoc->createElement('activity');\n $root->appendChild($newElement);\n $newText = $xmldoc->createTextNode($newAct);\n $newElement->appendChild($newText);\n\n $xmldoc->save('sample.xml');\n?>\n</code></pre>\n\n<p>sample.xml</p>\n\n<pre><code><list>\n <activity>swimming</activity> \n <activity>running</activity> \n</list>\n</code></pre>\n"
},
{
"answer_id": 1965053,
"author": "Amdad Hossain",
"author_id": 239045,
"author_profile": "https://Stackoverflow.com/users/239045",
"pm_score": 3,
"selected": false,
"text": "<p>Final Solution</p>\n\n<p><strong>sample.XML</strong></p>\n\n<pre><code><list>\n <activity>swimming</activity>\n <activity>running</activity>\n <activity>Jogging</activity>\n <activity>Theatre</activity>\n <activity>Programming</activity>\n</list>\n</code></pre>\n\n<p><strong>index.php</strong></p>\n\n<pre><code><html>\n<head><title>test</title></head>\n</head>\n\n<?php\n $xmldoc = new DOMDocument();\n $xmldoc->load(\"sample.xml\", LIBXML_NOBLANKS);\n\n $activities = $xmldoc->firstChild->firstChild;\n if($activities!=null){\n while($activities!=null){\n echo $activities->textContent.\"<br/>\";\n $activities = $activities->nextSibling;\n }\n }\n?>\n\n<form name=\"input\" action=\"insert.php\" method=\"post\">\n insert activity:\n <input type=\"text\" name=\"activity\"/>\n <input type=\"submit\" value=\"send\"/>\n</form>\n</body>\n</html>\n</code></pre>\n\n<p><strong>insert.php</strong></p>\n\n<pre><code><?php\n header('Location:index.php');\n $xmldoc = new DOMDocument();\n $xmldoc->load('sample.xml');\n\n $newAct = $_POST['activity'];\n\n $root = $xmldoc->firstChild;\n\n $newElement = $xmldoc->createElement('activity');\n $root->appendChild($newElement);\n $newText = $xmldoc->createTextNode($newAct);\n $newElement->appendChild($newText);\n\n $xmldoc->save('sample.xml');\n?>\n</code></pre>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27090/"
] |
I was trying to insert new data into an existing XML file, but it's not working. Here's my xml file:
```
<list>
<activity>swimming</activity>
<activity>running</activity>
<list>
```
Now, my idea was making two files: an index page, where it displays what's on the file and provides a field for inserting new elements, and a php page which will insert the data into the XML file. Here's the code for index.php:
```
<html>
<head><title>test</title></head>
</head>
<?php
$xmldoc = new DOMDocument();
$xmldoc->load('sample.xml', LIBXML_NOBLANKS);
$activities = = $xmldoc->firstChild->firstChild;
if($activities!=null){
while(activities!=null){
echo $activities->textContent.'<br/>';
activities = activities->nextSibling.
}
}
?>
<form name='input' action='insert.php' method='post'>
insert activity:
<input type='text' name='activity'/>
<input type='submit' value='send'/>
</form>
</body>
</html
```
and here's the code for insert.php:
```
<?php
header('Location:index.php');
$xmldoc = new DOMDocument();
$xmldoc->load('sample.xml');
$newAct = $_POST['activity'];
$root = $xmldoc->firstChild;
$newElement = $xmldoc->createElement('activity');
$root->appendChild($newElement);
$newText = $xmldoc->createTextNode($newAct);
$newElement->appendChild($newText);
$xmldoc->save('sample.xml');
?>
```
The user is to access index.php, where he would see a list of the current activities present in the XML file, and a text field below where he can insert new activities. Upon clicking the send button, the page would call insert.php, which contains a code that opens the XML file in a DOM tree, inserts a new node under the root node and calls back the index.php page, where the user should be able to see the list of activities, his new activity there under the others. It is not working. When i click on the button to submit a new entry, the pages refreshes and apparently nothing happens, the XML is the same as before. What did i do wrong? Also, i'd like to know if there's a better way of doing it.
|
is your code block copy and pasted from your existing files? if so i see two potential issues:
```
<form name='input' action'insert.php' method='post'> // should be:
<form name="input" action="insert.php" method="post">
```
note: you're missing `action`**=**`"insert.php"`, which would cause the form to just reload itself without submitting, which is the behaviour you describe.
secondly, make sure you have write permission to "sample.xml". you can confirm if you're actually writing anything:
```
print 'I wrote '.$xmldoc->save('sample.xml').' bytes of data';
```
|
194,579 |
<p>I've got a php page which handles requets for file downloads. I need to be able to detect when a file has been downloaded successfully. How can this be done? Perhaps there's some means of detecting this client-side then sending a confirmation down to the server.</p>
<p>Thanks.</p>
<p>Edit:
By handle, I mean that the page is doing something like this:</p>
<pre><code>$file = '/var/www/html/file-to-download.xyz';
header('Content-Type: application/octet-stream');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename=' . basename($file));
readfile($file);
</code></pre>
|
[
{
"answer_id": 194618,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 5,
"selected": true,
"text": "<p>Handle the download in a seperate php script (better do a little more than just <code>readfile($file);</code>, you can also provide the ability to resume downloads like in this <a href=\"https://stackoverflow.com/questions/157318/resumable-downloads-when-using-php-to-send-the-file\">question</a>).\nThen in this script, when you <em>read</em> the last block and send it, you know that all the file was sent. This is not the same as knowing that all was received, but it should be enough for most scenarios.</p>\n"
},
{
"answer_id": 196246,
"author": "Willem",
"author_id": 15447,
"author_profile": "https://Stackoverflow.com/users/15447",
"pm_score": 2,
"selected": false,
"text": "<p>What Treb said, but I should add that you can check if the client is still listening during download with <a href=\"http://nl3.php.net/connection_status\" rel=\"nofollow noreferrer\">connection_status()</a>.</p>\n\n<p>Don't forget to <code>flush()</code> after you've written data to the client, it helps in detecting if the connection is still up.</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19467/"
] |
I've got a php page which handles requets for file downloads. I need to be able to detect when a file has been downloaded successfully. How can this be done? Perhaps there's some means of detecting this client-side then sending a confirmation down to the server.
Thanks.
Edit:
By handle, I mean that the page is doing something like this:
```
$file = '/var/www/html/file-to-download.xyz';
header('Content-Type: application/octet-stream');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename=' . basename($file));
readfile($file);
```
|
Handle the download in a seperate php script (better do a little more than just `readfile($file);`, you can also provide the ability to resume downloads like in this [question](https://stackoverflow.com/questions/157318/resumable-downloads-when-using-php-to-send-the-file)).
Then in this script, when you *read* the last block and send it, you know that all the file was sent. This is not the same as knowing that all was received, but it should be enough for most scenarios.
|
194,616 |
<p>I have an application installed on my computer. How do I find out if it was compiled in DEBUG mode or not?</p>
<p>I've tried to use <a href="http://en.wikipedia.org/wiki/.NET_Reflector" rel="noreferrer">.NET Reflector</a>, but it does not show anything specific. Here is what I see:</p>
<pre><code>// Assembly APPLICATION_NAME, Version 8.0.0.15072
Location: C:\APPLICATION_FOLDER\APPLICATION_NAME.exe
Name: APPLICATION_NAME, Version=8.0.0.15072, Culture=neutral, PublicKeyToken=null
Type: Windows Application
</code></pre>
|
[
{
"answer_id": 194625,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 5,
"selected": false,
"text": "<p>I <a href=\"http://chillijam.co.uk/?p=134\" rel=\"noreferrer\">blogged</a> this a long time ago, and I don't know if it still valid or not, but the code is something like...</p>\n\n<pre><code>private void testfile(string file)\n{\n if(isAssemblyDebugBuild(file))\n {\n MessageBox.Show(String.Format(\"{0} seems to be a debug build\",file));\n }\n else\n {\n MessageBox.Show(String.Format(\"{0} seems to be a release build\",file));\n }\n} \n\nprivate bool isAssemblyDebugBuild(string filename)\n{\n return isAssemblyDebugBuild(System.Reflection.Assembly.LoadFile(filename)); \n} \n\nprivate bool isAssemblyDebugBuild(System.Reflection.Assembly assemb)\n{\n bool retVal = false;\n foreach(object att in assemb.GetCustomAttributes(false))\n {\n if(att.GetType() == System.Type.GetType(\"System.Diagnostics.DebuggableAttribute\"))\n {\n retVal = ((System.Diagnostics.DebuggableAttribute)att).IsJITTrackingEnabled;\n }\n }\n return retVal;\n}\n</code></pre>\n"
},
{
"answer_id": 194635,
"author": "Joe Basirico",
"author_id": 20795,
"author_profile": "https://Stackoverflow.com/users/20795",
"pm_score": 3,
"selected": false,
"text": "<p>You're on the right path actually. If you look in the Disassembler window in reflector you will see the following line if it was built in debug mode:</p>\n\n<pre><code>[assembly: Debuggable(...)]\n</code></pre>\n"
},
{
"answer_id": 638241,
"author": "flipdoubt",
"author_id": 470,
"author_profile": "https://Stackoverflow.com/users/470",
"pm_score": 2,
"selected": false,
"text": "<p>How about using Jeff Key's <a href=\"http://www.sliver.com/dotnet/IsDebug/\" rel=\"nofollow noreferrer\">IsDebug</a> utility? It is a little dated, but since you have Reflector you can decompile it and recompile it in any version of the framework. I did.</p>\n"
},
{
"answer_id": 5316442,
"author": "Dave Black",
"author_id": 251267,
"author_profile": "https://Stackoverflow.com/users/251267",
"pm_score": 5,
"selected": false,
"text": "<p>ZombieSheep's answer is incorrect.</p>\n\n<p>My answer to this duplicate question is here:<a href=\"https://stackoverflow.com/questions/798971/how-to-identify-if-the-dll-is-debug-or-release-build-in-net/5316565#5316565\">How to tell if a .NET application was compiled in DEBUG or RELEASE mode?</a> </p>\n\n<p>Be very careful - just looking at the 'assembly attributes' in the Assembly Manifest for the presence of the 'Debuggable' attribute does <strong>NOT</strong> mean that you have an assembly that is not JIT optimized. The assembly could be JIT optimized but have the Assembly Output under Advanced Build settings set to include 'full' or 'pdb-only' info - in which case the 'Debuggable' attribute will be present.</p>\n\n<p>Please refer to my posts below for more info:\n<a href=\"http://dave-black.blogspot.com/2011/12/how-to-tell-if-assembly-is-debug-or.html\" rel=\"nofollow noreferrer\">How to Tell if an Assembly is Debug or Release</a> and\n<a href=\"https://stackoverflow.com/questions/798971/how-to-idenfiy-if-the-dll-is-debug-or-release-build-in-net/5316565#5316565\">How to identify if the DLL is Debug or Release build (in .NET)</a></p>\n\n<p>Jeff Key's application doesn't work correctly, because it identifies a \"Debug\" build based on if the DebuggableAttribute is present. The DebuggableAttribute is present if you compile in Release mode and choose DebugOutput to anything other than \"none\".</p>\n\n<p>You also need to define <em>exaclty</em> what is meant by \"Debug\" vs. \"Release\"...</p>\n\n<ul>\n<li>Do you mean that the application is configured with code optimization?</li>\n<li>Do you mean that you can attach the Visual Studio/JIT Debugger to it?</li>\n<li>Do you mean that it generates DebugOutput?</li>\n<li>Do you mean that it defines the DEBUG constant? Remember that you can conditionally compile methods with the <code>System.Diagnostics.Conditional()</code> attribute.</li>\n</ul>\n"
},
{
"answer_id": 14160090,
"author": "Max",
"author_id": 1057961,
"author_profile": "https://Stackoverflow.com/users/1057961",
"pm_score": 2,
"selected": false,
"text": "<p>Here is the VB.Net version of the solution proposed by ZombieSheep</p>\n\n<pre><code>Public Shared Function IsDebug(Assem As [Assembly]) As Boolean\n For Each attrib In Assem.GetCustomAttributes(False)\n If TypeOf attrib Is System.Diagnostics.DebuggableAttribute Then\n Return DirectCast(attrib, System.Diagnostics.DebuggableAttribute).IsJITTrackingEnabled\n End If\n Next\n\n Return False\nEnd Function\n\nPublic Shared Function IsThisAssemblyDebug() As Boolean\n Return IsDebug([Assembly].GetCallingAssembly)\nEnd Function\n</code></pre>\n\n<p><strong>Update</strong><br>\nThis solution works for me but, as Dave Black pointed out, there may be situation where a different approach is needed.<br>\nSo maybe you can also take a look a Dave Black's answer:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/798971/how-to-identify-if-the-dll-is-debug-or-release-build-in-net/5316565#5316565\">How to identify if the DLL is Debug or Release build (in .NET)</a></li>\n<li><a href=\"https://stackoverflow.com/questions/194616/how-to-tell-if-a-net-application-was-compiled-in-debug-or-release-mode/5316442#5316442\">How to tell if a .NET application was compiled in DEBUG or RELEASE mode?</a></li>\n</ul>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have an application installed on my computer. How do I find out if it was compiled in DEBUG mode or not?
I've tried to use [.NET Reflector](http://en.wikipedia.org/wiki/.NET_Reflector), but it does not show anything specific. Here is what I see:
```
// Assembly APPLICATION_NAME, Version 8.0.0.15072
Location: C:\APPLICATION_FOLDER\APPLICATION_NAME.exe
Name: APPLICATION_NAME, Version=8.0.0.15072, Culture=neutral, PublicKeyToken=null
Type: Windows Application
```
|
I [blogged](http://chillijam.co.uk/?p=134) this a long time ago, and I don't know if it still valid or not, but the code is something like...
```
private void testfile(string file)
{
if(isAssemblyDebugBuild(file))
{
MessageBox.Show(String.Format("{0} seems to be a debug build",file));
}
else
{
MessageBox.Show(String.Format("{0} seems to be a release build",file));
}
}
private bool isAssemblyDebugBuild(string filename)
{
return isAssemblyDebugBuild(System.Reflection.Assembly.LoadFile(filename));
}
private bool isAssemblyDebugBuild(System.Reflection.Assembly assemb)
{
bool retVal = false;
foreach(object att in assemb.GetCustomAttributes(false))
{
if(att.GetType() == System.Type.GetType("System.Diagnostics.DebuggableAttribute"))
{
retVal = ((System.Diagnostics.DebuggableAttribute)att).IsJITTrackingEnabled;
}
}
return retVal;
}
```
|
194,621 |
<p>I know there are a few different <a href="http://en.wikipedia.org/wiki/Traveling_salesman_problem" rel="nofollow noreferrer">Traveling Salesman</a> projects out there and I've played with <a href="http://www.akira.ruc.dk/~keld/research/LKH/" rel="nofollow noreferrer">LKH</a> a bit, but I was wondering if anyone had any recommendations on any other ones?</p>
<p>My project is GPL'ed so I would need something that is compatible with that license.</p>
<p><img src="https://i.stack.imgur.com/6WnwE.gif" alt="Input"> <img src="https://i.stack.imgur.com/lAUwq.gif" alt="Output"></p>
|
[
{
"answer_id": 194631,
"author": "Simon",
"author_id": 24039,
"author_profile": "https://Stackoverflow.com/users/24039",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.ics.forth.gr/~lourakis/levmar/\" rel=\"nofollow noreferrer\">This one</a> looks good. </p>\n\n<p>I know it is not a great answer, but if you are open to changing technology then <a href=\"http://scipy.org\" rel=\"nofollow noreferrer\">scipy</a> has a bunch of optimisation algorithms which are very good</p>\n"
},
{
"answer_id": 197110,
"author": "dsm",
"author_id": 7780,
"author_profile": "https://Stackoverflow.com/users/7780",
"pm_score": 2,
"selected": false,
"text": "<p>In general, <a href=\"http://en.wikipedia.org/wiki/Special:Search?search=space+filling+fractal\" rel=\"nofollow noreferrer\">Space Filling Fractals</a> will give you some of the best results at the lowest costs.</p>\n\n<p>In particular, I would recommend the <a href=\"http://en.wikipedia.org/wiki/Sierpi%C5%84ski_curve\" rel=\"nofollow noreferrer\">Sierpiński curve</a>.</p>\n\n<p>Here is a sample implementation that uses it:</p>\n\n<pre><code>(defvar *grid-width* 100000)\n(defvar *grid-heigth* 100000)\n(defvar *max-number-of-points* 1000)\n(defvar *search-area-width* (* 2 *grid-width*))\n(defvar *search-area-heigth* (* 2 *grid-heigth*))\n\n(defun make-random-point (max-x max-y)\n \"makes a point in a random position of the grid\"\n (complex\n (/ (random (* max-x 1000)) 1000)\n (/ (random (* max-y 1000)) 1000)))\n\n\n(defun make-random-point-list (max-len)\n \"makes a list of random points up to max-len length\"\n (let ((value ())) ; Make a set of random points\n (dotimes (n (random max-len) value)\n (setq value\n (cons (make-random-point *grid-width* *grid-heigth*) value)))))\n\n(defun get-printable-point-position (point)\n \"Gets a rounded-off point that can be used to make a dot on a visual grid\"\n (complex\n (round (realpart point))\n (round (imagpart point))))\n\n(defun euclid (point-a point-b)\n \"calculates the euclidean distance in between two points\"\n (let* ((p (- point-a point-b)))\n (sqrt\n (+ (expt (realpart p) 2)\n (expt (imagpart p) 2)))))\n\n(defstruct triangle\n \"A triangle consists of 3 points.\n Complex numbers are used to construct the points,\n the real part signifying the X axis,\n and the imaginary part signifying the Y axis.\"\n a b c)\n\n(defun avg (&rest numbers)\n \"Gets the average of the numbers provided\"\n (if\n (null numbers)\n 1 ; prevents divide by 0\n (/ (apply #'+ numbers) (length numbers)))) ;/\n\n(defun get-triangle-centre (triangle)\n \"Gets the centre of a triangle\"\n (avg (triangle-a triangle)\n (triangle-b triangle)\n (triangle-c triangle)))\n\n(defstruct (triangle-list\n (:include triangle))\n point-list)\n\n(defun triangle-split (triangle)\n \"Splits a triangle in two according to the rule:\n { a0->c1; b0->a1,c2; c0->a2; avg(c0,a0)->b1,b2 }\"\n (let* ((old-a-point (triangle-a triangle))\n (old-b-point (triangle-b triangle))\n (old-c-point (triangle-c triangle))\n (new-b-point (avg old-a-point old-c-point)))\n (list\n (make-triangle-list :a old-b-point :b new-b-point :c old-a-point)\n (make-triangle-list :a old-c-point :b new-b-point :c old-b-point))))\n\n(defun triangle-list-split (triangle-list)\n \"Split a triangle list and acomodate all the points in their right places\"\n (let* ((triangles (triangle-split triangle-list))\n (triangle-a (car triangles))\n (triangle-b (cadr triangles))\n (centre-a (get-triangle-centre triangle-a))\n (centre-b (get-triangle-centre triangle-b)))\n (dolist (point (triangle-list-point-list triangle-list))\n (if (< (euclid point centre-a) (euclid point centre-b))\n (setf (triangle-list-point-list triangle-a)\n (cons point (triangle-list-point-list triangle-a)))\n (setf (triangle-list-point-list triangle-b)\n (cons point (triangle-list-point-list triangle-b)))))\n (let ((list-a (triangle-list-point-list triangle-a))\n (list-b (triangle-list-point-list triangle-b)))\n (if (= 1 (length list-a))\n (setf (triangle-list-point-list triangle-a) (car list-a)))\n (if (= 1 (length list-b))\n (setf (triangle-list-point-list triangle-b) (car list-b))))\n (list triangle-a triangle-b)))\n\n(defun print-point (out point &rest args)\n \"Utility function - Pretty-prints a point\"\n (format out \"(X:~F, Y:~F)\"\n (realpart point)\n (imagpart point))\n args)\n\n(defun pprint-triangle-list (out triangle-list &rest args)\n \"Utility function - Pretty-prints a triangle-list object\"\n (format out \" TRIANGLE{\n A:~/print-point/\n B:~/print-point/\n C:~/print-point/\n CENTRE:~/print-point/\n POINTS:{~{~/print-point/~^,~% ~}}~& }\"\n (triangle-a triangle-list)\n (triangle-b triangle-list)\n (triangle-c triangle-list)\n (get-triangle-centre triangle-list)\n (let ((points (triangle-list-point-list triangle-list)))\n (cond\n ((null points) ())\n ((listp points) points)\n (t (list points)))))\n args)\n\n(defun print-list-of-triangle-list (lst)\n \"Pretty-prints a list of triangle-list objects\"\n (format t \"(~{~/pprint-triangle-list/~^,~% ~}~&)\" lst))\n\n(defun explode (lst)\n \"explodes a triangle-list list and gets all\n the points in the order they should be\"\n (let ((l (flatten lst)))\n (cond\n ((null l) ())\n ((triangle-list-p l) (explode (triangle-list-split l)))\n ((null (triangle-list-point-list (car l)))\n (explode (cdr l)))\n ((atom (triangle-list-point-list (car l)))\n (cons (car l) (explode (cdr l))))\n (t (explode (append (triangle-list-split (car l)) (cdr l)))))))\n\n\n(defun flatten (lst)\n \"Flattens a list (removes nesting and nulls)\"\n (cond\n ((atom lst) lst)\n ((listp (car lst))\n (append (flatten (car lst)) (flatten (cdr lst))))\n (t (append (list (car lst)) (flatten (cdr lst))))))\n\n(let ((triangle (make-triangle-list\n :a (complex 0 *search-area-heigth*)\n :b 0\n :c *search-area-width*\n :point-list (make-random-point-list *max-number-of-points*))))\n (print-list-of-triangle-list (explode triangle)))\n</code></pre>\n\n<p>I also had a version using a GA (that one in C), but it lives in a dead hard drive.</p>\n"
},
{
"answer_id": 2165125,
"author": "Grembo",
"author_id": 240403,
"author_profile": "https://Stackoverflow.com/users/240403",
"pm_score": 0,
"selected": false,
"text": "<p>There's one <a href=\"http://www.cs.sunysb.edu/~algorith/implement/syslo/distrib/processed/babtsp.p\" rel=\"nofollow noreferrer\">here</a> that solves TSP exactly, but it's in PASCAL. In the current form the distances are integers, though. Shouldn't be hard too rewrite in C++. </p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13676/"
] |
I know there are a few different [Traveling Salesman](http://en.wikipedia.org/wiki/Traveling_salesman_problem) projects out there and I've played with [LKH](http://www.akira.ruc.dk/~keld/research/LKH/) a bit, but I was wondering if anyone had any recommendations on any other ones?
My project is GPL'ed so I would need something that is compatible with that license.
 
|
In general, [Space Filling Fractals](http://en.wikipedia.org/wiki/Special:Search?search=space+filling+fractal) will give you some of the best results at the lowest costs.
In particular, I would recommend the [Sierpiński curve](http://en.wikipedia.org/wiki/Sierpi%C5%84ski_curve).
Here is a sample implementation that uses it:
```
(defvar *grid-width* 100000)
(defvar *grid-heigth* 100000)
(defvar *max-number-of-points* 1000)
(defvar *search-area-width* (* 2 *grid-width*))
(defvar *search-area-heigth* (* 2 *grid-heigth*))
(defun make-random-point (max-x max-y)
"makes a point in a random position of the grid"
(complex
(/ (random (* max-x 1000)) 1000)
(/ (random (* max-y 1000)) 1000)))
(defun make-random-point-list (max-len)
"makes a list of random points up to max-len length"
(let ((value ())) ; Make a set of random points
(dotimes (n (random max-len) value)
(setq value
(cons (make-random-point *grid-width* *grid-heigth*) value)))))
(defun get-printable-point-position (point)
"Gets a rounded-off point that can be used to make a dot on a visual grid"
(complex
(round (realpart point))
(round (imagpart point))))
(defun euclid (point-a point-b)
"calculates the euclidean distance in between two points"
(let* ((p (- point-a point-b)))
(sqrt
(+ (expt (realpart p) 2)
(expt (imagpart p) 2)))))
(defstruct triangle
"A triangle consists of 3 points.
Complex numbers are used to construct the points,
the real part signifying the X axis,
and the imaginary part signifying the Y axis."
a b c)
(defun avg (&rest numbers)
"Gets the average of the numbers provided"
(if
(null numbers)
1 ; prevents divide by 0
(/ (apply #'+ numbers) (length numbers)))) ;/
(defun get-triangle-centre (triangle)
"Gets the centre of a triangle"
(avg (triangle-a triangle)
(triangle-b triangle)
(triangle-c triangle)))
(defstruct (triangle-list
(:include triangle))
point-list)
(defun triangle-split (triangle)
"Splits a triangle in two according to the rule:
{ a0->c1; b0->a1,c2; c0->a2; avg(c0,a0)->b1,b2 }"
(let* ((old-a-point (triangle-a triangle))
(old-b-point (triangle-b triangle))
(old-c-point (triangle-c triangle))
(new-b-point (avg old-a-point old-c-point)))
(list
(make-triangle-list :a old-b-point :b new-b-point :c old-a-point)
(make-triangle-list :a old-c-point :b new-b-point :c old-b-point))))
(defun triangle-list-split (triangle-list)
"Split a triangle list and acomodate all the points in their right places"
(let* ((triangles (triangle-split triangle-list))
(triangle-a (car triangles))
(triangle-b (cadr triangles))
(centre-a (get-triangle-centre triangle-a))
(centre-b (get-triangle-centre triangle-b)))
(dolist (point (triangle-list-point-list triangle-list))
(if (< (euclid point centre-a) (euclid point centre-b))
(setf (triangle-list-point-list triangle-a)
(cons point (triangle-list-point-list triangle-a)))
(setf (triangle-list-point-list triangle-b)
(cons point (triangle-list-point-list triangle-b)))))
(let ((list-a (triangle-list-point-list triangle-a))
(list-b (triangle-list-point-list triangle-b)))
(if (= 1 (length list-a))
(setf (triangle-list-point-list triangle-a) (car list-a)))
(if (= 1 (length list-b))
(setf (triangle-list-point-list triangle-b) (car list-b))))
(list triangle-a triangle-b)))
(defun print-point (out point &rest args)
"Utility function - Pretty-prints a point"
(format out "(X:~F, Y:~F)"
(realpart point)
(imagpart point))
args)
(defun pprint-triangle-list (out triangle-list &rest args)
"Utility function - Pretty-prints a triangle-list object"
(format out " TRIANGLE{
A:~/print-point/
B:~/print-point/
C:~/print-point/
CENTRE:~/print-point/
POINTS:{~{~/print-point/~^,~% ~}}~& }"
(triangle-a triangle-list)
(triangle-b triangle-list)
(triangle-c triangle-list)
(get-triangle-centre triangle-list)
(let ((points (triangle-list-point-list triangle-list)))
(cond
((null points) ())
((listp points) points)
(t (list points)))))
args)
(defun print-list-of-triangle-list (lst)
"Pretty-prints a list of triangle-list objects"
(format t "(~{~/pprint-triangle-list/~^,~% ~}~&)" lst))
(defun explode (lst)
"explodes a triangle-list list and gets all
the points in the order they should be"
(let ((l (flatten lst)))
(cond
((null l) ())
((triangle-list-p l) (explode (triangle-list-split l)))
((null (triangle-list-point-list (car l)))
(explode (cdr l)))
((atom (triangle-list-point-list (car l)))
(cons (car l) (explode (cdr l))))
(t (explode (append (triangle-list-split (car l)) (cdr l)))))))
(defun flatten (lst)
"Flattens a list (removes nesting and nulls)"
(cond
((atom lst) lst)
((listp (car lst))
(append (flatten (car lst)) (flatten (cdr lst))))
(t (append (list (car lst)) (flatten (cdr lst))))))
(let ((triangle (make-triangle-list
:a (complex 0 *search-area-heigth*)
:b 0
:c *search-area-width*
:point-list (make-random-point-list *max-number-of-points*))))
(print-list-of-triangle-list (explode triangle)))
```
I also had a version using a GA (that one in C), but it lives in a dead hard drive.
|
194,650 |
<p>Simply put, is there a way to create a 2D javascript array using similar syntax to this?</p>
<pre><code>var newArray = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
]
</code></pre>
|
[
{
"answer_id": 194660,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Yes. This works fine:</p>\n\n<pre><code><script>\nvar newArray = [\n [0, 1, 2],\n [3, 4, 5],\n [6, 7, 8]\n]\nalert(newArray[0][2]);\n</script>\n</code></pre>\n"
},
{
"answer_id": 194681,
"author": "dave",
"author_id": 27057,
"author_profile": "https://Stackoverflow.com/users/27057",
"pm_score": 2,
"selected": false,
"text": "<p>Tested and working in FF3, Opera 9, IE6, and Chrome.</p>\n"
},
{
"answer_id": 194961,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 5,
"selected": true,
"text": "<p>You can create any n-dimensional arrays using <em>exactly</em> the format you suggest as in the following sample:</p>\n\n<pre><code><script>\n var newArray = [\n [0, 1, 2],\n [3, 4, 5],\n [6, 7, 8]\n ]\n var newArray3d =\n [[[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8]],\n [[10, 11, 12],[13, 14, 15],[16, 17, 18]],\n [[20, 21, 22],[23, 24, 25],[26, 27, 28]]]\n alert(newArray[0]);\n alert(newArray[0][2]);\n alert(newArray3d[0]);\n alert(newArray3d[1][0]);\n alert(newArray3d[1][0][2]);\n</script>\n</code></pre>\n\n<p>The alert boxes return, in sequence:</p>\n\n<pre><code>0,1,2\n2\n0,1,2,3,4,5,6,7,8\n10,11,12\n12\n</code></pre>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
] |
Simply put, is there a way to create a 2D javascript array using similar syntax to this?
```
var newArray = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
]
```
|
You can create any n-dimensional arrays using *exactly* the format you suggest as in the following sample:
```
<script>
var newArray = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
]
var newArray3d =
[[[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8]],
[[10, 11, 12],[13, 14, 15],[16, 17, 18]],
[[20, 21, 22],[23, 24, 25],[26, 27, 28]]]
alert(newArray[0]);
alert(newArray[0][2]);
alert(newArray3d[0]);
alert(newArray3d[1][0]);
alert(newArray3d[1][0][2]);
</script>
```
The alert boxes return, in sequence:
```
0,1,2
2
0,1,2,3,4,5,6,7,8
10,11,12
12
```
|
194,652 |
<p>Is there any regular expression library written in T-SQL (no CLR, no extended <code>SP</code>, pure T-SQL) for SQL Server, and that should work with shared hosting?</p>
<p>Edit:</p>
<ul>
<li>Thanks, I know about <code>PATINDEX</code>, <code>LIKE</code>, <code>xp_</code> <code>sps</code> and CLR solutions</li>
<li>I also know it is not the best place for regex, the question is theoretical :)</li>
<li>Reduced functionality is also accepted</li>
</ul>
|
[
{
"answer_id": 194727,
"author": "Steven Murawski",
"author_id": 1233,
"author_profile": "https://Stackoverflow.com/users/1233",
"pm_score": 4,
"selected": false,
"text": "<p>There is some basic pattern matching available through using LIKE, where % matches any number and combination of characters, _ matches any one character, and [abc] could match a, b, or c...\nThere is more info on the <a href=\"http://msdn.microsoft.com/en-us/library/ms179859.aspx\" rel=\"noreferrer\">MSDN site</a>.</p>\n"
},
{
"answer_id": 198986,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 6,
"selected": false,
"text": "<p>How about the <a href=\"http://msdn.microsoft.com/en-us/library/ms188395.aspx\" rel=\"noreferrer\">PATINDEX</a> function?</p>\n\n<p>The pattern matching in TSQL is not a complete regex library, but it gives you the basics.</p>\n\n<p>(From Books Online)</p>\n\n<pre><code>Wildcard Meaning \n% Any string of zero or more characters.\n\n_ Any single character.\n\n[ ] Any single character within the specified range \n (for example, [a-f]) or set (for example, [abcdef]).\n\n[^] Any single character not within the specified range \n (for example, [^a - f]) or set (for example, [^abcdef]).\n</code></pre>\n"
},
{
"answer_id": 12903070,
"author": "James Poulose",
"author_id": 249097,
"author_profile": "https://Stackoverflow.com/users/249097",
"pm_score": 2,
"selected": false,
"text": "<p>You can use VBScript regular expression features using OLE Automation. This is way better than the overhead of creating and maintaining an assembly. Please make sure you go through the comments section to get a better modified version of the main one.</p>\n\n<p><a href=\"http://blogs.msdn.com/b/khen1234/archive/2005/05/11/416392.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/b/khen1234/archive/2005/05/11/416392.aspx</a></p>\n\n<pre><code>DECLARE @obj INT, @res INT, @match BIT;\nDECLARE @pattern varchar(255) = '<your regex pattern goes here>';\nDECLARE @matchstring varchar(8000) = '<string to search goes here>';\nSET @match = 0;\n\n-- Create a VB script component object\nEXEC @res = sp_OACreate 'VBScript.RegExp', @obj OUT;\n\n-- Apply/set the pattern to the RegEx object\nEXEC @res = sp_OASetProperty @obj, 'Pattern', @pattern;\n\n-- Set any other settings/properties here\nEXEC @res = sp_OASetProperty @obj, 'IgnoreCase', 1;\n\n-- Call the method 'Test' to find a match\nEXEC @res = sp_OAMethod @obj, 'Test', @match OUT, @matchstring;\n\n-- Don't forget to clean-up\nEXEC @res = sp_OADestroy @obj;\n</code></pre>\n\n<p>If you get <code>SQL Server blocked access to procedure 'sys.sp_OACreate'...</code> error, use <code>sp_reconfigure</code> to enable <code>Ole Automation Procedures</code>. (Yes, unfortunately that is a server level change!)</p>\n\n<p>More information about the <code>Test</code> method is available <a href=\"https://msdn.microsoft.com/en-us/library/ms974570.aspx?f=255&MSPPError=-2147217396\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>Happy coding</p>\n"
},
{
"answer_id": 30628145,
"author": "John Fisher",
"author_id": 50358,
"author_profile": "https://Stackoverflow.com/users/50358",
"pm_score": 3,
"selected": false,
"text": "<p>In case anyone else is still looking at this question, <a href=\"http://www.sqlsharp.com/\" rel=\"nofollow\">http://www.sqlsharp.com/</a> is a free, <em>easy way to add regular expression <strong>CLR functions</em></strong> into your database.</p>\n"
},
{
"answer_id": 30877281,
"author": "Matt Farguson",
"author_id": 4561434,
"author_profile": "https://Stackoverflow.com/users/4561434",
"pm_score": 4,
"selected": false,
"text": "<p>If anybody is interested in using regex with CLR here is a solution. The function below (C# .net 4.5) returns a 1 if the pattern is matched and a 0 if the pattern is not matched. I use it to tag lines in sub queries. The SQLfunction attribute tells sql server that this method is the actual UDF that SQL server will use. Save the file as a dll in a place where you can access it from management studio.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>// default using statements above\nusing System.Data.SqlClient;\nusing System.Data.SqlTypes;\nusing Microsoft.SqlServer.Server;\nusing System.Text.RegularExpressions;\n\nnamespace CLR_Functions\n{ \n public class myFunctions\n {\n [SqlFunction]\n public static SqlInt16 RegexContain(SqlString text, SqlString pattern)\n { \n SqlInt16 returnVal = 0;\n try\n {\n string myText = text.ToString();\n string myPattern = pattern.ToString();\n MatchCollection mc = Regex.Matches(myText, myPattern);\n if (mc.Count > 0)\n {\n returnVal = 1;\n }\n }\n catch\n {\n returnVal = 0;\n }\n\n return returnVal;\n }\n }\n}\n</code></pre>\n\n<p>In management studio import the dll file via programability -- assemblies -- new assembly</p>\n\n<p>Then run this query: </p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>CREATE FUNCTION RegexContain(@text NVARCHAR(50), @pattern NVARCHAR(50))\nRETURNS smallint \nAS\nEXTERNAL NAME CLR_Functions.[CLR_Functions.myFunctions].RegexContain\n</code></pre>\n\n<p>Then you should have complete access to the function via the database you stored the assembly in. </p>\n\n<p>Then use in queries like so: </p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT * \nFROM \n(\n SELECT\n DailyLog.Date,\n DailyLog.Researcher,\n DailyLog.team,\n DailyLog.field,\n DailyLog.EntityID,\n DailyLog.[From],\n DailyLog.[To],\n dbo.RegexContain(Researcher, '[\\p{L}\\s]+') as 'is null values'\n FROM [DailyOps].[dbo].[DailyLog]\n) AS a\nWHERE a.[is null values] = 0\n</code></pre>\n"
},
{
"answer_id": 46536661,
"author": "Dave Mason",
"author_id": 2961160,
"author_profile": "https://Stackoverflow.com/users/2961160",
"pm_score": 3,
"selected": false,
"text": "<p>If you are using SQL Server 2016 or above, you can use <code>sp_execute_external_script</code> along with R. It has functions for Regular Expression searches, such as <code>grep</code> and <code>grepl</code>. <br/></p>\n\n<p>Here's an example for email addresses. I'll query some \"people\" via the SQL Server database engine, pass the data for those people to R, let R decide which people have invalid email addresses, and have R pass back that subset of people to SQL Server. The \"people\" are from the <code>[Application].[People]</code> table in the <code>[WideWorldImporters]</code> sample database. They get passed to the R engine as a dataframe named <code>InputDataSet</code>. R uses the grepl function with the \"not\" operator (exclamation point!) to find which people have email addresses that don't match the RegEx string search pattern.</p>\n\n<pre><code>EXEC sp_execute_external_script \n @language = N'R',\n @script = N' RegexWithR <- InputDataSet;\nOutputDataSet <- RegexWithR[!grepl(\"([_a-z0-9-]+(\\\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\\\.[a-z0-9-]+)*(\\\\.[a-z]{2,4}))\", RegexWithR$EmailAddress), ];',\n @input_data_1 = N'SELECT PersonID, FullName, EmailAddress FROM Application.People'\n WITH RESULT SETS (([PersonID] INT, [FullName] NVARCHAR(50), [EmailAddress] NVARCHAR(256)))\n</code></pre>\n\n<p>Note that the appropriate features must be installed on the SQL Server host. For SQL Server 2016, it is called \"SQL Server R Services\". For SQL Server 2017, it was renamed to \"SQL Server Machine Learning Services\".</p>\n\n<p><strong>Closing Thoughts</strong>\nMicrosoft's implementation of SQL (T-SQL) doesn't have native support for RegEx. This proposed solution may not be any more desirable to the OP than the use of a CLR stored procedure. But it does offer an additional way to approach the problem.</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2622295/"
] |
Is there any regular expression library written in T-SQL (no CLR, no extended `SP`, pure T-SQL) for SQL Server, and that should work with shared hosting?
Edit:
* Thanks, I know about `PATINDEX`, `LIKE`, `xp_` `sps` and CLR solutions
* I also know it is not the best place for regex, the question is theoretical :)
* Reduced functionality is also accepted
|
How about the [PATINDEX](http://msdn.microsoft.com/en-us/library/ms188395.aspx) function?
The pattern matching in TSQL is not a complete regex library, but it gives you the basics.
(From Books Online)
```
Wildcard Meaning
% Any string of zero or more characters.
_ Any single character.
[ ] Any single character within the specified range
(for example, [a-f]) or set (for example, [abcdef]).
[^] Any single character not within the specified range
(for example, [^a - f]) or set (for example, [^abcdef]).
```
|
194,659 |
<p>This might be an odd question, but when I scale my image in C# I need it to be pixelated and not anti-aliased. Just like in MSpaint when you scale.</p>
<p>I hope images anti-alias by default in C#, or else I changed something I didn't want to.</p>
<p>I've tried playing around with the <code>Graphics.InterpolationMode</code> but no luck there. I'm using a Bitmap object to hold the image and it's being constructed like so:</p>
<pre><code>// A custom control holds the image
this.m_ZoomPanPicBox.Image = new Bitmap(szImagePath);
</code></pre>
<p>And a brief synapsis of the custom control:</p>
<pre><code>class ZoomPanPicBox : ScrollableControl
{
Image m_image;
float m_zoom = 1.0f;
InterpolationMode m_interpolationMode;
...
////////////////////////////////////////////////////////
public ZoomPanPicBox()
{
//Double buffer the control
this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true);
this.AutoScroll=true;
}
////////////////////////////////////////////////////////
protected override void OnPaint(PaintEventArgs e)
{
//if no image, don't bother
if(m_image==null)
{
base.OnPaintBackground(e);
return;
}
//Set up a zoom matrix
Matrix mx = new Matrix(m_zoom,0,0,m_zoom,0,0);
//now translate the matrix into position for the scrollbars
mx.Translate(this.AutoScrollPosition.X / m_zoom, this.AutoScrollPosition.Y / m_zoom);
//use the transform
e.Graphics.Transform = mx;
//and the desired interpolation mode
e.Graphics.InterpolationMode = m_interpolationMode;
//Draw the image ignoring the images resolution settings.
e.Graphics.DrawImage(m_image,new Rectangle(0,0,this.m_image.Width,this.m_image.Height),0,0,m_image.Width, m_image.Height,GraphicsUnit.Pixel);
base.OnPaint(e);
}
</code></pre>
<p>Any ideas? Thanks.</p>
|
[
{
"answer_id": 194662,
"author": "dicroce",
"author_id": 3886,
"author_profile": "https://Stackoverflow.com/users/3886",
"pm_score": 0,
"selected": false,
"text": "<p>Well, you could implement the scale yourself and do a simple linear interpolation (I.E. don't do any neighbor averaging like bicubic)... Those look nice and blocky.</p>\n"
},
{
"answer_id": 194675,
"author": "OregonGhost",
"author_id": 20363,
"author_profile": "https://Stackoverflow.com/users/20363",
"pm_score": 3,
"selected": true,
"text": "<p>Actually, you're right with InterpolationMode, as <a href=\"http://msdn.microsoft.com/en-us/library/k0fsyd4e.aspx\" rel=\"nofollow noreferrer\">the docs say</a>. Just set it to InterpolationMode.NearestNeighbor. In your code sample, you never set m_interpolationMode.</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13115/"
] |
This might be an odd question, but when I scale my image in C# I need it to be pixelated and not anti-aliased. Just like in MSpaint when you scale.
I hope images anti-alias by default in C#, or else I changed something I didn't want to.
I've tried playing around with the `Graphics.InterpolationMode` but no luck there. I'm using a Bitmap object to hold the image and it's being constructed like so:
```
// A custom control holds the image
this.m_ZoomPanPicBox.Image = new Bitmap(szImagePath);
```
And a brief synapsis of the custom control:
```
class ZoomPanPicBox : ScrollableControl
{
Image m_image;
float m_zoom = 1.0f;
InterpolationMode m_interpolationMode;
...
////////////////////////////////////////////////////////
public ZoomPanPicBox()
{
//Double buffer the control
this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true);
this.AutoScroll=true;
}
////////////////////////////////////////////////////////
protected override void OnPaint(PaintEventArgs e)
{
//if no image, don't bother
if(m_image==null)
{
base.OnPaintBackground(e);
return;
}
//Set up a zoom matrix
Matrix mx = new Matrix(m_zoom,0,0,m_zoom,0,0);
//now translate the matrix into position for the scrollbars
mx.Translate(this.AutoScrollPosition.X / m_zoom, this.AutoScrollPosition.Y / m_zoom);
//use the transform
e.Graphics.Transform = mx;
//and the desired interpolation mode
e.Graphics.InterpolationMode = m_interpolationMode;
//Draw the image ignoring the images resolution settings.
e.Graphics.DrawImage(m_image,new Rectangle(0,0,this.m_image.Width,this.m_image.Height),0,0,m_image.Width, m_image.Height,GraphicsUnit.Pixel);
base.OnPaint(e);
}
```
Any ideas? Thanks.
|
Actually, you're right with InterpolationMode, as [the docs say](http://msdn.microsoft.com/en-us/library/k0fsyd4e.aspx). Just set it to InterpolationMode.NearestNeighbor. In your code sample, you never set m\_interpolationMode.
|
194,663 |
<p>I'm new to Flex SDK and trying to implement a simple project using <a href="http://dougmccune.com/blog/2007/11/19/flex-coverflow-performance-improvement-flex-carousel-component-and-vertical-coverflow/" rel="nofollow noreferrer">Doug Mccune's CoverFlow</a> widget. Most of the documentation out there on how to do this assumes that one is using Adobe's FlexBuilder product, which is a $250 Eclipse plug-in that I'd rather avoid buying. The problem I'm having is simply getting Doug's swc file, which is the binary version of his component lib, to be recognized by mxmlc, the Flex SDK project compiler. I keep getting error messages such as</p>
<blockquote>
<p>Error: Could not resolve to a component installation</p>
</blockquote>
<p>and</p>
<blockquote>
<p>Error: Type was not found or was not a compile-time constant: CoverFlow.</p>
</blockquote>
<p>I have also tried the type "VideoCoverFlow" as I am pretty sure that these types are defined in Doug's lib. Alas, I am stuck on figuring out where I've gone wrong.</p>
<p>The following is the full text for my mxml project file, called coverflow.mxml.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:local="*"
height="100%"
width="100%"
layout="absolute">
<local:CoverFlow
id="CoverFlow"
horizontalCenter="0"
verticalCenter="0"
borderThickness="10"
borderColor="#FFFFFF"
width="100%"/>
</mx:Application>
</code></pre>
<p>I am trying to compile it with the following command:</p>
<pre><code>c:\flex_sdk_3\bin\mxmlc.exe -compiler.source-path=lib coverflow.mxml
</code></pre>
<p>I have also tried moving the CoverFlow_lib.swc file into the same dir as the mxml file instead of using the source-path argument, but that does not seem to make a difference.</p>
<p>I would gladly go RTFM if somebody could be so kind as to point me in the direction of the proper docs. There are related Stack Overflow questions <a href="https://stackoverflow.com/questions/78230/compiling-mxml-files-with-ant-and-flex-sdk">here</a> and <a href="https://stackoverflow.com/questions/119947/using-flash-component-swc-file-in-flex">here</a>.</p>
<p>Thank you!</p>
<hr>
<p><strong>Update</strong>: I have changed my build command to the following:</p>
<pre><code>mxmlc -library-path+=lib coverflow.mxml
</code></pre>
<p>And I also tried the following:</p>
<pre><code>mxmlc -library-path+=CoverFlow_lib.swc coverflow.mxml
</code></pre>
<p>With the swc file in the same dir as the mxml file. However, I'm still getting the same errors.</p>
<p>There's also a <a href="http://www.adobe.com/products/flex/media/flexapp/" rel="nofollow noreferrer">video here</a> showing the same library that I'm trying to use, but in Flex Builder. Unfortunately, it doesn't show how to use mxmlc.</p>
<p>I've also tried stripping down my mxml to simply,</p>
<pre><code><mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:local="*" >
<local:VideoCoverFlow />
</mx:Application>
</code></pre>
|
[
{
"answer_id": 194670,
"author": "Simon",
"author_id": 24039,
"author_profile": "https://Stackoverflow.com/users/24039",
"pm_score": 1,
"selected": false,
"text": "<p>If it is an swc shouldn't you be using library-path rather than source-path and referencing the swc?</p>\n"
},
{
"answer_id": 194682,
"author": "James Fassett",
"author_id": 27081,
"author_profile": "https://Stackoverflow.com/users/27081",
"pm_score": 4,
"selected": true,
"text": "<p>Here is a <a href=\"http://livedocs.adobe.com/flex/3/html/help.html?content=compilers_13.html\" rel=\"noreferrer\">link to the mxmlc command line tool docs from Adobe</a> and a <a href=\"http://livedocs.adobe.com/flex/3/html/help.html?content=compilers_14.html#157203\" rel=\"noreferrer\">direct link to the command line options reference.</a> I also find <code>mxmlc -help list</code> to be a good place to start.</p>\n\n<p>As another poster recommended, you really want to use <code>library-path</code> to add the path to the directory that contains the swc file. Use the += operator to make sure you don't overwrite the previous values</p>\n\n<p>e.g.)</p>\n\n<pre><code>c:\\flex_sdk_3\\bin\\mxmlc.exe -library-path+=lib coverflow.mxml\n</code></pre>\n"
},
{
"answer_id": 194716,
"author": "Parappa",
"author_id": 9974,
"author_profile": "https://Stackoverflow.com/users/9974",
"pm_score": 0,
"selected": false,
"text": "<p>I finally got my project to build. The use of library-path was part of the solution, but I also had to take a closer look at the Doug Mccune library's sources so I could use the correct path information and type names in my mxml.</p>\n\n<p>The winning command line is</p>\n\n<pre><code>mxmlc -library-path+=lib coverflow.mxml\n</code></pre>\n\n<p>And the working mxml is</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\"?>\n\n<mx:Application\n xmlns:mx=\"http://www.adobe.com/2006/mxml\"\n xmlns:coverflow=\"com.dougmccune.coverflow.*\"\n xmlns:containers=\"com.dougmccune.containers.*\"\n xmlns:local=\"*\" >\n\n <containers:CoverFlowContainer id=\"flow\" />\n\n</mx:Application\n</code></pre>\n\n<p>For some reason my container complains if I use <code>id=\"coverflow\"</code>. I get an error saying that the id name and the type name aren't allowed to be the same. If anyone can explain that to me, I'd love to understand what's going on there.</p>\n\n<p>Thanks again for the help, Simon and James.</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9974/"
] |
I'm new to Flex SDK and trying to implement a simple project using [Doug Mccune's CoverFlow](http://dougmccune.com/blog/2007/11/19/flex-coverflow-performance-improvement-flex-carousel-component-and-vertical-coverflow/) widget. Most of the documentation out there on how to do this assumes that one is using Adobe's FlexBuilder product, which is a $250 Eclipse plug-in that I'd rather avoid buying. The problem I'm having is simply getting Doug's swc file, which is the binary version of his component lib, to be recognized by mxmlc, the Flex SDK project compiler. I keep getting error messages such as
>
> Error: Could not resolve to a component installation
>
>
>
and
>
> Error: Type was not found or was not a compile-time constant: CoverFlow.
>
>
>
I have also tried the type "VideoCoverFlow" as I am pretty sure that these types are defined in Doug's lib. Alas, I am stuck on figuring out where I've gone wrong.
The following is the full text for my mxml project file, called coverflow.mxml.
```
<?xml version="1.0" encoding="utf-8"?>
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:local="*"
height="100%"
width="100%"
layout="absolute">
<local:CoverFlow
id="CoverFlow"
horizontalCenter="0"
verticalCenter="0"
borderThickness="10"
borderColor="#FFFFFF"
width="100%"/>
</mx:Application>
```
I am trying to compile it with the following command:
```
c:\flex_sdk_3\bin\mxmlc.exe -compiler.source-path=lib coverflow.mxml
```
I have also tried moving the CoverFlow\_lib.swc file into the same dir as the mxml file instead of using the source-path argument, but that does not seem to make a difference.
I would gladly go RTFM if somebody could be so kind as to point me in the direction of the proper docs. There are related Stack Overflow questions [here](https://stackoverflow.com/questions/78230/compiling-mxml-files-with-ant-and-flex-sdk) and [here](https://stackoverflow.com/questions/119947/using-flash-component-swc-file-in-flex).
Thank you!
---
**Update**: I have changed my build command to the following:
```
mxmlc -library-path+=lib coverflow.mxml
```
And I also tried the following:
```
mxmlc -library-path+=CoverFlow_lib.swc coverflow.mxml
```
With the swc file in the same dir as the mxml file. However, I'm still getting the same errors.
There's also a [video here](http://www.adobe.com/products/flex/media/flexapp/) showing the same library that I'm trying to use, but in Flex Builder. Unfortunately, it doesn't show how to use mxmlc.
I've also tried stripping down my mxml to simply,
```
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:local="*" >
<local:VideoCoverFlow />
</mx:Application>
```
|
Here is a [link to the mxmlc command line tool docs from Adobe](http://livedocs.adobe.com/flex/3/html/help.html?content=compilers_13.html) and a [direct link to the command line options reference.](http://livedocs.adobe.com/flex/3/html/help.html?content=compilers_14.html#157203) I also find `mxmlc -help list` to be a good place to start.
As another poster recommended, you really want to use `library-path` to add the path to the directory that contains the swc file. Use the += operator to make sure you don't overwrite the previous values
e.g.)
```
c:\flex_sdk_3\bin\mxmlc.exe -library-path+=lib coverflow.mxml
```
|
194,666 |
<p>Is there a way to suppress warnings in Xcode?</p>
<p>For example I am calling an undocumented method and since the method is not in the header I get a warning on compile. I know I can add it to my header to stop the warning, but I am wondering if there is a way other than adding it to the header (so I can keep the headers clean and standard) to suppress the warning? A pragma or something?</p>
|
[
{
"answer_id": 196781,
"author": "robottobor",
"author_id": 10184,
"author_profile": "https://Stackoverflow.com/users/10184",
"pm_score": 7,
"selected": false,
"text": "<p>To disable warnings on a per-file basis, using Xcode 3 and llvm-gcc-4.2 you can use:</p>\n\n<pre><code>#pragma GCC diagnostic ignored \"-Wwarning-flag\"\n</code></pre>\n\n<p>Where warning name is some gcc warning flag.</p>\n\n<p>This overrides any warning flags on the command line. It doesn't work with all warnings though. Add -fdiagnostics-show-option to your CFLAGS and you can see which flag you can use to disable that warning.</p>\n"
},
{
"answer_id": 203922,
"author": "Ken",
"author_id": 17320,
"author_profile": "https://Stackoverflow.com/users/17320",
"pm_score": 1,
"selected": false,
"text": "<p>Suppressing that particular warning is not safe. The compiler needs to know the types of the arguments and returns to a method to generate correct code. </p>\n\n<p>For example, if you're calling a method like this</p>\n\n<p>[foo doSomethingWithFloat:1.0];</p>\n\n<p>that takes a float, and there is no prototype visible, then the compiler will guess that the method takes a double, not a float. This can cause crashes and incorrectly interpreted values. In the example above, on a little endian machine like the intel machines, the receiver method would see 0 passed, not 1.</p>\n\n<p>You can read why in the <a href=\"http://developer.apple.com/documentation/DeveloperTools/Conceptual/LowLevelABI/Articles/IA32.html\" rel=\"nofollow noreferrer\">i386 ABI docs</a>, or you can just fix your warnings. :-)</p>\n"
},
{
"answer_id": 277244,
"author": "Matt Gallagher",
"author_id": 36103,
"author_profile": "https://Stackoverflow.com/users/36103",
"pm_score": 3,
"selected": false,
"text": "<p>With Objective-C, a number of serious errors only appear as warnings. Not only do I <em>never</em> disable warnings, I normally turn on \"Treat warnings as errors\" (-Werror).</p>\n\n<p>Every type of warning in your code can be avoided by doing things correctly (normally by casting objects to the correct type) or by declaring prototypes when you need them.</p>\n"
},
{
"answer_id": 1480048,
"author": "Mark Pauley",
"author_id": 146757,
"author_profile": "https://Stackoverflow.com/users/146757",
"pm_score": 3,
"selected": false,
"text": "<p>To get rid of the warning: try creating a category interface for the object in question</p>\n\n<p></p>\n\n<pre><code>@interface NSTheClass (MyUndocumentedMethodsForNSTheClass)\n\n-(id)theUndocumentedMethod;\n@end\n...\n\n@implementation myClass : mySuperclass\n\n-(void) myMethod {\n...\n [theObject theUndocumentedMethod];\n...\n}\n</code></pre>\n\n<p>As an aside, I <em>strongly</em> advise against calling undocumented methods in shipping code. The interface can and will change, and it will be your fault.</p>\n"
},
{
"answer_id": 3031426,
"author": "Mark A. Donohoe",
"author_id": 168179,
"author_profile": "https://Stackoverflow.com/users/168179",
"pm_score": 2,
"selected": false,
"text": "<p>Create a new, separate header file called 'Undocumented.h' and add it to your project. Then create one interface block for each class you want to call undocumented functions on and give each a category of '(Undocumented)'. Then just include that one header file in your PCH. This way your original header files remain clean, there's only one other file to maintain, and you can comment out one line in your PCH to re-enable all the warnings again.</p>\n\n<p>I also use this method for depreciated functions in 'Depreciated.h' with a category of '(Depreciated)'.</p>\n\n<p>the best part is you can selectively enable/disable individual warnings by commenting or uncommenting the individual prototypes.</p>\n"
},
{
"answer_id": 3964670,
"author": "AndersK",
"author_id": 45685,
"author_profile": "https://Stackoverflow.com/users/45685",
"pm_score": 5,
"selected": false,
"text": "<p>In order to surpress a warning for an individual file do the following:</p>\n\n<p>select the file in the xcode project.\npress get info\ngo to the page with build options\nenter -Wno- to negate a warning:</p>\n\n<blockquote>\n <p>-Wno-</p>\n</blockquote>\n\n<p>e.g.</p>\n\n<blockquote>\n <p>-Wno-unused-parameter</p>\n</blockquote>\n\n<p>You can get the name of the warning if you look on the project settings look at the GCC warnings located at the bottom of the build tab page, by clicking on each warning it will tell you the warning parameter name:</p>\n\n<p>e.g.</p>\n\n<blockquote>\n <p>Warn whenever a function parameter is\n unused aside from its declaration. \n [GCC_WARN_UNUSED_PARAMETER,\n -Wunused-parameter]</p>\n</blockquote>\n"
},
{
"answer_id": 7992423,
"author": "thesummersign",
"author_id": 751026,
"author_profile": "https://Stackoverflow.com/users/751026",
"pm_score": 6,
"selected": false,
"text": "<p>there is a simpler way to suppress <strong>Unused variable</strong> warnings:</p>\n\n<pre><code>#pragma unused(varname)\n</code></pre>\n\n<p>EDIT:\nsource: <a href=\"http://www.cocoadev.com/index.pl?XCodePragmas\" rel=\"noreferrer\">http://www.cocoadev.com/index.pl?XCodePragmas</a></p>\n\n<p>UPDATE:\nI came accross with a new solution, a more robust one</p>\n\n<ol>\n<li>Open the Project > Edit Active Target> Build tab.</li>\n<li>Under <code>User-Defined</code>: find (or create if you don't find one )the key : <code>GCC_WARN_UNUSED_VARIABLE</code> set it to <code>NO</code>.</li>\n</ol>\n\n<p>EDIT-2\nExample: </p>\n\n<pre><code>BOOL ok = YES;\nNSAssert1(ok, @\"Failed to calculate the first day the month based on %@\", self);\n</code></pre>\n\n<p>the compiler shows unused variable warning for <code>ok</code>.</p>\n\n<p>Solution:</p>\n\n<pre><code>BOOL ok = YES;\n#pragma unused(ok)\nNSAssert1(ok, @\"Failed to calculate the first day the month based on %@\", self);\n</code></pre>\n\n<p>PS: \nYou can also set/reset other warning:\n<code>GCC_WARN_ABOUT_RETURN_TYPE</code> : <code>YES/NO</code></p>\n"
},
{
"answer_id": 17493038,
"author": "Austin France",
"author_id": 644634,
"author_profile": "https://Stackoverflow.com/users/644634",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://nshipster.com/pragma/#inhibiting-warnings\" rel=\"nofollow\">http://nshipster.com/pragma/#inhibiting-warnings</a> - skip to inhibiting warnings section</p>\n"
},
{
"answer_id": 25700438,
"author": "Inder Kumar Rathore",
"author_id": 468724,
"author_profile": "https://Stackoverflow.com/users/468724",
"pm_score": 5,
"selected": false,
"text": "<h2>For gcc you can use</h2>\n<pre><code>#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored "-Wshadow-ivar"\n// your code\n#pragma GCC diagnostic pop\n</code></pre>\n<p>You can learn about <a href=\"http://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html\" rel=\"noreferrer\">GCC pragma here</a> and to get the warning code of a warning go to the Report Navigator (Command+9), select the topmost build, expand the log (the '=' button on the right), and scroll to the bottom and there your warning code is within square brackets like this <code>[-Wshadow-ivar]</code></p>\n<h2>For clang you can use</h2>\n<pre><code>#pragma clang diagnostic push\n#pragma clang diagnostic ignored "-Wshadow-ivar"\n// your code\n#pragma clang diagnostic pop\n</code></pre>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26728/"
] |
Is there a way to suppress warnings in Xcode?
For example I am calling an undocumented method and since the method is not in the header I get a warning on compile. I know I can add it to my header to stop the warning, but I am wondering if there is a way other than adding it to the header (so I can keep the headers clean and standard) to suppress the warning? A pragma or something?
|
To disable warnings on a per-file basis, using Xcode 3 and llvm-gcc-4.2 you can use:
```
#pragma GCC diagnostic ignored "-Wwarning-flag"
```
Where warning name is some gcc warning flag.
This overrides any warning flags on the command line. It doesn't work with all warnings though. Add -fdiagnostics-show-option to your CFLAGS and you can see which flag you can use to disable that warning.
|
194,698 |
<p>I was asked to build a java system that will have the ability to load new code (expansions) while running.
How do I re-load a jar file while my code is running? or how do I load a new jar?</p>
<p>Obviously, since constant up-time is important, I'd like to add the ability to re-load existing classes while at it (if it does not complicate things too much).</p>
<p>What are the things I should look out for?
(think of it as two different questions - one regarding reloading classes at runtime, the other regarding adding new classes).</p>
|
[
{
"answer_id": 194708,
"author": "Amir Arad",
"author_id": 11813,
"author_profile": "https://Stackoverflow.com/users/11813",
"pm_score": 2,
"selected": false,
"text": "<p>I googled a bit, and found this code <a href=\"https://community.oracle.com/message/5531305#5531305\" rel=\"nofollow noreferrer\">here</a>:</p>\n\n<pre><code>File file = getJarFileToLoadFrom(); \nString lcStr = getNameOfClassToLoad(); \nURL jarfile = new URL(\"jar\", \"\",\"file:\" + file.getAbsolutePath()+\"!/\"); \nURLClassLoader cl = URLClassLoader.newInstance(new URL[] {jarfile }); \nClass loadedClass = cl.loadClass(lcStr); \n</code></pre>\n\n<p>Can anyone share opinions/comments/answers regarding this approach?</p>\n"
},
{
"answer_id": 194712,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 7,
"selected": true,
"text": "<p>Reloading existing classes with existing data is likely to break things.</p>\n\n<p>You can load new code into new class loaders relatively easily:</p>\n\n<pre><code>ClassLoader loader = URLClassLoader.newInstance(\n new URL[] { yourURL },\n getClass().getClassLoader()\n);\nClass<?> clazz = Class.forName(\"mypackage.MyClass\", true, loader);\nClass<? extends Runnable> runClass = clazz.asSubclass(Runnable.class);\n// Avoid Class.newInstance, for it is evil.\nConstructor<? extends Runnable> ctor = runClass.getConstructor();\nRunnable doRun = ctor.newInstance();\ndoRun.run();\n</code></pre>\n\n<p>Class loaders no longer used can be garbage collected (unless there is a memory leak, as is often the case with using ThreadLocal, JDBC drivers, <code>java.beans</code>, etc).</p>\n\n<p>If you want to keep the object data, then I suggest a persistence mechanism such as Serialisation, or whatever you are used to.</p>\n\n<p>Of course debugging systems can do fancier things, but are more hacky and less reliable.</p>\n\n<p>It is possible to add new classes into a class loader. For instance, using <code>URLClassLoader.addURL</code>. However, if a class fails to load (because, say, you haven't added it), then it will never load in that class loader instance.</p>\n"
},
{
"answer_id": 432737,
"author": "Thilo",
"author_id": 14955,
"author_profile": "https://Stackoverflow.com/users/14955",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>I was asked to build a java system that will have the ability to load new code while running</p>\n</blockquote>\n\n<p>You might want to base your system on <a href=\"http://www.osgi.org/Main/HomePage\" rel=\"nofollow noreferrer\">OSGi</a> (or at least take a lot at it), which was made for exactly this situation.</p>\n\n<p>Messing with classloaders is really tricky business, mostly because of how class visibility works, and you do not want to run into hard-to-debug problems later on. For example, <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html\" rel=\"nofollow noreferrer\">Class.forName()</a>, which is widely used in many libraries does not work too well on a fragmented classloader space.</p>\n"
},
{
"answer_id": 673414,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>This works for me:</p>\n\n<pre><code>File file = new File(\"c:\\\\myjar.jar\");\n\nURL url = file.toURL(); \nURL[] urls = new URL[]{url};\n\nClassLoader cl = new URLClassLoader(urls);\nClass cls = cl.loadClass(\"com.mypackage.myclass\");\n</code></pre>\n"
},
{
"answer_id": 10715076,
"author": "Doan Huynh",
"author_id": 1411937,
"author_profile": "https://Stackoverflow.com/users/1411937",
"pm_score": 2,
"selected": false,
"text": "<p>Use org.openide.util.Lookup and ClassLoader to dynamically load the Jar plugin, as shown here.</p>\n\n<pre><code>public LoadEngine() {\n Lookup ocrengineLookup;\n Collection<OCREngine> ocrengines;\n Template ocrengineTemplate;\n Result ocrengineResults;\n try {\n //ocrengineLookup = Lookup.getDefault(); this only load OCREngine in classpath of application\n ocrengineLookup = Lookups.metaInfServices(getClassLoaderForExtraModule());//this load the OCREngine in the extra module as well\n ocrengineTemplate = new Template(OCREngine.class);\n ocrengineResults = ocrengineLookup.lookup(ocrengineTemplate); \n ocrengines = ocrengineResults.allInstances();//all OCREngines must implement the defined interface in OCREngine. Reference to guideline of implement org.openide.util.Lookup for more information\n\n } catch (Exception ex) {\n }\n}\n\npublic ClassLoader getClassLoaderForExtraModule() throws IOException {\n\n List<URL> urls = new ArrayList<URL>(5);\n //foreach( filepath: external file *.JAR) with each external file *.JAR, do as follows\n File jar = new File(filepath);\n JarFile jf = new JarFile(jar);\n urls.add(jar.toURI().toURL());\n Manifest mf = jf.getManifest(); // If the jar has a class-path in it's manifest add it's entries\n if (mf\n != null) {\n String cp =\n mf.getMainAttributes().getValue(\"class-path\");\n if (cp\n != null) {\n for (String cpe : cp.split(\"\\\\s+\")) {\n File lib =\n new File(jar.getParentFile(), cpe);\n urls.add(lib.toURI().toURL());\n }\n }\n }\n ClassLoader cl = ClassLoader.getSystemClassLoader();\n if (urls.size() > 0) {\n cl = new URLClassLoader(urls.toArray(new URL[urls.size()]), ClassLoader.getSystemClassLoader());\n }\n return cl;\n}\n</code></pre>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11813/"
] |
I was asked to build a java system that will have the ability to load new code (expansions) while running.
How do I re-load a jar file while my code is running? or how do I load a new jar?
Obviously, since constant up-time is important, I'd like to add the ability to re-load existing classes while at it (if it does not complicate things too much).
What are the things I should look out for?
(think of it as two different questions - one regarding reloading classes at runtime, the other regarding adding new classes).
|
Reloading existing classes with existing data is likely to break things.
You can load new code into new class loaders relatively easily:
```
ClassLoader loader = URLClassLoader.newInstance(
new URL[] { yourURL },
getClass().getClassLoader()
);
Class<?> clazz = Class.forName("mypackage.MyClass", true, loader);
Class<? extends Runnable> runClass = clazz.asSubclass(Runnable.class);
// Avoid Class.newInstance, for it is evil.
Constructor<? extends Runnable> ctor = runClass.getConstructor();
Runnable doRun = ctor.newInstance();
doRun.run();
```
Class loaders no longer used can be garbage collected (unless there is a memory leak, as is often the case with using ThreadLocal, JDBC drivers, `java.beans`, etc).
If you want to keep the object data, then I suggest a persistence mechanism such as Serialisation, or whatever you are used to.
Of course debugging systems can do fancier things, but are more hacky and less reliable.
It is possible to add new classes into a class loader. For instance, using `URLClassLoader.addURL`. However, if a class fails to load (because, say, you haven't added it), then it will never load in that class loader instance.
|
194,725 |
<p>I am a heavy command line user and use the <code>find</code> command extensively in my build system scripts. However on Mac OS X when I am not concentrating I often get output like this:</p>
<pre><code>$ find -name \*.plist
find: illegal option -- n
find: illegal option -- a
find: illegal option -- m
find: illegal option -- e
find: *.plist: No such file or directory
</code></pre>
<p>Basically, I forgot to add the little dot:</p>
<pre><code>$ find . -name \*.plist
</code></pre>
<p>Because BSD <code>find</code> requires the path and GNU <code>find</code> doesn't (it assumes the current directory if you don't specify one). I use Linux, Mac OS X and Cygwin often all at the same time, so it's of great benefit to me to have all my tools behave the same. I tried writing a bash <code>find</code> function that added "./" if I forgot, but I failed. Thanks for your help. :)</p>
|
[
{
"answer_id": 194732,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 2,
"selected": false,
"text": "<pre><code>find ./ -name \"*.plist\"\n</code></pre>\n\n<p><strong>edit</strong>: hmm, i may have misunderstood the question! if you were crazy, how about emulating it via a shell script? i routinely keep random utility scripts in ~/.bin, and that's the first thing in my PATH. if you had a similar setup perhaps you could do something like: (untested!)</p>\n\n<pre><code>#!/bin/sh\n# remapping find!\nCMD=`echo $1 | cut -c 1`\nif [ $CMD = '-' ]\nthen\n# pwd search\n /usr/bin/find ./ $*\nelse\n# regular find\n /usr/bin/find $*\nfi\n</code></pre>\n"
},
{
"answer_id": 194737,
"author": "James Fassett",
"author_id": 27081,
"author_profile": "https://Stackoverflow.com/users/27081",
"pm_score": 1,
"selected": false,
"text": "<p>This is probably not what you want but how about: <code>alias find=\"find .\"</code></p>\n\n<p>or choose a new name (<code>findl</code> for find local?)</p>\n"
},
{
"answer_id": 194738,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>I would suggest that if you're writing scripts (which are more likely to be migrated from one system to another sometime in the future) that you should try to use the more specific form of the command, that is specifying the \".\" instead of relying on a default. For the same reason, I might even suggest writing <code>sh</code> scripts instead of relying on <code>bash</code> which might not be installed everywhere.</p>\n"
},
{
"answer_id": 194756,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 3,
"selected": false,
"text": "<p>If you must call it 'find', then you want:</p>\n\n<pre><code>alias find=/usr/bin/find\\ .\n</code></pre>\n\n<p>in your .profile or .bash_profile or …. Substitute the real path (if not /usr/bin/find) on your Mac OSX. Enter the full path to avoid cycles (bash normally would interpret <code>alias find=find</code> without issues, but better be sure).</p>\n\n<p>But you better not name the alias <code>find</code> (findl, myfind etc), because it will become a habit and trouble for you if you try it on another system.</p>\n"
},
{
"answer_id": 194883,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 5,
"selected": true,
"text": "<p>If you can't discipline yourself to use <code>find</code> 'correctly', then why not install GNU <code>find</code> (from <code>findutils</code>) in a directory on your PATH ahead of the system <code>find</code> command.</p>\n\n<p>I used to have my own private variant of <code>cp</code> that would copy files to the current directory if the last item in the list was not a directory. I kept that in my personal <code>bin</code> directory for many years - but eventually removed it because I no longer used the functionality. (My 'cp.sh' was written in 1987 and edited twice, in 1990 and 1997, as part of changes to version control system notations. I think I removed it around 1998. The primary problem with the script is that <code>cp file1 file2</code> is ambiguous between copying a file over another and copying two files to the current directory.)</p>\n\n<p>Consider writing your own wrapper to <code>find</code>:</p>\n\n<pre><code>#!/bin/sh\n[ ! -d \"$1\" ] && set -- . \"$@\"\nexec /usr/bin/find \"$@\"\n</code></pre>\n\n<p>The second line says \"if argument 1 is not a directory, then adjust the command line arguments to include dot ahead of the rest of the command. That will be confusing if you ever type:</p>\n\n<pre><code>~/bin/find /non-existent/directory -name '*.plist' -print\n</code></pre>\n\n<p>because the non-existent directory isn't a directory and the script will add dot to the command line -- the sort of reason that I stopped using my private <code>cp</code> command.</p>\n"
},
{
"answer_id": 15003450,
"author": "odinho - Velmont",
"author_id": 179978,
"author_profile": "https://Stackoverflow.com/users/179978",
"pm_score": 5,
"selected": false,
"text": "<p>Install GNU find instead.</p>\n\n<pre><code>$ brew install findutils\n$ alias find=gfind\n</code></pre>\n\n<p>Yay, it works!</p>\n"
},
{
"answer_id": 32616689,
"author": "Pysis",
"author_id": 1091943,
"author_profile": "https://Stackoverflow.com/users/1091943",
"pm_score": 1,
"selected": false,
"text": "<p>You may want to run the commands found in this link: <a href=\"https://www.topbug.net/blog/2013/04/14/install-and-use-gnu-command-line-tools-in-mac-os-x/\" rel=\"nofollow noreferrer\">https://www.topbug.net/blog/2013/04/14/install-and-use-gnu-command-line-tools-in-mac-os-x/</a></p>\n\n<p>It is a bit outdated, for example I found I did not have to add many commands to my path at all.</p>\n\n<p>This covers your problem by having your system use the Non-BSD find utility from the <code>findutils</code> package, while also installing other tools you may want as well.</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6444/"
] |
I am a heavy command line user and use the `find` command extensively in my build system scripts. However on Mac OS X when I am not concentrating I often get output like this:
```
$ find -name \*.plist
find: illegal option -- n
find: illegal option -- a
find: illegal option -- m
find: illegal option -- e
find: *.plist: No such file or directory
```
Basically, I forgot to add the little dot:
```
$ find . -name \*.plist
```
Because BSD `find` requires the path and GNU `find` doesn't (it assumes the current directory if you don't specify one). I use Linux, Mac OS X and Cygwin often all at the same time, so it's of great benefit to me to have all my tools behave the same. I tried writing a bash `find` function that added "./" if I forgot, but I failed. Thanks for your help. :)
|
If you can't discipline yourself to use `find` 'correctly', then why not install GNU `find` (from `findutils`) in a directory on your PATH ahead of the system `find` command.
I used to have my own private variant of `cp` that would copy files to the current directory if the last item in the list was not a directory. I kept that in my personal `bin` directory for many years - but eventually removed it because I no longer used the functionality. (My 'cp.sh' was written in 1987 and edited twice, in 1990 and 1997, as part of changes to version control system notations. I think I removed it around 1998. The primary problem with the script is that `cp file1 file2` is ambiguous between copying a file over another and copying two files to the current directory.)
Consider writing your own wrapper to `find`:
```
#!/bin/sh
[ ! -d "$1" ] && set -- . "$@"
exec /usr/bin/find "$@"
```
The second line says "if argument 1 is not a directory, then adjust the command line arguments to include dot ahead of the rest of the command. That will be confusing if you ever type:
```
~/bin/find /non-existent/directory -name '*.plist' -print
```
because the non-existent directory isn't a directory and the script will add dot to the command line -- the sort of reason that I stopped using my private `cp` command.
|
194,733 |
<p>If I have a method such as:</p>
<pre><code>private function testMethod(param:string):void
{
// Get the object that called this function
}
</code></pre>
<p>Inside the testMethod, can I work out what object called us? e.g.</p>
<pre><code>class A
{
doSomething()
{
var b:B = new B();
b.fooBar();
}
}
class B
{
fooBar()
{
// Can I tell that the calling object is type of class A?
}
}
</code></pre>
|
[
{
"answer_id": 194745,
"author": "James Fassett",
"author_id": 27081,
"author_profile": "https://Stackoverflow.com/users/27081",
"pm_score": 4,
"selected": true,
"text": "<p>Sorry the answer is no (see edit below). Functions received a special property called <code>arguments</code> and in AS2 it used to have the property <code>caller</code> that would do roughly what you want. Although the arguments object is still available in AS3 the caller property was removed from AS3 (and therefore Flex 3) so there is no direct way you can do what you want. It is also recommeded that you use the [...rest parameter](<a href=\"http://livedocs.adobe.com/flex/3/langref/statements.html#..._(rest)_parameter)\" rel=\"noreferrer\">http://livedocs.adobe.com/flex/3/langref/statements.html#..._(rest)_parameter)</a> language feature instead of <a href=\"http://livedocs.adobe.com/flex/3/langref/arguments.html\" rel=\"noreferrer\">arguments</a>.</p>\n\n<p>Here is a <a href=\"http://www.senocular.com/flash/tutorials/as3withflashcs3/\" rel=\"noreferrer\">reference on the matter</a> (search for callee to find the relevant details).</p>\n\n<p><strong>Edit:</strong> Further investigation has shown that it is possible to get a stack trace for the current executing function so if you are lucky you can do something with that. See <a href=\"http://blog.joa-ebert.com/2006/12/12/looking-up-the-calling-function/\" rel=\"noreferrer\">this blog entry</a> and <a href=\"http://tech.groups.yahoo.com/group/flexcoders/message/58388\" rel=\"noreferrer\">this forum post</a> for more details.</p>\n\n<p>The basic idea from the blog post is you throw an Error and then catch it immediately and then parse the stack trace. Ugly, but it may work for you.</p>\n\n<p>code from the blog post:</p>\n\n<pre><code>\nvar stackTrace:String;\n\ntry { throw new Error(); }\ncatch (e:Error) { stackTrace = e.getStackTrace(); }\n\nvar lines:Array = stackTrace.split(\"\\n\");\nvar isDebug:Boolean = (lines[1] as String).indexOf('[') != -1;\n\nvar path:String;\nvar line:int = -1;\n\nif(isDebug)\n{\n var regex:RegExp = /at\\x20(.+?)\\[(.+?)\\]/i;\n var matches:Array = regex.exec(lines[2]);\n\n path = matches[1];\n\n //file:line = matches[2]\n //windows == 2 because of drive:\\\n line = matches[2].split(':')[2];\n}\nelse\n{\n path = (lines[2] as String).substring(4);\n}\n\ntrace(path + (line != -1 ? '[' + line.toString() + ']' : ''));\n</code></pre>\n"
},
{
"answer_id": 194888,
"author": "aib",
"author_id": 1088,
"author_profile": "https://Stackoverflow.com/users/1088",
"pm_score": 1,
"selected": false,
"text": "<p>I'd second the idea of explicitly passing a \"callingObject\" parameter. Unless you're doing really tricky stuff, it should be better for the caller to be able to supply the target object, anyway. (Sorry if this seems obvious, I can't tell what you're trying to accomplish.)</p>\n"
},
{
"answer_id": 195191,
"author": "Christophe Herreman",
"author_id": 17255,
"author_profile": "https://Stackoverflow.com/users/17255",
"pm_score": 1,
"selected": false,
"text": "<p>To add to the somewhat ambiguous first paragraph of James: the arguments property is still available inside a Function object, but the caller property has been removed.</p>\n\n<p>Here's a link to the docs: <a href=\"http://livedocs.adobe.com/flex/3/langref/arguments.html\" rel=\"nofollow noreferrer\">http://livedocs.adobe.com/flex/3/langref/arguments.html</a></p>\n"
},
{
"answer_id": 485509,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Is important to know that stackTrace is only available on the debugger version of Flash Player. Sorry! :(</p>\n"
},
{
"answer_id": 958720,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>This might help someone, I'm not sure... but if one is using an <code>Event</code> this is possible using the <code>e.currentTarget</code> as follows:</p>\n\n<pre><code>private function button_hover(e:Event):void\n{\n e.currentTarget.label=\"Hovering\";\n}\n</code></pre>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/986/"
] |
If I have a method such as:
```
private function testMethod(param:string):void
{
// Get the object that called this function
}
```
Inside the testMethod, can I work out what object called us? e.g.
```
class A
{
doSomething()
{
var b:B = new B();
b.fooBar();
}
}
class B
{
fooBar()
{
// Can I tell that the calling object is type of class A?
}
}
```
|
Sorry the answer is no (see edit below). Functions received a special property called `arguments` and in AS2 it used to have the property `caller` that would do roughly what you want. Although the arguments object is still available in AS3 the caller property was removed from AS3 (and therefore Flex 3) so there is no direct way you can do what you want. It is also recommeded that you use the [...rest parameter](<http://livedocs.adobe.com/flex/3/langref/statements.html#..._(rest)_parameter)> language feature instead of [arguments](http://livedocs.adobe.com/flex/3/langref/arguments.html).
Here is a [reference on the matter](http://www.senocular.com/flash/tutorials/as3withflashcs3/) (search for callee to find the relevant details).
**Edit:** Further investigation has shown that it is possible to get a stack trace for the current executing function so if you are lucky you can do something with that. See [this blog entry](http://blog.joa-ebert.com/2006/12/12/looking-up-the-calling-function/) and [this forum post](http://tech.groups.yahoo.com/group/flexcoders/message/58388) for more details.
The basic idea from the blog post is you throw an Error and then catch it immediately and then parse the stack trace. Ugly, but it may work for you.
code from the blog post:
```
var stackTrace:String;
try { throw new Error(); }
catch (e:Error) { stackTrace = e.getStackTrace(); }
var lines:Array = stackTrace.split("\n");
var isDebug:Boolean = (lines[1] as String).indexOf('[') != -1;
var path:String;
var line:int = -1;
if(isDebug)
{
var regex:RegExp = /at\x20(.+?)\[(.+?)\]/i;
var matches:Array = regex.exec(lines[2]);
path = matches[1];
//file:line = matches[2]
//windows == 2 because of drive:\
line = matches[2].split(':')[2];
}
else
{
path = (lines[2] as String).substring(4);
}
trace(path + (line != -1 ? '[' + line.toString() + ']' : ''));
```
|
194,742 |
<p>What is the best way to determine whether there is an available Internet connection for a WinForms app. (Programatically of course) I want to disable/hide certain functions if the user is not connected to the Internet.</p>
|
[
{
"answer_id": 194747,
"author": "QAZ",
"author_id": 14260,
"author_profile": "https://Stackoverflow.com/users/14260",
"pm_score": 3,
"selected": false,
"text": "<p>I'm not a c# developer but in C++ you can use the Win32 API (specifically from Wininet.dll) like this:</p>\n\n<pre><code>bool IsInternetConnected( void )\n{\n DWORD dwConnectionFlags = 0;\n\n if( !InternetGetConnectedState( &dwConnectionFlags, 0 ) )\n return false;\n\n if( InternetAttemptConnect( 0 ) != ERROR_SUCCESS )\n return false;\n\n return true;\n}\n</code></pre>\n\n<p>I assume this is trivially turned into c#</p>\n"
},
{
"answer_id": 194782,
"author": "Barry Kelly",
"author_id": 3712,
"author_profile": "https://Stackoverflow.com/users/3712",
"pm_score": 1,
"selected": false,
"text": "<p>A guess at Internet connectivity would be network availability, at <code>NetworkInterface.GetIsNetworkAvailable()</code>. The events on <code>NetworkChange</code> can tell you when it changes. Both classes are in the <code>System.Net.NetworkInformation</code> namespace.</p>\n\n<p>Of course, you won't know if the Internet is really available until you try to connect to something.</p>\n"
},
{
"answer_id": 194789,
"author": "sbeskur",
"author_id": 10446,
"author_profile": "https://Stackoverflow.com/users/10446",
"pm_score": 5,
"selected": true,
"text": "<p>The following will determine if you are connected to a network, however, that doesn't necessarily mean that you are connected to the Internet:</p>\n\n<pre><code>NetworkInterface.GetIsNetworkAvailable() \n</code></pre>\n\n<p>Here is a C# translation of Steve's code that seems to be pretty good:</p>\n\n<pre><code>private static int ERROR_SUCCESS = 0;\npublic static bool IsInternetConnected() {\n long dwConnectionFlags = 0;\n if (!InternetGetConnectedState(dwConnectionFlags, 0))\n return false;\n\n if(InternetAttemptConnect(0) != ERROR_SUCCESS)\n return false;\n\n return true;\n}\n\n\n [DllImport(\"wininet.dll\", SetLastError=true)]\n public static extern int InternetAttemptConnect(uint res);\n\n\n [DllImport(\"wininet.dll\", SetLastError=true)]\n public static extern bool InternetGetConnectedState(out int flags,int reserved); \n</code></pre>\n"
},
{
"answer_id": 194799,
"author": "Stuart Helwig",
"author_id": 5019,
"author_profile": "https://Stackoverflow.com/users/5019",
"pm_score": 2,
"selected": false,
"text": "<p>I found this code elsewhere, but really want to know if there is a better way.</p>\n\n<pre><code>HttpWebRequest req;\nHttpWebResponse resp;\ntry\n{\n req = (HttpWebRequest)WebRequest.Create(\"http://www.google.com\");\n resp = (HttpWebResponse)req.GetResponse();\n\n if(resp.StatusCode.ToString().Equals(\"OK\"))\n {\n Console.WriteLine(\"its connected.\");\n }\n else\n {\n Console.WriteLine(\"its not connected.\");\n }\n}\ncatch(Exception exc)\n{\n Console.WriteLine(\"its not connected.\");\n}\n</code></pre>\n\n<p>I like the idea of being able to monitor if the connection is lost via the NetworkChange event thrown by NetworkInterface. My app is for use by inexperienced users, on notebooks, where Internet connectivity is erratic (often in the Australian Outback).</p>\n"
},
{
"answer_id": 194800,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.csharphelp.com/archives3/archive499.html\" rel=\"nofollow noreferrer\">http://www.csharphelp.com/archives3/archive499.html</a></p>\n\n<p>Also, scroll past the experts-exchange links at: <a href=\"http://www.csharpfriends.com/Forums/ShowPost.aspx?PostID=13045\" rel=\"nofollow noreferrer\">http://www.csharpfriends.com/Forums/ShowPost.aspx?PostID=13045</a>, and you'll see some suggestions.</p>\n\n<p>Also, if you are game for the My namespace from VB.Net (which you can link to, btw), My.Computer.Network.IsAvailable is the simplest solution. </p>\n"
},
{
"answer_id": 194997,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 3,
"selected": false,
"text": "<p>sbeskur's response has a bug in the translation of InternetGetConnectedState. The parameters are both DWORD's (first one is an LPDWORD). Both of these translate to int's in C# (technically, uint but int will work for most scenarios). </p>\n\n<p>Correct translation below.</p>\n\n<pre><code>\n[DllImport(\"wininet.dll\", SetLastError=true)] \npublic static extern bool InternetGetConnectedState(out int flags,int reserved);\n</code></pre>\n"
},
{
"answer_id": 195038,
"author": "Jim In Texas",
"author_id": 15079,
"author_profile": "https://Stackoverflow.com/users/15079",
"pm_score": 1,
"selected": false,
"text": "<p>InternetGetConnected state is step one in establishing that you are connected to a network. In order to determine if you have an internet connection one technique is to use the <a href=\"http://msdn.microsoft.com/en-us/library/aa366358(VS.85).aspx\" rel=\"nofollow noreferrer\">IPHelper api to send an ARP</a> (address resolution protocol) request for some server on the internet. </p>\n"
},
{
"answer_id": 195276,
"author": "Mihai Limbășan",
"author_id": 14444,
"author_profile": "https://Stackoverflow.com/users/14444",
"pm_score": 1,
"selected": false,
"text": "<p>Ping google.com (or a list of well-known hosts) or try actually performing one of the functions (in a structural sense) for which your application requires Internet connectivity. There is no way, on any operating system, to truly determine whether or not Internet connectivity is functional without actually <em>trying</em> to communicate, as opposed to the operating system's view on what constitutes \"available\".</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5019/"
] |
What is the best way to determine whether there is an available Internet connection for a WinForms app. (Programatically of course) I want to disable/hide certain functions if the user is not connected to the Internet.
|
The following will determine if you are connected to a network, however, that doesn't necessarily mean that you are connected to the Internet:
```
NetworkInterface.GetIsNetworkAvailable()
```
Here is a C# translation of Steve's code that seems to be pretty good:
```
private static int ERROR_SUCCESS = 0;
public static bool IsInternetConnected() {
long dwConnectionFlags = 0;
if (!InternetGetConnectedState(dwConnectionFlags, 0))
return false;
if(InternetAttemptConnect(0) != ERROR_SUCCESS)
return false;
return true;
}
[DllImport("wininet.dll", SetLastError=true)]
public static extern int InternetAttemptConnect(uint res);
[DllImport("wininet.dll", SetLastError=true)]
public static extern bool InternetGetConnectedState(out int flags,int reserved);
```
|
194,765 |
<p>At the moment a default entry looks something like this:</p>
<pre><code>Oct 12, 2008 9:45:18 AM myClassInfoHere
INFO: MyLogMessageHere
</code></pre>
<p>How do I get it to do this?</p>
<pre><code>Oct 12, 2008 9:45:18 AM myClassInfoHere - INFO: MyLogMessageHere
</code></pre>
<p>Clarification I'm using java.util.logging</p>
|
[
{
"answer_id": 194767,
"author": "Leigh Caldwell",
"author_id": 3267,
"author_profile": "https://Stackoverflow.com/users/3267",
"pm_score": -1,
"selected": false,
"text": "<p>This logging is specific to your application and not a general Java feature. What application(s) are you running?</p>\n\n<p>It might be that this is coming from a specific logging library that you are using within your own code. If so, please post the details of which one you are using.</p>\n"
},
{
"answer_id": 194920,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": -1,
"selected": false,
"text": "<p>if you're using java.util.logging, then there is a configuration file that is doing this to log contents (unless you're using programmatic configuration). So, your options are <br>\n1) run post -processor that removes the line breaks<br>\n2) change the log configuration AND remove the line breaks from it. Restart your application (server) and you should be good.</p>\n"
},
{
"answer_id": 195147,
"author": "Obediah Stane",
"author_id": 23120,
"author_profile": "https://Stackoverflow.com/users/23120",
"pm_score": 3,
"selected": false,
"text": "<p>I've figured out a way that works. You can subclass SimpleFormatter and override the format method</p>\n\n<pre><code> public String format(LogRecord record) {\n return new java.util.Date() + \" \" + record.getLevel() + \" \" + record.getMessage() + \"\\r\\n\";\n }\n</code></pre>\n\n<p>A bit surprised at this API I would have thought that more functionality/flexibility would have been provided out of the box</p>\n"
},
{
"answer_id": 197361,
"author": "Benno Richters",
"author_id": 3565,
"author_profile": "https://Stackoverflow.com/users/3565",
"pm_score": 5,
"selected": false,
"text": "<p>Like Obediah Stane said, it's necessary to create your own <code>format</code> method. But I would change a few things:</p>\n\n<ul>\n<li><p>Create a subclass directly derived from <code>Formatter</code>, not from <code>SimpleFormatter</code>. The <code>SimpleFormatter</code> has nothing to add anymore.</p></li>\n<li><p>Be careful with creating a new <code>Date</code> object! You should make sure to represent the date of the <code>LogRecord</code>. When creating a new <code>Date</code> with the default constructor, it will represent the date and time the <code>Formatter</code> processes the <code>LogRecord</code>, not the date that the <code>LogRecord</code> was created.</p></li>\n</ul>\n\n<p>The following class can be <a href=\"http://java.sun.com/javase/6/docs/api/java/util/logging/Handler.html#setFormatter(java.util.logging.Formatter)\" rel=\"noreferrer\">used as formatter</a> in a <code>Handler</code>, which in turn can be <a href=\"http://java.sun.com/javase/6/docs/api/java/util/logging/Logger.html#addHandler(java.util.logging.Handler)\" rel=\"noreferrer\">added</a> to the <code>Logger</code>. Note that it ignores all class and method information available in the <code>LogRecord</code>.</p>\n\n<pre><code>import java.io.PrintWriter;\nimport java.io.StringWriter;\nimport java.util.Date;\nimport java.util.logging.Formatter;\nimport java.util.logging.LogRecord;\n\npublic final class LogFormatter extends Formatter {\n\n private static final String LINE_SEPARATOR = System.getProperty(\"line.separator\");\n\n @Override\n public String format(LogRecord record) {\n StringBuilder sb = new StringBuilder();\n\n sb.append(new Date(record.getMillis()))\n .append(\" \")\n .append(record.getLevel().getLocalizedName())\n .append(\": \")\n .append(formatMessage(record))\n .append(LINE_SEPARATOR);\n\n if (record.getThrown() != null) {\n try {\n StringWriter sw = new StringWriter();\n PrintWriter pw = new PrintWriter(sw);\n record.getThrown().printStackTrace(pw);\n pw.close();\n sb.append(sw.toString());\n } catch (Exception ex) {\n // ignore\n }\n }\n\n return sb.toString();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 5937929,
"author": "Ondra Žižka",
"author_id": 145989,
"author_profile": "https://Stackoverflow.com/users/145989",
"pm_score": 6,
"selected": false,
"text": "<h2>1) <code>-Djava.util.logging.SimpleFormatter.format</code></h2>\n<p>Java 7 supports a property with the <code>java.util.Formatter</code> format string syntax.</p>\n<pre><code>-Djava.util.logging.SimpleFormatter.format=... \n</code></pre>\n<p>See <a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6381464\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>My favorite is:</p>\n<pre><code>-Djava.util.logging.SimpleFormatter.format=%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$-6s %2$s %5$s%6$s%n\n</code></pre>\n<p>which makes output like:</p>\n<pre><code>2014-09-02 16:44:57 SEVERE org.jboss.windup.util.ZipUtil unzip: Failed to load: foo.zip\n</code></pre>\n<h2>2) Putting it to IDEs</h2>\n<p>IDEs typically let you set system properties for a project.\nE.g. in NetBeans, instead of adding -D...=... somewhere, add the property in the action dialog, in a form of <code>java.util.logging.SimpleFormatter.format=%1$tY-%1$tm-...</code> - without any quotes. The IDE should figure out.</p>\n<h2>3) Putting that to Maven - Surefire</h2>\n<p>For your convenience, Here is how to put it to Surefire:</p>\n<pre class=\"lang-xml prettyprint-override\"><code><!-- Surefire -->\n<plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-surefire-plugin</artifactId>\n <version>2.17</version>\n <configuration>\n <systemPropertyVariables>\n <!-- Set JUL Formatting -->\n <java.util.logging.SimpleFormatter.format>%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$-6s %2$s %5$s%6$s%n</java.util.logging.SimpleFormatter.format>\n </systemPropertyVariables>\n </configuration>\n</plugin>\n</code></pre>\n<h2>4) Hand-made</h2>\n<p>I have a library with <a href=\"http://code.google.com/p/ondrazizka/source/browse/#svn%2Ftrunk%2FDwLib%2Fsrc%2Fmain%2Fjava%2Fcz%2Fdynawest%2Flogging\" rel=\"nofollow noreferrer\">few <code>java.util.logging</code> related classes</a>. Amongst them, it's <code>SingleLineFormatter</code>.\nDownloadable jar <a href=\"http://code.google.com/p/ondrazizka/source/browse/maven/cz/dynawest/lib/DwLib/1.01/DwLib-1.01-javadoc.jar\" rel=\"nofollow noreferrer\">here</a>.</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class SingleLineFormatter extends Formatter {\n\n Date dat = new Date();\n private final static String format = "{0,date} {0,time}";\n private MessageFormat formatter;\n private Object args[] = new Object[1];\n\n // Line separator string. This is the value of the line.separator\n // property at the moment that the SimpleFormatter was created.\n //private String lineSeparator = (String) java.security.AccessController.doPrivileged(\n // new sun.security.action.GetPropertyAction("line.separator"));\n private String lineSeparator = "\\n";\n\n /**\n * Format the given LogRecord.\n * @param record the log record to be formatted.\n * @return a formatted log record\n */\n public synchronized String format(LogRecord record) {\n\n StringBuilder sb = new StringBuilder();\n\n // Minimize memory allocations here.\n dat.setTime(record.getMillis()); \n args[0] = dat;\n\n\n // Date and time \n StringBuffer text = new StringBuffer();\n if (formatter == null) {\n formatter = new MessageFormat(format);\n }\n formatter.format(args, text, null);\n sb.append(text);\n sb.append(" ");\n\n\n // Class name \n if (record.getSourceClassName() != null) {\n sb.append(record.getSourceClassName());\n } else {\n sb.append(record.getLoggerName());\n }\n\n // Method name \n if (record.getSourceMethodName() != null) {\n sb.append(" ");\n sb.append(record.getSourceMethodName());\n }\n sb.append(" - "); // lineSeparator\n\n\n\n String message = formatMessage(record);\n\n // Level\n sb.append(record.getLevel().getLocalizedName());\n sb.append(": ");\n\n // Indent - the more serious, the more indented.\n //sb.append( String.format("% ""s") );\n int iOffset = (1000 - record.getLevel().intValue()) / 100;\n for( int i = 0; i < iOffset; i++ ){\n sb.append(" ");\n }\n\n\n sb.append(message);\n sb.append(lineSeparator);\n if (record.getThrown() != null) {\n try {\n StringWriter sw = new StringWriter();\n PrintWriter pw = new PrintWriter(sw);\n record.getThrown().printStackTrace(pw);\n pw.close();\n sb.append(sw.toString());\n } catch (Exception ex) {\n }\n }\n return sb.toString();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 10706033,
"author": "Trevor Robinson",
"author_id": 123336,
"author_profile": "https://Stackoverflow.com/users/123336",
"pm_score": 7,
"selected": false,
"text": "<p>As of Java 7, <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/logging/SimpleFormatter.html#format%28java.util.logging.LogRecord%29\" rel=\"noreferrer\">java.util.logging.SimpleFormatter</a> supports getting its <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax\" rel=\"noreferrer\">format</a> from a system property, so adding something like this to the JVM command line will cause it to print on one line:</p>\n\n<pre><code>-Djava.util.logging.SimpleFormatter.format='%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n'\n</code></pre>\n\n<p>Alternatively, you can also add this to your <code>logger.properties</code>:</p>\n\n<pre><code>java.util.logging.SimpleFormatter.format='%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n'\n</code></pre>\n"
},
{
"answer_id": 15529903,
"author": "rupweb",
"author_id": 1964277,
"author_profile": "https://Stackoverflow.com/users/1964277",
"pm_score": 3,
"selected": false,
"text": "<p><img src=\"https://i.stack.imgur.com/0kOvJ.gif\" alt=\"Eclipse config\"></p>\n\n<p>Per screenshot, in Eclipse select \"run as\" then \"Run Configurations...\" and add the answer from Trevor Robinson with double quotes instead of quotes. If you miss the double quotes you'll get \"could not find or load main class\" errors.</p>\n"
},
{
"answer_id": 34229629,
"author": "Guy L",
"author_id": 1344896,
"author_profile": "https://Stackoverflow.com/users/1344896",
"pm_score": 6,
"selected": false,
"text": "<p>Similar to Tervor, But I like to change the property on runtime. </p>\n\n<p>Note that this need to be set before the first SimpleFormatter is created - as was written in the comments.</p>\n\n<pre><code> System.setProperty(\"java.util.logging.SimpleFormatter.format\", \n \"%1$tF %1$tT %4$s %2$s %5$s%6$s%n\");\n</code></pre>\n"
},
{
"answer_id": 39034822,
"author": "Jin Kwon",
"author_id": 330457,
"author_profile": "https://Stackoverflow.com/users/330457",
"pm_score": 4,
"selected": false,
"text": "<p>This is what I'm using.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class VerySimpleFormatter extends Formatter {\n\n private static final String PATTERN = \"yyyy-MM-dd'T'HH:mm:ss.SSSXXX\";\n\n @Override\n public String format(final LogRecord record) {\n return String.format(\n \"%1$s %2$-7s %3$s\\n\",\n new SimpleDateFormat(PATTERN).format(\n new Date(record.getMillis())),\n record.getLevel().getName(), formatMessage(record));\n }\n}\n</code></pre>\n\n<p>You'll get something like...</p>\n\n<pre><code>2016-08-19T17:43:14.295+09:00 INFO Hey~\n2016-08-19T17:43:16.068+09:00 SEVERE Seriously?\n2016-08-19T17:43:16.068+09:00 WARNING I'm warning you!!!\n</code></pre>\n"
},
{
"answer_id": 39827527,
"author": "Mohammad Irfan",
"author_id": 1927485,
"author_profile": "https://Stackoverflow.com/users/1927485",
"pm_score": -1,
"selected": false,
"text": "<p>If you log in a web application using tomcat add:</p>\n\n<pre><code>-Djava.util.logging.ConsoleHandler.formatter = org.apache.juli.OneLineFormatter\n</code></pre>\n\n<p>On VM arguments</p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23120/"
] |
At the moment a default entry looks something like this:
```
Oct 12, 2008 9:45:18 AM myClassInfoHere
INFO: MyLogMessageHere
```
How do I get it to do this?
```
Oct 12, 2008 9:45:18 AM myClassInfoHere - INFO: MyLogMessageHere
```
Clarification I'm using java.util.logging
|
As of Java 7, [java.util.logging.SimpleFormatter](http://docs.oracle.com/javase/7/docs/api/java/util/logging/SimpleFormatter.html#format%28java.util.logging.LogRecord%29) supports getting its [format](http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax) from a system property, so adding something like this to the JVM command line will cause it to print on one line:
```
-Djava.util.logging.SimpleFormatter.format='%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n'
```
Alternatively, you can also add this to your `logger.properties`:
```
java.util.logging.SimpleFormatter.format='%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n'
```
|
194,803 |
<p>I'm currently developing a website and my client wants the text of various articles to overflow into two columns. Kind of like in a newspaper? So it would look like:</p>
<pre class="lang-none prettyprint-override"><code>Today in Wales, someone actually Nobody was harmed in
did something interesting. the incident, although one
Authorities are baffled by this elderly victim is receiving
development and have arrested the counselling.
perpetrator.
</code></pre>
<p>Is there a way I can do this with just CSS alone? I'd prefer not to have to use multiple divs. I'm open to using JavaScript too, but I'm <em>really</em> bad at that, so help would be appreciated. I was thinking maybe JavaScript could count how many <p>'s there are in the content div, and then move the second half of them to be floated right based on that?</p>
|
[
{
"answer_id": 194816,
"author": "Kris",
"author_id": 18565,
"author_profile": "https://Stackoverflow.com/users/18565",
"pm_score": -1,
"selected": false,
"text": "<p>First off, i don't think just css can do that, but i would love to be proven wrong.</p>\n\n<p>Second, just counting paragraphs won't help you at all, you need at least all the heights and calculate the middle of the text height based on that, but you'd have to account for window resizing etc. I don't think there is a reasonably simple off the shelf solution. Unfortunately i'm pessimistic about finding a perfect solution to this problem, But it is an interesting one.</p>\n"
},
{
"answer_id": 194818,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 3,
"selected": false,
"text": "<p>I'd probably handle it in your backend, whatever that happens to be. An example in PHP might look like:</p>\n\n<pre><code>$content = \"Today in Wales, someone actually did something...\";\n// Find the literal halfway point, should be close to the textual halfway point\n$pos = int(strlen($content) / 2);\n// Find the end of the nearest word\nwhile ($content[$pos] != \" \") { $pos++; }\n// Split into columns based on the word ending.\n$column1 = substr($content, 0, $pos);\n$column2 = substr($content, $pos+1);\n</code></pre>\n\n<p>It should probably be possible to do something similar in JavaScript with InnerHTML, but personally I'd avoid that whole situation because more and more people are using plugins like NoScript that disables JavaScript till it's explicitly allowed for x site, and above anything else, div's and CSS were designed to degrade nicely. A JavaScript solution would degrade horribly in this case.</p>\n"
},
{
"answer_id": 194825,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 4,
"selected": false,
"text": "<p>The good news is that there is a <a href=\"http://www.w3.org/TR/css3-multicol/\" rel=\"nofollow noreferrer\">CSS-only solution</a>. If it was implemented, it would look like this:</p>\n<pre><code>div.multi {\n column-count: 3\n column-gap: 10px;\n column-rule: 1px solid black; \n}\n</code></pre>\n"
},
{
"answer_id": 194827,
"author": "Matt Dawdy",
"author_id": 232,
"author_profile": "https://Stackoverflow.com/users/232",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://welcome.totheinter.net/2008/07/22/multi-column-layout-with-css-and-jquery/\" rel=\"nofollow noreferrer\">Here's a JQuery plugin</a> which does columns automatically, and can even vary number of columns based on screen size.</p>\n\n<p>I haven't used this myself, but check it out.</p>\n"
},
{
"answer_id": 194861,
"author": "cheeaun",
"author_id": 20838,
"author_profile": "https://Stackoverflow.com/users/20838",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using Mootools, you can check out <a href=\"http://greengeckodesign.com/projects/moocolumns.aspx\" rel=\"nofollow noreferrer\">MooColumns</a>.</p>\n"
},
{
"answer_id": 195224,
"author": "Jason",
"author_id": 1072,
"author_profile": "https://Stackoverflow.com/users/1072",
"pm_score": -1,
"selected": false,
"text": "<p>This is difficult to achieve in HTML/CSS/JS for a reason (although I'm sure it's possible).</p>\n\n<p>Newspapers use multiple columns to reduce the line width make text more readable. This is fine on paper because when you finish one column you flip your eye up to the beginning of the next.</p>\n\n<p>On the web we use scrolling to allow text to continue past the bounds of the screen therefore don't need columns.</p>\n"
},
{
"answer_id": 3736256,
"author": "tholane",
"author_id": 450688,
"author_profile": "https://Stackoverflow.com/users/450688",
"pm_score": -1,
"selected": false,
"text": "<p>This is supported in a Mozilla only CSS extension: <code>-moz-column-count</code>. See : <a href=\"https://developer.mozilla.org/en/CSS3_Columns\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en/CSS3_Columns</a></p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12765/"
] |
I'm currently developing a website and my client wants the text of various articles to overflow into two columns. Kind of like in a newspaper? So it would look like:
```none
Today in Wales, someone actually Nobody was harmed in
did something interesting. the incident, although one
Authorities are baffled by this elderly victim is receiving
development and have arrested the counselling.
perpetrator.
```
Is there a way I can do this with just CSS alone? I'd prefer not to have to use multiple divs. I'm open to using JavaScript too, but I'm *really* bad at that, so help would be appreciated. I was thinking maybe JavaScript could count how many <p>'s there are in the content div, and then move the second half of them to be floated right based on that?
|
The good news is that there is a [CSS-only solution](http://www.w3.org/TR/css3-multicol/). If it was implemented, it would look like this:
```
div.multi {
column-count: 3
column-gap: 10px;
column-rule: 1px solid black;
}
```
|
194,828 |
<p>Is it possible to initialize an array of pointers to structs?
Something like:</p>
<pre><code>struct country_t *countries[] = {
{"United States of America", "America"},
{"England", "Europe"},
{"Ethiopia", "Africa"}
}
</code></pre>
<p>I want to do that in order to get the entities in not-contiguous memory, and the pointers to them in contiguous memory... But I can't use dynamic memory, so I wonder if it is possible without it.</p>
|
[
{
"answer_id": 194840,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 5,
"selected": false,
"text": "<p>Well, your code uses structures rather than pointers to structures. There are ways to do what you seek, including:</p>\n\n<pre><code>static struct country_t us = { \"United States of America\", \"America\" };\nstatic struct country_t uk = { \"England\", \"Europe\" };\nstatic struct country_t et = { \"Ethiopia\", \"Africa\" };\n\nstruct country_t *countries[] = { &us, &uk, &et, };\n</code></pre>\n\n<p>There are other ways to do it with designated initializers and compound literals in C99. Section 6.5.2.5 'Compound Literals' shows the way:</p>\n\n<pre><code>struct country_t *countries[] =\n{\n &(struct country_t) { \"United States of America\", \"America\" },\n &(struct country_t) { \"England\", \"Europe\" },\n &(struct country_t) { \"Ethiopia\", \"Africa\" },\n};\n</code></pre>\n\n<p>The standard illustrates pointers to structures with a function call. Be aware that not all C compilers accept C99 syntax, and these compound literals were not present in C89 (aka C90).</p>\n\n<p><em>Edit:</em> Upgraded to use 2-letter ISO 3166 country codes. Also made the named structures into static variables - those symbols were not visible outside the file before (because they did not exist), and now they aren't visible outside the file after, either. I debated whether to make anything const and decided not to - but using const when you can is generally a good idea. Also, in the example, there are 3 countries in 3 continents. Were you to have multiple countries in a single continent (the norm), you might want to be able to share the continent strings. However, whether you can do that safely (or at all) depends on the details of the <code>struct country_t</code> (which were not given), and on whether the program is allowed to update the table (which comes back to the const-ness question).</p>\n"
},
{
"answer_id": 194845,
"author": "James Fassett",
"author_id": 27081,
"author_profile": "https://Stackoverflow.com/users/27081",
"pm_score": 0,
"selected": false,
"text": "<p>This works for me:</p>\n\n<pre><code>\nstruct country_t {\n char *fullname;\n char *shortname;\n};\n\nstruct country_t countries[] = {\n {\"United States of America\", \"America\"},\n {\"England\", \"Europe\"},\n {\"Ethiopia\", \"Africa\"}\n};\n\nint main(int argc, char *argv[])\n{\n return 0;\n}\n</code></pre>\n\n<p>You could be more terse and use:</p>\n\n<pre><code>\nstruct country_t {\n char *fullname;\n char *shortname;\n} countries[] = {\n {\"United States of America\", \"America\"},\n {\"England\", \"Europe\"},\n {\"Ethiopia\", \"Africa\"}\n};\n\nint main(int argc, char *argv[])\n{\n return 0;\n}\n</code></pre>\n\n<p><strong>Edit:</strong> I found this information at <a href=\"http://publications.gbdirect.co.uk/c_book/chapter6/initialization.html\" rel=\"nofollow noreferrer\">The C Book</a></p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Is it possible to initialize an array of pointers to structs?
Something like:
```
struct country_t *countries[] = {
{"United States of America", "America"},
{"England", "Europe"},
{"Ethiopia", "Africa"}
}
```
I want to do that in order to get the entities in not-contiguous memory, and the pointers to them in contiguous memory... But I can't use dynamic memory, so I wonder if it is possible without it.
|
Well, your code uses structures rather than pointers to structures. There are ways to do what you seek, including:
```
static struct country_t us = { "United States of America", "America" };
static struct country_t uk = { "England", "Europe" };
static struct country_t et = { "Ethiopia", "Africa" };
struct country_t *countries[] = { &us, &uk, &et, };
```
There are other ways to do it with designated initializers and compound literals in C99. Section 6.5.2.5 'Compound Literals' shows the way:
```
struct country_t *countries[] =
{
&(struct country_t) { "United States of America", "America" },
&(struct country_t) { "England", "Europe" },
&(struct country_t) { "Ethiopia", "Africa" },
};
```
The standard illustrates pointers to structures with a function call. Be aware that not all C compilers accept C99 syntax, and these compound literals were not present in C89 (aka C90).
*Edit:* Upgraded to use 2-letter ISO 3166 country codes. Also made the named structures into static variables - those symbols were not visible outside the file before (because they did not exist), and now they aren't visible outside the file after, either. I debated whether to make anything const and decided not to - but using const when you can is generally a good idea. Also, in the example, there are 3 countries in 3 continents. Were you to have multiple countries in a single continent (the norm), you might want to be able to share the continent strings. However, whether you can do that safely (or at all) depends on the details of the `struct country_t` (which were not given), and on whether the program is allowed to update the table (which comes back to the const-ness question).
|
194,846 |
<p>Basically, I'm trying to create an object of unique objects, a set. I had the brilliant idea of just using a JavaScript object with objects for the property names. Such as,</p>
<pre><code>set[obj] = true;
</code></pre>
<p>This works, up to a point. It works great with string and numbers, but with other objects, they all seem to "hash" to the same value and access the same property. Is there some kind of way I can generate a unique hash value for an object? How do strings and numbers do it, can I override the same behavior?</p>
|
[
{
"answer_id": 194906,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 6,
"selected": true,
"text": "<p>JavaScript objects can only use strings as keys (anything else is converted to a string).</p>\n\n<p>You could, alternatively, maintain an array which indexes the objects in question, and use its index string as a reference to the object. Something like this:</p>\n\n<pre><code>var ObjectReference = [];\nObjectReference.push(obj);\n\nset['ObjectReference.' + ObjectReference.indexOf(obj)] = true;\n</code></pre>\n\n<p>Obviously it's a little verbose, but you could write a couple of methods that handle it and get and set all willy nilly.</p>\n\n<p>Edit:</p>\n\n<blockquote>\n <p>Your guess is fact -- this is defined behaviour in JavaScript -- specifically a toString conversion occurs meaning that you can can define your own toString function on the object that will be used as the property name. - olliej</p>\n</blockquote>\n\n<p>This brings up another interesting point; you can define a toString method on the objects you want to hash, and that can form their hash identifier.</p>\n"
},
{
"answer_id": 194967,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If you truly want set behavior (I'm going by Java knowledge), then you will be hard pressed to find a solution in JavaScript. Most developers will recommend a unique key to represent each object, but this is unlike set, in that you can get two identical objects each with a unique key. The Java API does the work of checking for duplicate values by comparing hash code values, not keys, and since there is no hash code value representation of objects in JavaScript, it becomes almost impossible to do the same. Even the Prototype JS library admits this shortcoming, when it says:</p>\n\n<blockquote>\n <p>\"Hash can be thought of as an\n associative array, binding unique keys\n to values (which are not necessarily\n unique)...\"</p>\n</blockquote>\n\n<p><a href=\"http://www.prototypejs.org/api/hash\" rel=\"nofollow noreferrer\">http://www.prototypejs.org/api/hash</a></p>\n"
},
{
"answer_id": 195222,
"author": "olliej",
"author_id": 784,
"author_profile": "https://Stackoverflow.com/users/784",
"pm_score": 3,
"selected": false,
"text": "<p>The JavaScript specification defines indexed property access as performing a toString conversion on the index name. For example,</p>\n\n<pre><code>myObject[myProperty] = ...;\n</code></pre>\n\n<p>is the same as</p>\n\n<pre><code>myObject[myProperty.toString()] = ...;\n</code></pre>\n\n<p>This is necessary as in JavaScript</p>\n\n<pre><code>myObject[\"someProperty\"]\n</code></pre>\n\n<p>is the same as</p>\n\n<pre><code>myObject.someProperty\n</code></pre>\n\n<p>And yes, it makes me sad as well :-(</p>\n"
},
{
"answer_id": 885944,
"author": "Daniel X Moore",
"author_id": 68210,
"author_profile": "https://Stackoverflow.com/users/68210",
"pm_score": 5,
"selected": false,
"text": "<p>The easiest way to do this is to give each of your objects its own unique <code>toString</code> method:</p>\n\n<pre><code>(function() {\n var id = 0;\n\n /*global MyObject */\n MyObject = function() {\n this.objectId = '<#MyObject:' + (id++) + '>';\n this.toString= function() {\n return this.objectId;\n };\n };\n})();\n</code></pre>\n\n<p>I had the same problem and this solved it perfectly for me with minimal fuss, and was a lot easier that re-implementing some fatty Java style <code>Hashtable</code> and adding <code>equals()</code> and <code>hashCode()</code> to your object classes. Just make sure that you don't also stick a string '<#MyObject:12> into your hash or it will wipe out the entry for your exiting object with that id.</p>\n\n<p>Now all my hashes are totally chill. I also just posted a blog entry a few days ago about <a href=\"http://strd6.com/?p=276\" rel=\"noreferrer\">this exact topic</a>.</p>\n"
},
{
"answer_id": 5790850,
"author": "theGecko",
"author_id": 39022,
"author_profile": "https://Stackoverflow.com/users/39022",
"pm_score": 4,
"selected": false,
"text": "<p>The solution I chose is similar to Daniel's, but rather than use an object factory and override the toString, I explicitly add the hash to the object when it is first requested through a getHashCode function. A little messy, but better for my needs :)</p>\n\n<pre><code>Function.prototype.getHashCode = (function(id) {\n return function() {\n if (!this.hashCode) {\n this.hashCode = '<hash|#' + (id++) + '>';\n }\n return this.hashCode;\n }\n}(0));\n</code></pre>\n"
},
{
"answer_id": 8076436,
"author": "KimKha",
"author_id": 333214,
"author_profile": "https://Stackoverflow.com/users/333214",
"pm_score": 6,
"selected": false,
"text": "<p>If you want a hashCode() function like Java's in JavaScript, that is yours:</p>\n<pre><code>function hashCode(string){\n var hash = 0;\n for (var i = 0; i < string.length; i++) {\n var code = string.charCodeAt(i);\n hash = ((hash<<5)-hash)+code;\n hash = hash & hash; // Convert to 32bit integer\n }\n return hash;\n}\n</code></pre>\n<p>That is the way of implementation in Java (bitwise operator).</p>\n<p>Please note that hashCode could be positive and negative, and that's normal, see <a href=\"https://stackoverflow.com/questions/9249983/hashcode-giving-negative-values\">HashCode giving negative values</a>. So, you could consider to use <code>Math.abs()</code> along with this function.</p>\n"
},
{
"answer_id": 8077416,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>What you described is covered by Harmony <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/WeakMap\" rel=\"noreferrer\">WeakMaps</a>, part of the <a href=\"http://en.wikipedia.org/wiki/ECMAScript#Versions\" rel=\"noreferrer\">ECMAScript 6</a> specification (next version of JavaScript). That is: a set where the keys can be anything (including undefined) and is non-enumerable.</p>\n\n<p>This means it's impossible to get a reference to a value unless you have a direct reference to the key (any object!) that links to it. It's important for a bunch of engine implementation reasons relating to efficiency and garbage collection, but it's also super cool for in that it allows for new semantics like revokable access permissions and passing data without exposing the data sender.</p>\n\n<p>From <a href=\"https://en.wikipedia.org/wiki/Mozilla_Developer_Network\" rel=\"noreferrer\">MDN</a>:</p>\n\n<pre><code>var wm1 = new WeakMap(),\n wm2 = new WeakMap();\nvar o1 = {},\n o2 = function(){},\n o3 = window;\n\nwm1.set(o1, 37);\nwm1.set(o2, \"azerty\");\nwm2.set(o1, o2); // A value can be anything, including an object or a function.\nwm2.set(o3, undefined);\nwm2.set(wm1, wm2); // Keys and values can be any objects. Even WeakMaps!\n\nwm1.get(o2); // \"azerty\"\nwm2.get(o2); // Undefined, because there is no value for o2 on wm2.\nwm2.get(o3); // Undefined, because that is the set value.\n\nwm1.has(o2); // True\nwm2.has(o2); // False\nwm2.has(o3); // True (even if the value itself is 'undefined').\n\nwm1.has(o1); // True\nwm1.delete(o1);\nwm1.has(o1); // False\n</code></pre>\n\n<p>WeakMaps are available in current Firefox, Chrome and Edge. They're also supported in Node v7 , and in v6 with the <code>--harmony-weak-maps</code> flag.</p>\n"
},
{
"answer_id": 11440965,
"author": "cburgmer",
"author_id": 575501,
"author_profile": "https://Stackoverflow.com/users/575501",
"pm_score": 0,
"selected": false,
"text": "<p>In addition to eyelidlessness's answer, here is a function that returns a reproducible, unique ID for any object:</p>\n\n<pre><code>var uniqueIdList = [];\nfunction getConstantUniqueIdFor(element) {\n // HACK, using a list results in O(n), but how do we hash e.g. a DOM node?\n if (uniqueIdList.indexOf(element) < 0) {\n uniqueIdList.push(element);\n }\n return uniqueIdList.indexOf(element);\n}\n</code></pre>\n\n<p>As you can see it uses a list for look-up which is very inefficient, however that's the best I could find for now.</p>\n"
},
{
"answer_id": 14469330,
"author": "darthmatch",
"author_id": 1872746,
"author_profile": "https://Stackoverflow.com/users/1872746",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to use objects as keys you need to overwrite their toString Method, as some already mentioned here. The hash functions that were used are all fine, but they only work for the same objects not for equal objects.</p>\n\n<p>I've written a small library that creates hashes from objects, which you can easily use for this purpose. The objects can even have a different order, the hashes will be the same. Internally you can use different types for your hash (djb2, md5, sha1, sha256, sha512, ripemd160).</p>\n\n<p>Here is a small example from the documentation:</p>\n\n<pre><code>var hash = require('es-hash');\n\n// Save data in an object with an object as a key\nObject.prototype.toString = function () {\n return '[object Object #'+hash(this)+']';\n}\n\nvar foo = {};\n\nfoo[{bar: 'foo'}] = 'foo';\n\n/*\n * Output:\n * foo\n * undefined\n */\nconsole.log(foo[{bar: 'foo'}]);\nconsole.log(foo[{}]);\n</code></pre>\n\n<p>The package can be used either in browser and in Node-Js.</p>\n\n<p>Repository: <a href=\"https://bitbucket.org/tehrengruber/es-js-hash\" rel=\"nofollow\">https://bitbucket.org/tehrengruber/es-js-hash</a></p>\n"
},
{
"answer_id": 14953738,
"author": "Johnny",
"author_id": 459753,
"author_profile": "https://Stackoverflow.com/users/459753",
"pm_score": 1,
"selected": false,
"text": "<p>My solution introduces a static function for the global <code>Object</code> object.</p>\n\n<pre><code>(function() {\n var lastStorageId = 0;\n\n this.Object.hash = function(object) {\n var hash = object.__id;\n\n if (!hash)\n hash = object.__id = lastStorageId++;\n\n return '#' + hash;\n };\n}());\n</code></pre>\n\n<p>I think this is more convenient with other object manipulating functions in JavaScript.</p>\n"
},
{
"answer_id": 15868654,
"author": "Metalstorm",
"author_id": 524126,
"author_profile": "https://Stackoverflow.com/users/524126",
"pm_score": 4,
"selected": false,
"text": "<p>I put together <a href=\"https://github.com/stuartbannerman/hashcode\">a small JavaScript module</a> a while ago to produce hashcodes for strings, objects, arrays, etc. (I just committed it to <a href=\"http://en.wikipedia.org/wiki/GitHub\">GitHub</a> :) )</p>\n\n<p>Usage:</p>\n\n<pre><code>Hashcode.value(\"stackoverflow\")\n// -2559914341\nHashcode.value({ 'site' : \"stackoverflow\" })\n// -3579752159\n</code></pre>\n"
},
{
"answer_id": 22330776,
"author": "ijmacd",
"author_id": 1228394,
"author_profile": "https://Stackoverflow.com/users/1228394",
"pm_score": 4,
"selected": false,
"text": "<p>For my specific situation I only care about the equality of the object as far as keys and primitive values go. The solution that worked for me was converting the object to its JSON representation and using that as the hash. There are limitations such as order of key definition potentially being inconsistent; but like I said it worked for me because these objects were all being generated in one place.</p>\n\n<pre><code>var hashtable = {};\n\nvar myObject = {a:0,b:1,c:2};\n\nvar hash = JSON.stringify(myObject);\n// '{\"a\":0,\"b\":1,\"c\":2}'\n\nhashtable[hash] = myObject;\n// {\n// '{\"a\":0,\"b\":1,\"c\":2}': myObject\n// }\n</code></pre>\n"
},
{
"answer_id": 27930322,
"author": "Daniel X Moore",
"author_id": 68210,
"author_profile": "https://Stackoverflow.com/users/68210",
"pm_score": 3,
"selected": false,
"text": "<p>In ECMAScript 6 there's now a <code>Set</code> that works how you'd like: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set</a></p>\n\n<p>It's already available in the latest Chrome, FF, and IE11.</p>\n"
},
{
"answer_id": 40187493,
"author": "A1rPun",
"author_id": 1449624,
"author_profile": "https://Stackoverflow.com/users/1449624",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to have unique values in a lookup object you can do something like this:</p>\n\n<p>Creating a lookup object</p>\n\n<pre><code>var lookup = {};\n</code></pre>\n\n<p>Setting up the hashcode function</p>\n\n<pre><code>function getHashCode(obj) {\n var hashCode = '';\n if (typeof obj !== 'object')\n return hashCode + obj;\n for (var prop in obj) // No hasOwnProperty needed\n hashCode += prop + getHashCode(obj[prop]); // Add key + value to the result string\n return hashCode;\n}\n</code></pre>\n\n<p><strong>Object</strong></p>\n\n<pre><code>var key = getHashCode({ 1: 3, 3: 7 });\n// key = '1337'\nlookup[key] = true;\n</code></pre>\n\n<p><strong>Array</strong></p>\n\n<pre><code>var key = getHashCode([1, 3, 3, 7]);\n// key = '01132337'\nlookup[key] = true;\n</code></pre>\n\n<p><strong>Other types</strong></p>\n\n<pre><code>var key = getHashCode('StackOverflow');\n// key = 'StackOverflow'\nlookup[key] = true;\n</code></pre>\n\n<p><strong>Final result</strong></p>\n\n<p><code>{ 1337: true, 01132337: true, StackOverflow: true }</code></p>\n\n<p><em>Do note that <code>getHashCode</code> doesn't return any value when the object or array is empty</em></p>\n\n<pre><code>getHashCode([{},{},{}]);\n// '012'\ngetHashCode([[],[],[]]);\n// '012'\n</code></pre>\n\n<p>This is similar to @ijmacd solution only <code>getHashCode</code> doesn't has the <code>JSON</code> dependency.</p>\n"
},
{
"answer_id": 41925534,
"author": "Khalid Azam",
"author_id": 988976,
"author_profile": "https://Stackoverflow.com/users/988976",
"pm_score": 2,
"selected": false,
"text": "<p>Reference: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol</a></p>\n\n<p>you can use Es6 symbol to create unique key and access object.\n Every symbol value returned from Symbol() is unique. A symbol value may be used as an identifier for object properties; this is the data type's only purpose. </p>\n\n<pre><code>var obj = {};\n\nobj[Symbol('a')] = 'a';\nobj[Symbol.for('b')] = 'b';\nobj['c'] = 'c';\nobj.d = 'd';\n</code></pre>\n"
},
{
"answer_id": 43245290,
"author": "Timothy Perez",
"author_id": 904725,
"author_profile": "https://Stackoverflow.com/users/904725",
"pm_score": 2,
"selected": false,
"text": "<p>Here's my simple solution that returns a unique integer.</p>\n\n<pre><code>function hashcode(obj) {\n var hc = 0;\n var chars = JSON.stringify(obj).replace(/\\{|\\\"|\\}|\\:|,/g, '');\n var len = chars.length;\n for (var i = 0; i < len; i++) {\n // Bump 7 to larger prime number to increase uniqueness\n hc += (chars.charCodeAt(i) * 7);\n }\n return hc;\n}\n</code></pre>\n"
},
{
"answer_id": 53450095,
"author": "Christophe Roussy",
"author_id": 657427,
"author_profile": "https://Stackoverflow.com/users/657427",
"pm_score": 1,
"selected": false,
"text": "<p>I will try to go a little deeper than other answers.</p>\n\n<p>Even if JS had better hashing support it would not magically hash everything perfectly, in many cases you will have to define your own hash function. For example Java has good hashing support, but you still have to think and do some work.</p>\n\n<p>One problem is with the term hash/hashcode ... there is cryptographic hashing and non-cryptographic hashing. The other problem, is you have to understand why hashing is useful and how it works.</p>\n\n<p>When we talk about hashing in JavaScript or Java most of the time we are talking about non-cryptographic hashing, usually about hashing for hashmap/hashtable (unless we are working on authentication or passwords, which you could be doing server-side using NodeJS ...).</p>\n\n<p>It depends on what data you have and what you want to achieve.</p>\n\n<p>Your data has some natural \"simple\" uniqueness:</p>\n\n<ul>\n<li>The hash of an integer is ... the integer, as it is unique, lucky you !</li>\n<li>The hash of a string ... it depends on the string, if the string represents a unique identifier, you may consider it as a hash (so no hashing needed).</li>\n<li>Anything which is indirectly pretty much a unique integer is the simplest case</li>\n<li>This will respect: hashcode equal if objects are equal</li>\n</ul>\n\n<p>Your data has some natural \"composite\" uniqueness:</p>\n\n<ul>\n<li>For example with a person object, you may compute a hash using firstname, lastname, birthdate, ... see how Java does it: <a href=\"https://stackoverflow.com/questions/2624192/good-hash-function-for-strings\">Good Hash Function for Strings</a>, or use some other ID info that is cheap and unique enough for your usecase</li>\n</ul>\n\n<p>You have no idea what your data will be:</p>\n\n<ul>\n<li>Good luck ... you could serialize to string and hash it Java style, but that may be expensive if the string is large and it will not avoid collisions as well as say the hash of an integer (self).</li>\n</ul>\n\n<p>There is no magically efficient hashing technique for unknown data, in some cases it is quite easy, in other cases you may have to think twice. So even if JavaScript/ECMAScript adds more support, there is no magic language solution for this problem.</p>\n\n<p>In practice you need two things: enough uniqueness, enough speed</p>\n\n<p>In addition to that it is great to have: \"hashcode equal if objects are equal\"</p>\n\n<ul>\n<li><a href=\"https://en.wikipedia.org/wiki/Hash_table#Collision_resolution\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Hash_table#Collision_resolution</a></li>\n<li><a href=\"https://stackoverflow.com/questions/17027777/relationship-between-hashcode-and-equals-method-in-java\">Relationship between hashCode and equals method in Java</a></li>\n</ul>\n"
},
{
"answer_id": 53905336,
"author": "jozsef morrissey",
"author_id": 7760485,
"author_profile": "https://Stackoverflow.com/users/7760485",
"pm_score": 1,
"selected": false,
"text": "<p>I combined the answers from eyelidlessness and KimKha.</p>\n\n<p>The following is an angularjs service and it supports numbers, strings, and objects.</p>\n\n<pre><code>exports.Hash = () => {\n let hashFunc;\n function stringHash(string, noType) {\n let hashString = string;\n if (!noType) {\n hashString = `string${string}`;\n }\n var hash = 0;\n for (var i = 0; i < hashString.length; i++) {\n var character = hashString.charCodeAt(i);\n hash = ((hash<<5)-hash)+character;\n hash = hash & hash; // Convert to 32bit integer\n }\n return hash;\n }\n\n function objectHash(obj, exclude) {\n if (exclude.indexOf(obj) > -1) {\n return undefined;\n }\n let hash = '';\n const keys = Object.keys(obj).sort();\n for (let index = 0; index < keys.length; index += 1) {\n const key = keys[index];\n const keyHash = hashFunc(key);\n const attrHash = hashFunc(obj[key], exclude);\n exclude.push(obj[key]);\n hash += stringHash(`object${keyHash}${attrHash}`, true);\n }\n return stringHash(hash, true);\n }\n\n function Hash(unkType, exclude) {\n let ex = exclude;\n if (ex === undefined) {\n ex = [];\n }\n if (!isNaN(unkType) && typeof unkType !== 'string') {\n return unkType;\n }\n switch (typeof unkType) {\n case 'object':\n return objectHash(unkType, ex);\n default:\n return stringHash(String(unkType));\n }\n }\n\n hashFunc = Hash;\n\n return Hash;\n};\n</code></pre>\n\n<p><strong>Example Usage:</strong></p>\n\n<pre><code>Hash('hello world'), Hash('hello world') == Hash('hello world')\nHash({hello: 'hello world'}), Hash({hello: 'hello world'}) == Hash({hello: 'hello world'})\nHash({hello: 'hello world', goodbye: 'adios amigos'}), Hash({hello: 'hello world', goodbye: 'adios amigos'}) == Hash({goodbye: 'adios amigos', hello: 'hello world'})\nHash(['hello world']), Hash(['hello world']) == Hash(['hello world'])\nHash(1), Hash(1) == Hash(1)\nHash('1'), Hash('1') == Hash('1')\n</code></pre>\n\n<p><strong>Output</strong></p>\n\n<pre><code>432700947 true\n-411117486 true\n1725787021 true\n-1585332251 true\n1 true\n-1881759168 true\n</code></pre>\n\n<p><strong>Explanation</strong></p>\n\n<p>As you can see the heart of the service is the hash function created by KimKha.I have added types to the strings so that the sturucture of the object would also impact the final hash value.The keys are hashed to prevent array|object collisions.</p>\n\n<p>eyelidlessness object comparision is used to prevent infinit recursion by self referencing objects.</p>\n\n<p><strong>Usage</strong></p>\n\n<p>I created this service so that I could have an error service that is accessed with objects. So that one service can register an error with a given object and another can determine if any errors were found.</p>\n\n<p><strong>ie</strong></p>\n\n<p><strong>JsonValidation.js</strong></p>\n\n<pre><code>ErrorSvc({id: 1, json: '{attr: \"not-valid\"}'}, 'Invalid Json Syntax - key not double quoted');\n</code></pre>\n\n<p><strong>UserOfData.js</strong></p>\n\n<pre><code>ErrorSvc({id: 1, json: '{attr: \"not-valid\"}'});\n</code></pre>\n\n<p>This would return:</p>\n\n<pre><code>['Invalid Json Syntax - key not double quoted']\n</code></pre>\n\n<p>While</p>\n\n<pre><code>ErrorSvc({id: 1, json: '{\"attr\": \"not-valid\"}'});\n</code></pre>\n\n<p>This would return</p>\n\n<pre><code>[]\n</code></pre>\n"
},
{
"answer_id": 57385857,
"author": "NVRM",
"author_id": 2494754,
"author_profile": "https://Stackoverflow.com/users/2494754",
"pm_score": 3,
"selected": false,
"text": "<p>Based on the title, we can generate strong <a href=\"https://en.wikipedia.org/wiki/Secure_Hash_Algorithms\" rel=\"nofollow noreferrer\">SHA</a> hashes, in a browser context, it can be used to generate a unique hash from an object, an array of params, a string, or whatever.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>async function H(m) {\n const msgUint8 = new TextEncoder().encode(m) \n const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8) \n const hashArray = Array.from(new Uint8Array(hashBuffer)) \n const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('')\n console.log(hashHex)\n}\n\n/* Examples ----------------------- */\nH(\"An obscure ....\")\nH(JSON.stringify( {\"hello\" : \"world\"} ))\nH(JSON.stringify( [54,51,54,47] ))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>The above output in my browser, it should be equal for you too:</p>\n<pre><code>bf1cf3fe6975fe382ab392ec1dd42009380614be03d489f23601c11413cfca2b\n93a23971a914e5eacbf0a8d25154cda309c3c1c72fbb9914d47c60f3cb681588\nd2f209e194045604a3b15bdfd7502898a0e848e4603c5a818bd01da69c00ad19\n</code></pre>\n<p>Supported algos:</p>\n<pre><code>SHA-1 (but don't use this in cryptographic applications)\nSHA-256\nSHA-384\nSHA-512\n</code></pre>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest#Converting_a_digest_to_a_hex_string\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest#Converting_a_digest_to_a_hex_string</a></p>\n<hr />\n<p>However, for a simple FAST checksum hash function, made only for collision avoidance, see <strong>CRC32 (Content Redundancy Check)</strong></p>\n<p><a href=\"https://stackoverflow.com/questions/18638900/javascript-crc32\">JavaScript CRC32</a></p>\n<hr />\n<p>You might also be interested by this similar method to <a href=\"https://stackoverflow.com/a/56416039/2494754\">generate HMAC codes</a> via the web crypto api.</p>\n"
},
{
"answer_id": 60344292,
"author": "Nikolay Makhonin",
"author_id": 5221762,
"author_profile": "https://Stackoverflow.com/users/5221762",
"pm_score": 0,
"selected": false,
"text": "<p>Just use hidden secret property with the <code>defineProperty</code> <code>enumerable: false</code></p>\n\n<p>It work <a href=\"https://jsbench.me/wlk6wi04ph/1\" rel=\"nofollow noreferrer\">very fast</a>:</p>\n\n<ul>\n<li>The first read uniqueId: <strong>1,257,500 ops/s</strong></li>\n<li>All others: <strong>309,226,485 ops/s</strong></li>\n</ul>\n\n<pre><code>var nextObjectId = 1\nfunction getNextObjectId() {\n return nextObjectId++\n}\n\nvar UNIQUE_ID_PROPERTY_NAME = '458d576952bc489ab45e98ac7f296fd9'\nfunction getObjectUniqueId(object) {\n if (object == null) {\n return null\n }\n\n var id = object[UNIQUE_ID_PROPERTY_NAME]\n\n if (id != null) {\n return id\n }\n\n if (Object.isFrozen(object)) {\n return null\n }\n\n var uniqueId = getNextObjectId()\n Object.defineProperty(object, UNIQUE_ID_PROPERTY_NAME, {\n enumerable: false,\n configurable: false,\n writable: false,\n value: uniqueId,\n })\n\n return uniqueId\n}\n</code></pre>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16492/"
] |
Basically, I'm trying to create an object of unique objects, a set. I had the brilliant idea of just using a JavaScript object with objects for the property names. Such as,
```
set[obj] = true;
```
This works, up to a point. It works great with string and numbers, but with other objects, they all seem to "hash" to the same value and access the same property. Is there some kind of way I can generate a unique hash value for an object? How do strings and numbers do it, can I override the same behavior?
|
JavaScript objects can only use strings as keys (anything else is converted to a string).
You could, alternatively, maintain an array which indexes the objects in question, and use its index string as a reference to the object. Something like this:
```
var ObjectReference = [];
ObjectReference.push(obj);
set['ObjectReference.' + ObjectReference.indexOf(obj)] = true;
```
Obviously it's a little verbose, but you could write a couple of methods that handle it and get and set all willy nilly.
Edit:
>
> Your guess is fact -- this is defined behaviour in JavaScript -- specifically a toString conversion occurs meaning that you can can define your own toString function on the object that will be used as the property name. - olliej
>
>
>
This brings up another interesting point; you can define a toString method on the objects you want to hash, and that can form their hash identifier.
|
194,852 |
<p>Consider a database table holding names, with three rows:</p>
<pre><code>Peter
Paul
Mary
</code></pre>
<p>Is there an easy way to turn this into a single string of <code>Peter, Paul, Mary</code>?</p>
|
[
{
"answer_id": 194858,
"author": "Manu",
"author_id": 2133,
"author_profile": "https://Stackoverflow.com/users/2133",
"pm_score": 2,
"selected": false,
"text": "<p>One way you could do it in SQL Server would be to return the table content as XML (for XML raw), convert the result to a string and then replace the tags with \", \".</p>\n"
},
{
"answer_id": 194875,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 7,
"selected": false,
"text": "<p>In MySQL, there is a function, <a href=\"https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat\" rel=\"noreferrer\">GROUP_CONCAT()</a>, which allows you to concatenate the values from multiple rows. Example:</p>\n<pre><code>SELECT 1 AS a, GROUP_CONCAT(name ORDER BY name ASC SEPARATOR ', ') AS people \nFROM users \nWHERE id IN (1,2,3) \nGROUP BY a\n</code></pre>\n"
},
{
"answer_id": 194886,
"author": "Dana",
"author_id": 7856,
"author_profile": "https://Stackoverflow.com/users/7856",
"pm_score": 5,
"selected": false,
"text": "<p>I don't have access to a SQL Server at home, so I'm guess at the syntax here, but it's more or less:</p>\n\n<pre><code>DECLARE @names VARCHAR(500)\n\nSELECT @names = @names + ' ' + Name\nFROM Names\n</code></pre>\n"
},
{
"answer_id": 194887,
"author": "Chris Shaffer",
"author_id": 6744,
"author_profile": "https://Stackoverflow.com/users/6744",
"pm_score": 10,
"selected": false,
"text": "<blockquote>\n <p><strong>This answer may return <a href=\"https://stackoverflow.com/questions/15138593/nvarchar-concatenation-index-nvarcharmax-inexplicable-behavior/15163136#15163136\">unexpected results</a> For consistent results, use one of the FOR XML PATH methods detailed in other answers.</strong></p>\n</blockquote>\n\n<p>Use <code>COALESCE</code>:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>DECLARE @Names VARCHAR(8000) \nSELECT @Names = COALESCE(@Names + ', ', '') + Name \nFROM People\n</code></pre>\n\n<p>Just some explanation (since this answer seems to get relatively regular views):</p>\n\n<ul>\n<li>Coalesce is really just a helpful cheat that accomplishes two things: </li>\n</ul>\n\n<p>1) No need to initialize <code>@Names</code> with an empty string value. </p>\n\n<p>2) No need to strip off an extra separator at the end.</p>\n\n<ul>\n<li>The solution above will give incorrect results if a row has a <em>NULL</em> Name value (if there is a <em>NULL</em>, the <em>NULL</em> will make <code>@Names</code> <em>NULL</em> after that row, and the next row will start over as an empty string again. Easily fixed with one of two solutions:</li>\n</ul>\n\n<pre class=\"lang-sql prettyprint-override\"><code>DECLARE @Names VARCHAR(8000) \nSELECT @Names = COALESCE(@Names + ', ', '') + Name\nFROM People\nWHERE Name IS NOT NULL\n</code></pre>\n\n<p>or:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>DECLARE @Names VARCHAR(8000) \nSELECT @Names = COALESCE(@Names + ', ', '') + \n ISNULL(Name, 'N/A')\nFROM People\n</code></pre>\n\n<p>Depending on what behavior you want (the first option just filters <em>NULL</em>s out, the second option keeps them in the list with a marker message [replace 'N/A' with whatever is appropriate for you]).</p>\n"
},
{
"answer_id": 198333,
"author": "gbn",
"author_id": 27535,
"author_profile": "https://Stackoverflow.com/users/27535",
"pm_score": 3,
"selected": false,
"text": "<pre><code>DECLARE @Names VARCHAR(8000)\nSELECT @name = ''\nSELECT @Names = @Names + ',' + Names FROM People\nSELECT SUBSTRING(2, @Names, 7998)\n</code></pre>\n\n<p>This puts the stray comma at the beginning.</p>\n\n<p>However, if you need other columns, or to CSV a child table you need to wrap this in a scalar user defined field (UDF).</p>\n\n<p>You can use XML path as a correlated subquery in the SELECT clause too (but I'd have to wait until I go back to work because Google doesn't do work stuff at home :-)</p>\n"
},
{
"answer_id": 545672,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 12,
"selected": true,
"text": "<p>If you are on SQL Server 2017 or Azure, see <a href=\"https://stackoverflow.com/a/42778050/1178676\">Mathieu Renda answer</a>.</p>\n<p>I had a similar issue when I was trying to join two tables with one-to-many relationships. In SQL 2005 I found that <code>XML PATH</code> method can handle the concatenation of the rows very easily.</p>\n<p>If there is a table called <code>STUDENTS</code></p>\n<pre><code>SubjectID StudentName\n---------- -------------\n1 Mary\n1 John\n1 Sam\n2 Alaina\n2 Edward\n</code></pre>\n<p>Result I expected was:</p>\n<pre><code>SubjectID StudentName\n---------- -------------\n1 Mary, John, Sam\n2 Alaina, Edward\n</code></pre>\n<p>I used the following <code>T-SQL</code>:</p>\n<pre><code>SELECT Main.SubjectID,\n LEFT(Main.Students,Len(Main.Students)-1) As "Students"\nFROM\n (\n SELECT DISTINCT ST2.SubjectID, \n (\n SELECT ST1.StudentName + ',' AS [text()]\n FROM dbo.Students ST1\n WHERE ST1.SubjectID = ST2.SubjectID\n ORDER BY ST1.SubjectID\n FOR XML PATH (''), TYPE\n ).value('text()[1]','nvarchar(max)') [Students]\n FROM dbo.Students ST2\n ) [Main]\n</code></pre>\n<p>You can do the same thing in a more compact way if you can concat the commas at the beginning and use <code>substring</code> to skip the first one so you don't need to do a sub-query:</p>\n<pre><code>SELECT DISTINCT ST2.SubjectID, \n SUBSTRING(\n (\n SELECT ','+ST1.StudentName AS [text()]\n FROM dbo.Students ST1\n WHERE ST1.SubjectID = ST2.SubjectID\n ORDER BY ST1.SubjectID\n FOR XML PATH (''), TYPE\n ).value('text()[1]','nvarchar(max)'), 2, 1000) [Students]\nFROM dbo.Students ST2\n</code></pre>\n"
},
{
"answer_id": 3672860,
"author": "teamchong",
"author_id": 442938,
"author_profile": "https://Stackoverflow.com/users/442938",
"pm_score": 8,
"selected": false,
"text": "<h2>In <a href=\"http://en.wikipedia.org/wiki/Microsoft_SQL_Server#SQL_Server_2005\" rel=\"noreferrer\">SQL Server 2005</a></h2>\n\n<pre><code>SELECT Stuff(\n (SELECT N', ' + Name FROM Names FOR XML PATH(''),TYPE)\n .value('text()[1]','nvarchar(max)'),1,2,N'')\n</code></pre>\n\n<hr>\n\n<h2>In SQL Server 2016</h2>\n\n<p>you can use the <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/queries/select-for-clause-transact-sql\" rel=\"noreferrer\">FOR JSON syntax</a></p>\n\n<p>i.e. </p>\n\n<pre><code>SELECT per.ID,\nEmails = JSON_VALUE(\n REPLACE(\n (SELECT _ = em.Email FROM Email em WHERE em.Person = per.ID FOR JSON PATH)\n ,'\"},{\"_\":\"',', '),'$[0]._'\n) \nFROM Person per\n</code></pre>\n\n<p>And the result will become</p>\n\n<pre><code>Id Emails\n1 [email protected]\n2 NULL\n3 [email protected], [email protected]\n</code></pre>\n\n<p>This will work even your data contains invalid XML characters</p>\n\n<p>the <code>'\"},{\"_\":\"'</code> is safe because if you data contain <code>'\"},{\"_\":\"',</code> it will be escaped to <code>\"},{\\\"_\\\":\\\"</code></p>\n\n<p>You can replace <code>', '</code> with any string separator</p>\n\n<hr>\n\n<h2>And in SQL Server 2017, Azure SQL Database</h2>\n\n<p>You can use the new <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql\" rel=\"noreferrer\">STRING_AGG function</a></p>\n"
},
{
"answer_id": 5558670,
"author": "jens frandsen",
"author_id": 693784,
"author_profile": "https://Stackoverflow.com/users/693784",
"pm_score": 9,
"selected": false,
"text": "<p>One method not yet shown via the <code>XML</code> <code>data()</code> command in SQL Server is:</p>\n<p>Assume a table called NameList with one column called FName,</p>\n<pre><code>SELECT FName + ', ' AS 'data()'\nFROM NameList\nFOR XML PATH('')\n</code></pre>\n<p>returns:</p>\n<pre><code>"Peter, Paul, Mary, "\n</code></pre>\n<p>Only the extra comma must be dealt with.</p>\n<p>As adopted from @NReilingh's comment, you can use the following method to remove the trailing comma. Assuming the same table and column names:</p>\n<pre><code>STUFF(REPLACE((SELECT '#!' + LTRIM(RTRIM(FName)) AS 'data()' FROM NameList\nFOR XML PATH('')),' #!',', '), 1, 2, '') as Brands\n</code></pre>\n"
},
{
"answer_id": 5580166,
"author": "Diwakar",
"author_id": 696690,
"author_profile": "https://Stackoverflow.com/users/696690",
"pm_score": 4,
"selected": false,
"text": "<p>Using XML helped me in getting rows separated with commas. For the extra comma we can use the replace function of SQL Server. Instead of adding a comma, use of the AS 'data()' will concatenate the rows with spaces, which later can be replaced with commas as the syntax written below.</p>\n\n<pre><code>REPLACE(\n (select FName AS 'data()' from NameList for xml path(''))\n , ' ', ', ') \n</code></pre>\n"
},
{
"answer_id": 5834020,
"author": "Hans Bluh",
"author_id": 731334,
"author_profile": "https://Stackoverflow.com/users/731334",
"pm_score": 1,
"selected": false,
"text": "<p>Use this:</p>\n<pre><code>ISNULL(SUBSTRING(REPLACE((select ',' FName as 'data()' from NameList for xml path('')), ' ,',', '), 2, 300), '') 'MyList'\n</code></pre>\n<p>Where the "300" could be any width taking into account the maximum number of items you think will show up.</p>\n"
},
{
"answer_id": 6231011,
"author": "user762952",
"author_id": 762952,
"author_profile": "https://Stackoverflow.com/users/762952",
"pm_score": 3,
"selected": false,
"text": "<p>In Oracle, it is <code>wm_concat</code>. I believe this function is available in the <a href=\"http://en.wikipedia.org/wiki/Oracle_10g\" rel=\"noreferrer\">10g release</a> and higher.</p>\n"
},
{
"answer_id": 6592636,
"author": "Vladimir Nesterovsky",
"author_id": 831007,
"author_profile": "https://Stackoverflow.com/users/831007",
"pm_score": 3,
"selected": false,
"text": "<p>I usually use select like this to concatenate strings in SQL Server:</p>\n\n<pre><code>with lines as \n( \n select \n row_number() over(order by id) id, -- id is a line id\n line -- line of text.\n from\n source -- line source\n), \nresult_lines as \n( \n select \n id, \n cast(line as nvarchar(max)) line \n from \n lines \n where \n id = 1 \n union all \n select \n l.id, \n cast(r.line + N', ' + l.line as nvarchar(max))\n from \n lines l \n inner join \n result_lines r \n on \n l.id = r.id + 1 \n) \nselect top 1 \n line\nfrom\n result_lines\norder by\n id desc\n</code></pre>\n"
},
{
"answer_id": 6596590,
"author": "Yogesh Bhadauirya",
"author_id": 831537,
"author_profile": "https://Stackoverflow.com/users/831537",
"pm_score": 5,
"selected": false,
"text": "<p>In SQL Server 2005 and later, use the query below to concatenate the rows.</p>\n\n<pre><code>DECLARE @t table\n(\n Id int,\n Name varchar(10)\n)\nINSERT INTO @t\nSELECT 1,'a' UNION ALL\nSELECT 1,'b' UNION ALL\nSELECT 2,'c' UNION ALL\nSELECT 2,'d' \n\nSELECT ID,\nstuff(\n(\n SELECT ','+ [Name] FROM @t WHERE Id = t.Id FOR XML PATH('')\n),1,1,'') \nFROM (SELECT DISTINCT ID FROM @t ) t\n</code></pre>\n"
},
{
"answer_id": 6850549,
"author": "Pramod",
"author_id": 249496,
"author_profile": "https://Stackoverflow.com/users/249496",
"pm_score": 3,
"selected": false,
"text": "<p>If you want to deal with nulls you can do it by adding a where clause or add another COALESCE around the first one.</p>\n\n<pre><code>DECLARE @Names VARCHAR(8000) \nSELECT @Names = COALESCE(COALESCE(@Names + ', ', '') + Name, @Names) FROM People\n</code></pre>\n"
},
{
"answer_id": 8206256,
"author": "Oleg Sakharov",
"author_id": 87057,
"author_profile": "https://Stackoverflow.com/users/87057",
"pm_score": 3,
"selected": false,
"text": "<p>I really liked elegancy of <a href=\"https://stackoverflow.com/questions/194852/concatenate-many-rows-into-a-single-text-string/194886#194886\">Dana's answer</a> and just wanted to make it complete.</p>\n<pre><code>DECLARE @names VARCHAR(MAX)\nSET @names = ''\n\nSELECT @names = @names + ', ' + Name FROM Names\n\n-- Deleting last two symbols (', ')\nSET @sSql = LEFT(@sSql, LEN(@sSql) - 1)\n</code></pre>\n"
},
{
"answer_id": 9127273,
"author": "Daniel Reis",
"author_id": 959570,
"author_profile": "https://Stackoverflow.com/users/959570",
"pm_score": 4,
"selected": false,
"text": "<p>A ready-to-use solution, with no extra commas:</p>\n\n<pre><code>select substring(\n (select ', '+Name AS 'data()' from Names for xml path(''))\n ,3, 255) as \"MyList\"\n</code></pre>\n\n<p>An empty list will result in NULL value.\nUsually you will insert the list into a table column or program variable: adjust the 255 max length to your need.</p>\n\n<p>(Diwakar and Jens Frandsen provided good answers, but need improvement.)</p>\n"
},
{
"answer_id": 9621167,
"author": "Alex",
"author_id": 265877,
"author_profile": "https://Stackoverflow.com/users/265877",
"pm_score": 6,
"selected": false,
"text": "<p>Oracle 11g Release 2 supports the LISTAGG function. Documentation <a href=\"http://www.oracle-base.com/articles/misc/StringAggregationTechniques.php\" rel=\"noreferrer\">here</a>.</p>\n\n<pre><code>COLUMN employees FORMAT A50\n\nSELECT deptno, LISTAGG(ename, ',') WITHIN GROUP (ORDER BY ename) AS employees\nFROM emp\nGROUP BY deptno;\n\n DEPTNO EMPLOYEES\n---------- --------------------------------------------------\n 10 CLARK,KING,MILLER\n 20 ADAMS,FORD,JONES,SCOTT,SMITH\n 30 ALLEN,BLAKE,JAMES,MARTIN,TURNER,WARD\n\n3 rows selected.\n</code></pre>\n\n<h2>Warning</h2>\n\n<p>Be careful implementing this function if there is possibility of the resulting string going over 4000 characters. It will throw an exception. If that's the case then you need to either handle the exception or roll your own function that prevents the joined string from going over 4000 characters.</p>\n"
},
{
"answer_id": 11891963,
"author": "jmoreno",
"author_id": 234954,
"author_profile": "https://Stackoverflow.com/users/234954",
"pm_score": 5,
"selected": false,
"text": "<p>A recursive <a href=\"https://en.wikipedia.org/wiki/Hierarchical_and_recursive_queries_in_SQL#Common_table_expression\" rel=\"nofollow noreferrer\">CTE</a> solution was suggested, but no code was provided. The code below is an example of a recursive CTE.</p>\n<p>Note that although the results match the question, the data doesn't <em>quite</em> match the given description, as I assume that you really want to be doing this on groups of rows, not all rows in the table. Changing it to match all rows in the table is left as an exercise for the reader.</p>\n<pre><code>;WITH basetable AS (\n SELECT\n id,\n CAST(name AS VARCHAR(MAX)) name,\n ROW_NUMBER() OVER (Partition BY id ORDER BY seq) rw,\n COUNT(*) OVER (Partition BY id) recs\n FROM (VALUES\n (1, 'Johnny', 1),\n (1, 'M', 2),\n (2, 'Bill', 1),\n (2, 'S.', 4),\n (2, 'Preston', 5),\n (2, 'Esq.', 6),\n (3, 'Ted', 1),\n (3, 'Theodore', 2),\n (3, 'Logan', 3),\n (4, 'Peter', 1),\n (4, 'Paul', 2),\n (4, 'Mary', 3)\n ) g (id, name, seq)\n),\nrCTE AS (\n SELECT recs, id, name, rw\n FROM basetable\n WHERE rw = 1\n\n UNION ALL\n\n SELECT b.recs, r.ID, r.name +', '+ b.name name, r.rw + 1\n FROM basetable b\n INNER JOIN rCTE r ON b.id = r.id AND b.rw = r.rw + 1\n)\nSELECT name\nFROM rCTE\nWHERE recs = rw AND ID=4\nOPTION (MAXRECURSION 101)\n</code></pre>\n"
},
{
"answer_id": 11892100,
"author": "hgmnz",
"author_id": 165452,
"author_profile": "https://Stackoverflow.com/users/165452",
"pm_score": 6,
"selected": false,
"text": "<p>PostgreSQL arrays are awesome. Example:</p>\n<p>Create some test data:</p>\n<pre class=\"lang-none prettyprint-override\"><code>postgres=# \\c test\nYou are now connected to database "test" as user "hgimenez".\ntest=# create table names (name text);\nCREATE TABLE\ntest=# insert into names (name) values ('Peter'), ('Paul'), ('Mary');\nINSERT 0 3\ntest=# select * from names;\n name\n-------\n Peter\n Paul\n Mary\n(3 rows)\n</code></pre>\n<p>Aggregate them in an array:</p>\n<pre class=\"lang-none prettyprint-override\"><code>test=# select array_agg(name) from names;\n array_agg\n-------------------\n {Peter,Paul,Mary}\n(1 row)\n</code></pre>\n<p>Convert the array to a comma-delimited string:</p>\n<pre class=\"lang-none prettyprint-override\"><code>test=# select array_to_string(array_agg(name), ', ') from names;\n array_to_string\n-------------------\n Peter, Paul, Mary\n(1 row)\n</code></pre>\n<p>DONE</p>\n<p>Since PostgreSQL 9.0 it is even easier, quoting from deleted answer by "horse with no name":</p>\n<pre><code>select string_agg(name, ',') \nfrom names;\n</code></pre>\n"
},
{
"answer_id": 12647157,
"author": "Priti Getkewar Joshi",
"author_id": 1653179,
"author_profile": "https://Stackoverflow.com/users/1653179",
"pm_score": 2,
"selected": false,
"text": "<p>There are a couple of ways in Oracle:</p>\n<pre><code> create table name\n (first_name varchar2(30));\n\n insert into name values ('Peter');\n insert into name values ('Paul');\n insert into name values ('Mary');\n</code></pre>\n<p>Solution is 1:</p>\n<pre><code> select substr(max(sys_connect_by_path (first_name, ',')),2) from (select rownum r, first_name from name ) n start with r=1 connect by prior r+1=r\n o/p=> Peter,Paul,Mary\n</code></pre>\n<p>Solution is 2:</p>\n<pre><code> select rtrim(xmlagg (xmlelement (e, first_name || ',')).extract ('//text()'), ',') first_name from name\n o/p=> Peter,Paul,Mary\n</code></pre>\n"
},
{
"answer_id": 16526394,
"author": "ZeroK",
"author_id": 1535863,
"author_profile": "https://Stackoverflow.com/users/1535863",
"pm_score": 3,
"selected": false,
"text": "<p>For Oracle DBs, see this question: <a href=\"https://stackoverflow.com/questions/1076011/how-can-multiple-rows-be-concatenated-into-one-in-oracle-without-creating-a-stor\">How can multiple rows be concatenated into one in Oracle without creating a stored procedure?</a></p>\n\n<p>The best answer appears to be by @Emmanuel, using the built-in LISTAGG() function, available in Oracle 11g Release 2 and later.</p>\n\n<pre><code>SELECT question_id,\n LISTAGG(element_id, ',') WITHIN GROUP (ORDER BY element_id)\nFROM YOUR_TABLE;\nGROUP BY question_id\n</code></pre>\n\n<p>as @user762952 pointed out, and according to Oracle's documentation <a href=\"http://www.oracle-base.com/articles/misc/string-aggregation-techniques.php\" rel=\"nofollow noreferrer\">http://www.oracle-base.com/articles/misc/string-aggregation-techniques.php</a>, the WM_CONCAT() function is also an option. It seems stable, but Oracle explicitly recommends against using it for any application SQL, so use at your own risk.</p>\n\n<p>Other than that, you will have to write your own function; the Oracle document above has a guide on how to do that.</p>\n"
},
{
"answer_id": 19584555,
"author": "endo64",
"author_id": 333153,
"author_profile": "https://Stackoverflow.com/users/333153",
"pm_score": 3,
"selected": false,
"text": "<p>This can be useful too</p>\n\n<pre><code>create table #test (id int,name varchar(10))\n--use separate inserts on older versions of SQL Server\ninsert into #test values (1,'Peter'), (1,'Paul'), (1,'Mary'), (2,'Alex'), (3,'Jack')\n\nDECLARE @t VARCHAR(255)\nSELECT @t = ISNULL(@t + ',' + name, name) FROM #test WHERE id = 1\nselect @t\ndrop table #test\n</code></pre>\n\n<p>returns</p>\n\n<pre><code>Peter,Paul,Mary\n</code></pre>\n"
},
{
"answer_id": 20009988,
"author": "topchef",
"author_id": 59470,
"author_profile": "https://Stackoverflow.com/users/59470",
"pm_score": 2,
"selected": false,
"text": "<p>This method applies to the <a href=\"https://en.wikipedia.org/wiki/Teradata#Technology_and_products\" rel=\"nofollow noreferrer\">Teradata</a> Aster database only as it uses its NPATH function.</p>\n<p>Again, we have table Students</p>\n<pre><code>SubjectID StudentName\n---------- -------------\n1 Mary\n1 John\n1 Sam\n2 Alaina\n2 Edward\n</code></pre>\n<p>Then with NPATH it is just single SELECT:</p>\n<pre><code>SELECT * FROM npath(\n ON Students\n PARTITION BY SubjectID\n ORDER BY StudentName\n MODE(nonoverlapping)\n PATTERN('A*')\n SYMBOLS(\n 'true' as A\n )\n RESULT(\n FIRST(SubjectID of A) as SubjectID,\n ACCUMULATE(StudentName of A) as StudentName\n )\n);\n</code></pre>\n<p>Result:</p>\n<pre><code>SubjectID StudentName\n---------- -------------\n1 [John, Mary, Sam]\n2 [Alaina, Edward]\n</code></pre>\n"
},
{
"answer_id": 20324790,
"author": "Max Tkachenko",
"author_id": 1393791,
"author_profile": "https://Stackoverflow.com/users/1393791",
"pm_score": 1,
"selected": false,
"text": "<p>With the 'TABLE' type it is extremely easy. Let's imagine that your table is called <code>Students</code> and it has column <code>name</code>.</p>\n<pre><code>declare @rowsCount INT\ndeclare @i INT = 1\ndeclare @names varchar(max) = ''\n\nDECLARE @MyTable TABLE\n(\n Id int identity,\n Name varchar(500)\n)\ninsert into @MyTable select name from Students\nset @rowsCount = (select COUNT(Id) from @MyTable)\n\nwhile @i < @rowsCount\nbegin\n set @names = @names + ', ' + (select name from @MyTable where Id = @i)\n set @i = @i + 1\nend\nselect @names\n</code></pre>\n<p>This example was tested with <a href=\"https://en.wikipedia.org/wiki/History_of_Microsoft_SQL_Server#SQL_Server_2008\" rel=\"nofollow noreferrer\">SQL Server 2008</a> R2.</p>\n"
},
{
"answer_id": 28476945,
"author": "Rapunzo",
"author_id": 141800,
"author_profile": "https://Stackoverflow.com/users/141800",
"pm_score": 3,
"selected": false,
"text": "<p>To avoid null values you can use CONCAT()</p>\n\n<pre><code>DECLARE @names VARCHAR(500)\nSELECT @names = CONCAT(@names, ' ', name) \nFROM Names\nselect @names\n</code></pre>\n"
},
{
"answer_id": 29740361,
"author": "Hamid Bahmanabady",
"author_id": 1527921,
"author_profile": "https://Stackoverflow.com/users/1527921",
"pm_score": -1,
"selected": false,
"text": "<pre><code> declare @phone varchar(max)='' \n select @phone=@phone + mobileno +',' from members\n select @phone\n</code></pre>\n"
},
{
"answer_id": 30114419,
"author": "Nizam",
"author_id": 358614,
"author_profile": "https://Stackoverflow.com/users/358614",
"pm_score": 3,
"selected": false,
"text": "<p>This answer will require some privilege on the server to work.</p>\n<p><a href=\"https://msdn.microsoft.com/pt-br/library/ms189524.aspx\" rel=\"nofollow noreferrer\">Assemblies</a> are a good option for you. There are a lot of sites that explain how to create it. The one I think is very well explained is this <a href=\"http://www.mssqltips.com/sqlservertip/2022/concat-aggregates-sql-server-clr-function/\" rel=\"nofollow noreferrer\">one</a>.</p>\n<p>If you want, I have already created the assembly, and it is possible to download the DLL file <a href=\"https://1drv.ms/u/s!AsecqFu3CHaYtZMLaMJ7Y2z70xU7nQ?e=CssM8J\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>Once you have downloaded it, you will need to run the following script in your SQL Server:</p>\n<pre><code>EXEC sp_configure 'show advanced options', 1\nRECONFIGURE;\nEXEC sp_configure 'clr strict security', 1;\nRECONFIGURE;\n\nCREATE Assembly concat_assembly\n AUTHORIZATION dbo\n FROM '<PATH TO Concat.dll IN SERVER>'\n WITH PERMISSION_SET = SAFE;\nGO\n\nCREATE AGGREGATE dbo.concat (\n\n @Value NVARCHAR(MAX)\n , @Delimiter NVARCHAR(4000)\n\n) RETURNS NVARCHAR(MAX)\nEXTERNAL Name concat_assembly.[Concat.Concat];\nGO\n\nsp_configure 'clr enabled', 1;\nRECONFIGURE\n</code></pre>\n<p>Observe that the path to assembly may be accessible to server. Since you have successfully done all the steps, you can use the function like:</p>\n<pre><code>SELECT dbo.Concat(field1, ',')\nFROM Table1\n</code></pre>\n<hr />\n<p>Since <a href=\"https://en.wikipedia.org/wiki/History_of_Microsoft_SQL_Server#SQL_Server_2017\" rel=\"nofollow noreferrer\">SQL Server 2017</a> it is possible to use the <a href=\"https://learn.microsoft.com/pt-br/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-ver15\" rel=\"nofollow noreferrer\">STRING_AGG</a> function.</p>\n"
},
{
"answer_id": 31557028,
"author": "user1767754",
"author_id": 1767754,
"author_profile": "https://Stackoverflow.com/users/1767754",
"pm_score": 3,
"selected": false,
"text": "<p><strong>MySQL complete example:</strong></p>\n<p>We have users who can have much data and we want to have an output, where we can see all users' data in a list:</p>\n<p><strong>Result:</strong></p>\n<pre><code>___________________________\n| id | rowList |\n|-------------------------|\n| 0 | 6, 9 |\n| 1 | 1,2,3,4,5,7,8,1 |\n|_________________________|\n</code></pre>\n<p><strong>Table Setup:</strong></p>\n<pre><code>CREATE TABLE `Data` (\n `id` int(11) NOT NULL,\n `user_id` int(11) NOT NULL\n) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1;\n\n\nINSERT INTO `Data` (`id`, `user_id`) VALUES\n(1, 1),\n(2, 1),\n(3, 1),\n(4, 1),\n(5, 1),\n(6, 0),\n(7, 1),\n(8, 1),\n(9, 0),\n(10, 1);\n\n\nCREATE TABLE `User` (\n `id` int(11) NOT NULL\n) ENGINE=InnoDB DEFAULT CHARSET=latin1;\n\n\nINSERT INTO `User` (`id`) VALUES\n(0),\n(1);\n</code></pre>\n<p><strong>Query:</strong></p>\n<pre><code>SELECT User.id, GROUP_CONCAT(Data.id ORDER BY Data.id) AS rowList FROM User LEFT JOIN Data ON User.id = Data.user_id GROUP BY User.id\n</code></pre>\n"
},
{
"answer_id": 36419425,
"author": "Pedram",
"author_id": 1156018,
"author_profile": "https://Stackoverflow.com/users/1156018",
"pm_score": 6,
"selected": false,
"text": "<p>Use <em><strong>COALESCE</strong></em> - <a href=\"https://msdn.microsoft.com/en-IN/library/ms190349.aspx\" rel=\"noreferrer\">Learn more from here</a></p>\n<p><em>For an example:</em></p>\n<blockquote>\n<p>102</p>\n<p>103</p>\n<p>104</p>\n</blockquote>\n<p>Then write the below code in SQL Server,</p>\n<pre><code>Declare @Numbers AS Nvarchar(MAX) -- It must not be MAX if you have few numbers\nSELECT @Numbers = COALESCE(@Numbers + ',', '') + Number\nFROM TableName where Number IS NOT NULL\n\nSELECT @Numbers\n</code></pre>\n<p>The output would be:</p>\n<pre><code>102,103,104\n</code></pre>\n"
},
{
"answer_id": 37036438,
"author": "Mike Barlow - BarDev",
"author_id": 92166,
"author_profile": "https://Stackoverflow.com/users/92166",
"pm_score": 4,
"selected": false,
"text": "<p>With the other answers, the person reading the answer must be aware of a specific domain table such as vehicle or student. The table must be created and populated with data to test a solution.</p>\n\n<p>Below is an example that uses SQL Server \"Information_Schema.Columns\" table. By using this solution, no tables need to be created or data added. This example creates a comma separated list of column names for all tables in the database.</p>\n\n<pre><code>SELECT\n Table_Name\n ,STUFF((\n SELECT ',' + Column_Name\n FROM INFORMATION_SCHEMA.Columns Columns\n WHERE Tables.Table_Name = Columns.Table_Name\n ORDER BY Column_Name\n FOR XML PATH ('')), 1, 1, ''\n )Columns\nFROM INFORMATION_SCHEMA.Columns Tables\nGROUP BY TABLE_NAME \n</code></pre>\n"
},
{
"answer_id": 37459266,
"author": "Muhammad Bilal",
"author_id": 1415927,
"author_profile": "https://Stackoverflow.com/users/1415927",
"pm_score": 2,
"selected": false,
"text": "<pre><code>SELECT PageContent = Stuff(\n ( SELECT PageContent\n FROM dbo.InfoGuide\n WHERE CategoryId = @CategoryId\n AND SubCategoryId = @SubCategoryId\n for xml path(''), type\n ).value('.[1]','nvarchar(max)'),\n 1, 1, '')\nFROM dbo.InfoGuide info\n</code></pre>\n"
},
{
"answer_id": 37578420,
"author": "Graeme",
"author_id": 832552,
"author_profile": "https://Stackoverflow.com/users/832552",
"pm_score": 3,
"selected": false,
"text": "<h3>SQL Server 2005 or later</h3>\n<pre><code>CREATE TABLE dbo.Students\n(\n StudentId INT\n , Name VARCHAR(50)\n , CONSTRAINT PK_Students PRIMARY KEY (StudentId)\n);\n\nCREATE TABLE dbo.Subjects\n(\n SubjectId INT\n , Name VARCHAR(50)\n , CONSTRAINT PK_Subjects PRIMARY KEY (SubjectId)\n);\n\nCREATE TABLE dbo.Schedules\n(\n StudentId INT\n , SubjectId INT\n , CONSTRAINT PK__Schedule PRIMARY KEY (StudentId, SubjectId)\n , CONSTRAINT FK_Schedule_Students FOREIGN KEY (StudentId) REFERENCES dbo.Students (StudentId)\n , CONSTRAINT FK_Schedule_Subjects FOREIGN KEY (SubjectId) REFERENCES dbo.Subjects (SubjectId)\n);\n\nINSERT dbo.Students (StudentId, Name) VALUES\n (1, 'Mary')\n , (2, 'John')\n , (3, 'Sam')\n , (4, 'Alaina')\n , (5, 'Edward')\n;\n\nINSERT dbo.Subjects (SubjectId, Name) VALUES\n (1, 'Physics')\n , (2, 'Geography')\n , (3, 'French')\n , (4, 'Gymnastics')\n;\n\nINSERT dbo.Schedules (StudentId, SubjectId) VALUES\n (1, 1) --Mary, Physics\n , (2, 1) --John, Physics\n , (3, 1) --Sam, Physics\n , (4, 2) --Alaina, Geography\n , (5, 2) --Edward, Geography\n;\n\nSELECT\n sub.SubjectId\n , sub.Name AS [SubjectName]\n , ISNULL( x.Students, '') AS Students\nFROM\n dbo.Subjects sub\n OUTER APPLY\n (\n SELECT\n CASE ROW_NUMBER() OVER (ORDER BY stu.Name) WHEN 1 THEN '' ELSE ', ' END\n + stu.Name\n FROM\n dbo.Students stu\n INNER JOIN dbo.Schedules sch\n ON stu.StudentId = sch.StudentId\n WHERE\n sch.SubjectId = sub.SubjectId\n ORDER BY\n stu.Name\n FOR XML PATH('')\n ) x (Students)\n;\n</code></pre>\n"
},
{
"answer_id": 37738837,
"author": "Glen",
"author_id": 1828277,
"author_profile": "https://Stackoverflow.com/users/1828277",
"pm_score": 2,
"selected": false,
"text": "<p>Not that I have done any analysis on performance as my list had less than 10 items but I was amazed after looking through the 30 odd answers I still had a twist on a similar answer already given similar to using COALESCE for a single group list and didn't even have to set my variable (defaults to NULL anyhow) and it assumes all entries in my source data table are non blank:</p>\n<pre><code>DECLARE @MyList VARCHAR(1000), @Delimiter CHAR(2) = ', '\nSELECT @MyList = CASE WHEN @MyList > '' THEN @MyList + @Delimiter ELSE '' END + FieldToConcatenate FROM MyData\n</code></pre>\n<p>I am sure COALESCE internally uses the same idea.\nLet’s hope Microsoft don't change this on me.</p>\n"
},
{
"answer_id": 40619710,
"author": "Tigerjz32",
"author_id": 1556242,
"author_profile": "https://Stackoverflow.com/users/1556242",
"pm_score": 5,
"selected": false,
"text": "<p>You need to create a variable that will hold your final result and select into it, like so.</p>\n\n<h1>Easiest Solution</h1>\n\n<pre><code>DECLARE @char VARCHAR(MAX);\n\nSELECT @char = COALESCE(@char + ', ' + [column], [column]) \nFROM [table];\n\nPRINT @char;\n</code></pre>\n"
},
{
"answer_id": 40719033,
"author": "Henrik Fransas",
"author_id": 2435919,
"author_profile": "https://Stackoverflow.com/users/2435919",
"pm_score": 5,
"selected": false,
"text": "<p>In SQL Server vNext this will be built in with the STRING_AGG function. Read more about it in <em><a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql\" rel=\"nofollow noreferrer\">STRING_AGG (Transact-SQL)</a></em>.</p>\n"
},
{
"answer_id": 42778050,
"author": "Mathieu Renda",
"author_id": 3506362,
"author_profile": "https://Stackoverflow.com/users/3506362",
"pm_score": 10,
"selected": false,
"text": "<h3>SQL Server 2017+ and SQL Azure: STRING_AGG</h3>\n<p>Starting with the next version of SQL Server, we can finally concatenate across rows without having to resort to any variable or XML witchery.</p>\n<p><a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql\" rel=\"noreferrer\">STRING_AGG (Transact-SQL)</a></p>\n<p><strong>Without grouping</strong></p>\n<pre><code>SELECT STRING_AGG(Name, ', ') AS Departments\nFROM HumanResources.Department;\n</code></pre>\n<p><strong>With grouping:</strong></p>\n<pre><code>SELECT GroupName, STRING_AGG(Name, ', ') AS Departments\nFROM HumanResources.Department\nGROUP BY GroupName;\n</code></pre>\n<p><strong>With grouping and sub-sorting</strong></p>\n<pre><code>SELECT GroupName, STRING_AGG(Name, ', ') WITHIN GROUP (ORDER BY Name ASC) AS Departments\nFROM HumanResources.Department\nGROUP BY GroupName;\n</code></pre>\n"
},
{
"answer_id": 47700428,
"author": "Shahbaz",
"author_id": 3273603,
"author_profile": "https://Stackoverflow.com/users/3273603",
"pm_score": 2,
"selected": false,
"text": "<p>Although it's too late, and already has many solutions. Here is simple solution for MySQL:</p>\n\n<pre><code>SELECT t1.id,\n GROUP_CONCAT(t1.id) ids\n FROM table t1 JOIN table t2 ON (t1.id = t2.id)\n GROUP BY t1.id\n</code></pre>\n"
},
{
"answer_id": 48435921,
"author": "Max Szczurek",
"author_id": 1208034,
"author_profile": "https://Stackoverflow.com/users/1208034",
"pm_score": 4,
"selected": false,
"text": "<pre><code>SELECT STUFF((SELECT ', ' + name FROM [table] FOR XML PATH('')), 1, 2, '')\n</code></pre>\n\n<p>Here's a sample:</p>\n\n<pre><code>DECLARE @t TABLE (name VARCHAR(10))\nINSERT INTO @t VALUES ('Peter'), ('Paul'), ('Mary')\nSELECT STUFF((SELECT ', ' + name FROM @t FOR XML PATH('')), 1, 2, '')\n--Peter, Paul, Mary\n</code></pre>\n"
},
{
"answer_id": 48803931,
"author": "Pooja Bhat",
"author_id": 5906392,
"author_profile": "https://Stackoverflow.com/users/5906392",
"pm_score": 2,
"selected": false,
"text": "<h2>Below is a simple PL/SQL procedure to implement the given scenario using \"basic loop\" and \"rownum\"</h2>\n\n<p>Table definition</p>\n\n<pre><code>CREATE TABLE \"NAMES\" (\"NAME\" VARCHAR2(10 BYTE))) ;\n</code></pre>\n\n<p>Let's insert values into this table</p>\n\n<pre><code>INSERT INTO NAMES VALUES('PETER');\nINSERT INTO NAMES VALUES('PAUL');\nINSERT INTO NAMES VALUES('MARY');\n</code></pre>\n\n<p>Procedure starts from here</p>\n\n<pre><code>DECLARE \n\nMAXNUM INTEGER;\nCNTR INTEGER := 1;\nC_NAME NAMES.NAME%TYPE;\nNSTR VARCHAR2(50);\n\nBEGIN\n\nSELECT MAX(ROWNUM) INTO MAXNUM FROM NAMES;\n\nLOOP\n\nSELECT NAME INTO C_NAME FROM \n(SELECT ROWNUM RW, NAME FROM NAMES ) P WHERE P.RW = CNTR;\n\nNSTR := NSTR ||','||C_NAME;\nCNTR := CNTR + 1;\nEXIT WHEN CNTR > MAXNUM;\n\nEND LOOP;\n\ndbms_output.put_line(SUBSTR(NSTR,2));\n\nEND;\n</code></pre>\n\n<p>Result</p>\n\n<pre><code>PETER,PAUL,MARY\n</code></pre>\n"
},
{
"answer_id": 49611871,
"author": "Ravi Pipaliya",
"author_id": 5608331,
"author_profile": "https://Stackoverflow.com/users/5608331",
"pm_score": 2,
"selected": false,
"text": "<p>Here is the complete solution to achieve this:</p>\n\n<pre><code>-- Table Creation\nCREATE TABLE Tbl\n( CustomerCode VARCHAR(50)\n, CustomerName VARCHAR(50)\n, Type VARCHAR(50)\n,Items VARCHAR(50)\n)\n\ninsert into Tbl\nSELECT 'C0001','Thomas','BREAKFAST','Milk'\nunion SELECT 'C0001','Thomas','BREAKFAST','Bread'\nunion SELECT 'C0001','Thomas','BREAKFAST','Egg'\nunion SELECT 'C0001','Thomas','LUNCH','Rice'\nunion SELECT 'C0001','Thomas','LUNCH','Fish Curry'\nunion SELECT 'C0001','Thomas','LUNCH','Lessy'\nunion SELECT 'C0002','JOSEPH','BREAKFAST','Bread'\nunion SELECT 'C0002','JOSEPH','BREAKFAST','Jam'\nunion SELECT 'C0002','JOSEPH','BREAKFAST','Tea'\nunion SELECT 'C0002','JOSEPH','Supper','Tea'\nunion SELECT 'C0002','JOSEPH','Brunch','Roti'\n\n-- function creation\nGO\nCREATE FUNCTION [dbo].[fn_GetItemsByType]\n( \n @CustomerCode VARCHAR(50)\n ,@Type VARCHAR(50)\n)\nRETURNS @ItemType TABLE ( Items VARCHAR(5000) )\nAS\nBEGIN\n\n INSERT INTO @ItemType(Items)\n SELECT STUFF((SELECT distinct ',' + [Items]\n FROM Tbl \n WHERE CustomerCode = @CustomerCode\n AND Type=@Type\n FOR XML PATH(''))\n ,1,1,'') as Items\n\n\n\n RETURN \nEND\n\nGO\n\n-- fianl Query\nDECLARE @cols AS NVARCHAR(MAX),\n @query AS NVARCHAR(MAX)\n\nselect @cols = STUFF((SELECT distinct ',' + QUOTENAME(Type) \n from Tbl\n FOR XML PATH(''), TYPE\n ).value('.', 'NVARCHAR(MAX)') \n ,1,1,'')\n\nset @query = 'SELECT CustomerCode,CustomerName,' + @cols + '\n from \n (\n select \n distinct CustomerCode\n ,CustomerName\n ,Type\n ,F.Items\n FROM Tbl T\n CROSS APPLY [fn_GetItemsByType] (T.CustomerCode,T.Type) F\n ) x\n pivot \n (\n max(Items)\n for Type in (' + @cols + ')\n ) p '\n\nexecute(@query) \n</code></pre>\n"
},
{
"answer_id": 51606514,
"author": "Esperento57",
"author_id": 3735690,
"author_profile": "https://Stackoverflow.com/users/3735690",
"pm_score": 1,
"selected": false,
"text": "<p>With a recursive query you can do it:</p>\n\n<pre><code>-- Create example table\nCREATE TABLE tmptable (NAME VARCHAR(30)) ;\n\n-- Insert example data\nINSERT INTO tmptable VALUES('PETER');\nINSERT INTO tmptable VALUES('PAUL');\nINSERT INTO tmptable VALUES('MARY');\n\n-- Recurse query\nwith tblwithrank as (\nselect * , row_number() over(order by name) rang , count(*) over() NbRow\nfrom tmptable\n),\ntmpRecursive as (\nselect *, cast(name as varchar(2000)) as AllName from tblwithrank where rang=1\nunion all\nselect f0.*, cast(f0.name + ',' + f1.AllName as varchar(2000)) as AllName \nfrom tblwithrank f0 inner join tmpRecursive f1 on f0.rang=f1.rang +1 \n)\nselect AllName from tmpRecursive\nwhere rang=NbRow\n</code></pre>\n"
},
{
"answer_id": 55816724,
"author": "Kemal AL GAZZAH",
"author_id": 6774506,
"author_profile": "https://Stackoverflow.com/users/6774506",
"pm_score": 0,
"selected": false,
"text": "<p>We can use RECUSRSIVITY, WITH CTE, union ALL as follows</p>\n\n<pre><code>declare @mytable as table(id int identity(1,1), str nvarchar(100))\ninsert into @mytable values('Peter'),('Paul'),('Mary')\n\ndeclare @myresult as table(id int,str nvarchar(max),ind int, R# int)\n\n;with cte as(select id,cast(str as nvarchar(100)) as str, cast(0 as int) ind from @mytable\nunion all\nselect t2.id,cast(t1.str+',' +t2.str as nvarchar(100)) ,t1.ind+1 from cte t1 inner join @mytable t2 on t2.id=t1.id+1)\ninsert into @myresult select *,row_number() over(order by ind) R# from cte\n\nselect top 1 str from @myresult order by R# desc\n</code></pre>\n"
},
{
"answer_id": 57517612,
"author": "asmgx",
"author_id": 1492229,
"author_profile": "https://Stackoverflow.com/users/1492229",
"pm_score": 3,
"selected": false,
"text": "<p>On top of <a href=\"https://stackoverflow.com/questions/194852/how-to-concatenate-text-from-multiple-rows-into-a-single-text-string-in-sql-serv/194887#194887\">Chris Shaffer's answer</a>:</p>\n<p>If your data may get repeated, such as</p>\n<pre><code>Tom\nAli\nJohn\nAli\nTom\nMike\n</code></pre>\n<p>Instead of having <code>Tom,Ali,John,Ali,Tom,Mike</code></p>\n<p>You can use DISTINCT to avoid duplicates and get <code>Tom,Ali,John,Mike</code>:</p>\n<pre><code>DECLARE @Names VARCHAR(8000)\nSELECT DISTINCT @Names = COALESCE(@Names + ',', '') + Name\nFROM People\nWHERE Name IS NOT NULL\nSELECT @Names\n</code></pre>\n"
},
{
"answer_id": 57956819,
"author": "Arash.Zandi",
"author_id": 3046588,
"author_profile": "https://Stackoverflow.com/users/3046588",
"pm_score": 4,
"selected": false,
"text": "<p>This worked for me (<strong>SQL Server 2016</strong>):</p>\n<pre><code>SELECT CarNamesString = STUFF((\n SELECT ',' + [Name]\n FROM tbl_cars\n FOR XML PATH('')\n ), 1, 1, '')\n</code></pre>\n<p>Here is the source: <a href=\"https://www.mytecbits.com/microsoft/sql-server/concatenate-multiple-rows-into-single-string\" rel=\"noreferrer\">https://www.mytecbits.com/</a></p>\n<p>And a solution for <strong>MySQL</strong> (since this page show up in Google for MySQL):</p>\n<pre><code>SELECT [Name],\n GROUP_CONCAT(DISTINCT [Name] SEPARATOR ',')\n FROM tbl_cars\n</code></pre>\n<p>From <a href=\"https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html#function_group-concat\" rel=\"noreferrer\">MySQL documentation</a>.</p>\n"
},
{
"answer_id": 64820174,
"author": "Amirreza mohammadi",
"author_id": 8508960,
"author_profile": "https://Stackoverflow.com/users/8508960",
"pm_score": 0,
"selected": false,
"text": "<p>First of all you should declare a table variable and fill it with your table data and after that, with a WHILE loop, select row one by one and add its value to a nvarchar(max) variable.</p>\n<pre><code> Go\n declare @temp table(\n title nvarchar(50)\n )\n insert into @temp(title)\n select p.Title from dbo.person p\n --\n declare @mainString nvarchar(max)\n set @mainString = '';\n --\n while ((select count(*) from @temp) != 0)\n begin\n declare @itemTitle nvarchar(50)\n set @itemTitle = (select top(1) t.Title from @temp t)\n \n if @mainString = ''\n begin\n set @mainString = @itemTitle\n end\n else\n begin\n set @mainString = concat(@mainString,',',@itemTitle)\n end\n \n delete top(1) from @temp\n \n end\n print @mainString\n</code></pre>\n"
},
{
"answer_id": 65716131,
"author": "panser",
"author_id": 3554624,
"author_profile": "https://Stackoverflow.com/users/3554624",
"pm_score": 2,
"selected": false,
"text": "<p>In PostgreSQL - <strong>array_agg</strong></p>\n<pre><code>SELECT array_to_string(array_agg(DISTINCT rolname), ',') FROM pg_catalog.pg_roles;\n</code></pre>\n<p>Or <strong>STRING_AGG</strong></p>\n<pre><code>SELECT STRING_AGG(rolname::text,',') FROM pg_catalog.pg_roles;\n</code></pre>\n"
},
{
"answer_id": 66944063,
"author": "sameer Ahmed",
"author_id": 4796661,
"author_profile": "https://Stackoverflow.com/users/4796661",
"pm_score": 5,
"selected": false,
"text": "<p>In <a href=\"https://en.wikipedia.org/wiki/History_of_Microsoft_SQL_Server#SQL_Server_2017\" rel=\"noreferrer\">SQL Server 2017</a> or later versions, you can use the STRING_AGG() function to generate <strong>comma-separated</strong> values. Please have a look below at one example.</p>\n<pre><code>SELECT\n VendorId, STRING_AGG(FirstName,',') UsersName\nFROM Users\nWHERE VendorId != 9\nGROUP BY VendorId\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/Z5m6r.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Z5m6r.png\" alt=\"Enter image description here\" /></a></p>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27109/"
] |
Consider a database table holding names, with three rows:
```
Peter
Paul
Mary
```
Is there an easy way to turn this into a single string of `Peter, Paul, Mary`?
|
If you are on SQL Server 2017 or Azure, see [Mathieu Renda answer](https://stackoverflow.com/a/42778050/1178676).
I had a similar issue when I was trying to join two tables with one-to-many relationships. In SQL 2005 I found that `XML PATH` method can handle the concatenation of the rows very easily.
If there is a table called `STUDENTS`
```
SubjectID StudentName
---------- -------------
1 Mary
1 John
1 Sam
2 Alaina
2 Edward
```
Result I expected was:
```
SubjectID StudentName
---------- -------------
1 Mary, John, Sam
2 Alaina, Edward
```
I used the following `T-SQL`:
```
SELECT Main.SubjectID,
LEFT(Main.Students,Len(Main.Students)-1) As "Students"
FROM
(
SELECT DISTINCT ST2.SubjectID,
(
SELECT ST1.StudentName + ',' AS [text()]
FROM dbo.Students ST1
WHERE ST1.SubjectID = ST2.SubjectID
ORDER BY ST1.SubjectID
FOR XML PATH (''), TYPE
).value('text()[1]','nvarchar(max)') [Students]
FROM dbo.Students ST2
) [Main]
```
You can do the same thing in a more compact way if you can concat the commas at the beginning and use `substring` to skip the first one so you don't need to do a sub-query:
```
SELECT DISTINCT ST2.SubjectID,
SUBSTRING(
(
SELECT ','+ST1.StudentName AS [text()]
FROM dbo.Students ST1
WHERE ST1.SubjectID = ST2.SubjectID
ORDER BY ST1.SubjectID
FOR XML PATH (''), TYPE
).value('text()[1]','nvarchar(max)'), 2, 1000) [Students]
FROM dbo.Students ST2
```
|
194,863 |
<p>I'm looking for some succinct, modern C# code to generate a random date between Jan 1 1995 and the current date.</p>
<p>I'm thinking some solution that utilizes Enumerable.Range somehow may make this more succinct.</p>
|
[
{
"answer_id": 194868,
"author": "friol",
"author_id": 23034,
"author_profile": "https://Stackoverflow.com/users/23034",
"pm_score": 2,
"selected": false,
"text": "<p>Start with a fixed date object (Jan 1, 1995), and add a random number of days with AddDays (obviusly, pay attention not surpassing the current date).</p>\n"
},
{
"answer_id": 194870,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 9,
"selected": true,
"text": "<pre><code>private Random gen = new Random();\nDateTime RandomDay()\n{\n DateTime start = new DateTime(1995, 1, 1);\n int range = (DateTime.Today - start).Days; \n return start.AddDays(gen.Next(range));\n}\n</code></pre>\n\n<p>For better performance if this will be called repeatedly, create the <code>start</code> and <code>gen</code> (and maybe even <code>range</code>) variables <em>outside</em> of the function.</p>\n"
},
{
"answer_id": 194992,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 5,
"selected": false,
"text": "<p>This is in slight response to Joel's comment about making a slighly more optimized version. Instead of returning a random date directly, why not return a generator function which can be called repeatedly to create a random date. </p>\n\n<pre><code>Func<DateTime> RandomDayFunc()\n{\n DateTime start = new DateTime(1995, 1, 1); \n Random gen = new Random(); \n int range = ((TimeSpan)(DateTime.Today - start)).Days; \n return () => start.AddDays(gen.Next(range));\n}\n</code></pre>\n"
},
{
"answer_id": 195050,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 3,
"selected": false,
"text": "<p>Well, if you gonna present alternate optimization, we can also go for an iterator:</p>\n\n<pre><code> static IEnumerable<DateTime> RandomDay()\n {\n DateTime start = new DateTime(1995, 1, 1);\n Random gen = new Random();\n int range = ((TimeSpan)(DateTime.Today - start)).Days;\n while (true)\n yield return start.AddDays(gen.Next(range)); \n}\n</code></pre>\n\n<p>you could use it like this:</p>\n\n<pre><code>int i=0;\nforeach(DateTime dt in RandomDay())\n{\n Console.WriteLine(dt);\n if (++i == 10)\n break;\n}\n</code></pre>\n"
},
{
"answer_id": 26263669,
"author": "prespic",
"author_id": 984081,
"author_profile": "https://Stackoverflow.com/users/984081",
"pm_score": 4,
"selected": false,
"text": "<p>I have taken @Joel Coehoorn answer and made the changes he adviced - put the variable out of the method and put all in class. Plus now the time is random too. Here is the result.</p>\n\n<pre><code>class RandomDateTime\n{\n DateTime start;\n Random gen;\n int range;\n\n public RandomDateTime()\n {\n start = new DateTime(1995, 1, 1);\n gen = new Random();\n range = (DateTime.Today - start).Days;\n }\n\n public DateTime Next()\n {\n return start.AddDays(gen.Next(range)).AddHours(gen.Next(0,24)).AddMinutes(gen.Next(0,60)).AddSeconds(gen.Next(0,60));\n }\n}\n</code></pre>\n\n<p>And example how to use to write 100 random DateTimes to console:</p>\n\n<pre><code>RandomDateTime date = new RandomDateTime();\nfor (int i = 0; i < 100; i++)\n{\n Console.WriteLine(date.Next());\n}\n</code></pre>\n"
},
{
"answer_id": 53300329,
"author": "Hamit Gündogdu",
"author_id": 3464638,
"author_profile": "https://Stackoverflow.com/users/3464638",
"pm_score": 0,
"selected": false,
"text": "<p>I am a bit late in to the game, but here is one solution which works fine:</p>\n\n<pre><code> void Main()\n {\n var dateResult = GetRandomDates(new DateTime(1995, 1, 1), DateTime.UtcNow, 100);\n foreach (var r in dateResult)\n Console.WriteLine(r);\n }\n\n public static IList<DateTime> GetRandomDates(DateTime startDate, DateTime maxDate, int range)\n {\n var randomResult = GetRandomNumbers(range).ToArray();\n\n var calculationValue = maxDate.Subtract(startDate).TotalMinutes / int.MaxValue;\n var dateResults = randomResult.Select(s => startDate.AddMinutes(s * calculationValue)).ToList();\n return dateResults;\n }\n\n public static IEnumerable<int> GetRandomNumbers(int size)\n {\n var data = new byte[4];\n using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider(data))\n {\n for (int i = 0; i < size; i++)\n {\n rng.GetBytes(data);\n\n var value = BitConverter.ToInt32(data, 0);\n yield return value < 0 ? value * -1 : value;\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 60612579,
"author": "BernardV",
"author_id": 3324415,
"author_profile": "https://Stackoverflow.com/users/3324415",
"pm_score": 0,
"selected": false,
"text": "<p>Small method that returns a random date as string, based on some simple input parameters. Built based on variations from the above answers:</p>\n\n<pre><code>public string RandomDate(int startYear = 1960, string outputDateFormat = \"yyyy-MM-dd\")\n{\n DateTime start = new DateTime(startYear, 1, 1);\n Random gen = new Random(Guid.NewGuid().GetHashCode());\n int range = (DateTime.Today - start).Days;\n return start.AddDays(gen.Next(range)).ToString(outputDateFormat);\n}\n</code></pre>\n"
},
{
"answer_id": 65782552,
"author": "Ben",
"author_id": 7471204,
"author_profile": "https://Stackoverflow.com/users/7471204",
"pm_score": -1,
"selected": false,
"text": "<p>Useful extension based of @Jeremy Thompson's solution</p>\n<pre><code>public static class RandomExtensions\n{\n public static DateTime Next(this Random random, DateTime start, DateTime? end = null)\n {\n end ??= new DateTime();\n int range = (end.Value - start).Days;\n return start.AddDays(random.Next(range));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 69634338,
"author": "user16789193",
"author_id": 16789193,
"author_profile": "https://Stackoverflow.com/users/16789193",
"pm_score": 1,
"selected": false,
"text": "<pre><code>Random rnd = new Random();\nDateTime datetoday = DateTime.Now;\n\nint rndYear = rnd.Next(1995, datetoday.Year);\nint rndMonth = rnd.Next(1, 12);\nint rndDay = rnd.Next(1, 31);\n\nDateTime generateDate = new DateTime(rndYear, rndMonth, rndDay);\nConsole.WriteLine(generateDate);\n</code></pre>\n<p>//this maybe is not the best method but is fast and easy to understand</p>\n"
},
{
"answer_id": 73559337,
"author": "Hefaistos68",
"author_id": 198310,
"author_profile": "https://Stackoverflow.com/users/198310",
"pm_score": 0,
"selected": false,
"text": "<p>One more solution to the problem, this time a class to which you provide a range you want the dates in. Its down to random minutes in the results.</p>\n<pre><code>/// <summary>\n/// A random date/time class that provides random dates within a given range\n/// </summary>\npublic class RandomDateTime\n{\n private readonly Random rng = new Random();\n private readonly int totalMinutes;\n private readonly DateTime startDateTime;\n\n /// <summary>\n /// Initializes a new instance of the <see cref="RandomDateTime"/> class.\n /// </summary>\n /// <param name="startDate">The start date.</param>\n /// <param name="endDate">The end date.</param>\n public RandomDateTime(DateTime startDate, DateTime endDate)\n {\n this.startDateTime = startDate;\n TimeSpan timeSpan = endDate - startDate;\n this.totalMinutes = (int)timeSpan.TotalMinutes;\n }\n\n /// <summary>\n /// Gets the next random datetime object within the range of startDate and endDate provided in the ctor\n /// </summary>\n /// <returns>A DateTime.</returns>\n public DateTime NextDateTime\n {\n get\n {\n TimeSpan newSpan = new TimeSpan(0, rng.Next(0, this.totalMinutes), 0);\n return this.startDateTime + newSpan;\n }\n }\n}\n</code></pre>\n<p>Use it like this to spit out 5 random dates between january 1st 2020 and december 31 2022:</p>\n<pre><code>RandomDateTime rdt = new RandomDateTime(DateTime.Parse("01/01/2020"), DateTime.Parse("31/12/2022"));\n\nfor (int i = 0; i < 5; i++)\n Debug.WriteLine(rdt.NextDateTime);\n</code></pre>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/194863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/536/"
] |
I'm looking for some succinct, modern C# code to generate a random date between Jan 1 1995 and the current date.
I'm thinking some solution that utilizes Enumerable.Range somehow may make this more succinct.
|
```
private Random gen = new Random();
DateTime RandomDay()
{
DateTime start = new DateTime(1995, 1, 1);
int range = (DateTime.Today - start).Days;
return start.AddDays(gen.Next(range));
}
```
For better performance if this will be called repeatedly, create the `start` and `gen` (and maybe even `range`) variables *outside* of the function.
|
194,869 |
<p>I am working on a project that does a large amount of hashing, signing, and both asymmetric and symmetric encryption. Since these steps have a significant effect on our performance and available load, I was wondering if there is a hardware based solution to offloading the work. </p>
<p>I have done some surfing to find out, and the only items I can find are dedicated to SSL based communications. I need a more generic solution that will allow me to speed up signing and encryption regardless of where it occurs. </p>
<p>Is it possible to adapt these SSL based solutions (maybe it's just marketing and it would be easy to re-use elsewhere)? Is there a good generic co-processor that can help out? </p>
<p>I need this on a Windows Server 2008 based box, but I would be interested in solutions on any platform.</p>
|
[
{
"answer_id": 194868,
"author": "friol",
"author_id": 23034,
"author_profile": "https://Stackoverflow.com/users/23034",
"pm_score": 2,
"selected": false,
"text": "<p>Start with a fixed date object (Jan 1, 1995), and add a random number of days with AddDays (obviusly, pay attention not surpassing the current date).</p>\n"
},
{
"answer_id": 194870,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 9,
"selected": true,
"text": "<pre><code>private Random gen = new Random();\nDateTime RandomDay()\n{\n DateTime start = new DateTime(1995, 1, 1);\n int range = (DateTime.Today - start).Days; \n return start.AddDays(gen.Next(range));\n}\n</code></pre>\n\n<p>For better performance if this will be called repeatedly, create the <code>start</code> and <code>gen</code> (and maybe even <code>range</code>) variables <em>outside</em> of the function.</p>\n"
},
{
"answer_id": 194992,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 5,
"selected": false,
"text": "<p>This is in slight response to Joel's comment about making a slighly more optimized version. Instead of returning a random date directly, why not return a generator function which can be called repeatedly to create a random date. </p>\n\n<pre><code>Func<DateTime> RandomDayFunc()\n{\n DateTime start = new DateTime(1995, 1, 1); \n Random gen = new Random(); \n int range = ((TimeSpan)(DateTime.Today - start)).Days; \n return () => start.AddDays(gen.Next(range));\n}\n</code></pre>\n"
},
{
"answer_id": 195050,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 3,
"selected": false,
"text": "<p>Well, if you gonna present alternate optimization, we can also go for an iterator:</p>\n\n<pre><code> static IEnumerable<DateTime> RandomDay()\n {\n DateTime start = new DateTime(1995, 1, 1);\n Random gen = new Random();\n int range = ((TimeSpan)(DateTime.Today - start)).Days;\n while (true)\n yield return start.AddDays(gen.Next(range)); \n}\n</code></pre>\n\n<p>you could use it like this:</p>\n\n<pre><code>int i=0;\nforeach(DateTime dt in RandomDay())\n{\n Console.WriteLine(dt);\n if (++i == 10)\n break;\n}\n</code></pre>\n"
},
{
"answer_id": 26263669,
"author": "prespic",
"author_id": 984081,
"author_profile": "https://Stackoverflow.com/users/984081",
"pm_score": 4,
"selected": false,
"text": "<p>I have taken @Joel Coehoorn answer and made the changes he adviced - put the variable out of the method and put all in class. Plus now the time is random too. Here is the result.</p>\n\n<pre><code>class RandomDateTime\n{\n DateTime start;\n Random gen;\n int range;\n\n public RandomDateTime()\n {\n start = new DateTime(1995, 1, 1);\n gen = new Random();\n range = (DateTime.Today - start).Days;\n }\n\n public DateTime Next()\n {\n return start.AddDays(gen.Next(range)).AddHours(gen.Next(0,24)).AddMinutes(gen.Next(0,60)).AddSeconds(gen.Next(0,60));\n }\n}\n</code></pre>\n\n<p>And example how to use to write 100 random DateTimes to console:</p>\n\n<pre><code>RandomDateTime date = new RandomDateTime();\nfor (int i = 0; i < 100; i++)\n{\n Console.WriteLine(date.Next());\n}\n</code></pre>\n"
},
{
"answer_id": 53300329,
"author": "Hamit Gündogdu",
"author_id": 3464638,
"author_profile": "https://Stackoverflow.com/users/3464638",
"pm_score": 0,
"selected": false,
"text": "<p>I am a bit late in to the game, but here is one solution which works fine:</p>\n\n<pre><code> void Main()\n {\n var dateResult = GetRandomDates(new DateTime(1995, 1, 1), DateTime.UtcNow, 100);\n foreach (var r in dateResult)\n Console.WriteLine(r);\n }\n\n public static IList<DateTime> GetRandomDates(DateTime startDate, DateTime maxDate, int range)\n {\n var randomResult = GetRandomNumbers(range).ToArray();\n\n var calculationValue = maxDate.Subtract(startDate).TotalMinutes / int.MaxValue;\n var dateResults = randomResult.Select(s => startDate.AddMinutes(s * calculationValue)).ToList();\n return dateResults;\n }\n\n public static IEnumerable<int> GetRandomNumbers(int size)\n {\n var data = new byte[4];\n using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider(data))\n {\n for (int i = 0; i < size; i++)\n {\n rng.GetBytes(data);\n\n var value = BitConverter.ToInt32(data, 0);\n yield return value < 0 ? value * -1 : value;\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 60612579,
"author": "BernardV",
"author_id": 3324415,
"author_profile": "https://Stackoverflow.com/users/3324415",
"pm_score": 0,
"selected": false,
"text": "<p>Small method that returns a random date as string, based on some simple input parameters. Built based on variations from the above answers:</p>\n\n<pre><code>public string RandomDate(int startYear = 1960, string outputDateFormat = \"yyyy-MM-dd\")\n{\n DateTime start = new DateTime(startYear, 1, 1);\n Random gen = new Random(Guid.NewGuid().GetHashCode());\n int range = (DateTime.Today - start).Days;\n return start.AddDays(gen.Next(range)).ToString(outputDateFormat);\n}\n</code></pre>\n"
},
{
"answer_id": 65782552,
"author": "Ben",
"author_id": 7471204,
"author_profile": "https://Stackoverflow.com/users/7471204",
"pm_score": -1,
"selected": false,
"text": "<p>Useful extension based of @Jeremy Thompson's solution</p>\n<pre><code>public static class RandomExtensions\n{\n public static DateTime Next(this Random random, DateTime start, DateTime? end = null)\n {\n end ??= new DateTime();\n int range = (end.Value - start).Days;\n return start.AddDays(random.Next(range));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 69634338,
"author": "user16789193",
"author_id": 16789193,
"author_profile": "https://Stackoverflow.com/users/16789193",
"pm_score": 1,
"selected": false,
"text": "<pre><code>Random rnd = new Random();\nDateTime datetoday = DateTime.Now;\n\nint rndYear = rnd.Next(1995, datetoday.Year);\nint rndMonth = rnd.Next(1, 12);\nint rndDay = rnd.Next(1, 31);\n\nDateTime generateDate = new DateTime(rndYear, rndMonth, rndDay);\nConsole.WriteLine(generateDate);\n</code></pre>\n<p>//this maybe is not the best method but is fast and easy to understand</p>\n"
},
{
"answer_id": 73559337,
"author": "Hefaistos68",
"author_id": 198310,
"author_profile": "https://Stackoverflow.com/users/198310",
"pm_score": 0,
"selected": false,
"text": "<p>One more solution to the problem, this time a class to which you provide a range you want the dates in. Its down to random minutes in the results.</p>\n<pre><code>/// <summary>\n/// A random date/time class that provides random dates within a given range\n/// </summary>\npublic class RandomDateTime\n{\n private readonly Random rng = new Random();\n private readonly int totalMinutes;\n private readonly DateTime startDateTime;\n\n /// <summary>\n /// Initializes a new instance of the <see cref="RandomDateTime"/> class.\n /// </summary>\n /// <param name="startDate">The start date.</param>\n /// <param name="endDate">The end date.</param>\n public RandomDateTime(DateTime startDate, DateTime endDate)\n {\n this.startDateTime = startDate;\n TimeSpan timeSpan = endDate - startDate;\n this.totalMinutes = (int)timeSpan.TotalMinutes;\n }\n\n /// <summary>\n /// Gets the next random datetime object within the range of startDate and endDate provided in the ctor\n /// </summary>\n /// <returns>A DateTime.</returns>\n public DateTime NextDateTime\n {\n get\n {\n TimeSpan newSpan = new TimeSpan(0, rng.Next(0, this.totalMinutes), 0);\n return this.startDateTime + newSpan;\n }\n }\n}\n</code></pre>\n<p>Use it like this to spit out 5 random dates between january 1st 2020 and december 31 2022:</p>\n<pre><code>RandomDateTime rdt = new RandomDateTime(DateTime.Parse("01/01/2020"), DateTime.Parse("31/12/2022"));\n\nfor (int i = 0; i < 5; i++)\n Debug.WriteLine(rdt.NextDateTime);\n</code></pre>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/194869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/71994/"
] |
I am working on a project that does a large amount of hashing, signing, and both asymmetric and symmetric encryption. Since these steps have a significant effect on our performance and available load, I was wondering if there is a hardware based solution to offloading the work.
I have done some surfing to find out, and the only items I can find are dedicated to SSL based communications. I need a more generic solution that will allow me to speed up signing and encryption regardless of where it occurs.
Is it possible to adapt these SSL based solutions (maybe it's just marketing and it would be easy to re-use elsewhere)? Is there a good generic co-processor that can help out?
I need this on a Windows Server 2008 based box, but I would be interested in solutions on any platform.
|
```
private Random gen = new Random();
DateTime RandomDay()
{
DateTime start = new DateTime(1995, 1, 1);
int range = (DateTime.Today - start).Days;
return start.AddDays(gen.Next(range));
}
```
For better performance if this will be called repeatedly, create the `start` and `gen` (and maybe even `range`) variables *outside* of the function.
|
194,890 |
<p>I have a large project that I want to start using visual studio 2005 to edit. I want to tell it "Here are all the files I want you to track, now get on with it" and have them displayed as a directory tree, for example:</p>
<pre><code>Folder 1
- File A
- File B
- File C
Folder 2
- Folder 3
- File X
- File Y
- File D
- File E
</code></pre>
<p>Right now it's just showing all the header files in one big list, and all the source files in one big list, which I find unhelpful. I also don't want to spend ages creating a folder in the project for each folder on the disk.</p>
<p>Is there any way I can get VS to show me a source tree of everything in the solution, organised by where it is on the actual disk?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 194897,
"author": "Manu",
"author_id": 2133,
"author_profile": "https://Stackoverflow.com/users/2133",
"pm_score": 3,
"selected": false,
"text": "<p>click on the 'show all files' icon in the solution explorer, then select the folders you want to include, right click and select 'include in project'.</p>\n"
},
{
"answer_id": 3599629,
"author": "crayor",
"author_id": 434800,
"author_profile": "https://Stackoverflow.com/users/434800",
"pm_score": 0,
"selected": false,
"text": "<p>To clairfy this: To import a source tree with all subfolders, represented in the VS Explorer View like it is on the filesystem, you have to create a new Solution via the menu entry\n<code>Datei >> Neu >> Projekt aus vorhandenem Code</code>\nwhich is the last entry in the <code>New...</code> menu in VS2005 Pro (german version) for example.</p>\n\n<p>This opens a wizard where you will find the mentioned <code>Show All Files</code> and <code>Select Folders</code> options.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/194890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13500/"
] |
I have a large project that I want to start using visual studio 2005 to edit. I want to tell it "Here are all the files I want you to track, now get on with it" and have them displayed as a directory tree, for example:
```
Folder 1
- File A
- File B
- File C
Folder 2
- Folder 3
- File X
- File Y
- File D
- File E
```
Right now it's just showing all the header files in one big list, and all the source files in one big list, which I find unhelpful. I also don't want to spend ages creating a folder in the project for each folder on the disk.
Is there any way I can get VS to show me a source tree of everything in the solution, organised by where it is on the actual disk?
Thanks.
|
click on the 'show all files' icon in the solution explorer, then select the folders you want to include, right click and select 'include in project'.
|
194,914 |
<p>What's the best way of adding spaces between strings</p>
<pre><code>myString = string.Concat("a"," ","b")
</code></pre>
<p>or</p>
<pre><code>myString = string.Concat("a",Chr(9),"b")
</code></pre>
<p>I am using stringbuilder to build an XML file and looking for something efficient.</p>
<p>Thanks</p>
<p>Edit ~ Language VB.NET</p>
|
[
{
"answer_id": 194916,
"author": "Razor",
"author_id": 17211,
"author_profile": "https://Stackoverflow.com/users/17211",
"pm_score": 3,
"selected": false,
"text": "<p>Create your XML file with the XmlDocument class. Your wasting your time creating a string from scratch.</p>\n"
},
{
"answer_id": 194918,
"author": "defeated",
"author_id": 16997,
"author_profile": "https://Stackoverflow.com/users/16997",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/57a79xd0.aspx\" rel=\"nofollow noreferrer\">String.Join</a> is a static method that can take the separator (in this case, \" \") and an array of strings.</p>\n\n<pre><code>string sentence = String.Join(\" \", new string[] { \"The\", \"quick\", \"brown\", \"fox\" });\n</code></pre>\n"
},
{
"answer_id": 194919,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<p>Definitely not Chr(9). Not everyone uses ascii, after all.</p>\n"
},
{
"answer_id": 194928,
"author": "defeated",
"author_id": 16997,
"author_profile": "https://Stackoverflow.com/users/16997",
"pm_score": 1,
"selected": false,
"text": "<p>As an alternative to the \"tranditional\" <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx\" rel=\"nofollow noreferrer\">XMLDocument</a> , if you're using .NET 3.5 and up, take a look at the new <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.aspx\" rel=\"nofollow noreferrer\">XDocument</a> / <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.aspx\" rel=\"nofollow noreferrer\">XElement</a> classes in LINQ.</p>\n\n<p>A good tutorial is here:</p>\n\n<p><a href=\"http://www.hookedonlinq.com/Print.aspx?Page=LINQtoXML5MinuteOverview\" rel=\"nofollow noreferrer\">http://www.hookedonlinq.com/Print.aspx?Page=LINQtoXML5MinuteOverview</a></p>\n"
},
{
"answer_id": 194940,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": true,
"text": "<p>Well, for a start, chr(9) is a tab character - you would want to use chr(32) to get a space.</p>\n\n<p>That said, the first option, <strong><code>string.Concat(\"a\",\" \",\"b\")</code></strong>, is a more readable one. I would be concentrating on getting your code functionally correct to start with. Optimization should always be a last step and targeted only to those areas that need it. In other words, you need a baseline to check your optimizations against.</p>\n\n<p>Far too many times, you optimize then find yourself having to change the code anyway, meaning that your optimization effort was wasted.</p>\n"
},
{
"answer_id": 194981,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 0,
"selected": false,
"text": "<p>The simplest way is to use an aggregate function to combine the elements.</p>\n\n<pre><code>string[] input = new string[]{\"a\", \"b\"};\nvar withSpaces = input.Aggregate( (x,y) => x + \" \" + );\n</code></pre>\n"
},
{
"answer_id": 195026,
"author": "DancesWithBamboo",
"author_id": 1334,
"author_profile": "https://Stackoverflow.com/users/1334",
"pm_score": 0,
"selected": false,
"text": "<p>I don't see where in the code example in the question there is a stringbuilder; but since you say you are using one; I would use:</p>\n\n<pre><code>sb.AppendFormat(\"{0} {1}\", a, b);\n</code></pre>\n"
},
{
"answer_id": 195364,
"author": "ICR",
"author_id": 214,
"author_profile": "https://Stackoverflow.com/users/214",
"pm_score": 1,
"selected": false,
"text": "<p>If you're concatenating a known number of strings it's probably better to just use + as the compiler translates it into a call to string.Concat anyway. So</p>\n\n<pre><code>s = a + \" \" + b\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>s = string.Concat(a, \" \", b)\n</code></pre>\n\n<p>But the first is a lot more readable. Though the usual caveat, StringBuilders are generally preferable when doing this in a loop.</p>\n\n<p>Using Chr(32) over \" \" will make no difference speed wise as in this case Chr(x) is translated at compile time in VB.Net (don't know if it always is, but on my machine it did) so you're just making it more difficult to read with no benifit. Chr is mainly there for backwards compatibility and is generally best used for defining characters outside of the printable range.</p>\n\n<p>That said, it's probably better to use one of the framework library to build XML unless it's a very small fragment.</p>\n"
},
{
"answer_id": 16684534,
"author": "Santosh Wavare",
"author_id": 2408154,
"author_profile": "https://Stackoverflow.com/users/2408154",
"pm_score": 1,
"selected": false,
"text": "<pre><code> Dim TestString As String\n' Returns a string with 10 spaces.\nTestString = Space(10)\n' Inserts 10 spaces between two strings.\nTestString = \"Hello\" & Space(10) & \"World\"\n</code></pre>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/194914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23667/"
] |
What's the best way of adding spaces between strings
```
myString = string.Concat("a"," ","b")
```
or
```
myString = string.Concat("a",Chr(9),"b")
```
I am using stringbuilder to build an XML file and looking for something efficient.
Thanks
Edit ~ Language VB.NET
|
Well, for a start, chr(9) is a tab character - you would want to use chr(32) to get a space.
That said, the first option, **`string.Concat("a"," ","b")`**, is a more readable one. I would be concentrating on getting your code functionally correct to start with. Optimization should always be a last step and targeted only to those areas that need it. In other words, you need a baseline to check your optimizations against.
Far too many times, you optimize then find yourself having to change the code anyway, meaning that your optimization effort was wasted.
|
194,930 |
<p>I got one big question.</p>
<p>I got a linq query to put it simply looks like this:</p>
<pre><code>from xx in table
where xx.uid.ToString().Contains(string[])
select xx
</code></pre>
<p>The values of the <code>string[]</code> array would be numbers like (1,45,20,10,etc...)</p>
<p>the Default for <code>.Contains</code> is <code>.Contains(string)</code>.</p>
<p>I need it to do this instead: <code>.Contains(string[])</code>...</p>
<p><strong>EDIT :</strong> One user suggested writing an extension class for <code>string[]</code>. I would like to learn how, but any one willing to point me in the right direction?</p>
<p><strong>EDIT :</strong> The uid would also be a number. That's why it is converted to a string.</p>
<p>Help anyone?</p>
|
[
{
"answer_id": 194939,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 2,
"selected": false,
"text": "<p>How about:</p>\n\n<pre><code>from xx in table\nwhere stringarray.Contains(xx.uid.ToString())\nselect xx\n</code></pre>\n"
},
{
"answer_id": 194970,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 2,
"selected": false,
"text": "<p>This is an example of one way of writing an extension method (note: I wouldn't use this for very large arrays; another data structure would be more appropriate...):</p>\n\n<pre><code>namespace StringExtensionMethods\n{\n public static class StringExtension\n {\n public static bool Contains(this string[] stringarray, string pat)\n {\n bool result = false;\n\n foreach (string s in stringarray)\n {\n if (s == pat)\n {\n result = true;\n break;\n }\n }\n\n return result;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 194972,
"author": "ctrlShiftBryan",
"author_id": 6161,
"author_profile": "https://Stackoverflow.com/users/6161",
"pm_score": 1,
"selected": false,
"text": "<p>I believe you could also do something like this.</p>\n\n<pre><code>from xx in table\nwhere (from yy in string[] \n select yy).Contains(xx.uid.ToString())\nselect xx\n</code></pre>\n"
},
{
"answer_id": 194974,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 7,
"selected": true,
"text": "<p>spoulson has it nearly right, but you need to create a <code>List<string></code> from <code>string[]</code> first. Actually a <code>List<int></code> would be better if uid is also <code>int</code>. <code>List<T></code> supports <code>Contains()</code>. Doing <code>uid.ToString().Contains(string[])</code> would imply that the uid as a string contains all of the values of the array as a substring??? Even if you did write the extension method the sense of it would be wrong. </p>\n\n<p><strong>[EDIT]</strong></p>\n\n<p>Unless you changed it around and wrote it for <code>string[]</code> as Mitch Wheat demonstrates, then you'd just be able to skip the conversion step. </p>\n\n<p><strong>[ENDEDIT]</strong> </p>\n\n<p>Here is what you want, if you don't do the extension method (unless you already have the collection of potential uids as ints -- then just use <code>List<int>()</code> instead). This uses the chained method syntax, which I think is cleaner, and\ndoes the conversion to int to ensure that the query can be used with more providers.</p>\n\n<pre><code>var uids = arrayofuids.Select(id => int.Parse(id)).ToList();\n\nvar selected = table.Where(t => uids.Contains(t.uid));\n</code></pre>\n"
},
{
"answer_id": 194975,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 5,
"selected": false,
"text": "<p>Try the following. </p>\n\n<pre><code>string input = \"someString\";\nstring[] toSearchFor = GetSearchStrings();\nvar containsAll = toSearchFor.All(x => input.Contains(x));\n</code></pre>\n"
},
{
"answer_id": 195628,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 5,
"selected": false,
"text": "<p>If you are truly looking to replicate <em>Contains</em>, but for an array, here is an <a href=\"http://msdn.microsoft.com/en-us/library/bb383977.aspx\" rel=\"noreferrer\">extension method</a> and sample code for usage:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ContainsAnyThingy\n{\n class Program\n {\n static void Main(string[] args)\n {\n string testValue = \"123345789\";\n\n //will print true\n Console.WriteLine(testValue.ContainsAny(\"123\", \"987\", \"554\")); \n\n //but so will this also print true\n Console.WriteLine(testValue.ContainsAny(\"1\", \"987\", \"554\"));\n Console.ReadKey();\n\n }\n }\n\n public static class StringExtensions\n {\n public static bool ContainsAny(this string str, params string[] values)\n {\n if (!string.IsNullOrEmpty(str) || values.Length > 0)\n {\n foreach (string value in values)\n {\n if(str.Contains(value))\n return true;\n }\n }\n\n return false;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 195674,
"author": "justin.m.chase",
"author_id": 12958,
"author_profile": "https://Stackoverflow.com/users/12958",
"pm_score": 0,
"selected": false,
"text": "<p>So am I assuming correctly that uid is a Unique Identifier (Guid)? Is this just an example of a possible scenario or are you really trying to find a guid that matches an array of strings?</p>\n\n<p>If this is true you may want to really rethink this whole approach, this seems like a really bad idea. You should probably be trying to match a Guid to a Guid</p>\n\n<pre><code>Guid id = new Guid(uid);\nvar query = from xx in table\n where xx.uid == id\n select xx;\n</code></pre>\n\n<p>I honestly can't imagine a scenario where matching a string array using \"contains\" to the contents of a Guid would be a good idea. For one thing, Contains() will not guarantee the order of numbers in the Guid so you could potentially match multiple items. Not to mention comparing guids this way would be way slower than just doing it directly.</p>\n"
},
{
"answer_id": 456594,
"author": "Gorkem Pacaci",
"author_id": 51749,
"author_profile": "https://Stackoverflow.com/users/51749",
"pm_score": 0,
"selected": false,
"text": "<p>You should write it the other way around, checking your priviliged user id list contains the id on that row of table:</p>\n\n<pre><code>string[] search = new string[] { \"2\", \"3\" };\nvar result = from x in xx where search.Contains(x.uid.ToString()) select x;\n</code></pre>\n\n<p>LINQ behaves quite bright here and converts it to a good SQL statement:</p>\n\n<pre><code>sp_executesql N'SELECT [t0].[uid]\nFROM [dbo].[xx] AS [t0]\nWHERE (CONVERT(NVarChar,[t0].[uid]))\nIN (@p0, @p1)',N'@p0 nvarchar(1),\n@p1 nvarchar(1)',@p0=N'2',@p1=N'3'\n</code></pre>\n\n<p>which basicly embeds the contents of the 'search' array into the sql query, and does the filtering with 'IN' keyword in SQL.</p>\n"
},
{
"answer_id": 1142232,
"author": "Brett Ryan",
"author_id": 140037,
"author_profile": "https://Stackoverflow.com/users/140037",
"pm_score": 0,
"selected": false,
"text": "<p>I managed to find a solution, but not a great one as it requires using AsEnumerable() which is going to return all results from the DB, fortunately I only have 1k records in the table so it isn't really noticable, but here goes.</p>\n\n<pre><code>var users = from u in (from u in ctx.Users\n where u.Mod_Status != \"D\"\n select u).AsEnumerable()\n where ar.All(n => u.FullName.IndexOf(n,\n StringComparison.InvariantCultureIgnoreCase) >= 0)\n select u;\n</code></pre>\n\n<hr>\n\n<p><em>My original post follows:</em></p>\n\n<blockquote>\n <p>How do you do the reverse? I want to\n do something like the following in\n entity framework.</p>\n\n<pre><code>string[] search = new string[] { \"John\", \"Doe\" };\nvar users = from u in ctx.Users\n from s in search\n where u.FullName.Contains(s)\n select u;\n</code></pre>\n \n <p>What I want is to find all users where\n their FullName contains all of the\n elements in `search'. I've tried a\n number of different ways, all of which\n haven't been working for me.</p>\n \n <p>I've also tried</p>\n\n<pre><code>var users = from u in ctx.Users select u;\nforeach (string s in search) {\n users = users.Where(u => u.FullName.Contains(s));\n}\n</code></pre>\n \n <p>This version only finds those that\n contain the last element in the search\n array.</p>\n</blockquote>\n"
},
{
"answer_id": 3072348,
"author": "beauXjames",
"author_id": 370605,
"author_profile": "https://Stackoverflow.com/users/370605",
"pm_score": 0,
"selected": false,
"text": "<p>The best solution I found was to go ahead and create a Table-Valued Function in SQL that produces the results, such as ::</p>\n\n<pre><code>CREATE function [dbo].[getMatches](@textStr nvarchar(50)) returns @MatchTbl table(\nFullname nvarchar(50) null,\nID nvarchar(50) null\n)\nas begin\ndeclare @SearchStr nvarchar(50);\nset @SearchStr = '%' + @textStr + '%';\ninsert into @MatchTbl \nselect (LName + ', ' + FName + ' ' + MName) AS FullName, ID = ID from employees where LName like @SearchStr;\nreturn;\nend\n\nGO\n\nselect * from dbo.getMatches('j')\n</code></pre>\n\n<p>Then, you simply drag the function into your LINQ.dbml designer and call it like you do your other objects. The LINQ even knows the columns of your stored function. I call it out like this ::</p>\n\n<pre><code>Dim db As New NobleLINQ\nDim LNameSearch As String = txt_searchLName.Text\nDim hlink As HyperLink\n\nFor Each ee In db.getMatches(LNameSearch)\n hlink = New HyperLink With {.Text = ee.Fullname & \"<br />\", .NavigateUrl = \"?ID=\" & ee.ID}\n pnl_results.Controls.Add(hlink)\nNext\n</code></pre>\n\n<p>Incredibly simple and really utlizes the power of SQL and LINQ in the application...and you can, of course, generate any table valued function you want for the same effects!</p>\n"
},
{
"answer_id": 3402358,
"author": "Lucas Cria",
"author_id": 410331,
"author_profile": "https://Stackoverflow.com/users/410331",
"pm_score": 0,
"selected": false,
"text": "<p>I believe that what you really want to do is:\nlet's imagine a scenario\nyou have two database\nand they have a table of products in common\nAnd you want to select products from the table \"A\" that id has in common with the \"B\"</p>\n\n<p>using the method contains would be too complicated to do this\nwhat we are doing is an intersection, and there is a method called intersection for that</p>\n\n<p>an example from msdn:\n<a href=\"http://msdn.microsoft.com/en-us/vcsharp/aa336761.aspx#intersect1\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/vcsharp/aa336761.aspx#intersect1</a></p>\n\n<p>int [] numbers = (0, 2, 4, 5, 6, 8, 9);\nint [] numbersB = (1, 3, 5, 7, 8);\nvar = commonNumbers numbersA.Intersect (numbersB);</p>\n\n<p>I think what you need is easily solved with intersection</p>\n"
},
{
"answer_id": 3611735,
"author": "knroc",
"author_id": 436215,
"author_profile": "https://Stackoverflow.com/users/436215",
"pm_score": -1,
"selected": false,
"text": "<pre><code>string[] stringArray = {1,45,20,10};\nfrom xx in table \nwhere stringArray.Contains(xx.uid.ToString()) \nselect xx\n</code></pre>\n"
},
{
"answer_id": 5813288,
"author": "JumpingJezza",
"author_id": 345659,
"author_profile": "https://Stackoverflow.com/users/345659",
"pm_score": 3,
"selected": false,
"text": "<p>Or if you already have the data in a list and prefer the other Linq format :)</p>\n\n<pre><code>List<string> uids = new List<string>(){\"1\", \"45\", \"20\", \"10\"};\nList<user> table = GetDataFromSomewhere();\n\nList<user> newTable = table.Where(xx => uids.Contains(xx.uid)).ToList();\n</code></pre>\n"
},
{
"answer_id": 9711404,
"author": "RJ Lohan",
"author_id": 897994,
"author_profile": "https://Stackoverflow.com/users/897994",
"pm_score": 4,
"selected": false,
"text": "<p>LINQ in .NET 4.0 has another option for you; the .Any() method;</p>\n\n<pre><code>string[] values = new[] { \"1\", \"2\", \"3\" };\nstring data = \"some string 1\";\nbool containsAny = values.Any(data.Contains);\n</code></pre>\n"
},
{
"answer_id": 11716734,
"author": "user1119399",
"author_id": 1119399,
"author_profile": "https://Stackoverflow.com/users/1119399",
"pm_score": 0,
"selected": false,
"text": "<pre><code>from xx in table\nwhere xx.uid.Split(',').Contains(string value )\nselect xx\n</code></pre>\n"
},
{
"answer_id": 11903169,
"author": "theRonny",
"author_id": 1048512,
"author_profile": "https://Stackoverflow.com/users/1048512",
"pm_score": 0,
"selected": false,
"text": "<p>Check this extension method:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\n\nnamespace ContainsAnyProgram\n{\n class Program\n {\n static void Main(string[] args)\n {\n const string iphoneAgent = \"Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like...\";\n\n var majorAgents = new[] { \"iPhone\", \"Android\", \"iPad\" };\n var minorAgents = new[] { \"Blackberry\", \"Windows Phone\" };\n\n // true\n Console.WriteLine(iphoneAgent.ContainsAny(majorAgents));\n\n // false\n Console.WriteLine(iphoneAgent.ContainsAny(minorAgents));\n Console.ReadKey();\n }\n }\n\n public static class StringExtensions\n {\n /// <summary>\n /// Replicates Contains but for an array\n /// </summary>\n /// <param name=\"str\">The string.</param>\n /// <param name=\"values\">The values.</param>\n /// <returns></returns>\n public static bool ContainsAny(this string str, params string[] values)\n {\n if (!string.IsNullOrEmpty(str) && values.Length > 0)\n return values.Any(str.Contains);\n\n return false;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 21749510,
"author": "NinjaNye",
"author_id": 611288,
"author_profile": "https://Stackoverflow.com/users/611288",
"pm_score": 2,
"selected": false,
"text": "<p><em>This is a late answer, but I believe it is still useful</em>.<br>\nI have created the <a href=\"http://nuget.org/packages/NinjaNye.SearchExtensions/\" rel=\"nofollow\">NinjaNye.SearchExtension</a> nuget package that can help solve this very problem.:</p>\n\n<pre><code>string[] terms = new[]{\"search\", \"term\", \"collection\"};\nvar result = context.Table.Search(terms, x => x.Name);\n</code></pre>\n\n<p>You could also search multiple string properties</p>\n\n<pre><code>var result = context.Table.Search(terms, x => x.Name, p.Description);\n</code></pre>\n\n<p>Or perform a <code>RankedSearch</code> which returns <code>IQueryable<IRanked<T>></code> which simply includes a property which shows how many times the search terms appeared:</p>\n\n<pre><code>//Perform search and rank results by the most hits\nvar result = context.Table.RankedSearch(terms, x => x.Name, x.Description)\n .OrderByDescending(r = r.Hits);\n</code></pre>\n\n<h2>There is a more extensive guide on the projects GitHub page: <a href=\"https://github.com/ninjanye/SearchExtensions\" rel=\"nofollow\">https://github.com/ninjanye/SearchExtensions</a></h2>\n\n<p>Hope this helps future visitors</p>\n"
},
{
"answer_id": 23124316,
"author": "kravits88",
"author_id": 1427220,
"author_profile": "https://Stackoverflow.com/users/1427220",
"pm_score": 2,
"selected": false,
"text": "<p>Linq extension method. Will work with any IEnumerable object:</p>\n\n<pre><code> public static bool ContainsAny<T>(this IEnumerable<T> Collection, IEnumerable<T> Values)\n {\n return Collection.Any(x=> Values.Contains(x));\n }\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>string[] Array1 = {\"1\", \"2\"};\nstring[] Array2 = {\"2\", \"4\"};\n\nbool Array2ItemsInArray1 = List1.ContainsAny(List2);\n</code></pre>\n"
},
{
"answer_id": 31893529,
"author": "Hedego",
"author_id": 1744906,
"author_profile": "https://Stackoverflow.com/users/1744906",
"pm_score": 0,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>var stringInput = \"test\";\nvar listOfNames = GetNames();\nvar result = from names in listOfNames where names.firstName.Trim().ToLower().Contains(stringInput.Trim().ToLower());\nselect names;\n</code></pre>\n"
},
{
"answer_id": 40073806,
"author": "EVONZ",
"author_id": 7027695,
"author_profile": "https://Stackoverflow.com/users/7027695",
"pm_score": -1,
"selected": false,
"text": "<pre><code>Dim stringArray() = {\"Pink Floyd\", \"AC/DC\"}\nDim inSQL = From alb In albums Where stringArray.Contains(alb.Field(Of String)(\"Artiste\").ToString())\nSelect New With\n {\n .Album = alb.Field(Of String)(\"Album\"),\n .Annee = StrReverse(alb.Field(Of Integer)(\"Annee\").ToString()) \n }\n</code></pre>\n"
},
{
"answer_id": 55021586,
"author": "Hari Lakkakula",
"author_id": 6601939,
"author_profile": "https://Stackoverflow.com/users/6601939",
"pm_score": 0,
"selected": false,
"text": "<pre><code>var SelecetdSteps = Context.FFTrakingSubCriticalSteps\n .Where(x => x.MeetingId == meetid)\n .Select(x => \n x.StepID \n );\n\n var crtiticalsteps = Context.MT_CriticalSteps.Where(x =>x.cropid==FFT.Cropid).Select(x=>new\n {\n StepID= x.crsid,\n x.Name,\n Checked=false\n\n });\n\n\n var quer = from ax in crtiticalsteps\n where (!SelecetdSteps.Contains(ax.StepID))\n select ax;\n</code></pre>\n"
},
{
"answer_id": 63497470,
"author": "William Peixoto",
"author_id": 10949845,
"author_profile": "https://Stackoverflow.com/users/10949845",
"pm_score": 0,
"selected": false,
"text": "<pre><code> string texto = "CALCA 40";\n string[] descpart = texto.Split(' ');\n\n var lst = (from item in db.InvItemsMaster\n where descpart.All(val => item.itm_desc.Contains(val))\n select item\n ).ToList();\n Console.WriteLine("ITM".PadRight(10) + "DESC".PadRight(50)+"EAN".PadRight(14));\n foreach(var i in lst)\n {\n \n\n Console.Write(i.itm_id.ToString().PadRight(10));\n Console.Write(i.itm_desc.ToString().PadRight(50));\n Console.WriteLine(i.itm_ean.ToString().PadRight(14));\n\n\n }\n\n Console.ReadKey();\n</code></pre>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/194930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7644/"
] |
I got one big question.
I got a linq query to put it simply looks like this:
```
from xx in table
where xx.uid.ToString().Contains(string[])
select xx
```
The values of the `string[]` array would be numbers like (1,45,20,10,etc...)
the Default for `.Contains` is `.Contains(string)`.
I need it to do this instead: `.Contains(string[])`...
**EDIT :** One user suggested writing an extension class for `string[]`. I would like to learn how, but any one willing to point me in the right direction?
**EDIT :** The uid would also be a number. That's why it is converted to a string.
Help anyone?
|
spoulson has it nearly right, but you need to create a `List<string>` from `string[]` first. Actually a `List<int>` would be better if uid is also `int`. `List<T>` supports `Contains()`. Doing `uid.ToString().Contains(string[])` would imply that the uid as a string contains all of the values of the array as a substring??? Even if you did write the extension method the sense of it would be wrong.
**[EDIT]**
Unless you changed it around and wrote it for `string[]` as Mitch Wheat demonstrates, then you'd just be able to skip the conversion step.
**[ENDEDIT]**
Here is what you want, if you don't do the extension method (unless you already have the collection of potential uids as ints -- then just use `List<int>()` instead). This uses the chained method syntax, which I think is cleaner, and
does the conversion to int to ensure that the query can be used with more providers.
```
var uids = arrayofuids.Select(id => int.Parse(id)).ToList();
var selected = table.Where(t => uids.Contains(t.uid));
```
|
194,944 |
<p>I am creating a lightweight editor in C# and would like to know the best method for converting a string into a nicely formatted XML string. I would hope that there's a public method in the C# library like "public bool FormatAsXml(string text, out string formattedXmlText)", but it couldn't be that easy, could it?</p>
<p>Very specifically, what would the method "SomeMethod" have to be that would produce the output below?</p>
<pre><code>string unformattedXml;
string formattedXml;
unformattedXml = "<?xml version=\"1.0\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>"
formattedXml = SomeMethod(unformattedXml);
Console.WriteLine(formattedXml);
</code></pre>
<p>Output:</p>
<pre><code><?xml version="1.0"?>
<book id="123">
<author>Lewis, C.S.</author>
<title>The Four Loves</title>
</book>
</code></pre>
|
[
{
"answer_id": 194951,
"author": "rp.",
"author_id": 2536,
"author_profile": "https://Stackoverflow.com/users/2536",
"pm_score": 0,
"selected": false,
"text": "<p>Is the string valid XML? Do you mean how can you convert an XML string into an XML document? If so, do this:</p>\n\n<pre><code>XmlDocument xml = new XmlDocument();\n\nxml.LoadXml( YourString );\n</code></pre>\n"
},
{
"answer_id": 194956,
"author": "defeated",
"author_id": 16997,
"author_profile": "https://Stackoverflow.com/users/16997",
"pm_score": 3,
"selected": false,
"text": "<p>It sounds like you want to load the XML into an <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmltextwriter.aspx\" rel=\"nofollow noreferrer\">XmlTextWriter</a> objects and set the Formatting and Indentation properties:</p>\n\n<pre><code>writer.Formatting = Formatting.Indented;\nwriter.Indentation = 1;\nwriter.IndentChar = '\\t';\n</code></pre>\n"
},
{
"answer_id": 194996,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 4,
"selected": false,
"text": "<p>Unfortunately no, it's not as easy as a FormatXMLForOutput method, this is Microsoft were talking about here ;) </p>\n\n<p>Anyway, as of .NET 2.0, the recommended approach is to use the XMlWriterSettingsClass to set up formatting, as opposed to setting properties directly on the XmlTextWriter object. <a href=\"http://msdn.microsoft.com/en-us/library/kkz7cs0d.aspx\" rel=\"noreferrer\">See this MSDN page</a> for more details. It says:</p>\n\n<p>\"In the .NET Framework version 2.0 release, the recommended practice is to create XmlWriter instances using the XmlWriter.Create method and the XmlWriterSettings class. This allows you to take full advantage of all the new features introduced in this release. For more information, see Creating XML Writers. \"</p>\n\n<p>Here is an example of the recommended approach:</p>\n\n<pre><code>XmlWriterSettings settings = new XmlWriterSettings();\nsettings.Indent = true;\nsettings.IndentChars = (\" \");\nusing (XmlWriter writer = XmlWriter.Create(\"books.xml\", settings))\n{\n // Write XML data.\n writer.WriteStartElement(\"book\");\n writer.WriteElementString(\"price\", \"19.95\");\n writer.WriteEndElement();\n writer.Flush();\n}\n</code></pre>\n"
},
{
"answer_id": 195060,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 4,
"selected": false,
"text": "<p>Using the new System.Xml.Linq namespace (System.Xml.Linq Assembly) you can use the following:</p>\n\n<pre><code>string theString = \"<nodeName>blah</nodeName>\";\nXDocument doc = XDocument.Parse(theString);\n</code></pre>\n\n<p>You can also create a fragment with:</p>\n\n<pre><code>string theString = \"<nodeName>blah</nodeName>\";\nXElement element = XElement.Parse(theString);\n</code></pre>\n\n<p>If the string is not yet XML, you can do something like this:</p>\n\n<pre><code>string theString = \"blah\";\n//creates <nodeName>blah</nodeName>\nXElement element = new XElement(XName.Get(\"nodeName\"), theString); \n</code></pre>\n\n<p>Something to note in this last example is that XElement will XML Encode the provided string.</p>\n\n<p>I highly recommend the new XLINQ classes. They are lighter weight, and easier to user that most of the existing XmlDocument-related types.</p>\n"
},
{
"answer_id": 195077,
"author": "sbeskur",
"author_id": 10446,
"author_profile": "https://Stackoverflow.com/users/10446",
"pm_score": 1,
"selected": false,
"text": "<p>If you just need to escape XML characters the following might be useful:</p>\n\n<pre><code>string myText = \"This & that > <> &lt;\";\nmyText = System.Security.SecurityElement.Escape(myText);\n</code></pre>\n"
},
{
"answer_id": 196242,
"author": "Wonko",
"author_id": 14842,
"author_profile": "https://Stackoverflow.com/users/14842",
"pm_score": 7,
"selected": true,
"text": "<pre><code>string unformattedXml = \"<?xml version=\\\"1.0\\\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>\";\nstring formattedXml = XElement.Parse(unformattedXml).ToString();\nConsole.WriteLine(formattedXml);\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code><book>\n <author>Lewis, C.S.</author>\n <title>The Four Loves</title>\n</book>\n</code></pre>\n\n<p>The Xml Declaration isn't output by ToString(), but it is by Save() ...</p>\n\n<pre><code> XElement.Parse(unformattedXml).Save(@\"C:\\doc.xml\");\n Console.WriteLine(File.ReadAllText(@\"C:\\doc.xml\"));\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\"?>\n<book>\n <author>Lewis, C.S.</author>\n <title>The Four Loves</title>\n</book>\n</code></pre>\n"
},
{
"answer_id": 196738,
"author": "JohnnyM",
"author_id": 27109,
"author_profile": "https://Stackoverflow.com/users/27109",
"pm_score": 2,
"selected": false,
"text": "<p>Jason's approach is the simplest. Here's the method: </p>\n\n<pre><code>private static string FormatXmlString(string xmlString)\n{\n System.Xml.Linq.XElement element = System.Xml.Linq.XElement.Parse(xmlString);\n return element.ToString();\n}\n</code></pre>\n"
},
{
"answer_id": 3475029,
"author": "Daniel Bradley",
"author_id": 366550,
"author_profile": "https://Stackoverflow.com/users/366550",
"pm_score": 3,
"selected": false,
"text": "<p>Assuming your're simply wanting to re-format an XML document to put new nodes on new lines and add indenting, then, if you are using .NET 3.5 or above then the best solution is to parse then output with XDocument, somthing like:</p>\n\n<pre><code>string unformattedXml;\nstring formattedXml;\n\nunformattedXml = \"<?xml version=\\\"1.0\\\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>\";\nformattedXml = System.Xml.Linq.XDocument.Parse(unformattedXml).ToString();\n\nConsole.WriteLine(formattedXml);\n</code></pre>\n\n<p>Neat hu?</p>\n\n<p>This should then re-format the XML nodes.</p>\n\n<p>To do this with previous versions of the framework requires a lot more legwork as there is no built in functions to re-calculate the whitespace.</p>\n\n<p>In fact, to do it using pre-Linq classes would be:</p>\n\n<pre><code>string unformattedXml;\nstring formattedXml;\n\nunformattedXml = \"<?xml version=\\\"1.0\\\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>\";\nSystem.Xml.XmlDocument doc = new System.Xml.XmlDocument();\ndoc.LoadXml(unformattedXml);\nSystem.Text.StringBuilder sb = new System.Text.StringBuilder();\nSystem.Xml.XmlWriter xw = System.Xml.XmlTextWriter.Create(sb, new System.Xml.XmlWriterSettings() { Indent = true });\ndoc.WriteTo(xw);\nxw.Flush();\nformattedXml = sb.ToString();\nConsole.WriteLine(formattedXml);\n</code></pre>\n"
},
{
"answer_id": 11421415,
"author": "radarbob",
"author_id": 463206,
"author_profile": "https://Stackoverflow.com/users/463206",
"pm_score": 0,
"selected": false,
"text": "<p><strong>System.Xml.Linq.XElement.ToString() Automatically Formats!</strong></p>\n\n<pre><code>XElement formattedXML = new XElement.Parse(unformattedXmlString);\nConsole.WriteLine(formattedXML.ToString());\n</code></pre>\n"
},
{
"answer_id": 16184805,
"author": "midspace",
"author_id": 294393,
"author_profile": "https://Stackoverflow.com/users/294393",
"pm_score": 1,
"selected": false,
"text": "<p>In Framework 4.0 it <strong>is</strong> simple.</p>\n\n<pre><code>var unformattedXml = \"<?xml version=\\\"1.0\\\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>\";\nvar xdoc = System.Xml.Linq.XDocument.Parse(unformattedXml);\nvar formattedXml = (xdoc.Declaration != null ? xdoc.Declaration + \"\\r\\n\" : \"\") + xdoc.ToString();\nConsole.WriteLine(formattedXml);\n</code></pre>\n\n<p>This adds in the required indentation, and <strong>maintains the Xml Declaration</strong>.</p>\n\n<pre><code><?xml version=\"1.0\"?>\n<book>\n <author>Lewis, C.S.</author>\n <title>The Four Loves</title>\n</book>\n</code></pre>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/194944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27109/"
] |
I am creating a lightweight editor in C# and would like to know the best method for converting a string into a nicely formatted XML string. I would hope that there's a public method in the C# library like "public bool FormatAsXml(string text, out string formattedXmlText)", but it couldn't be that easy, could it?
Very specifically, what would the method "SomeMethod" have to be that would produce the output below?
```
string unformattedXml;
string formattedXml;
unformattedXml = "<?xml version=\"1.0\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>"
formattedXml = SomeMethod(unformattedXml);
Console.WriteLine(formattedXml);
```
Output:
```
<?xml version="1.0"?>
<book id="123">
<author>Lewis, C.S.</author>
<title>The Four Loves</title>
</book>
```
|
```
string unformattedXml = "<?xml version=\"1.0\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>";
string formattedXml = XElement.Parse(unformattedXml).ToString();
Console.WriteLine(formattedXml);
```
Output:
```
<book>
<author>Lewis, C.S.</author>
<title>The Four Loves</title>
</book>
```
The Xml Declaration isn't output by ToString(), but it is by Save() ...
```
XElement.Parse(unformattedXml).Save(@"C:\doc.xml");
Console.WriteLine(File.ReadAllText(@"C:\doc.xml"));
```
Output:
```
<?xml version="1.0" encoding="utf-8"?>
<book>
<author>Lewis, C.S.</author>
<title>The Four Loves</title>
</book>
```
|
194,976 |
<p>I thought the web page designer screen in 2005 was mediocre until I used the one in 2008 which I think is bad. There is an interesting white paper here:</p>
<p><a href="http://www.west-wind.com/weblog/posts/484172.aspx" rel="nofollow noreferrer">http://www.west-wind.com/weblog/posts/484172.aspx</a></p>
<p>I've gotten very used to these WYSIWYG designers over the years, but I am looking now for a new way. </p>
<p>I make business web apps which call for data entry forms. I don't need anything particularly artistic, but I do need to be able to line up text boxes etc on input forms so that they lkook orderly and are convenient for the user. I use Telerik controls, and my skills with CSS are approaching passable.</p>
<p>People often mention that they don't use the designer, but they rarely state what approach they DO use.</p>
<p>What are some of the alternatives to using the VS designer? </p>
|
[
{
"answer_id": 194951,
"author": "rp.",
"author_id": 2536,
"author_profile": "https://Stackoverflow.com/users/2536",
"pm_score": 0,
"selected": false,
"text": "<p>Is the string valid XML? Do you mean how can you convert an XML string into an XML document? If so, do this:</p>\n\n<pre><code>XmlDocument xml = new XmlDocument();\n\nxml.LoadXml( YourString );\n</code></pre>\n"
},
{
"answer_id": 194956,
"author": "defeated",
"author_id": 16997,
"author_profile": "https://Stackoverflow.com/users/16997",
"pm_score": 3,
"selected": false,
"text": "<p>It sounds like you want to load the XML into an <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmltextwriter.aspx\" rel=\"nofollow noreferrer\">XmlTextWriter</a> objects and set the Formatting and Indentation properties:</p>\n\n<pre><code>writer.Formatting = Formatting.Indented;\nwriter.Indentation = 1;\nwriter.IndentChar = '\\t';\n</code></pre>\n"
},
{
"answer_id": 194996,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 4,
"selected": false,
"text": "<p>Unfortunately no, it's not as easy as a FormatXMLForOutput method, this is Microsoft were talking about here ;) </p>\n\n<p>Anyway, as of .NET 2.0, the recommended approach is to use the XMlWriterSettingsClass to set up formatting, as opposed to setting properties directly on the XmlTextWriter object. <a href=\"http://msdn.microsoft.com/en-us/library/kkz7cs0d.aspx\" rel=\"noreferrer\">See this MSDN page</a> for more details. It says:</p>\n\n<p>\"In the .NET Framework version 2.0 release, the recommended practice is to create XmlWriter instances using the XmlWriter.Create method and the XmlWriterSettings class. This allows you to take full advantage of all the new features introduced in this release. For more information, see Creating XML Writers. \"</p>\n\n<p>Here is an example of the recommended approach:</p>\n\n<pre><code>XmlWriterSettings settings = new XmlWriterSettings();\nsettings.Indent = true;\nsettings.IndentChars = (\" \");\nusing (XmlWriter writer = XmlWriter.Create(\"books.xml\", settings))\n{\n // Write XML data.\n writer.WriteStartElement(\"book\");\n writer.WriteElementString(\"price\", \"19.95\");\n writer.WriteEndElement();\n writer.Flush();\n}\n</code></pre>\n"
},
{
"answer_id": 195060,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 4,
"selected": false,
"text": "<p>Using the new System.Xml.Linq namespace (System.Xml.Linq Assembly) you can use the following:</p>\n\n<pre><code>string theString = \"<nodeName>blah</nodeName>\";\nXDocument doc = XDocument.Parse(theString);\n</code></pre>\n\n<p>You can also create a fragment with:</p>\n\n<pre><code>string theString = \"<nodeName>blah</nodeName>\";\nXElement element = XElement.Parse(theString);\n</code></pre>\n\n<p>If the string is not yet XML, you can do something like this:</p>\n\n<pre><code>string theString = \"blah\";\n//creates <nodeName>blah</nodeName>\nXElement element = new XElement(XName.Get(\"nodeName\"), theString); \n</code></pre>\n\n<p>Something to note in this last example is that XElement will XML Encode the provided string.</p>\n\n<p>I highly recommend the new XLINQ classes. They are lighter weight, and easier to user that most of the existing XmlDocument-related types.</p>\n"
},
{
"answer_id": 195077,
"author": "sbeskur",
"author_id": 10446,
"author_profile": "https://Stackoverflow.com/users/10446",
"pm_score": 1,
"selected": false,
"text": "<p>If you just need to escape XML characters the following might be useful:</p>\n\n<pre><code>string myText = \"This & that > <> &lt;\";\nmyText = System.Security.SecurityElement.Escape(myText);\n</code></pre>\n"
},
{
"answer_id": 196242,
"author": "Wonko",
"author_id": 14842,
"author_profile": "https://Stackoverflow.com/users/14842",
"pm_score": 7,
"selected": true,
"text": "<pre><code>string unformattedXml = \"<?xml version=\\\"1.0\\\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>\";\nstring formattedXml = XElement.Parse(unformattedXml).ToString();\nConsole.WriteLine(formattedXml);\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code><book>\n <author>Lewis, C.S.</author>\n <title>The Four Loves</title>\n</book>\n</code></pre>\n\n<p>The Xml Declaration isn't output by ToString(), but it is by Save() ...</p>\n\n<pre><code> XElement.Parse(unformattedXml).Save(@\"C:\\doc.xml\");\n Console.WriteLine(File.ReadAllText(@\"C:\\doc.xml\"));\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\"?>\n<book>\n <author>Lewis, C.S.</author>\n <title>The Four Loves</title>\n</book>\n</code></pre>\n"
},
{
"answer_id": 196738,
"author": "JohnnyM",
"author_id": 27109,
"author_profile": "https://Stackoverflow.com/users/27109",
"pm_score": 2,
"selected": false,
"text": "<p>Jason's approach is the simplest. Here's the method: </p>\n\n<pre><code>private static string FormatXmlString(string xmlString)\n{\n System.Xml.Linq.XElement element = System.Xml.Linq.XElement.Parse(xmlString);\n return element.ToString();\n}\n</code></pre>\n"
},
{
"answer_id": 3475029,
"author": "Daniel Bradley",
"author_id": 366550,
"author_profile": "https://Stackoverflow.com/users/366550",
"pm_score": 3,
"selected": false,
"text": "<p>Assuming your're simply wanting to re-format an XML document to put new nodes on new lines and add indenting, then, if you are using .NET 3.5 or above then the best solution is to parse then output with XDocument, somthing like:</p>\n\n<pre><code>string unformattedXml;\nstring formattedXml;\n\nunformattedXml = \"<?xml version=\\\"1.0\\\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>\";\nformattedXml = System.Xml.Linq.XDocument.Parse(unformattedXml).ToString();\n\nConsole.WriteLine(formattedXml);\n</code></pre>\n\n<p>Neat hu?</p>\n\n<p>This should then re-format the XML nodes.</p>\n\n<p>To do this with previous versions of the framework requires a lot more legwork as there is no built in functions to re-calculate the whitespace.</p>\n\n<p>In fact, to do it using pre-Linq classes would be:</p>\n\n<pre><code>string unformattedXml;\nstring formattedXml;\n\nunformattedXml = \"<?xml version=\\\"1.0\\\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>\";\nSystem.Xml.XmlDocument doc = new System.Xml.XmlDocument();\ndoc.LoadXml(unformattedXml);\nSystem.Text.StringBuilder sb = new System.Text.StringBuilder();\nSystem.Xml.XmlWriter xw = System.Xml.XmlTextWriter.Create(sb, new System.Xml.XmlWriterSettings() { Indent = true });\ndoc.WriteTo(xw);\nxw.Flush();\nformattedXml = sb.ToString();\nConsole.WriteLine(formattedXml);\n</code></pre>\n"
},
{
"answer_id": 11421415,
"author": "radarbob",
"author_id": 463206,
"author_profile": "https://Stackoverflow.com/users/463206",
"pm_score": 0,
"selected": false,
"text": "<p><strong>System.Xml.Linq.XElement.ToString() Automatically Formats!</strong></p>\n\n<pre><code>XElement formattedXML = new XElement.Parse(unformattedXmlString);\nConsole.WriteLine(formattedXML.ToString());\n</code></pre>\n"
},
{
"answer_id": 16184805,
"author": "midspace",
"author_id": 294393,
"author_profile": "https://Stackoverflow.com/users/294393",
"pm_score": 1,
"selected": false,
"text": "<p>In Framework 4.0 it <strong>is</strong> simple.</p>\n\n<pre><code>var unformattedXml = \"<?xml version=\\\"1.0\\\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>\";\nvar xdoc = System.Xml.Linq.XDocument.Parse(unformattedXml);\nvar formattedXml = (xdoc.Declaration != null ? xdoc.Declaration + \"\\r\\n\" : \"\") + xdoc.ToString();\nConsole.WriteLine(formattedXml);\n</code></pre>\n\n<p>This adds in the required indentation, and <strong>maintains the Xml Declaration</strong>.</p>\n\n<pre><code><?xml version=\"1.0\"?>\n<book>\n <author>Lewis, C.S.</author>\n <title>The Four Loves</title>\n</book>\n</code></pre>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/194976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I thought the web page designer screen in 2005 was mediocre until I used the one in 2008 which I think is bad. There is an interesting white paper here:
<http://www.west-wind.com/weblog/posts/484172.aspx>
I've gotten very used to these WYSIWYG designers over the years, but I am looking now for a new way.
I make business web apps which call for data entry forms. I don't need anything particularly artistic, but I do need to be able to line up text boxes etc on input forms so that they lkook orderly and are convenient for the user. I use Telerik controls, and my skills with CSS are approaching passable.
People often mention that they don't use the designer, but they rarely state what approach they DO use.
What are some of the alternatives to using the VS designer?
|
```
string unformattedXml = "<?xml version=\"1.0\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>";
string formattedXml = XElement.Parse(unformattedXml).ToString();
Console.WriteLine(formattedXml);
```
Output:
```
<book>
<author>Lewis, C.S.</author>
<title>The Four Loves</title>
</book>
```
The Xml Declaration isn't output by ToString(), but it is by Save() ...
```
XElement.Parse(unformattedXml).Save(@"C:\doc.xml");
Console.WriteLine(File.ReadAllText(@"C:\doc.xml"));
```
Output:
```
<?xml version="1.0" encoding="utf-8"?>
<book>
<author>Lewis, C.S.</author>
<title>The Four Loves</title>
</book>
```
|
194,999 |
<p>On an ASP.NET website, are static classes unique to each web request, or are they instantiated whenever needed and GCed whenever the GC decides to disposed of them?</p>
<p>The reason I ask is because I've written some static classes before in C# and the behavior is different than I would have expected. I would have expected static classes to be unique to each request, but it doesn't seem like that is the case.</p>
<p>If they are not unique to each request, is there a way to allow them to be?</p>
<p><strong>UPDATE:</strong><br>
The answer driis gave me was exactly what I needed. I was already using a singleton class, however it was using a static instance and therefore was being shared between requests even if the users were different which in this case was a bad thing. Using <code>HttpContext.Current.Items</code> solves my problem perfectly. For anyone who stumbles upon this question in the future, here is my implementation, simplified and shortened so that it easy to understand the pattern:</p>
<pre><code>using System.Collections;
using System.Web;
public class GloballyAccessibleClass
{
private GloballyAccessibleClass() { }
public static GloballyAccessibleClass Instance
{
get
{
IDictionary items = HttpContext.Current.Items;
if(!items.Contains("TheInstance"))
{
items["TheInstance"] = new GloballyAccessibleClass();
}
return items["TheInstance"] as GloballyAccessibleClass;
}
}
}
</code></pre>
|
[
{
"answer_id": 195003,
"author": "Sijin",
"author_id": 8884,
"author_profile": "https://Stackoverflow.com/users/8884",
"pm_score": 4,
"selected": false,
"text": "<p>Since the types are contained in an app domain, I would expect static classes to be present as long as the app domain is not recycled, or if the request gets served by a different app domain.</p>\n\n<p>I can think of several ways to make objects specific to a particular request depends on what you want to do, for e.g. you could instantiate the object in Application.BeginRequest and then store it in HttpRequest object so that it can be accessed by all objects in the request processing pipeline.</p>\n"
},
{
"answer_id": 195029,
"author": "rp.",
"author_id": 2536,
"author_profile": "https://Stackoverflow.com/users/2536",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>If they are not unique to each request, is there a way to allow them to be?</p>\n</blockquote>\n\n<p>Nope. Static members are owned by the ASP.NET process and shared by <em>all</em> users of the Web app. You'll need to turn to other session management techniques such as session variables. </p>\n"
},
{
"answer_id": 195290,
"author": "driis",
"author_id": 13627,
"author_profile": "https://Stackoverflow.com/users/13627",
"pm_score": 8,
"selected": true,
"text": "<p>Your static classes and static instance fields are shared between all requests to the application, and has the same lifetime as the application domain. Therefore, you should be careful when using static instances, since you might have synchronization issues and the like. Also bear in mind, that static instances will not be GC'ed before the application pool is recycled, and therefore everything that is referenced by the static instance, will not be GC'ed. This can lead to memory usage problems.</p>\n\n<p>If you need an instance with the same lifetime as a request, I would suggest to use the <code>HttpContext.Current.Items</code> collection. This is by design meant to be a place to store stuff that you need througout the request. For nicer design and readability, you can use the Singleton pattern to help you manage these items. Simply create a Singleton class that stores its instance in <code>HttpContext.Current.Items</code>. (In my common library for ASP.NET, I have a generic SingletonRequest class for this purpose).</p>\n"
},
{
"answer_id": 195297,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 2,
"selected": false,
"text": "<p>Normally static methods, properties and classes are common at the <code>Application</code> level. As long as the application lives, they are shared.</p>\n\n<p>You can specify a different behaviour by using the <code>ThreadStatic</code> attribute. In that case they will be specific to the current thread, which, I think, is specific for each request.<br>\nI would not advise this though as it seems overcomplicated.</p>\n\n<p>You can use <code>HttpContext.Current.Items</code> to set stuff up for one request, or <code>HttpContext.Current.Session</code> to set stuff up for one user (across requests).</p>\n\n<p>In general though, unless you have to use things like <code>Server.Transfer</code>, the best way is basically creating things once and then passing them explicitly via method invocation.</p>\n"
},
{
"answer_id": 18334667,
"author": "Moshe Bixenshpaner",
"author_id": 922340,
"author_profile": "https://Stackoverflow.com/users/922340",
"pm_score": 5,
"selected": false,
"text": "<p>Static members have a scope of the current worker process only, so it has nothing to do with requests, because different requests may or may not be handled by the same worker process.</p>\n\n<ul>\n<li>In order to share data with a specific user and across requests, use HttpContext.Current.Session.</li>\n<li>In order to share data within a specific request, use HttpContext.Current.Items.</li>\n<li>In order to share data across the entire application, either write a mechanism for that, or configure IIS to work with a single process and write a singleton / use Application.</li>\n</ul>\n\n<p>By the way, the default number of worker processes is 1, so this is why the web is full of people thinking that static members have a scope of the entire application.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/194999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
] |
On an ASP.NET website, are static classes unique to each web request, or are they instantiated whenever needed and GCed whenever the GC decides to disposed of them?
The reason I ask is because I've written some static classes before in C# and the behavior is different than I would have expected. I would have expected static classes to be unique to each request, but it doesn't seem like that is the case.
If they are not unique to each request, is there a way to allow them to be?
**UPDATE:**
The answer driis gave me was exactly what I needed. I was already using a singleton class, however it was using a static instance and therefore was being shared between requests even if the users were different which in this case was a bad thing. Using `HttpContext.Current.Items` solves my problem perfectly. For anyone who stumbles upon this question in the future, here is my implementation, simplified and shortened so that it easy to understand the pattern:
```
using System.Collections;
using System.Web;
public class GloballyAccessibleClass
{
private GloballyAccessibleClass() { }
public static GloballyAccessibleClass Instance
{
get
{
IDictionary items = HttpContext.Current.Items;
if(!items.Contains("TheInstance"))
{
items["TheInstance"] = new GloballyAccessibleClass();
}
return items["TheInstance"] as GloballyAccessibleClass;
}
}
}
```
|
Your static classes and static instance fields are shared between all requests to the application, and has the same lifetime as the application domain. Therefore, you should be careful when using static instances, since you might have synchronization issues and the like. Also bear in mind, that static instances will not be GC'ed before the application pool is recycled, and therefore everything that is referenced by the static instance, will not be GC'ed. This can lead to memory usage problems.
If you need an instance with the same lifetime as a request, I would suggest to use the `HttpContext.Current.Items` collection. This is by design meant to be a place to store stuff that you need througout the request. For nicer design and readability, you can use the Singleton pattern to help you manage these items. Simply create a Singleton class that stores its instance in `HttpContext.Current.Items`. (In my common library for ASP.NET, I have a generic SingletonRequest class for this purpose).
|
195,010 |
<p>I have an array of 1000 or so entries, with examples below:</p>
<pre><code>wickedweather
liquidweather
driveourtrucks
gocompact
slimprojector
</code></pre>
<p>I would like to be able to split these into their respective words, as:</p>
<pre><code>wicked weather
liquid weather
drive our trucks
go compact
slim projector
</code></pre>
<p>I was hoping a regular expression my do the trick. But, since there is no boundary to stop on, nor is there any sort of capitalization that I could possibly key on, I am thinking, that some sort of reference to a dictionary might be necessary? </p>
<p>I suppose it could be done by hand, but why - when it can be done with code! =) But this has stumped me. Any ideas? </p>
|
[
{
"answer_id": 195015,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>I think you're right in thinking that it's not really a job for a regular expression. I would approach this using the dictionary idea - look for the longest prefix that is a word in the dictionary. When you find that, chop it off and do the same with the remainder of the string.</p>\n\n<p>The above method is subject to ambiguity, for example \"drivereallyfast\" would first find \"driver\" and then have trouble with \"eallyfast\". So you would also have to do some backtracking if you ran into this situation. Or, since you don't have that many strings to split, just do by hand the ones that fail the automated split.</p>\n"
},
{
"answer_id": 195016,
"author": "Zoe Gagnon",
"author_id": 26929,
"author_profile": "https://Stackoverflow.com/users/26929",
"pm_score": 1,
"selected": false,
"text": "<p>Well, the problem itself is not solvable with just a regular expression. A solution (probably not the best) would be to get a dictionary and do a regular expression match for each work in the dictionary to each word in the list, adding the space whenever successful. Certainly this would not be terribly quick, but it would be easy to program and faster than hand doing it. </p>\n"
},
{
"answer_id": 195017,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 1,
"selected": false,
"text": "<p>A dictionary based solution would be required. This might be simplified somewhat if you have a limited dictionary of words that can occur, otherwise words that form the prefix of other words are going to be a problem.</p>\n"
},
{
"answer_id": 195023,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 0,
"selected": false,
"text": "<p>I may get downmodded for this, but <strong>have the secretary do it</strong>.</p>\n\n<p>You'll spend more time on a dictionary solution than it would take to manually process. Further, you won't possibly have 100% confidence in the solution, so you'll still have to give it manual attention anyway.</p>\n"
},
{
"answer_id": 195024,
"author": "SquareCog",
"author_id": 15962,
"author_profile": "https://Stackoverflow.com/users/15962",
"pm_score": 6,
"selected": true,
"text": "<p>Can a human do it?</p>\n\n<pre>\nfarsidebag\nfar sidebag\nfarside bag\nfar side bag\n</pre>\n\n<p>Not only do you have to use a dictionary, you might have to use a statistical approach to figure out what's most likely (or, god forbid, an actual HMM for your human language of choice...)</p>\n\n<p>For how to do statistics that might be helpful, I turn you to Dr. Peter Norvig, who addresses a different, but related problem of spell-checking <strong><em>in 21 lines of code</em></strong>:\n<a href=\"http://norvig.com/spell-correct.html\" rel=\"noreferrer\">http://norvig.com/spell-correct.html</a></p>\n\n<p>(he does cheat a bit by folding every for loop into a single line.. but still).</p>\n\n<p><strong><em>Update</em></strong> This got stuck in my head, so I had to birth it today. This code does a similar split to the one described by Robert Gamble, but then it orders the results based on word frequency in the provided dictionary file (which is now expected to be some text representative of your domain or English in general. I used big.txt from Norvig, linked above, and catted a dictionary to it, to cover missing words).</p>\n\n<p>A combination of two words will most of the time beat a combination of 3 words, unless the frequency difference is enormous.</p>\n\n<hr>\n\n<p><strong>I posted this code with some minor changes on my blog</strong></p>\n\n<p><a href=\"http://squarecog.wordpress.com/2008/10/19/splitting-words-joined-into-a-single-string/\" rel=\"noreferrer\">http://squarecog.wordpress.com/2008/10/19/splitting-words-joined-into-a-single-string/</a>\nand also wrote a little about the underflow bug in this code.. I was tempted to just quietly fix it, but figured this may help some folks who haven't seen the log trick before:\n<a href=\"http://squarecog.wordpress.com/2009/01/10/dealing-with-underflow-in-joint-probability-calculations/\" rel=\"noreferrer\">http://squarecog.wordpress.com/2009/01/10/dealing-with-underflow-in-joint-probability-calculations/</a></p>\n\n<hr>\n\n<p>Output on your words, plus a few of my own -- notice what happens with \"orcore\":</p>\n\n<pre>\nperl splitwords.pl big.txt words\nanswerveal: 2 possibilities\n - answer veal\n - answer ve al\n\nwickedweather: 4 possibilities\n - wicked weather\n - wicked we at her\n - wick ed weather\n - wick ed we at her\n\nliquidweather: 6 possibilities\n - liquid weather\n - liquid we at her\n - li quid weather\n - li quid we at her\n - li qu id weather\n - li qu id we at her\n\ndriveourtrucks: 1 possibilities\n - drive our trucks\n\ngocompact: 1 possibilities\n - go compact\n\nslimprojector: 2 possibilities\n - slim projector\n - slim project or\n\norcore: 3 possibilities\n - or core\n - or co re\n - orc ore\n\n</pre>\n\n<p>Code:</p>\n\n<pre><code>#!/usr/bin/env perl\n\nuse strict;\nuse warnings;\n\nsub find_matches($);\nsub find_matches_rec($\\@\\@);\nsub find_word_seq_score(@);\nsub get_word_stats($);\nsub print_results($@);\nsub Usage();\n\nour(%DICT,$TOTAL);\n{\n my( $dict_file, $word_file ) = @ARGV;\n ($dict_file && $word_file) or die(Usage);\n\n {\n my $DICT;\n ($DICT, $TOTAL) = get_word_stats($dict_file);\n %DICT = %$DICT;\n }\n\n {\n open( my $WORDS, '<', $word_file ) or die \"unable to open $word_file\\n\";\n\n foreach my $word (<$WORDS>) {\n chomp $word;\n my $arr = find_matches($word);\n\n\n local $_;\n # Schwartzian Transform\n my @sorted_arr =\n map { $_->[0] }\n sort { $b->[1] <=> $a->[1] }\n map {\n [ $_, find_word_seq_score(@$_) ]\n }\n @$arr;\n\n\n print_results( $word, @sorted_arr );\n }\n\n close $WORDS;\n }\n}\n\n\nsub find_matches($){\n my( $string ) = @_;\n\n my @found_parses;\n my @words;\n find_matches_rec( $string, @words, @found_parses );\n\n return @found_parses if wantarray;\n return \\@found_parses;\n}\n\nsub find_matches_rec($\\@\\@){\n my( $string, $words_sofar, $found_parses ) = @_;\n my $length = length $string;\n\n unless( $length ){\n push @$found_parses, $words_sofar;\n\n return @$found_parses if wantarray;\n return $found_parses;\n }\n\n foreach my $i ( 2..$length ){\n my $prefix = substr($string, 0, $i);\n my $suffix = substr($string, $i, $length-$i);\n\n if( exists $DICT{$prefix} ){\n my @words = ( @$words_sofar, $prefix );\n find_matches_rec( $suffix, @words, @$found_parses );\n }\n }\n\n return @$found_parses if wantarray;\n return $found_parses;\n}\n\n\n## Just a simple joint probability\n## assumes independence between words, which is obviously untrue\n## that's why this is broken out -- feel free to add better brains\nsub find_word_seq_score(@){\n my( @words ) = @_;\n local $_;\n\n my $score = 1;\n foreach ( @words ){\n $score = $score * $DICT{$_} / $TOTAL;\n }\n\n return $score;\n}\n\nsub get_word_stats($){\n my ($filename) = @_;\n\n open(my $DICT, '<', $filename) or die \"unable to open $filename\\n\";\n\n local $/= undef;\n local $_;\n my %dict;\n my $total = 0;\n\n while ( <$DICT> ){\n foreach ( split(/\\b/, $_) ) {\n $dict{$_} += 1;\n $total++;\n }\n }\n\n close $DICT;\n\n return (\\%dict, $total);\n}\n\nsub print_results($@){\n #( 'word', [qw'test one'], [qw'test two'], ... )\n my ($word, @combos) = @_;\n local $_;\n my $possible = scalar @combos;\n\n print \"$word: $possible possibilities\\n\";\n foreach (@combos) {\n print ' - ', join(' ', @$_), \"\\n\";\n }\n print \"\\n\";\n}\n\nsub Usage(){\n return \"$0 /path/to/dictionary /path/to/your_words\";\n}\n</code></pre>\n"
},
{
"answer_id": 195085,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 3,
"selected": false,
"text": "<p>The best tool for the job here is recursion, not regular expressions. The basic idea is to start from the beginning of the string looking for a word, then take the remainder of the string and look for another word, and so on until the end of the string is reached. A recursive solution is natural since backtracking needs to happen when a given remainder of the string cannot be broken into a set of words. The solution below uses a dictionary to determine what is a word and prints out solutions as it finds them (some strings can be broken out into multiple possible sets of words, for example wickedweather could be parsed as \"wicked we at her\"). If you just want one set of words you will need to determine the rules for selecting the best set, perhaps by selecting the solution with fewest number of words or by setting a minimum word length.</p>\n\n<pre><code>#!/usr/bin/perl\n\nuse strict;\n\nmy $WORD_FILE = '/usr/share/dict/words'; #Change as needed\nmy %words; # Hash of words in dictionary\n\n# Open dictionary, load words into hash\nopen(WORDS, $WORD_FILE) or die \"Failed to open dictionary: $!\\n\";\nwhile (<WORDS>) {\n chomp;\n $words{lc($_)} = 1;\n}\nclose(WORDS);\n\n# Read one line at a time from stdin, break into words\nwhile (<>) {\n chomp;\n my @words;\n find_words(lc($_));\n}\n\nsub find_words {\n # Print every way $string can be parsed into whole words\n my $string = shift;\n my @words = @_;\n my $length = length $string;\n\n foreach my $i ( 1 .. $length ) {\n my $word = substr $string, 0, $i;\n my $remainder = substr $string, $i, $length - $i;\n # Some dictionaries contain each letter as a word\n next if ($i == 1 && ($word ne \"a\" && $word ne \"i\"));\n\n if (defined($words{$word})) {\n push @words, $word;\n if ($remainder eq \"\") {\n print join(' ', @words), \"\\n\";\n return;\n } else {\n find_words($remainder, @words);\n }\n pop @words;\n }\n }\n\n return;\n}\n</code></pre>\n"
},
{
"answer_id": 481773,
"author": "Darius Bacon",
"author_id": 27024,
"author_profile": "https://Stackoverflow.com/users/27024",
"pm_score": 6,
"selected": false,
"text": "<p>The <a href=\"http://en.wikipedia.org/wiki/Viterbi_algorithm\" rel=\"noreferrer\">Viterbi algorithm</a> is much faster. It computes the same scores as the recursive search in Dmitry's answer above, but in O(n) time. (Dmitry's search takes exponential time; Viterbi does it by dynamic programming.)</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import re\nfrom collections import Counter\n\ndef viterbi_segment(text):\n probs, lasts = [1.0], [0]\n for i in range(1, len(text) + 1):\n prob_k, k = max((probs[j] * word_prob(text[j:i]), j)\n for j in range(max(0, i - max_word_length), i))\n probs.append(prob_k)\n lasts.append(k)\n words = []\n i = len(text)\n while 0 < i:\n words.append(text[lasts[i]:i])\n i = lasts[i]\n words.reverse()\n return words, probs[-1]\n\ndef word_prob(word): return dictionary[word] / total\ndef words(text): return re.findall('[a-z]+', text.lower()) \ndictionary = Counter(words(open('big.txt').read()))\nmax_word_length = max(map(len, dictionary))\ntotal = float(sum(dictionary.values()))\n</code></pre>\n\n<p>Testing it:</p>\n\n<pre><code>>>> viterbi_segment('wickedweather')\n(['wicked', 'weather'], 5.1518198982768158e-10)\n>>> ' '.join(viterbi_segment('itseasyformetosplitlongruntogetherblocks')[0])\n'its easy for me to split long run together blocks'\n</code></pre>\n\n<p>To be practical you'll likely want a couple refinements:</p>\n\n<ul>\n<li>Add logs of probabilities, don't multiply probabilities. This avoids floating-point underflow.</li>\n<li>Your inputs will in general use words not in your corpus. These substrings must be assigned a nonzero probability as words, or you end up with no solution or a bad solution. (That's just as true for the above exponential search algorithm.) This probability has to be siphoned off the corpus words' probabilities and distributed plausibly among all other word candidates: the general topic is known as smoothing in statistical language models. (You can get away with some pretty rough hacks, though.) This is where the O(n) Viterbi algorithm blows away the search algorithm, because considering non-corpus words blows up the branching factor.</li>\n</ul>\n"
},
{
"answer_id": 49440472,
"author": "mhucka",
"author_id": 743730,
"author_profile": "https://Stackoverflow.com/users/743730",
"pm_score": 2,
"selected": false,
"text": "<p>This is related to a problem known as <em>identifier splitting</em> or <em>identifier name tokenization</em>. In the OP's case, the inputs seem to be concatenations of ordinary words; in identifier splitting, the inputs are class names, function names or other identifiers from source code, and the problem is harder. I realize this is an old question and the OP has either solved their problem or moved on, but in case someone else comes across this question while looking for identifier splitters (like I was, not long ago), I would like to offer <a href=\"https://github.com/casics/spiral\" rel=\"nofollow noreferrer\">Spiral</a> (\"<em>SPlitters for IdentifieRs: A Library</em>\"). It is written in Python but comes with a command-line utility that can read a file of identifiers (one per line) and split each one.</p>\n\n<p>Splitting identifiers is deceptively difficult. Programmers commonly use abbreviations, acronyms and word fragments when naming things, and they don't always use consistent conventions. Even in when identifiers do follow some convention such as camel case, ambiguities can arise.</p>\n\n<p><a href=\"https://github.com/casics/spiral\" rel=\"nofollow noreferrer\">Spiral</a> implements numerous identifier splitting algorithms, including a novel algorithm called Ronin. It uses a variety of heuristic rules, English dictionaries, and tables of token frequencies obtained from mining source code repositories. Ronin can split identifiers that do not use camel case or other naming conventions, including cases such as splitting <code>J2SEProjectTypeProfiler</code> into [<code>J2SE</code>, <code>Project</code>, <code>Type</code>, <code>Profiler</code>], which requires the reader to recognize <code>J2SE</code> as a unit. Here are some more examples of what Ronin can split:</p>\n\n<pre><code># spiral mStartCData nonnegativedecimaltype getUtf8Octets GPSmodule savefileas nbrOfbugs\nmStartCData: ['m', 'Start', 'C', 'Data']\nnonnegativedecimaltype: ['nonnegative', 'decimal', 'type']\ngetUtf8Octets: ['get', 'Utf8', 'Octets']\nGPSmodule: ['GPS', 'module']\nsavefileas: ['save', 'file', 'as']\nnbrOfbugs: ['nbr', 'Of', 'bugs']\n</code></pre>\n\n<p>Using the examples from the OP's question:</p>\n\n<pre><code># spiral wickedweather liquidweather driveourtrucks gocompact slimprojector\nwickedweather: ['wicked', 'weather']\nliquidweather: ['liquid', 'weather']\ndriveourtrucks: ['driveourtrucks']\ngocompact: ['go', 'compact']\nslimprojector: ['slim', 'projector']\n</code></pre>\n\n<p>As you can see, it is not perfect. It's worth noting that Ronin has a number of parameters and adjusting them makes it possible to split <code>driveourtrucks</code> too, but at the cost of worsening performance on program identifiers.</p>\n\n<p>More information can be found in the <a href=\"https://github.com/casics/spiral\" rel=\"nofollow noreferrer\">GitHub repo for Spiral</a>.</p>\n"
},
{
"answer_id": 54210972,
"author": "adam shamsudeen",
"author_id": 6741167,
"author_profile": "https://Stackoverflow.com/users/6741167",
"pm_score": 1,
"selected": false,
"text": "<p>There is python package released Santhosh thottingal called mlmorph which can be used for morphological analysis.</p>\n\n<p><a href=\"https://pypi.org/project/mlmorph/\" rel=\"nofollow noreferrer\">https://pypi.org/project/mlmorph/</a></p>\n\n<p>Examples:</p>\n\n<pre><code>from mlmorph import Analyser\nanalyser = Analyser()\nanalyser.analyse(\"കേരളത്തിന്റെ\")\n</code></pre>\n\n<p>Gives</p>\n\n<pre><code>[('കേരളം<np><genitive>', 179)]\n</code></pre>\n\n<p>He also wrote a blog on the topic <a href=\"https://thottingal.in/blog/2017/11/26/towards-a-malayalam-morphology-analyser/\" rel=\"nofollow noreferrer\">https://thottingal.in/blog/2017/11/26/towards-a-malayalam-morphology-analyser/</a></p>\n"
},
{
"answer_id": 57733635,
"author": "Rabash",
"author_id": 3266110,
"author_profile": "https://Stackoverflow.com/users/3266110",
"pm_score": 2,
"selected": false,
"text": "<p>A simple solution with Python: install the <a href=\"https://github.com/grantjenks/python-wordsegment\" rel=\"nofollow noreferrer\">wordsegment</a> package: <code>pip install wordsegment</code>.</p>\n\n<pre><code>$ echo thisisatest | python -m wordsegment\nthis is a test\n</code></pre>\n"
},
{
"answer_id": 58010290,
"author": "kamran kausar",
"author_id": 3486460,
"author_profile": "https://Stackoverflow.com/users/3486460",
"pm_score": 4,
"selected": false,
"text": "<p>pip install wordninja</p>\n\n<pre><code>>>> import wordninja\n>>> wordninja.split('bettergood')\n['better', 'good']\n</code></pre>\n"
},
{
"answer_id": 61159132,
"author": "Naphtali Duniya",
"author_id": 7892029,
"author_profile": "https://Stackoverflow.com/users/7892029",
"pm_score": 1,
"selected": false,
"text": "<p>This will work if the are camelCase. JavaScript!!!</p>\n\n<pre><code>function spinalCase(str) {\n let lowercase = str.trim()\n let regEx = /\\W+|(?=[A-Z])|_/g\n let result = lowercase.split(regEx).join(\"-\").toLowerCase()\n\n return result;\n}\n\nspinalCase(\"AllThe-small Things\");\n</code></pre>\n"
},
{
"answer_id": 64449782,
"author": "Vishrant",
"author_id": 2704032,
"author_profile": "https://Stackoverflow.com/users/2704032",
"pm_score": 1,
"selected": false,
"text": "<p>One of the solutions could be with recurssion (the same can be converted into dynamic-programming):</p>\n<pre><code>static List<String> wordBreak(\n String input,\n Set<String> dictionary\n) {\n\n List<List<String>> result = new ArrayList<>();\n List<String> r = new ArrayList<>();\n\n helper(input, dictionary, result, "", 0, new Stack<>());\n\n for (List<String> strings : result) {\n String s = String.join(" ", strings);\n r.add(s);\n }\n\n return r;\n}\n\nstatic void helper(\n final String input,\n final Set<String> dictionary,\n final List<List<String>> result,\n String state,\n int index,\n Stack<String> stack\n) {\n\n if (index == input.length()) {\n\n // add the last word\n stack.push(state);\n\n for (String s : stack) {\n if (!dictionary.contains(s)) {\n return;\n }\n }\n\n result.add((List<String>) stack.clone());\n\n return;\n }\n\n if (dictionary.contains(state)) {\n // bifurcate\n stack.push(state);\n helper(input, dictionary, result, "" + input.charAt(index),\n index + 1, stack);\n\n String pop = stack.pop();\n String s = stack.pop();\n\n helper(input, dictionary, result, s + pop.charAt(0),\n index + 1, stack);\n\n }\n else {\n helper(input, dictionary, result, state + input.charAt(index),\n index + 1, stack);\n }\n\n return;\n}\n</code></pre>\n<p>The other possible solution would be the use of <code>Tries</code> data structure.</p>\n"
},
{
"answer_id": 68095697,
"author": "Mukund Biradar",
"author_id": 11431613,
"author_profile": "https://Stackoverflow.com/users/11431613",
"pm_score": 1,
"selected": false,
"text": "<pre><code>output :-\n['better', 'good'] ['coffee', 'shop']\n['coffee', 'shop']\n\n pip install wordninja\nimport wordninja\nn=wordninja.split('bettergood')\nm=wordninja.split("coffeeshop")\nprint(n,m)\n\nlist=['hello','coffee','shop','better','good']\nmat='coffeeshop'\nexpected=[]\nfor i in list:\n if i in mat:\n expected.append(i)\nprint(expected)\n</code></pre>\n"
},
{
"answer_id": 70162407,
"author": "Jimmy Slagle",
"author_id": 17546121,
"author_profile": "https://Stackoverflow.com/users/17546121",
"pm_score": 1,
"selected": false,
"text": "<p>So I spent like 2 days on this answer, since I need it for my own NLP work. My answer is derived from <a href=\"https://stackoverflow.com/users/27024/darius-bacon\">Darius Bacon's</a> answer, which itself was derived from the <a href=\"https://en.wikipedia.org/wiki/Viterbi_algorithm\" rel=\"nofollow noreferrer\">Viterbi algorithm</a>. I also abstracted it to take each word in a message, attempt to split it, and then reassemble the message. I expanded Darius's code to make it debuggable. I also swapped out the need for "big.txt", and use the <a href=\"https://pypi.org/project/wordfreq/\" rel=\"nofollow noreferrer\">wordfreq</a> library instead. Some comments stress the need to use a non-zero word frequency for non-existent words. I found that using any frequency higher than zero would cause "itseasyformetosplitlongruntogetherblocks" to undersplit into "itseasyformetosplitlongruntogether blocks". The algorithm in general tends to either oversplit or undersplit various test messages depending on how you combine word frequencies and how you handle missing word frequencies. I played around with many tweaks until it behaved well. My solution uses a 0.0 frequency for missing words. It also adds a reward for word length (otherwise it tends to split words into characters). I tried many length rewards, and the one that seems to work best for my test cases is <code>word_frequency * (e ** word_length)</code>. There were also comments warning against multiplying word frequencies together. I tried adding them, using the harmonic mean, and using 1-freq instead of the 0.00001 form. They all tended to oversplit the test cases. Simply multiplying word frequencies together worked best. I left my debugging print statements in there, to make it easier for others to continue tweaking. Finally, there's a special case where if your whole message is a word that doesn't exist, like "Slagle's", then the function splits the word into individual letters. In my case, I don't want that, so I have a special return statement at the end to return the original message in those cases.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import numpy as np\nfrom wordfreq import get_frequency_dict\n\nword_prob = get_frequency_dict(lang='en', wordlist='large')\nmax_word_len = max(map(len, word_prob)) # 34\n\ndef viterbi_segment(text, debug=False):\n probs, lasts = [1.0], [0]\n for i in range(1, len(text) + 1):\n new_probs = []\n for j in range(max(0, i - max_word_len), i):\n substring = text[j:i]\n length_reward = np.exp(len(substring))\n freq = word_prob.get(substring, 0) * length_reward\n compounded_prob = probs[j] * freq\n new_probs.append((compounded_prob, j))\n \n if debug:\n print(f'[{j}:{i}] = "{text[lasts[j]:j]} & {substring}" = ({probs[j]:.8f} & {freq:.8f}) = {compounded_prob:.8f}')\n\n prob_k, k = max(new_probs) # max of a touple is the max across the first elements, which is the max of the compounded probabilities\n probs.append(prob_k)\n lasts.append(k)\n\n if debug:\n print(f'i = {i}, prob_k = {prob_k:.8f}, k = {k}, ({text[k:i]})\\n')\n\n\n # when text is a word that doesn't exist, the algorithm breaks it into individual letters.\n # in that case, return the original word instead\n if len(set(lasts)) == len(text):\n return text\n\n words = []\n k = len(text)\n while 0 < k:\n word = text[lasts[k]:k]\n words.append(word)\n k = lasts[k]\n words.reverse()\n return ' '.join(words)\n\ndef split_message(message):\n new_message = ' '.join(viterbi_segment(wordmash, debug=False) for wordmash in message.split())\n return new_message\n\nmessages = [\n 'tosplit',\n 'split',\n 'driveourtrucks',\n "Slagle's",\n "Slagle's wickedweather liquidweather driveourtrucks gocompact slimprojector",\n 'itseasyformetosplitlongruntogetherblocks',\n]\n\nfor message in messages:\n print(f'{message}')\n new_message = split_message(message)\n print(f'{new_message}\\n')\n</code></pre>\n<pre><code>tosplit\nto split\n\nsplit\nsplit\n\ndriveourtrucks\ndrive our trucks\n\nSlagle's\nSlagle's\n\nSlagle's wickedweather liquidweather driveourtrucks gocompact slimprojector\nSlagle's wicked weather liquid weather drive our trucks go compact slim projector\n\nitseasyformetosplitlongruntogetherblocks\nits easy for me to split long run together blocks\n</code></pre>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14728/"
] |
I have an array of 1000 or so entries, with examples below:
```
wickedweather
liquidweather
driveourtrucks
gocompact
slimprojector
```
I would like to be able to split these into their respective words, as:
```
wicked weather
liquid weather
drive our trucks
go compact
slim projector
```
I was hoping a regular expression my do the trick. But, since there is no boundary to stop on, nor is there any sort of capitalization that I could possibly key on, I am thinking, that some sort of reference to a dictionary might be necessary?
I suppose it could be done by hand, but why - when it can be done with code! =) But this has stumped me. Any ideas?
|
Can a human do it?
```
farsidebag
far sidebag
farside bag
far side bag
```
Not only do you have to use a dictionary, you might have to use a statistical approach to figure out what's most likely (or, god forbid, an actual HMM for your human language of choice...)
For how to do statistics that might be helpful, I turn you to Dr. Peter Norvig, who addresses a different, but related problem of spell-checking ***in 21 lines of code***:
<http://norvig.com/spell-correct.html>
(he does cheat a bit by folding every for loop into a single line.. but still).
***Update*** This got stuck in my head, so I had to birth it today. This code does a similar split to the one described by Robert Gamble, but then it orders the results based on word frequency in the provided dictionary file (which is now expected to be some text representative of your domain or English in general. I used big.txt from Norvig, linked above, and catted a dictionary to it, to cover missing words).
A combination of two words will most of the time beat a combination of 3 words, unless the frequency difference is enormous.
---
**I posted this code with some minor changes on my blog**
<http://squarecog.wordpress.com/2008/10/19/splitting-words-joined-into-a-single-string/>
and also wrote a little about the underflow bug in this code.. I was tempted to just quietly fix it, but figured this may help some folks who haven't seen the log trick before:
<http://squarecog.wordpress.com/2009/01/10/dealing-with-underflow-in-joint-probability-calculations/>
---
Output on your words, plus a few of my own -- notice what happens with "orcore":
```
perl splitwords.pl big.txt words
answerveal: 2 possibilities
- answer veal
- answer ve al
wickedweather: 4 possibilities
- wicked weather
- wicked we at her
- wick ed weather
- wick ed we at her
liquidweather: 6 possibilities
- liquid weather
- liquid we at her
- li quid weather
- li quid we at her
- li qu id weather
- li qu id we at her
driveourtrucks: 1 possibilities
- drive our trucks
gocompact: 1 possibilities
- go compact
slimprojector: 2 possibilities
- slim projector
- slim project or
orcore: 3 possibilities
- or core
- or co re
- orc ore
```
Code:
```
#!/usr/bin/env perl
use strict;
use warnings;
sub find_matches($);
sub find_matches_rec($\@\@);
sub find_word_seq_score(@);
sub get_word_stats($);
sub print_results($@);
sub Usage();
our(%DICT,$TOTAL);
{
my( $dict_file, $word_file ) = @ARGV;
($dict_file && $word_file) or die(Usage);
{
my $DICT;
($DICT, $TOTAL) = get_word_stats($dict_file);
%DICT = %$DICT;
}
{
open( my $WORDS, '<', $word_file ) or die "unable to open $word_file\n";
foreach my $word (<$WORDS>) {
chomp $word;
my $arr = find_matches($word);
local $_;
# Schwartzian Transform
my @sorted_arr =
map { $_->[0] }
sort { $b->[1] <=> $a->[1] }
map {
[ $_, find_word_seq_score(@$_) ]
}
@$arr;
print_results( $word, @sorted_arr );
}
close $WORDS;
}
}
sub find_matches($){
my( $string ) = @_;
my @found_parses;
my @words;
find_matches_rec( $string, @words, @found_parses );
return @found_parses if wantarray;
return \@found_parses;
}
sub find_matches_rec($\@\@){
my( $string, $words_sofar, $found_parses ) = @_;
my $length = length $string;
unless( $length ){
push @$found_parses, $words_sofar;
return @$found_parses if wantarray;
return $found_parses;
}
foreach my $i ( 2..$length ){
my $prefix = substr($string, 0, $i);
my $suffix = substr($string, $i, $length-$i);
if( exists $DICT{$prefix} ){
my @words = ( @$words_sofar, $prefix );
find_matches_rec( $suffix, @words, @$found_parses );
}
}
return @$found_parses if wantarray;
return $found_parses;
}
## Just a simple joint probability
## assumes independence between words, which is obviously untrue
## that's why this is broken out -- feel free to add better brains
sub find_word_seq_score(@){
my( @words ) = @_;
local $_;
my $score = 1;
foreach ( @words ){
$score = $score * $DICT{$_} / $TOTAL;
}
return $score;
}
sub get_word_stats($){
my ($filename) = @_;
open(my $DICT, '<', $filename) or die "unable to open $filename\n";
local $/= undef;
local $_;
my %dict;
my $total = 0;
while ( <$DICT> ){
foreach ( split(/\b/, $_) ) {
$dict{$_} += 1;
$total++;
}
}
close $DICT;
return (\%dict, $total);
}
sub print_results($@){
#( 'word', [qw'test one'], [qw'test two'], ... )
my ($word, @combos) = @_;
local $_;
my $possible = scalar @combos;
print "$word: $possible possibilities\n";
foreach (@combos) {
print ' - ', join(' ', @$_), "\n";
}
print "\n";
}
sub Usage(){
return "$0 /path/to/dictionary /path/to/your_words";
}
```
|
195,020 |
<p>I've just started using Java's enums in my own projects (I have to use JDK 1.4 at work) and I am confused as to the best practice of using JavaDoc for an enum.</p>
<p>I have found that this method works, but the resultant code is a little unrefined:</p>
<pre><code>/**
* Doc for enum
*/
public enum Something {
/**
* First thing
*/
FIRST_THING,
/**
* Second thing
*/
SECOND_THING;
//could continue with more
}
</code></pre>
<p>Is there any way I could break up the enum declarations on their own lines without chaining them by commas, or is this the best approach for using JavaDoc for an enum?</p>
|
[
{
"answer_id": 195074,
"author": "Mike Deck",
"author_id": 1247,
"author_profile": "https://Stackoverflow.com/users/1247",
"pm_score": 6,
"selected": true,
"text": "<p>To answer the first part of your question, you do have to separate each enum value with a comma. As far as I know, there's no way around that.</p>\n\n<p>Personally I don't have a problem with the code the way you've presented it. Seems like a perfectly reasonable way to document an enum to me.</p>\n"
},
{
"answer_id": 195089,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": -1,
"selected": false,
"text": "<p>There is a google code search online tool -- <a href=\"http://www.google.com/codesearch\" rel=\"nofollow noreferrer\">http://www.google.com/codesearch</a></p>\n\n<p>I try to lookup stuff by doing something like <a href=\"http://www.google.com/codesearch#search&q=lang:java+public+enum\" rel=\"nofollow noreferrer\">\"lang:java public enum\"</a></p>\n\n<p><a href=\"http://www.google.com/codesearch#search&q=public+enum+lang:java+show:C2YXOCVDRYM:BdNY19GPXpI:C2YXOCVDRYM\" rel=\"nofollow noreferrer\">An example from Sun</a></p>\n"
},
{
"answer_id": 195105,
"author": "Dov Wasserman",
"author_id": 26010,
"author_profile": "https://Stackoverflow.com/users/26010",
"pm_score": 4,
"selected": false,
"text": "<p>As Mike mentioned, you do have to separate the enum values with commas, and they have to be the first things listed in the enum declaration (instance variables, constants, constructors and methods may follow).</p>\n\n<p>I think the best way to document enums is similar to regular classes: the enum type gets a description of the function and role of the enum as a whole (\"<code>Something values are used to indicate which mode of operation a client wishes...</code>\") and each enum value gets a Javadoc description of its purpose and function (\"<code>FIRST_THING indicates that the operation should evaluate the first argument first..</code>\").</p>\n\n<p>If the enum value descriptions are short you might want to put them on one line as <code>/** Evaluate first argument first. */</code>, but I recommend keeping each enum value on its own line. Most IDEs can be configured to format them this way automatically.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8026/"
] |
I've just started using Java's enums in my own projects (I have to use JDK 1.4 at work) and I am confused as to the best practice of using JavaDoc for an enum.
I have found that this method works, but the resultant code is a little unrefined:
```
/**
* Doc for enum
*/
public enum Something {
/**
* First thing
*/
FIRST_THING,
/**
* Second thing
*/
SECOND_THING;
//could continue with more
}
```
Is there any way I could break up the enum declarations on their own lines without chaining them by commas, or is this the best approach for using JavaDoc for an enum?
|
To answer the first part of your question, you do have to separate each enum value with a comma. As far as I know, there's no way around that.
Personally I don't have a problem with the code the way you've presented it. Seems like a perfectly reasonable way to document an enum to me.
|
195,036 |
<p>I've been researching PHP frameworks as of late for some personal projects, and it looks like most of them use a front controller to mimic a response. The controller gets the params from the request, and re-routes by sending the appropriate headers depending on the logic. This is the "response". Is this the best way to do this in PHP, or are there other theories about how to handle re-routing and responses?</p>
|
[
{
"answer_id": 195047,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 3,
"selected": true,
"text": "<p>a front controller lends itself quite well to a web environment, allowing you to funnel all requests to your application. since HTTP is stateless, and a user can, in a sense, inadvertently stumble upon parts of your app by accident (ie, hitting random URL's), a front controller allows you to determine the entry point of your application, and respond appropriately.</p>\n\n<p><strong>edit</strong>: in response to the comments, i think the confusion may be that java has a lot more structure to it than PHP, which might be overcomplicating the whole thing? ultimately PHP can provide for the very basic interaction from request to response:</p>\n\n<pre><code>switch($_GET['page']) {\n case \"one\";\n print \"page one!\";\n break;\n default:\n print \"default page\";\n break;\n}\n</code></pre>\n\n<p>and from there you can layer in all sorts of things to front controllers passing request objects down a filter chain to a page controller which reroutes to the appropriate model which grabs data via your db abstraction layer, filters it, back up to the controller, and on to the view which constructs the appropriate response, all the while firing off random event hooks. ultimately it's up to you (as developer) to choose what level of complexity/separation you're looking for. this is both the beauty and evilness of PHP :)</p>\n"
},
{
"answer_id": 195092,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 1,
"selected": false,
"text": "<p>I think you are confusing an Http response with a response object in the frameworks you looked at. A front controller is the gateway for your application - all (http) requests go through it, and it routes to the appropriate controller/action. Processing a request does not necessary results in a returned response (often requests are only meant to send information to the server), however all requests would have passed through the Front Controller.</p>\n\n<p>A request object is often used to encapsulate the environment and http request parameters and provide an API to retrieve them. Its complement, the response object, is often used to encapsulate the process of generating an http response, including the generation headers.</p>\n\n<p>There are other approaches to handling requests and routing, which are not unique to PHP (and neither is the front controller), such as a Page Controller, or not using an MVC structure at all.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I've been researching PHP frameworks as of late for some personal projects, and it looks like most of them use a front controller to mimic a response. The controller gets the params from the request, and re-routes by sending the appropriate headers depending on the logic. This is the "response". Is this the best way to do this in PHP, or are there other theories about how to handle re-routing and responses?
|
a front controller lends itself quite well to a web environment, allowing you to funnel all requests to your application. since HTTP is stateless, and a user can, in a sense, inadvertently stumble upon parts of your app by accident (ie, hitting random URL's), a front controller allows you to determine the entry point of your application, and respond appropriately.
**edit**: in response to the comments, i think the confusion may be that java has a lot more structure to it than PHP, which might be overcomplicating the whole thing? ultimately PHP can provide for the very basic interaction from request to response:
```
switch($_GET['page']) {
case "one";
print "page one!";
break;
default:
print "default page";
break;
}
```
and from there you can layer in all sorts of things to front controllers passing request objects down a filter chain to a page controller which reroutes to the appropriate model which grabs data via your db abstraction layer, filters it, back up to the controller, and on to the view which constructs the appropriate response, all the while firing off random event hooks. ultimately it's up to you (as developer) to choose what level of complexity/separation you're looking for. this is both the beauty and evilness of PHP :)
|
195,058 |
<p>Below is my $.ajax call, how do I put a selects (multiple) selected values in the data section?</p>
<pre><code>$.ajax({
type: "post",
url: "http://myServer" ,
dataType: "text",
data: {
'service' : 'myService',
'program' : 'myProgram',
'start' : start,
'end' : end ,
},
success: function(request) {
result.innerHTML = request ;
} // End success
}); // End ajax method
</code></pre>
<p><strong>EDIT</strong> I should have included that I understand how to loop through the selects selected options with this code:</p>
<pre><code>$('#userid option').each(function(i) {
if (this.selected == true) {
</code></pre>
<p>but how do I fit that into my data: section?</p>
|
[
{
"answer_id": 195064,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 4,
"selected": true,
"text": "<p>how about using an array?</p>\n\n<pre><code>data: {\n ...\n 'select' : ['value1', 'value2', 'value3'],\n ...\n},\n</code></pre>\n\n<p><strong>edit</strong>: ah sorry, here's the code, a few caveats:</p>\n\n<pre><code>'select' : $('#myselectbox').serializeArray(),\n</code></pre>\n\n<p>in order for serializeArray() to work though, all form elements must have a name attribute. the value of <code>'select'</code> above will be an array of objects containing the name and values of the selected elements.</p>\n\n<pre><code>'select' : [\n { 'name' : 'box', 'value' : 1 },\n { 'name' : 'box', 'value' : 2 }\n],\n</code></pre>\n\n<p>the select box to produce the above result would be:</p>\n\n<pre><code><select multiple=\"true\" name=\"box\" id=\"myselectbox\">\n <option value=\"1\" name=\"option1\" selected=\"selected\">One</option>\n <option value=\"2\" name=\"option2\" selected=\"selected\">Two</option>\n <option value=\"3\" name=\"option3\">Three</option>\n</select>\n</code></pre>\n"
},
{
"answer_id": 196274,
"author": "Jay Corbett",
"author_id": 2755,
"author_profile": "https://Stackoverflow.com/users/2755",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks to the answer from @Owen, I got this code to work.</p>\n\n<p>For a select box with an id=\"mySelect\" multiple=\"true\"</p>\n\n<pre><code> var mySelections = [];\n $('#mySelect option').each(function(i) {\n if (this.selected == true) {\n mySelections.push(this.value);\n }\n });\n\n\n $.ajax({\n type: \"post\",\n url: \"http://myServer\" ,\n dataType: \"text\",\n data: {\n 'service' : 'myService',\n 'program' : 'myProgram',\n 'selected' : mySelections\n },\n success: function(request) {\n result.innerHTML = request ;\n }\n }); // End ajax method\n</code></pre>\n"
},
{
"answer_id": 2199286,
"author": "EmanueleDG",
"author_id": 266138,
"author_profile": "https://Stackoverflow.com/users/266138",
"pm_score": 2,
"selected": false,
"text": "<p>The correct way to represent a collection of multiple options selected is to use an <strong>array</strong>, by naming the SELECT tag with a [] suffix.<br />\nThe problem is that it is not correctly handled by the jQuery method serialize().<br />\nFor a SELECT like this, infact:</p>\n\n<pre><select name="a[]">\n <option value="five">5</option>\n <option value="six">6</option>\n <option value="seven">7</option>\n</select>\n</pre>\n\n<p>serialize sends this array: a[]=0&a[]=1&a[]=2\nreceived by PHP this way:</p>\n\n<pre>[a] => Array\n (\n [0] => 0\n [1] => 1\n [2] => 2\n )\n</pre>\n\n<p>where real values are lost.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2755/"
] |
Below is my $.ajax call, how do I put a selects (multiple) selected values in the data section?
```
$.ajax({
type: "post",
url: "http://myServer" ,
dataType: "text",
data: {
'service' : 'myService',
'program' : 'myProgram',
'start' : start,
'end' : end ,
},
success: function(request) {
result.innerHTML = request ;
} // End success
}); // End ajax method
```
**EDIT** I should have included that I understand how to loop through the selects selected options with this code:
```
$('#userid option').each(function(i) {
if (this.selected == true) {
```
but how do I fit that into my data: section?
|
how about using an array?
```
data: {
...
'select' : ['value1', 'value2', 'value3'],
...
},
```
**edit**: ah sorry, here's the code, a few caveats:
```
'select' : $('#myselectbox').serializeArray(),
```
in order for serializeArray() to work though, all form elements must have a name attribute. the value of `'select'` above will be an array of objects containing the name and values of the selected elements.
```
'select' : [
{ 'name' : 'box', 'value' : 1 },
{ 'name' : 'box', 'value' : 2 }
],
```
the select box to produce the above result would be:
```
<select multiple="true" name="box" id="myselectbox">
<option value="1" name="option1" selected="selected">One</option>
<option value="2" name="option2" selected="selected">Two</option>
<option value="3" name="option3">Three</option>
</select>
```
|
195,061 |
<p>I have some assembly that references NUnit and creates a single test class with a single test method. I am able to get the file system path to this assembly (e.g. "C:...\test.dll"). I would like to programmatically use NUnit to run against this assembly.</p>
<p>So far I have:</p>
<pre><code>var runner = new SimpleTestRunner();
runner.Load(path);
var result = runner.Run(NullListener.NULL);
</code></pre>
<p>However, calling runner.Load(path) throws a FileNotFound exception. I can see through the stack trace that the problem is with NUnit calling Assembly.Load(path) down the stack. If I change path to be something like "Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" then I still get the same error.</p>
<p>I have added an event handler to AppDomain.Current.AssemblyResolve to see if I could manually resolve this type but my handler never gets called.</p>
<p>What is the secret to getting Assembly.Load(...) to work??</p>
|
[
{
"answer_id": 195066,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 2,
"selected": false,
"text": "<p>\"What is the secret to getting Assembly.Load to work?\"</p>\n\n<p>System.Reflection.Assembly.Load takes an string containing an assembly name, not a path to a file.</p>\n\n<p>If you want to load an assembly from a file use:</p>\n\n<pre><code>Assembly a = System.Reflection.Assembly.LoadFrom(pathToFileOnDisk);\n</code></pre>\n\n<p>(LoadFrom actually uses Assembly.Load internally)</p>\n\n<p>By the way, is there any reason why you can;t use the <a href=\"http://www.nunit.org/index.php?p=consoleCommandLine&r=2.2.4\" rel=\"nofollow noreferrer\">NUnit-Console command line tool</a> and just pass it the path to your test assembly? You could then just use the System.Diagnostics.Process to run this from within your client application, might be simpler?</p>\n"
},
{
"answer_id": 450076,
"author": "Ricibald",
"author_id": 20409,
"author_profile": "https://Stackoverflow.com/users/20409",
"pm_score": 6,
"selected": true,
"text": "<p>If you want to open in a <em>console mode</em>, add <strong>nunit-console-runner.dll</strong> reference and use:</p>\n\n<pre><code>NUnit.ConsoleRunner.Runner.Main(new string[]\n {\n System.Reflection.Assembly.GetExecutingAssembly().Location, \n });\n</code></pre>\n\n<p>If you want to open in a <em>gui mode</em>, add <strong>nunit-gui-runner.dll</strong> reference and use:</p>\n\n<pre><code>NUnit.Gui.AppEntry.Main(new string[]\n {\n System.Reflection.Assembly.GetExecutingAssembly().Location, \n \"/run\"\n });\n</code></pre>\n\n<p>This is the best approach because you don't have to specify any path.</p>\n\n<p>Another option is also to integrate NUnit runner in Visual Studio debugger output:</p>\n\n<pre><code>public static void Main()\n{\n var assembly = Assembly.GetExecutingAssembly().FullName;\n new TextUI (new DebugTextWriter()).Execute(new[] { assembly, \"-wait\" });\n}\n\npublic class DebugTextWriter : StreamWriter\n{\n public DebugTextWriter()\n : base(new DebugOutStream(), Encoding.Unicode, 1024)\n {\n this.AutoFlush = true;\n }\n\n class DebugOutStream : Stream\n {\n public override void Write(byte[] buffer, int offset, int count)\n {\n Debug.Write(Encoding.Unicode.GetString(buffer, offset, count));\n }\n\n public override bool CanRead { get { return false; } }\n public override bool CanSeek { get { return false; } }\n public override bool CanWrite { get { return true; } }\n public override void Flush() { Debug.Flush(); }\n public override long Length { get { throw new InvalidOperationException(); } }\n public override int Read(byte[] buffer, int offset, int count) { throw new InvalidOperationException(); }\n public override long Seek(long offset, SeekOrigin origin) { throw new InvalidOperationException(); }\n public override void SetLength(long value) { throw new InvalidOperationException(); }\n public override long Position\n {\n get { throw new InvalidOperationException(); }\n set { throw new InvalidOperationException(); }\n }\n };\n}\n</code></pre>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12958/"
] |
I have some assembly that references NUnit and creates a single test class with a single test method. I am able to get the file system path to this assembly (e.g. "C:...\test.dll"). I would like to programmatically use NUnit to run against this assembly.
So far I have:
```
var runner = new SimpleTestRunner();
runner.Load(path);
var result = runner.Run(NullListener.NULL);
```
However, calling runner.Load(path) throws a FileNotFound exception. I can see through the stack trace that the problem is with NUnit calling Assembly.Load(path) down the stack. If I change path to be something like "Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" then I still get the same error.
I have added an event handler to AppDomain.Current.AssemblyResolve to see if I could manually resolve this type but my handler never gets called.
What is the secret to getting Assembly.Load(...) to work??
|
If you want to open in a *console mode*, add **nunit-console-runner.dll** reference and use:
```
NUnit.ConsoleRunner.Runner.Main(new string[]
{
System.Reflection.Assembly.GetExecutingAssembly().Location,
});
```
If you want to open in a *gui mode*, add **nunit-gui-runner.dll** reference and use:
```
NUnit.Gui.AppEntry.Main(new string[]
{
System.Reflection.Assembly.GetExecutingAssembly().Location,
"/run"
});
```
This is the best approach because you don't have to specify any path.
Another option is also to integrate NUnit runner in Visual Studio debugger output:
```
public static void Main()
{
var assembly = Assembly.GetExecutingAssembly().FullName;
new TextUI (new DebugTextWriter()).Execute(new[] { assembly, "-wait" });
}
public class DebugTextWriter : StreamWriter
{
public DebugTextWriter()
: base(new DebugOutStream(), Encoding.Unicode, 1024)
{
this.AutoFlush = true;
}
class DebugOutStream : Stream
{
public override void Write(byte[] buffer, int offset, int count)
{
Debug.Write(Encoding.Unicode.GetString(buffer, offset, count));
}
public override bool CanRead { get { return false; } }
public override bool CanSeek { get { return false; } }
public override bool CanWrite { get { return true; } }
public override void Flush() { Debug.Flush(); }
public override long Length { get { throw new InvalidOperationException(); } }
public override int Read(byte[] buffer, int offset, int count) { throw new InvalidOperationException(); }
public override long Seek(long offset, SeekOrigin origin) { throw new InvalidOperationException(); }
public override void SetLength(long value) { throw new InvalidOperationException(); }
public override long Position
{
get { throw new InvalidOperationException(); }
set { throw new InvalidOperationException(); }
}
};
}
```
|
195,070 |
<p>I would like the fastest and most accurate function <code>boolean isReachable(String host, int port)</code> that passes the following JUnit tests under the conditions below. Timeout values are specified by the JUnit test itself, and may be considered "unreachable."</p>
<p><strong>Please note:</strong> All answers must be platform-independent. This means that <code>InetAddress.isReachable(int timeout)</code> is not going to work, since it relies on port <code>7</code> to do a ping on Windows (ICMP ping being an undocumented function on Windows), and this port is blocked in this setup.</p>
<p>LAN Setup:</p>
<ul>
<li><code>thisMachine</code> (<code>192.168.0.100</code>)</li>
<li><code>otherMachine</code> (<code>192.168.0.200</code>)</li>
<li><strong>no</strong> machine is called <code>noMachine</code> or has the IP <code>192.168.0.222</code> (always unreachable)</li>
<li>both machines are running Apache Tomcat on port <code>8080</code>; all other ports are unreachable (including port <code>7</code>)</li>
<li><code>example.com</code> (<code>208.77.188.166</code>) is running a webserver on port <code>80</code> and is only reachable when the LAN is connected to the Internet</li>
</ul>
<p>Occasionally, the LAN is disconnected from the Internet in which case only local machines called by IP address are reachable (all others are unreachable; there's no DNS).</p>
<p><strong>All tests are run on <code>thisMachine</code>.</strong></p>
<pre><code>@Test(timeout=1600) // ~320ms per call (should be possible to do better)
public void testLocalhost() {
// We can always reach ourselves.
assertTrue(isReachable("localhost", 8080));
assertTrue(isReachable("127.0.0.1", 8080));
assertTrue(isReachable("thisMachine", 8080)); // Even if there's no DNS!
assertTrue(isReachable("192.168.0.100", 8080));
assertFalse(isReachable("localhost", 80)); // Nothing on that port.
}
@Test(timeout=5500) // ~1867ms per call (should be able to do better)
public void testLAN() {
assertTrue(isReachable("192.168.0.200", 8080)); // Always connected to the LAN.
assertFalse(isReachable("192.168.0.222", 8080)); // No such a machine.
assertFalse(isReachable("noMachine", 8080)); // No such machine.
}
</code></pre>
<p>The following test is only run when the LAN is <strong>disconnected</strong> from the Internet.</p>
<pre><code>@Test(timeout=5600) // ~1867ms per call (reasonable?)
public void testNoDNS() {
assertFalse(isReachable("otherMachine", 8080)); // No DNS.
assertFalse(isReachable("example.com", 80)); // No DNS & no Internet.
assertFalse(isReachable("208.77.188.166", 80)); // No Internet.
}
</code></pre>
<p>The following test is only run when the LAN is <strong>connected</strong> to the Internet.</p>
<pre><code>@Test(timeout=5600) // ~1867ms per call (reasonable?)
public void testHaveDNS() {
assertTrue(isReachable("otherMachine", 8080)); // DNS resolves local names.
assertTrue(isReachable("example.com", 80)); // DNS available.
assertTrue(isReachable("208.77.188.166", 80)); // Internet available.
}
</code></pre>
|
[
{
"answer_id": 195071,
"author": "grammar31",
"author_id": 12815,
"author_profile": "https://Stackoverflow.com/users/12815",
"pm_score": 0,
"selected": false,
"text": "<p>My most recent solution depends using a <code>TimedSocket</code> (<a href=\"http://www.javaworld.com/jw-09-1999/jw-09-timeout.html\" rel=\"nofollow noreferrer\">source code</a>) with 3000ms timeout while performing a connect.</p>\n\n<p>Timings:</p>\n\n<ul>\n<li>1406ms : <code>testLocalHost()</code></li>\n<li>5280ms : <code>testLAN()</code></li>\n</ul>\n\n<p>Can't even get these to work properly:</p>\n\n<ul>\n<li><code>testNoDNS()</code></li>\n<li><code>testHaveDNS()</code></li>\n</ul>\n"
},
{
"answer_id": 195080,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure how practical this is.</p>\n\n<p>How about doing the equivalent of traceroute(tracert on windows) and once you get a success, you can proceed.</p>\n\n<p>In corporate networks, I've seen ICMP(ping) blocked by admins BUT usually, tracert still works. If you can figure out a quick way to do what tracert does, that should do the trick ?</p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 200221,
"author": "Jasper",
"author_id": 18702,
"author_profile": "https://Stackoverflow.com/users/18702",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to test whether you can connect to a web server you could also create a <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/net/URL.html\" rel=\"nofollow noreferrer\">URL</a> based on the host name and the port number and use that to create a <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/net/URLConnection.html\" rel=\"nofollow noreferrer\">URLConnection</a> checking the result (including exceptions) of the <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/net/URLConnection.html#connect()\" rel=\"nofollow noreferrer\">connect method</a> should tell you whether the webserver is reachable.</p>\n"
},
{
"answer_id": 200647,
"author": "Martin Spamer",
"author_id": 15527,
"author_profile": "https://Stackoverflow.com/users/15527",
"pm_score": 3,
"selected": false,
"text": "<p>Firstly you need to recognise that you have <em>potentially</em> conflicting requirements; IP sockets are not time deterministic. The quickest you can ever detect unreachability is after your elapsed timeout. You can only detect reachability quicker.</p>\n\n<p>Assuming reachability/isReachable is your real objective, you should just use a straightforward non-blocking socket IO as shown in the <a href=\"http://java.sun.com/j2se/1.4.2/docs/guide/nio/example/Ping.java\" rel=\"noreferrer\">Java Ping</a> simulator, the example connects to the time service but would work equally well on 8080.</p>\n"
},
{
"answer_id": 205500,
"author": "Tim Howland",
"author_id": 4276,
"author_profile": "https://Stackoverflow.com/users/4276",
"pm_score": 0,
"selected": false,
"text": "<p>If you need to do this with a seriously large number of hosts in a very brief period of time, I'd consider using a tool like <a href=\"http://fping.sourceforge.net/\" rel=\"nofollow noreferrer\">fping</a> instead- shell out to exec it and parse the output when it comes back. fping runs a large number of parallel queries at once, so you could theoretically check a few thousand hosts in a minute (I think the limit is 4096?)</p>\n"
},
{
"answer_id": 5827839,
"author": "David Moss",
"author_id": 730456,
"author_profile": "https://Stackoverflow.com/users/730456",
"pm_score": 0,
"selected": false,
"text": "<p>The rate determining step for host availability is not within your own code, but in the netlag. You must wait for the host to respond, and this can take time. If your program blocks while waiting for a response it could be a problem. I got around this by creating each host as an object, each with its own threaded method for checking availability. In my own situation I have 40 hosts I keep track of. My main program loops through an array of 40 machine objects once every 20 seconds, calling the appropriate method on each to check availability. Since each machine object spawns its own thread to do this, all 40 machines are interrogated concurrently and the (up to 500ms) response time for each isn't a problem.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12815/"
] |
I would like the fastest and most accurate function `boolean isReachable(String host, int port)` that passes the following JUnit tests under the conditions below. Timeout values are specified by the JUnit test itself, and may be considered "unreachable."
**Please note:** All answers must be platform-independent. This means that `InetAddress.isReachable(int timeout)` is not going to work, since it relies on port `7` to do a ping on Windows (ICMP ping being an undocumented function on Windows), and this port is blocked in this setup.
LAN Setup:
* `thisMachine` (`192.168.0.100`)
* `otherMachine` (`192.168.0.200`)
* **no** machine is called `noMachine` or has the IP `192.168.0.222` (always unreachable)
* both machines are running Apache Tomcat on port `8080`; all other ports are unreachable (including port `7`)
* `example.com` (`208.77.188.166`) is running a webserver on port `80` and is only reachable when the LAN is connected to the Internet
Occasionally, the LAN is disconnected from the Internet in which case only local machines called by IP address are reachable (all others are unreachable; there's no DNS).
**All tests are run on `thisMachine`.**
```
@Test(timeout=1600) // ~320ms per call (should be possible to do better)
public void testLocalhost() {
// We can always reach ourselves.
assertTrue(isReachable("localhost", 8080));
assertTrue(isReachable("127.0.0.1", 8080));
assertTrue(isReachable("thisMachine", 8080)); // Even if there's no DNS!
assertTrue(isReachable("192.168.0.100", 8080));
assertFalse(isReachable("localhost", 80)); // Nothing on that port.
}
@Test(timeout=5500) // ~1867ms per call (should be able to do better)
public void testLAN() {
assertTrue(isReachable("192.168.0.200", 8080)); // Always connected to the LAN.
assertFalse(isReachable("192.168.0.222", 8080)); // No such a machine.
assertFalse(isReachable("noMachine", 8080)); // No such machine.
}
```
The following test is only run when the LAN is **disconnected** from the Internet.
```
@Test(timeout=5600) // ~1867ms per call (reasonable?)
public void testNoDNS() {
assertFalse(isReachable("otherMachine", 8080)); // No DNS.
assertFalse(isReachable("example.com", 80)); // No DNS & no Internet.
assertFalse(isReachable("208.77.188.166", 80)); // No Internet.
}
```
The following test is only run when the LAN is **connected** to the Internet.
```
@Test(timeout=5600) // ~1867ms per call (reasonable?)
public void testHaveDNS() {
assertTrue(isReachable("otherMachine", 8080)); // DNS resolves local names.
assertTrue(isReachable("example.com", 80)); // DNS available.
assertTrue(isReachable("208.77.188.166", 80)); // Internet available.
}
```
|
Firstly you need to recognise that you have *potentially* conflicting requirements; IP sockets are not time deterministic. The quickest you can ever detect unreachability is after your elapsed timeout. You can only detect reachability quicker.
Assuming reachability/isReachable is your real objective, you should just use a straightforward non-blocking socket IO as shown in the [Java Ping](http://java.sun.com/j2se/1.4.2/docs/guide/nio/example/Ping.java) simulator, the example connects to the time service but would work equally well on 8080.
|
195,072 |
<p>I'm experiencing what I believe is a circular dependency issue with my PHP application. Please let me know if this is incorrect. Here is the situation:</p>
<p>Two classes, LogManager and DBSession.</p>
<p>DBSession is used to interact with the database, and LogManager is used to log to files. Both are widely used in my application. When you create an instance of DBSession, you must give it an instance of LogManager via a constructor parameter. This because DBSession will sometimes log information to a file, and will use the LogManager instance to do this. </p>
<p>Now, I wanted to extend LogManager so that it could also log to a database table, rather than a text file. Naturally, my preference is to re-use existing classes, but I soon realized this brought about an interesting situation.</p>
<p>DBSession already requires an instance of LogManager for construction. If I want to re-use the DBSession class in LogManager, it will now require an instance of DBSession. How can I satisfy both demands? Clearly, something must be wrong with my approach.</p>
<p>How would you suggest I fix this?</p>
<p>Thanks in advance, guys.</p>
|
[
{
"answer_id": 195076,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe you can apply some pattern, like the <a href=\"http://en.wikipedia.org/wiki/Singleton_pattern\" rel=\"nofollow noreferrer\">Singleton Pattern</a> to ensure that you only have one instance of your LogManager class for example.</p>\n"
},
{
"answer_id": 195083,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 4,
"selected": true,
"text": "<p>Don't extend LogManager, let it be an aggregate type. And delay the choice of where you want to log, i.e.:</p>\n\n<pre><code>$logManager = new LogManager();\n$dbSession = new DbSession($logManager);\n$logManager->add(new FileLog($filename) );\n$logManager->add(new DBLog($dbSession) );\n</code></pre>\n\n<p>Where of course FileLog and DBLog share a common interface.\nThis is an application of the Observer pattern, where add() is the \"subscribe\" operation, and FileLog/DBLog are the observers of logging events.\n(In this way you could also save logs in many places.)</p>\n\n<p><strong>Owen edit</strong>: adjusted to php syntax.</p>\n"
},
{
"answer_id": 195084,
"author": "Edward Z. Yang",
"author_id": 23845,
"author_profile": "https://Stackoverflow.com/users/23845",
"pm_score": 2,
"selected": false,
"text": "<p>One of these objects doesn't actually need the other: you guessed it, it's the DBSession. Modify that object so that the logger can be attached to it after construction.</p>\n"
},
{
"answer_id": 195087,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 2,
"selected": false,
"text": "<p>Why demand a LogManager object for the creation of a DbSession object, if it only sometimes writes to files? lazy load it instead only when you need it. Also, in my opinion both should be independent from each other. Each could instance the other when needed.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21263/"
] |
I'm experiencing what I believe is a circular dependency issue with my PHP application. Please let me know if this is incorrect. Here is the situation:
Two classes, LogManager and DBSession.
DBSession is used to interact with the database, and LogManager is used to log to files. Both are widely used in my application. When you create an instance of DBSession, you must give it an instance of LogManager via a constructor parameter. This because DBSession will sometimes log information to a file, and will use the LogManager instance to do this.
Now, I wanted to extend LogManager so that it could also log to a database table, rather than a text file. Naturally, my preference is to re-use existing classes, but I soon realized this brought about an interesting situation.
DBSession already requires an instance of LogManager for construction. If I want to re-use the DBSession class in LogManager, it will now require an instance of DBSession. How can I satisfy both demands? Clearly, something must be wrong with my approach.
How would you suggest I fix this?
Thanks in advance, guys.
|
Don't extend LogManager, let it be an aggregate type. And delay the choice of where you want to log, i.e.:
```
$logManager = new LogManager();
$dbSession = new DbSession($logManager);
$logManager->add(new FileLog($filename) );
$logManager->add(new DBLog($dbSession) );
```
Where of course FileLog and DBLog share a common interface.
This is an application of the Observer pattern, where add() is the "subscribe" operation, and FileLog/DBLog are the observers of logging events.
(In this way you could also save logs in many places.)
**Owen edit**: adjusted to php syntax.
|
195,078 |
<p>I need to hide (make private) the <code>-init</code> method of my class in Objective-C.</p>
<p>How can I do that?</p>
|
[
{
"answer_id": 195107,
"author": "Matt Dillard",
"author_id": 863,
"author_profile": "https://Stackoverflow.com/users/863",
"pm_score": 2,
"selected": false,
"text": "<p>That depends on what you mean by \"make private\". In Objective-C, calling a method on an object might better be described as sending a message to that object. There's nothing in the language that prohibits a client from calling any given method on an object; the best you can do is not declare the method in the header file. If a client nevertheless calls the \"private\" method with the right signature, it will still execute at runtime.</p>\n\n<p>That said, the most common way to create a private method in Objective-C is to create a <a href=\"http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/Articles/chapter_4_section_1.html\" rel=\"nofollow noreferrer\">Category</a> in the implementation file, and declare all of the \"hidden\" methods in there. Remember that this won't truly prevent calls to <code>init</code> from running, but the compiler will spit out warnings if anyone tries to do this.</p>\n\n<p>MyClass.m</p>\n\n<pre><code>@interface MyClass (PrivateMethods)\n- (NSString*) init;\n@end\n\n@implementation MyClass\n\n- (NSString*) init\n{\n // code...\n}\n\n@end\n</code></pre>\n\n<p>There's a decent <a href=\"http://forums.macrumors.com/showthread.php?t=470056\" rel=\"nofollow noreferrer\">thread</a> on MacRumors.com about this topic.</p>\n"
},
{
"answer_id": 195138,
"author": "Nathan Kinsinger",
"author_id": 20045,
"author_profile": "https://Stackoverflow.com/users/20045",
"pm_score": 2,
"selected": false,
"text": "<p>If you are talking about the default -init method then you can't. It's inherited from NSObject and every class will respond to it with no warnings.</p>\n\n<p>You could create a new method, say -initMyClass, and put it in a private category like Matt suggests. Then define the default -init method to either raise an exception if it's called or (better) call your private -initMyClass with some default values. </p>\n\n<p>One of the main reasons people seem to want to hide init is for <a href=\"http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/chapter_3_section_10.html\" rel=\"nofollow noreferrer\">singleton objects</a>. If that's the case then you don't need to hide -init, just return the singleton object instead (or create it if it doesn't exist yet).</p>\n"
},
{
"answer_id": 195223,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 7,
"selected": true,
"text": "<p>Objective-C, like Smalltalk, has no concept of \"private\" versus \"public\" methods. Any message can be sent to any object at any time.</p>\n\n<p>What you can do is throw an <code>NSInternalInconsistencyException</code> if your <code>-init</code> method is invoked:</p>\n\n<pre><code>- (id)init {\n [self release];\n @throw [NSException exceptionWithName:NSInternalInconsistencyException\n reason:@\"-init is not a valid initializer for the class Foo\"\n userInfo:nil];\n return nil;\n}\n</code></pre>\n\n<p>The other alternative — which is probably far better in practice — is to make <code>-init</code> do something sensible for your class if at all possible.</p>\n\n<p>If you're trying to do this because you're trying to \"ensure\" a singleton object is used, don't bother. Specifically, don't bother with the \"override <code>+allocWithZone:</code>, <code>-init</code>, <code>-retain</code>, <code>-release</code>\" method of creating singletons. It's virtually always unnecessary and is just adding complication for no real significant advantage.</p>\n\n<p>Instead, just write your code such that your <code>+sharedWhatever</code> method is how you access a singleton, and document that as the way to get the singleton instance in your header. That should be all you need in the vast majority of cases.</p>\n"
},
{
"answer_id": 5772821,
"author": "Jano",
"author_id": 412916,
"author_profile": "https://Stackoverflow.com/users/412916",
"pm_score": 9,
"selected": false,
"text": "<h3><code>NS_UNAVAILABLE</code></h3>\n\n<pre><code>- (instancetype)init NS_UNAVAILABLE;\n</code></pre>\n\n<p>This is a the short version of the unavailable attribute. It first appeared in macOS <a href=\"https://developer.apple.com/library/content/releasenotes/General/MacOSXLionAPIDiffs/Foundation.html\" rel=\"noreferrer\">10.7</a> and <a href=\"https://developer.apple.com/library/content/releasenotes/General/iOS50APIDiff/index.html\" rel=\"noreferrer\">iOS 5</a>. It is defined in NSObjCRuntime.h as <code>#define NS_UNAVAILABLE UNAVAILABLE_ATTRIBUTE</code>.</p>\n\n<p>There is a version that <a href=\"https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-ID178\" rel=\"noreferrer\">disables the method only for Swift clients</a>, not for ObjC code:</p>\n\n<pre><code>- (instancetype)init NS_SWIFT_UNAVAILABLE;\n</code></pre>\n\n<h3><code>unavailable</code></h3>\n\n<p>Add the <a href=\"http://clang.llvm.org/docs/LanguageExtensions.html#messages-on-deprecated-and-unavailable-attributes\" rel=\"noreferrer\"><code>unavailable</code></a> attribute to the header to generate a <strong>compiler error</strong> on any call to init.</p>\n\n<pre><code>-(instancetype) init __attribute__((unavailable(\"init not available\"))); \n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/AXcPr.png\" alt=\"compile time error\"></p>\n\n<p>If you don't have a reason, just type <code>__attribute__((unavailable))</code>, or even <code>__unavailable</code>:</p>\n\n<pre><code>-(instancetype) __unavailable init; \n</code></pre>\n\n<p></p>\n\n<h3><code>doesNotRecognizeSelector:</code></h3>\n\n<p>Use <a href=\"http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html\" rel=\"noreferrer\"><code>doesNotRecognizeSelector:</code></a> to raise a NSInvalidArgumentException. <em>“The runtime system invokes this method whenever an object receives an aSelector message it can’t respond to or forward.”</em></p>\n\n<pre><code>- (instancetype) init {\n [self release];\n [super doesNotRecognizeSelector:_cmd];\n return nil;\n}\n</code></pre>\n\n<p></p>\n\n<h3><code>NSAssert</code></h3>\n\n<p>Use <a href=\"https://developer.apple.com/library/mac/#documentation/cocoa/reference/foundation/miscellaneous/foundation_functions/reference/reference.html\" rel=\"noreferrer\"><code>NSAssert</code></a> to throw NSInternalInconsistencyException and show a message:</p>\n\n<pre><code>- (instancetype) init {\n [self release];\n NSAssert(false,@\"unavailable, use initWithBlah: instead\");\n return nil;\n}\n</code></pre>\n\n<p></p>\n\n<h3><code>raise:format:</code></h3>\n\n<p>Use <a href=\"https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSException_Class/Reference/Reference.html#//apple_ref/occ/clm/NSException/raise:format:\" rel=\"noreferrer\"><code>raise:format:</code></a> to throw your own exception:</p>\n\n<pre><code>- (instancetype) init {\n [self release];\n [NSException raise:NSGenericException \n format:@\"Disabled. Use +[[%@ alloc] %@] instead\",\n NSStringFromClass([self class]),\n NSStringFromSelector(@selector(initWithStateDictionary:))];\n return nil;\n}\n</code></pre>\n\n<p><code>[self release]</code> is needed because the object was already <code>alloc</code>ated. When using ARC the compiler will call it for you. In any case, not something to worry when you are about to intentionally stop execution.</p>\n\n<h3><code>objc_designated_initializer</code></h3>\n\n<p>In case you intend to disable <code>init</code> to force the use of a designated initializer, there is an attribute for that:</p>\n\n<pre><code>-(instancetype)myOwnInit NS_DESIGNATED_INITIALIZER;\n</code></pre>\n\n<p>This generates a warning unless any other initializer method calls <code>myOwnInit</code> internally. Details will be published in <a href=\"https://developer.apple.com/library/ios/releasenotes/ObjectiveC/ModernizationObjC/AdoptingModernObjective-C/AdoptingModernObjective-C.html#//apple_ref/doc/uid/TP40014150\" rel=\"noreferrer\">Adopting Modern Objective-C</a> after next Xcode release (I guess).</p>\n"
},
{
"answer_id": 8431959,
"author": "Peter Lapisu",
"author_id": 533422,
"author_profile": "https://Stackoverflow.com/users/533422",
"pm_score": 2,
"selected": false,
"text": "<p>well the problem why you can't make it \"private/invisible\" is cause the init method gets send to id (as alloc returns an id) not to YourClass </p>\n\n<p>Note that from the point of the compiler (checker) an id could potencialy respond to anything ever typed (it can't check what really goes into the id at runtime), so you could hide init only when nothing nowhere would (publicly = in header) use a method init, than the compile would know, that there is no way for id to respond to init, since there is no init anywhere (in your source, all libs etc...)</p>\n\n<p>so you cannot forbid the user to pass init and get smashed by the compiler... but what you can do, is to prevent the user from getting a real instance by calling a init</p>\n\n<p>simply by implementing init, which returns nil and have an (private / invisible) initializer which name somebody else won't get (like initOnce, initWithSpecial ...)</p>\n\n<pre><code>static SomeClass * SInstance = nil;\n\n- (id)init\n{\n // possibly throw smth. here\n return nil;\n}\n\n- (id)initOnce\n{\n self = [super init];\n if (self) {\n return self;\n }\n return nil;\n}\n\n+ (SomeClass *) shared \n{\n if (nil == SInstance) {\n SInstance = [[SomeClass alloc] initOnce];\n }\n return SInstance;\n}\n</code></pre>\n\n<p>Note : that somebody could do this</p>\n\n<pre><code>SomeClass * c = [[SomeClass alloc] initOnce];\n</code></pre>\n\n<p>and it would in fact return a new instance, but if the initOnce would nowhere in our project be publicly (in header) declared, it would generate a warning (id might not respond ...) and anyway the person using this, would need to know exactly that the real initializer is the initOnce</p>\n\n<p>we could prevent this even further, but there is no need</p>\n"
},
{
"answer_id": 23644634,
"author": "techniao",
"author_id": 2400328,
"author_profile": "https://Stackoverflow.com/users/2400328",
"pm_score": 0,
"selected": false,
"text": "<p>I have to mention that placing assertions and raising exceptions to hide methods in the subclass has a nasty trap for the well-intended.</p>\n\n<p>I would recommend using <code>__unavailable</code> as <a href=\"https://stackoverflow.com/a/5772821/2400328\">Jano explained for his first example</a>.</p>\n\n<p>Methods can be overridden in subclasses. This means that if a method in the superclass uses a method that just raises an exception in the subclass, it probably won't work as intended. In other words, you've just broken what used to work. This is true with initialization methods as well. Here is an example of such rather common implementation:</p>\n\n<pre><code>- (SuperClass *)initWithParameters:(Type1 *)arg1 optional:(Type2 *)arg2\n{\n ...bla bla...\n return self;\n}\n\n- (SuperClass *)initWithLessParameters:(Type1 *)arg1\n{\n self = [self initWithParameters:arg1 optional:DEFAULT_ARG2];\n return self;\n}\n</code></pre>\n\n<p>Imagine what happens to -initWithLessParameters, if I do this in the subclass:</p>\n\n<pre><code>- (SubClass *)initWithParameters:(Type1 *)arg1 optional:(Type2 *)arg2\n{\n [self release];\n [super doesNotRecognizeSelector:_cmd];\n return nil;\n}\n</code></pre>\n\n<p>This implies that you should tend to use private (hidden) methods, especially in initialization methods, unless you plan to have the methods overridden. But, this is another topic, since you don't always have full control in the implementation of the superclass. (This makes me question the use of __attribute((objc_designated_initializer)) as bad practice, although I haven't used it in depth.)</p>\n\n<p>It also implies that you can use assertions and exceptions in methods that must be overridden in subclasses. (The \"abstract\" methods as in <a href=\"https://stackoverflow.com/questions/1034373/creating-an-abstract-class-in-objective-c\">Creating an abstract class in Objective-C</a> )</p>\n\n<p>And, don't forget about the +new class method.</p>\n"
},
{
"answer_id": 27693034,
"author": "lehn0058",
"author_id": 1199792,
"author_profile": "https://Stackoverflow.com/users/1199792",
"pm_score": 7,
"selected": false,
"text": "<p>Apple has started using the following in their header files to disable the init constructor:</p>\n\n<pre><code>- (instancetype)init NS_UNAVAILABLE;\n</code></pre>\n\n<p>This correctly displays as a compiler error in Xcode. Specifically, this is set in several of their HealthKit header files (HKUnit is one of them).</p>\n"
},
{
"answer_id": 30387880,
"author": "Jerry Juang",
"author_id": 2588432,
"author_profile": "https://Stackoverflow.com/users/2588432",
"pm_score": 2,
"selected": false,
"text": "<p>Put this in header file</p>\n\n<pre><code>- (id)init UNAVAILABLE_ATTRIBUTE;\n</code></pre>\n"
},
{
"answer_id": 45629903,
"author": "Kaunteya",
"author_id": 1311902,
"author_profile": "https://Stackoverflow.com/users/1311902",
"pm_score": 2,
"selected": false,
"text": "<p>You can declare any method to be not available using <code>NS_UNAVAILABLE</code>.</p>\n\n<p>So you can put these lines below your @interface</p>\n\n<pre><code>- (instancetype)init NS_UNAVAILABLE;\n+ (instancetype)new NS_UNAVAILABLE;\n</code></pre>\n\n<hr>\n\n<p>Even better define a macro in your prefix header</p>\n\n<pre><code>#define NO_INIT \\\n- (instancetype)init NS_UNAVAILABLE; \\\n+ (instancetype)new NS_UNAVAILABLE;\n</code></pre>\n\n<p>and</p>\n\n<pre><code>@interface YourClass : NSObject\nNO_INIT\n\n// Your properties and messages\n\n@end\n</code></pre>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3740/"
] |
I need to hide (make private) the `-init` method of my class in Objective-C.
How can I do that?
|
Objective-C, like Smalltalk, has no concept of "private" versus "public" methods. Any message can be sent to any object at any time.
What you can do is throw an `NSInternalInconsistencyException` if your `-init` method is invoked:
```
- (id)init {
[self release];
@throw [NSException exceptionWithName:NSInternalInconsistencyException
reason:@"-init is not a valid initializer for the class Foo"
userInfo:nil];
return nil;
}
```
The other alternative — which is probably far better in practice — is to make `-init` do something sensible for your class if at all possible.
If you're trying to do this because you're trying to "ensure" a singleton object is used, don't bother. Specifically, don't bother with the "override `+allocWithZone:`, `-init`, `-retain`, `-release`" method of creating singletons. It's virtually always unnecessary and is just adding complication for no real significant advantage.
Instead, just write your code such that your `+sharedWhatever` method is how you access a singleton, and document that as the way to get the singleton instance in your header. That should be all you need in the vast majority of cases.
|
195,114 |
<p>I'm trying to do a custom button to my form (which has FormBorderStyle = none) using Visual Studio 2005. I have my 3 states button images in an ImageList linked to the button.</p>
<pre><code>this.btnClose.AutoSize = false;
this.btnClose.BackColor = System.Drawing.Color.Transparent;
this.btnClose.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
this.btnClose.FlatAppearance.BorderSize = 0;
this.btnClose.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnClose.ForeColor = System.Drawing.Color.Transparent;
this.btnClose.ImageKey = "Disabled";
this.btnClose.ImageList = this.imageList1;
this.btnClose.Location = new System.Drawing.Point(368, -5);
this.btnClose.Margin = new System.Windows.Forms.Padding(0);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(31, 31);
this.btnClose.TabIndex = 0;
this.btnClose.UseVisualStyleBackColor = false;
this.btnClose.MouseLeave += new System.EventHandler(this.btnClose_MouseLeave);
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
this.btnClose.MouseDown += new System.Windows.Forms.MouseEventHandler(this.btnClose_MouseDown);
this.btnClose.MouseHover += new System.EventHandler(this.btnClose_MouseHover);
private void btnClose_MouseHover(object sender, EventArgs e)
{
btnClose.ImageKey = "enabled";
}
private void btnClose_MouseDown(object sender, MouseEventArgs e)
{
btnClose.ImageKey = "down";
}
private void btnClose_MouseLeave(object sender, EventArgs e)
{
btnClose.ImageKey = "disabled";
}
</code></pre>
<p>All is working, but there's one catch. Whenever I move the mouse hover the button I get a really annoying grey background.</p>
<p>How can I remove that?</p>
|
[
{
"answer_id": 195128,
"author": "faulty",
"author_id": 20007,
"author_profile": "https://Stackoverflow.com/users/20007",
"pm_score": 5,
"selected": true,
"text": "<p>The grey background is due to the setting of \"System.Windows.Forms.FlatStyle.Flat\", it's the default behaviour, since it need to highlight the button when you hover. To eliminate that, you might have to write a custom button class, inherit from the original button and do some custom painting to achieve that.</p>\n\n<p>Btw, instead of setting \"enabled\" in MouseHover, you should do it in MouseEnter. MouseEnter and MouseLeave is a pair which indicate whether is the mouse is within the button or not, and it's fired once per entry/exit. Where as MouseHover is fire whenever the mouse moved within the button, which create unnessecery repeated setting of \"enabled\". </p>\n"
},
{
"answer_id": 196202,
"author": "Tute",
"author_id": 4386,
"author_profile": "https://Stackoverflow.com/users/4386",
"pm_score": 2,
"selected": false,
"text": "<p>I've solved this using a label instead of a button.</p>\n\n<pre><code>// \n// imageListButtons\n// \nthis.imageListButtons.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject(\"imageListButtons.ImageStream\")));\nthis.imageListButtons.TransparentColor = System.Drawing.Color.Transparent;\nthis.imageListButtons.Images.SetKeyName(0, \"close_normal\");\nthis.imageListButtons.Images.SetKeyName(1, \"close_hover\");\n// \n// lblClose\n// \nthis.lblClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));\nthis.lblClose.BackColor = System.Drawing.Color.Transparent;\nthis.lblClose.ImageKey = \"close_normal\";\nthis.lblClose.ImageList = this.imageListButtons;\nthis.lblClose.Location = new System.Drawing.Point(381, 7);\nthis.lblClose.Margin = new System.Windows.Forms.Padding(0);\nthis.lblClose.Name = \"lblClose\";\nthis.lblClose.Size = new System.Drawing.Size(12, 12);\nthis.lblClose.TabIndex = 0;\nthis.lblClose.MouseLeave += new System.EventHandler(this.lblClose_MouseLeave);\nthis.lblClose.MouseClick += new System.Windows.Forms.MouseEventHandler(this.lblClose_MouseClick);\nthis.lblClose.MouseEnter += new System.EventHandler(this.lblClose_MouseEnter);\n\n\nprivate void lblClose_MouseEnter(object sender, EventArgs e)\n{\n lblClose.ImageKey = \"close_hover\";\n}\n\nprivate void lblClose_MouseLeave(object sender, EventArgs e)\n{\n lblClose.ImageKey = \"close_normal\";\n}\n\nprivate void lblClose_MouseClick(object sender, MouseEventArgs e)\n{\n this.Close();\n}\n</code></pre>\n\n<p>PS: notice that I'm using now a two state button, instead of three. It is intended (I know that I still can use three).</p>\n"
},
{
"answer_id": 2951036,
"author": "Vassili",
"author_id": 355568,
"author_profile": "https://Stackoverflow.com/users/355568",
"pm_score": 5,
"selected": false,
"text": "<pre><code>btnClose.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;\n</code></pre>\n"
},
{
"answer_id": 20713586,
"author": "Fazil Mir",
"author_id": 2902517,
"author_profile": "https://Stackoverflow.com/users/2902517",
"pm_score": 2,
"selected": false,
"text": "<p>create Mouse Enter event which is given below.</p>\n\n<pre><code>private void forAllButtons_MouseEnter(object sender, EventArgs e)\n{\n Button b = (Button)sender;\n b.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;\n}\n</code></pre>\n\n<p>then assign this event to all the buttons.</p>\n\n<p>Happy programming :)</p>\n"
},
{
"answer_id": 23547572,
"author": "Robin",
"author_id": 3617356,
"author_profile": "https://Stackoverflow.com/users/3617356",
"pm_score": 0,
"selected": false,
"text": "<p>You can also stop changing color of button by deselecting IsHitTestVisible option in Button Properties>common> IsHitTestVisible\nMaybe this can also help ...</p>\n"
},
{
"answer_id": 32729645,
"author": "Ahmed Suror",
"author_id": 1655837,
"author_profile": "https://Stackoverflow.com/users/1655837",
"pm_score": 2,
"selected": false,
"text": "<p>I have got one suggestion.Create your own button class deriving from Button.Then override the MouseEnter event in that.Just remove the code for calling the base implementaion.</p>\n<pre><code>base.OnMouseEnter(e)\n</code></pre>\n<p>PS: You won't be able to use the MouseEnter event outside the derived class (e.g. a project using this control)</p>\n"
},
{
"answer_id": 35957916,
"author": "Peck_conyon",
"author_id": 3268370,
"author_profile": "https://Stackoverflow.com/users/3268370",
"pm_score": 1,
"selected": false,
"text": "<p>Hi you simply can apply these changes to your button easily using these two lines of codes.</p>\n\n<ol>\n<li><p>Set the button's FlatStyle to Flat</p>\n\n<pre><code>this.btnClose.FlatStyle = FlatStyle.Flat;\n</code></pre></li>\n<li><p>Set the button's MouseOverBackColor to Transparent</p>\n\n<pre><code>this.btnClose.FlatAppearance.MouseOverBackColor = Color.Transparent;\n</code></pre></li>\n</ol>\n\n<p>Hope this will help. Thanks</p>\n"
},
{
"answer_id": 46028724,
"author": "Sospeter Mong'are",
"author_id": 5349470,
"author_profile": "https://Stackoverflow.com/users/5349470",
"pm_score": -1,
"selected": false,
"text": "<p>To solve the problem, Set the MouseOverBackColor to transparent inorder to remove the grey backgroud.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4386/"
] |
I'm trying to do a custom button to my form (which has FormBorderStyle = none) using Visual Studio 2005. I have my 3 states button images in an ImageList linked to the button.
```
this.btnClose.AutoSize = false;
this.btnClose.BackColor = System.Drawing.Color.Transparent;
this.btnClose.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
this.btnClose.FlatAppearance.BorderSize = 0;
this.btnClose.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnClose.ForeColor = System.Drawing.Color.Transparent;
this.btnClose.ImageKey = "Disabled";
this.btnClose.ImageList = this.imageList1;
this.btnClose.Location = new System.Drawing.Point(368, -5);
this.btnClose.Margin = new System.Windows.Forms.Padding(0);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(31, 31);
this.btnClose.TabIndex = 0;
this.btnClose.UseVisualStyleBackColor = false;
this.btnClose.MouseLeave += new System.EventHandler(this.btnClose_MouseLeave);
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
this.btnClose.MouseDown += new System.Windows.Forms.MouseEventHandler(this.btnClose_MouseDown);
this.btnClose.MouseHover += new System.EventHandler(this.btnClose_MouseHover);
private void btnClose_MouseHover(object sender, EventArgs e)
{
btnClose.ImageKey = "enabled";
}
private void btnClose_MouseDown(object sender, MouseEventArgs e)
{
btnClose.ImageKey = "down";
}
private void btnClose_MouseLeave(object sender, EventArgs e)
{
btnClose.ImageKey = "disabled";
}
```
All is working, but there's one catch. Whenever I move the mouse hover the button I get a really annoying grey background.
How can I remove that?
|
The grey background is due to the setting of "System.Windows.Forms.FlatStyle.Flat", it's the default behaviour, since it need to highlight the button when you hover. To eliminate that, you might have to write a custom button class, inherit from the original button and do some custom painting to achieve that.
Btw, instead of setting "enabled" in MouseHover, you should do it in MouseEnter. MouseEnter and MouseLeave is a pair which indicate whether is the mouse is within the button or not, and it's fired once per entry/exit. Where as MouseHover is fire whenever the mouse moved within the button, which create unnessecery repeated setting of "enabled".
|
195,116 |
<p>Does anyone know of a faster decimal implementation in python?</p>
<p>As the example below demonstrates, the standard library's decimal module is ~100 times slower than <code>float</code>.</p>
<pre class="lang-py prettyprint-override"><code>from timeit import Timer
def run(val, the_class):
test = the_class(1)
for c in xrange(10000):
d = the_class(val)
d + test
d - test
d * test
d / test
d ** test
str(d)
abs(d)
if __name__ == "__main__":
a = Timer("run(123.345, float)", "from decimal_benchmark import run")
print "FLOAT", a.timeit(1)
a = Timer("run('123.345', Decimal)", "from decimal_benchmark import run; from decimal import Decimal")
print "DECIMAL", a.timeit(1)
</code></pre>
<p><em>Outputs:</em></p>
<pre><code>FLOAT 0.040635041427
DECIMAL 3.39666790146
</code></pre>
|
[
{
"answer_id": 195124,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 5,
"selected": true,
"text": "<p>The <a href=\"http://gmplib.org\" rel=\"noreferrer\">GMP</a> library is one of the best arbitrary precision math libraries around, and there is a Python binding available at <a href=\"http://www.aleax.it/gmpy.html\" rel=\"noreferrer\">GMPY</a>. I would try that method.</p>\n"
},
{
"answer_id": 195140,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 2,
"selected": false,
"text": "<p>You should compare <em>Decimal</em> to <em>Long Integer</em> performance, not floating point. Floating point is mostly hardware these days. <em>Decimal</em> is used for <strong>decimal precision</strong>, while <em>Floating Point</em> is for wider range. Use the <em>decimal</em> package for monetary calculations.</p>\n<p>To quote the <em>decimal</em> package manual:</p>\n<blockquote>\n<p>Decimal numbers can be represented exactly. In contrast, numbers like 1.1 do not have an exact representation in binary floating point. End users typically would not expect 1.1 to display as 1.1000000000000001 as it does with binary floating point.</p>\n<p>The exactness carries over into arithmetic. In decimal floating point, "0.1 + 0.1 + 0.1 - 0.3" is exactly equal to zero. In binary floating point, result is 5.5511151231257827e-017. While near to zero, the differences prevent reliable equality testing and differences can accumulate. For this reason, decimal would be preferred in accounting applications which have strict equality invariants.</p>\n</blockquote>\n"
},
{
"answer_id": 8192918,
"author": "Andrew G",
"author_id": 995672,
"author_profile": "https://Stackoverflow.com/users/995672",
"pm_score": 5,
"selected": false,
"text": "<p>You can try <a href=\"http://www.bytereef.org/mpdecimal/index.html\" rel=\"nofollow noreferrer\">cdecimal</a>:</p>\n\n<pre><code>from cdecimal import Decimal\n</code></pre>\n\n<p>As of Python 3.3, the cdecimal implementation is now the built-in implementation of the <code>decimal</code> standard library module, so you don't need to install anything. Just use <code>decimal</code>.</p>\n\n<p>For Python 2.7, installing <code>cdecimal</code> and using it instead of <code>decimal</code> should provide a speedup similar to what Python 3 gets by default.</p>\n"
},
{
"answer_id": 13876446,
"author": "pranjal",
"author_id": 319806,
"author_profile": "https://Stackoverflow.com/users/319806",
"pm_score": 0,
"selected": false,
"text": "<p>python Decimal is very slow, one can use float or a faster implementation of Decimal cDecimal.</p>\n"
},
{
"answer_id": 24408798,
"author": "Joel Santirso",
"author_id": 567959,
"author_profile": "https://Stackoverflow.com/users/567959",
"pm_score": 2,
"selected": false,
"text": "<p>Use <a href=\"http://www.bytereef.org/mpdecimal/index.html\" rel=\"nofollow\">cDecimal</a>.</p>\n\n<p>Adding the following to your benchmark:</p>\n\n<pre><code>a = Timer(\"run('123.345', Decimal)\", \"import sys; import cdecimal; sys.modules['decimal'] = cdecimal; from decimal_benchmark import run; from decimal import Decimal\")\nprint \"CDECIMAL\", a.timeit(1)\n</code></pre>\n\n<p>My results are:</p>\n\n<pre><code>FLOAT 0.0257983528473\nDECIMAL 2.45782495288\nCDECIMAL 0.0687125069413\n</code></pre>\n\n<p>(Python 2.7.6/32, Win7/64, AMD Athlon II 2.1GHz)</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/52490/"
] |
Does anyone know of a faster decimal implementation in python?
As the example below demonstrates, the standard library's decimal module is ~100 times slower than `float`.
```py
from timeit import Timer
def run(val, the_class):
test = the_class(1)
for c in xrange(10000):
d = the_class(val)
d + test
d - test
d * test
d / test
d ** test
str(d)
abs(d)
if __name__ == "__main__":
a = Timer("run(123.345, float)", "from decimal_benchmark import run")
print "FLOAT", a.timeit(1)
a = Timer("run('123.345', Decimal)", "from decimal_benchmark import run; from decimal import Decimal")
print "DECIMAL", a.timeit(1)
```
*Outputs:*
```
FLOAT 0.040635041427
DECIMAL 3.39666790146
```
|
The [GMP](http://gmplib.org) library is one of the best arbitrary precision math libraries around, and there is a Python binding available at [GMPY](http://www.aleax.it/gmpy.html). I would try that method.
|
195,150 |
<p>How can I raise an event from a SWF file loaded into a Flex application (using SWFLoader)?</p>
<p>I want to be able to detect</p>
<pre><code>a) when a button is pressed
b) when the animation ends
</code></pre>
|
[
{
"answer_id": 195160,
"author": "Christophe Herreman",
"author_id": 17255,
"author_profile": "https://Stackoverflow.com/users/17255",
"pm_score": 2,
"selected": false,
"text": "<p>You'll need to do 2 things:</p>\n\n<ol>\n<li>Dispatch an event from the loaded swf. Make sure the event bubbles if you sent it from nested views. Bubbling can be set through the bubbles property of the event.</li>\n<li><p>Listen to the event from your main application. I think you should be able to do that on the content property of the SWFLoader instance.</p>\n\n<pre><code>mySWFLoader.content.addEventListener(\"myEvent\", myEventHandler);\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 195249,
"author": "Simon",
"author_id": 24039,
"author_profile": "https://Stackoverflow.com/users/24039",
"pm_score": 0,
"selected": false,
"text": "<p>As an adjunct to the answer by Christophe Herreman, and in case you were wondering, here is a way of making your own events...</p>\n\n<pre><code>package yourpackage.events\n{\n import flash.events.Event;\n\n [Event(name=\"EV_Notify\", type=\"yourpackage.events.EV_Notify\")]\n public class EV_Notify extends Event\n {\n public function EV_Notify(bubbles:Boolean=true, cancelable:Boolean=false)\n {\n super(\"EV_Notify\", bubbles, cancelable);\n }\n\n }\n}\n</code></pre>\n\n<p>I have taken the liberty of setting the default value of <code>bubbles</code> to true and passing the custom event type to the super constructor by default, so you can then just say...</p>\n\n<pre><code>dispatchEvent(new EV_Notify());\n</code></pre>\n\n<p>In your particular case I doubt there are times when you would not want your event to bubble.</p>\n\n<p>The prefix <code>EV_</code> on the name is my own convention for events so I can easily find them in the code completion popups, you'll obviously pick your own name.</p>\n\n<p>For the two cases you cite you can either have two events and listen for both of them, or add a property to the event which says what just happened, which is the approach which is taken by controls like <code>Alert</code>...</p>\n\n<pre><code>package yourpackage.events\n{\n import flash.events.Event;\n\n [Event(name=\"EV_Notify\", type=\"yourpackage.events.EV_Notify\")]\n public class EV_Notify extends Event\n {\n public static var BUTTON_PRESSED:int = 1;\n public static var ANIMATION_ENDED:int = 2;\n\n public var whatHappened:int;\n\n public function EV_Notify(whatHappened:int, bubbles:Boolean=true, cancelable:Boolean=false)\n {\n this.whatHappened = whatHappened;\n super(\"EV_Notify\", bubbles, cancelable);\n }\n\n }\n}\n</code></pre>\n\n<p>then you call it as follows...</p>\n\n<pre><code>dispatchEvent(new EV_Notify(EV_NOTIFY.ANIMATION_ENDED));\n</code></pre>\n\n<p>you can then inspect the whatHappened field in your event handler.</p>\n\n<pre><code>private function handleNotify(ev:EV_Notify):void\n{\n if (ev.whatHappened == EV_Notify.ANIMATION_ENDED)\n {\n // do something\n }\n else if (ev.whatHappened == EV_Notify.BUTTON_PRESSED)\n {\n // do something else\n }\n etc...\n}\n</code></pre>\n\n<p>HTH</p>\n"
},
{
"answer_id": 195987,
"author": "Simon",
"author_id": 24727,
"author_profile": "https://Stackoverflow.com/users/24727",
"pm_score": 2,
"selected": false,
"text": "<p>I took a lazier approach for raising the event inside flash</p>\n\n<h2>Flex:</h2>\n\n<pre><code><mx:SWFLoader source=\"homeanimations/tired.swf\" id=\"swfTired\" complete=\"swfTiredLoaded(event)\" />\n\nprivate function swfTiredLoaded(event:Event): void {\n mySWFLoader.content.addEventListener(\"continueClicked\", continueClickedHandler);\n}\n</code></pre>\n\n<h2>Flash:</h2>\n\n<pre><code>dispatchEvent(new Event(\"continueClicked\", true, true));\n</code></pre>\n"
},
{
"answer_id": 697032,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I could not make this last approach work (with Flash CS4 and Flex 3). I put the dispatchEvent call in one of the last frames of my Flash animation, but could not pick it up in Flex. </p>\n\n<p>I resorted to a counter variable and incrementing until I reached the known last frame number using the ENTER_FRAME event - which I can pick up using almost the same code. </p>\n\n<p>If I can pick this up, then why can't I pick up a custom event?</p>\n"
},
{
"answer_id": 5949423,
"author": "Ashar Azeem",
"author_id": 746748,
"author_profile": "https://Stackoverflow.com/users/746748",
"pm_score": 1,
"selected": false,
"text": "<p>I believe its because you would be creating two seperate custom event class one in Flash and the other in Flex.\nDispatching one EV_NOTIFY.ANIMATION_ENDED from Flash may not be understood by Flex,since it has its own version of EV_NOTIFY.ANIMATION_ENDED.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24727/"
] |
How can I raise an event from a SWF file loaded into a Flex application (using SWFLoader)?
I want to be able to detect
```
a) when a button is pressed
b) when the animation ends
```
|
You'll need to do 2 things:
1. Dispatch an event from the loaded swf. Make sure the event bubbles if you sent it from nested views. Bubbling can be set through the bubbles property of the event.
2. Listen to the event from your main application. I think you should be able to do that on the content property of the SWFLoader instance.
```
mySWFLoader.content.addEventListener("myEvent", myEventHandler);
```
|
195,151 |
<p>I have a ListView in WPF that is databound to a basic table that I pull from the database. The code for the ListView is as follows:</p>
<pre><code><ListView Canvas.Left="402" Canvas.Top="480" Height="78" ItemsSource="{Binding}" Name="lsvViewEditCardPrint" Width="419">
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Path=IdCst}">Set</GridViewColumn>
<GridViewColumn DisplayMemberBinding="{Binding Path=Language}">Language</GridViewColumn>
<GridViewColumn DisplayMemberBinding="{Binding Path=Number}">Number</GridViewColumn>
<GridViewColumn DisplayMemberBinding="{Binding Path=IdArt}">Artwork</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</code></pre>
<p>The IdCst column is a foreign key to a separate table, and I'd like to display the actual name field from that table instead of just the Id. Does anybody know how to set a databinding, or is there an event, such as OnItemDataBound, that I could intercept to modify the display?</p>
|
[
{
"answer_id": 195171,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 3,
"selected": true,
"text": "<p>This blog <a href=\"http://almosteric.wordpress.com/2008/06/24/databinding-to-foreign-keys-in-wpf/\" rel=\"nofollow noreferrer\">post</a> may help:</p>\n\n<blockquote>\n <p>...I assumed the foreign key should be bound to the ‘SelectedValue’ property,\n and there is an ItemSource that I can\n bind to my fact table so the drop down\n is populated.</p>\n \n <p>At this point my dropdown worked, but\n nothing would appear in the combobox. \n I finally noticed a ‘SelectedItemPath’\n property - I assumed this would be the\n name of the field in my dropdown that\n was associated to my foreign key. Sure\n enough, that’s exactly what it is.</p>\n</blockquote>\n"
},
{
"answer_id": 198015,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 1,
"selected": false,
"text": "<p>I'd add a new property to your underlying class:</p>\n\n<pre><code>Public ReadOnly Property NameCst() as String\n Get\n Return Names.LookupName(Me.IdCst)\n End Get\nEnd Property\n</code></pre>\n\n<p>or something similar. Note that you'll probably have to include a Notify Property Changed event in your .IdCst setter for \"NameCst\".</p>\n\n<p>An alternative is to write a ValueConverter that does the lookup, but that's pretty heavy weight for something so simple.</p>\n"
},
{
"answer_id": 230950,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": -1,
"selected": false,
"text": "<p>BOO YAH!!!</p>\n\n<p>I looked at the samples here, dug off a few of the references from other posts here, and found the answer... IValueConverter ... an interface that can be used with WPF that will convert values at the point of binding. It is a little tricky to put together at first, but not that difficult.</p>\n\n<p>The first step is to create a simple lookup or converter class that implements the IValueConverter interface. For my solution, I did this:</p>\n\n<pre><code>Namespace TCRConverters\n\n Public Class SetIdToNameConverter\n Implements IValueConverter\n\n Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert\n Dim taCardSet As New TCRTableAdapters.CardSetTableAdapter\n Return taCardSet.GetDataById(DirectCast(value, Integer)).Item(0).Name\n End Function\n\n Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack\n Return Nothing\n End Function\n\n End Class\n\nEnd Namespace\n</code></pre>\n\n<p><em>Note: I am not utilizing the ConvertBack method, but it is required by the interface.</em></p>\n\n<p>From there you need to add a reference to the namespace in your XAML header section:</p>\n\n<pre><code><Window x:Class=\"Main\" Loaded=\"Main_Loaded\"\n // Standard references here...\n xmlns:c=\"clr-namespace:TCR_Editor.TCRConverters\"\n Title=\"TCR Editor\" Height=\"728\" Width=\"1135\" Name=\"Main\">\n</code></pre>\n\n<p>Then in your Windows.Resources section, you can reference the converter, and in my case, I created a static reference to the CollectionViewSource that would be storing the data:</p>\n\n<pre><code><Window.Resources>\n <CollectionViewSource Source=\"{Binding Source={x:Static Application.Current}, Path=CardDetails}\" x:Key=\"CardDetails\"> \n </CollectionViewSource>\n\n <c:SetIdToNameConverter x:Key=\"SetConverter\"/> \n</Window.Resources>\n</code></pre>\n\n<p>Then finally, in the ListView that was part of the initial problem, you add the converter reference:</p>\n\n<pre><code><ListView Canvas.Left=\"402\" Canvas.Top=\"480\" Height=\"78\" ItemsSource=\"{Binding}\" Name=\"lsvViewEditCardPrint\" Width=\"419\">\n <ListView.View>\n <GridView>\n <GridViewColumn DisplayMemberBinding=\"{Binding Path=IdCst, Converter={StaticResource SetConverter}}\">Set</GridViewColumn>\n // Other Columns here...\n </GridView>\n </ListView.View>\n</ListView>\n</code></pre>\n\n<p>So the great part now is that when I trigger an event that has a Card Id, all I need to do is reset set the CollectionViewSource...</p>\n\n<pre><code>DirectCast(Me.FindResource(\"CardDetails\"), CollectionViewSource).Source = taCardDetails.GetDataById(CardId)\n</code></pre>\n\n<p>...and all the binding elements of WPF do the rest!</p>\n\n<p>The nice thing about is is that I can easily create other converters, add them to various DataTemplates or columns elsewhere in the application, and once I get all of the data into the WPF app itself, the conversions can be conducted without going to the database.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/71/"
] |
I have a ListView in WPF that is databound to a basic table that I pull from the database. The code for the ListView is as follows:
```
<ListView Canvas.Left="402" Canvas.Top="480" Height="78" ItemsSource="{Binding}" Name="lsvViewEditCardPrint" Width="419">
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Path=IdCst}">Set</GridViewColumn>
<GridViewColumn DisplayMemberBinding="{Binding Path=Language}">Language</GridViewColumn>
<GridViewColumn DisplayMemberBinding="{Binding Path=Number}">Number</GridViewColumn>
<GridViewColumn DisplayMemberBinding="{Binding Path=IdArt}">Artwork</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
```
The IdCst column is a foreign key to a separate table, and I'd like to display the actual name field from that table instead of just the Id. Does anybody know how to set a databinding, or is there an event, such as OnItemDataBound, that I could intercept to modify the display?
|
This blog [post](http://almosteric.wordpress.com/2008/06/24/databinding-to-foreign-keys-in-wpf/) may help:
>
> ...I assumed the foreign key should be bound to the ‘SelectedValue’ property,
> and there is an ItemSource that I can
> bind to my fact table so the drop down
> is populated.
>
>
> At this point my dropdown worked, but
> nothing would appear in the combobox.
> I finally noticed a ‘SelectedItemPath’
> property - I assumed this would be the
> name of the field in my dropdown that
> was associated to my foreign key. Sure
> enough, that’s exactly what it is.
>
>
>
|
195,173 |
<p>When you run something similar to:</p>
<pre><code>UPDATE table SET datetime = NOW();
</code></pre>
<p>on a table with 1 000 000 000 records and the query takes 10 seconds to run, will all the rows have the exact same time (minutes and seconds) or will they have different times? In other words, will the time be when the query started or when each row is updated?</p>
<p>I'm running MySQL, but I'm thinking this applies to all dbs.</p>
|
[
{
"answer_id": 195179,
"author": "gizmo",
"author_id": 9396,
"author_profile": "https://Stackoverflow.com/users/9396",
"pm_score": 1,
"selected": false,
"text": "<p>They should have the same time, the update is supposed to be atomic, meaning that whatever how long it takes to perform, the action is supposed to occurs as if all was done at the same time.</p>\n\n<p>If you're experiencing a different behaviour, it's time to change for another DBMS.</p>\n"
},
{
"answer_id": 195181,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": 7,
"selected": true,
"text": "<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_now\" rel=\"noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_now</a></p>\n\n<blockquote>\n <p>\"NOW() returns a constant time that indicates the time at which the statement began to execute. (Within a stored routine or trigger, NOW() returns the time at which the routine or triggering statement began to execute.) This differs from the behavior for SYSDATE(), which returns the exact time at which it executes as of MySQL 5.0.13. \"</p>\n</blockquote>\n"
},
{
"answer_id": 11587803,
"author": "My Name Goes Here",
"author_id": 1541909,
"author_profile": "https://Stackoverflow.com/users/1541909",
"pm_score": 0,
"selected": false,
"text": "<p>The sqlite answer is </p>\n\n<pre><code>update TABLE set mydatetime = datetime('now');\n</code></pre>\n\n<p>in case someone else was looking for it.</p>\n"
},
{
"answer_id": 38186380,
"author": "MRRaja",
"author_id": 2357497,
"author_profile": "https://Stackoverflow.com/users/2357497",
"pm_score": 3,
"selected": false,
"text": "<p>Assign <code>NOW()</code> to a variable then update the datetime with variable:</p>\n\n<pre><code>update_date_time=now()\n</code></pre>\n\n<p>now update like this</p>\n\n<pre><code>UPDATE table SET datetime =update_date_time;\n</code></pre>\n\n<p>correct the syntax, as per your requirement </p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5441/"
] |
When you run something similar to:
```
UPDATE table SET datetime = NOW();
```
on a table with 1 000 000 000 records and the query takes 10 seconds to run, will all the rows have the exact same time (minutes and seconds) or will they have different times? In other words, will the time be when the query started or when each row is updated?
I'm running MySQL, but I'm thinking this applies to all dbs.
|
<http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_now>
>
> "NOW() returns a constant time that indicates the time at which the statement began to execute. (Within a stored routine or trigger, NOW() returns the time at which the routine or triggering statement began to execute.) This differs from the behavior for SYSDATE(), which returns the exact time at which it executes as of MySQL 5.0.13. "
>
>
>
|
195,177 |
<p>I have a Zimbra installation and I need to programmaticaly update contacts in it. It seems that its REST interface is only working to add new contacts, but I need to update existing ones. Is there a way, tool or something, open-source, to do that ?</p>
|
[
{
"answer_id": 195708,
"author": "edomaur",
"author_id": 14262,
"author_profile": "https://Stackoverflow.com/users/14262",
"pm_score": 3,
"selected": true,
"text": "<p>Well, I have an answer to my question : you may use the \"zmmailbox\" command. Under the Zimbra system user, it is possible to modify content in a mailbox. Since quite everything is stored in the Zimbra mailbox, contacts can be edited. I need now to find a way to use this :</p>\n\n<pre><code>box$ zmmailbox help contact\n\n autoComplete(ac) [opts] {query}\n -v/--verbose verbose output\n\n autoCompleteGal(acg) [opts] {query}\n -v/--verbose verbose output\n\n createContact(cct) [opts] [attr1 value1 [attr2 value2...]]\n -i/--ignore ignore unknown contact attrs\n -f/--folder <arg> folder-path-or-id\n -T/--tags <arg> list of tag ids/names\n\n deleteContact(dct) {contact-ids}\n\n flagContact(fct) {contact-ids} [0|1*]\n\n getAllContacts(gact) [opts] [attr1 [attr2...]]\n -f/--folder <arg> folder-path-or-id\n -v/--verbose verbose output\n\n getContacts(gct) [opts] {contact-ids} [attr1 [attr2...]]\n -v/--verbose verbose output\n\n modifyContactAttrs(mcta) [opts] {contact-id} [attr1 value1 [attr2 value2...]]\n -i/--ignore ignore unknown contact attrs\n -r/--replace replace contact (default is to merge)\n\n moveContact(mct) {contact-ids} {dest-folder-path}\n\n tagContact(tct) {contact-ids} {tag-name} [0|1*]\n</code></pre>\n"
},
{
"answer_id": 204671,
"author": "conny",
"author_id": 23023,
"author_profile": "https://Stackoverflow.com/users/23023",
"pm_score": 0,
"selected": false,
"text": "<p>There's actually also a SOAP interface in Zimbra but from what I've been able to tell by reading the forums at <a href=\"http://www.zimbra.com/forums/\" rel=\"nofollow noreferrer\">zimbra.com/forums</a>, for some reason they \"could not\" (?!) document it properly, nor generate any WSDL file; thus I've never used it. </p>\n\n<p>Apparently one would have to study the Java source code of Zimbra to see what's available.</p>\n"
},
{
"answer_id": 758760,
"author": "Matt Mencel",
"author_id": 46698,
"author_profile": "https://Stackoverflow.com/users/46698",
"pm_score": 0,
"selected": false,
"text": "<p>If you have a recent install of Zimbra, you should be able to find the SOAP docs in /opt/zimbra/docs. I've not tried to use it yet myself....it's still Greek to me.</p>\n\n<p>Matt</p>\n"
},
{
"answer_id": 1937871,
"author": "skhavari",
"author_id": 235725,
"author_profile": "https://Stackoverflow.com/users/235725",
"pm_score": 2,
"selected": false,
"text": "<p>You can send SOAP to ZCS, the details are in soap.txt (located under /opt/zimbra/docs). To modify a contact see ModifyContactRequest. You'll need to authenticate first using AuthRequest. Tons of good Zimbra developer information is here: <a href=\"http://www.zimbra.com/forums/developers/\" rel=\"nofollow noreferrer\">http://www.zimbra.com/forums/developers/</a></p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14262/"
] |
I have a Zimbra installation and I need to programmaticaly update contacts in it. It seems that its REST interface is only working to add new contacts, but I need to update existing ones. Is there a way, tool or something, open-source, to do that ?
|
Well, I have an answer to my question : you may use the "zmmailbox" command. Under the Zimbra system user, it is possible to modify content in a mailbox. Since quite everything is stored in the Zimbra mailbox, contacts can be edited. I need now to find a way to use this :
```
box$ zmmailbox help contact
autoComplete(ac) [opts] {query}
-v/--verbose verbose output
autoCompleteGal(acg) [opts] {query}
-v/--verbose verbose output
createContact(cct) [opts] [attr1 value1 [attr2 value2...]]
-i/--ignore ignore unknown contact attrs
-f/--folder <arg> folder-path-or-id
-T/--tags <arg> list of tag ids/names
deleteContact(dct) {contact-ids}
flagContact(fct) {contact-ids} [0|1*]
getAllContacts(gact) [opts] [attr1 [attr2...]]
-f/--folder <arg> folder-path-or-id
-v/--verbose verbose output
getContacts(gct) [opts] {contact-ids} [attr1 [attr2...]]
-v/--verbose verbose output
modifyContactAttrs(mcta) [opts] {contact-id} [attr1 value1 [attr2 value2...]]
-i/--ignore ignore unknown contact attrs
-r/--replace replace contact (default is to merge)
moveContact(mct) {contact-ids} {dest-folder-path}
tagContact(tct) {contact-ids} {tag-name} [0|1*]
```
|
195,207 |
<p>Very simply put:</p>
<p>I have a class that consists mostly of static public members, so I can group similar functions together that still have to be called from other classes/functions.</p>
<p>Anyway, I have defined two static unsigned char variables in my class public scope, when I try to modify these values in the same class' constructor, I am getting an "unresolved external symbol" error at compilation.</p>
<pre><code>class test
{
public:
static unsigned char X;
static unsigned char Y;
...
test();
};
test::test()
{
X = 1;
Y = 2;
}
</code></pre>
<p>I'm new to C++ so go easy on me. Why can't I do this?</p>
|
[
{
"answer_id": 195209,
"author": "Colin Jensen",
"author_id": 9884,
"author_profile": "https://Stackoverflow.com/users/9884",
"pm_score": 8,
"selected": true,
"text": "<p>If you are using <strong>C++ 17</strong> you can just use the <code>inline</code> specifier (see <a href=\"https://stackoverflow.com/a/11711082/55721\">https://stackoverflow.com/a/11711082/55721</a>)</p>\n<hr />\n<p>If using older versions of the C++ standard, you must add the definitions to match your declarations of X and Y</p>\n<pre><code>unsigned char test::X;\nunsigned char test::Y;\n</code></pre>\n<p>somewhere. You might want to also initialize a static member</p>\n<pre><code>unsigned char test::X = 4;\n</code></pre>\n<p>and again, you do that in the definition (usually in a CXX file) not in the declaration (which is often in a .H file)</p>\n"
},
{
"answer_id": 195233,
"author": "sergtk",
"author_id": 13441,
"author_profile": "https://Stackoverflow.com/users/13441",
"pm_score": 6,
"selected": false,
"text": "<p>Static data members declarations in the class declaration are not definition of them.\nTo define them you should do this in the <code>.CPP</code> file to avoid duplicated symbols.</p>\n\n<p>The only data you can declare and define is integral static constants.\n(Values of <code>enums</code> can be used as constant values as well)</p>\n\n<p>You might want to rewrite your code as:</p>\n\n<pre><code>class test {\npublic:\n const static unsigned char X = 1;\n const static unsigned char Y = 2;\n ...\n test();\n};\n\ntest::test() {\n}\n</code></pre>\n\n<p>If you want to have ability to modify you static variables (in other words when it is inappropriate to declare them as const), you can separate you code between <code>.H</code> and <code>.CPP</code> in the following way:</p>\n\n<p>.H :</p>\n\n<pre><code>class test {\npublic:\n\n static unsigned char X;\n static unsigned char Y;\n\n ...\n\n test();\n};\n</code></pre>\n\n<p>.CPP :</p>\n\n<pre><code>unsigned char test::X = 1;\nunsigned char test::Y = 2;\n\ntest::test()\n{\n // constructor is empty.\n // We don't initialize static data member here, \n // because static data initialization will happen on every constructor call.\n}\n</code></pre>\n"
},
{
"answer_id": 50169640,
"author": "Johann Studanski",
"author_id": 6155053,
"author_profile": "https://Stackoverflow.com/users/6155053",
"pm_score": 3,
"selected": false,
"text": "<p>Since this is the first SO thread that seemed to come up for me when searching for \"unresolved externals with static const members\" in general, I'll leave another hint to solve one problem with unresolved externals here:</p>\n\n<p>For me, the thing that I forgot was to mark my class definition <code>__declspec(dllexport)</code>, and when called from another class (outside that class's dll's boundaries), I of course got the my unresolved external error.<br>\nStill, easy to forget when you're changing an internal helper class to a one accessible from elsewhere, so if you're working in a dynamically linked project, you might as well check that, too.</p>\n"
},
{
"answer_id": 52395927,
"author": "Penny",
"author_id": 6824513,
"author_profile": "https://Stackoverflow.com/users/6824513",
"pm_score": 3,
"selected": false,
"text": "<p>in my case, I declared one static variable in .h file, like</p>\n\n<pre><code>//myClass.h\nclass myClass\n{\nstatic int m_nMyVar;\nstatic void myFunc();\n}\n</code></pre>\n\n<p>and in myClass.cpp, I tried to use this m_nMyVar. It got LINK error like:</p>\n\n<p>error LNK2001: unresolved external symbol \"public: static class...\nThe link error related cpp file looks like:</p>\n\n<pre><code>//myClass.cpp\nvoid myClass::myFunc()\n{\nmyClass::m_nMyVar = 123; //I tried to use this m_nMyVar here and got link error\n}\n</code></pre>\n\n<p>So I add below code on the top of myClass.cpp</p>\n\n<pre><code>//myClass.cpp\nint myClass::m_nMyVar; //it seems redefine m_nMyVar, but it works well\nvoid myClass::myFunc()\n{\nmyClass::m_nMyVar = 123; //I tried to use this m_nMyVar here and got link error\n}\n</code></pre>\n\n<p>then LNK2001 is gone. </p>\n"
},
{
"answer_id": 60151378,
"author": "whats_wrong_here",
"author_id": 5403966,
"author_profile": "https://Stackoverflow.com/users/5403966",
"pm_score": 0,
"selected": false,
"text": "<p>In my case, I was using wrong linking. <br/>\nIt was managed c++ (cli) but with native exporting. I have added to linker -> input -> assembly link resource the dll of the library from which the function is exported. But native c++ linking requires .lib file to \"see\" implementations in cpp correctly, so for me helped to add the .lib file to linker -> input -> additional dependencies. <br/>\n[Usually managed code does not use dll export and import, it uses references, but that was unique situation.]</p>\n"
},
{
"answer_id": 67138464,
"author": "Sanya Tayal",
"author_id": 9079222,
"author_profile": "https://Stackoverflow.com/users/9079222",
"pm_score": 3,
"selected": false,
"text": "<p>When we declare a static variable in a class, it is shared by all the objects of that class. As static variables are initialized only once they are never initialized by a constructor. Instead, the static variable should be explicitly initialized outside the class only once using the scope resolution operator (::).</p>\n<p>In the below example, static variable counter is a member of the class Demo. Note how it is initialized explicitly outside the class with the initial value = 0.</p>\n<pre><code>#include <iostream>\n#include <string>\nusing namespace std;\nclass Demo{\n int var;\n static int counter;\n\n public:\n Demo(int var):var(var){\n cout<<"Counter = "<<counter<<endl;\n counter++;\n }\n};\nint Demo::counter = 0; //static variable initialisation\nint main()\n{\n Demo d(2), d1(10),d3(1);\n}\n\nOutput:\nCount = 0\nCount = 1\nCount = 2\n</code></pre>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Very simply put:
I have a class that consists mostly of static public members, so I can group similar functions together that still have to be called from other classes/functions.
Anyway, I have defined two static unsigned char variables in my class public scope, when I try to modify these values in the same class' constructor, I am getting an "unresolved external symbol" error at compilation.
```
class test
{
public:
static unsigned char X;
static unsigned char Y;
...
test();
};
test::test()
{
X = 1;
Y = 2;
}
```
I'm new to C++ so go easy on me. Why can't I do this?
|
If you are using **C++ 17** you can just use the `inline` specifier (see <https://stackoverflow.com/a/11711082/55721>)
---
If using older versions of the C++ standard, you must add the definitions to match your declarations of X and Y
```
unsigned char test::X;
unsigned char test::Y;
```
somewhere. You might want to also initialize a static member
```
unsigned char test::X = 4;
```
and again, you do that in the definition (usually in a CXX file) not in the declaration (which is often in a .H file)
|
195,240 |
<p>I have the following template</p>
<pre><code><h2>one</h2>
<xsl:apply-templates select="one"/>
<h2>two</h2>
<xsl:apply-templates select="two"/>
<h2>three</h2>
<xsl:apply-templates select="three"/>
</code></pre>
<p>I would like to only display the headers (one,two,three) if there is at least one member of the corresponding template. How do I check for this?</p>
|
[
{
"answer_id": 195248,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": true,
"text": "<pre><code><xsl:if test=\"one\">\n <h2>one</h2>\n <xsl:apply-templates select=\"one\"/>\n</xsl:if>\n<!-- etc -->\n</code></pre>\n\n<p>Alternatively, you could create a named template,</p>\n\n<pre><code><xsl:template name=\"WriteWithHeader\">\n <xsl:param name=\"header\"/>\n <xsl:param name=\"data\"/>\n <xsl:if test=\"$data\">\n <h2><xsl:value-of select=\"$header\"/></h2>\n <xsl:apply-templates select=\"$data\"/>\n </xsl:if>\n</xsl:template>\n</code></pre>\n\n<p>and then call as:</p>\n\n<pre><code> <xsl:call-template name=\"WriteWithHeader\">\n <xsl:with-param name=\"header\" select=\"'one'\"/>\n <xsl:with-param name=\"data\" select=\"one\"/>\n </xsl:call-template>\n</code></pre>\n\n<p>But to be honest, that looks like more work to me... only useful if drawing a header is complex... for a simple <code><h2>...</h2></code> I'd be tempted to leave it inline.</p>\n\n<p>If the header title is always the node name, you could simplifiy the template by removing the \"$header\" arg, and use instead:</p>\n\n<pre><code><xsl:value-of select=\"name($header[1])\"/>\n</code></pre>\n"
},
{
"answer_id": 212328,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I like to exercise the <em>functional</em> aspects of XSL which lead me to the following implementation:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"UTF-8\"?>\n</code></pre>\n\n<p>\n </p>\n\n<pre><code><!-- test data inlined -->\n<test>\n <one>Content 1</one>\n <two>Content 2</two>\n <three>Content 3</three>\n <four/>\n <special>I'm special!</special>\n</test>\n\n<!-- any root since take test content from stylesheet -->\n<xsl:template match=\"/\">\n <html>\n <head>\n <title>Header/Content Widget</title>\n </head>\n <body>\n <xsl:apply-templates select=\"document('')//test/*\" mode=\"header-content-widget\"/>\n </body>\n </html>\n</xsl:template>\n\n<!-- default action for header-content -widget is apply header then content views -->\n<xsl:template match=\"*\" mode=\"header-content-widget\">\n <xsl:apply-templates select=\".\" mode=\"header-view\"/>\n <xsl:apply-templates select=\".\" mode=\"content-view\"/>\n</xsl:template>\n\n<!-- default header-view places element name in <h2> tag -->\n<xsl:template match=\"*\" mode=\"header-view\">\n <h2><xsl:value-of select=\"name()\"/></h2>\n</xsl:template>\n\n<!-- default header-view when no text content is no-op -->\n<xsl:template match=\"*[not(text())]\" mode=\"header-view\"/>\n\n<!-- default content-view is to apply-templates -->\n<xsl:template match=\"*\" mode=\"content-view\">\n <xsl:apply-templates/>\n</xsl:template>\n\n<!-- special content handling -->\n<xsl:template match=\"special\" mode=\"content-view\">\n <strong><xsl:apply-templates/></strong>\n</xsl:template>\n</code></pre>\n\n<p></p>\n\n<p>Once in the <em>body</em> all elements contained in the <em>test</em> element have <em>header-content-widget</em> applied (in document order).</p>\n\n<p>The default <em>header-content-widget</em> template (matching \"*\") first applies a <em>header-view</em> then applies a <em>content-view</em> to the current element.</p>\n\n<p>The default <em>header-view</em> template places the current element's <em>name</em> in the h2 tag. The default <em>content-view</em> applies generic processing rules.</p>\n\n<p>When there is no content as judged by the <em>[not(text())]</em> predicate no output for the element occurs.</p>\n\n<p>One off <em>special</em> cases are easily handled.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2133/"
] |
I have the following template
```
<h2>one</h2>
<xsl:apply-templates select="one"/>
<h2>two</h2>
<xsl:apply-templates select="two"/>
<h2>three</h2>
<xsl:apply-templates select="three"/>
```
I would like to only display the headers (one,two,three) if there is at least one member of the corresponding template. How do I check for this?
|
```
<xsl:if test="one">
<h2>one</h2>
<xsl:apply-templates select="one"/>
</xsl:if>
<!-- etc -->
```
Alternatively, you could create a named template,
```
<xsl:template name="WriteWithHeader">
<xsl:param name="header"/>
<xsl:param name="data"/>
<xsl:if test="$data">
<h2><xsl:value-of select="$header"/></h2>
<xsl:apply-templates select="$data"/>
</xsl:if>
</xsl:template>
```
and then call as:
```
<xsl:call-template name="WriteWithHeader">
<xsl:with-param name="header" select="'one'"/>
<xsl:with-param name="data" select="one"/>
</xsl:call-template>
```
But to be honest, that looks like more work to me... only useful if drawing a header is complex... for a simple `<h2>...</h2>` I'd be tempted to leave it inline.
If the header title is always the node name, you could simplifiy the template by removing the "$header" arg, and use instead:
```
<xsl:value-of select="name($header[1])"/>
```
|
195,267 |
<p>I'm trying to use the Windows API to set the primary monitor. It doesn't seem to work - my screen just flicks and nothing happens.</p>
<pre><code> public const int DM_ORIENTATION = 0x00000001;
public const int DM_PAPERSIZE = 0x00000002;
public const int DM_PAPERLENGTH = 0x00000004;
public const int DM_PAPERWIDTH = 0x00000008;
public const int DM_SCALE = 0x00000010;
public const int DM_POSITION = 0x00000020;
public const int DM_NUP = 0x00000040;
public const int DM_DISPLAYORIENTATION = 0x00000080;
public const int DM_COPIES = 0x00000100;
public const int DM_DEFAULTSOURCE = 0x00000200;
public const int DM_PRINTQUALITY = 0x00000400;
public const int DM_COLOR = 0x00000800;
public const int DM_DUPLEX = 0x00001000;
public const int DM_YRESOLUTION = 0x00002000;
public const int DM_TTOPTION = 0x00004000;
public const int DM_COLLATE = 0x00008000;
public const int DM_FORMNAME = 0x00010000;
public const int DM_LOGPIXELS = 0x00020000;
public const int DM_BITSPERPEL = 0x00040000;
public const int DM_PELSWIDTH = 0x00080000;
public const int DM_PELSHEIGHT = 0x00100000;
public const int DM_DISPLAYFLAGS = 0x00200000;
public const int DM_DISPLAYFREQUENCY = 0x00400000;
public const int DM_ICMMETHOD = 0x00800000;
public const int DM_ICMINTENT = 0x01000000;
public const int DM_MEDIATYPE = 0x02000000;
public const int DM_DITHERTYPE = 0x04000000;
public const int DM_PANNINGWIDTH = 0x08000000;
public const int DM_PANNINGHEIGHT = 0x10000000;
public const int DM_DISPLAYFIXEDOUTPUT = 0x20000000;
public const int ENUM_CURRENT_SETTINGS = -1;
public const int CDS_UPDATEREGISTRY = 0x01;
public const int CDS_TEST = 0x02;
public const int CDS_SET_PRIMARY = 0x00000010;
public const long DISP_CHANGE_SUCCESSFUL = 0;
public const long DISP_CHANGE_RESTART = 1;
public const long DISP_CHANGE_FAILED = -1;
public const long DISP_CHANGE_BADMODE = -2;
public const long DISP_CHANGE_NOTUPDATED = -3;
public const long DISP_CHANGE_BADFLAGS = -4;
public const long DISP_CHANGE_BADPARAM = -5;
public const long DISP_CHANGE_BADDUALVIEW = -6;
public static void SetPrimary(Screen screen)
{
DISPLAY_DEVICE d = new DISPLAY_DEVICE();
DEVMODE dm = new DEVMODE();
d.cb = Marshal.SizeOf(d);
uint deviceID = 1;
User_32.EnumDisplayDevices(null, deviceID, ref d, 0); //
User_32.EnumDisplaySettings(d.DeviceName, 0, ref dm);
dm.dmPelsWidth = 2560;
dm.dmPelsHeight = 1600;
dm.dmPositionX = screen.Bounds.Right;
dm.dmFields = DM_POSITION | DM_PELSWIDTH | DM_PELSHEIGHT;
User_32.ChangeDisplaySettingsEx(d.DeviceName, ref dm, IntPtr.Zero, CDS_SET_PRIMARY, IntPtr.Zero);
}
</code></pre>
<p>I call the method like this:</p>
<pre><code>SetPrimary(Screen.AllScreens[1])
</code></pre>
<p>Any ideas?</p>
|
[
{
"answer_id": 195319,
"author": "tobsen",
"author_id": 27083,
"author_profile": "https://Stackoverflow.com/users/27083",
"pm_score": 2,
"selected": false,
"text": "<p>I can't really help you with the winapi-stuff but if you are using a Nvidia card you may have a look at the <a href=\"http://developer.download.nvidia.com/SDK/9.5/Samples/DEMOS/common/src/NvCpl/docs/NVControlPanel_API.pdf\" rel=\"nofollow noreferrer\">NVcontrolPanel Api Documentation</a>\nThen you could make the secondary output your primary using <code>rundll32.exe NvCpl.dll,dtcfg primary 2</code>\nHope that will help you.</p>\n"
},
{
"answer_id": 195560,
"author": "Bradley Grainger",
"author_id": 23633,
"author_profile": "https://Stackoverflow.com/users/23633",
"pm_score": 2,
"selected": false,
"text": "<p>According to the <a href=\"http://msdn.microsoft.com/en-us/library/ms533235(VS.85).aspx\" rel=\"nofollow noreferrer\">documentation for ChangeDisplaySettingsEx</a>, \"the dmSize member must be initialized to the size, in bytes, of the DEVMODE structure.\" Furthermore, <a href=\"http://msdn.microsoft.com/en-us/library/ms533265(VS.85).aspx\" rel=\"nofollow noreferrer\">the EnumDisplaySettings documentation</a> states, \"Before calling EnumDisplaySettings, set the dmSize member to sizeof(DEVMODE), and set the dmDriverExtra member to indicate the size, in bytes, of the additional space available to receive private driver data\". I don't see this happening in the code sample given in the question; that's one reason why it may be failing.</p>\n\n<p>Additionally, you might have errors in the definitions of the DEVMODE and DISPLAY_DEVICE structs, which were not included in the question. <a href=\"https://stackoverflow.com/questions/195267/use-windows-api-from-c-to-set-primary-monitor#195272\">Roger Lipscombe's suggestion</a> to get it working from C/C++ first is an excellent way to rule out this type of problem.</p>\n\n<p>Finally, check the return value from ChangeDisplaySettingsEx and see if that gives a clue as to why it might be failing.</p>\n"
},
{
"answer_id": 23044185,
"author": "ADBailey",
"author_id": 3410046,
"author_profile": "https://Stackoverflow.com/users/3410046",
"pm_score": 3,
"selected": false,
"text": "<p>I ran into exactly the same problem, both from C# and after following the advice here to try it in C++. I eventually discovered that the thing the Microsoft documentation doesn't make clear is that the request to set the primary monitor will be ignored (but with the operation reported as successful!) unless you also set the position of the monitor to (0, 0) on the DEVMODE struct. Of course, this means that you also need to shift the positions of your other monitors so that they stay in the same place relative to the new primary monitor. Per the documentation (<a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/dd183413%28v=vs.85%29.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/windows/desktop/dd183413%28v=vs.85%29.aspx</a>), call ChangeDisplaySettingsEx for each monitor with the CDS_NORESET flag and then make a final call with everything null.</p>\n\n<p>The following code worked for me:</p>\n\n<pre><code> public static void SetAsPrimaryMonitor(uint id)\n {\n var device = new DISPLAY_DEVICE();\n var deviceMode = new DEVMODE();\n device.cb = Marshal.SizeOf(device);\n\n NativeMethods.EnumDisplayDevices(null, id, ref device, 0);\n NativeMethods.EnumDisplaySettings(device.DeviceName, -1, ref deviceMode);\n var offsetx = deviceMode.dmPosition.x;\n var offsety = deviceMode.dmPosition.y;\n deviceMode.dmPosition.x = 0;\n deviceMode.dmPosition.y = 0;\n\n NativeMethods.ChangeDisplaySettingsEx(\n device.DeviceName, \n ref deviceMode, \n (IntPtr)null, \n (ChangeDisplaySettingsFlags.CDS_SET_PRIMARY | ChangeDisplaySettingsFlags.CDS_UPDATEREGISTRY | ChangeDisplaySettingsFlags.CDS_NORESET), \n IntPtr.Zero);\n\n device = new DISPLAY_DEVICE();\n device.cb = Marshal.SizeOf(device);\n\n // Update remaining devices\n for (uint otherid = 0; NativeMethods.EnumDisplayDevices(null, otherid, ref device, 0); otherid++)\n {\n if (device.StateFlags.HasFlag(DisplayDeviceStateFlags.AttachedToDesktop) && otherid != id)\n {\n device.cb = Marshal.SizeOf(device);\n var otherDeviceMode = new DEVMODE();\n\n NativeMethods.EnumDisplaySettings(device.DeviceName, -1, ref otherDeviceMode);\n\n otherDeviceMode.dmPosition.x -= offsetx;\n otherDeviceMode.dmPosition.y -= offsety;\n\n NativeMethods.ChangeDisplaySettingsEx(\n device.DeviceName,\n ref otherDeviceMode,\n (IntPtr)null,\n (ChangeDisplaySettingsFlags.CDS_UPDATEREGISTRY | ChangeDisplaySettingsFlags.CDS_NORESET),\n IntPtr.Zero);\n\n }\n\n device.cb = Marshal.SizeOf(device);\n }\n\n // Apply settings\n NativeMethods.ChangeDisplaySettingsEx(null, IntPtr.Zero, (IntPtr)null, ChangeDisplaySettingsFlags.CDS_NONE, (IntPtr)null);\n }\n</code></pre>\n\n<p>Note that a signature for ChangeDisplaySettingsEx with a DEVMODE struct as the second parameter obviously won't allow you to pass in IntPtr.Zero. Create yourself two different signatures for the same extern call, i.e.</p>\n\n<pre><code> [DllImport(\"user32.dll\")]\n public static extern DISP_CHANGE ChangeDisplaySettingsEx(string lpszDeviceName, ref DEVMODE lpDevMode, IntPtr hwnd, ChangeDisplaySettingsFlags dwflags, IntPtr lParam);\n\n [DllImport(\"user32.dll\")]\n public static extern DISP_CHANGE ChangeDisplaySettingsEx(string lpszDeviceName, IntPtr lpDevMode, IntPtr hwnd, ChangeDisplaySettingsFlags dwflags, IntPtr lParam);\n</code></pre>\n"
},
{
"answer_id": 36968861,
"author": "Vladimir",
"author_id": 1266849,
"author_profile": "https://Stackoverflow.com/users/1266849",
"pm_score": 3,
"selected": false,
"text": "<p>Here is the full code based on ADBailey's solution:</p>\n\n<pre><code>public class MonitorChanger\n{\n public static void SetAsPrimaryMonitor(uint id)\n {\n var device = new DISPLAY_DEVICE();\n var deviceMode = new DEVMODE();\n device.cb = Marshal.SizeOf(device);\n\n NativeMethods.EnumDisplayDevices(null, id, ref device, 0);\n NativeMethods.EnumDisplaySettings(device.DeviceName, -1, ref deviceMode);\n var offsetx = deviceMode.dmPosition.x;\n var offsety = deviceMode.dmPosition.y;\n deviceMode.dmPosition.x = 0;\n deviceMode.dmPosition.y = 0;\n\n NativeMethods.ChangeDisplaySettingsEx(\n device.DeviceName,\n ref deviceMode,\n (IntPtr)null,\n (ChangeDisplaySettingsFlags.CDS_SET_PRIMARY | ChangeDisplaySettingsFlags.CDS_UPDATEREGISTRY | ChangeDisplaySettingsFlags.CDS_NORESET),\n IntPtr.Zero);\n\n device = new DISPLAY_DEVICE();\n device.cb = Marshal.SizeOf(device);\n\n // Update remaining devices\n for (uint otherid = 0; NativeMethods.EnumDisplayDevices(null, otherid, ref device, 0); otherid++)\n {\n if (device.StateFlags.HasFlag(DisplayDeviceStateFlags.AttachedToDesktop) && otherid != id)\n {\n device.cb = Marshal.SizeOf(device);\n var otherDeviceMode = new DEVMODE();\n\n NativeMethods.EnumDisplaySettings(device.DeviceName, -1, ref otherDeviceMode);\n\n otherDeviceMode.dmPosition.x -= offsetx;\n otherDeviceMode.dmPosition.y -= offsety;\n\n NativeMethods.ChangeDisplaySettingsEx(\n device.DeviceName,\n ref otherDeviceMode,\n (IntPtr)null,\n (ChangeDisplaySettingsFlags.CDS_UPDATEREGISTRY | ChangeDisplaySettingsFlags.CDS_NORESET),\n IntPtr.Zero);\n\n }\n\n device.cb = Marshal.SizeOf(device);\n }\n\n // Apply settings\n NativeMethods.ChangeDisplaySettingsEx(null, IntPtr.Zero, (IntPtr)null, ChangeDisplaySettingsFlags.CDS_NONE, (IntPtr)null);\n }\n}\n\n[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi)]\npublic struct DEVMODE\n{\n public const int CCHDEVICENAME = 32;\n public const int CCHFORMNAME = 32;\n\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCHDEVICENAME)]\n [System.Runtime.InteropServices.FieldOffset(0)]\n public string dmDeviceName;\n [System.Runtime.InteropServices.FieldOffset(32)]\n public Int16 dmSpecVersion;\n [System.Runtime.InteropServices.FieldOffset(34)]\n public Int16 dmDriverVersion;\n [System.Runtime.InteropServices.FieldOffset(36)]\n public Int16 dmSize;\n [System.Runtime.InteropServices.FieldOffset(38)]\n public Int16 dmDriverExtra;\n [System.Runtime.InteropServices.FieldOffset(40)]\n public UInt32 dmFields;\n\n [System.Runtime.InteropServices.FieldOffset(44)]\n Int16 dmOrientation;\n [System.Runtime.InteropServices.FieldOffset(46)]\n Int16 dmPaperSize;\n [System.Runtime.InteropServices.FieldOffset(48)]\n Int16 dmPaperLength;\n [System.Runtime.InteropServices.FieldOffset(50)]\n Int16 dmPaperWidth;\n [System.Runtime.InteropServices.FieldOffset(52)]\n Int16 dmScale;\n [System.Runtime.InteropServices.FieldOffset(54)]\n Int16 dmCopies;\n [System.Runtime.InteropServices.FieldOffset(56)]\n Int16 dmDefaultSource;\n [System.Runtime.InteropServices.FieldOffset(58)]\n Int16 dmPrintQuality;\n\n [System.Runtime.InteropServices.FieldOffset(44)]\n public POINTL dmPosition;\n [System.Runtime.InteropServices.FieldOffset(52)]\n public Int32 dmDisplayOrientation;\n [System.Runtime.InteropServices.FieldOffset(56)]\n public Int32 dmDisplayFixedOutput;\n\n [System.Runtime.InteropServices.FieldOffset(60)]\n public short dmColor; // See note below!\n [System.Runtime.InteropServices.FieldOffset(62)]\n public short dmDuplex; // See note below!\n [System.Runtime.InteropServices.FieldOffset(64)]\n public short dmYResolution;\n [System.Runtime.InteropServices.FieldOffset(66)]\n public short dmTTOption;\n [System.Runtime.InteropServices.FieldOffset(68)]\n public short dmCollate; // See note below!\n [System.Runtime.InteropServices.FieldOffset(72)]\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCHFORMNAME)]\n public string dmFormName;\n [System.Runtime.InteropServices.FieldOffset(102)]\n public Int16 dmLogPixels;\n [System.Runtime.InteropServices.FieldOffset(104)]\n public Int32 dmBitsPerPel;\n [System.Runtime.InteropServices.FieldOffset(108)]\n public Int32 dmPelsWidth;\n [System.Runtime.InteropServices.FieldOffset(112)]\n public Int32 dmPelsHeight;\n [System.Runtime.InteropServices.FieldOffset(116)]\n public Int32 dmDisplayFlags;\n [System.Runtime.InteropServices.FieldOffset(116)]\n public Int32 dmNup;\n [System.Runtime.InteropServices.FieldOffset(120)]\n public Int32 dmDisplayFrequency;\n}\n\npublic enum DISP_CHANGE : int\n{\n Successful = 0,\n Restart = 1,\n Failed = -1,\n BadMode = -2,\n NotUpdated = -3,\n BadFlags = -4,\n BadParam = -5,\n BadDualView = -6\n}\n\n[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]\npublic struct DISPLAY_DEVICE\n{\n [MarshalAs(UnmanagedType.U4)]\n public int cb;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]\n public string DeviceName;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]\n public string DeviceString;\n [MarshalAs(UnmanagedType.U4)]\n public DisplayDeviceStateFlags StateFlags;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]\n public string DeviceID;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]\n public string DeviceKey;\n}\n\n[Flags()]\npublic enum DisplayDeviceStateFlags : int\n{\n /// <summary>The device is part of the desktop.</summary>\n AttachedToDesktop = 0x1,\n MultiDriver = 0x2,\n /// <summary>The device is part of the desktop.</summary>\n PrimaryDevice = 0x4,\n /// <summary>Represents a pseudo device used to mirror application drawing for remoting or other purposes.</summary>\n MirroringDriver = 0x8,\n /// <summary>The device is VGA compatible.</summary>\n VGACompatible = 0x10,\n /// <summary>The device is removable; it cannot be the primary display.</summary>\n Removable = 0x20,\n /// <summary>The device has more display modes than its output devices support.</summary>\n ModesPruned = 0x8000000,\n Remote = 0x4000000,\n Disconnect = 0x2000000,\n}\n\n[Flags()]\npublic enum ChangeDisplaySettingsFlags : uint\n{\n CDS_NONE = 0,\n CDS_UPDATEREGISTRY = 0x00000001,\n CDS_TEST = 0x00000002,\n CDS_FULLSCREEN = 0x00000004,\n CDS_GLOBAL = 0x00000008,\n CDS_SET_PRIMARY = 0x00000010,\n CDS_VIDEOPARAMETERS = 0x00000020,\n CDS_ENABLE_UNSAFE_MODES = 0x00000100,\n CDS_DISABLE_UNSAFE_MODES = 0x00000200,\n CDS_RESET = 0x40000000,\n CDS_RESET_EX = 0x20000000,\n CDS_NORESET = 0x10000000\n}\n\npublic class NativeMethods\n{\n [DllImport(\"user32.dll\")]\n public static extern DISP_CHANGE ChangeDisplaySettingsEx(string lpszDeviceName, ref DEVMODE lpDevMode, IntPtr hwnd, ChangeDisplaySettingsFlags dwflags, IntPtr lParam);\n\n [DllImport(\"user32.dll\")]\n // A signature for ChangeDisplaySettingsEx with a DEVMODE struct as the second parameter won't allow you to pass in IntPtr.Zero, so create an overload\n public static extern DISP_CHANGE ChangeDisplaySettingsEx(string lpszDeviceName, IntPtr lpDevMode, IntPtr hwnd, ChangeDisplaySettingsFlags dwflags, IntPtr lParam);\n\n [DllImport(\"user32.dll\")]\n public static extern bool EnumDisplayDevices(string lpDevice, uint iDevNum, ref DISPLAY_DEVICE lpDisplayDevice, uint dwFlags);\n\n [DllImport(\"user32.dll\")]\n public static extern bool EnumDisplaySettings(string deviceName, int modeNum, ref DEVMODE devMode);\n}\n\n[StructLayout(LayoutKind.Sequential)]\npublic struct POINTL\n{\n public int x;\n public int y;\n}\n</code></pre>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2972/"
] |
I'm trying to use the Windows API to set the primary monitor. It doesn't seem to work - my screen just flicks and nothing happens.
```
public const int DM_ORIENTATION = 0x00000001;
public const int DM_PAPERSIZE = 0x00000002;
public const int DM_PAPERLENGTH = 0x00000004;
public const int DM_PAPERWIDTH = 0x00000008;
public const int DM_SCALE = 0x00000010;
public const int DM_POSITION = 0x00000020;
public const int DM_NUP = 0x00000040;
public const int DM_DISPLAYORIENTATION = 0x00000080;
public const int DM_COPIES = 0x00000100;
public const int DM_DEFAULTSOURCE = 0x00000200;
public const int DM_PRINTQUALITY = 0x00000400;
public const int DM_COLOR = 0x00000800;
public const int DM_DUPLEX = 0x00001000;
public const int DM_YRESOLUTION = 0x00002000;
public const int DM_TTOPTION = 0x00004000;
public const int DM_COLLATE = 0x00008000;
public const int DM_FORMNAME = 0x00010000;
public const int DM_LOGPIXELS = 0x00020000;
public const int DM_BITSPERPEL = 0x00040000;
public const int DM_PELSWIDTH = 0x00080000;
public const int DM_PELSHEIGHT = 0x00100000;
public const int DM_DISPLAYFLAGS = 0x00200000;
public const int DM_DISPLAYFREQUENCY = 0x00400000;
public const int DM_ICMMETHOD = 0x00800000;
public const int DM_ICMINTENT = 0x01000000;
public const int DM_MEDIATYPE = 0x02000000;
public const int DM_DITHERTYPE = 0x04000000;
public const int DM_PANNINGWIDTH = 0x08000000;
public const int DM_PANNINGHEIGHT = 0x10000000;
public const int DM_DISPLAYFIXEDOUTPUT = 0x20000000;
public const int ENUM_CURRENT_SETTINGS = -1;
public const int CDS_UPDATEREGISTRY = 0x01;
public const int CDS_TEST = 0x02;
public const int CDS_SET_PRIMARY = 0x00000010;
public const long DISP_CHANGE_SUCCESSFUL = 0;
public const long DISP_CHANGE_RESTART = 1;
public const long DISP_CHANGE_FAILED = -1;
public const long DISP_CHANGE_BADMODE = -2;
public const long DISP_CHANGE_NOTUPDATED = -3;
public const long DISP_CHANGE_BADFLAGS = -4;
public const long DISP_CHANGE_BADPARAM = -5;
public const long DISP_CHANGE_BADDUALVIEW = -6;
public static void SetPrimary(Screen screen)
{
DISPLAY_DEVICE d = new DISPLAY_DEVICE();
DEVMODE dm = new DEVMODE();
d.cb = Marshal.SizeOf(d);
uint deviceID = 1;
User_32.EnumDisplayDevices(null, deviceID, ref d, 0); //
User_32.EnumDisplaySettings(d.DeviceName, 0, ref dm);
dm.dmPelsWidth = 2560;
dm.dmPelsHeight = 1600;
dm.dmPositionX = screen.Bounds.Right;
dm.dmFields = DM_POSITION | DM_PELSWIDTH | DM_PELSHEIGHT;
User_32.ChangeDisplaySettingsEx(d.DeviceName, ref dm, IntPtr.Zero, CDS_SET_PRIMARY, IntPtr.Zero);
}
```
I call the method like this:
```
SetPrimary(Screen.AllScreens[1])
```
Any ideas?
|
I ran into exactly the same problem, both from C# and after following the advice here to try it in C++. I eventually discovered that the thing the Microsoft documentation doesn't make clear is that the request to set the primary monitor will be ignored (but with the operation reported as successful!) unless you also set the position of the monitor to (0, 0) on the DEVMODE struct. Of course, this means that you also need to shift the positions of your other monitors so that they stay in the same place relative to the new primary monitor. Per the documentation (<http://msdn.microsoft.com/en-us/library/windows/desktop/dd183413%28v=vs.85%29.aspx>), call ChangeDisplaySettingsEx for each monitor with the CDS\_NORESET flag and then make a final call with everything null.
The following code worked for me:
```
public static void SetAsPrimaryMonitor(uint id)
{
var device = new DISPLAY_DEVICE();
var deviceMode = new DEVMODE();
device.cb = Marshal.SizeOf(device);
NativeMethods.EnumDisplayDevices(null, id, ref device, 0);
NativeMethods.EnumDisplaySettings(device.DeviceName, -1, ref deviceMode);
var offsetx = deviceMode.dmPosition.x;
var offsety = deviceMode.dmPosition.y;
deviceMode.dmPosition.x = 0;
deviceMode.dmPosition.y = 0;
NativeMethods.ChangeDisplaySettingsEx(
device.DeviceName,
ref deviceMode,
(IntPtr)null,
(ChangeDisplaySettingsFlags.CDS_SET_PRIMARY | ChangeDisplaySettingsFlags.CDS_UPDATEREGISTRY | ChangeDisplaySettingsFlags.CDS_NORESET),
IntPtr.Zero);
device = new DISPLAY_DEVICE();
device.cb = Marshal.SizeOf(device);
// Update remaining devices
for (uint otherid = 0; NativeMethods.EnumDisplayDevices(null, otherid, ref device, 0); otherid++)
{
if (device.StateFlags.HasFlag(DisplayDeviceStateFlags.AttachedToDesktop) && otherid != id)
{
device.cb = Marshal.SizeOf(device);
var otherDeviceMode = new DEVMODE();
NativeMethods.EnumDisplaySettings(device.DeviceName, -1, ref otherDeviceMode);
otherDeviceMode.dmPosition.x -= offsetx;
otherDeviceMode.dmPosition.y -= offsety;
NativeMethods.ChangeDisplaySettingsEx(
device.DeviceName,
ref otherDeviceMode,
(IntPtr)null,
(ChangeDisplaySettingsFlags.CDS_UPDATEREGISTRY | ChangeDisplaySettingsFlags.CDS_NORESET),
IntPtr.Zero);
}
device.cb = Marshal.SizeOf(device);
}
// Apply settings
NativeMethods.ChangeDisplaySettingsEx(null, IntPtr.Zero, (IntPtr)null, ChangeDisplaySettingsFlags.CDS_NONE, (IntPtr)null);
}
```
Note that a signature for ChangeDisplaySettingsEx with a DEVMODE struct as the second parameter obviously won't allow you to pass in IntPtr.Zero. Create yourself two different signatures for the same extern call, i.e.
```
[DllImport("user32.dll")]
public static extern DISP_CHANGE ChangeDisplaySettingsEx(string lpszDeviceName, ref DEVMODE lpDevMode, IntPtr hwnd, ChangeDisplaySettingsFlags dwflags, IntPtr lParam);
[DllImport("user32.dll")]
public static extern DISP_CHANGE ChangeDisplaySettingsEx(string lpszDeviceName, IntPtr lpDevMode, IntPtr hwnd, ChangeDisplaySettingsFlags dwflags, IntPtr lParam);
```
|
195,287 |
<p>I'd like to get all the permutations of swapped characters pairs of a string. For example:</p>
<p>Base string: <code>abcd</code></p>
<p>Combinations:</p>
<ol>
<li><code>bacd</code></li>
<li><code>acbd</code></li>
<li><code>abdc</code></li>
</ol>
<p>etc.</p>
<h3>Edit</h3>
<p>I want to swap only letters that are next to each other. Like first with second, second with third, but not third with sixth.</p>
<p>What's the best way to do this?</p>
<h3>Edit</h3>
<p>Just for fun: there are three or four solutions, could somebody post a speed test of those so we could compare which is fastest?</p>
<h3>Speed test</h3>
<p>I made speed test of nickf's code and mine, and results are that mine is beating the nickf's at four letters (0.08 and 0.06 for 10K times) but nickf's is beating it at 10 letters (nick's 0.24 and mine 0.37)</p>
|
[
{
"answer_id": 195295,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 3,
"selected": true,
"text": "<p>Edit: Markdown hates me today...</p>\n\n<pre><code>$input = \"abcd\";\n$len = strlen($input);\n$output = array();\n\nfor ($i = 0; $i < $len - 1; ++$i) {\n $output[] = substr($input, 0, $i)\n . substr($input, $i + 1, 1)\n . substr($input, $i, 1)\n . substr($input, $i + 2);\n}\nprint_r($output);\n</code></pre>\n"
},
{
"answer_id": 195313,
"author": "Chris",
"author_id": 27186,
"author_profile": "https://Stackoverflow.com/users/27186",
"pm_score": 1,
"selected": false,
"text": "<p>nickf made beautiful solution thank you , i came up with less beautiful:</p>\n\n<pre><code> $arr=array(0=>'a',1=>'b',2=>'c',3=>'d');\n for($i=0;$i<count($arr)-1;$i++){\n $swapped=\"\";\n //Make normal before swapped\n for($z=0;$z<$i;$z++){\n $swapped.=$arr[$z];\n }\n //Create swapped\n $i1=$i+1;\n $swapped.=$arr[$i1].$arr[$i];\n\n //Make normal after swapped. \n for($y=$z+2;$y<count($arr);$y++){\n $swapped.=$arr[$y];\n\n }\n$arrayswapped[$i]=$swapped;\n}\nvar_dump($arrayswapped);\n</code></pre>\n"
},
{
"answer_id": 195314,
"author": "Georg Schölly",
"author_id": 24587,
"author_profile": "https://Stackoverflow.com/users/24587",
"pm_score": 1,
"selected": false,
"text": "<p>A fast search in google gave me that:</p>\n\n<p><a href=\"http://cogo.wordpress.com/2008/01/08/string-permutation-in-php/\" rel=\"nofollow noreferrer\">http://cogo.wordpress.com/2008/01/08/string-permutation-in-php/</a></p>\n"
},
{
"answer_id": 195337,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 0,
"selected": false,
"text": "<p>How about just using the following:</p>\n\n<pre><code>function swap($s, $i)\n{\n $t = $s[$i];\n $s[$i] = $s[$i+1];\n $s[$i+1] = $t;\n\n return $s;\n}\n\n$s = \"abcd\";\n$l = strlen($s);\nfor ($i=0; $i<$l-1; ++$i)\n{\n print swap($s,$i).\"\\n\";\n}\n</code></pre>\n"
},
{
"answer_id": 195738,
"author": "Czimi",
"author_id": 3906,
"author_profile": "https://Stackoverflow.com/users/3906",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a slightly faster solution as its not overusing substr().</p>\n\n<pre><code>function swapcharpairs($input = \"abcd\") {\n $pre = \"\";\n $a=\"\";\n $b = $input[0];\n $post = substr($input, 1);\n while($post!='') {\n $pre.=$a;\n $a=$b;\n $b=$post[0];\n $post=substr($post,1);\n $swaps[] = $pre.$b.$a.$post;\n };\n return $swaps;\n}\n\nprint_R(swapcharpairs());\n</code></pre>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27186/"
] |
I'd like to get all the permutations of swapped characters pairs of a string. For example:
Base string: `abcd`
Combinations:
1. `bacd`
2. `acbd`
3. `abdc`
etc.
### Edit
I want to swap only letters that are next to each other. Like first with second, second with third, but not third with sixth.
What's the best way to do this?
### Edit
Just for fun: there are three or four solutions, could somebody post a speed test of those so we could compare which is fastest?
### Speed test
I made speed test of nickf's code and mine, and results are that mine is beating the nickf's at four letters (0.08 and 0.06 for 10K times) but nickf's is beating it at 10 letters (nick's 0.24 and mine 0.37)
|
Edit: Markdown hates me today...
```
$input = "abcd";
$len = strlen($input);
$output = array();
for ($i = 0; $i < $len - 1; ++$i) {
$output[] = substr($input, 0, $i)
. substr($input, $i + 1, 1)
. substr($input, $i, 1)
. substr($input, $i + 2);
}
print_r($output);
```
|
195,288 |
<p>I'm working on an ASP.NET website where I am using an asp:repeater with paging done through a VB.NET code-behind file. I'm having trouble with the database connection though. As far as I can tell, the paging is working, but I can't get the data to be certain.</p>
<p>The database is a Microsoft Access database. The function that should be accessing the database is:</p>
<pre><code>Dim pagedData As New PagedDataSource
Sub Page_Load(ByVal obj As Object, ByVal e As EventArgs)
doPaging()
End Sub
Function getTheData() As DataTable
Dim DS As New DataSet()
Dim strConnect As New OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0;Data Source=App_Data/ArtDatabase.mdb")
Dim objOleDBAdapter As New OleDbDataAdapter("SELECT ArtID, FileLocation, Title, UserName, ArtDate FROM Art ORDER BY Art.ArtDate DESC", strConnect)
objOleDBAdapter.Fill(DS, "Art")
Return DS.Tables("Art").Copy
End Function
Sub doPaging()
pagedData.DataSource = getTheData().DefaultView
pagedData.AllowPaging = True
pagedData.PageSize = 2
Try
pagedData.CurrentPageIndex = Int32.Parse(Request.QueryString("Page")).ToString()
Catch ex As Exception
pagedData.CurrentPageIndex = 0
End Try
btnPrev.Visible = (Not pagedData.IsFirstPage)
btnNext.Visible = (Not pagedData.IsLastPage)
pageNumber.Text = (pagedData.CurrentPageIndex + 1) & " of " & pagedData.PageCount
ArtRepeater.DataSource = pagedData
ArtRepeater.DataBind()
End Sub
</code></pre>
<p>The ASP.NET is:</p>
<pre><code><asp:Repeater ID="ArtRepeater" runat="server">
<HeaderTemplate>
<h2>Items in Selected Category:</h2>
</HeaderTemplate>
<ItemTemplate>
<li>
<asp:HyperLink runat="server" ID="HyperLink"
NavigateUrl='<%# Eval("ArtID", "ArtPiece.aspx?ArtID={0}") %>'>
<img src="<%# Eval("FileLocation") %>"
alt="<%# DataBinder.Eval(Container.DataItem, "Title") %>t"/> <br />
<%# DataBinder.Eval(Container.DataItem, "Title") %>
</asp:HyperLink>
</li>
</ItemTemplate>
</asp:Repeater>
</code></pre>
|
[
{
"answer_id": 195300,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 1,
"selected": false,
"text": "<p>If you need help with Connection Strings, this site is the ultimate resource!</p>\n\n<p><a href=\"http://www.connectionstrings.com/\" rel=\"nofollow noreferrer\">http://www.connectionstrings.com/</a></p>\n"
},
{
"answer_id": 196477,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 0,
"selected": false,
"text": "<p>Are you creating the connection string by hand? If so...don't do that! Use the Server Explorer to create your connection. Then highlight it and go to the Properties window, and you'll see the connection string it uses.</p>\n\n<p>Also, using the Server Explorer will let you browse through your tables and even open them up to see your data. At least that'll tell you for certain whether your data is accessible.</p>\n"
},
{
"answer_id": 201365,
"author": "Matt",
"author_id": 17020,
"author_profile": "https://Stackoverflow.com/users/17020",
"pm_score": 1,
"selected": true,
"text": "<p>Problem solved! Pretty much banging my head against the wall now considering how simple it was. It was the Page_Load, I changed it to the following:</p>\n\n<pre><code>Protected Sub Page_Load1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n doPaging()\nEnd Sub\n</code></pre>\n\n<p>And voila, it works!</p>\n\n<p>Also, for the connection string, I ended up using:</p>\n\n<p>Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\ArtDatabase.mdb</p>\n\n<p>Which works great.</p>\n\n<p>Thanks for your help and input guys! </p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17020/"
] |
I'm working on an ASP.NET website where I am using an asp:repeater with paging done through a VB.NET code-behind file. I'm having trouble with the database connection though. As far as I can tell, the paging is working, but I can't get the data to be certain.
The database is a Microsoft Access database. The function that should be accessing the database is:
```
Dim pagedData As New PagedDataSource
Sub Page_Load(ByVal obj As Object, ByVal e As EventArgs)
doPaging()
End Sub
Function getTheData() As DataTable
Dim DS As New DataSet()
Dim strConnect As New OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0;Data Source=App_Data/ArtDatabase.mdb")
Dim objOleDBAdapter As New OleDbDataAdapter("SELECT ArtID, FileLocation, Title, UserName, ArtDate FROM Art ORDER BY Art.ArtDate DESC", strConnect)
objOleDBAdapter.Fill(DS, "Art")
Return DS.Tables("Art").Copy
End Function
Sub doPaging()
pagedData.DataSource = getTheData().DefaultView
pagedData.AllowPaging = True
pagedData.PageSize = 2
Try
pagedData.CurrentPageIndex = Int32.Parse(Request.QueryString("Page")).ToString()
Catch ex As Exception
pagedData.CurrentPageIndex = 0
End Try
btnPrev.Visible = (Not pagedData.IsFirstPage)
btnNext.Visible = (Not pagedData.IsLastPage)
pageNumber.Text = (pagedData.CurrentPageIndex + 1) & " of " & pagedData.PageCount
ArtRepeater.DataSource = pagedData
ArtRepeater.DataBind()
End Sub
```
The ASP.NET is:
```
<asp:Repeater ID="ArtRepeater" runat="server">
<HeaderTemplate>
<h2>Items in Selected Category:</h2>
</HeaderTemplate>
<ItemTemplate>
<li>
<asp:HyperLink runat="server" ID="HyperLink"
NavigateUrl='<%# Eval("ArtID", "ArtPiece.aspx?ArtID={0}") %>'>
<img src="<%# Eval("FileLocation") %>"
alt="<%# DataBinder.Eval(Container.DataItem, "Title") %>t"/> <br />
<%# DataBinder.Eval(Container.DataItem, "Title") %>
</asp:HyperLink>
</li>
</ItemTemplate>
</asp:Repeater>
```
|
Problem solved! Pretty much banging my head against the wall now considering how simple it was. It was the Page\_Load, I changed it to the following:
```
Protected Sub Page_Load1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
doPaging()
End Sub
```
And voila, it works!
Also, for the connection string, I ended up using:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\ArtDatabase.mdb
Which works great.
Thanks for your help and input guys!
|
195,317 |
<p>I am tryiing to create an "add to cart" button for each item that is displayed by an XSLT file. The button must be run at server (VB) and I need to pass parameters into the onlick, so that the requested item is added to the cart. Is this possible, and if so, how should I go about it?</p>
<p>When I try</p>
<pre><code><asp:Button id="Button123"
Text="Add to Cart"
CommandName="AddToCart"
CommandArgument="123"
OnCommand="CommandBtn_Click"
runat="server"/>
</code></pre>
<p>I get "'asp' is an undeclared namespace"</p>
<p>I've also tried</p>
<pre><code><asp>
<xsl:attribute name="Button">id="BtnAddToCart"</xsl:attribute>
<xsl:attribute name="text">Add to cart</xsl:attribute>
<xsl:attribute name="CommandName">AddToCart</xsl:attribute>
<xsl:attribute name="CommandArgument">123</xsl:attribute>
<xsl:attribute name="Command">CommandBtn_Click</xsl:attribute>
<xsl:attribute name="runat">server"</xsl:attribute>
</asp>
</code></pre>
<p>Which doesn't give any errors, but doesn't do anything at all</p>
<p>I need to use XSLT directly for displaying my products, as it is for an assignment, although what I am trying to do here is beyond the scope of the assignment.</p>
|
[
{
"answer_id": 195384,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 2,
"selected": false,
"text": "<p>XSLT can generate pretty much anything you want - but you need to know what you want to generate first.</p>\n\n<p>In ASP.Net I would recommend doing this using the CommandArgument and OnCommand event.</p>\n\n<pre><code><asp:Button id=\"Button123\"\n Text=\"Add to Cart\"\n CommandName=\"AddToCart\"\n CommandArgument=\"123\"\n OnCommand=\"CommandBtn_Click\" \n runat=\"server\"/>\n</code></pre>\n\n<p>Then the single event handler can handle all the button events.</p>\n\n<p>Seeing as I have no idea what your input XML looks like it is very hard to guess how you could generate this in XSLT, but you probably would make good use of Attribute Value Templates, like so:</p>\n\n<pre><code><xsl:for-each select=\"Item\">\n ...\n <asp:Button id=\"Button{@Id}\"\n Text=\"Add To Cart\"\n CommandName=\"AddToCart\"\n CommandArgument=\"{@Id}\"\n OnCommand=\"CommandBtn_Click\" \n runat=\"server\"/>\n</xsl:foreach>\n</code></pre>\n"
},
{
"answer_id": 195745,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 1,
"selected": false,
"text": "<p>Why not use an XmlDataSource with a GridView or Repeater, which ever is more appropriate and use a Template to generate custom buttons bound to the appropriate properties from the Xml element? You can still use XSLT to transform the data (sort, extract subsets, select properties, etc.) if needed.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am tryiing to create an "add to cart" button for each item that is displayed by an XSLT file. The button must be run at server (VB) and I need to pass parameters into the onlick, so that the requested item is added to the cart. Is this possible, and if so, how should I go about it?
When I try
```
<asp:Button id="Button123"
Text="Add to Cart"
CommandName="AddToCart"
CommandArgument="123"
OnCommand="CommandBtn_Click"
runat="server"/>
```
I get "'asp' is an undeclared namespace"
I've also tried
```
<asp>
<xsl:attribute name="Button">id="BtnAddToCart"</xsl:attribute>
<xsl:attribute name="text">Add to cart</xsl:attribute>
<xsl:attribute name="CommandName">AddToCart</xsl:attribute>
<xsl:attribute name="CommandArgument">123</xsl:attribute>
<xsl:attribute name="Command">CommandBtn_Click</xsl:attribute>
<xsl:attribute name="runat">server"</xsl:attribute>
</asp>
```
Which doesn't give any errors, but doesn't do anything at all
I need to use XSLT directly for displaying my products, as it is for an assignment, although what I am trying to do here is beyond the scope of the assignment.
|
XSLT can generate pretty much anything you want - but you need to know what you want to generate first.
In ASP.Net I would recommend doing this using the CommandArgument and OnCommand event.
```
<asp:Button id="Button123"
Text="Add to Cart"
CommandName="AddToCart"
CommandArgument="123"
OnCommand="CommandBtn_Click"
runat="server"/>
```
Then the single event handler can handle all the button events.
Seeing as I have no idea what your input XML looks like it is very hard to guess how you could generate this in XSLT, but you probably would make good use of Attribute Value Templates, like so:
```
<xsl:for-each select="Item">
...
<asp:Button id="Button{@Id}"
Text="Add To Cart"
CommandName="AddToCart"
CommandArgument="{@Id}"
OnCommand="CommandBtn_Click"
runat="server"/>
</xsl:foreach>
```
|
195,321 |
<p><a href="https://stackoverflow.com/users/9931/ryan-delucchi">Ryan Delucchi</a> asked <a href="https://stackoverflow.com/questions/194698/how-to-load-a-jar-file-at-runtime#194712">here</a> in comment #3 to <a href="https://stackoverflow.com/users/4725/tom-hawtin-tackline">Tom Hawtin</a>'s answer:</p>
<blockquote>
<p>why is Class.newInstance() "evil"?</p>
</blockquote>
<p>this in response to the code sample:</p>
<pre><code>// Avoid Class.newInstance, for it is evil.
Constructor<? extends Runnable> ctor = runClass.getConstructor();
Runnable doRun = ctor.newInstance();
</code></pre>
<p>so, why is it Evil?</p>
|
[
{
"answer_id": 195328,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 7,
"selected": true,
"text": "<p>The Java API documentation explains why (<a href=\"http://java.sun.com/javase/6/docs/api/java/lang/Class.html#newInstance()\" rel=\"noreferrer\">http://java.sun.com/javase/6/docs/api/java/lang/Class.html#newInstance()</a>):</p>\n\n<blockquote>\n <p>Note that this method propagates any exception thrown by the nullary constructor, including a checked exception. Use of this method effectively bypasses the compile-time exception checking that would otherwise be performed by the compiler. The <code>Constructor.newInstance</code> method avoids this problem by wrapping any exception thrown by the constructor in a (checked) <code>InvocationTargetException</code>.</p>\n</blockquote>\n\n<p>In other words, it can defeat the checked exceptions system.</p>\n"
},
{
"answer_id": 196657,
"author": "alexei.vidmich",
"author_id": 7199,
"author_profile": "https://Stackoverflow.com/users/7199",
"pm_score": 5,
"selected": false,
"text": "<p>One more reason:</p>\n\n<p>Modern IDEs allow you to find class usages - it helps during refactoring, if you and your IDE know what code is using class that you plan to change.</p>\n\n<p>When you don't do an explicit usage of the constructor, but use Class.newInstance() instead, you risk not to find that usage during refactoring and this problem will not manifest itself when you compile.</p>\n"
},
{
"answer_id": 53014482,
"author": "Eugene",
"author_id": 1059372,
"author_profile": "https://Stackoverflow.com/users/1059372",
"pm_score": 4,
"selected": false,
"text": "<p>I don't know why no one provided a simple example based explanation to this, as compared to <code>Constructor::newInstance</code> for example, since <em>finally</em> <code>Class::newInstance</code> was deprecated since java-9.</p>\n\n<p>Suppose you have this very simple class (does not matter that it is broken):</p>\n\n<pre><code>static class Foo {\n public Foo() throws IOException {\n throw new IOException();\n }\n}\n</code></pre>\n\n<p>And you try to create an instance of it via reflection. First <code>Class::newInstance</code>:</p>\n\n<pre><code> Class<Foo> clazz = ...\n\n try {\n clazz.newInstance();\n } catch (InstantiationException e) {\n // handle 1\n } catch (IllegalAccessException e) {\n // handle 2\n }\n</code></pre>\n\n<p>Calling this will result in a <code>IOException</code> being thrown - problem is that your code does not handle it, neither <code>handle 1</code> nor <code>handle 2</code> will catch it.</p>\n\n<p>In contrast when doing it via a <code>Constructor</code>:</p>\n\n<pre><code> Constructor<Foo> constructor = null;\n try {\n constructor = clazz.getConstructor();\n } catch (NoSuchMethodException e) {\n e.printStackTrace();\n }\n\n try {\n Foo foo = constructor.newInstance();\n } catch (InstantiationException e) {\n e.printStackTrace();\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n } catch (InvocationTargetException e) {\n System.out.println(\"handle 3 called\");\n e.printStackTrace();\n }\n</code></pre>\n\n<p>that handle 3 will be called, thus you will handle it.</p>\n\n<p>Effectively, <code>Class::newInstance</code> bypasses the exception handling - which you really don't want.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11813/"
] |
[Ryan Delucchi](https://stackoverflow.com/users/9931/ryan-delucchi) asked [here](https://stackoverflow.com/questions/194698/how-to-load-a-jar-file-at-runtime#194712) in comment #3 to [Tom Hawtin](https://stackoverflow.com/users/4725/tom-hawtin-tackline)'s answer:
>
> why is Class.newInstance() "evil"?
>
>
>
this in response to the code sample:
```
// Avoid Class.newInstance, for it is evil.
Constructor<? extends Runnable> ctor = runClass.getConstructor();
Runnable doRun = ctor.newInstance();
```
so, why is it Evil?
|
The Java API documentation explains why (<http://java.sun.com/javase/6/docs/api/java/lang/Class.html#newInstance()>):
>
> Note that this method propagates any exception thrown by the nullary constructor, including a checked exception. Use of this method effectively bypasses the compile-time exception checking that would otherwise be performed by the compiler. The `Constructor.newInstance` method avoids this problem by wrapping any exception thrown by the constructor in a (checked) `InvocationTargetException`.
>
>
>
In other words, it can defeat the checked exceptions system.
|
195,323 |
<p>I'd like to read whole content of a text file to a <code>std::string</code> object with c++. </p>
<p>With Python, I can write:</p>
<pre><code>text = open("text.txt", "rt").read()
</code></pre>
<p>It is very simple and elegant. I hate ugly stuff, so I'd like to know - what is the most elegant way to read a text file with C++?
Thanks.</p>
|
[
{
"answer_id": 195349,
"author": "sharkin",
"author_id": 7891,
"author_profile": "https://Stackoverflow.com/users/7891",
"pm_score": 2,
"selected": false,
"text": "<p>You seem to speak of elegance as a definite property of \"little code\". This is ofcourse subjective in some extent. Some would say that omitting all error handling isn't very elegant. Some would say that clear and compact code you understand right away is elegant.</p>\n\n<p>Write your own one-liner function/method which reads the file contents, but make it rigorous and safe underneath the surface and you will have covered both aspects of elegance.</p>\n\n<p>All the best</p>\n\n<p>/Robert</p>\n"
},
{
"answer_id": 195350,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 8,
"selected": true,
"text": "<p>There are many ways, you pick which is the most elegant for you.</p>\n\n<p>Reading into char*:</p>\n\n<pre><code>ifstream file (\"file.txt\", ios::in|ios::binary|ios::ate);\nif (file.is_open())\n{\n file.seekg(0, ios::end);\n size = file.tellg();\n char *contents = new char [size];\n file.seekg (0, ios::beg);\n file.read (contents, size);\n file.close();\n //... do something with it\n delete [] contents;\n}\n</code></pre>\n\n<p>Into std::string:</p>\n\n<pre><code>std::ifstream in(\"file.txt\");\nstd::string contents((std::istreambuf_iterator<char>(in)), \n std::istreambuf_iterator<char>());\n</code></pre>\n\n<p>Into vector<char>:</p>\n\n<pre><code>std::ifstream in(\"file.txt\");\nstd::vector<char> contents((std::istreambuf_iterator<char>(in)),\n std::istreambuf_iterator<char>());\n</code></pre>\n\n<p>Into string, using stringstream:</p>\n\n<pre><code>std::ifstream in(\"file.txt\");\nstd::stringstream buffer;\nbuffer << in.rdbuf();\nstd::string contents(buffer.str());\n</code></pre>\n\n<p>file.txt is just an example, everything works fine for binary files as well, just make sure you use ios::binary in ifstream constructor.</p>\n"
},
{
"answer_id": 195545,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 0,
"selected": false,
"text": "<p>I like Milan's char* way, but with std::string.</p>\n\n<pre><code>\n#include <iostream>\n#include <string>\n#include <fstream>\n#include <cstdlib>\nusing namespace std;\n\nstring& getfile(const string& filename, string& buffer) {\n ifstream in(filename.c_str(), ios_base::binary | ios_base::ate);\n in.exceptions(ios_base::badbit | ios_base::failbit | ios_base::eofbit);\n buffer.resize(in.tellg());\n in.seekg(0, ios_base::beg);\n in.read(&buffer[0], buffer.size());\n return buffer;\n}\n\nint main(int argc, char* argv[]) {\n if (argc != 2) {\n cerr << \"Usage: this_executable file_to_read\\n\";\n return EXIT_FAILURE;\n }\n string buffer;\n cout << getfile(argv[1], buffer).size() << \"\\n\";\n}\n</code></pre>\n\n<p>(with or without the ios_base::binary, depending on whether you want newlines tranlated or not. You could also change getfile to just return a string so that you don't have to pass a buffer string in. Then, test to see if the compiler optimizes the copy out when returning.)</p>\n\n<p>However, this might look a little better (and be a lot slower):</p>\n\n<pre><code>\n#include <iostream>\n#include <string>\n#include <fstream>\n#include <cstdlib>\nusing namespace std;\n\nstring getfile(const string& filename) {\n ifstream in(filename.c_str(), ios_base::binary);\n in.exceptions(ios_base::badbit | ios_base::failbit | ios_base::eofbit);\n return string(istreambuf_iterator<char>(in), istreambuf_iterator<char>());\n}\n\nint main(int argc, char* argv[]) {\n if (argc != 2) {\n cerr << \"Usage: this_executable file_to_read\\n\";\n return EXIT_FAILURE;\n }\n cout << getfile(argv[1]).size() << \"\\n\";\n}\n</code></pre>\n"
},
{
"answer_id": 195558,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": false,
"text": "<p>There's <a href=\"https://stackoverflow.com/questions/116038/what-is-the-best-way-to-slurp-a-file-into-a-stdstring-in-c\">another thread</a> on this subject.</p>\n\n<p>My solutions from this thread (both one-liners):</p>\n\n<p>The nice (see Milan's second solution):</p>\n\n<pre><code>string str((istreambuf_iterator<char>(ifs)), istreambuf_iterator<char>());\n</code></pre>\n\n<p>and the fast:</p>\n\n<pre><code>string str(static_cast<stringstream const&>(stringstream() << ifs.rdbuf()).str());\n</code></pre>\n"
},
{
"answer_id": 3777946,
"author": "Don Pedro",
"author_id": 456108,
"author_profile": "https://Stackoverflow.com/users/456108",
"pm_score": 2,
"selected": false,
"text": "<p>But beware that a c++-string (or more concrete: An STL-string) is as little as a C-String capable of holding a string of arbitraty length - of course not!</p>\n\n<p>Take a look at the member max_size() which gives you the maximum number of characters a string might contain. This is an implementation definied number and may not be portable among different platforms. Visual Studio gives a value of about 4gigs for strings, others might give you only 64k and on 64Bit-platforms it might give you something really huge! It depends and of course normally you will run into a bad_alloc-exception due to memory exhaustion a long time before reaching the 4gig limit...</p>\n\n<p>BTW: max_size() is a member of other STL-containers as well! It will give you the maximum number of elements of a certain type (for which you instanciated the container) which this container will (theoretically) be able to hold.</p>\n\n<p>So, if you're reading from a file of unknow origin you should:<br>\n- Check its size and make sure it's smaller than max_size()<br>\n- Catch and process bad_alloc-exceptions </p>\n\n<p>And another point:\nWhy are you keen on reading the file into a string? I would expect to further process it by incrementally parsing it or something, right? So instead of reading it into a string you might as well read it into a stringstream (which basically is just some syntactic sugar for a string) and do the processing. But then you could do the processing directly from the file as well. Because if properly programmed the stringstream could seamlessly be replaced by a filestream, i. e. by the file itself. Or by any other input stream as well, they all share the same members and operators and can thus be seamlessly interchanged! </p>\n\n<p>And for the processing itself: There's also a lot you can have automated by the compiler! E. g. let's say you want to tokenize the string. When defining a proper template the following actions:<br>\n- Reading from a file (or a string or any other input stream)<br>\n- Tokenizing the content<br>\n- pushing all found tokens into an STL-container<br>\n- sort the tokens alphabetically<br>\n- eleminating any double values<br>\ncan all(!!) be achived in one single(!) line of C++-code (let aside the template itself and the error handling)! It's just a single call of the function std::copy()! Just google for \"token iterator\" and you'll get an idea of what I mean. So this appears to me to be even more \"elegant\" than just reading from a file...</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25077/"
] |
I'd like to read whole content of a text file to a `std::string` object with c++.
With Python, I can write:
```
text = open("text.txt", "rt").read()
```
It is very simple and elegant. I hate ugly stuff, so I'd like to know - what is the most elegant way to read a text file with C++?
Thanks.
|
There are many ways, you pick which is the most elegant for you.
Reading into char\*:
```
ifstream file ("file.txt", ios::in|ios::binary|ios::ate);
if (file.is_open())
{
file.seekg(0, ios::end);
size = file.tellg();
char *contents = new char [size];
file.seekg (0, ios::beg);
file.read (contents, size);
file.close();
//... do something with it
delete [] contents;
}
```
Into std::string:
```
std::ifstream in("file.txt");
std::string contents((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
```
Into vector<char>:
```
std::ifstream in("file.txt");
std::vector<char> contents((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
```
Into string, using stringstream:
```
std::ifstream in("file.txt");
std::stringstream buffer;
buffer << in.rdbuf();
std::string contents(buffer.str());
```
file.txt is just an example, everything works fine for binary files as well, just make sure you use ios::binary in ifstream constructor.
|
195,363 |
<p>In IE when I insert text into a <code><pre></code> tag the newlines are ignored:</p>
<pre><code><pre id="putItHere"></pre>
<script>
function putText() {
document.getElementById("putItHere").innerHTML = "first line\nsecond line";
}
</script>
</code></pre>
<p>Using <code>\r\n</code> instead of a plain <code>\n</code> does not work. </p>
<p><code><br/></code> does work but inserts an extra blank line in FF, which is not acceptable for my purposes.</p>
|
[
{
"answer_id": 195370,
"author": "GavinCattell",
"author_id": 21644,
"author_profile": "https://Stackoverflow.com/users/21644",
"pm_score": 2,
"selected": false,
"text": "<p><code><br/></code> shoud only output one line in all browsers. Of course remove the \\n as well, code should be:</p>\n\n<pre><code>document.getElementById(\"putItHere\").innerHTML = \"first line<br/>second line\";\n</code></pre>\n"
},
{
"answer_id": 195382,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 5,
"selected": true,
"text": "<p>These <a href=\"http://www.quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html\" rel=\"noreferrer\">quirksmode.org bug report and comments</a> about innerHTML behaviour of Internet Explorer could help:</p>\n\n<p>\"<em>IE applies <strong>HTML normalization</strong> to the data that is assigned to the innerHTML property. This causes incorrect display of whitespace in elements that ought to preserve formatting, such as <pre> and <textarea>.</em>\"</p>\n"
},
{
"answer_id": 195385,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 3,
"selected": false,
"text": "<p>Does this work in IE?</p>\n\n<pre><code>document.getElementById(\"putItHere\")\n .appendChild(document.createTextNode(\"first line\\nsecond line\"));\n</code></pre>\n\n<p>I tested it with Firefox and it works. :-)</p>\n"
},
{
"answer_id": 195399,
"author": "Samuel Kim",
"author_id": 437435,
"author_profile": "https://Stackoverflow.com/users/437435",
"pm_score": 2,
"selected": false,
"text": "<p>Content inside the <code><pre></code> tag should not be considered HTML.</p>\n\n<p>In fact, the point of <code><pre></code> tag is so that it does display formatted text.</p>\n\n<p>Using the innerText property is the correct way to modify the content of a <code><pre></code> tag.</p>\n\n<pre><code>document.getElementById(\"putItHere\").innerText = \"first line\\nsecond line\";\n</code></pre>\n"
},
{
"answer_id": 195407,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I reckon this.</p>\n\n<p>What I found was IE is using \\r\\n and Fx(others) is using \\n</p>\n\n<pre><code>var newline;\nif ( document.all ) newline = '\\r\\n';\nelse newline = '\\n';\n\nvar data = 'firstline' + newline + 'second line';\ndocument.getElementById(\"putItHere\").appendChild(document.createTextNode(data));\n</code></pre>\n\n<p>For a TinyMCE(wysiwyg editor) plugin I once made I ended up with using BR i edit mode\nand cleaned it up on submit etc.</p>\n\n<p>This code loops through all BR elements inside PRE elements and replaces BR with newlines.</p>\n\n<p>Note that the code relies on the TinyMCE API, but can easily be written using standard Javascript.</p>\n\n<p>Clean up:</p>\n\n<pre><code> var br = ed.dom.select('pre br');\n for (var i = 0; i < br.length; i++) {\n var nlChar;\n if (tinymce.isIE)\n nlChar = '\\r\\n';\n else\n nlChar = '\\n';\n\n var nl = ed.getDoc().createTextNode(nlChar);\n ed.dom.insertAfter(nl, br[i]);\n ed.dom.remove(br[i]);\n }\n</code></pre>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 363188,
"author": "Edward Wilde",
"author_id": 5182,
"author_profile": "https://Stackoverflow.com/users/5182",
"pm_score": 3,
"selected": false,
"text": "<p>The workaround can be found in the page linked to in the accepted answer. For ease of use here it is:</p>\n\n<pre><code>if (elem.tagName == \"PRE\" && \"outerHTML\" in elem)\n{\n elem.outerHTML = \"<PRE>\" + str + \"</PRE>\";\n}\nelse\n{\n elem.innerHTML = str;\n}\n</code></pre>\n"
},
{
"answer_id": 613542,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>if (typeof div2.innerText == 'undefined')\n div2.innerHTML = value;\nelse\n div2.innerText = value;\n</code></pre>\n\n<p>that worked for me.</p>\n"
},
{
"answer_id": 825098,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I've found that innerHTML is processed before it is applied to the element, hence <br> becomes a newline and multiple white spaces are removed.</p>\n\n<p>To preserve the raw text you must use nodeValue, for example;</p>\n\n<pre><code>document.getElementById('pre_id').firstChild.nodeValue=' white space \\r\\n ad new line';\n</code></pre>\n"
},
{
"answer_id": 2720402,
"author": "Vivek Jani",
"author_id": 326768,
"author_profile": "https://Stackoverflow.com/users/326768",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't want to use outerHTML, you can also do the following for IE, if an additional pre tag is not an issue:</p>\n\n<pre><code> if(isIE)\n document.getElementById(\"putItHere\").innerHTML = \"<pre>\" + content+\"</pre>\";\n else\n document.getElementById(\"putItHere\").innerHTML = content;\n</code></pre>\n"
},
{
"answer_id": 5263220,
"author": "Drew",
"author_id": 160755,
"author_profile": "https://Stackoverflow.com/users/160755",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://blogs.msdn.com/b/ie/archive/2010/09/13/interoperable-html-parsing-in-ie9.aspx\" rel=\"nofollow\">IE9 does not normalize white spaces</a>, unlike its predecessors.</p>\n\n<p>You should test for support rather than targeting any specific browser. E.g...</p>\n\n<pre><code>var t = document.createElement(elem.tagName);\nt.innerHTML = \"\\n\";\n\nif( t.innerHTML === \"\\n\" ){\n elem.innerHTML = str;\n}\nelse if(\"outerHTML\" in elem)\n{\n elem.outerHTML = \"<\"+elem.tagName+\">\" + str + \"</\"+elem.tagName+\">\";\n}\nelse {\n // fallback of your choice, probably do the first one.\n}\n</code></pre>\n"
},
{
"answer_id": 8402133,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a very small tweak to Edward Wilde's answer that preserves the attributes on the <pre> tag.</p>\n\n<pre><code>if (elem.tagName == \"PRE\" && \"outerHTML\" in elem) {\n var outer = elem.outerHTML;\n elem.outerHTML = outer.substring(0, outer.indexOf('>') + 1) + str + \"</PRE>\";\n}\nelse {\n elem.innerHTML = str;\n}\n</code></pre>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27198/"
] |
In IE when I insert text into a `<pre>` tag the newlines are ignored:
```
<pre id="putItHere"></pre>
<script>
function putText() {
document.getElementById("putItHere").innerHTML = "first line\nsecond line";
}
</script>
```
Using `\r\n` instead of a plain `\n` does not work.
`<br/>` does work but inserts an extra blank line in FF, which is not acceptable for my purposes.
|
These [quirksmode.org bug report and comments](http://www.quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html) about innerHTML behaviour of Internet Explorer could help:
"*IE applies **HTML normalization** to the data that is assigned to the innerHTML property. This causes incorrect display of whitespace in elements that ought to preserve formatting, such as <pre> and <textarea>.*"
|
195,368 |
<p>How is it possible for this to be true</p>
<pre><code>XmlDocument d = BuildReportXML(schema);
DataSet ds = new DataSet();
ds.ReadXmlSchema(schema);
ds.ReadXml(new XmlNodeReader(d));
</code></pre>
<p>Schema is the schema location that I apply to the XmlDocument before I start setting data, assuring that all the columns are of the correct type. Then I set the schema to the DataSet, and read the document into it. When I do this it throws an "Input string was not in a correct format." I have a few decimal variables in the Xml, and I assume this is the error. All of the information is obviously of the correct format, else the XmlDocument would have had errors. What can I do?</p>
|
[
{
"answer_id": 195370,
"author": "GavinCattell",
"author_id": 21644,
"author_profile": "https://Stackoverflow.com/users/21644",
"pm_score": 2,
"selected": false,
"text": "<p><code><br/></code> shoud only output one line in all browsers. Of course remove the \\n as well, code should be:</p>\n\n<pre><code>document.getElementById(\"putItHere\").innerHTML = \"first line<br/>second line\";\n</code></pre>\n"
},
{
"answer_id": 195382,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 5,
"selected": true,
"text": "<p>These <a href=\"http://www.quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html\" rel=\"noreferrer\">quirksmode.org bug report and comments</a> about innerHTML behaviour of Internet Explorer could help:</p>\n\n<p>\"<em>IE applies <strong>HTML normalization</strong> to the data that is assigned to the innerHTML property. This causes incorrect display of whitespace in elements that ought to preserve formatting, such as <pre> and <textarea>.</em>\"</p>\n"
},
{
"answer_id": 195385,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 3,
"selected": false,
"text": "<p>Does this work in IE?</p>\n\n<pre><code>document.getElementById(\"putItHere\")\n .appendChild(document.createTextNode(\"first line\\nsecond line\"));\n</code></pre>\n\n<p>I tested it with Firefox and it works. :-)</p>\n"
},
{
"answer_id": 195399,
"author": "Samuel Kim",
"author_id": 437435,
"author_profile": "https://Stackoverflow.com/users/437435",
"pm_score": 2,
"selected": false,
"text": "<p>Content inside the <code><pre></code> tag should not be considered HTML.</p>\n\n<p>In fact, the point of <code><pre></code> tag is so that it does display formatted text.</p>\n\n<p>Using the innerText property is the correct way to modify the content of a <code><pre></code> tag.</p>\n\n<pre><code>document.getElementById(\"putItHere\").innerText = \"first line\\nsecond line\";\n</code></pre>\n"
},
{
"answer_id": 195407,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I reckon this.</p>\n\n<p>What I found was IE is using \\r\\n and Fx(others) is using \\n</p>\n\n<pre><code>var newline;\nif ( document.all ) newline = '\\r\\n';\nelse newline = '\\n';\n\nvar data = 'firstline' + newline + 'second line';\ndocument.getElementById(\"putItHere\").appendChild(document.createTextNode(data));\n</code></pre>\n\n<p>For a TinyMCE(wysiwyg editor) plugin I once made I ended up with using BR i edit mode\nand cleaned it up on submit etc.</p>\n\n<p>This code loops through all BR elements inside PRE elements and replaces BR with newlines.</p>\n\n<p>Note that the code relies on the TinyMCE API, but can easily be written using standard Javascript.</p>\n\n<p>Clean up:</p>\n\n<pre><code> var br = ed.dom.select('pre br');\n for (var i = 0; i < br.length; i++) {\n var nlChar;\n if (tinymce.isIE)\n nlChar = '\\r\\n';\n else\n nlChar = '\\n';\n\n var nl = ed.getDoc().createTextNode(nlChar);\n ed.dom.insertAfter(nl, br[i]);\n ed.dom.remove(br[i]);\n }\n</code></pre>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 363188,
"author": "Edward Wilde",
"author_id": 5182,
"author_profile": "https://Stackoverflow.com/users/5182",
"pm_score": 3,
"selected": false,
"text": "<p>The workaround can be found in the page linked to in the accepted answer. For ease of use here it is:</p>\n\n<pre><code>if (elem.tagName == \"PRE\" && \"outerHTML\" in elem)\n{\n elem.outerHTML = \"<PRE>\" + str + \"</PRE>\";\n}\nelse\n{\n elem.innerHTML = str;\n}\n</code></pre>\n"
},
{
"answer_id": 613542,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>if (typeof div2.innerText == 'undefined')\n div2.innerHTML = value;\nelse\n div2.innerText = value;\n</code></pre>\n\n<p>that worked for me.</p>\n"
},
{
"answer_id": 825098,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I've found that innerHTML is processed before it is applied to the element, hence <br> becomes a newline and multiple white spaces are removed.</p>\n\n<p>To preserve the raw text you must use nodeValue, for example;</p>\n\n<pre><code>document.getElementById('pre_id').firstChild.nodeValue=' white space \\r\\n ad new line';\n</code></pre>\n"
},
{
"answer_id": 2720402,
"author": "Vivek Jani",
"author_id": 326768,
"author_profile": "https://Stackoverflow.com/users/326768",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't want to use outerHTML, you can also do the following for IE, if an additional pre tag is not an issue:</p>\n\n<pre><code> if(isIE)\n document.getElementById(\"putItHere\").innerHTML = \"<pre>\" + content+\"</pre>\";\n else\n document.getElementById(\"putItHere\").innerHTML = content;\n</code></pre>\n"
},
{
"answer_id": 5263220,
"author": "Drew",
"author_id": 160755,
"author_profile": "https://Stackoverflow.com/users/160755",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://blogs.msdn.com/b/ie/archive/2010/09/13/interoperable-html-parsing-in-ie9.aspx\" rel=\"nofollow\">IE9 does not normalize white spaces</a>, unlike its predecessors.</p>\n\n<p>You should test for support rather than targeting any specific browser. E.g...</p>\n\n<pre><code>var t = document.createElement(elem.tagName);\nt.innerHTML = \"\\n\";\n\nif( t.innerHTML === \"\\n\" ){\n elem.innerHTML = str;\n}\nelse if(\"outerHTML\" in elem)\n{\n elem.outerHTML = \"<\"+elem.tagName+\">\" + str + \"</\"+elem.tagName+\">\";\n}\nelse {\n // fallback of your choice, probably do the first one.\n}\n</code></pre>\n"
},
{
"answer_id": 8402133,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a very small tweak to Edward Wilde's answer that preserves the attributes on the <pre> tag.</p>\n\n<pre><code>if (elem.tagName == \"PRE\" && \"outerHTML\" in elem) {\n var outer = elem.outerHTML;\n elem.outerHTML = outer.substring(0, outer.indexOf('>') + 1) + str + \"</PRE>\";\n}\nelse {\n elem.innerHTML = str;\n}\n</code></pre>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11137/"
] |
How is it possible for this to be true
```
XmlDocument d = BuildReportXML(schema);
DataSet ds = new DataSet();
ds.ReadXmlSchema(schema);
ds.ReadXml(new XmlNodeReader(d));
```
Schema is the schema location that I apply to the XmlDocument before I start setting data, assuring that all the columns are of the correct type. Then I set the schema to the DataSet, and read the document into it. When I do this it throws an "Input string was not in a correct format." I have a few decimal variables in the Xml, and I assume this is the error. All of the information is obviously of the correct format, else the XmlDocument would have had errors. What can I do?
|
These [quirksmode.org bug report and comments](http://www.quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html) about innerHTML behaviour of Internet Explorer could help:
"*IE applies **HTML normalization** to the data that is assigned to the innerHTML property. This causes incorrect display of whitespace in elements that ought to preserve formatting, such as <pre> and <textarea>.*"
|
195,377 |
<p>I'm trying to debug an application (under PostgreSQL) and came across the following error:
"current transaction is aborted, commands ignored".</p>
<p>As far as I can understand a "transaction" is just a notion related to the underlying database connection.</p>
<p>If the connection has an auto commit "false", you can execute queries through the same Statement as long as it isn't failing. In which case you should rollback.</p>
<p>If auto commit is "true" then it doesn't matter as long as all your queries are considered atomic.</p>
<p>Using auto commit false, I get the aforementioned error by PostgreSQL even when a simple </p>
<pre><code>select * from foo
</code></pre>
<p>fails, which makes me ask, under which SQLException(s) is a "transaction" considered invalid and should be rolled backed or not used for another query?</p>
<blockquote>
<p>using MacOS 10.5, Java 1.5.0_16, PostgreSQL 8.3 with JDBC driver 8.1-407.jdbc3</p>
</blockquote>
|
[
{
"answer_id": 195383,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": true,
"text": "<p>That error means that one of the queries sent in a transaction has failed, so the rest of the queries are ignored until the end of the current transaction (which will automatically be a rollback). To PostgreSQL the transaction has failed, and it will be rolled back in any case after the error with one exception. You have to take appropriate measures, one of</p>\n\n<ol>\n<li>discard the statement and start anew.</li>\n<li>use <a href=\"http://www.postgresql.org/docs/8.3/interactive/sql-savepoint.html\" rel=\"nofollow noreferrer\">SAVEPOINT</a>s in the transaction to be able to get back to that point in time and try another path. (This is the exception)</li>\n</ol>\n\n<p>Enable <a href=\"http://www.databasejournal.com/features/postgresql/article.php/3323561\" rel=\"nofollow noreferrer\">query logging</a> to see which query is the failing one and why.</p>\n\n<p>In any case the exact answer to your question is that any SQLException should mean a rollback happened when the end of transaction command is sent, that is when a COMMIT or ROLLBACK (or END) is issued. This is how it works, if you use savepoints you'll still be bound by the same rules, you'll just be able to get back to where you saved and try something else.</p>\n"
},
{
"answer_id": 195547,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 1,
"selected": false,
"text": "<p>It seems to be a characteristic behaviour of PostgreSQL that is not shared by most other DBMS. In general (outside of PostgreSQL), you can have one operation fail because of an error and then, in the same transaction, can try alternative actions that will succeed, compensating for the error. One example: consider a merging (insert/update) operation. If you try to INSERT the new record but find that it already exists, you can switch to an UPDATE operation that changes the existing record instead. This works fine in all the main DBMS. I'm not certain that it does not work in PostgreSQL, but the descriptions I've seen elsewhere, as well as in this question, suggest that when the attempted INSERT means that any further activity in the transaction is doomed to fail too. Which is at best draconian and at worst 'unusable'.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3887/"
] |
I'm trying to debug an application (under PostgreSQL) and came across the following error:
"current transaction is aborted, commands ignored".
As far as I can understand a "transaction" is just a notion related to the underlying database connection.
If the connection has an auto commit "false", you can execute queries through the same Statement as long as it isn't failing. In which case you should rollback.
If auto commit is "true" then it doesn't matter as long as all your queries are considered atomic.
Using auto commit false, I get the aforementioned error by PostgreSQL even when a simple
```
select * from foo
```
fails, which makes me ask, under which SQLException(s) is a "transaction" considered invalid and should be rolled backed or not used for another query?
>
> using MacOS 10.5, Java 1.5.0\_16, PostgreSQL 8.3 with JDBC driver 8.1-407.jdbc3
>
>
>
|
That error means that one of the queries sent in a transaction has failed, so the rest of the queries are ignored until the end of the current transaction (which will automatically be a rollback). To PostgreSQL the transaction has failed, and it will be rolled back in any case after the error with one exception. You have to take appropriate measures, one of
1. discard the statement and start anew.
2. use [SAVEPOINT](http://www.postgresql.org/docs/8.3/interactive/sql-savepoint.html)s in the transaction to be able to get back to that point in time and try another path. (This is the exception)
Enable [query logging](http://www.databasejournal.com/features/postgresql/article.php/3323561) to see which query is the failing one and why.
In any case the exact answer to your question is that any SQLException should mean a rollback happened when the end of transaction command is sent, that is when a COMMIT or ROLLBACK (or END) is issued. This is how it works, if you use savepoints you'll still be bound by the same rules, you'll just be able to get back to where you saved and try something else.
|
195,410 |
<p>I am interested in what methods of logging is frequent in an Oracle database.
Our method is the following:</p>
<p>We create a log table for the table to be logged. The log table contains all the columns of the original table plus some special fields including timestamp, modification type (insert, update, delete), modifier's id. A trigger on the original table creates one log row for each insertion and deletion, and two rows for a modification. Log rows contain the data before and after the alteration of the original one.</p>
<p>Although state of the records can be mined back in time using this method, it has some drawbacks:</p>
<ul>
<li>Introduction of a new column in the original table does not automatically involves log modification.</li>
<li>Log modification affects log table and trigger and it is easy to mess up.</li>
<li>State of a record at a specific past time cannot be determined in a straightforward way.</li>
<li>...</li>
</ul>
<p>What other possibilities exist?
What kind of tools can be used to solve this problem?</p>
<p>I only know of <a href="http://log4plsql.sourceforge.net/" rel="noreferrer">log4plsql</a>. What are the pros/cons of this tool?</p>
<p>Edit: Based on Brian's answer I have found the following <a href="http://www.oracle-base.com/articles/10g/Auditing_10gR2.php" rel="noreferrer">reference</a> that explains standard and fine grain auditing.</p>
|
[
{
"answer_id": 196331,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 0,
"selected": false,
"text": "<p>log4plsql is a completely different thing, its for logging debug info from PL/SQL</p>\n\n<p>For what you want, you need to either.</p>\n\n<ol>\n<li>Setup a trigger</li>\n<li>Setup PL/SQL interface around the tables, CRUD operations happen via this interface, the interface ensures the log tables are updated.</li>\n<li>Setup interface in your application layer, as with PL/SQL interface, just higher up.</li>\n<li>Oracle 11g contains versioned tables, I have not used this at all though, so can make no real comment.</li>\n</ol>\n"
},
{
"answer_id": 196454,
"author": "Salamander2007",
"author_id": 10629,
"author_profile": "https://Stackoverflow.com/users/10629",
"pm_score": 2,
"selected": false,
"text": "<p>Judging from your description, I wonder if what you really need is not logging mechanism, but rather some sort of Historical value of some table. If this is the case, then maybe you better off using some kind of Temporal Database design (using VALID_FROM and VALID_TO fields). You can track changes in database using <a href=\"http://download.oracle.com/docs/cd/B19306_01/server.102/b14215/logminer.htm\" rel=\"nofollow noreferrer\">Oracle LogMiner</a> tools.</p>\n\n<p>As for your scenarios, I would rather stored the changes data in this kind of schema :</p>\n\n<pre><code>+----------------------------------------------------------------------------+\n| Column Name | Function |\n+----------------------------------------------------------------------------+\n| Id | PRIMARY_KEY value of the SOURCE table |\n| TimeStamp | Time stamp of the action |\n| User | User who make the action |\n| ActionType | INSERT, UPDATE, or DELETE |\n| OldValues | All fields value from source table, seperated by '|' |\n| Newvalues | All fields value from source table, seperated by '|' |\n+----------------------------------------------------------------------------+\n</code></pre>\n\n<p>With this type of logging table, you can easily determine :</p>\n\n<ul>\n<li>Historical Change action of particular record (using Id)</li>\n<li>State of specific record in some point in time</li>\n</ul>\n\n<p>Of course this kind of logging cannot easily determine all valid values of table in specific point in time. For this, you need to change you table design to <a href=\"http://en.wikipedia.org/wiki/Temporal_database\" rel=\"nofollow noreferrer\">Temporal Database Design</a>.</p>\n"
},
{
"answer_id": 196630,
"author": "Brian",
"author_id": 700,
"author_profile": "https://Stackoverflow.com/users/700",
"pm_score": 4,
"selected": true,
"text": "<p>It sounds like you are after 'auditing'. Oracle has a built-in feature called Fine Grain Auditing (FGA). In a nutshell you can audit everything or specific conditions. What is really cool is you can 'audit' selects as well as transactions. Simple command to get started with auditing:</p>\n\n<pre><code>audit UPDATE on SCOTT.EMP by access;\n</code></pre>\n\n<p>Think of it as a 'trigger' for select statements. For example, you create policies:</p>\n\n<pre><code>begin\n dbms_fga.add_policy (\n object_schema=>'BANK',\n object_name=>'ACCOUNTS',\n policy_name=>'ACCOUNTS_ACCESS'\n );\nend;\n</code></pre>\n\n<p>After you have defined the policy, when a user queries the table in the usual way, as follows:</p>\n\n<pre><code>select * from bank.accounts; \n</code></pre>\n\n<p>the audit trail records this action. You can see the trail by issuing:</p>\n\n<pre><code>select timestamp, \n db_user,\n os_user,\n object_schema,\n object_name,\n sql_text\nfrom dba_fga_audit_trail;\n\nTIMESTAMP DB_USER OS_USER OBJECT_ OBJECT_N SQL_TEXT\n--------- ------- ------- ------- -------- ----------------------\n22-OCT-08 BANK ananda BANK ACCOUNTS select * from accounts\n</code></pre>\n"
},
{
"answer_id": 197392,
"author": "Leigh Riffel",
"author_id": 27010,
"author_profile": "https://Stackoverflow.com/users/27010",
"pm_score": 0,
"selected": false,
"text": "<p>If you just interested in knowing what the data looked like in the recent past you could just use Oracles flashback query functionality to query the data for a specific time in the past. How far in the past is dependent on how much disk space you have and how much database activity there is. The bright side of this solution is that new columns automatically get added. The downside is that you can't flashback query past ddl operations.</p>\n"
},
{
"answer_id": 403185,
"author": "rics",
"author_id": 21047,
"author_profile": "https://Stackoverflow.com/users/21047",
"pm_score": 1,
"selected": false,
"text": "<p>In the similar question (<a href=\"https://stackoverflow.com/questions/67557/how-to-audit-database-activity-without-performance-and-scalability-issues\">How to Audit Database Activity without Performance and Scalability Issues?</a>) the accepted answer mentions the monitoring of database traffic using a network traffic sniffer as an interesting alternative.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21047/"
] |
I am interested in what methods of logging is frequent in an Oracle database.
Our method is the following:
We create a log table for the table to be logged. The log table contains all the columns of the original table plus some special fields including timestamp, modification type (insert, update, delete), modifier's id. A trigger on the original table creates one log row for each insertion and deletion, and two rows for a modification. Log rows contain the data before and after the alteration of the original one.
Although state of the records can be mined back in time using this method, it has some drawbacks:
* Introduction of a new column in the original table does not automatically involves log modification.
* Log modification affects log table and trigger and it is easy to mess up.
* State of a record at a specific past time cannot be determined in a straightforward way.
* ...
What other possibilities exist?
What kind of tools can be used to solve this problem?
I only know of [log4plsql](http://log4plsql.sourceforge.net/). What are the pros/cons of this tool?
Edit: Based on Brian's answer I have found the following [reference](http://www.oracle-base.com/articles/10g/Auditing_10gR2.php) that explains standard and fine grain auditing.
|
It sounds like you are after 'auditing'. Oracle has a built-in feature called Fine Grain Auditing (FGA). In a nutshell you can audit everything or specific conditions. What is really cool is you can 'audit' selects as well as transactions. Simple command to get started with auditing:
```
audit UPDATE on SCOTT.EMP by access;
```
Think of it as a 'trigger' for select statements. For example, you create policies:
```
begin
dbms_fga.add_policy (
object_schema=>'BANK',
object_name=>'ACCOUNTS',
policy_name=>'ACCOUNTS_ACCESS'
);
end;
```
After you have defined the policy, when a user queries the table in the usual way, as follows:
```
select * from bank.accounts;
```
the audit trail records this action. You can see the trail by issuing:
```
select timestamp,
db_user,
os_user,
object_schema,
object_name,
sql_text
from dba_fga_audit_trail;
TIMESTAMP DB_USER OS_USER OBJECT_ OBJECT_N SQL_TEXT
--------- ------- ------- ------- -------- ----------------------
22-OCT-08 BANK ananda BANK ACCOUNTS select * from accounts
```
|
195,437 |
<p>Would it be possible to execute a JSP page and capture its output outside of a web application?
Mode specifically, in my case there still exists a usual web application, but it loads JSP pages not from its classpath, but from an arbitrary source. It seems like I cannot simply get RequestDispatcher and point it to a JSP file on disk. </p>
|
[
{
"answer_id": 195447,
"author": "Rodger Cooley",
"author_id": 5667,
"author_profile": "https://Stackoverflow.com/users/5667",
"pm_score": 0,
"selected": false,
"text": "<p>Correct me if I'm wrong, but I think you mean you want to capture the HTML... not the JSP. A JSP is processed (into a JAVA file) on a servlet-engine (Web app Server) and after the HTML is formatted and served up to the requestor via a Web server (not the same as a web APP server). You can't get the RequestDispatcher to work on a straight JSP from disk because it hasn't been processed yet by the web app server.\nNow, to capture the output of a JSP (in HTML) should be possible, but I've never done that before. There may be some slick APIs that those out there more knowledgable than I can address, but HTTP is typically done on port 80, so I guess one could read/write to port 80 on a TCPIP socket. There's probably some more things to do on top of that, but at least that's some point to start looking into. <br/>\nSorry I can't provide more details, but hell... it's all theory to me at this point.</p>\n"
},
{
"answer_id": 195503,
"author": "Olaf Kock",
"author_id": 13447,
"author_profile": "https://Stackoverflow.com/users/13447",
"pm_score": 2,
"selected": false,
"text": "<p>I think you're better off with a templating engine like velocity. This provides a clean infrastructure for dynamic content that's clearly different from the jsp/servlet stuff that you are asking fore.</p>\n\n<p>That said, I've seen applications that copy jsps into their deployed directory in order for the container to pick them up and translate them. Should you do this, please note that this limits your future options:</p>\n\n<ul>\n<li>you rely upon your application to be \"exploded\" - e.g. it can't run directly out of a WAR archive (this might limit your deployment options)</li>\n<li>making jsps editable at runtime might open up security holes if you don't disable scriptlets (also if you do disable, but it'll be somewhat harder...). Disabling scriptlets prohibits real Java code in the jsps, you're limited to tag libraries then. </li>\n<li>You'll need a Java compiler available at runtime, which you might not want to have in production systems - e.g. you cannot precompile your jsps before deployment. Also you pay the usual jsp-translation-penalty at runtime in your productive system.</li>\n</ul>\n\n<p>web.xml configuration for disabling scripting:</p>\n\n<pre><code><jsp-config>\n <jsp-property-group>\n <url-pattern>*.jsp</url-pattern>\n <scripting-invalid>true</scripting-invalid>\n </jsp-property-group>\n</jsp-config>\n</code></pre>\n\n<p>I hope this web.xml snippet went through, the preview didn't show it correctly...</p>\n\n<p><em>Update</em>: Tried to make xml-snippet display correctly.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6954/"
] |
Would it be possible to execute a JSP page and capture its output outside of a web application?
Mode specifically, in my case there still exists a usual web application, but it loads JSP pages not from its classpath, but from an arbitrary source. It seems like I cannot simply get RequestDispatcher and point it to a JSP file on disk.
|
I think you're better off with a templating engine like velocity. This provides a clean infrastructure for dynamic content that's clearly different from the jsp/servlet stuff that you are asking fore.
That said, I've seen applications that copy jsps into their deployed directory in order for the container to pick them up and translate them. Should you do this, please note that this limits your future options:
* you rely upon your application to be "exploded" - e.g. it can't run directly out of a WAR archive (this might limit your deployment options)
* making jsps editable at runtime might open up security holes if you don't disable scriptlets (also if you do disable, but it'll be somewhat harder...). Disabling scriptlets prohibits real Java code in the jsps, you're limited to tag libraries then.
* You'll need a Java compiler available at runtime, which you might not want to have in production systems - e.g. you cannot precompile your jsps before deployment. Also you pay the usual jsp-translation-penalty at runtime in your productive system.
web.xml configuration for disabling scripting:
```
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<scripting-invalid>true</scripting-invalid>
</jsp-property-group>
</jsp-config>
```
I hope this web.xml snippet went through, the preview didn't show it correctly...
*Update*: Tried to make xml-snippet display correctly.
|
195,451 |
<p>I use <code>public boolean mouseDown(Event ev, int x, int y)</code> to detect a click of the mouse.<br>
I can distinguish between the right mouse button (ev.metaDown() is true) and the left and middle.</p>
<p>How can i differentiate the left from the middle button?
Or if it is impossible with mouseDown, what should i use?</p>
|
[
{
"answer_id": 195459,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>This might do it:</p>\n\n<p><a href=\"http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/SwingUtilities.html#isMiddleMouseButton(java.awt.event.MouseEvent)\" rel=\"nofollow noreferrer\">http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/SwingUtilities.html#isMiddleMouseButton(java.awt.event.MouseEvent)</a></p>\n\n<p>Haven't tried it myself.</p>\n"
},
{
"answer_id": 195469,
"author": "PW.",
"author_id": 927,
"author_profile": "https://Stackoverflow.com/users/927",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://docs.oracle.com/javase/7/docs/api/java/awt/Component.html#mouseDown%28java.awt.Event,%20int,%20int%29\" rel=\"nofollow noreferrer\">mouseDown</a> is deprecated. All you need is accessible by the MouseEvent.<a href=\"http://java.sun.com/javase/6/docs/api/java/awt/event/MouseEvent.html#getButton()\" rel=\"nofollow noreferrer\">getButton</a>. Track BUTTON3. </p>\n"
},
{
"answer_id": 270373,
"author": "Michael Myers",
"author_id": 13531,
"author_profile": "https://Stackoverflow.com/users/13531",
"pm_score": 2,
"selected": true,
"text": "<p>Try using <a href=\"http://java.sun.com/javase/6/docs/api/java/awt/Event.html#ALT_MASK\" rel=\"nofollow noreferrer\">ALT_MASK</a>:</p>\n\n<blockquote>\n <p>This flag indicates that the Alt key was down when the event occurred. For mouse events, this flag indicates that the middle mouse button was pressed or released.</p>\n</blockquote>\n\n<p>So your code might be:</p>\n\n<pre><code>if (ev.modifiers & Event.ALT_MASK != 0) {\n // middle button was pressed\n}\n</code></pre>\n\n<p>Of course, all this is assuming you have a <em>very</em> good reason to use mouseDown in the first place, since it is deprecated. You should (probably) be using <a href=\"http://java.sun.com/javase/6/docs/api/java/awt/Component.html#processMouseEvent(java.awt.event.MouseEvent)\" rel=\"nofollow noreferrer\">processMouseEvent</a> instead, which gives you a MouseEvent to play with.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12860/"
] |
I use `public boolean mouseDown(Event ev, int x, int y)` to detect a click of the mouse.
I can distinguish between the right mouse button (ev.metaDown() is true) and the left and middle.
How can i differentiate the left from the middle button?
Or if it is impossible with mouseDown, what should i use?
|
Try using [ALT\_MASK](http://java.sun.com/javase/6/docs/api/java/awt/Event.html#ALT_MASK):
>
> This flag indicates that the Alt key was down when the event occurred. For mouse events, this flag indicates that the middle mouse button was pressed or released.
>
>
>
So your code might be:
```
if (ev.modifiers & Event.ALT_MASK != 0) {
// middle button was pressed
}
```
Of course, all this is assuming you have a *very* good reason to use mouseDown in the first place, since it is deprecated. You should (probably) be using [processMouseEvent](http://java.sun.com/javase/6/docs/api/java/awt/Component.html#processMouseEvent(java.awt.event.MouseEvent)) instead, which gives you a MouseEvent to play with.
|
195,454 |
<p>How can I <strong>protect a ClickOnce deployed application with a password</strong>? Do I have to change the IIS settings of the web or is there a way to do it programmatically? I'm using Visual Studio 2005 (.NET 2.0).</p>
<p>If I have to use web credentials, are auto-updates of the application still possible?</p>
<p>Would be great if you could provide some sample code or detailed instructions for administering IIS.</p>
<p>Thank you! </p>
|
[
{
"answer_id": 195471,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure it can be done. I may be wrong, but I didn't think that would work. Apart from anything else, even if your user puts in their credentials to get the .application, the runtime then does separate downloading, for which it needs anonymous access.</p>\n\n<p>If you want to protect the client so much, you may have to come up with a different way of deploying it.</p>\n"
},
{
"answer_id": 196846,
"author": "Aaron Axvig",
"author_id": 26732,
"author_profile": "https://Stackoverflow.com/users/26732",
"pm_score": 0,
"selected": false,
"text": "<p>A ClickOnce installer is just a couple installer files sitting out on your web server, right? So then, you can just implement some sort of directory security on those files. You can do this on a couple different levels I believe; for example IIS permissions or (if your users are on your domain) NTFS permissions.</p>\n\n<p>Also, IIS permissions (everything actually?) should be able to be setup programatically.</p>\n"
},
{
"answer_id": 215100,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 5,
"selected": true,
"text": "<p>I found a possible solution by myself in this MSDN article: <a href=\"http://msdn.microsoft.com/en-us/library/76e4d2xw.aspx\" rel=\"noreferrer\">ClickOnce Deployment and Security</a>.</p>\n\n<h2>ASP.NET Form-Based Authentication</h2>\n\n<p>If you want to control which deployments each user can access, you should <strong>not enable anonymous access</strong> to ClickOnce applications deployed on a Web server. Rather, you would enable users access to the deployments you have installed based on a user's identity (using Windows NT authentication).</p>\n\n<p>If you deploy to an environment without Windows NT authentication, a solution could be to try using <strong>ASP.NET form-based authentication</strong> to authenticate the user. However, ClickOnce does not support forms-based authentication because it uses persistent cookies; these present a security risk because they reside in the Internet Explorer cache and can be hacked. Therefore, if you are deploying ClickOnce applications, any authentication scenario besides Windows NT authentication is unsupported.</p>\n\n<h2>Passing Arguments</h2>\n\n<p>An additional security consideration occurs if you have to pass arguments into a ClickOnce application. ClickOnce enables developers to supply a query string to applications deployed over the Web. The query string takes the form of a series of name-value pairs at the end of the URL used to start the application:</p>\n\n<pre><code>http://servername.adatum.com/WindowsApp1.application?username=joeuser\n</code></pre>\n\n<p>By default, query-string arguments are disabled. To enable them, the attribute <strong>trustUrlParameters must be set in the application's deployment manifest</strong>. This value can be set from Visual Studio and from MageUI.exe. For detailed steps on how to enable passing query strings, see How to: Retrieve Query String Information in a ClickOnce Application.</p>\n\n<p>You should never pass arguments retrieved through a query string to a database or to the command line without checking the arguments to make sure that they are safe. Unsafe arguments are ones that include database or command line escape characters that could allow a malicious user to manipulate your application into executing arbitrary commands. </p>\n\n<p><em>Note: Query-string arguments are the only way to pass arguments to a ClickOnce application at startup. You cannot pass arguments to a ClickOnce application from the command line.</em> </p>\n"
},
{
"answer_id": 2916365,
"author": "Bob Wintemberg",
"author_id": 12999,
"author_profile": "https://Stackoverflow.com/users/12999",
"pm_score": 1,
"selected": false,
"text": "<p>The only solution I've ever seen is here: <a href=\"http://www.codeproject.com/KB/web-security/ClickOnceFormsAuth.aspx\" rel=\"nofollow noreferrer\">Click Once Forms Auth</a></p>\n\n<p>We've run into the same problem with trying to secure an application. The one problem with the solution above that I've noticed is that the cookie information is in the URL, which means if someone theoretically intercepted the URL, they could use it to also download the application. Other than that, it seems like a viable solution.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6461/"
] |
How can I **protect a ClickOnce deployed application with a password**? Do I have to change the IIS settings of the web or is there a way to do it programmatically? I'm using Visual Studio 2005 (.NET 2.0).
If I have to use web credentials, are auto-updates of the application still possible?
Would be great if you could provide some sample code or detailed instructions for administering IIS.
Thank you!
|
I found a possible solution by myself in this MSDN article: [ClickOnce Deployment and Security](http://msdn.microsoft.com/en-us/library/76e4d2xw.aspx).
ASP.NET Form-Based Authentication
---------------------------------
If you want to control which deployments each user can access, you should **not enable anonymous access** to ClickOnce applications deployed on a Web server. Rather, you would enable users access to the deployments you have installed based on a user's identity (using Windows NT authentication).
If you deploy to an environment without Windows NT authentication, a solution could be to try using **ASP.NET form-based authentication** to authenticate the user. However, ClickOnce does not support forms-based authentication because it uses persistent cookies; these present a security risk because they reside in the Internet Explorer cache and can be hacked. Therefore, if you are deploying ClickOnce applications, any authentication scenario besides Windows NT authentication is unsupported.
Passing Arguments
-----------------
An additional security consideration occurs if you have to pass arguments into a ClickOnce application. ClickOnce enables developers to supply a query string to applications deployed over the Web. The query string takes the form of a series of name-value pairs at the end of the URL used to start the application:
```
http://servername.adatum.com/WindowsApp1.application?username=joeuser
```
By default, query-string arguments are disabled. To enable them, the attribute **trustUrlParameters must be set in the application's deployment manifest**. This value can be set from Visual Studio and from MageUI.exe. For detailed steps on how to enable passing query strings, see How to: Retrieve Query String Information in a ClickOnce Application.
You should never pass arguments retrieved through a query string to a database or to the command line without checking the arguments to make sure that they are safe. Unsafe arguments are ones that include database or command line escape characters that could allow a malicious user to manipulate your application into executing arbitrary commands.
*Note: Query-string arguments are the only way to pass arguments to a ClickOnce application at startup. You cannot pass arguments to a ClickOnce application from the command line.*
|
195,455 |
<p>I am writing a compiler in F# and I want to be able to access the <a href="http://msdn.microsoft.com/en-us/library/ms404384.aspx" rel="nofollow noreferrer">unmanaged metadata COM interfaces</a> in the .net runtime. Before anybody mentions it, <em>Reflection.Emit is not suitable for my purposes</em>, nor do I want to use any other method than the metadata COM interfaces.</p>
<p>I've imported mscoree.tlb but it doesn't seem to include the interfaces I need.</p>
<p>The interfaces I'm interested in include <a href="http://msdn.microsoft.com/en-us/library/ms230877.aspx" rel="nofollow noreferrer">IMetaDataEmit</a>. Any sample code relating to this would be very useful, though I've not been able to find any so far.</p>
<p>C# samples would be fine as I can easily convert them to F#.</p>
<p>Thanks in advance to anybody who can help me with this rather cryptic query!</p>
<p><strong>Update:</strong> I have now got this sorted by writing explicit COM references using the interface GUIDs!</p>
|
[
{
"answer_id": 195471,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure it can be done. I may be wrong, but I didn't think that would work. Apart from anything else, even if your user puts in their credentials to get the .application, the runtime then does separate downloading, for which it needs anonymous access.</p>\n\n<p>If you want to protect the client so much, you may have to come up with a different way of deploying it.</p>\n"
},
{
"answer_id": 196846,
"author": "Aaron Axvig",
"author_id": 26732,
"author_profile": "https://Stackoverflow.com/users/26732",
"pm_score": 0,
"selected": false,
"text": "<p>A ClickOnce installer is just a couple installer files sitting out on your web server, right? So then, you can just implement some sort of directory security on those files. You can do this on a couple different levels I believe; for example IIS permissions or (if your users are on your domain) NTFS permissions.</p>\n\n<p>Also, IIS permissions (everything actually?) should be able to be setup programatically.</p>\n"
},
{
"answer_id": 215100,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 5,
"selected": true,
"text": "<p>I found a possible solution by myself in this MSDN article: <a href=\"http://msdn.microsoft.com/en-us/library/76e4d2xw.aspx\" rel=\"noreferrer\">ClickOnce Deployment and Security</a>.</p>\n\n<h2>ASP.NET Form-Based Authentication</h2>\n\n<p>If you want to control which deployments each user can access, you should <strong>not enable anonymous access</strong> to ClickOnce applications deployed on a Web server. Rather, you would enable users access to the deployments you have installed based on a user's identity (using Windows NT authentication).</p>\n\n<p>If you deploy to an environment without Windows NT authentication, a solution could be to try using <strong>ASP.NET form-based authentication</strong> to authenticate the user. However, ClickOnce does not support forms-based authentication because it uses persistent cookies; these present a security risk because they reside in the Internet Explorer cache and can be hacked. Therefore, if you are deploying ClickOnce applications, any authentication scenario besides Windows NT authentication is unsupported.</p>\n\n<h2>Passing Arguments</h2>\n\n<p>An additional security consideration occurs if you have to pass arguments into a ClickOnce application. ClickOnce enables developers to supply a query string to applications deployed over the Web. The query string takes the form of a series of name-value pairs at the end of the URL used to start the application:</p>\n\n<pre><code>http://servername.adatum.com/WindowsApp1.application?username=joeuser\n</code></pre>\n\n<p>By default, query-string arguments are disabled. To enable them, the attribute <strong>trustUrlParameters must be set in the application's deployment manifest</strong>. This value can be set from Visual Studio and from MageUI.exe. For detailed steps on how to enable passing query strings, see How to: Retrieve Query String Information in a ClickOnce Application.</p>\n\n<p>You should never pass arguments retrieved through a query string to a database or to the command line without checking the arguments to make sure that they are safe. Unsafe arguments are ones that include database or command line escape characters that could allow a malicious user to manipulate your application into executing arbitrary commands. </p>\n\n<p><em>Note: Query-string arguments are the only way to pass arguments to a ClickOnce application at startup. You cannot pass arguments to a ClickOnce application from the command line.</em> </p>\n"
},
{
"answer_id": 2916365,
"author": "Bob Wintemberg",
"author_id": 12999,
"author_profile": "https://Stackoverflow.com/users/12999",
"pm_score": 1,
"selected": false,
"text": "<p>The only solution I've ever seen is here: <a href=\"http://www.codeproject.com/KB/web-security/ClickOnceFormsAuth.aspx\" rel=\"nofollow noreferrer\">Click Once Forms Auth</a></p>\n\n<p>We've run into the same problem with trying to secure an application. The one problem with the solution above that I've noticed is that the cookie information is in the URL, which means if someone theoretically intercepted the URL, they could use it to also download the application. Other than that, it seems like a viable solution.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
] |
I am writing a compiler in F# and I want to be able to access the [unmanaged metadata COM interfaces](http://msdn.microsoft.com/en-us/library/ms404384.aspx) in the .net runtime. Before anybody mentions it, *Reflection.Emit is not suitable for my purposes*, nor do I want to use any other method than the metadata COM interfaces.
I've imported mscoree.tlb but it doesn't seem to include the interfaces I need.
The interfaces I'm interested in include [IMetaDataEmit](http://msdn.microsoft.com/en-us/library/ms230877.aspx). Any sample code relating to this would be very useful, though I've not been able to find any so far.
C# samples would be fine as I can easily convert them to F#.
Thanks in advance to anybody who can help me with this rather cryptic query!
**Update:** I have now got this sorted by writing explicit COM references using the interface GUIDs!
|
I found a possible solution by myself in this MSDN article: [ClickOnce Deployment and Security](http://msdn.microsoft.com/en-us/library/76e4d2xw.aspx).
ASP.NET Form-Based Authentication
---------------------------------
If you want to control which deployments each user can access, you should **not enable anonymous access** to ClickOnce applications deployed on a Web server. Rather, you would enable users access to the deployments you have installed based on a user's identity (using Windows NT authentication).
If you deploy to an environment without Windows NT authentication, a solution could be to try using **ASP.NET form-based authentication** to authenticate the user. However, ClickOnce does not support forms-based authentication because it uses persistent cookies; these present a security risk because they reside in the Internet Explorer cache and can be hacked. Therefore, if you are deploying ClickOnce applications, any authentication scenario besides Windows NT authentication is unsupported.
Passing Arguments
-----------------
An additional security consideration occurs if you have to pass arguments into a ClickOnce application. ClickOnce enables developers to supply a query string to applications deployed over the Web. The query string takes the form of a series of name-value pairs at the end of the URL used to start the application:
```
http://servername.adatum.com/WindowsApp1.application?username=joeuser
```
By default, query-string arguments are disabled. To enable them, the attribute **trustUrlParameters must be set in the application's deployment manifest**. This value can be set from Visual Studio and from MageUI.exe. For detailed steps on how to enable passing query strings, see How to: Retrieve Query String Information in a ClickOnce Application.
You should never pass arguments retrieved through a query string to a database or to the command line without checking the arguments to make sure that they are safe. Unsafe arguments are ones that include database or command line escape characters that could allow a malicious user to manipulate your application into executing arbitrary commands.
*Note: Query-string arguments are the only way to pass arguments to a ClickOnce application at startup. You cannot pass arguments to a ClickOnce application from the command line.*
|
195,468 |
<p>Basically, I have a class with 2 methods: one to serialize an object into an XML file and another to read an object from XML.
Here is an example of synchronized part from the method that restores an object:</p>
<pre><code> public T restore(String from) throws Exception {
// variables declaration
synchronized (from) {
try {
decoder = new XMLDecoder(new BufferedInputStream(
new FileInputStream(from)));
restoredItem = decoder.readObject();
decoder.close();
} catch (Exception e) {
logger.warning("file not found or smth: " + from);
throw new Exception(e);
}
}
// try to cast it
}
</code></pre>
<p>A similar approach is taken when serializing an object. Now, when I create a unit test which in turn creates 10 threads with each thread trying to serialize and instantly read either a Boolean or a String it would fail showing that ClassCastExceptions occur. This makes me think that I get serialization wrong (everything's ok in a single-threaded environment). If you've stayed with me down to this point :), here are the 2 issues I need your help on:</p>
<ol>
<li>does it make sense to synchronize on a string argument passed to method (considering there's a string pool in java)? BTW, I've tried synchronizing on the XMLSerializer class itself with result staying the same.</li>
<li>how do i correctly synchronize io operations on a single file?</li>
</ol>
|
[
{
"answer_id": 195474,
"author": "Itay Maman",
"author_id": 27198,
"author_profile": "https://Stackoverflow.com/users/27198",
"pm_score": 2,
"selected": false,
"text": "<p>Given that the some parts of your code are missing, my bet is that the problem lies with synchronizing on a string. You cannot freely assume that strings are pooled (which would break your synchronization scheme). </p>\n\n<p>The best approach would be to add a map that will associate a key (string) with its actual synchronization object. </p>\n\n<p>Other than that, I would suggest to play with the multi-threaded test to see what make it fail. For example, if you make all threads only store string values (rather than strings or beooleans), does the test still fail?</p>\n"
},
{
"answer_id": 195533,
"author": "Dave Cheney",
"author_id": 6449,
"author_profile": "https://Stackoverflow.com/users/6449",
"pm_score": 2,
"selected": false,
"text": "<p>There are a number of problems with this approach. </p>\n\n<ol>\n<li><p>Unless you've called String.intern then your from string is probably not the same from as the other one you are calling. Relying on the behaviour of the internal java string cache is not very robust.</p></li>\n<li><p>you aren't properly disposing of your XMLDecoder in a finally block, any exception thrown during that call will leak the file description associated with that FileInputStream.</p></li>\n<li><p>You don't need to wrap e in another Exception(e), you can just throw e as you have declared the enclosing method also throws Exception</p></li>\n<li><p>Catching/Throwing exception is a code smell. Yes, it is a super class of IOException, and whatever XML decoding exception might be thrown, but its also a superclass of a bunch of other things you probably didn't want to catch, NullPointerException for instance.</p></li>\n</ol>\n\n<p>To answer your question, how can you serialize access to a shared file to ensure its not being used by more than one thread, is tricky. FileChannel.lock() doesn't work inside the JVM, they just lock the file from modification by other processes in the machine.</p>\n\n<p>My approach would be to strip any locking out of this class and wrap it in something that is aware of the threading issues of your code.</p>\n\n<p>I'd also not pass a String as the filename, but a File, which gives you the ability to use File.createTempFile(2) to create opaque filenames between the thing writing xml and the thing reading xml.</p>\n\n<p>Finally, do you want to synchronise access to a shared file, or fail when you detect multiple access to the same file? </p>\n"
},
{
"answer_id": 195706,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 2,
"selected": false,
"text": "<p>A String does not good make a good mutex, but can be used to create one: <a href=\"http://illegalargumentexception.blogspot.com/2008/04/java-synchronizing-on-transient-id.html\" rel=\"nofollow noreferrer\">Java: synchronizing on an ID</a>.</p>\n"
},
{
"answer_id": 195796,
"author": "Ran Biron",
"author_id": 931,
"author_profile": "https://Stackoverflow.com/users/931",
"pm_score": 4,
"selected": true,
"text": "<p>1.\nYes, it's OK to synchronize on a String, however you'd need to synchronize on the string.<a href=\"http://java.sun.com/javase/6/docs/api/java/lang/String.html#intern()\" rel=\"noreferrer\">intern()</a> in order to always get the same Object</p>\n\n<pre><code>StringBuffer sb = new StringBuffer(); sb.append(\"a\").append(\"b\");\nString a = new String(sb.toString());\nString b = new String(sb.toString());\na == b; //false\na.equals(b); //true\na.intern() == b.intern(); //true\n</code></pre>\n\n<p>Since you want to synchronize on the same monitor, you'd want the intern().</p>\n\n<p>2.\nYou'd probably not want to synchronize on a String since it may synchronized on somewhere else, inside your code, in 3rd party or in the JRE. What I'd do, if I wanted to stay with synchronize, is create an ID class (which may hold only String), override equals() and hashcode() to match, put it in a WeakHashMap with both as key and value (see IdentityHashMap for idea why) and use only what I .get() from the map (sync map{ syncKey = map.get(new ID(from)); if syncKey==null create and put new key} sync{syncKey}).</p>\n\n<p>3.\nThen again, I'd ditch synchronize all together and use the java.util.concurrent.locks.Lock instead, in the same setup as above only with the lock attached to the ID.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15187/"
] |
Basically, I have a class with 2 methods: one to serialize an object into an XML file and another to read an object from XML.
Here is an example of synchronized part from the method that restores an object:
```
public T restore(String from) throws Exception {
// variables declaration
synchronized (from) {
try {
decoder = new XMLDecoder(new BufferedInputStream(
new FileInputStream(from)));
restoredItem = decoder.readObject();
decoder.close();
} catch (Exception e) {
logger.warning("file not found or smth: " + from);
throw new Exception(e);
}
}
// try to cast it
}
```
A similar approach is taken when serializing an object. Now, when I create a unit test which in turn creates 10 threads with each thread trying to serialize and instantly read either a Boolean or a String it would fail showing that ClassCastExceptions occur. This makes me think that I get serialization wrong (everything's ok in a single-threaded environment). If you've stayed with me down to this point :), here are the 2 issues I need your help on:
1. does it make sense to synchronize on a string argument passed to method (considering there's a string pool in java)? BTW, I've tried synchronizing on the XMLSerializer class itself with result staying the same.
2. how do i correctly synchronize io operations on a single file?
|
1.
Yes, it's OK to synchronize on a String, however you'd need to synchronize on the string.[intern()](http://java.sun.com/javase/6/docs/api/java/lang/String.html#intern()) in order to always get the same Object
```
StringBuffer sb = new StringBuffer(); sb.append("a").append("b");
String a = new String(sb.toString());
String b = new String(sb.toString());
a == b; //false
a.equals(b); //true
a.intern() == b.intern(); //true
```
Since you want to synchronize on the same monitor, you'd want the intern().
2.
You'd probably not want to synchronize on a String since it may synchronized on somewhere else, inside your code, in 3rd party or in the JRE. What I'd do, if I wanted to stay with synchronize, is create an ID class (which may hold only String), override equals() and hashcode() to match, put it in a WeakHashMap with both as key and value (see IdentityHashMap for idea why) and use only what I .get() from the map (sync map{ syncKey = map.get(new ID(from)); if syncKey==null create and put new key} sync{syncKey}).
3.
Then again, I'd ditch synchronize all together and use the java.util.concurrent.locks.Lock instead, in the same setup as above only with the lock attached to the ID.
|
195,483 |
<p>Is there an easy way of programmatically checking if a serial COM port is already open/being used?</p>
<p>Normally I would use:</p>
<pre><code>try
{
// open port
}
catch (Exception ex)
{
// handle the exception
}
</code></pre>
<p>However, I would like to programatically check so I can attempt to use another COM port or some such.</p>
|
[
{
"answer_id": 195493,
"author": "Fionn",
"author_id": 21566,
"author_profile": "https://Stackoverflow.com/users/21566",
"pm_score": 5,
"selected": true,
"text": "<p>I needed something similar some time ago, to search for a device.</p>\n\n<p>I obtained a list of available COM ports and then simply iterated over them, if it didn't throw an exception i tried to communicate with the device. A bit rough but working.</p>\n\n<pre><code>var portNames = SerialPort.GetPortNames();\n\nforeach(var port in portNames) {\n //Try for every portName and break on the first working\n}\n</code></pre>\n"
},
{
"answer_id": 195494,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 0,
"selected": false,
"text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.aspx\" rel=\"nofollow noreferrer\">SerialPort class</a> has an <a href=\"http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.open.aspx\" rel=\"nofollow noreferrer\"><em>Open</em></a> method, which will throw a few exceptions.\nThe reference above contains detailed examples.</p>\n\n<p>See also, the <a href=\"http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.isopen.aspx\" rel=\"nofollow noreferrer\">IsOpen</a> property.</p>\n\n<p>A simple test:</p>\n\n<pre><code>using System;\nusing System.IO.Ports;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace SerPort1\n{\nclass Program\n{\n static private SerialPort MyPort;\n static void Main(string[] args)\n {\n MyPort = new SerialPort(\"COM1\");\n OpenMyPort();\n Console.WriteLine(\"BaudRate {0}\", MyPort.BaudRate);\n OpenMyPort();\n MyPort.Close();\n Console.ReadLine();\n }\n\n private static void OpenMyPort()\n {\n try\n {\n MyPort.Open();\n }\n catch (Exception ex)\n {\n Console.WriteLine(\"Error opening my port: {0}\", ex.Message);\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 327593,
"author": "Funky81",
"author_id": 37509,
"author_profile": "https://Stackoverflow.com/users/37509",
"pm_score": -1,
"selected": false,
"text": "<p>You can try folloing code to check whether a port already open or not. I'm assumming you dont know specificaly which port you want to check.</p>\n\n<pre><code>foreach (var portName in Serial.GetPortNames()\n{\n SerialPort port = new SerialPort(portName);\n if (port.IsOpen){\n /** do something **/\n }\n else {\n /** do something **/\n }\n}\n</code></pre>\n"
},
{
"answer_id": 5052499,
"author": "Jeff",
"author_id": 303284,
"author_profile": "https://Stackoverflow.com/users/303284",
"pm_score": 4,
"selected": false,
"text": "<p>This is how I did it:</p>\n\n<pre><code> [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n internal static extern SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, int dwShareMode, IntPtr securityAttrs, int dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);\n</code></pre>\n\n<p>then later on</p>\n\n<pre><code> int dwFlagsAndAttributes = 0x40000000;\n\n var portName = \"COM5\";\n\n var isValid = SerialPort.GetPortNames().Any(x => string.Compare(x, portName, true) == 0);\n if (!isValid)\n throw new System.IO.IOException(string.Format(\"{0} port was not found\", portName));\n\n //Borrowed from Microsoft's Serial Port Open Method :)\n SafeFileHandle hFile = CreateFile(@\"\\\\.\\\" + portName, -1073741824, 0, IntPtr.Zero, 3, dwFlagsAndAttributes, IntPtr.Zero);\n if (hFile.IsInvalid)\n throw new System.IO.IOException(string.Format(\"{0} port is already open\", portName));\n\n hFile.Close();\n\n\n using (var serialPort = new SerialPort(portName, 115200, Parity.None, 8, StopBits.One))\n {\n serialPort.Open();\n }\n</code></pre>\n"
},
{
"answer_id": 59880011,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Sharing what worked for me (a simple helper method):</p>\n\n<pre><code>private string portName { get; set; } = string.Empty;\n\n /// <summary>\n /// Returns SerialPort Port State (Open / Closed)\n /// </summary>\n /// <returns></returns>\n internal bool HasOpenPort()\n {\n bool portState = false;\n\n if (portName != string.Empty)\n {\n using (SerialPort serialPort = new SerialPort(portName))\n {\n foreach (var itm in SerialPort.GetPortNames())\n {\n if (itm.Contains(serialPort.PortName))\n {\n if (serialPort.IsOpen) { portState = true; }\n else { portState = false; }\n }\n }\n }\n }\n\n else { System.Windows.Forms.MessageBox.Show(\"Error: No Port Specified.\"); }\n\n return portState;\n}\n</code></pre>\n\n<p><br><strong>Notes:</strong>\n<br>- For more advanced technique(s) I recommend using <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.management.managementobjectsearcher?view=netframework-4.8\" rel=\"nofollow noreferrer\">ManagementObjectSearcher Class</a>.\n<br> More info <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.management.managementobjectsearcher?view=netframework-4.8\" rel=\"nofollow noreferrer\">Here</a>.\n<br>- For Arduino devices I would leave the Port Open.\n<br>- Recommend using a Try Catch block if you need to catch exceptions.\n<br>- Check also: \"TimeoutException\"\n<br>- More information on how to get SerialPort (Open) Exceptions <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.io.ports.serialport.open?view=netframework-4.7.2\" rel=\"nofollow noreferrer\">Here</a>.</p>\n"
},
{
"answer_id": 60986566,
"author": "Farrukh Azad",
"author_id": 11632237,
"author_profile": "https://Stackoverflow.com/users/11632237",
"pm_score": 0,
"selected": false,
"text": "<pre><code> public void MobileMessages(string ComNo, string MobileMessage, string MobileNo)\n {\n if (SerialPort.IsOpen )\n SerialPort.Close();\n try\n {\n SerialPort.PortName = ComNo;\n SerialPort.BaudRate = 9600;\n SerialPort.Parity = Parity.None;\n SerialPort.StopBits = StopBits.One;\n SerialPort.DataBits = 8;\n SerialPort.Handshake = Handshake.RequestToSend;\n SerialPort.DtrEnable = true;\n SerialPort.RtsEnable = true;\n SerialPort.NewLine = Constants.vbCrLf;\n string message;\n message = MobileMessage;\n\n SerialPort.Open();\n if (SerialPort.IsOpen )\n {\n SerialPort.Write(\"AT\" + Constants.vbCrLf);\n SerialPort.Write(\"AT+CMGF=1\" + Constants.vbCrLf);\n SerialPort.Write(\"AT+CMGS=\" + Strings.Chr(34) + MobileNo + Strings.Chr(34) + Constants.vbCrLf);\n SerialPort.Write(message + Strings.Chr(26));\n }\n else\n (\"Port not available\");\n SerialPort.Close();\n System.Threading.Thread.Sleep(5000);\n }\n catch (Exception ex)\n {\n\n message.show(\"The port \" + ComNo + \" does not exist, change port no \");\n }\n }\n</code></pre>\n"
},
{
"answer_id": 63306698,
"author": "Tono Nam",
"author_id": 637142,
"author_profile": "https://Stackoverflow.com/users/637142",
"pm_score": 1,
"selected": false,
"text": "<p>For people that cannot use <code>SerialPort.GetPortNames();</code> because they are not targeting <code>.net framework</code> (like in my case I am using .Net Core and NOT .Net Framework) here is what I ended up doing:</p>\n<p>In command prompt if you type mode you get something like this:</p>\n<p><a href=\"https://i.stack.imgur.com/sE7VW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/sE7VW.png\" alt=\"enter image description here\" /></a></p>\n<p>mode is an executable located at <code>C:\\Windows\\System32\\mode.com</code>. Just parse the results of that executable with a regex like this:</p>\n<pre><code>// Code that answers the question\n\nvar proc = new Process\n{\n StartInfo = new ProcessStartInfo\n {\n FileName = @"C:\\Windows\\System32\\mode.com",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n CreateNoWindow = true\n }\n};\n\nproc.Start();\nproc.WaitForExit(4000); // wait up to 4 seconds. It usually takes less than a second\n\n// get ports being used\nvar output = proc.StandardOutput.ReadToEnd();\n</code></pre>\n<p>Now if you want to parse the output this is how I do it:</p>\n<pre><code>List<string> comPortsBeingUsed = new List<string>();\nRegex.Replace(output, @"(?xi) status [\\s\\w]+? (COM\\d) \\b ", regexCapture =>\n{\n comPortsBeingUsed.Add(regexCapture.Groups[1].Value);\n return null;\n});\n\nforeach(var item in comPortsBeingUsed)\n{\n Console.WriteLine($"COM port {item} is in use");\n}\n</code></pre>\n"
},
{
"answer_id": 66330471,
"author": "Jack",
"author_id": 10155902,
"author_profile": "https://Stackoverflow.com/users/10155902",
"pm_score": 1,
"selected": false,
"text": "<p>I wanted to open the next available port and did it like this.\nPlease note, is it not for WPF but for Windows Forms.\nI populated a combobox with the com ports available.\nThen I try to open the first one. If it fails, I select the next available item from the combobox. If the selected index did not change in the end, there were no alternate com ports available and we show a message.</p>\n<pre><code>private void GetPortNames()\n{\n comboBoxComPort.Items.Clear();\n foreach (string s in SerialPort.GetPortNames())\n {\n comboBoxComPort.Items.Add(s);\n }\n comboBoxComPort.SelectedIndex = 0;\n}\n\nprivate void OpenSerialPort()\n{\n try\n {\n serialPort1.PortName = comboBoxComPort.SelectedItem.ToString();\n serialPort1.Open();\n }\n catch (Exception ex)\n {\n int SelectedIndex = comboBoxComPort.SelectedIndex;\n if (comboBoxComPort.SelectedIndex >= comboBoxComPort.Items.Count - 1)\n {\n comboBoxComPort.SelectedIndex = 0;\n }\n else\n {\n comboBoxComPort.SelectedIndex++;\n }\n if (comboBoxComPort.SelectedIndex == SelectedIndex)\n {\n buttonOpenClose.Text = "Open Port";\n MessageBox.Show("Error accessing port." + Environment.NewLine + ex.Message, "Port Error!!!", MessageBoxButtons.OK);\n }\n else\n {\n OpenSerialPort();\n }\n }\n\n if (serialPort1.IsOpen)\n {\n StartAsyncSerialReading();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 71442239,
"author": "Mike",
"author_id": 608583,
"author_profile": "https://Stackoverflow.com/users/608583",
"pm_score": 0,
"selected": false,
"text": "<p>I have been fighting with this problem for a few weeks now. Thanks to the suggestions on here and from the site, <a href=\"https://www.dreamincode.net/forums/topic/91090-c%23-serial-port-unauthorizedaccessexception/\" rel=\"nofollow noreferrer\">https://www.dreamincode.net/forums/topic/91090-c%23-serial-port-unauthorizedaccessexception/</a> .</p>\n<p>I finally came up with a solution that seems to work.</p>\n<p>The application I am working on allows a user to connect to a USB device and display data from it.</p>\n<p><strong>The Problem I was battling.</strong> Along side the application I am writing, I use another serial terminal application for doing my testing. Sometimes I forget to disconnect the COMport being used on the other application. If I do, and try to connect with the application I am writing, I would get an “UnAuthorizedAccessException” error. Along with this exception came some side effects, such as double lines of data being spit out and the application locking up on closing down.</p>\n<p><strong>My Solution</strong></p>\n<p>Thanks to the advice on here and the other site referenced, this was my solution.</p>\n<pre><code> private void checkAndFillPortNameList()\n {\n SerialPort _testingSerialPort;\n\n\n AvailablePortNamesFound.Clear();\n List<string> availablePortNames = new List<string>();//mySerial.GetAvailablePortNames();\n\n foreach (string portName in SerialPortDataAccess.GetAvailablePortNames())\n {\n try\n {\n _testingSerialPort = new SerialPort(portName);\n _testingSerialPort.Open();\n\n if (_testingSerialPort.IsOpen)\n {\n availablePortNames.Add(portName);\n _testingSerialPort.Close();\n }\n }\n catch (Exception ex)\n {\n \n }\n }\n availablePortNames.Sort();\n AvailablePortNamesFound = new ObservableCollection<string>(availablePortNames);\n }\n\n</code></pre>\n<p>This routine connects to a combobox which holds the available Comports for selection. If a Comport is already, in use by another application, that port name will not appear in the combo box.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1816/"
] |
Is there an easy way of programmatically checking if a serial COM port is already open/being used?
Normally I would use:
```
try
{
// open port
}
catch (Exception ex)
{
// handle the exception
}
```
However, I would like to programatically check so I can attempt to use another COM port or some such.
|
I needed something similar some time ago, to search for a device.
I obtained a list of available COM ports and then simply iterated over them, if it didn't throw an exception i tried to communicate with the device. A bit rough but working.
```
var portNames = SerialPort.GetPortNames();
foreach(var port in portNames) {
//Try for every portName and break on the first working
}
```
|
195,537 |
<p>I am working on an implementation for RSS feeds for a collaboration platform.
Say there are several thousands of different collaboration rooms where users can share information, and each needs to publish an RSS feed with news, changes, etc...</p>
<p>Using a plain servlet (i.e. <a href="http://www.site.com/RSSServlet/?id=roomID" rel="nofollow noreferrer">http://www.site.com/RSSServlet/?id=roomID</a>) is costly, every time an RSS client is calling the servlet (and this will happen say every 10 minutes for each user registered to an RSS feed on one of the thousand of rooms) this will trigger the entire servlet lifecycle, which is costly.</p>
<p>On the other hand, keeping a static XML file on the disk for each of the thousands of rooms is costly as well, in terms of hard disk space as well as IO operations...</p>
<p>One more limitation - using already existing frameworks might not be an option...</p>
<p>So, how would you implement RSS feeds in a Java envoronment?</p>
|
[
{
"answer_id": 195566,
"author": "Shimi Bandiel",
"author_id": 15100,
"author_profile": "https://Stackoverflow.com/users/15100",
"pm_score": 2,
"selected": false,
"text": "<p>You should try the <a href=\"https://rome.dev.java.net/\" rel=\"nofollow noreferrer\">ROME</a> framework. It is excellent for RSS.</p>\n"
},
{
"answer_id": 202044,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 4,
"selected": true,
"text": "<p>You say that a new http request to your servlet \"will trigger the entire servlet lifecycle\", which as Alexander has already pointed out, isn't exactly true. It will simply trigger another method call to your <code>doGet()</code> or <code>doPost()</code> methods. </p>\n\n<p>I think what you mean to say is that if you have a <code>doGet</code>/<code>doPost</code> method which contains code to build the data needed for the RSS feed from scratch, then each request triggers this fetching of data over and over again.</p>\n\n<p>If this is your concern, and you are ruling static content out, simply modify your Servlet <code>doGet</code>/<code>doPost</code> method to cache the RSS content that you would otherwise return, so that handling each request does not mean re-fetching all of the data all over again.</p>\n\n<p>For example</p>\n\n<pre><code>public void doGet(HttpServletRequest request, HttpServletResponse response) {\n //build the objects you need for the RSS response\n Room room = getRoom(request.getParameter(\"roomid\"));\n //loadData();\n //moreMethodCalls();\n out.println( createRssContent(...) );\n}\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>Map rssCache;\n\npublic void doGet(HttpServletRequest request, HttpServletResponse response) {\n\n //Map is initialized in the init() method or somewhere else \n String roomId = request.getParameter(\"roomid\");\n\n String rssDocument = rssCache.get(roomId);\n if (rssDocument == null) {\n\n //build the objects you need for the RSS response\n Room room = getRoom(roomId);\n //loadData();\n //moreMethodCalls();\n rssDocument = createRssContent(...);\n rssCache.put(roomId, rssDocument);\n }\n out.println( rssDocument );\n}\n</code></pre>\n\n<p>If you only want to store items in a \"cache\" for a certain amount of time you can use one of a dozen different caching frameworks, but the idea here is that you don't reconstruct the entire object graph necessary for your RSS response with each http request. If I am reading your original question right then I think that this is what you hoping to accomplish.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24545/"
] |
I am working on an implementation for RSS feeds for a collaboration platform.
Say there are several thousands of different collaboration rooms where users can share information, and each needs to publish an RSS feed with news, changes, etc...
Using a plain servlet (i.e. <http://www.site.com/RSSServlet/?id=roomID>) is costly, every time an RSS client is calling the servlet (and this will happen say every 10 minutes for each user registered to an RSS feed on one of the thousand of rooms) this will trigger the entire servlet lifecycle, which is costly.
On the other hand, keeping a static XML file on the disk for each of the thousands of rooms is costly as well, in terms of hard disk space as well as IO operations...
One more limitation - using already existing frameworks might not be an option...
So, how would you implement RSS feeds in a Java envoronment?
|
You say that a new http request to your servlet "will trigger the entire servlet lifecycle", which as Alexander has already pointed out, isn't exactly true. It will simply trigger another method call to your `doGet()` or `doPost()` methods.
I think what you mean to say is that if you have a `doGet`/`doPost` method which contains code to build the data needed for the RSS feed from scratch, then each request triggers this fetching of data over and over again.
If this is your concern, and you are ruling static content out, simply modify your Servlet `doGet`/`doPost` method to cache the RSS content that you would otherwise return, so that handling each request does not mean re-fetching all of the data all over again.
For example
```
public void doGet(HttpServletRequest request, HttpServletResponse response) {
//build the objects you need for the RSS response
Room room = getRoom(request.getParameter("roomid"));
//loadData();
//moreMethodCalls();
out.println( createRssContent(...) );
}
```
becomes
```
Map rssCache;
public void doGet(HttpServletRequest request, HttpServletResponse response) {
//Map is initialized in the init() method or somewhere else
String roomId = request.getParameter("roomid");
String rssDocument = rssCache.get(roomId);
if (rssDocument == null) {
//build the objects you need for the RSS response
Room room = getRoom(roomId);
//loadData();
//moreMethodCalls();
rssDocument = createRssContent(...);
rssCache.put(roomId, rssDocument);
}
out.println( rssDocument );
}
```
If you only want to store items in a "cache" for a certain amount of time you can use one of a dozen different caching frameworks, but the idea here is that you don't reconstruct the entire object graph necessary for your RSS response with each http request. If I am reading your original question right then I think that this is what you hoping to accomplish.
|
195,548 |
<p>Due to company constraints out of my control, I have the following scenario:</p>
<p>A COM library that defines the following interface (no CoClass, just the interface):</p>
<pre><code>[
object,
uuid(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx),
dual,
nonextensible,
helpstring("IService Interface"),
pointer_default(unique)
]
IService : IDispatch
{
HRESULT DoSomething();
}
[
object,
uuid(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx),
dual,
nonextensible,
helpstring("IProvider Interface"),
pointer_default(unique)
]
IServiceProvider : IDispatch
{
HRESULT Init( IDispatch *sink, VARIANT_BOOL * result );
HRESULT GetService( LONG serviceIndicator, IService ** result );
};
[
uuid(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx),
version(1.0),
]
library ServiceLibrary
{
importlib("stdole2.tlb");
interface IService;
interface IServiceProvider;
};
</code></pre>
<p>I have a COM (written w/ C++) that implements both interfaces and provides our application(s) with said service. All is fine, I think.</p>
<p>I'm trying to build a new <code>IProvider</code> and <code>IService</code> in .NET (C#). </p>
<p>I've built a Primary Interop Assembly for the COM library, and implemented the following C#:</p>
<pre><code>[ComVisible( true )]
[Guid( "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" )]
public interface INewService : IService
{
// adds a couple new properties
}
[ComVisible( true )]
[Guid( "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" )]
public class NewService : INewService
{
// implement interface
}
[ComVisible( true )]
[Guid( "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" )]
public interface INewProvider : IServiceProvider
{
// adds nothing, just implements
}
[ComVisible( true )]
[Guid( "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" )]
public class NewProvider : INewProvider
{
// implement interface
}
</code></pre>
<p>When I attempt to slip this into the existing runtime, I am able to create the <code>NewProvider</code> object from COM (C++), and <code>QueryInterface</code> for IServiceProvider. When I attempt to call a method on the IServiceProvider, a <code>System.ExecutionEngineException</code> is thrown. </p>
<p>The only other thing I can find, is by looking at the .tlh files created by the #import, shows the legacy COM IExistingProvider class correctly shows that it is derived from IServiceProvider. However the .NET class shows a base of IDispatch. I'm not sure if this a sign, indication, helpful, something else.</p>
|
[
{
"answer_id": 195861,
"author": "Richard Nienaber",
"author_id": 9539,
"author_profile": "https://Stackoverflow.com/users/9539",
"pm_score": 1,
"selected": false,
"text": "<p>You may have to specify additional attributes on your class to have it marshal correctly. I would look through available attributes <a href=\"http://msdn.microsoft.com/en-us/library/d4w8x20h(VS.71).aspx\" rel=\"nofollow noreferrer\">here</a> and maybe look at <a href=\"http://www.codeproject.com/KB/COM/cominterop.aspx\" rel=\"nofollow noreferrer\">this tutorial</a> if you haven't done so already.</p>\n"
},
{
"answer_id": 195885,
"author": "ilitirit",
"author_id": 9825,
"author_profile": "https://Stackoverflow.com/users/9825",
"pm_score": 4,
"selected": true,
"text": "<p>It could be a problem with the name <em>IServiceProvider</em>. Check that you haven't already imported an interface with the same name.</p>\n\n<p>When I create an COM Interface library using your IDL, and then try to import it from another client, I get the warning:</p>\n\n<pre><code>Warning 65 warning C4192: automatically excluding 'IServiceProvider' while importing type library 'ServiceLibrary.dll'\n</code></pre>\n\n<p>Otherwise, you can try renaming it to IServiceProvider2. That's what I did, and everything works fine. I'm using Visual Studio 2008.</p>\n\n<p>If this code runs properly on your machine (it works perfectly on mine) then the problem could be in your implementation.</p>\n\n<p>IDL:</p>\n\n<pre><code>import \"oaidl.idl\";\n\n[\n object,\n uuid(9219CC5B-31CC-4868-A1DE-E18300F73C43),\n dual,\n nonextensible,\n helpstring(\"IService Interface\"),\n pointer_default(unique)\n]\ninterface IService : IDispatch\n{\n HRESULT DoSomething(void);\n}\n\n[\n object,\n uuid(9219CC5B-31CC-4868-A1DE-E18300F73C44),\n dual,\n nonextensible,\n helpstring(\"IProvider Interface\"),\n pointer_default(unique)\n]\ninterface IServiceProvider2 : IDispatch\n{\n HRESULT Init( IDispatch *sink, VARIANT_BOOL * result );\n HRESULT GetService( LONG serviceIndicator, IService ** result );\n};\n\n[\n uuid(9219CC5B-31CC-4868-A1DE-E18300F73C45),\n version(1.0),\n]\nlibrary ServiceLibrary\n{\n importlib(\"stdole2.tlb\");\n\n interface IService;\n interface IServiceProvider2;\n};\n</code></pre>\n\n<p>C#:</p>\n\n<pre><code>using System.Runtime.InteropServices;\nusing System.Windows.Forms;\nusing ServiceLibrary;\nusing IServiceProvider=ServiceLibrary.IServiceProvider2;\n\nnamespace COMInterfaceTester\n{\n [ComVisible(true)]\n [Guid(\"2B9D06B9-EB59-435e-B3FF-B891C63108B2\")]\n public interface INewService : IService\n {\n string ServiceName { get; }\n }\n\n [ComVisible(true)]\n [Guid(\"2B9D06B9-EB59-435e-B3FF-B891C63108B3\")]\n public class NewService : INewService\n {\n public string _name;\n\n public NewService(string name)\n {\n _name = name;\n }\n\n // implement interface\n #region IService Members\n\n public void DoSomething()\n {\n MessageBox.Show(\"NewService.DoSomething\");\n }\n\n #endregion\n\n public string ServiceName\n {\n get { return _name; }\n }\n }\n\n [ComVisible(true)]\n [Guid(\"2B9D06B9-EB59-435e-B3FF-B891C63108B4\")]\n public interface INewProvider : IServiceProvider\n {\n // adds nothing, just implements\n }\n\n [ComVisible(true)]\n [Guid(\"2B9D06B9-EB59-435e-B3FF-B891C63108B5\")]\n public class NewProvider : INewProvider\n {\n // implement interface\n public void Init(object sink, ref bool result)\n {\n MessageBox.Show(\"NewProvider.Init\");\n }\n\n public void GetService(int serviceIndicator, ref IService result)\n {\n result = new NewService(\"FooBar\");\n MessageBox.Show(\"NewProvider.GetService\");\n }\n }\n} \n</code></pre>\n\n<p>C++ Client:</p>\n\n<pre><code>#include \"stdafx.h\"\n#include <iostream>\n#include <atlbase.h>\n#import \"COMInterfaceTester.tlb\" raw_interfaces_only\n#import \"ServiceLibrary.dll\" raw_interfaces_only\n\nusing std::cout;\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n CoInitialize(NULL); //Initialize all COM Components\n COMInterfaceTester::INewProviderPtr pNewProvider(__uuidof(COMInterfaceTester::NewProvider));\n ServiceLibrary::IServiceProvider2 *pNewProviderPtr;\n\n HRESULT hr = pNewProvider.QueryInterface(__uuidof(ServiceLibrary::IServiceProvider2), (void**)&pNewProviderPtr);\n\n if(SUCCEEDED(hr))\n { \n VARIANT_BOOL result = VARIANT_FALSE;\n int *p = NULL;\n\n hr = pNewProviderPtr->Init((IDispatch*)p, &result);\n\n if (FAILED(hr))\n {\n cout << \"Failed to call Init\";\n }\n\n ServiceLibrary::IService *pService = NULL;\n hr = pNewProviderPtr->GetService(0, &pService);\n\n if (FAILED(hr))\n {\n cout << \"Failed to call GetService\";\n }\n else\n {\n COMInterfaceTester::INewService* pNewService = NULL;\n hr = pService->QueryInterface(__uuidof(COMInterfaceTester::INewService), (void**)&pNewService);\n\n if (SUCCEEDED(hr))\n {\n CComBSTR serviceName;\n pNewService->get_ServiceName(&serviceName); \n\n if (serviceName == \"FooBar\")\n {\n pService->DoSomething();\n }\n else\n cout << \"Unexpected service\";\n\n pNewService->Release();\n\n }\n\n pService->Release();\n }\n\n pNewProviderPtr->Release();\n }\n else\n cout << \"Failed to query for IServiceProvider2\";\n\n pNewProvider.Release();\n CoUninitialize (); //DeInitialize all COM Components\n\n}\n</code></pre>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25565/"
] |
Due to company constraints out of my control, I have the following scenario:
A COM library that defines the following interface (no CoClass, just the interface):
```
[
object,
uuid(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx),
dual,
nonextensible,
helpstring("IService Interface"),
pointer_default(unique)
]
IService : IDispatch
{
HRESULT DoSomething();
}
[
object,
uuid(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx),
dual,
nonextensible,
helpstring("IProvider Interface"),
pointer_default(unique)
]
IServiceProvider : IDispatch
{
HRESULT Init( IDispatch *sink, VARIANT_BOOL * result );
HRESULT GetService( LONG serviceIndicator, IService ** result );
};
[
uuid(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx),
version(1.0),
]
library ServiceLibrary
{
importlib("stdole2.tlb");
interface IService;
interface IServiceProvider;
};
```
I have a COM (written w/ C++) that implements both interfaces and provides our application(s) with said service. All is fine, I think.
I'm trying to build a new `IProvider` and `IService` in .NET (C#).
I've built a Primary Interop Assembly for the COM library, and implemented the following C#:
```
[ComVisible( true )]
[Guid( "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" )]
public interface INewService : IService
{
// adds a couple new properties
}
[ComVisible( true )]
[Guid( "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" )]
public class NewService : INewService
{
// implement interface
}
[ComVisible( true )]
[Guid( "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" )]
public interface INewProvider : IServiceProvider
{
// adds nothing, just implements
}
[ComVisible( true )]
[Guid( "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" )]
public class NewProvider : INewProvider
{
// implement interface
}
```
When I attempt to slip this into the existing runtime, I am able to create the `NewProvider` object from COM (C++), and `QueryInterface` for IServiceProvider. When I attempt to call a method on the IServiceProvider, a `System.ExecutionEngineException` is thrown.
The only other thing I can find, is by looking at the .tlh files created by the #import, shows the legacy COM IExistingProvider class correctly shows that it is derived from IServiceProvider. However the .NET class shows a base of IDispatch. I'm not sure if this a sign, indication, helpful, something else.
|
It could be a problem with the name *IServiceProvider*. Check that you haven't already imported an interface with the same name.
When I create an COM Interface library using your IDL, and then try to import it from another client, I get the warning:
```
Warning 65 warning C4192: automatically excluding 'IServiceProvider' while importing type library 'ServiceLibrary.dll'
```
Otherwise, you can try renaming it to IServiceProvider2. That's what I did, and everything works fine. I'm using Visual Studio 2008.
If this code runs properly on your machine (it works perfectly on mine) then the problem could be in your implementation.
IDL:
```
import "oaidl.idl";
[
object,
uuid(9219CC5B-31CC-4868-A1DE-E18300F73C43),
dual,
nonextensible,
helpstring("IService Interface"),
pointer_default(unique)
]
interface IService : IDispatch
{
HRESULT DoSomething(void);
}
[
object,
uuid(9219CC5B-31CC-4868-A1DE-E18300F73C44),
dual,
nonextensible,
helpstring("IProvider Interface"),
pointer_default(unique)
]
interface IServiceProvider2 : IDispatch
{
HRESULT Init( IDispatch *sink, VARIANT_BOOL * result );
HRESULT GetService( LONG serviceIndicator, IService ** result );
};
[
uuid(9219CC5B-31CC-4868-A1DE-E18300F73C45),
version(1.0),
]
library ServiceLibrary
{
importlib("stdole2.tlb");
interface IService;
interface IServiceProvider2;
};
```
C#:
```
using System.Runtime.InteropServices;
using System.Windows.Forms;
using ServiceLibrary;
using IServiceProvider=ServiceLibrary.IServiceProvider2;
namespace COMInterfaceTester
{
[ComVisible(true)]
[Guid("2B9D06B9-EB59-435e-B3FF-B891C63108B2")]
public interface INewService : IService
{
string ServiceName { get; }
}
[ComVisible(true)]
[Guid("2B9D06B9-EB59-435e-B3FF-B891C63108B3")]
public class NewService : INewService
{
public string _name;
public NewService(string name)
{
_name = name;
}
// implement interface
#region IService Members
public void DoSomething()
{
MessageBox.Show("NewService.DoSomething");
}
#endregion
public string ServiceName
{
get { return _name; }
}
}
[ComVisible(true)]
[Guid("2B9D06B9-EB59-435e-B3FF-B891C63108B4")]
public interface INewProvider : IServiceProvider
{
// adds nothing, just implements
}
[ComVisible(true)]
[Guid("2B9D06B9-EB59-435e-B3FF-B891C63108B5")]
public class NewProvider : INewProvider
{
// implement interface
public void Init(object sink, ref bool result)
{
MessageBox.Show("NewProvider.Init");
}
public void GetService(int serviceIndicator, ref IService result)
{
result = new NewService("FooBar");
MessageBox.Show("NewProvider.GetService");
}
}
}
```
C++ Client:
```
#include "stdafx.h"
#include <iostream>
#include <atlbase.h>
#import "COMInterfaceTester.tlb" raw_interfaces_only
#import "ServiceLibrary.dll" raw_interfaces_only
using std::cout;
int _tmain(int argc, _TCHAR* argv[])
{
CoInitialize(NULL); //Initialize all COM Components
COMInterfaceTester::INewProviderPtr pNewProvider(__uuidof(COMInterfaceTester::NewProvider));
ServiceLibrary::IServiceProvider2 *pNewProviderPtr;
HRESULT hr = pNewProvider.QueryInterface(__uuidof(ServiceLibrary::IServiceProvider2), (void**)&pNewProviderPtr);
if(SUCCEEDED(hr))
{
VARIANT_BOOL result = VARIANT_FALSE;
int *p = NULL;
hr = pNewProviderPtr->Init((IDispatch*)p, &result);
if (FAILED(hr))
{
cout << "Failed to call Init";
}
ServiceLibrary::IService *pService = NULL;
hr = pNewProviderPtr->GetService(0, &pService);
if (FAILED(hr))
{
cout << "Failed to call GetService";
}
else
{
COMInterfaceTester::INewService* pNewService = NULL;
hr = pService->QueryInterface(__uuidof(COMInterfaceTester::INewService), (void**)&pNewService);
if (SUCCEEDED(hr))
{
CComBSTR serviceName;
pNewService->get_ServiceName(&serviceName);
if (serviceName == "FooBar")
{
pService->DoSomething();
}
else
cout << "Unexpected service";
pNewService->Release();
}
pService->Release();
}
pNewProviderPtr->Release();
}
else
cout << "Failed to query for IServiceProvider2";
pNewProvider.Release();
CoUninitialize (); //DeInitialize all COM Components
}
```
|
195,549 |
<p>Here's a problem I keep running into:</p>
<p>I have a lot of situations where I need to display some text with a styled container like so:</p>
<pre><code><mx:Canvas>
<mx:Text text="{text}" left="5" verticalCenter="0" right="5" />
</mx:Canvas>
</code></pre>
<p>As you can see - the text in constrained by the left and right margins of the canvas and I have not specified a height for the text control because I want it to grow vertically when I add text to it. Reason being - if there is one line of text I want it to display in the center of the canvas but if there are two or three lines of text I want the text control to show those two or three lines of text.</p>
<p>What keeps happening however, is that it will only display one line of text - no matter how many times I call invalidateSize() on it or the container. What do I do?</p>
<p>CAVEAT: The canvas height and width is set by the component that instantiates it (this is all wrapped up in a custom component) so I can't explicitly set the width or height of the text control...</p>
<p>NOTE: Ok, maybe it's an easy fix because as I was typing this question I figured it out - but, here's a chance to answer an easy question!?</p>
|
[
{
"answer_id": 195561,
"author": "Stephen Cox",
"author_id": 534,
"author_profile": "https://Stackoverflow.com/users/534",
"pm_score": 1,
"selected": false,
"text": "<p>Take a look at the TextArea component.</p>\n"
},
{
"answer_id": 195570,
"author": "James Fassett",
"author_id": 27081,
"author_profile": "https://Stackoverflow.com/users/27081",
"pm_score": 3,
"selected": true,
"text": "<p>The Text component needs a width if you want it to automatically wrap for you. If you used a string with newlines in it it will work grow as you expected without a width. For you, use:</p>\n\n<p><strong>Edit:</strong> Ok, you want it centered in a canvas of varying size. Then you can:</p>\n\n<pre><code><mx:HBox \n width=\"500\"\n paddingLeft=\"5\"\n paddingRight=\"5\">\n <mx:Spacer width=\"100%\" />\n <mx:Text \n width=\"100%\"\n text=\"{text}\" />\n <mx:Spacer width=\"100%\" />\n</mx:HBox>\n</code></pre>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3435/"
] |
Here's a problem I keep running into:
I have a lot of situations where I need to display some text with a styled container like so:
```
<mx:Canvas>
<mx:Text text="{text}" left="5" verticalCenter="0" right="5" />
</mx:Canvas>
```
As you can see - the text in constrained by the left and right margins of the canvas and I have not specified a height for the text control because I want it to grow vertically when I add text to it. Reason being - if there is one line of text I want it to display in the center of the canvas but if there are two or three lines of text I want the text control to show those two or three lines of text.
What keeps happening however, is that it will only display one line of text - no matter how many times I call invalidateSize() on it or the container. What do I do?
CAVEAT: The canvas height and width is set by the component that instantiates it (this is all wrapped up in a custom component) so I can't explicitly set the width or height of the text control...
NOTE: Ok, maybe it's an easy fix because as I was typing this question I figured it out - but, here's a chance to answer an easy question!?
|
The Text component needs a width if you want it to automatically wrap for you. If you used a string with newlines in it it will work grow as you expected without a width. For you, use:
**Edit:** Ok, you want it centered in a canvas of varying size. Then you can:
```
<mx:HBox
width="500"
paddingLeft="5"
paddingRight="5">
<mx:Spacer width="100%" />
<mx:Text
width="100%"
text="{text}" />
<mx:Spacer width="100%" />
</mx:HBox>
```
|
195,578 |
<p>I got a problem like this (this is html/css menu):</p>
<p>Eshop | Another eshop | Another eshop</p>
<p>Client wants it work like this:</p>
<p>User comes to website, clicks on Eshop. Eshop changes to red color with red box outline. User decides to visit Another eshop, so Eshop will go back to normaln color without red box outline, and another eshop will do the red outline trick again.. </p>
<p>I know there is A:visited but I don't want all visited menu links to be red with red box outline.</p>
<p>Thx for any help :)</p>
|
[
{
"answer_id": 195579,
"author": "Joe Skora",
"author_id": 14057,
"author_profile": "https://Stackoverflow.com/users/14057",
"pm_score": 1,
"selected": false,
"text": "<p>You can do this with CSS classes. For example, a <em>selected</em> class could identify the current shop, changing the color and outline. Then you can change the selection by adding/removing the class from the menu item.</p>\n\n<p>Take a look <a href=\"http://www.seoconsultants.com/css/menus/tutorial/\" rel=\"nofollow noreferrer\">here</a>, it walks through a tutorial on building CSS menus.</p>\n"
},
{
"answer_id": 195597,
"author": "Nir",
"author_id": 3509,
"author_profile": "https://Stackoverflow.com/users/3509",
"pm_score": 0,
"selected": false,
"text": "<p>As far as I know you can do this only by generating different code for every page (setting a different class for the current page) or by using JavaScript to change the menu after the page is loaded.</p>\n"
},
{
"answer_id": 195601,
"author": "Georg Schölly",
"author_id": 24587,
"author_profile": "https://Stackoverflow.com/users/24587",
"pm_score": 3,
"selected": true,
"text": "<p>The same that Joe Skora has written but more specific:</p>\n\n<pre><code>.red {\n outline-color:red;\n outline-width:10px;\n}\n</code></pre>\n\n<p>Now you could use Javascript (in this example using <a href=\"http://jquery.com\" rel=\"nofollow noreferrer\">jQuery</a>) in the click-event-handler:</p>\n\n<pre><code>$('.red').removeClass('red'); // removes class red from all items with class red\n$(this).addClass('red'); // adds class red to the clicked item\n</code></pre>\n\n<p>Another way of doing it is the use of the pseudo selector :target.<br />\nFor informations about it: <a href=\"http://www.thinkvitamin.com/features/css/stay-on-target\" rel=\"nofollow noreferrer\">www.thinkvitamin.com</a></p>\n"
},
{
"answer_id": 195603,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 1,
"selected": false,
"text": "<p>Basically, it can't be done with CSS alone, some scripting would have to take place (server or client side, preferably server). As the others have suggested, add a 'selected' class (or something similar) to the active link, and define the styles for it in CSS.</p>\n\n<p>For example, the links:</p>\n\n<pre><code> <a href=\"#\">Eshop</a> | <a href=\"#\" class=\"selected\">Another eshop</a> | <a href=\"#\">Another eshop</a>\n</code></pre>\n\n<p>The styles:</p>\n\n<pre><code>.selected {\n font-weight:bold;\n color:#efefef;\n}\n</code></pre>\n\n<p>The links would be generated dynamically, using PHP for example:</p>\n\n<pre><code> <?php\n foreach(array('eshop' => '#','another eshop' => '#','yet another eshop' => '#') as $title => $url) {\n echo '<a href=\"' . $url . '\"' \n . ($url == $_SERVER['REQUEST_URI'] ? ' class=\"selected\"' : null) \n . '>' . $title . '</a>'; \n }\n</code></pre>\n"
},
{
"answer_id": 199282,
"author": "Matthew M. Osborn",
"author_id": 5235,
"author_profile": "https://Stackoverflow.com/users/5235",
"pm_score": 0,
"selected": false,
"text": "<p>you could use and attribute selector like this...</p>\n\n<pre><code>a[href^=\"http:\\\\www.EShop\"]:visted { color: red; }\n</code></pre>\n\n<p>By doing that you are saying any link that has a href that starts with http:\\Eshop.com and has been visted apply this style.</p>\n"
},
{
"answer_id": 199357,
"author": "Zack The Human",
"author_id": 18265,
"author_profile": "https://Stackoverflow.com/users/18265",
"pm_score": 2,
"selected": false,
"text": "<p>You can do this with plain CSS and HTML. A method we commonly use is to have a matching ID and class selector for each navigation item.</p>\n\n<p>The benefit to this is that you don't have to modify your <strong>menu code</strong> per page, you modify the <strong>page itself</strong>, which you'll already be doing unless everything is fully dynamic.</p>\n\n<p>It works like this:</p>\n\n<pre><code><!-- ... head, etc ... -->\n<body>\n\n<ul class=\"nav\">\n <li><a href=\"home.html\" class=\"nav-home\">Home</a></li>\n <li><a href=\"art.html\" class=\"nav-art\">Art</a></li>\n <li><a href=\"contact.html\" class=\"nav-contact\">Contact</a></li>\n</ul>\n\n<!-- ... more page ... -->\n\n</body>\n</code></pre>\n\n<p>Then you set up some CSS like this:</p>\n\n<pre><code>#NAV-HOME .nav-home,\n#NAV-ART .nav-art,\n#NAV-CONTACT .nav-contact { color:red; }\n</code></pre>\n\n<p>To change the \"current\" menu item, you can just assign the corresponding ID to an element higher in the document's structure. Typically I add it to the <body> tag.</p>\n\n<p>To highlight the \"Art\" page, all you have to do is this:</p>\n\n<pre><code><!-- The \"Art\" item will stand out. -->\n<body id=\"NAV-ART\">\n\n<ul class=\"nav\">\n <li><a href=\"home.html\" class=\"nav-home\">Home</a></li>\n <li><a href=\"art.html\" class=\"nav-art\">Art</a></li>\n <li><a href=\"contact.html\" class=\"nav-contact\">Contact</a></li>\n</ul>\n\n<!-- ... more page ... -->\n\n</body>\n</code></pre>\n"
},
{
"answer_id": 199379,
"author": "Bobby Jack",
"author_id": 5058,
"author_profile": "https://Stackoverflow.com/users/5058",
"pm_score": 0,
"selected": false,
"text": "<p>It depends on how your pages are constructed, but the classic CSS was of doing this is with an id on the body, as well as each navigational link, so you might have something like:</p>\n\n<p><em>eshop.html</em></p>\n\n<pre><code><body id=\"eshop\">\n <ul>\n <li><a href=\"\" id=\"link-eshop\">Eshop</a></li>\n <li><a href=\"\" id=\"link-aeshop\">Another eshop</a></li>\n <li><a href=\"\" id=\"link-eshop-three\">Another eshop</a></li>\n </ul>\n</body>\n</code></pre>\n\n<p>and corresponding CSS:</p>\n\n<pre><code>#eshop #link-eshop, #aeshop, #link-aeshop, #eshop-three #link-eshop-three\n{\n color: red;\n outline: 1px solid red;\n}\n</code></pre>\n\n<p>the navigation is consistent; only the id on the body changes from page to page.</p>\n"
},
{
"answer_id": 201979,
"author": "Traingamer",
"author_id": 27609,
"author_profile": "https://Stackoverflow.com/users/27609",
"pm_score": 1,
"selected": false,
"text": "<p><strong>If</strong> you are moving to a new page in the <em>same</em> browser window, <em>Zack Mulgrew</em> and <em>Bobby Jack</em> both have excellent answers.</p>\n\n<p>If you are opening the eshop link in a new window, there is not much you can do with css alone, and <em>gs</em> has a reasonable answer except for the choice of class name of (<em>red</em>).</p>\n\n<p>Which is it?</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21209/"
] |
I got a problem like this (this is html/css menu):
Eshop | Another eshop | Another eshop
Client wants it work like this:
User comes to website, clicks on Eshop. Eshop changes to red color with red box outline. User decides to visit Another eshop, so Eshop will go back to normaln color without red box outline, and another eshop will do the red outline trick again..
I know there is A:visited but I don't want all visited menu links to be red with red box outline.
Thx for any help :)
|
The same that Joe Skora has written but more specific:
```
.red {
outline-color:red;
outline-width:10px;
}
```
Now you could use Javascript (in this example using [jQuery](http://jquery.com)) in the click-event-handler:
```
$('.red').removeClass('red'); // removes class red from all items with class red
$(this).addClass('red'); // adds class red to the clicked item
```
Another way of doing it is the use of the pseudo selector :target.
For informations about it: [www.thinkvitamin.com](http://www.thinkvitamin.com/features/css/stay-on-target)
|
195,582 |
<p>I am taking my first steps programming in Lua and get this error when I run my script:</p>
<pre><code>attempt to index upvalue 'base' (a function value)
</code></pre>
<p>It's probably due to something very basic that I haven't grasped yet, but I can't find any good information about it when googling. Could someone explain to me what it means?</p>
|
[
{
"answer_id": 195599,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "<p>In this case it looks <code>base</code> is a function, but you're trying to index it like a table (eg. <code>base[5]</code> or <code>base.somefield</code>).</p>\n\n<p>The 'upvalue' part is just telling you what kind of variable <code>base</code> is, in this case an upvalue (aka external local variable).</p>\n"
},
{
"answer_id": 42890331,
"author": "GoojajiGreg",
"author_id": 3455883,
"author_profile": "https://Stackoverflow.com/users/3455883",
"pm_score": 3,
"selected": false,
"text": "<h1>One \"local\" too many?</h1>\n\n<p>As <a href=\"https://stackoverflow.com/a/195599/6286781\">Mike F</a> explained, an \"upvalue\" is an external local variable. This error often occurs when a variable has been declared <code>local</code> in a forward declaration and then declared <code>local</code> <strong>again</strong> when it is initialized. This leaves the forward declared variable with a value of <code>nil</code>. This code snippet demonstrates what <strong>not</strong> to do:</p>\n\n<pre><code> local foo -- a forward declaration \n\n local function useFoo()\n print( foo.bar ) -- foo is an upvalue and this will produce the error in question\n -- not only is foo.bar == nil at this point, but so is foo\n end\n\n local function f()\n\n -- one LOCAL too many coming up...\n\n local foo = {} -- this is a **new** foo with function scope\n\n foo.bar = \"Hi!\"\n\n -- the local foo has been initialized to a table\n -- the upvalue (external local variable) foo declared above is not\n -- initialized\n\n useFoo()\n end \n\n f()\n</code></pre>\n\n<p>In this case, removing the <code>local</code> in front of <code>foo</code> when it is initialized in <code>f()</code> fixes the example, i.e.</p>\n\n<pre><code>foo = {}\nfoo.bar = \"Hi!\"\n</code></pre>\n\n<p>Now the call to useFoo() will produce the desired output</p>\n\n<blockquote>\n <p>Hi!</p>\n</blockquote>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22283/"
] |
I am taking my first steps programming in Lua and get this error when I run my script:
```
attempt to index upvalue 'base' (a function value)
```
It's probably due to something very basic that I haven't grasped yet, but I can't find any good information about it when googling. Could someone explain to me what it means?
|
In this case it looks `base` is a function, but you're trying to index it like a table (eg. `base[5]` or `base.somefield`).
The 'upvalue' part is just telling you what kind of variable `base` is, in this case an upvalue (aka external local variable).
|
195,587 |
<p>Got a class that serializes into xml with XMLEncoder nicely with all the variables there. Except for the one that holds <em>java.util.Locale</em>. What could be the trick?</p>
|
[
{
"answer_id": 195646,
"author": "Miguel Ping",
"author_id": 22992,
"author_profile": "https://Stackoverflow.com/users/22992",
"pm_score": 0,
"selected": false,
"text": "<p>Sorry, don't you mean <em>java.util.Locale</em>? The javadocs say that <em>java.util.Locale</em> implements <em>Serializable</em>, so you should have no problem using the <em>Locale</em> class from the <em>lang</em> package.</p>\n"
},
{
"answer_id": 195693,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 4,
"selected": true,
"text": "<p>The problem is that java.util.Locale is not a <a href=\"http://java.sun.com/javase/technologies/desktop/javabeans/docs/spec.html\" rel=\"noreferrer\">bean</a>. From the <a href=\"http://java.sun.com/javase/6/docs/api/index.html?java/beans/XMLEncoder.html\" rel=\"noreferrer\">XMLEncoder</a> doc:</p>\n\n<blockquote>\n <p>The XMLEncoder class is a\n complementary alternative to the\n ObjectOutputStream and can used to\n generate a textual representation of a\n <strong>JavaBean</strong> in the same way that the\n ObjectOutputStream can be used to\n create binary representation of\n Serializable objects.</p>\n</blockquote>\n\n<p>However, the API allows you to use PersistenceDelegates to serialize non-bean types:</p>\n\n<p>Sample bean:</p>\n\n<pre><code>public class MyBean implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n private Locale locale;\n private String foo;\n\n public MyBean() {\n }\n\n public Locale getLocale() {\n return locale;\n }\n\n public void setLocale(Locale locale) {\n this.locale = locale;\n }\n\n public String getFoo() {\n return foo;\n }\n\n public void setFoo(String foo) {\n this.foo = foo;\n }\n\n}\n</code></pre>\n\n<p>Serializing a data graph that includes a Locale type:</p>\n\n<pre><code>public class MyBeanTest {\n\n public static void main(String[] args) throws Exception {\n // quick and dirty test\n\n MyBean c = new MyBean();\n c.setLocale(Locale.CHINA);\n c.setFoo(\"foo\");\n\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n XMLEncoder encoder = new XMLEncoder(outputStream);\n encoder.setPersistenceDelegate(Locale.class, new PersistenceDelegate() {\n protected Expression instantiate(Object oldInstance, Encoder out) {\n Locale l = (Locale) oldInstance;\n return new Expression(oldInstance, oldInstance.getClass(),\n \"new\", new Object[] { l.getLanguage(), l.getCountry(),\n l.getVariant() });\n }\n });\n encoder.writeObject(c);\n encoder.flush();\n encoder.close();\n\n System.out.println(outputStream.toString(\"UTF-8\"));\n\n ByteArrayInputStream bain = new ByteArrayInputStream(outputStream\n .toByteArray());\n XMLDecoder decoder = new XMLDecoder(bain);\n\n c = (MyBean) decoder.readObject();\n\n System.out.println(\"===================\");\n System.out.println(c.getLocale());\n System.out.println(c.getFoo());\n }\n\n}\n</code></pre>\n\n<p>This is the section of code that describes how the object should be instantiated on deserialization - it sets the constructor arguments to three string values:</p>\n\n<pre><code> new PersistenceDelegate() {\n protected Expression instantiate(Object oldInstance, Encoder out) {\n Locale l = (Locale) oldInstance;\n return new Expression(oldInstance, oldInstance.getClass(),\n \"new\", new Object[] { l.getLanguage(), l.getCountry(),\n l.getVariant() });\n }\n }\n</code></pre>\n\n<p>Read <a href=\"http://java.sun.com/products/jfc/tsc/articles/persistence4/\" rel=\"noreferrer\">Using XMLEncoder</a> by Philip Milne for more info.</p>\n\n<p>All this aside, it might be smarter to store the locale information in textual form and use it to look up the appropriate Locale object whenever it is needed. That way you don't need special case code when serializing your object and make it more portable.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15187/"
] |
Got a class that serializes into xml with XMLEncoder nicely with all the variables there. Except for the one that holds *java.util.Locale*. What could be the trick?
|
The problem is that java.util.Locale is not a [bean](http://java.sun.com/javase/technologies/desktop/javabeans/docs/spec.html). From the [XMLEncoder](http://java.sun.com/javase/6/docs/api/index.html?java/beans/XMLEncoder.html) doc:
>
> The XMLEncoder class is a
> complementary alternative to the
> ObjectOutputStream and can used to
> generate a textual representation of a
> **JavaBean** in the same way that the
> ObjectOutputStream can be used to
> create binary representation of
> Serializable objects.
>
>
>
However, the API allows you to use PersistenceDelegates to serialize non-bean types:
Sample bean:
```
public class MyBean implements Serializable {
private static final long serialVersionUID = 1L;
private Locale locale;
private String foo;
public MyBean() {
}
public Locale getLocale() {
return locale;
}
public void setLocale(Locale locale) {
this.locale = locale;
}
public String getFoo() {
return foo;
}
public void setFoo(String foo) {
this.foo = foo;
}
}
```
Serializing a data graph that includes a Locale type:
```
public class MyBeanTest {
public static void main(String[] args) throws Exception {
// quick and dirty test
MyBean c = new MyBean();
c.setLocale(Locale.CHINA);
c.setFoo("foo");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
XMLEncoder encoder = new XMLEncoder(outputStream);
encoder.setPersistenceDelegate(Locale.class, new PersistenceDelegate() {
protected Expression instantiate(Object oldInstance, Encoder out) {
Locale l = (Locale) oldInstance;
return new Expression(oldInstance, oldInstance.getClass(),
"new", new Object[] { l.getLanguage(), l.getCountry(),
l.getVariant() });
}
});
encoder.writeObject(c);
encoder.flush();
encoder.close();
System.out.println(outputStream.toString("UTF-8"));
ByteArrayInputStream bain = new ByteArrayInputStream(outputStream
.toByteArray());
XMLDecoder decoder = new XMLDecoder(bain);
c = (MyBean) decoder.readObject();
System.out.println("===================");
System.out.println(c.getLocale());
System.out.println(c.getFoo());
}
}
```
This is the section of code that describes how the object should be instantiated on deserialization - it sets the constructor arguments to three string values:
```
new PersistenceDelegate() {
protected Expression instantiate(Object oldInstance, Encoder out) {
Locale l = (Locale) oldInstance;
return new Expression(oldInstance, oldInstance.getClass(),
"new", new Object[] { l.getLanguage(), l.getCountry(),
l.getVariant() });
}
}
```
Read [Using XMLEncoder](http://java.sun.com/products/jfc/tsc/articles/persistence4/) by Philip Milne for more info.
All this aside, it might be smarter to store the locale information in textual form and use it to look up the appropriate Locale object whenever it is needed. That way you don't need special case code when serializing your object and make it more portable.
|
195,626 |
<p>I have a python module that makes use of a huge dictionary global variable, currently I put the computation code in the top section, every first time import or reload of the module takes more then one minute which is totally unacceptable. How can I save the computation result somewhere so that the next import/reload doesn't have to compute it? I tried cPickle, but loading the dictionary variable from a file(1.3M) takes approximately the same time as computation.</p>
<p>To give more information about my problem, </p>
<pre><code>FD = FreqDist(word for word in brown.words()) # this line of code takes 1 min
</code></pre>
|
[
{
"answer_id": 195645,
"author": "David Grant",
"author_id": 26829,
"author_profile": "https://Stackoverflow.com/users/26829",
"pm_score": 2,
"selected": false,
"text": "<p>I assume you've pasted the dict literal into the source, and that's what's taking a minute? I don't know how to get around that, but you could probably avoid instantiating this dict upon <em>import</em>... You could lazily-instantiate it the first time it's actually used.</p>\n"
},
{
"answer_id": 195702,
"author": "Peter Hoffmann",
"author_id": 720,
"author_profile": "https://Stackoverflow.com/users/720",
"pm_score": 1,
"selected": false,
"text": "<p>You can use a <a href=\"http://www.python.org/doc/2.5.2/lib/module-shelve.html\" rel=\"nofollow noreferrer\">shelve</a> to store your data on disc instead of loading the whole data into memory. So startup time will be very fast, but the trade-off will be slower access time. </p>\n\n<p>Shelve will pickle the dict values too, but will do the (un)pickle not at startup for all the items, but only at access time for each item itself.</p>\n"
},
{
"answer_id": 195739,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 2,
"selected": false,
"text": "<p>Calculate your global var on the first use.</p>\n\n<pre><code>class Proxy:\n @property\n def global_name(self):\n # calculate your global var here, enable cache if needed\n ...\n\n_proxy_object = Proxy()\nGLOBAL_NAME = _proxy_object.global_name\n</code></pre>\n\n<p>Or better yet, access necessery data via special data object.</p>\n\n<pre><code>class Data:\n GLOBAL_NAME = property(...)\n\ndata = Data()\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>from some_module import data\n\nprint(data.GLOBAL_NAME)\n</code></pre>\n\n<p>See <a href=\"http://docs.djangoproject.com/en/dev/topics/settings/\" rel=\"nofollow noreferrer\">Django settings</a>.</p>\n"
},
{
"answer_id": 195758,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 2,
"selected": false,
"text": "<p>You could try using the <a href=\"http://en.wikipedia.org/wiki/All_You_Zombies%E2%80%94\" rel=\"nofollow noreferrer\">marshal</a> module instead of the c?Pickle one; it could be faster. This module is used by python to store values in a binary format. Note especially the following paragraph, to see if marshal fits your needs:</p>\n\n<blockquote>\n <p>Not all Python object types are supported; in general, only objects whose value is independent from a particular invocation of Python can be written and read by this module. The following types are supported: None, integers, long integers, floating point numbers, strings, Unicode objects, tuples, lists, sets, dictionaries, and code objects, where it should be understood that tuples, lists and dictionaries are only supported as long as the values contained therein are themselves supported; and recursive lists and dictionaries should not be written (they will cause infinite loops). </p>\n</blockquote>\n\n<p>Just to be on the safe side, before unmarshalling the dict, make sure that the Python version that unmarshals the dict is the same as the one that did the marshal, since there are no guarantees for backwards compatibility.</p>\n"
},
{
"answer_id": 195776,
"author": "HUAGHAGUAH",
"author_id": 27233,
"author_profile": "https://Stackoverflow.com/users/27233",
"pm_score": 0,
"selected": false,
"text": "<p>Expanding on the delayed-calculation idea, why not turn the dict into a class that supplies (and caches) elements as necessary?</p>\n\n<p>You might also use psyco to speed up overall execution...</p>\n"
},
{
"answer_id": 195792,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 0,
"selected": false,
"text": "<p><em>OR</em> you could just use a database for storing the values in? Check out SQLObject, which makes it very easy to store stuff to a database.</p>\n"
},
{
"answer_id": 195962,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 5,
"selected": true,
"text": "<p>Just to clarify: the code in the body of a module is <em>not</em> executed every time the module is imported - it is run only once, after which future imports find the already created module, rather than recreating it. Take a look at sys.modules to see the list of cached modules.</p>\n\n<p>However, if your problem is the time it takes for the first import after the program is run, you'll probably need to use some other method than a python dict. Probably best would be to use an on-disk form, for instance a sqlite database, one of the dbm modules.</p>\n\n<p>For a minimal change in your interface, the shelve module may be your best option - this puts a pretty transparent interface between the dbm modules that makes them act like an arbitrary python dict, allowing any picklable value to be stored. Here's an example:</p>\n\n<pre><code># Create dict with a million items:\nimport shelve\nd = shelve.open('path/to/my_persistant_dict')\nd.update(('key%d' % x, x) for x in xrange(1000000))\nd.close()\n</code></pre>\n\n<p>Then in the next process, use it. There should be no large delay, as lookups are only performed for the key requested on the on-disk form, so everything doesn't have to get loaded into memory:</p>\n\n<pre><code>>>> d = shelve.open('path/to/my_persistant_dict')\n>>> print d['key99999']\n99999\n</code></pre>\n\n<p>It's a bit slower than a real dict, and it <strong>will</strong> still take a long time to load if you do something that requires all the keys (eg. try to print it), but may solve your problem.</p>\n"
},
{
"answer_id": 196218,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 1,
"selected": false,
"text": "<p>A couple of things that will help speed up imports:</p>\n\n<ol>\n<li>You might try running python using the -OO flag when running python. This will do some optimizations that will reduce import time of modules.</li>\n<li>Is there any reason why you couldn't break the dictionary up into smaller dictionaries in separate modules that can be loaded more quickly?</li>\n<li>As a last resort, you could do the calculations asynchronously so that they won't delay your program until it needs the results. Or maybe even put the dictionary in a separate process and pass data back and forth using IPC if you want to take advantage of multi-core architectures.</li>\n</ol>\n\n<p>With that said, I agree that you shouldn't be experiencing any delay in importing modules after the first time you import it. Here are a couple of other general thoughts:</p>\n\n<ol>\n<li>Are you importing the module within a function? If so, this <em>can</em> lead to performance problems since it has to check and see if the module is loaded every time it hits the import statement.</li>\n<li>Is your program multi-threaded? I have seen occassions where executing code upon module import in a multi-threaded app can cause some wonkiness and application instability (most notably with the cgitb module).</li>\n<li>If this is a global variable, be aware that global variable lookup times can be significantly longer than local variable lookup times. In this case, you can achieve a significant performance improvement by binding the dictionary to a local variable if you're using it multiple times in the same context.</li>\n</ol>\n\n<p>With that said, it's a tad bit difficult to give you any specific advice without a little bit more context. More specifically, where are you importing it? And what are the computations?</p>\n"
},
{
"answer_id": 201077,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 1,
"selected": false,
"text": "<ol>\n<li><p>Factor the computationally intensive part into a separate module. Then at least on reload, you won't have to wait. </p></li>\n<li><p>Try dumping the data structure using protocol 2. The command to try would be <code>cPickle.dump(FD, protocol=2)</code>. From the docstring for <code>cPickle.Pickler</code>:</p>\n\n<blockquote>\n<pre><code>Protocol 0 is the\nonly protocol that can be written to a file opened in text\nmode and read back successfully. When using a protocol higher\nthan 0, make sure the file is opened in binary mode, both when\npickling and unpickling. \n</code></pre>\n</blockquote></li>\n</ol>\n"
},
{
"answer_id": 345744,
"author": "saffsd",
"author_id": 37984,
"author_profile": "https://Stackoverflow.com/users/37984",
"pm_score": 2,
"selected": false,
"text": "<p>If the 'shelve' solution turns out to be too slow or fiddly, there are other possibilities:</p>\n\n<ul>\n<li><a href=\"http://pypi.python.org/pypi/shove\" rel=\"nofollow noreferrer\">shove</a></li>\n<li><a href=\"http://www.mems-exchange.org/software/durus/\" rel=\"nofollow noreferrer\">Durus</a></li>\n<li><a href=\"http://www.zope.org\" rel=\"nofollow noreferrer\">ZopeDB</a></li>\n<li><a href=\"http://www.pytables.org/\" rel=\"nofollow noreferrer\">pyTables</a></li>\n</ul>\n"
},
{
"answer_id": 431452,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>There's another pretty obvious solution for this problem. When code is reloaded the original scope is still available.</p>\n\n<p>So... doing something like this will make sure this code is executed only once.</p>\n\n<pre><code>try:\n FD\nexcept NameError:\n FD = FreqDist(word for word in brown.words())\n</code></pre>\n"
},
{
"answer_id": 1184838,
"author": "Jacob",
"author_id": 144563,
"author_profile": "https://Stackoverflow.com/users/144563",
"pm_score": 2,
"selected": false,
"text": "<p><code>shelve</code> gets really slow with large data sets. I've been using <a href=\"http://streamhacker.com/2009/05/20/building-a-nltk-freqdist-on-redis/\" rel=\"nofollow noreferrer\">redis</a> quite successfully, and wrote a <a href=\"http://bitbucket.org/japerk/nltk-extras/src/tip/probability.py\" rel=\"nofollow noreferrer\">FreqDist wrapper</a> around it. It's very fast, and can be accessed concurrently.</p>\n"
},
{
"answer_id": 2213775,
"author": "James",
"author_id": 252253,
"author_profile": "https://Stackoverflow.com/users/252253",
"pm_score": 1,
"selected": false,
"text": "<p>I'm going through this same issue... \nshelve, databases, etc... are all too slow for this type of problem. You'll need to take the hit once, insert it into an inmemory key/val store like Redis. It will just live there in memory (warning it could use up a good amount of memory so you may want a dedicated box). You'll never have to reload it and you'll just get looking in memory for keys</p>\n\n<pre><code>r = Redis()\nr.set(key, word)\n\nword = r.get(key)\n</code></pre>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1925263/"
] |
I have a python module that makes use of a huge dictionary global variable, currently I put the computation code in the top section, every first time import or reload of the module takes more then one minute which is totally unacceptable. How can I save the computation result somewhere so that the next import/reload doesn't have to compute it? I tried cPickle, but loading the dictionary variable from a file(1.3M) takes approximately the same time as computation.
To give more information about my problem,
```
FD = FreqDist(word for word in brown.words()) # this line of code takes 1 min
```
|
Just to clarify: the code in the body of a module is *not* executed every time the module is imported - it is run only once, after which future imports find the already created module, rather than recreating it. Take a look at sys.modules to see the list of cached modules.
However, if your problem is the time it takes for the first import after the program is run, you'll probably need to use some other method than a python dict. Probably best would be to use an on-disk form, for instance a sqlite database, one of the dbm modules.
For a minimal change in your interface, the shelve module may be your best option - this puts a pretty transparent interface between the dbm modules that makes them act like an arbitrary python dict, allowing any picklable value to be stored. Here's an example:
```
# Create dict with a million items:
import shelve
d = shelve.open('path/to/my_persistant_dict')
d.update(('key%d' % x, x) for x in xrange(1000000))
d.close()
```
Then in the next process, use it. There should be no large delay, as lookups are only performed for the key requested on the on-disk form, so everything doesn't have to get loaded into memory:
```
>>> d = shelve.open('path/to/my_persistant_dict')
>>> print d['key99999']
99999
```
It's a bit slower than a real dict, and it **will** still take a long time to load if you do something that requires all the keys (eg. try to print it), but may solve your problem.
|
195,632 |
<p>So, I can create an input button with an image using</p>
<pre><code><INPUT type="image" src="/images/Btn.PNG" value="">
</code></pre>
<p>But, I can't get the same behavior using CSS. For instance, I've tried</p>
<pre><code><INPUT type="image" class="myButton" value="">
</code></pre>
<p>where "myButton" is defined in the CSS file as</p>
<pre><code>.myButton {
background:url(/images/Btn.PNG) no-repeat;
cursor:pointer;
width: 200px;
height: 100px;
border: none;
}
</code></pre>
<p>If that's all I wanted to do, I could use the original style, but I want to change the button's appearance on hover (using a <code>myButton:hover</code> class). I know the links are good, because I've been able to load them for a background image for other parts of the page (just as a check). I found examples on the web of how to do it using JavaScript, but I'm looking for a CSS solution.</p>
<p>I'm using Firefox 3.0.3 if that makes a difference.</p>
|
[
{
"answer_id": 195637,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 8,
"selected": true,
"text": "<p>If you're wanting to style the button using CSS, make it a type=\"submit\" button instead of type=\"image\". type=\"image\" expects a SRC, which you can't set in CSS.</p>\n\n<p>Note that Safari won't let you style any button in the manner you're looking for. If you need Safari support, you'll need to place an image and have an onclick function that submits the form.</p>\n"
},
{
"answer_id": 195638,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 5,
"selected": false,
"text": "<p>This article about <a href=\"http://www.ampsoft.net/webdesign-l/image-button.html\" rel=\"noreferrer\">CSS image replacement for submit buttons</a> could help.</p>\n\n<p><em>\"Using this method you'll get a clickable image when style sheets are active, and a standard button when style sheets are off. The trick is to apply the image replace methods to a button tag and use it as the submit button, instead of using input.<br /><br />\nAnd since button borders are erased, it's also recommendable change the button cursor to \nthe hand shaped one used for links, since this provides a visual tip to the users.\"</em></p>\n\n<p>The CSS code:</p>\n\n<pre><code>#replacement-1 {\n width: 100px;\n height: 55px;\n margin: 0;\n padding: 0;\n border: 0;\n background: transparent url(image.gif) no-repeat center top;\n text-indent: -1000em;\n cursor: pointer; /* hand-shaped cursor */\n cursor: hand; /* for IE 5.x */\n}\n\n#replacement-2 {\n width: 100px;\n height: 55px;\n padding: 55px 0 0;\n margin: 0;\n border: 0;\n background: transparent url(image.gif) no-repeat center top;\n overflow: hidden;\n cursor: pointer; /* hand-shaped cursor */\n cursor: hand; /* for IE 5.x */\n}\nform>#replacement-2 { /* For non-IE browsers*/\n height: 0px;\n}\n</code></pre>\n"
},
{
"answer_id": 195644,
"author": "Dimitry",
"author_id": 27073,
"author_profile": "https://Stackoverflow.com/users/27073",
"pm_score": 7,
"selected": false,
"text": "<p>You can use the <code><button></code> tag. For a submit, simply add <code>type="submit"</code>. Then use a background image when you want the button to appear as a graphic.</p>\n<p>Like so:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><button type=\"submit\" style=\"border: 0; background: transparent\">\n <img src=\"https://i.imgur.com/tXLqhgC.png\" width=\"90\" height=\"90\" alt=\"submit\" />\n</button></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><a href=\"http://htmldog.com/reference/htmltags/button/\" rel=\"nofollow noreferrer\">More info</a></p>\n"
},
{
"answer_id": 236918,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps you could just import a .js file as well and have the image replacement there, in JavaScript.</p>\n"
},
{
"answer_id": 1193338,
"author": "SI Web Design",
"author_id": 146326,
"author_profile": "https://Stackoverflow.com/users/146326",
"pm_score": 6,
"selected": false,
"text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>div.myButton input {\n background: url(https://i.imgur.com/tXLqhgC.png) no-repeat;\n background-size: 90px;\n width: 90px;\n height: 90px;\n cursor: pointer;\n border: none;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"myButton\">\n <INPUT type=\"submit\" name=\"\" value=\"\">\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>This will work anywhere, even in Safari.</p>\n"
},
{
"answer_id": 4882160,
"author": "philoye",
"author_id": 109864,
"author_profile": "https://Stackoverflow.com/users/109864",
"pm_score": 4,
"selected": false,
"text": "<p>Here's a simpler solution but with no extra surrounding div:</p>\n\n<pre><code><input type=\"submit\" value=\"Submit\">\n</code></pre>\n\n<p>The CSS uses a basic image replacement technique. For bonus points, it shows using an image sprite:</p>\n\n<pre><code><style>\n input[type=\"submit\"] {\n border: 0;\n background: url('sprite.png') no-repeat -40px left;\n text-indent: -9999em;\n line-height:3000;\n width: 50px;\n height: 20px;\n }\n</style>\n</code></pre>\n\n<p>Source:\n<a href=\"http://work.arounds.org/issue/21/using-css-sprites-with-input-type-submit-buttons/\" rel=\"noreferrer\">http://work.arounds.org/issue/21/using-css-sprites-with-input-type-submit-buttons/</a></p>\n"
},
{
"answer_id": 4971303,
"author": "user545376",
"author_id": 545376,
"author_profile": "https://Stackoverflow.com/users/545376",
"pm_score": 2,
"selected": false,
"text": "<p>Here is what worked for me on Internet Explorer, a slight modification to the solution by Philoye.</p>\n\n<pre><code>>#divbutton\n{\n position:relative;\n top:-64px;\n left:210px;\n background: transparent url(\"../../images/login_go.png\") no-repeat;\n line-height:3000;\n width:33px;\n height:32px;\n border:none;\n cursor:pointer;\n}\n</code></pre>\n"
},
{
"answer_id": 5517032,
"author": "dafyk",
"author_id": 688057,
"author_profile": "https://Stackoverflow.com/users/688057",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <em>blank.gif</em> (a one-pixel transparent image) as the target in your tag:</p>\n<pre><code><input type="image" src="img/blank.gif" class="button">\n</code></pre>\n<p>And then style background in CSS:</p>\n<pre><code>.button {border:0;background:transparent url("../img/button.png") no-repeat 0 0;}\n.button:hover {background:transparent url("../img/button-hover.png") no-repeat 0 0;}\n</code></pre>\n"
},
{
"answer_id": 5682333,
"author": "Reed Richards",
"author_id": 27943,
"author_profile": "https://Stackoverflow.com/users/27943",
"pm_score": 2,
"selected": false,
"text": "<p>A variation on the previous answers:</p>\n<p>I found that opacity needs to be set, of course this will work in Internet Explorer 6 and on. There was a problem with the line-height solution in Internet Explorer 8 where the button would not respond. And with this you get a hand cursor as well!</p>\n<pre><code><div id="myButton">\n <input id="myInputButton" type="submit" name="" value="">\n</div>\n\n#myButton {\n background: url("form_send_button.gif") no-repeat;\n width: 62px;\n height: 24px;\n}\n\n#myInputButton {\n background: url("form_send_button.gif") no-repeat;\n opacity: 0;\n -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";\n filter: alpha(opacity=0);\n width: 67px;\n height: 26px;\n cursor: pointer;\n cursor: hand;\n}\n</code></pre>\n"
},
{
"answer_id": 10286771,
"author": "inf3rno",
"author_id": 607033,
"author_profile": "https://Stackoverflow.com/users/607033",
"pm_score": 2,
"selected": false,
"text": "<p>I think the following is the best solution:</p>\n<p>CSS:</p>\n<pre><code>.edit-button {\n background-image: url(edit.png);\n background-size: 100%;\n background-repeat: no-repeat;\n width: 24px;\n height: 24px;\n}\n</code></pre>\n<p>HTML:</p>\n<pre><code><input class="edit-button" type="image" src="transparent.png" />\n</code></pre>\n"
},
{
"answer_id": 13481271,
"author": "John",
"author_id": 1833395,
"author_profile": "https://Stackoverflow.com/users/1833395",
"pm_score": 1,
"selected": false,
"text": "<p>My solution without JavaScript and without images is this:</p>\n<p><em><strong>HTML:</strong></em></p>\n<pre><code><input type=Submit class=continue_shopping_2\n name=Register title="Confirm Your Data!"\n value="confirm your data">\n</code></pre>\n<p><em><strong>CSS:</strong></em></p>\n<pre><code>.continue_shopping_2: hover {\n background-color: #FF9933;\n text-decoration: none;\n color: #FFFFFF;\n}\n\n\n.continue_shopping_2 {\n padding: 0 0 3px 0;\n cursor: pointer;\n background-color: #EC5500;\n display: block;\n text-align: center;\n margin-top: 8px;\n width: 174px;\n height: 21px;\n border-radius: 5px;\n border-width: 1px;\n border-style: solid;\n border-color: #919191;\n font-family: Verdana;\n font-size: 13px;\n font-style: normal;\n line-height: normal;\n font-weight: bold;\n color: #FFFFFF;\n}\n</code></pre>\n"
},
{
"answer_id": 60635900,
"author": "Colin James Firth",
"author_id": 1448603,
"author_profile": "https://Stackoverflow.com/users/1448603",
"pm_score": 0,
"selected": false,
"text": "<p>Let's assume you can't change the input type, or even the <em>src</em>. You <em>only</em> have CSS to play with.</p>\n<p>If you know the height you want, and you have the URL of a background image you want to use instead, you're in luck.</p>\n<p>Set the height to zero and padding-top to the height you want. That'll shove the original image out of sight, giving you a perfectly clean space to show your CSS background-image.</p>\n<p>It works in Chrome. I don't have any idea if it works in Internet Explorer. Barely anything clever does, so probably not.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#daft {\n height: 0;\n padding-top: 100px;\n width: 100px;\n background-image: url(clever.jpg);\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><input type=\"image\" src=\"daft.jpg\" id=\"daft\"></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1179/"
] |
So, I can create an input button with an image using
```
<INPUT type="image" src="/images/Btn.PNG" value="">
```
But, I can't get the same behavior using CSS. For instance, I've tried
```
<INPUT type="image" class="myButton" value="">
```
where "myButton" is defined in the CSS file as
```
.myButton {
background:url(/images/Btn.PNG) no-repeat;
cursor:pointer;
width: 200px;
height: 100px;
border: none;
}
```
If that's all I wanted to do, I could use the original style, but I want to change the button's appearance on hover (using a `myButton:hover` class). I know the links are good, because I've been able to load them for a background image for other parts of the page (just as a check). I found examples on the web of how to do it using JavaScript, but I'm looking for a CSS solution.
I'm using Firefox 3.0.3 if that makes a difference.
|
If you're wanting to style the button using CSS, make it a type="submit" button instead of type="image". type="image" expects a SRC, which you can't set in CSS.
Note that Safari won't let you style any button in the manner you're looking for. If you need Safari support, you'll need to place an image and have an onclick function that submits the form.
|
195,635 |
<p>I am trying to figure out Messagebox( ownerWindow, ... ).</p>
<p>Using reflector I see that the ownerWindow defaults to the ActiveWindow for the thread.</p>
<p>So the only time I need the ownerWindow parameter is to call Show from another thread. </p>
<p>However when I try this, I get a cross threading exception.</p>
<pre><code> private void button1_Click( object sender, EventArgs e ) {
new Thread( () => MessageBox.Show( this, "Test" ) ).Start();
}
</code></pre>
<p>So it looks like the only time I need the explicitly state the owner window, I cann't use it!</p>
|
[
{
"answer_id": 195640,
"author": "Patrik Svensson",
"author_id": 936,
"author_profile": "https://Stackoverflow.com/users/936",
"pm_score": 2,
"selected": false,
"text": "<p>You will have to do a BeginInvoke to marshal the call to the UI thread.</p>\n\n<p>The code below is a simple example how you can do it. I haven't compiled it, so there might be errors in it, but it might give you some pointers.</p>\n\n<pre><code>private delegate void ThreadExecuteDelegate(object args);\n\npublic void StartThread\n{\n Thread thread = new Thread(new ParameterizedThreadStart(ThreadExecute));\n thread.Start((IWin32Window)this);\n}\n\nprivate void ThreadExecute(object args)\n{\n if(this.InvokeRequired)\n {\n this.BeginInvoke(new ThreadExecuteDelegate(ThreadExecute), args);\n return;\n } \n\n IWin32Window window = (IWin32Window)args;\n MessageBox.Show(window, \"Hello world\");\n}\n</code></pre>\n"
},
{
"answer_id": 195656,
"author": "Scott Weinstein",
"author_id": 25201,
"author_profile": "https://Stackoverflow.com/users/25201",
"pm_score": 0,
"selected": false,
"text": "<p>If you don't want to bother with explictly marshaling calls across threads, use the <a href=\"http://msdn.microsoft.com/en-us/library/8xs8549b.aspx\" rel=\"nofollow noreferrer\">BackgroundWorker</a> and <code>ReportProgress</code></p>\n"
},
{
"answer_id": 195673,
"author": "Sijin",
"author_id": 8884,
"author_profile": "https://Stackoverflow.com/users/8884",
"pm_score": 1,
"selected": true,
"text": "<p>You may want to take a look at <a href=\"http://msdn.microsoft.com/en-us/library/ms997562.aspx\" rel=\"nofollow noreferrer\">Win32 Window Hierarchy and Styles</a> to understand the difference between owner and parent windows. It's not always necessary that the ActiveWindows needs to own the messagebox, I've worked on application where the ActiveWindow was not necessarily the owner of the MessageBox.</p>\n\n<p>Also according to win32 window rules control hierarchy cannot have controls created on different threads which is why you need to marshall the call to the MessageBox.Show to the \n parent window's thread.</p>\n"
},
{
"answer_id": 196111,
"author": "jyoung",
"author_id": 14841,
"author_profile": "https://Stackoverflow.com/users/14841",
"pm_score": 1,
"selected": false,
"text": "<p>It was the Control.Handle getter that was testing for cross threading.</p>\n\n<p>Adding the following code fixes things.</p>\n\n<pre><code> public class Win32Window :IWin32Window {\n IntPtr handle;\n public Win32Window( IWin32Window window ) {\n this.handle = window.Handle;\n }\n\n IntPtr IWin32Window.Handle {\n get { return handle; }\n }\n }\n\n private void button1_Click( object sender, EventArgs e ) {\n IWin32Window window = new Win32Window( this );\n new Thread( () => MessageBox.Show( window, \"Test\" ) ).Start();\n }\n</code></pre>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14841/"
] |
I am trying to figure out Messagebox( ownerWindow, ... ).
Using reflector I see that the ownerWindow defaults to the ActiveWindow for the thread.
So the only time I need the ownerWindow parameter is to call Show from another thread.
However when I try this, I get a cross threading exception.
```
private void button1_Click( object sender, EventArgs e ) {
new Thread( () => MessageBox.Show( this, "Test" ) ).Start();
}
```
So it looks like the only time I need the explicitly state the owner window, I cann't use it!
|
You may want to take a look at [Win32 Window Hierarchy and Styles](http://msdn.microsoft.com/en-us/library/ms997562.aspx) to understand the difference between owner and parent windows. It's not always necessary that the ActiveWindows needs to own the messagebox, I've worked on application where the ActiveWindow was not necessarily the owner of the MessageBox.
Also according to win32 window rules control hierarchy cannot have controls created on different threads which is why you need to marshall the call to the MessageBox.Show to the
parent window's thread.
|
195,639 |
<p>I need a way to bind POJO objects to an external entity, that could be XML, YAML, structured text or anything easy to write and maintain in order to create Mock data for unit testing and TDD. Below are some libraries I tried, but the main problems with them were that I am stuck (for at least more 3 months) to Java 1.4. I'd like any insights on what I could use instead, with as low overhead and upfront setup (like using Schemas or DTDs, for instance) as possible and without complex XML. Here are the libraries I really like (but that apparently doesn't work with 1.4 or doesn't support constructors - you gotta have setters):</p>
<p><b>RE-JAXB (or Really Easy Java XML Bindings)</b></p>
<p><a href="http://jvalentino.blogspot.com/2008/07/in-response-to-easiest-java-xml-binding.html" rel="nofollow noreferrer"><a href="http://jvalentino.blogspot.com/2008/07/in-response-to-easiest-java-xml-binding.html" rel="nofollow noreferrer">http://jvalentino.blogspot.com/2008/07/in-response-to-easiest-java-xml-binding.html</a></a>
<a href="http://sourceforge.net/projects/rejaxb/" rel="nofollow noreferrer"> <a href="http://sourceforge.net/projects/rejaxb/" rel="nofollow noreferrer">http://sourceforge.net/projects/rejaxb/</a></a></p>
<p>Seamlessy binds this:</p>
<pre><code><item>
<title>Astronauts' Dirty Laundry</title>
<link>http://liftoff.msfc.nasa.gov/news/2003/news-laundry.asp</link>
<description>Compared to earlier spacecraft, the International Space
Station has many luxuries, but laundry facilities are not one of them.
Instead, astronauts have other options.</description>
<pubDate>Tue, 20 May 2003 08:56:02 GMT</pubDate>
<guid>http://liftoff.msfc.nasa.gov/2003/05/20.html#item570</guid>
</item>
</code></pre>
<p>To this:</p>
<pre><code>@ClassXmlNodeName("item")
public class Item {
private String title;
private String link;
private String description;
private String pubDate;
private String guid;
//getters and settings go here...
}
</code></pre>
<p>Using:</p>
<pre><code>Rss rss = new Rss();
XmlBinderFactory.newInstance().bind(rss, new File("Rss2Test.xml"));
</code></pre>
<p>Problem: It relies on annotations, so no good for Java 1.4</p>
<p><b>jYaml</b>
<a href="http://jyaml.sourceforge.net/" rel="nofollow noreferrer"><a href="http://jyaml.sourceforge.net/" rel="nofollow noreferrer">http://jyaml.sourceforge.net/</a></a></p>
<p>Seamlessly binds this:</p>
<pre><code>--- !user
name: Felipe Coury
password: felipe
modules:
- !module
id: 1
name: Main Menu
admin: !user
name: Admin
password: password
</code></pre>
<p>To this:</p>
<pre><code>public class User {
private String name;
private String password;
private List modules;
}
public class Module {
private int id;
private String name;
private User admin;
}
</code></pre>
<p>Using:</p>
<pre><code>YamlReader reader = new YamlReader(new FileReader("example.yaml"));
reader.getConfig().setClassTag("user", User.class);
reader.getConfig().setClassTag("module", Module.class);
User user = (User) reader.read(User.class);
</code></pre>
<p>Problem: It won't work with constructors (so no good for immutable objects). I'd have to either change my objects or write custom code por handling the YAML parsing.</p>
<p>Remember that I would like to avoid - as much as I can - writing data descriptors, I'd like something that "just works".</p>
<p>Do you have any suggestions?</p>
|
[
{
"answer_id": 195680,
"author": "questzen",
"author_id": 25210,
"author_profile": "https://Stackoverflow.com/users/25210",
"pm_score": 3,
"selected": true,
"text": "<p>If the objects to be populated are simple beans it may be a good idea to look at apache common's BeanUtils class. The populate() method might suit the described cases. Generally dependency injection frameworks like Spring can be very useful, but that might not be answer for the current problem. For input in form of xml, jibx might be a good alternative, so would be jaxb 1.0.</p>\n"
},
{
"answer_id": 195780,
"author": "marcospereira",
"author_id": 4600,
"author_profile": "https://Stackoverflow.com/users/4600",
"pm_score": 0,
"selected": false,
"text": "<p>Just use XStream (for XML or you could give a try to JSON).</p>\n\n<p>But...</p>\n\n<p>Man, I just can't avoid to think that put the test data outside the unit test itself will leads you to unreadable tests. You will need look two files when reading a test case, you will lose refactoring tools (when changing property's name). Jay Fields can explain it better than me:</p>\n\n<p><a href=\"http://blog.jayfields.com/2007/06/testing-inline-setup.html\" rel=\"nofollow noreferrer\">http://blog.jayfields.com/2007/06/testing-inline-setup.html</a></p>\n\n<p>Kind Regards</p>\n"
},
{
"answer_id": 196243,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 0,
"selected": false,
"text": "<p>You may give it a try to the deefault XMLEncoder/XMLDecoder that was added to the platform in Java1.4</p>\n\n<p>Here's the way I use it.</p>\n\n<pre><code>import java.beans.XMLEncoder;\nimport java.beans.XMLDecoder;\nimport java.io.BufferedInputStream;\nimport java.io.BufferedOutputStream;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\n\npublic class ToXml {\n\n /**\n * Write an object to a file in XML format.\n * @param o - The object to serialize.\n * @param file - The file where to write the object.\n */\n public static void writeObject( Object o, String file ) {\n XMLEncoder e = null;\n try {\n\n e = new XMLEncoder( new BufferedOutputStream( new FileOutputStream(file)));\n\n e.writeObject(o);\n\n }catch( IOException ioe ) {\n throw new RuntimeException( ioe );\n }finally{\n if( e != null ) {\n e.close();\n }\n }\n }\n\n /**\n * Read a xml serialized object from the specified file.\n * @param file - The file where the serialized xml version of the object is.\n * @return The object represented by the xmlfile.\n */\n public static Object readObject( String file ){\n XMLDecoder d = null;\n try {\n\n d = new XMLDecoder( new BufferedInputStream( new FileInputStream(file)));\n\n return d.readObject();\n\n }catch( IOException ioe ) {\n throw new RuntimeException( ioe );\n }finally{\n if( d != null ) {\n d.close();\n }\n }\n }\n</code></pre>\n\n<p>}</p>\n\n<p>It's easy, is simple, is in the core libraries. </p>\n\n<p>You just have to write the load mechanism. </p>\n\n<p>I have this swing app that loads data from a remote EJB in 5 - 10 secs. What I do is to store the previous session in XML like this and when the app loads it has all the data from the previous session in less than 1 sec. </p>\n\n<p>While the user start to work with the app, a background thread fetches those elements that have changed since the last session. </p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14540/"
] |
I need a way to bind POJO objects to an external entity, that could be XML, YAML, structured text or anything easy to write and maintain in order to create Mock data for unit testing and TDD. Below are some libraries I tried, but the main problems with them were that I am stuck (for at least more 3 months) to Java 1.4. I'd like any insights on what I could use instead, with as low overhead and upfront setup (like using Schemas or DTDs, for instance) as possible and without complex XML. Here are the libraries I really like (but that apparently doesn't work with 1.4 or doesn't support constructors - you gotta have setters):
**RE-JAXB (or Really Easy Java XML Bindings)**
[<http://jvalentino.blogspot.com/2008/07/in-response-to-easiest-java-xml-binding.html>](http://jvalentino.blogspot.com/2008/07/in-response-to-easiest-java-xml-binding.html)
[<http://sourceforge.net/projects/rejaxb/>](http://sourceforge.net/projects/rejaxb/)
Seamlessy binds this:
```
<item>
<title>Astronauts' Dirty Laundry</title>
<link>http://liftoff.msfc.nasa.gov/news/2003/news-laundry.asp</link>
<description>Compared to earlier spacecraft, the International Space
Station has many luxuries, but laundry facilities are not one of them.
Instead, astronauts have other options.</description>
<pubDate>Tue, 20 May 2003 08:56:02 GMT</pubDate>
<guid>http://liftoff.msfc.nasa.gov/2003/05/20.html#item570</guid>
</item>
```
To this:
```
@ClassXmlNodeName("item")
public class Item {
private String title;
private String link;
private String description;
private String pubDate;
private String guid;
//getters and settings go here...
}
```
Using:
```
Rss rss = new Rss();
XmlBinderFactory.newInstance().bind(rss, new File("Rss2Test.xml"));
```
Problem: It relies on annotations, so no good for Java 1.4
**jYaml**
[<http://jyaml.sourceforge.net/>](http://jyaml.sourceforge.net/)
Seamlessly binds this:
```
--- !user
name: Felipe Coury
password: felipe
modules:
- !module
id: 1
name: Main Menu
admin: !user
name: Admin
password: password
```
To this:
```
public class User {
private String name;
private String password;
private List modules;
}
public class Module {
private int id;
private String name;
private User admin;
}
```
Using:
```
YamlReader reader = new YamlReader(new FileReader("example.yaml"));
reader.getConfig().setClassTag("user", User.class);
reader.getConfig().setClassTag("module", Module.class);
User user = (User) reader.read(User.class);
```
Problem: It won't work with constructors (so no good for immutable objects). I'd have to either change my objects or write custom code por handling the YAML parsing.
Remember that I would like to avoid - as much as I can - writing data descriptors, I'd like something that "just works".
Do you have any suggestions?
|
If the objects to be populated are simple beans it may be a good idea to look at apache common's BeanUtils class. The populate() method might suit the described cases. Generally dependency injection frameworks like Spring can be very useful, but that might not be answer for the current problem. For input in form of xml, jibx might be a good alternative, so would be jaxb 1.0.
|
195,641 |
<p>During the installation of Apache2 I got the following message into cmd window:</p>
<blockquote>
<p>Installing the Apache2.2 service The
Apache2.2 service is successfully
installed. Testing httpd.conf....</p>
<p>Errors reported here must be corrected
before the service can be started.
httpd.exe: Could not reliably
determine the server's fully qualified
domain name , using 192.168.1.3 for
ServerName (OS 10048)Only one usage of
each socket address (protocol/network
address/port) is normally permitted.
: make_sock: could not bind to address
0.0.0.0:80 no listening sockets available, shutting down Unable to
open logs Note the errors or messages
above, and press the key to
exit. 24...</p>
</blockquote>
<p>and after installing everything look fine, but it isn't. If I try to start service I got the following message:</p>
<blockquote>
<p>Windows could not start the Apache2 on
Local Computer. For more information,
review the System Event Log. If this
is a non-Micorsoft service, contact
the service vendor, and refer to
service-specific error code 1.</p>
</blockquote>
<p>Apach2 version is 2.2.9</p>
<p>Does anyone have the same problem, or could help me.</p>
|
[
{
"answer_id": 195654,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 8,
"selected": true,
"text": "<p>There is some other program listening on port 80, usual suspects are</p>\n\n<ol>\n<li>Skype (Listens on port 80)</li>\n<li>NOD32 (Add Apache to the IMON exceptions' list for it to allow apache to bind)</li>\n<li>Some other antivirus (Same as above)</li>\n</ol>\n\n<p>Way to correct it is either shutting down the program that's using the port 80 or configure it to use a different port or configure Apache to listen on a different port with the Listen directive in httpd.conf. In the case of antivirus configure the antivirus to allow Apache to bind on the port you have chosen.</p>\n\n<p>Way to diagnose which app, if any, has bound to port 80 is run the netstat with those options, look for :80 next to the local IP address (second column) and find the PID (last column). Then, on the task manager you can find which process has the PID you got in the previous step. (You might need to add the PID column on the task manager)</p>\n\n<p>C:\\Users\\vinko>netstat -ao -p tcp</p>\n\n<pre><code>Conexiones activas\n\n Proto Dirección local Dirección remota Estado PID\n TCP 127.0.0.1:1110 127.0.0.1:51373 TIME_WAIT 0\n TCP 127.0.0.1:1110 127.0.0.1:51379 TIME_WAIT 0\n TCP 127.0.0.1:1110 127.0.0.1:51381 ESTABLISHED 388\n TCP 127.0.0.1:1110 127.0.0.1:51382 TIME_WAIT 0\n TCP 127.0.0.1:1110 127.0.0.1:51479 TIME_WAIT 0\n TCP 127.0.0.1:1110 127.0.0.1:51481 TIME_WAIT 0\n TCP 127.0.0.1:1110 127.0.0.1:51483 TIME_WAIT 0\n TCP 127.0.0.1:1110 127.0.0.1:51485 ESTABLISHED 388\n TCP 127.0.0.1:1110 127.0.0.1:51487 TIME_WAIT 0\n TCP 127.0.0.1:1110 127.0.0.1:51489 ESTABLISHED 388\n TCP 127.0.0.1:51381 127.0.0.1:1110 ESTABLISHED 5168\n TCP 127.0.0.1:51485 127.0.0.1:1110 ESTABLISHED 5168\n TCP 127.0.0.1:51489 127.0.0.1:1110 ESTABLISHED 5168\n TCP 127.0.0.1:59264 127.0.0.1:59265 ESTABLISHED 5168\n TCP 127.0.0.1:59265 127.0.0.1:59264 ESTABLISHED 5168\n TCP 127.0.0.1:59268 127.0.0.1:59269 ESTABLISHED 5168\n TCP 127.0.0.1:59269 127.0.0.1:59268 ESTABLISHED 5168\n TCP 192.168.1.34:51278 192.168.1.33:445 ESTABLISHED 4\n TCP 192.168.1.34:51383 67.199.15.132:80 ESTABLISHED 388\n TCP 192.168.1.34:51486 66.102.9.18:80 ESTABLISHED 388\n TCP 192.168.1.34:51490 74.125.4.20:80 ESTABLISHED 388\n</code></pre>\n\n<p>If you want to Disable Skype from listening on port 80 and 443, you can follow the link <a href=\"http://www.mydigitallife.info/disable-skype-from-using-opening-and-listening-on-port-80-and-443-on-local-computer/\" rel=\"noreferrer\">http://www.mydigitallife.info/disable-skype-from-using-opening-and-listening-on-port-80-and-443-on-local-computer/</a></p>\n"
},
{
"answer_id": 431032,
"author": "user46795",
"author_id": 46795,
"author_profile": "https://Stackoverflow.com/users/46795",
"pm_score": 3,
"selected": false,
"text": "<p>I had the same problem. I checked netstat, other processes running, firewall and changed httpd.conf, stopped antivirus, But all my efforts were in vain. :(</p>\n\n<p>So finally the solution was to stop the IIS. And it worked :)</p>\n\n<p>I guess IIS and apache cant work together. If anybody know any work around let us know.</p>\n"
},
{
"answer_id": 1036791,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>the better way to resolve the issue is change the port number in Apache2\\conf\\httpd.conf . Change the port number as fallows::: Listen 8888 and ServerName machinename:8888 .Restart the Apache server after changing the port number.</p>\n"
},
{
"answer_id": 1406451,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks for the help guys. I found another culprit. Recently SimplifyMedia added a photo sharing option. Apparently it too uses port 80 and prevented Apache from starting up. I hope this helps someone out.</p>\n"
},
{
"answer_id": 2806014,
"author": "raajesh",
"author_id": 337633,
"author_profile": "https://Stackoverflow.com/users/337633",
"pm_score": 0,
"selected": false,
"text": "<p>Me also coming the same problem. The solution is goto add or remove programes then click the turn windows features on or off. Turn off the IIS. That is turn off the 'Internet information services' and 'Internet information service removable web core'. I chosed the remaining features are on. Computer will ask to restart the system. Restart ur computer and then install the apache http server. I got it. Server succesfully working...</p>\n"
},
{
"answer_id": 3235672,
"author": "vijay",
"author_id": 390284,
"author_profile": "https://Stackoverflow.com/users/390284",
"pm_score": 1,
"selected": false,
"text": "<p>Remove apache from Control Panel and delete the apache folder from Program Files and restart the machine, then install apache again. This will solve the problem; if not do the following: Install IIS if not installed, then start IIS and stop it ... Using services start apache service... enjoy apache.</p>\n"
},
{
"answer_id": 4644033,
"author": "jayaram",
"author_id": 569409,
"author_profile": "https://Stackoverflow.com/users/569409",
"pm_score": 2,
"selected": false,
"text": "<p>if appache and IIS both are running at a time then there is a posibility to hang the apache service,,,,</p>\n\n<p>when i stopped all IIS websites once and then restarted apache service and it works for me....Jai...</p>\n"
},
{
"answer_id": 5447224,
"author": "Bruno Bertowski Comp Expert",
"author_id": 678626,
"author_profile": "https://Stackoverflow.com/users/678626",
"pm_score": 2,
"selected": false,
"text": "<p>Windows Vista Home Premium operating system issue: The easiest way to resolve the issue is to change the port number in Apache2\\conf\\httpd.conf. </p>\n\n<p>Change the port number at the following lines. 'Listen' from 80 to 8888 and 'ServerName' machinename (ex:localhost) from 80 to 8888. Save then close. Open up Apache Service Monitor and restart service or go to Computer Management > Services and locate Apache 2.2 and start or restart.</p>\n"
},
{
"answer_id": 8549572,
"author": "Tim Santeford",
"author_id": 78685,
"author_profile": "https://Stackoverflow.com/users/78685",
"pm_score": 7,
"selected": false,
"text": "<p>I hope this helps others with this error.</p>\n\n<p><strong>Run the httpd.exe from the command line</strong> to get an accurate description of the problem.</p>\n\n<p>I had the same error message and it turned out to be a miss configured ServerRoot path. Even after running setup_xampp.bat the httpd.conf had the wrong path.</p>\n\n<p>My error.log was empty and starting the service does not give an informative error message.</p>\n"
},
{
"answer_id": 9518506,
"author": "mickburkejnr",
"author_id": 395729,
"author_profile": "https://Stackoverflow.com/users/395729",
"pm_score": 1,
"selected": false,
"text": "<p>I've had this problem twice. The first problem was fixed using the marked answer on this page (thank you for that). However, the second time proved a bit more difficult.</p>\n\n<p>I found that in my httpd-vhosts.conf file that I made a mistake when assigning the document root to a domain name. Fixing this solved my problem. It is well worth checking (or even reverting to a blank copy) your httpd-vhosts.conf file for any errors and typo's.</p>\n"
},
{
"answer_id": 15378104,
"author": "Aldee",
"author_id": 969645,
"author_profile": "https://Stackoverflow.com/users/969645",
"pm_score": 1,
"selected": false,
"text": "<p>if you are using windows os and believe that skype is not the suspect, then you might want to check the task manager and check the \"Show processes from all users\" and make sure that there is NO entry for httpd.exe. Otherwise, end its process. That solves my problem.</p>\n"
},
{
"answer_id": 17584901,
"author": "Gopinath Guru",
"author_id": 2546492,
"author_profile": "https://Stackoverflow.com/users/2546492",
"pm_score": 2,
"selected": false,
"text": "<p>Follow this step it will works fine.\n Go to <strong>Control panel</strong>--><strong>Programs and features</strong>-->click Turn <strong>Windows features on and off</strong>--> see <strong>IIS is Checked Or Not</strong> If checked please unckeck <strong>IIS</strong> and restart the computer.After that Open services see <strong>Web Deployement Agent</strong> Service status if its started please stop.And also see <strong>WampAppache and WampSqlID</strong> if its not started please start manually. it will works for me.</p>\n"
},
{
"answer_id": 18257422,
"author": "chunguiw",
"author_id": 2582783,
"author_profile": "https://Stackoverflow.com/users/2582783",
"pm_score": 2,
"selected": false,
"text": "<p>Hi i also meet this problem today.\nAnd the log error in the Event viewer is as following\nThe Apache service named reported the following error:</p>\n\n<blockquote>\n <blockquote>\n <blockquote>\n <p>1.Wrapper php-cgi.exe cannot be accessed: (720005)Access is denied. </p>\n \n <p>2.apache service monitor:the requested operation has failed</p>\n </blockquote>\n </blockquote>\n</blockquote>\n\n<p>It is actual the access problem.So the solution as flowing is help me\nchange the php-cgi.exe security properties</p>\n\n<ul>\n<li><p><em><strong>not inheit from parent the permission...</em></strong></p></li>\n<li><p><em><strong>please add the everyone user</em></strong> </p></li>\n</ul>\n"
},
{
"answer_id": 18437304,
"author": "Atul Darne",
"author_id": 996695,
"author_profile": "https://Stackoverflow.com/users/996695",
"pm_score": 1,
"selected": false,
"text": "<p>Yes , i had to change the port :80 to :90 as port :80 was busy by some other system resource.</p>\n\n<p>You can see the logs in the folder of Apache2.2\\logs</p>\n\n<p>Thanks,</p>\n"
},
{
"answer_id": 20168079,
"author": "Junior Mayhé",
"author_id": 66708,
"author_profile": "https://Stackoverflow.com/users/66708",
"pm_score": 1,
"selected": false,
"text": "<p>Always double check httpd.conf to see if document root is correctly pointing to an existing folder</p>\n\n<pre><code>#if you have c:\\your-main-folder\\www\\\nDocumentRoot \"c:/your-main-folder/www/\" \n\n#if you have c:\\your-main-folder\\www\\sub-folder\\\nDocumentRoot \"c:/your-main-folder/www/sub-folder/\" \n</code></pre>\n\n<p><code>DocumentRoot</code> points to a folder that must exist in your drive.</p>\n"
},
{
"answer_id": 22267587,
"author": "FARAZ",
"author_id": 2800626,
"author_profile": "https://Stackoverflow.com/users/2800626",
"pm_score": 1,
"selected": false,
"text": "<p>I had the same issue. when i restarted my wamp it turns to Yellow color icon but not green.\nIn services i stop all sql server services. after that it works for me..</p>\n\n<ul>\n<li>Two thinks that should must be take care. \n1 ) port should be different\n2 ) stop those services which can be on port 80</li>\n</ul>\n"
},
{
"answer_id": 29900265,
"author": "John",
"author_id": 606371,
"author_profile": "https://Stackoverflow.com/users/606371",
"pm_score": 2,
"selected": false,
"text": "<p>Run the httpd.exe from the command line, as Tim mentioned. The path to PostgreSQL changed, nothing else was running on Port 80 and I didn't see anything in the <code>error.log</code> file.</p>\n\n<p>I clone my boot drive/partition once the base is setup so I don't have to spend three days installing and retweaking everything. Turns I had reinstalled my WAPP stack and used very specific names/versions for PostgreSQL. <strong>Windows will not return a specific error message unless you run the command from the command line.</strong></p>\n"
},
{
"answer_id": 37505142,
"author": "PapaHotelPapa",
"author_id": 2859605,
"author_profile": "https://Stackoverflow.com/users/2859605",
"pm_score": 0,
"selected": false,
"text": "<p>For me, this was the result of having set the document root (in <code>httpd.conf</code>) to a directory that did not exist (I had just emptied htdocs of a previous project). </p>\n"
},
{
"answer_id": 44534650,
"author": "eddyparkinson",
"author_id": 1378888,
"author_profile": "https://Stackoverflow.com/users/1378888",
"pm_score": 0,
"selected": false,
"text": "<p>Windows 10 - administrator account </p>\n\n<p>I needed to switch the account to an admin type account, in windows services</p>\n\n<pre><code>httpd.exe -k install\n</code></pre>\n\n<p>fails to add setup with enough user rights.</p>\n"
},
{
"answer_id": 59232670,
"author": "Abhishek D K",
"author_id": 7303415,
"author_profile": "https://Stackoverflow.com/users/7303415",
"pm_score": 1,
"selected": false,
"text": "<p>i faced the same issue, in my case i needed to add module in httpd.conf<br>\nthe file was incomplete with incorrect keywords ( like LoadModule )<br>\n go to command line, go to <strong>C:\\Apache24\\bin</strong> </p>\n\n<p>C:\\Apache24\\bin <strong>> httpd.exe</strong> </p>\n\n<p>the reason for the error can be known from the output of the above command</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16039/"
] |
During the installation of Apache2 I got the following message into cmd window:
>
> Installing the Apache2.2 service The
> Apache2.2 service is successfully
> installed. Testing httpd.conf....
>
>
> Errors reported here must be corrected
> before the service can be started.
> httpd.exe: Could not reliably
> determine the server's fully qualified
> domain name , using 192.168.1.3 for
> ServerName (OS 10048)Only one usage of
> each socket address (protocol/network
> address/port) is normally permitted.
> : make\_sock: could not bind to address
> 0.0.0.0:80 no listening sockets available, shutting down Unable to
> open logs Note the errors or messages
> above, and press the key to
> exit. 24...
>
>
>
and after installing everything look fine, but it isn't. If I try to start service I got the following message:
>
> Windows could not start the Apache2 on
> Local Computer. For more information,
> review the System Event Log. If this
> is a non-Micorsoft service, contact
> the service vendor, and refer to
> service-specific error code 1.
>
>
>
Apach2 version is 2.2.9
Does anyone have the same problem, or could help me.
|
There is some other program listening on port 80, usual suspects are
1. Skype (Listens on port 80)
2. NOD32 (Add Apache to the IMON exceptions' list for it to allow apache to bind)
3. Some other antivirus (Same as above)
Way to correct it is either shutting down the program that's using the port 80 or configure it to use a different port or configure Apache to listen on a different port with the Listen directive in httpd.conf. In the case of antivirus configure the antivirus to allow Apache to bind on the port you have chosen.
Way to diagnose which app, if any, has bound to port 80 is run the netstat with those options, look for :80 next to the local IP address (second column) and find the PID (last column). Then, on the task manager you can find which process has the PID you got in the previous step. (You might need to add the PID column on the task manager)
C:\Users\vinko>netstat -ao -p tcp
```
Conexiones activas
Proto Dirección local Dirección remota Estado PID
TCP 127.0.0.1:1110 127.0.0.1:51373 TIME_WAIT 0
TCP 127.0.0.1:1110 127.0.0.1:51379 TIME_WAIT 0
TCP 127.0.0.1:1110 127.0.0.1:51381 ESTABLISHED 388
TCP 127.0.0.1:1110 127.0.0.1:51382 TIME_WAIT 0
TCP 127.0.0.1:1110 127.0.0.1:51479 TIME_WAIT 0
TCP 127.0.0.1:1110 127.0.0.1:51481 TIME_WAIT 0
TCP 127.0.0.1:1110 127.0.0.1:51483 TIME_WAIT 0
TCP 127.0.0.1:1110 127.0.0.1:51485 ESTABLISHED 388
TCP 127.0.0.1:1110 127.0.0.1:51487 TIME_WAIT 0
TCP 127.0.0.1:1110 127.0.0.1:51489 ESTABLISHED 388
TCP 127.0.0.1:51381 127.0.0.1:1110 ESTABLISHED 5168
TCP 127.0.0.1:51485 127.0.0.1:1110 ESTABLISHED 5168
TCP 127.0.0.1:51489 127.0.0.1:1110 ESTABLISHED 5168
TCP 127.0.0.1:59264 127.0.0.1:59265 ESTABLISHED 5168
TCP 127.0.0.1:59265 127.0.0.1:59264 ESTABLISHED 5168
TCP 127.0.0.1:59268 127.0.0.1:59269 ESTABLISHED 5168
TCP 127.0.0.1:59269 127.0.0.1:59268 ESTABLISHED 5168
TCP 192.168.1.34:51278 192.168.1.33:445 ESTABLISHED 4
TCP 192.168.1.34:51383 67.199.15.132:80 ESTABLISHED 388
TCP 192.168.1.34:51486 66.102.9.18:80 ESTABLISHED 388
TCP 192.168.1.34:51490 74.125.4.20:80 ESTABLISHED 388
```
If you want to Disable Skype from listening on port 80 and 443, you can follow the link <http://www.mydigitallife.info/disable-skype-from-using-opening-and-listening-on-port-80-and-443-on-local-computer/>
|
195,648 |
<p>What's an example of something dangerous that would not be caught by the code below?</p>
<p>EDIT: After some of the comments I added another line, commented below. See Vinko's comment in David Grant's answer. So far only Vinko has answered the question, which asks for specific examples that would slip through this function. Vinko provided one, but I've edited the code to close that hole. If another of you can think of another specific example, you'll have my vote!</p>
<pre><code>public static string strip_dangerous_tags(string text_with_tags)
{
string s = Regex.Replace(text_with_tags, @"<script", "<scrSAFEipt", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"</script", "</scrSAFEipt", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"<object", "</objSAFEct", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"</object", "</obSAFEct", RegexOptions.IgnoreCase);
// ADDED AFTER THIS QUESTION WAS POSTED
s = Regex.Replace(s, @"javascript", "javaSAFEscript", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onabort", "onSAFEabort", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onblur", "onSAFEblur", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onchange", "onSAFEchange", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onclick", "onSAFEclick", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"ondblclick", "onSAFEdblclick", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onerror", "onSAFEerror", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onfocus", "onSAFEfocus", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onkeydown", "onSAFEkeydown", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onkeypress", "onSAFEkeypress", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onkeyup", "onSAFEkeyup", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onload", "onSAFEload", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onmousedown", "onSAFEmousedown", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onmousemove", "onSAFEmousemove", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onmouseout", "onSAFEmouseout", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onmouseup", "onSAFEmouseup", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onmouseup", "onSAFEmouseup", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onreset", "onSAFEresetK", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onresize", "onSAFEresize", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onselect", "onSAFEselect", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onsubmit", "onSAFEsubmit", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onunload", "onSAFEunload", RegexOptions.IgnoreCase);
return s;
}
</code></pre>
|
[
{
"answer_id": 195662,
"author": "David Grant",
"author_id": 26829,
"author_profile": "https://Stackoverflow.com/users/26829",
"pm_score": 2,
"selected": false,
"text": "<pre><code><a href=\"javascript:document.writeln('on' + 'unload' + ' and more malicious stuff here...');\">example</a>\n</code></pre>\n\n<p>Any time you can write a string to the document, a big door swings open.</p>\n\n<p>There are myriad places to inject malicious things into HTML/JavaScript. For this reason, Facebook didn't initially allow JavaScript in their applications platform. Their solution was to later implement a markup/script compiler that allows them to seriously filter out the bad stuff.</p>\n\n<p>As said already, whitelist a few tags and attributes and strip out everything else. Don't blacklist a few known malicious attributes and allow everything else.</p>\n"
},
{
"answer_id": 195670,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": false,
"text": "<p>As David shows, there's no easy way to protect with just some regexes you can always forget something, like javascript: in your case. You better escape the HTML entities on output. There is a lot of discussion about the best way to do this, depending on what you actually need to allow, but <strong>what's certain is that your function is not enough</strong>.</p>\n\n<p>Jeff has talked a bit about this <a href=\"http://www.codinghorror.com/blog/archives/001167.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 195671,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 2,
"selected": false,
"text": "<p>Although I can't provide a specific example of why not, I am going to go ahead and outright say no. This is more on principal. Regex's are an amazing tool but they should only be used for certain problems. They are fantastic for data matching and searching. </p>\n\n<p>They are not however a good tool for security. It is too easy to mess up a regex and have it be only partially correct. Hackers can find lots of wiggle room inside a poorly or even well constructed regex. I would try another avenue to prevent cross site scripting. </p>\n"
},
{
"answer_id": 195677,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 3,
"selected": false,
"text": "<p>You're much better off turning all <code><</code> into <code>&lt;</code> and all <code>></code> into <code>&gt;</code>, then converting acceptable tags back. In other words, whitelist, don't blacklist.</p>\n"
},
{
"answer_id": 195687,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 1,
"selected": false,
"text": "<p>Another vote for whitelisting. But it looks like you're going about this the wrong way. The way <em>I</em> do it, is to parse the HTML into a tag tree. If the tag you're parsing is in the whitelist, give it a tree node, and parse on. Same goes for its attributes.</p>\n\n<p>Dropped attributes are just dropped. Everything else is HTML-escaped literal content.</p>\n\n<p>And the bonus of this route is because you're effectively regenerating all the markup, it's all completely valid markup! (I hate it when people leave comments and they screw up the validation/design.)</p>\n\n<p><strong>Re \"I can't whitelist\" (para)</strong>: Blacklisting is a maintenance-heavy approach. You'll have to keep an eye on new exploits and make sure your covered. It's a <em>miserable</em> existence. <strong><em>Just do it right once and you'll never need to touch it again.</em></strong></p>\n"
},
{
"answer_id": 195703,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 7,
"selected": true,
"text": "<h2>It's never enough – whitelist, don't blacklist</h2>\n\n<p>For example <code>javascript:</code> pseudo-URL can be obfuscated with HTML entities, you've forgotten about <code><embed></code> and there are dangerous CSS properties like <code>behavior</code> and <code>expression</code> in IE. </p>\n\n<p>There are <a href=\"http://ha.ckers.org/xss.html\" rel=\"noreferrer\">countless ways</a> to evade filters and such approach is bound to fail. Even if you find and block all exploits possible today, new unsafe elements and attributes may be added in the future.</p>\n\n<p>There are only two good ways to secure HTML:</p>\n\n<ul>\n<li><p>convert it to text by replacing every <code><</code> with <code>&lt;</code>.<br>\nIf you want to allow users enter formatted text, you can use your own markup (e.g. markdown like SO does).</p></li>\n<li><p>parse HTML into DOM, check every element and attribute and remove everything that is not whitelisted.<br>\nYou will also need to check contents of allowed attributes like <code>href</code> (make sure that URLs use safe protocol, block all unknown protocols).<br>\nOnce you've cleaned up the DOM, generate new, valid HTML from it. Never work on HTML as if it was text, because invalid markup, comments, entities, etc. can easily fool your filter.</p></li>\n</ul>\n\n<p>Also make sure your page declares its encoding, because there are exploits that take advantage of browsers auto-detecting wrong encoding.</p>\n"
},
{
"answer_id": 195712,
"author": "Rich",
"author_id": 22003,
"author_profile": "https://Stackoverflow.com/users/22003",
"pm_score": 2,
"selected": false,
"text": "<p>Whitespace makes you vulnerable. <a href=\"http://lookout.net/2008/08/26/advisory-attack-of-the-mongolian-space-evaders-and-other-medieval-xss-vectors/\" rel=\"nofollow noreferrer\">Read this</a>.</p>\n"
},
{
"answer_id": 198074,
"author": "tduehr",
"author_id": 20486,
"author_profile": "https://Stackoverflow.com/users/20486",
"pm_score": 2,
"selected": false,
"text": "<p>Take a look at the XSS cheatsheet at <a href=\"http://ha.ckers.org/xss.html\" rel=\"nofollow noreferrer\">http://ha.ckers.org/xss.html</a> it's not a complete list but a good start.</p>\n\n<p>One that comes to mind is <img src=\"http://badsite.com/javascriptfile\" /></p>\n\n<p>You also forgot onmouseover, and the style tag.</p>\n\n<p>The easiest thing to do really is <strong>entity escaping</strong>. If the vector can't render properly in the first place, an incomplete blacklist won't matter.</p>\n"
},
{
"answer_id": 198208,
"author": "Sundar R",
"author_id": 8127,
"author_profile": "https://Stackoverflow.com/users/8127",
"pm_score": 1,
"selected": false,
"text": "<p>From a different point of view, what happens when someone wants to have 'javascript' or 'functionload' or 'visionblurred' in what they submit? This can happen in most places for any number of reasons... From what I understand, those will become 'javaSAFEscript', 'functionSAFEload' and 'visionSAFEblurred'(!!).</p>\n\n<p>If this might apply to you, and you're stuck with the blacklist approach, be sure to use the exact matching regexes to avoid annoying the user. In other words, be at the optimum point between security and usability, compromising either as little as possible.</p>\n"
},
{
"answer_id": 430133,
"author": "Mike Samuel",
"author_id": 20394,
"author_profile": "https://Stackoverflow.com/users/20394",
"pm_score": 2,
"selected": false,
"text": "<p>As an example of an attack that makes it through this:</p>\n\n<pre><code> <div style=\"color: expression('alert(4)')\">\n</code></pre>\n\n<p>Shameless plug:\nThe Caja project defines whitelists of HTML elements and attributes so that it can control how and when scripts in HTML get executed.</p>\n\n<p>See the project at <a href=\"http://code.google.com/p/google-caja/\" rel=\"nofollow noreferrer\">http://code.google.com/p/google-caja/</a>\nand the whitelists are the JSON files in\n<a href=\"http://code.google.com/p/google-caja/source/browse/#svn/trunk/src/com/google/caja/lang/html\" rel=\"nofollow noreferrer\">http://code.google.com/p/google-caja/source/browse/#svn/trunk/src/com/google/caja/lang/html</a>\nand\n<a href=\"http://code.google.com/p/google-caja/source/browse/#svn/trunk/src/com/google/caja/lang/css\" rel=\"nofollow noreferrer\">http://code.google.com/p/google-caja/source/browse/#svn/trunk/src/com/google/caja/lang/css</a></p>\n"
},
{
"answer_id": 11800969,
"author": "mholly",
"author_id": 1013424,
"author_profile": "https://Stackoverflow.com/users/1013424",
"pm_score": 2,
"selected": false,
"text": "<p>I still have not figured out why developers want to massage bad input into good input with a regular expression replace. Unless your site is a blog and needs to allow embedded html or javascript or any other sort of code, reject the bad input and return an error. The old saying is Garbage In - Garbage Out, why would you want to take in a nice steaming pile of poo and make it edible?</p>\n\n<p>If your site is not internationalized, why accept any unicode?</p>\n\n<p>If your site only does POST, why accept any URL encoded values?</p>\n\n<p>Why accept any hex? Why accept html entities? What user inputs '&#x0A' or '&quot;' ?</p>\n\n<p>As for regular expressions, using them is fine, however, you do not have to code a separate regular expression for the full attack string. You can reject many different attack signatures with just a few well constructed regex patterns:</p>\n\n<pre><code>patterns.put(\"xssAttack1\", Pattern.compile(\"<script\",Pattern.CASE_INSENSITIVE) );\npatterns.put(\"xssAttack2\", Pattern.compile(\"SRC=\",Pattern.CASE_INSENSITIVE) );\npatterns.put(\"xssAttack3\", Pattern.compile(\"pt:al\",Pattern.CASE_INSENSITIVE) );\npatterns.put(\"xssAttack4\", Pattern.compile(\"xss\",Pattern.CASE_INSENSITIVE) );\n\n<FRAMESET><FRAME SRC=\"javascript:alert('XSS');\"></FRAMESET>\n<DIV STYLE=\"width: expression(alert('XSS'));\">\n<LINK REL=\"stylesheet\" HREF=\"javascript:alert('XSS');\">\n<IMG SRC=\"jav ascript:alert('XSS');\"> // hmtl allows embedded tabs...\n<IMG SRC=\"jav&#x0A;ascript:alert('XSS');\"> // hmtl allows embedded newline...\n<IMG SRC=\"jav&#x0D;ascript:alert('XSS');\"> // hmtl allows embedded carriage return...\n</code></pre>\n\n<p>Notice that my patterns are not the full attack signature, just enough to detect if the value is malicious. It is unlikely that a user would enter 'SRC=' or 'pt:al' This allows my regex patterns to detect unknown attacks that have any of these tokens in them.</p>\n\n<p>Many developers will tell you that you cannot protect a site with a blacklist. Since the set of attacks is infinite, that is basically true, however, if you parse the entire request (params, param values, headers, cookies) with a blacklist constructed based on tokens, you will be able to figure out what is an attack and what is valid. Remember, the attacker will most likely be shotgunning exploits at you from a tool. If you have properly hardened your server, he will not know what environment you are running and will have to blast you with lists of exploits. If he pesters you enough, put the attacker, or his IP on a quarantine list. If he has a tool with 50k exploits ready to hit your site, how long will it take him if you quarantine his id or ip for 30 min for each violation? Admittedly there is still exposure if the attacker uses a botnet to multiplex his attack. Still your site ends up being a much tougher nugget to crack.</p>\n\n<p>Now having checked the entire request for malicious content you can now use whitelist type checks against length, referential/ logical, naming to determine validity of the request</p>\n\n<p>Don't forget to implement some sort of CSRF protection. Maybe a honey token, and check the user-agent string from previous requests to see if it has changed. </p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9328/"
] |
What's an example of something dangerous that would not be caught by the code below?
EDIT: After some of the comments I added another line, commented below. See Vinko's comment in David Grant's answer. So far only Vinko has answered the question, which asks for specific examples that would slip through this function. Vinko provided one, but I've edited the code to close that hole. If another of you can think of another specific example, you'll have my vote!
```
public static string strip_dangerous_tags(string text_with_tags)
{
string s = Regex.Replace(text_with_tags, @"<script", "<scrSAFEipt", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"</script", "</scrSAFEipt", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"<object", "</objSAFEct", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"</object", "</obSAFEct", RegexOptions.IgnoreCase);
// ADDED AFTER THIS QUESTION WAS POSTED
s = Regex.Replace(s, @"javascript", "javaSAFEscript", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onabort", "onSAFEabort", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onblur", "onSAFEblur", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onchange", "onSAFEchange", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onclick", "onSAFEclick", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"ondblclick", "onSAFEdblclick", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onerror", "onSAFEerror", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onfocus", "onSAFEfocus", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onkeydown", "onSAFEkeydown", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onkeypress", "onSAFEkeypress", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onkeyup", "onSAFEkeyup", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onload", "onSAFEload", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onmousedown", "onSAFEmousedown", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onmousemove", "onSAFEmousemove", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onmouseout", "onSAFEmouseout", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onmouseup", "onSAFEmouseup", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onmouseup", "onSAFEmouseup", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onreset", "onSAFEresetK", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onresize", "onSAFEresize", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onselect", "onSAFEselect", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onsubmit", "onSAFEsubmit", RegexOptions.IgnoreCase);
s = Regex.Replace(s, @"onunload", "onSAFEunload", RegexOptions.IgnoreCase);
return s;
}
```
|
It's never enough – whitelist, don't blacklist
----------------------------------------------
For example `javascript:` pseudo-URL can be obfuscated with HTML entities, you've forgotten about `<embed>` and there are dangerous CSS properties like `behavior` and `expression` in IE.
There are [countless ways](http://ha.ckers.org/xss.html) to evade filters and such approach is bound to fail. Even if you find and block all exploits possible today, new unsafe elements and attributes may be added in the future.
There are only two good ways to secure HTML:
* convert it to text by replacing every `<` with `<`.
If you want to allow users enter formatted text, you can use your own markup (e.g. markdown like SO does).
* parse HTML into DOM, check every element and attribute and remove everything that is not whitelisted.
You will also need to check contents of allowed attributes like `href` (make sure that URLs use safe protocol, block all unknown protocols).
Once you've cleaned up the DOM, generate new, valid HTML from it. Never work on HTML as if it was text, because invalid markup, comments, entities, etc. can easily fool your filter.
Also make sure your page declares its encoding, because there are exploits that take advantage of browsers auto-detecting wrong encoding.
|
195,655 |
<p>Is it possible to copy a single file to multiple directories using the cp command ?</p>
<p>I tried the following , which did not work: </p>
<pre><code>cp file1 /foo/ /bar/
cp file1 {/foo/,/bar}
</code></pre>
<p>I know it's possible using a for loop, or find. But is it possible using the gnu cp command?</p>
|
[
{
"answer_id": 195663,
"author": "moonshadow",
"author_id": 11834,
"author_profile": "https://Stackoverflow.com/users/11834",
"pm_score": 8,
"selected": true,
"text": "<p>No, <code>cp</code> can copy multiple sources but will only copy to a single destination. You need to arrange to invoke <code>cp</code> multiple times - once per destination - for what you want to do; using, as you say, a loop or some other tool.</p>\n"
},
{
"answer_id": 195972,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 9,
"selected": false,
"text": "<p>You can't do this with <code>cp</code> alone but you can combine <code>cp</code> with <code>xargs</code>:</p>\n\n<pre><code>echo dir1 dir2 dir3 | xargs -n 1 cp file1\n</code></pre>\n\n<p>Will copy <code>file1</code> to <code>dir1</code>, <code>dir2</code>, and <code>dir3</code>. <code>xargs</code> will call <code>cp</code> 3 times to do this, see the man page for <code>xargs</code> for details.</p>\n"
},
{
"answer_id": 1374908,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Another way is to use cat and tee as follows:</p>\n\n<pre><code>cat <source file> | tee <destination file 1> | tee <destination file 2> [...] > <last destination file>\n</code></pre>\n\n<p>I think this would be pretty inefficient though, since the job would be split among several processes (one per destination) and the hard drive would be writing several files at once over different parts of the platter. However if you wanted to write a file out to several different drives, this method would probably be pretty efficient (as all copies could happen concurrently).</p>\n"
},
{
"answer_id": 4803535,
"author": "Paul",
"author_id": 590431,
"author_profile": "https://Stackoverflow.com/users/590431",
"pm_score": 6,
"selected": false,
"text": "<p>Wildcards also work with Roberts code</p>\n\n<pre><code>echo ./fs*/* | xargs -n 1 cp test \n</code></pre>\n"
},
{
"answer_id": 6988966,
"author": "Evgeny",
"author_id": 876687,
"author_profile": "https://Stackoverflow.com/users/876687",
"pm_score": 4,
"selected": false,
"text": "<p>As far as I can see it you can use the following:</p>\n\n<pre><code>ls | xargs -n 1 cp -i file.dat\n</code></pre>\n\n<p>The <code>-i</code> option of <code>cp</code> command means that you will be asked whether to overwrite a file in the current directory with the <code>file.dat</code>. Though it is not a completely automatic solution it worked out for me.</p>\n"
},
{
"answer_id": 9071256,
"author": "deterb",
"author_id": 15585,
"author_profile": "https://Stackoverflow.com/users/15585",
"pm_score": 4,
"selected": false,
"text": "<p>I would use <code>cat</code> and <code>tee</code> based on the answers I saw at <a href=\"https://superuser.com/questions/32630/parallel-file-copy-from-single-source-to-multiple-targets\">https://superuser.com/questions/32630/parallel-file-copy-from-single-source-to-multiple-targets</a> instead of <code>cp</code>.</p>\n\n<p>For example:</p>\n\n<pre><code>cat inputfile | tee outfile1 outfile2 > /dev/null\n</code></pre>\n"
},
{
"answer_id": 13812788,
"author": "Hedgehog",
"author_id": 152860,
"author_profile": "https://Stackoverflow.com/users/152860",
"pm_score": -1,
"selected": false,
"text": "<p>This will copy to the immediate sub-directories, if you want to go deeper, adjust the <code>-maxdepth</code> parameter. </p>\n\n<pre><code>find . -mindepth 1 -maxdepth 1 -type d| xargs -n 1 cp -i index.html\n</code></pre>\n\n<p>If you don't want to copy to all directories, hopefully you can filter the directories you are not interested in. Example copying to all folders starting with <code>a</code></p>\n\n<pre><code>find . -mindepth 1 -maxdepth 1 -type d| grep \\/a |xargs -n 1 cp -i index.html\n</code></pre>\n\n<p>If copying to a arbitrary/disjoint set of directories you'll need Robert Gamble's suggestion.</p>\n"
},
{
"answer_id": 16450615,
"author": "Behrooz",
"author_id": 2364079,
"author_profile": "https://Stackoverflow.com/users/2364079",
"pm_score": -1,
"selected": false,
"text": "<p>For example if you are in the parent directory of you destination folders you can do:</p>\n\n<p>for i in $(ls); do cp sourcefile $i; done</p>\n"
},
{
"answer_id": 18063738,
"author": "ddavison",
"author_id": 1695163,
"author_profile": "https://Stackoverflow.com/users/1695163",
"pm_score": 0,
"selected": false,
"text": "<p>No - you cannot.</p>\n\n<p>I've found on multiple occasions that I could use this functionality so I've made my own tool to do this for me.</p>\n\n<p><a href=\"http://github.com/ddavison/branch\" rel=\"nofollow\">http://github.com/ddavison/branch</a></p>\n\n<p>pretty simple -<br>\n<code>branch myfile dir1 dir2 dir3</code></p>\n"
},
{
"answer_id": 19260399,
"author": "Isaac",
"author_id": 2793556,
"author_profile": "https://Stackoverflow.com/users/2793556",
"pm_score": -1,
"selected": false,
"text": "<p>if you want to copy multiple folders to multiple folders one can do something like this:</p>\n\n<p>echo dir1 dir2 dir3 | xargs -n 1 cp -r /path/toyourdir/{subdir1,subdir2,subdir3}</p>\n"
},
{
"answer_id": 21459130,
"author": "Kristofer",
"author_id": 259485,
"author_profile": "https://Stackoverflow.com/users/259485",
"pm_score": -1,
"selected": false,
"text": "<p>If you need to be specific on into which folders to copy the file you can combine find with one or more greps. For example to replace any occurences of favicon.ico in any subfolder you can use:</p>\n\n<pre><code>find . | grep favicon\\.ico | xargs -n 1 cp -f /root/favicon.ico\n</code></pre>\n"
},
{
"answer_id": 21477075,
"author": "thAAAnos",
"author_id": 616698,
"author_profile": "https://Stackoverflow.com/users/616698",
"pm_score": 3,
"selected": false,
"text": "<p><code>ls -db di*/subdir | xargs -n 1 cp File</code></p>\n\n<p><code>-b</code> in case there is <strong>a space in directory name</strong> otherwise it will be broken as a different item by xargs, had this problem with the echo version</p>\n"
},
{
"answer_id": 22752248,
"author": "Taywee",
"author_id": 1362309,
"author_profile": "https://Stackoverflow.com/users/1362309",
"pm_score": 3,
"selected": false,
"text": "<p>If you want to do it without a forked command:</p>\n\n<p><code>tee <inputfile file2 file3 file4 ... >/dev/null</code></p>\n"
},
{
"answer_id": 23985038,
"author": "alainv",
"author_id": 3697704,
"author_profile": "https://Stackoverflow.com/users/3697704",
"pm_score": 2,
"selected": false,
"text": "<p>Essentially equivalent to the xargs answer, but in case you want parallel execution:</p>\n\n<pre><code>parallel -q cp file1 ::: /foo/ /bar/\n</code></pre>\n\n<p>So, for example, to copy file1 into all subdirectories of current folder (including recursion):</p>\n\n<pre><code>parallel -q cp file1 ::: `find -mindepth 1 -type d`\n</code></pre>\n\n<p>N.B.: This probably only conveys any noticeable speed gains for very specific use cases, e.g. if each target directory is a distinct disk. </p>\n\n<p>It is also functionally similar to the '-P' argument for xargs.</p>\n"
},
{
"answer_id": 26813325,
"author": "Stace Fauske",
"author_id": 4229261,
"author_profile": "https://Stackoverflow.com/users/4229261",
"pm_score": -1,
"selected": false,
"text": "<p>I like to copy a file into multiple directories as such:\n<code>cp file1 /foo/; cp file1 /bar/; cp file1 /foo2/; cp file1 /bar2/</code>\nAnd copying a directory into other directories:\n<code>cp -r dir1/ /foo/; cp -r dir1/ /bar/; cp -r dir1/ /foo2/; cp -r dir1/ /bar2/</code></p>\n\n<p>I know it's like issuing several commands, but it works well for me when I want to type 1 line and walk away for a while.</p>\n"
},
{
"answer_id": 29456982,
"author": "Sj Lee",
"author_id": 4751449,
"author_profile": "https://Stackoverflow.com/users/4751449",
"pm_score": 0,
"selected": false,
"text": "<pre><code>ls -d */ | xargs -iA cp file.txt A\n</code></pre>\n"
},
{
"answer_id": 36142701,
"author": "Devendra Lattu",
"author_id": 2889297,
"author_profile": "https://Stackoverflow.com/users/2889297",
"pm_score": 0,
"selected": false,
"text": "<p>Suppose you want to copy <code>fileName.txt</code> to all sub-directories within present working directory.</p>\n\n<ol>\n<li><p>Get all sub-directories names through <code>ls</code> and save them to some temporary file say, <code>allFolders.txt</code></p>\n\n<pre><code>ls > allFolders.txt\n</code></pre></li>\n<li><p>Print the list and pass it to command <code>xargs</code>.</p>\n\n<pre><code>cat allFolders.txt | xargs -n 1 cp fileName.txt\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 37948571,
"author": "oggust",
"author_id": 6491685,
"author_profile": "https://Stackoverflow.com/users/6491685",
"pm_score": 3,
"selected": false,
"text": "<p>Not using cp per se, but...</p>\n\n<p>This came up for me in the context of copying lots of Gopro footage off of a (slow) SD card to three (slow) USB drives. I wanted to read the data only once, because it took forever. And I wanted it recursive.</p>\n\n<pre><code>$ tar cf - src | tee >( cd dest1 ; tar xf - ) >( cd dest2 ; tar xf - ) | ( cd dest3 ; tar xf - )\n</code></pre>\n\n<p>(And you can add more of those >() sections if you want more outputs.)</p>\n\n<p>I haven't benchmarked that, but it's definitely a lot faster than cp-in-a-loop (or a bunch of parallel cp invocations).</p>\n"
},
{
"answer_id": 41433002,
"author": "Waxrat",
"author_id": 2102698,
"author_profile": "https://Stackoverflow.com/users/2102698",
"pm_score": 4,
"selected": false,
"text": "<p>These answers all seem more complicated than the obvious:</p>\n\n<pre><code>for i in /foo /bar; do cp \"$file1\" \"$i\"; done\n</code></pre>\n"
},
{
"answer_id": 45444089,
"author": "MegaCookie",
"author_id": 3801276,
"author_profile": "https://Stackoverflow.com/users/3801276",
"pm_score": 3,
"selected": false,
"text": "<p>To use copying with <code>xargs</code> to directories using wildcards on Mac OS, the only solution that worked for me <strong>with</strong> spaces in the directory name is:</p>\n\n<pre><code>find ./fs*/* -type d -print0 | xargs -0 -n 1 cp test \n</code></pre>\n\n<p>Where <code>test</code> is the file to copy<br>\nAnd <code>./fs*/*</code> the directories to copy to</p>\n\n<p>The problem is that xargs sees spaces as a new argument, the solutions to change the delimiter character using <code>-d</code> or <code>-E</code> is unfortunately not properly working on Mac OS.</p>\n"
},
{
"answer_id": 52121255,
"author": "Patrick Manley",
"author_id": 10301505,
"author_profile": "https://Stackoverflow.com/users/10301505",
"pm_score": 0,
"selected": false,
"text": "<p>Using a bash script</p>\n\n<pre><code>DESTINATIONPATH[0]=\"xxx/yyy\"\nDESTINATIONPATH[1]=\"aaa/bbb\"\n ..\nDESTINATIONPATH[5]=\"MainLine/USER\"\nNumberOfDestinations=6\n\nfor (( i=0; i<NumberOfDestinations; i++))\n do\n cp SourcePath/fileName.ext ${DESTINATIONPATH[$i]}\n\n done\nexit\n</code></pre>\n"
},
{
"answer_id": 56791292,
"author": "Mig82",
"author_id": 4124574,
"author_profile": "https://Stackoverflow.com/users/4124574",
"pm_score": -1,
"selected": false,
"text": "<p>If all your target directories match a path expression — like they're all subdirectories of <code>path/to</code> — then just use <code>find</code> in combination with <code>cp</code> like this:</p>\n\n<pre><code>find ./path/to/* -type d -exec cp [file name] {} \\;\n</code></pre>\n\n<p>That's it.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13523/"
] |
Is it possible to copy a single file to multiple directories using the cp command ?
I tried the following , which did not work:
```
cp file1 /foo/ /bar/
cp file1 {/foo/,/bar}
```
I know it's possible using a for loop, or find. But is it possible using the gnu cp command?
|
No, `cp` can copy multiple sources but will only copy to a single destination. You need to arrange to invoke `cp` multiple times - once per destination - for what you want to do; using, as you say, a loop or some other tool.
|
195,667 |
<p>I have an iframe and couple of tables on my aspx page. Now when the page loads these tables are hidden. The iframe is used to upload file to database. Depending on the result of the event I have to show a particular table on my main page (these tables basically have "Retry","next" buttons...depending on whether or not the file is uploaded I have to show respective button).</p>
<p>Now I have a JavaScript on the "onload" event of the iframe where I am hiding these tables to start with. When the control comes back after the event I show a particular table. But then the iframe loads again and the tables are hidden. Can any one help me with this problem. I don't want the iframe to load the second time.</p>
<p>Thanks</p>
|
[
{
"answer_id": 195675,
"author": "Dimitry",
"author_id": 27073,
"author_profile": "https://Stackoverflow.com/users/27073",
"pm_score": 0,
"selected": false,
"text": "<p>I am not sure what your problem is, but perhaps your approach should be a little different. Try putting code into the iframe what would call functions of the parent. These functions would display the proper table:</p>\n\n<pre><code><!-- in the main page --->\nfunction showTable1() {}\n\n<!-- in the iframe -->\nwindow.onload = function () {\n parent.showTable1();\n}\n</code></pre>\n\n<p>This would put a lot of control into your iframe, away from the main page.</p>\n"
},
{
"answer_id": 195679,
"author": "Sijin",
"author_id": 8884,
"author_profile": "https://Stackoverflow.com/users/8884",
"pm_score": 0,
"selected": false,
"text": "<p>I don't have enough specifics from your question to determine if the iframe second load can be prevented. But I would suggest using a javascript variable to check if the iframe is being loaded a second time and in that case skip the logic for hiding the tables,</p>\n"
},
{
"answer_id": 195698,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>This is my code</p>\n\n<p>function initUpload()\n {\n //alert(\"IFrame loads\");\n _divFrame = document.getElementById('divFrame');\n _divUploadMessage = document.getElementById('divUploadMessage');\n _divUploadProgress = document.getElementById('divUploadProgress');\n _ifrFile = document.getElementById('ifrFile');\n _tbRetry = document.getElementById('tbRetry');\n _tbNext=document.getElementById('tblNext');</p>\n\n<pre><code> _tbRetry.style.display='none';\n _tbNext.style.display='none';\n\n var btnUpload = _ifrFile.contentWindow.document.getElementById('btnUpload');\n\n btnUpload.onclick = function(event)\n {\n var myFile = _ifrFile.contentWindow.document.getElementById('myFile');\n\n //Baisic validation\n _divUploadMessage.style.display = 'none';\n\n\n if (myFile.value.length == 0)\n {\n _divUploadMessage.innerHTML = '<span style=\\\"color:#ff0000\\\">Please select a file.</span>';\n _divUploadMessage.style.display = '';\n myFile.focus();\n return;\n }\n\n var regExp = /^(([a-zA-Z]:)|(\\\\{2}\\w+)\\$?)(\\\\(\\w[\\w].*))(.doc|.txt|.xls|.docx |.xlsx)$/;\n\n if (!regExp.test(myFile.value)) //Somehow the expression does not work in Opera\n {\n _divUploadMessage.innerHTML = '<span style=\\\"color:#ff0000\\\">Invalid file type. Only supports doc, txt, xls.</span>';\n _divUploadMessage.style.display = '';\n myFile.focus();\n return;\n }\n\n\n _ifrFile.contentWindow.document.getElementById('Upload').submit();\n _divFrame.style.display = 'none';\n\n\n }\n }\n</code></pre>\n\n<p>function UploadComplete(message, isError)\n {\n alert(message);\n //alert(isError);</p>\n\n<pre><code> clearUploadProgress();\n\n\n if (_UploadProgressTimer)\n {\n clearTimeout(_UploadProgressTimer);\n }\n\n _divUploadProgress.style.display = 'none';\n _divUploadMessage.style.display = 'none';\n _divFrame.style.display = 'none';\n _tbNext.style.display='';\n\n if (message.length)\n {\n var color = (isError) ? '#008000' : '#ff0000';\n\n _divUploadMessage.innerHTML = '<span style=\\\"color:' + color + '\\;font-weight:bold\">' + message + '</span>';\n _divUploadMessage.style.display = '';\n _tbNext.style.display='';\n _tbRetry.style.display='none';\n\n\n\n }\n }\n</code></pre>\n\n<p>tblRetry and tblNext are the tables that I want to display depending on the result of the event.</p>\n"
},
{
"answer_id": 213459,
"author": "kentaromiura",
"author_id": 27340,
"author_profile": "https://Stackoverflow.com/users/27340",
"pm_score": 1,
"selected": false,
"text": "<p>mmm you said you're on aspx page, \nI suppose that the iframe do a postback, so for this it reload the page.\nIf you can't avoid the postback, you've to set a flag on the main page just before posting back, and check against that while you're loading...</p>\n\n<p>...something like:</p>\n\n<pre><code>mainpage.waitTillPostBack = true\nYourFunctionCausingPostBack();\n\n\n..\n\nonload=function(){\nif(!mainpage.waitTillPostBack){\nhideTables();\n}\nmainpage.waitTillPostBack = false;\n}\n</code></pre>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have an iframe and couple of tables on my aspx page. Now when the page loads these tables are hidden. The iframe is used to upload file to database. Depending on the result of the event I have to show a particular table on my main page (these tables basically have "Retry","next" buttons...depending on whether or not the file is uploaded I have to show respective button).
Now I have a JavaScript on the "onload" event of the iframe where I am hiding these tables to start with. When the control comes back after the event I show a particular table. But then the iframe loads again and the tables are hidden. Can any one help me with this problem. I don't want the iframe to load the second time.
Thanks
|
mmm you said you're on aspx page,
I suppose that the iframe do a postback, so for this it reload the page.
If you can't avoid the postback, you've to set a flag on the main page just before posting back, and check against that while you're loading...
...something like:
```
mainpage.waitTillPostBack = true
YourFunctionCausingPostBack();
..
onload=function(){
if(!mainpage.waitTillPostBack){
hideTables();
}
mainpage.waitTillPostBack = false;
}
```
|
195,682 |
<p>Here's my issue, I'd like to mock a class that creates a thread at initialization and closes it at destruction. There's no reason for my mock class to actually create and close threads. But, to mock a class, I have inherit from it. When I create a new instance of my mock class, the base classes constructor is called, creating the thread. When my mock object is destroyed, the base classes destructor is called, attempting to close the thread. </p>
<p>How does one mock an RAII class without having to deal with the actual resource?</p>
|
[
{
"answer_id": 195747,
"author": "hazzen",
"author_id": 5066,
"author_profile": "https://Stackoverflow.com/users/5066",
"pm_score": 5,
"selected": true,
"text": "<p>You instead make an interface that describes the type, and have both the real class and the mock class inherit from that. So if you had:</p>\n\n<pre><code>class RAIIClass {\n public:\n RAIIClass(Foo* f);\n ~RAIIClass();\n bool DoOperation();\n\n private:\n ...\n};\n</code></pre>\n\n<p>You would make an interface like:</p>\n\n<pre><code>class MockableInterface {\n public:\n MockableInterface(Foo* f);\n virtual ~MockableInterface();\n virtual bool DoOperation() = 0;\n};\n</code></pre>\n\n<p>And go from there.</p>\n"
},
{
"answer_id": 195750,
"author": "ejgottl",
"author_id": 9808,
"author_profile": "https://Stackoverflow.com/users/9808",
"pm_score": 3,
"selected": false,
"text": "<p>First of all, it is not necessarily an unreasonable thing that your classes might be well designed for their use, but poorly designed for testing. Not everything is easy to test.</p>\n\n<p>Presumably you want to use another function or class which makes use of the class which you want to mock (otherwise the solution is trivial). Lets call the former \"User\" and the latter \"Mocked\". Here are some possibilities:</p>\n\n<ol>\n<li>Change User to use an abstract version of Mocked (you get to choose what kind of abstraction to use: inheritance, callback, templates, etc....).</li>\n<li>Compile a different version of Mocked for your testing code (for example, #def out the RAII code when you compile your tests).</li>\n<li>Have Mocked accept a constructor flag to turn off its behavior. I personally would avoid doing this.</li>\n<li>Just suck up the cost of allocating the resource.</li>\n<li>Skip the test.</li>\n</ol>\n\n<p>The last two may be your only recourse if you can not modify User or Mocked. If you can modify User and you believe that designing your code to be testable is important, then you should explore the first option before any of the others. Note that there can be a trade off between making your code generic/flexible and keeping it simple, both of which are admirable qualities.</p>\n"
},
{
"answer_id": 196116,
"author": "quamrana",
"author_id": 4834,
"author_profile": "https://Stackoverflow.com/users/4834",
"pm_score": 0,
"selected": false,
"text": "<p>One technique I've used is to use some form of decorator. Your final code has a method which creates its instance on the stack and then calls the same method, but on a member which is a pointer to your base class. When that call returns, your method returns destroying the instance you created.</p>\n\n<p>At test time, you swap in a mock which doesn't create any threads, but just forwards to the method you want to test.</p>\n\n<pre><code>class Base{\n protected:\n Base* decorated;\n public:\n virtual void method(void)=0;\n};\nclass Final: public Base{\n void method(void) { Thread athread; decorated->method(); } // I expect Final to do something with athread\n};\nclass TestBase: public Base{\n void method(void) { decorated->method(); }\n};\n</code></pre>\n"
},
{
"answer_id": 196587,
"author": "Mark Kegel",
"author_id": 14788,
"author_profile": "https://Stackoverflow.com/users/14788",
"pm_score": 1,
"selected": false,
"text": "<p>The pimpl idiom might suit you as well. Create your Thread class, with a concrete implementation that it brings in underneath. If you put in the right #defines and #ifdefs your implementation can change when you enable unit testing, which means that you can switch between a real implementation and a mocked one depending on what you are trying to accomplish.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23071/"
] |
Here's my issue, I'd like to mock a class that creates a thread at initialization and closes it at destruction. There's no reason for my mock class to actually create and close threads. But, to mock a class, I have inherit from it. When I create a new instance of my mock class, the base classes constructor is called, creating the thread. When my mock object is destroyed, the base classes destructor is called, attempting to close the thread.
How does one mock an RAII class without having to deal with the actual resource?
|
You instead make an interface that describes the type, and have both the real class and the mock class inherit from that. So if you had:
```
class RAIIClass {
public:
RAIIClass(Foo* f);
~RAIIClass();
bool DoOperation();
private:
...
};
```
You would make an interface like:
```
class MockableInterface {
public:
MockableInterface(Foo* f);
virtual ~MockableInterface();
virtual bool DoOperation() = 0;
};
```
And go from there.
|
195,688 |
<p>I have a string(char*), and i need to find its underlying datatype such as int, float, double, short, long, or just a character array containing alphabets with or with out digits(like varchar in SQL).
For ex: </p>
<pre><code> char* str1 = "12312"
char* str2 = "231.342"
char* str3 = "234234243234"
char* str4 = "4323434.2432342"
char* str5 = "i contain only alphabets"
</code></pre>
<p><strong>Given these strings, i need to find that the first string is of type int and typecast it to an int, and so on</strong> ex:</p>
<pre><code>int no1 = atoi(str1)
float no2 = atof(str2)
long no3 = atol(str3)
double no4 = strtod(str4)
char* varchar1 = strdup(str5)
</code></pre>
<hr>
<p>Clarifying a bit more... </p>
<p>I have a string and its contents could be alphabets and/or digits and/or special characters. Right now, I am able to parse string and </p>
<ol>
<li>Identify if it contains only digits,<br>
Here i convert the string into short or int or long, based on best fit. ( <strong>How do i know if the string can be converted to an short int or long?</strong>) </li>
<li>Only alphabets, leave it as a string. </li>
<li>Digits with a single decimal point.<br>
Here i need to convert the string into float or double ( <strong>Same question here</strong>)</li>
<li>other. leave it as a string</li>
</ol>
|
[
{
"answer_id": 195732,
"author": "Pitarou",
"author_id": 1260685,
"author_profile": "https://Stackoverflow.com/users/1260685",
"pm_score": 1,
"selected": false,
"text": "<p>First, check whether the problem hasn't already been solved for you. It could be that your library functions for converting strings to numbers already do the checks that you need.</p>\n\n<p>Failing that, you're going to need to do some pattern matching on strings, and that's what regular expressions are for!</p>\n\n<p>E.g. if the string matches the regexp:</p>\n\n<p><code>[+-]?\\d+</code></p>\n\n<p>then you know that it's an int or a long. Convert it to a long, and then check its size. If your long can fit into an int, convert it to an int.</p>\n\n<p>You can do the same for floats and doubles, although the regular expression is a bit mroe complicated.</p>\n\n<p>Watch out for awkward cases like the empty string, a lone decimal point, numbers too large for a long, and so on. You also need to decide whether you will allow exponent notation.</p>\n"
},
{
"answer_id": 195775,
"author": "fizzer",
"author_id": 18167,
"author_profile": "https://Stackoverflow.com/users/18167",
"pm_score": 1,
"selected": false,
"text": "<p>Try getting it into a long with sscanf. If that fails, try getting it into a double with sscanf. If that fails, it's a string. You can use the %n conversion to tell whether all of the input was consumed successfully. The constants in <code><limits.h></code> and <code><float.h></code> may help you decide if the numeric results can fit into narrower types on your platform. If this isn't homework, your destination types are probably externally defined - e.g. by a database schema - and the latter comment is irrelevant.</p>\n"
},
{
"answer_id": 195795,
"author": "Remo.D",
"author_id": 16827,
"author_profile": "https://Stackoverflow.com/users/16827",
"pm_score": 0,
"selected": false,
"text": "<p>First of all, you should decide which representatins you want to recognize. For example, is 0xBAC0 an unsigned short expressed in hex? Same goes for 010 (in octal) and 1E-2 (for 0,01).</p>\n\n<p>Once you have decided on the represantation, you can use regular expressions to determine the general forms. For example:</p>\n\n<ul>\n<li><strong><code>-?\\d*.\\d*([eE]?[+-]?\\d*.\\d*)?</code></strong> is a floating point number (almost, it accept weird things like <code>.e-.</code> you should define the regex that is most appropriate for you)</li>\n<li><strong><code>-?\\d+</code></strong> is an integer</li>\n<li><strong><code>0x[0-9A-Fa-f]+</code></strong> is an hex constant</li>\n</ul>\n\n<p>and so on. If you are not using a regex library you will have to write a small parser for those represantion from scratch.</p>\n\n<p>Now you can convert it to the largest possible type (e.g. <code>long long</code> for integers, double for floating pointers) and then use the values in <code>limits.h</code> to see if the value would fit in a smaller type.</p>\n\n<p>For example if the integer is less than <code>SHRT_MAX</code> you can assume it's a <code>short</code>.</p>\n\n<p>You might also have to take arbitrary decisions, for example 54321 can only be an <code>unsigned short</code> but 12345 could be a <code>signed short</code> or an <code>unsigned short</code>.</p>\n"
},
{
"answer_id": 195837,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 2,
"selected": true,
"text": "<p>In C (not in C++), I would use a combination of strtod/strol and max values from <limits.h> and <float.h>:</p>\n\n<pre><code>#include <stdlib.h>\n#include <stdio.h>\n#include <limits.h>\n#include <float.h>\n\n/* Now, we know the following values:\n INT_MAX, INT_MIN, SHRT_MAX, SHRT_MIN, CHAR_MAX, CHAR_MIN, etc. */\n\ntypedef union tagMyUnion\n{\n char TChar_ ; short TShort_ ; long TLong_ ; double TDouble_ ;\n} MyUnion ;\n\ntypedef enum tagMyEnum\n{\n TChar, TShort, TLong, TDouble, TNaN\n} MyEnum ;\n\nvoid whatIsTheValue(const char * string_, MyEnum * enum_, MyUnion * union_)\n{\n char * endptr ;\n long lValue ;\n double dValue ;\n\n *enum_ = TNaN ;\n\n /* integer value */\n lValue = strtol(string_, &endptr, 10) ;\n\n if(*endptr == 0) /* It is an integer value ! */\n {\n if((lValue >= CHAR_MIN) && (lValue <= CHAR_MAX)) /* is it a char ? */\n {\n *enum_ = TChar ;\n union_->TChar_ = (char) lValue ;\n }\n else if((lValue >= SHRT_MIN) && (lValue <= SHRT_MAX)) /* is it a short ? */\n {\n *enum_ = TShort ;\n union_->TShort_ = (short) lValue ;\n }\n else if((lValue >= LONG_MIN) && (lValue <= LONG_MAX)) /* is it a long ? */\n {\n *enum_ = TLong ;\n union_->TLong_ = (long) lValue ;\n }\n\n return ;\n }\n\n /* real value */\n dValue = strtod(string_, &endptr) ;\n\n if(*endptr == 0) /* It is an real value ! */\n {\n if((dValue >= -DBL_MAX) && (dValue <= DBL_MAX)) /* is it a double ? */\n {\n *enum_ = TDouble ;\n union_->TDouble_ = (double) dValue ;\n }\n\n return ;\n }\n\n return ;\n}\n\nvoid studyValue(const char * string_)\n{\n MyEnum enum_ ;\n MyUnion union_ ;\n\n whatIsTheValue(string_, &enum_, &union_) ;\n\n switch(enum_)\n {\n case TChar : printf(\"It is a char : %li\\n\", (long) union_.TChar_) ; break ;\n case TShort : printf(\"It is a short : %li\\n\", (long) union_.TShort_) ; break ;\n case TLong : printf(\"It is a long : %li\\n\", (long) union_.TLong_) ; break ;\n case TDouble : printf(\"It is a double : %f\\n\", (double) union_.TDouble_) ; break ;\n case TNaN : printf(\"It is a not a number : %s\\n\", string_) ; break ;\n default : printf(\"I really don't know : %s\\n\", string_) ; break ;\n }\n}\n\nint main(int argc, char **argv)\n{\n studyValue(\"25\") ;\n studyValue(\"-25\") ;\n studyValue(\"30000\") ;\n studyValue(\"-30000\") ;\n studyValue(\"300000\") ;\n studyValue(\"-300000\") ;\n studyValue(\"25.5\") ;\n studyValue(\"-25.5\") ;\n studyValue(\"25555555.55555555\") ;\n studyValue(\"-25555555.55555555\") ;\n studyValue(\"Hello World\") ;\n studyValue(\"555-55-55\") ;\n\n return 0;\n}\n</code></pre>\n\n<p>Which results in the following:</p>\n\n<pre><code>[25] is a char : 25\n[-25] is a char : -25\n[30000] is a short : 30000\n[-30000] is a short : -30000\n[300000] is a long : 300000\n[-300000] is a long : -300000\n[25.5] is a double : 25.500000\n[-25.5] is a double : -25.500000\n[25555555.55555555] is a double : 25555555.555556\n[-25555555.55555555] is a double : -25555555.555556\n[Hello World] is a not a number\n[555-55-55] is a not a number\n</code></pre>\n\n<p>Sorry for my rusty C.</p>\n\n<p>:-)</p>\n\n<p>So, in substance, you after the call of whatIsTheValue, you retrieve the type through the MyEnum enum, and then, according to the value in this enum, retrieve the right value, correctly typed, from the union MyUnion.</p>\n\n<p>Note that finding if the number is a double or a float is a bit more complicated because the difference seems to be in the precision, i.e. is your number representable in a double, or in float. A most \"decimal real\" numbers are not exactly representable into a double, I would not bother.</p>\n\n<p>Note, too, that there is a catch, as 25.0 could be both real and an integer number. My comparing \"dValue == (double)(long)dValue\", I guess you should know if is an integer, again, not taking into account the usual precision problems coming witb binary real numbers used by computers.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27221/"
] |
I have a string(char\*), and i need to find its underlying datatype such as int, float, double, short, long, or just a character array containing alphabets with or with out digits(like varchar in SQL).
For ex:
```
char* str1 = "12312"
char* str2 = "231.342"
char* str3 = "234234243234"
char* str4 = "4323434.2432342"
char* str5 = "i contain only alphabets"
```
**Given these strings, i need to find that the first string is of type int and typecast it to an int, and so on** ex:
```
int no1 = atoi(str1)
float no2 = atof(str2)
long no3 = atol(str3)
double no4 = strtod(str4)
char* varchar1 = strdup(str5)
```
---
Clarifying a bit more...
I have a string and its contents could be alphabets and/or digits and/or special characters. Right now, I am able to parse string and
1. Identify if it contains only digits,
Here i convert the string into short or int or long, based on best fit. ( **How do i know if the string can be converted to an short int or long?**)
2. Only alphabets, leave it as a string.
3. Digits with a single decimal point.
Here i need to convert the string into float or double ( **Same question here**)
4. other. leave it as a string
|
In C (not in C++), I would use a combination of strtod/strol and max values from <limits.h> and <float.h>:
```
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <float.h>
/* Now, we know the following values:
INT_MAX, INT_MIN, SHRT_MAX, SHRT_MIN, CHAR_MAX, CHAR_MIN, etc. */
typedef union tagMyUnion
{
char TChar_ ; short TShort_ ; long TLong_ ; double TDouble_ ;
} MyUnion ;
typedef enum tagMyEnum
{
TChar, TShort, TLong, TDouble, TNaN
} MyEnum ;
void whatIsTheValue(const char * string_, MyEnum * enum_, MyUnion * union_)
{
char * endptr ;
long lValue ;
double dValue ;
*enum_ = TNaN ;
/* integer value */
lValue = strtol(string_, &endptr, 10) ;
if(*endptr == 0) /* It is an integer value ! */
{
if((lValue >= CHAR_MIN) && (lValue <= CHAR_MAX)) /* is it a char ? */
{
*enum_ = TChar ;
union_->TChar_ = (char) lValue ;
}
else if((lValue >= SHRT_MIN) && (lValue <= SHRT_MAX)) /* is it a short ? */
{
*enum_ = TShort ;
union_->TShort_ = (short) lValue ;
}
else if((lValue >= LONG_MIN) && (lValue <= LONG_MAX)) /* is it a long ? */
{
*enum_ = TLong ;
union_->TLong_ = (long) lValue ;
}
return ;
}
/* real value */
dValue = strtod(string_, &endptr) ;
if(*endptr == 0) /* It is an real value ! */
{
if((dValue >= -DBL_MAX) && (dValue <= DBL_MAX)) /* is it a double ? */
{
*enum_ = TDouble ;
union_->TDouble_ = (double) dValue ;
}
return ;
}
return ;
}
void studyValue(const char * string_)
{
MyEnum enum_ ;
MyUnion union_ ;
whatIsTheValue(string_, &enum_, &union_) ;
switch(enum_)
{
case TChar : printf("It is a char : %li\n", (long) union_.TChar_) ; break ;
case TShort : printf("It is a short : %li\n", (long) union_.TShort_) ; break ;
case TLong : printf("It is a long : %li\n", (long) union_.TLong_) ; break ;
case TDouble : printf("It is a double : %f\n", (double) union_.TDouble_) ; break ;
case TNaN : printf("It is a not a number : %s\n", string_) ; break ;
default : printf("I really don't know : %s\n", string_) ; break ;
}
}
int main(int argc, char **argv)
{
studyValue("25") ;
studyValue("-25") ;
studyValue("30000") ;
studyValue("-30000") ;
studyValue("300000") ;
studyValue("-300000") ;
studyValue("25.5") ;
studyValue("-25.5") ;
studyValue("25555555.55555555") ;
studyValue("-25555555.55555555") ;
studyValue("Hello World") ;
studyValue("555-55-55") ;
return 0;
}
```
Which results in the following:
```
[25] is a char : 25
[-25] is a char : -25
[30000] is a short : 30000
[-30000] is a short : -30000
[300000] is a long : 300000
[-300000] is a long : -300000
[25.5] is a double : 25.500000
[-25.5] is a double : -25.500000
[25555555.55555555] is a double : 25555555.555556
[-25555555.55555555] is a double : -25555555.555556
[Hello World] is a not a number
[555-55-55] is a not a number
```
Sorry for my rusty C.
:-)
So, in substance, you after the call of whatIsTheValue, you retrieve the type through the MyEnum enum, and then, according to the value in this enum, retrieve the right value, correctly typed, from the union MyUnion.
Note that finding if the number is a double or a float is a bit more complicated because the difference seems to be in the precision, i.e. is your number representable in a double, or in float. A most "decimal real" numbers are not exactly representable into a double, I would not bother.
Note, too, that there is a catch, as 25.0 could be both real and an integer number. My comparing "dValue == (double)(long)dValue", I guess you should know if is an integer, again, not taking into account the usual precision problems coming witb binary real numbers used by computers.
|
195,696 |
<p>While researching this issue, I found multiple mentions of the following scenario online, invariably as unanswered questions on programming forums. I hope that posting this here will at least serve to document my findings.</p>
<p>First, the symptom: While running pretty standard code that uses waveOutWrite() to output PCM audio, I sometimes get this when running under the debugger:</p>
<pre><code> ntdll.dll!_DbgBreakPoint@0()
ntdll.dll!_RtlpBreakPointHeap@4() + 0x28 bytes
ntdll.dll!_RtlpValidateHeapEntry@12() + 0x113 bytes
ntdll.dll!_RtlDebugGetUserInfoHeap@20() + 0x96 bytes
ntdll.dll!_RtlGetUserInfoHeap@20() + 0x32743 bytes
kernel32.dll!_GlobalHandle@4() + 0x3a bytes
wdmaud.drv!_waveCompleteHeader@4() + 0x40 bytes
wdmaud.drv!_waveThread@4() + 0x9c bytes
kernel32.dll!_BaseThreadStart@8() + 0x37 bytes
</code></pre>
<p>While the obvious suspect would be a heap corruption somewhere else in the code, I found out that that's not the case. Furthermore, I was able to reproduce this problem using the following code (this is part of a dialog based MFC application:)</p>
<pre><code>void CwaveoutDlg::OnBnClickedButton1()
{
WAVEFORMATEX wfx;
wfx.nSamplesPerSec = 44100; /* sample rate */
wfx.wBitsPerSample = 16; /* sample size */
wfx.nChannels = 2;
wfx.cbSize = 0; /* size of _extra_ info */
wfx.wFormatTag = WAVE_FORMAT_PCM;
wfx.nBlockAlign = (wfx.wBitsPerSample >> 3) * wfx.nChannels;
wfx.nAvgBytesPerSec = wfx.nBlockAlign * wfx.nSamplesPerSec;
waveOutOpen(&hWaveOut,
WAVE_MAPPER,
&wfx,
(DWORD_PTR)m_hWnd,
0,
CALLBACK_WINDOW );
ZeroMemory(&header, sizeof(header));
header.dwBufferLength = 4608;
header.lpData = (LPSTR)GlobalLock(GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE | GMEM_ZEROINIT, 4608));
waveOutPrepareHeader(hWaveOut, &header, sizeof(header));
waveOutWrite(hWaveOut, &header, sizeof(header));
}
afx_msg LRESULT CwaveoutDlg::OnWOMDone(WPARAM wParam, LPARAM lParam)
{
HWAVEOUT dev = (HWAVEOUT)wParam;
WAVEHDR *hdr = (WAVEHDR*)lParam;
waveOutUnprepareHeader(dev, hdr, sizeof(WAVEHDR));
GlobalFree(GlobalHandle(hdr->lpData));
ZeroMemory(hdr, sizeof(*hdr));
hdr->dwBufferLength = 4608;
hdr->lpData = (LPSTR)GlobalLock(GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE | GMEM_ZEROINIT, 4608));
waveOutPrepareHeader(hWaveOut, &header, sizeof(WAVEHDR));
waveOutWrite(hWaveOut, hdr, sizeof(WAVEHDR));
return 0;
}
</code></pre>
<p>Before anyone comments on this, yes - the sample code plays back uninitialized memory. Don't try this with your speakers turned all the way up.</p>
<p>Some debugging revealed the following information: waveOutPrepareHeader() populates header.reserved with a pointer to what appears to be a structure containing at least two pointers as its first two members. The first pointer is set to NULL. After calling waveOutWrite(), this pointer is set to a pointer allocated on the global heap. In pseudo code, that would look something like this:</p>
<pre><code>struct Undocumented { void *p1, *p2; } /* This might have more members */
MMRESULT waveOutPrepareHeader( handle, LPWAVEHDR hdr, ...) {
hdr->reserved = (Undocumented*)calloc(sizeof(Undocumented));
/* Do more stuff... */
}
MMRESULT waveOutWrite( handle, LPWAVEHDR hdr, ...) {
/* The following assignment fails rarely, causing the problem: */
hdr->reserved->p1 = malloc( /* chunk of private data */ );
/* Probably more code to initiate playback */
}
</code></pre>
<p>Normally, the header is returned to the application by waveCompleteHeader(), a function internal to wdmaud.dll. waveCompleteHeader() tries to deallocate the pointer allocated by waveOutWrite() by calling GlobalHandle()/GlobalUnlock() and friends. Sometimes, GlobalHandle() bombs, as shown above.</p>
<p>Now, the reason that GlobalHandle() bombs is not due to a heap corruption, as I suspected at first - it's because waveOutWrite() returned without setting the first pointer in the internal structure to a valid pointer. I suspect that it frees the memory pointed to by that pointer before returning, but I haven't disassembled it yet.</p>
<p>This only appears to happen when the wave playback system is low on buffers, which is why I'm using a single header to reproduce this.</p>
<p>At this point I have a pretty good case against this being a bug in my application - after all, my application is not even running. Has anyone seen this before?</p>
<p>I'm seeing this on Windows XP SP2. The audio card is from SigmaTel, and the driver version is 5.10.0.4995.</p>
<p>Notes:</p>
<p>To prevent confusion in the future, I'd like to point out that the answer suggesting that the problem lies with the use of malloc()/free() to manage the buffers being played is simply wrong. You'll note that I changed the code above to reflect the suggestion, to prevent more people from making the same mistake - it doesn't make a difference. The buffer being freed by waveCompleteHeader() is not the one containing the PCM data, the responsibility to free the PCM buffer lies with the application, and there's no requirement that it be allocated in any specific way.</p>
<p>Also, I make sure that none of the waveOut API calls I use fail.</p>
<p>I'm currently assuming that this is either a bug in Windows, or in the audio driver. Dissenting opinions are always welcome.</p>
|
[
{
"answer_id": 199762,
"author": "dmazzoni",
"author_id": 7193,
"author_profile": "https://Stackoverflow.com/users/7193",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure about this particular problem, but have you considered using a higher-level, cross-platform audio library? There are a lot of quirks with Windows audio programming, and these libraries can save you a lot of headaches.</p>\n\n<p>Examples include <a href=\"http://portaudio.com\" rel=\"nofollow noreferrer\">PortAudio</a>, <a href=\"http://www.music.mcgill.ca/~gary/rtaudio/\" rel=\"nofollow noreferrer\">RtAudio</a>, and <a href=\"http://www.libsdl.org/\" rel=\"nofollow noreferrer\">SDL</a>.</p>\n"
},
{
"answer_id": 212468,
"author": "Stu Mackellar",
"author_id": 28591,
"author_profile": "https://Stackoverflow.com/users/28591",
"pm_score": 0,
"selected": false,
"text": "<p>The first thing that I'd do would be to check the return values from the waveOutX functions. If any of them fail - which isn't unreasonable given the scenario you describe - and you carry on regardless then it isn't surprising that things start to go wrong. My guess would be that waveOutWrite is returning MMSYSERR_NOMEM at some point.</p>\n"
},
{
"answer_id": 450744,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I'm seeing the same problem and have done some analysis myself:</p>\n\n<p>waveOutWrite() allocates (i.e. GlobalAlloc) a pointer to a heap area of 354 bytes and correctly stores it in the data area pointed to by header.reserved.</p>\n\n<p>But when this heap area is to be freed again (in waveCompleteHeader(), according to your analysis; I don't have the symbols for wdmaud.drv myself), the least significant byte of the pointer has been set to zero, thus invalidating the pointer (while the heap is not corrupted yet). In other words, what happens is something like:</p>\n\n<ul>\n<li>(BYTE *) (header.reserved) = 0</li>\n</ul>\n\n<p>So I disagree with your statements in one point: waveOutWrite() stores a valid pointer first; the pointer only becomes corrupted later from another thread.\nProbably that's the same thread (mxdmessage) that later tries to free this heap area, but I did not yet find the point where the zero byte is stored.</p>\n\n<p>This does not happen very often, and the same heap area (same address) has successfully been allocated and deallocated before.\nI'm quite convinced that this is a bug somewhere in the system code.</p>\n"
},
{
"answer_id": 496160,
"author": "Ana Betts",
"author_id": 5728,
"author_profile": "https://Stackoverflow.com/users/5728",
"pm_score": 0,
"selected": false,
"text": "<p>Use Application Verifier to figure out what's going on, if you do something suspicious, it will catch it much earlier.</p>\n"
},
{
"answer_id": 498958,
"author": "Stefan",
"author_id": 48003,
"author_profile": "https://Stackoverflow.com/users/48003",
"pm_score": 3,
"selected": true,
"text": "<p>You're not alone with this issue:\n<a href=\"http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=100589\" rel=\"nofollow noreferrer\">http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=100589</a></p>\n"
},
{
"answer_id": 499035,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 0,
"selected": false,
"text": "<p>It may be helpful to look at the <a href=\"http://winehq.org/download/#source\" rel=\"nofollow noreferrer\">source code for Wine</a>, although it's possible that Wine has fixed whatever bug there is, and it's also possible Wine has other bugs in it. The relevant files are dlls/winmm/winmm.c, dlls/winmm/lolvldrv.c, and possibly others. Good luck!</p>\n"
},
{
"answer_id": 514317,
"author": "AShelly",
"author_id": 10396,
"author_profile": "https://Stackoverflow.com/users/10396",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Now, the reason that GlobalHandle()\n bombs is not due to a heap corruption,\n as I suspected at first - it's because\n waveOutWrite() returned without\n setting the first pointer in the\n internal structure to a valid pointer.\n I suspect that it frees the memory\n pointed to by that pointer before\n returning, but I haven't disassembled\n it yet.</p>\n</blockquote>\n\n<p>I can reproduce this with your code on my system. I see something similar to what Johannes reported. After the call to WaveOutWrite, hdr->reserved normally holds a pointer to allocated memory (which appears to contain the wave out device name in unicode, among other things). </p>\n\n<p>But occasionally, after returning from WaveOutWrite(), the byte pointed to by <code>hdr->reserved</code> is set to 0. This is normally the least significant byte of that pointer. The rest of the bytes in <code>hdr->reserved</code> are ok, and the block of memory that it normally points to is still allocated and uncorrupted. </p>\n\n<p>It probably is being clobbered by another thread - I can catch the change with a conditional breakpoint immediately after the call to WaveOutWrite(). And the system debug breakpoint is occurring in another thread, not the message handler.</p>\n\n<p>However, I can't cause the system debug breakpoint to occur if I use a callback function instead of the windows messsage pump. (<code>fdwOpen = CALLBACK_FUNCTION</code> in WaveOutOpen() )\nWhen I do it this way, my OnWOMDone handler is called by a different thread - possibly the one that's otherwise responsible for the corruption. </p>\n\n<p>So I think there is a bug, either in windows or the driver, but I think you can work around by handling WOM_DONE with a callback function instead of the windows message pump.</p>\n"
},
{
"answer_id": 1303694,
"author": "pps",
"author_id": 96174,
"author_profile": "https://Stackoverflow.com/users/96174",
"pm_score": 0,
"selected": false,
"text": "<p>What about the fact that you are not allowed to call winmm functions from within callback?\nMSDN does not mention such restrictions about window messages, but usage of window messages is similar to callback function. Possibly, internally it's implemented as a callback function from the driver and that callback does SendMessage.\nInternally, waveout has to maintain linked list of headers that were written using waveOutWrite; So, I guess that: </p>\n\n<pre><code>hdr->reserved = (Undocumented*)calloc(sizeof(Undocumented));\n</code></pre>\n\n<p>sets previous/next pointers of the linked list or something like this. If you write more buffers, then if you check the pointers and if any of them point to one another then my guess is most likely correct.</p>\n\n<p>Multiple sources on the web mention that you don't need to unprepare/prepare same headers repeatedly. If you comment out Prepare/unprepare header in the original example then it appears to work fine without any problems.</p>\n"
},
{
"answer_id": 36082265,
"author": "Vadim Galkin",
"author_id": 4098174,
"author_profile": "https://Stackoverflow.com/users/4098174",
"pm_score": 0,
"selected": false,
"text": "<p>I solved the problem by polling the sound playback and delays:</p>\n\n<pre><code>WAVEHDR header = { buffer, sizeof(buffer), 0, 0, 0, 0, 0, 0 };\nwaveOutPrepareHeader(hWaveOut, &header, sizeof(WAVEHDR));\nwaveOutWrite(hWaveOut, &header, sizeof(WAVEHDR));\n/*\n* wait a while for the block to play then start trying\n* to unprepare the header. this will fail until the block has\n* played.\n*/\nwhile (waveOutUnprepareHeader(hWaveOut,&header,sizeof(WAVEHDR)) == WAVERR_STILLPLAYING) \nSleep(100);\nwaveOutClose(hWaveOut);\n</code></pre>\n\n<p><a href=\"https://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=4422&lngWId=3\" rel=\"nofollow\">Playing Audio in Windows using waveOut Interface</a></p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9047/"
] |
While researching this issue, I found multiple mentions of the following scenario online, invariably as unanswered questions on programming forums. I hope that posting this here will at least serve to document my findings.
First, the symptom: While running pretty standard code that uses waveOutWrite() to output PCM audio, I sometimes get this when running under the debugger:
```
ntdll.dll!_DbgBreakPoint@0()
ntdll.dll!_RtlpBreakPointHeap@4() + 0x28 bytes
ntdll.dll!_RtlpValidateHeapEntry@12() + 0x113 bytes
ntdll.dll!_RtlDebugGetUserInfoHeap@20() + 0x96 bytes
ntdll.dll!_RtlGetUserInfoHeap@20() + 0x32743 bytes
kernel32.dll!_GlobalHandle@4() + 0x3a bytes
wdmaud.drv!_waveCompleteHeader@4() + 0x40 bytes
wdmaud.drv!_waveThread@4() + 0x9c bytes
kernel32.dll!_BaseThreadStart@8() + 0x37 bytes
```
While the obvious suspect would be a heap corruption somewhere else in the code, I found out that that's not the case. Furthermore, I was able to reproduce this problem using the following code (this is part of a dialog based MFC application:)
```
void CwaveoutDlg::OnBnClickedButton1()
{
WAVEFORMATEX wfx;
wfx.nSamplesPerSec = 44100; /* sample rate */
wfx.wBitsPerSample = 16; /* sample size */
wfx.nChannels = 2;
wfx.cbSize = 0; /* size of _extra_ info */
wfx.wFormatTag = WAVE_FORMAT_PCM;
wfx.nBlockAlign = (wfx.wBitsPerSample >> 3) * wfx.nChannels;
wfx.nAvgBytesPerSec = wfx.nBlockAlign * wfx.nSamplesPerSec;
waveOutOpen(&hWaveOut,
WAVE_MAPPER,
&wfx,
(DWORD_PTR)m_hWnd,
0,
CALLBACK_WINDOW );
ZeroMemory(&header, sizeof(header));
header.dwBufferLength = 4608;
header.lpData = (LPSTR)GlobalLock(GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE | GMEM_ZEROINIT, 4608));
waveOutPrepareHeader(hWaveOut, &header, sizeof(header));
waveOutWrite(hWaveOut, &header, sizeof(header));
}
afx_msg LRESULT CwaveoutDlg::OnWOMDone(WPARAM wParam, LPARAM lParam)
{
HWAVEOUT dev = (HWAVEOUT)wParam;
WAVEHDR *hdr = (WAVEHDR*)lParam;
waveOutUnprepareHeader(dev, hdr, sizeof(WAVEHDR));
GlobalFree(GlobalHandle(hdr->lpData));
ZeroMemory(hdr, sizeof(*hdr));
hdr->dwBufferLength = 4608;
hdr->lpData = (LPSTR)GlobalLock(GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE | GMEM_ZEROINIT, 4608));
waveOutPrepareHeader(hWaveOut, &header, sizeof(WAVEHDR));
waveOutWrite(hWaveOut, hdr, sizeof(WAVEHDR));
return 0;
}
```
Before anyone comments on this, yes - the sample code plays back uninitialized memory. Don't try this with your speakers turned all the way up.
Some debugging revealed the following information: waveOutPrepareHeader() populates header.reserved with a pointer to what appears to be a structure containing at least two pointers as its first two members. The first pointer is set to NULL. After calling waveOutWrite(), this pointer is set to a pointer allocated on the global heap. In pseudo code, that would look something like this:
```
struct Undocumented { void *p1, *p2; } /* This might have more members */
MMRESULT waveOutPrepareHeader( handle, LPWAVEHDR hdr, ...) {
hdr->reserved = (Undocumented*)calloc(sizeof(Undocumented));
/* Do more stuff... */
}
MMRESULT waveOutWrite( handle, LPWAVEHDR hdr, ...) {
/* The following assignment fails rarely, causing the problem: */
hdr->reserved->p1 = malloc( /* chunk of private data */ );
/* Probably more code to initiate playback */
}
```
Normally, the header is returned to the application by waveCompleteHeader(), a function internal to wdmaud.dll. waveCompleteHeader() tries to deallocate the pointer allocated by waveOutWrite() by calling GlobalHandle()/GlobalUnlock() and friends. Sometimes, GlobalHandle() bombs, as shown above.
Now, the reason that GlobalHandle() bombs is not due to a heap corruption, as I suspected at first - it's because waveOutWrite() returned without setting the first pointer in the internal structure to a valid pointer. I suspect that it frees the memory pointed to by that pointer before returning, but I haven't disassembled it yet.
This only appears to happen when the wave playback system is low on buffers, which is why I'm using a single header to reproduce this.
At this point I have a pretty good case against this being a bug in my application - after all, my application is not even running. Has anyone seen this before?
I'm seeing this on Windows XP SP2. The audio card is from SigmaTel, and the driver version is 5.10.0.4995.
Notes:
To prevent confusion in the future, I'd like to point out that the answer suggesting that the problem lies with the use of malloc()/free() to manage the buffers being played is simply wrong. You'll note that I changed the code above to reflect the suggestion, to prevent more people from making the same mistake - it doesn't make a difference. The buffer being freed by waveCompleteHeader() is not the one containing the PCM data, the responsibility to free the PCM buffer lies with the application, and there's no requirement that it be allocated in any specific way.
Also, I make sure that none of the waveOut API calls I use fail.
I'm currently assuming that this is either a bug in Windows, or in the audio driver. Dissenting opinions are always welcome.
|
You're not alone with this issue:
<http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=100589>
|
195,697 |
<p>I have an XML file, which I open in F# like this:</p>
<pre><code>let Bookmarks(xmlFile:string) =
let xml = XDocument.Load(xmlFile)
</code></pre>
<p>Once I have the XDocument I need to navigate it using LINQ to XML and extract all specific tags. Part of my solution is:</p>
<pre><code>let xname (tag:string) = XName.Get(tag)
let tagUrl (tag:XElement) = let attribute = tag.Attribute(xname "href")
attribute.Value
let Bookmarks(xmlFile:string) =
let xml = XDocument.Load(xmlFile)
xml.Elements <| xname "A" |> Seq.map(tagUrl)
</code></pre>
<p>How can I extract the specific tags from the XML file?</p>
|
[
{
"answer_id": 195859,
"author": "Brian",
"author_id": 19299,
"author_profile": "https://Stackoverflow.com/users/19299",
"pm_score": 2,
"selected": false,
"text": "<p>Caveat: I've never done linq-to-xml before, but looking through other posts on the topic, this snippet has some F# code that compiles and does <em>something</em>, and thus it may help you get started:</p>\n\n<pre><code>open System.IO\nopen System.Xml\nopen System.Xml.Linq \n\nlet xmlStr = @\"<?xml version='1.0' encoding='UTF-8'?>\n<doc>\n <blah>Blah</blah>\n <a href='urn:foo' />\n <yadda>\n <blah>Blah</blah>\n <a href='urn:bar' />\n </yadda>\n</doc>\"\n\nlet xns = XNamespace.op_Implicit \"\"\nlet a = xns + \"a\"\nlet reader = new StringReader(xmlStr)\nlet xdoc = XDocument.Load(reader)\nlet aElements = [for x in xdoc.Root.Elements() do\n if x.Name = a then\n yield x]\nlet href = xns + \"href\"\naElements |> List.iter (fun e -> printfn \"%A\" (e.Attribute(href)))\n</code></pre>\n"
},
{
"answer_id": 195870,
"author": "MichaelGG",
"author_id": 27012,
"author_profile": "https://Stackoverflow.com/users/27012",
"pm_score": 4,
"selected": true,
"text": "<pre><code>#light\nopen System\nopen System.Xml.Linq\n\nlet xname s = XName.Get(s)\nlet bookmarks (xmlFile : string) = \n let xd = XDocument.Load xmlFile\n xd.Descendants <| xname \"bookmark\"\n</code></pre>\n\n<p>This will find all the descendant elements of \"bookmark\". If you only want direct descendants, use the Elements method (xd.Root.Elements <| xname \"whatever\").</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18619/"
] |
I have an XML file, which I open in F# like this:
```
let Bookmarks(xmlFile:string) =
let xml = XDocument.Load(xmlFile)
```
Once I have the XDocument I need to navigate it using LINQ to XML and extract all specific tags. Part of my solution is:
```
let xname (tag:string) = XName.Get(tag)
let tagUrl (tag:XElement) = let attribute = tag.Attribute(xname "href")
attribute.Value
let Bookmarks(xmlFile:string) =
let xml = XDocument.Load(xmlFile)
xml.Elements <| xname "A" |> Seq.map(tagUrl)
```
How can I extract the specific tags from the XML file?
|
```
#light
open System
open System.Xml.Linq
let xname s = XName.Get(s)
let bookmarks (xmlFile : string) =
let xd = XDocument.Load xmlFile
xd.Descendants <| xname "bookmark"
```
This will find all the descendant elements of "bookmark". If you only want direct descendants, use the Elements method (xd.Root.Elements <| xname "whatever").
|
195,709 |
<p>After switching back and forth between several scripting languages this week, I found myself thinking how similar they all are. Yet I'm always reaching for Google (or nowadays SO) to remember details like what the local equivalents of "instanceof" and "endswith" are, or the right syntax to declare an interface, or whatever.</p>
<p>This reminded me of the (human) language <a href="http://en.wikipedia.org/wiki/Europanto" rel="nofollow noreferrer">Europonto</a>. Just pick some vaguely English syntax and some vaguely Romance/Germanic/Slavic vocabulary, and it's all good!</p>
<p>So what would happen if we tried to do the same thing with a scripting language. In the mood for Python-style indented blocks today? Fine! Want to use a prototype object? Ok! Can only remember how to spell the PHP names of some library function? No problem!</p>
<p>Anyway, that's the wild and crazy idea. Since we need a question that admits concrete answers, let's tighten it up like this:</p>
<p>What would be the most significant conflicts in creating a scripting language that permitted all the native syntax and library functions of [Python, Ruby, PHP, Perl, shell, and JavaScript], such that you could freely intermix code blocks and function names between languages?</p>
<p>And let's say that any particular construction should be consistent at the statement level. So we'll allow:</p>
<pre><code>foreach( $foo as $bar )
{
if $foo == 2:
print "hi"
}
</code></pre>
<p>but not, say,</p>
<pre><code>foreach( $foo as $bar )
{
if $foo == 2:
print "hi"
endif
end
</code></pre>
<p>Conflicts can include: parser ambiguities; name collision; conflicting semantics for objects or functions or closures; etc. I'm guessing that scope will be a ginormous issue, but you tell me.</p>
<p>I'll start this as "community wiki" from the get go, so if you think it's a fun question but want to make it more rigorous, feel free to edit.</p>
|
[
{
"answer_id": 195715,
"author": "Marcin",
"author_id": 21640,
"author_profile": "https://Stackoverflow.com/users/21640",
"pm_score": 2,
"selected": false,
"text": "<p>I would suggest that the main problem is recognising what the syntax of each statement is supposed to be. </p>\n\n<p>In any case, what is the point? Almost all scripting languages have facilities to do much the same things, which is why people tend to master one that they use consistently, and stick with it.</p>\n"
},
{
"answer_id": 195727,
"author": "gbarry",
"author_id": 19512,
"author_profile": "https://Stackoverflow.com/users/19512",
"pm_score": 0,
"selected": false,
"text": "<p>I have begun to see that syntax is but one property of a language. And most of them look like C to me. The purpose of a language (object oriented, strong typing, etc) is something else again. It starts to look like syntax is not the most important aspect.</p>\n\n<p>I went and read the wikipedia entry...</p>\n\n<blockquote>\n <p>Europanto is a linguistic jest presented as a \"constructed language\" with a hodge-podge vocabulary </p>\n</blockquote>\n\n<p>\"Hodge-podge\" sounds like the way Perl has been described to me!</p>\n"
},
{
"answer_id": 195752,
"author": "Eric",
"author_id": 4540,
"author_profile": "https://Stackoverflow.com/users/4540",
"pm_score": 0,
"selected": false,
"text": "<p>I found a <a href=\"http://innig.net/software/ruby/closures-in-ruby.rb\" rel=\"nofollow noreferrer\">rather detailed discussion of closures in Ruby</a>. It sounds like getting Ruby's behavior to coexist with JavaScript's or Python's would require some kind of ugly disambiguation.</p>\n\n<p>If anybody were to add Perl to the list of languages to be covered, I think its lexical scoping rules would present a related problem?</p>\n"
},
{
"answer_id": 195846,
"author": "shoosh",
"author_id": 9611,
"author_profile": "https://Stackoverflow.com/users/9611",
"pm_score": 1,
"selected": false,
"text": "<p>The main difficulty would to be to allow people maintain it. With a well defined language you can only <code>print</code> a certain way and do <code>sys.argv</code> a certain way. once you allow multiple syntaxes there is no sane way to search for all the <code>sys.argv</code> in the code base you have.</p>\n"
},
{
"answer_id": 850141,
"author": "inkredibl",
"author_id": 22129,
"author_profile": "https://Stackoverflow.com/users/22129",
"pm_score": 1,
"selected": false,
"text": "<p>At the <strong>syntactical</strong> level the only problem I can see would be to detect which block has which syntax, then separate them and parse them with specific parsers. Of course given very small statements there could be ambiguities as to which language it is and you could argue that it doesn't matter, but it just may be the case, that in different languages the same string of characters does different things so this <em>could</em> be a subtle issue.</p>\n\n<p>At the <strong>API</strong> level you would have lots of different methods of doing the same thing but in a subtly different way or subset of doing it. So for example you could have no way of doing Java's <code>string.startsWith()</code> in let's say PHP, so you would do something different, or no way of doing PHP's <code>strstr()</code> (which returns a part of the string from the found needle to the end) and you would implement something different for that or even think differently about the problem. Then you would have to have <em>all</em> those different API methods of doing the same things and that would be huge API to implement, support and (god forbid) learn.</p>\n\n<p>At the <strong>wetware</strong> level the code written by others would be totally unreadable unless you know a ton of languages and their subtle differences. I think it is difficult enough to learn a single programming language to the smallest details and so it is not practical at all to have this kind of frankensteinish beast created. I can think of an exception for use as an algorithm description language which it already is used in universities all over the world, where teacher takes some language of his liking and makes the code as readable as it can be for a human without needing to implement a parser for it.</p>\n\n<p>As a side note I think this kind of system could be <strong>implemented</strong> at the least effort by <em>somehow</em> utilizing .NET's CLR where you have a ton of different languages each compiling to the same bytecode and accessing the same variables and stuff. <em>All you'd need to do</em> is split the code to clusters of different languages, then compile them separately on their respective compilers and then just merge the bytecode and <em>somehow</em> make sure they all point to the same variables and functions when mentioning the same names across the different languages.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4540/"
] |
After switching back and forth between several scripting languages this week, I found myself thinking how similar they all are. Yet I'm always reaching for Google (or nowadays SO) to remember details like what the local equivalents of "instanceof" and "endswith" are, or the right syntax to declare an interface, or whatever.
This reminded me of the (human) language [Europonto](http://en.wikipedia.org/wiki/Europanto). Just pick some vaguely English syntax and some vaguely Romance/Germanic/Slavic vocabulary, and it's all good!
So what would happen if we tried to do the same thing with a scripting language. In the mood for Python-style indented blocks today? Fine! Want to use a prototype object? Ok! Can only remember how to spell the PHP names of some library function? No problem!
Anyway, that's the wild and crazy idea. Since we need a question that admits concrete answers, let's tighten it up like this:
What would be the most significant conflicts in creating a scripting language that permitted all the native syntax and library functions of [Python, Ruby, PHP, Perl, shell, and JavaScript], such that you could freely intermix code blocks and function names between languages?
And let's say that any particular construction should be consistent at the statement level. So we'll allow:
```
foreach( $foo as $bar )
{
if $foo == 2:
print "hi"
}
```
but not, say,
```
foreach( $foo as $bar )
{
if $foo == 2:
print "hi"
endif
end
```
Conflicts can include: parser ambiguities; name collision; conflicting semantics for objects or functions or closures; etc. I'm guessing that scope will be a ginormous issue, but you tell me.
I'll start this as "community wiki" from the get go, so if you think it's a fun question but want to make it more rigorous, feel free to edit.
|
I would suggest that the main problem is recognising what the syntax of each statement is supposed to be.
In any case, what is the point? Almost all scripting languages have facilities to do much the same things, which is why people tend to master one that they use consistently, and stick with it.
|
195,714 |
<p>I'm writing an editor for large <em>archive files</em> (see below) of 4GB+, in native&managed C++.</p>
<p>For accessing the files, I'm using <em>file mapping</em> (see below) like any sane person. This is absolutely great for reading data, but a problem arises in actually editing the archive.
File mapping does not allow resizing a file while it's being accessed, so I don't know how I should proceed when the user wants to insert new data in the file (which would exceed the file's original size, when it was mapped.)</p>
<p>Should I remap the whole thing every time? That's bound to be slow. However, I'd want to keep the editor real-time with exclusive file access, since that simplifies the programming a lot, and won't let the file get screwed by other applications while being modified. I wouldn't want to spend an eternity working on the editor; It's just a simple dev-tool for the actual project I'm working on.</p>
<p>So I'd like to hear how you've handled similar cases, and what other archiving software and especially other games do to solve this?</p>
<p>To clarify:</p>
<ul>
<li><p>This is not a text file, I'm writing a specific binary <em>archive file format</em>. By which I mean a big file that contains many others, in directories. Custom archive files are very common in game usage for a number of reasons. With my format, I'm aiming to a similar (but somewhat simpler) structure as with <a href="http://www.wunderboy.org/docs/gcfformat.php" rel="nofollow noreferrer">Valve Software's GCF format</a> - I would have used the GCF format as it is, but unfortunately no editor exists for the format, although there are many great implementations for reading them, like <a href="http://nemesis.thewavelength.net/index.php?p=35" rel="nofollow noreferrer">HLLib</a>.</p></li>
<li><p>Accessing the file must be fast, as it is intended for storing game resources. So it's not a database. Database files would be contained inside it, along with GFX, SFX etc. files.</p></li>
<li><p>"File mapping" as talked here is a specific technique on the Windows platform, which allows direct access to a large file through creating "views" to parts of it, see here: <a href="http://msdn.microsoft.com/en-us/library/aa366556(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa366556(VS.85).aspx</a> - This technique allows minimal latency and memory usage and is a no-brainer for accessing any large files.
So this does <em>not</em> mean reading the whole 4GB file into memory, it's exactly the contrary.</p></li>
</ul>
|
[
{
"answer_id": 195757,
"author": "Diomidis Spinellis",
"author_id": 20520,
"author_profile": "https://Stackoverflow.com/users/20520",
"pm_score": 2,
"selected": false,
"text": "<p>What do you mean by 'editor software'? If this is a text file, have you tried existing production-quality editors, before writing your own? If it's a file storing binary data, have you considered using an RDBMS and manipulating its contents using SQL statements?</p>\n\n<p>If you absolutely have to write this from scratch, I'm not sure that mmapping is the way to go. Mmapping a huge file will put a lot of pressure on your machine's VM system, and unless there are many editing operations all over the file its efficiency may lag behind a simple read/write scheme. Worse, as you say, you have problems when you want to extend the file.</p>\n\n<p>Instead, maintain buffer windows to the file's data, which the user can modify. When the user decides to save the file, traverse sequentially the file and the edited buffers to create the new file image. If you have disk space it's easier to write a new file (especially if a buffer's size has changed), otherwise you need to be clever on how you read-ahead existing data, before you overwrite it with the new contents. </p>\n\n<p>Alternatively, you can keep a journal of editing operations. When the user decides to save the file, perform a topological sort on the journal and play it on the existing file to create the new one.</p>\n\n<p>For exclusive file access use the file locking of your operating system or implement application-level locking (if only your editor will touch these files). Depending on mmap for exclusive access constrains your implementation choices.</p>\n"
},
{
"answer_id": 195767,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 2,
"selected": false,
"text": "<p>Mapping the file is create for actually accessing the data, but I think you need another abstraction that represents the structure of the file. There are various ways of doing this, but consider representing the file as a sequence of 'extents'.</p>\n\n<p>To start with the file is a single extent that is equivalent to the whole mapping. If the user then starts to edit the file, you would split the single extent into two at the edit point, and insert a new extent that contains the data the user has inserted. Modifications and deletes would also modify your view of the file by creating or modifying these extents.</p>\n\n<p>Maybe you could examine the source code for one of the open source editors -- there are lots to choose from, but finding one that is simple enough would be the challenge.</p>\n"
},
{
"answer_id": 195799,
"author": "Head Geek",
"author_id": 12193,
"author_profile": "https://Stackoverflow.com/users/12193",
"pm_score": 1,
"selected": false,
"text": "<p>There's no easy answer for this problem -- I've looked for one for a long time, in vain. You'll have to modify the file's size, then re-map it.</p>\n"
},
{
"answer_id": 196248,
"author": "Shane Powell",
"author_id": 23235,
"author_profile": "https://Stackoverflow.com/users/23235",
"pm_score": 2,
"selected": true,
"text": "<p>What I do is to close view handle(s) and FileMapping handle, set the file size then reopen mapping / view handles.</p>\n\n<pre><code>// Open memory mapped file \nHANDLE FileHandle = ::CreateFileW(file_name, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);\nsize_t Size = ::GetFileSize(FileHandle, 0);\nHANDLE MappingHandle = ::CreateFileMapping(FileHandle, NULL, PAGE_READWRITE, 0, Size, NULL);\nvoid* ViewHandle = ::MapViewOfFile(MappingHandle, FILE_MAP_ALL_ACCESS, 0, 0, Size);\n\n...\n\n// increase size of file\nUnmapViewOfFile(ViewHandle);\nCloseHandle(MappingHandle);\n\nSize += 1024;\n\n\nLARGE_INTEGER offset;\noffset.QuadPart = Size;\n\nLARGE_INTEGER newpos;\nSetFilePointerEx(FileHandle, offset, &newpos, FILE_BEGIN);\nSetEndOfFile(FileHandle);\n\nMappingHandle = ::CreateFileMapping(FileHandle, NULL, PAGE_READWRITE, 0, Size, NULL);\nViewHandle = ::MapViewOfFile(MappingHandle, FILE_MAP_ALL_ACCESS, 0, 0, Size);\n</code></pre>\n\n<p>The above code has no error checking and does not handle 64bit sizes, but that's not hard to fix.</p>\n"
},
{
"answer_id": 498788,
"author": "vrdhn",
"author_id": 414441,
"author_profile": "https://Stackoverflow.com/users/414441",
"pm_score": 1,
"selected": false,
"text": "<p>Mapping has a basic issue with file on remote system.</p>\n\n<p>In good old DOS days, there a was a fine editor called Norton Editor ( ne.com .. this the \nfilename, not web site ). It can load file of any size ( we are talking of 640kb RAM\nand 20 GB hard disks, if any ).</p>\n\n<p>It used to load only part of file, cleverly managing file-long searches with on demand\nloading </p>\n\n<p>IMHO, such an approach should be used.</p>\n\n<p>If properly hidden under a file-read-write layer , it can be surprisingly transparent.</p>\n"
},
{
"answer_id": 768847,
"author": "Roger Lipscombe",
"author_id": 8446,
"author_profile": "https://Stackoverflow.com/users/8446",
"pm_score": 0,
"selected": false,
"text": "<p>I'd build the large file from pieces at build-time. You have your editor deal with normal, flat files, in the usual file system (with subdirectories, etc., as appropriate). You then have a compile step that gathers all of these pieces together into your <em>archive</em> file format.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15477/"
] |
I'm writing an editor for large *archive files* (see below) of 4GB+, in native&managed C++.
For accessing the files, I'm using *file mapping* (see below) like any sane person. This is absolutely great for reading data, but a problem arises in actually editing the archive.
File mapping does not allow resizing a file while it's being accessed, so I don't know how I should proceed when the user wants to insert new data in the file (which would exceed the file's original size, when it was mapped.)
Should I remap the whole thing every time? That's bound to be slow. However, I'd want to keep the editor real-time with exclusive file access, since that simplifies the programming a lot, and won't let the file get screwed by other applications while being modified. I wouldn't want to spend an eternity working on the editor; It's just a simple dev-tool for the actual project I'm working on.
So I'd like to hear how you've handled similar cases, and what other archiving software and especially other games do to solve this?
To clarify:
* This is not a text file, I'm writing a specific binary *archive file format*. By which I mean a big file that contains many others, in directories. Custom archive files are very common in game usage for a number of reasons. With my format, I'm aiming to a similar (but somewhat simpler) structure as with [Valve Software's GCF format](http://www.wunderboy.org/docs/gcfformat.php) - I would have used the GCF format as it is, but unfortunately no editor exists for the format, although there are many great implementations for reading them, like [HLLib](http://nemesis.thewavelength.net/index.php?p=35).
* Accessing the file must be fast, as it is intended for storing game resources. So it's not a database. Database files would be contained inside it, along with GFX, SFX etc. files.
* "File mapping" as talked here is a specific technique on the Windows platform, which allows direct access to a large file through creating "views" to parts of it, see here: <http://msdn.microsoft.com/en-us/library/aa366556(VS.85).aspx> - This technique allows minimal latency and memory usage and is a no-brainer for accessing any large files.
So this does *not* mean reading the whole 4GB file into memory, it's exactly the contrary.
|
What I do is to close view handle(s) and FileMapping handle, set the file size then reopen mapping / view handles.
```
// Open memory mapped file
HANDLE FileHandle = ::CreateFileW(file_name, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
size_t Size = ::GetFileSize(FileHandle, 0);
HANDLE MappingHandle = ::CreateFileMapping(FileHandle, NULL, PAGE_READWRITE, 0, Size, NULL);
void* ViewHandle = ::MapViewOfFile(MappingHandle, FILE_MAP_ALL_ACCESS, 0, 0, Size);
...
// increase size of file
UnmapViewOfFile(ViewHandle);
CloseHandle(MappingHandle);
Size += 1024;
LARGE_INTEGER offset;
offset.QuadPart = Size;
LARGE_INTEGER newpos;
SetFilePointerEx(FileHandle, offset, &newpos, FILE_BEGIN);
SetEndOfFile(FileHandle);
MappingHandle = ::CreateFileMapping(FileHandle, NULL, PAGE_READWRITE, 0, Size, NULL);
ViewHandle = ::MapViewOfFile(MappingHandle, FILE_MAP_ALL_ACCESS, 0, 0, Size);
```
The above code has no error checking and does not handle 64bit sizes, but that's not hard to fix.
|
195,740 |
<p>I'm writing a Rails application, but can't seem to find how to do relative time, i.e. if given a certain Time class, it can calculate "30 seconds ago" or "2 days ago" or if it's longer than a month "9/1/2008", etc.</p>
|
[
{
"answer_id": 195743,
"author": "TonyLa",
"author_id": 1295,
"author_profile": "https://Stackoverflow.com/users/1295",
"pm_score": 4,
"selected": false,
"text": "<p>You can use the arithmetic operators to do relative time.</p>\n\n<pre><code>Time.now - 2.days \n</code></pre>\n\n<p>Will give you 2 days ago.</p>\n"
},
{
"answer_id": 195793,
"author": "Gordon Wilson",
"author_id": 23071,
"author_profile": "https://Stackoverflow.com/users/23071",
"pm_score": 3,
"selected": false,
"text": "<p>Something like this would work.</p>\n\n<pre><code>def relative_time(start_time)\n diff_seconds = Time.now - start_time\n case diff_seconds\n when 0 .. 59\n puts \"#{diff_seconds} seconds ago\"\n when 60 .. (3600-1)\n puts \"#{diff_seconds/60} minutes ago\"\n when 3600 .. (3600*24-1)\n puts \"#{diff_seconds/3600} hours ago\"\n when (3600*24) .. (3600*24*30) \n puts \"#{diff_seconds/(3600*24)} days ago\"\n else\n puts start_time.strftime(\"%m/%d/%Y\")\n end\nend\n</code></pre>\n"
},
{
"answer_id": 195841,
"author": "Honza",
"author_id": 8621,
"author_profile": "https://Stackoverflow.com/users/8621",
"pm_score": 4,
"selected": false,
"text": "<p>What about</p>\n\n<pre><code>30.seconds.ago\n2.days.ago\n</code></pre>\n\n<p>Or something else you were shooting for?</p>\n"
},
{
"answer_id": 195883,
"author": "Ben Scofield",
"author_id": 6478,
"author_profile": "https://Stackoverflow.com/users/6478",
"pm_score": 9,
"selected": false,
"text": "<p>Sounds like you're looking for the <a href=\"http://apidock.com/rails/ActionView/Helpers/DateHelper/time_ago_in_words\" rel=\"noreferrer\"><code>time_ago_in_words</code></a> method (or <a href=\"http://apidock.com/rails/ActionView/Helpers/DateHelper/distance_of_time_in_words\" rel=\"noreferrer\"><code>distance_of_time_in_words</code></a>), from ActiveSupport. Call it like this:</p>\n\n<pre><code><%= time_ago_in_words(timestamp) %>\n</code></pre>\n"
},
{
"answer_id": 195894,
"author": "Matthias Winkelmann",
"author_id": 4494,
"author_profile": "https://Stackoverflow.com/users/4494",
"pm_score": 6,
"selected": false,
"text": "<p>I've written this, but have to check the existing methods mentioned to see if they are better.</p>\n\n<pre><code>module PrettyDate\n def to_pretty\n a = (Time.now-self).to_i\n\n case a\n when 0 then 'just now'\n when 1 then 'a second ago'\n when 2..59 then a.to_s+' seconds ago' \n when 60..119 then 'a minute ago' #120 = 2 minutes\n when 120..3540 then (a/60).to_i.to_s+' minutes ago'\n when 3541..7100 then 'an hour ago' # 3600 = 1 hour\n when 7101..82800 then ((a+99)/3600).to_i.to_s+' hours ago' \n when 82801..172000 then 'a day ago' # 86400 = 1 day\n when 172001..518400 then ((a+800)/(60*60*24)).to_i.to_s+' days ago'\n when 518400..1036800 then 'a week ago'\n else ((a+180000)/(60*60*24*7)).to_i.to_s+' weeks ago'\n end\n end\nend\n\nTime.send :include, PrettyDate\n</code></pre>\n"
},
{
"answer_id": 16182048,
"author": "davogones",
"author_id": 59631,
"author_profile": "https://Stackoverflow.com/users/59631",
"pm_score": 3,
"selected": false,
"text": "<p>Take a look at the instance methods here:</p>\n\n<p><a href=\"http://apidock.com/rails/Time\" rel=\"noreferrer\">http://apidock.com/rails/Time</a></p>\n\n<p>This has useful methods such as yesterday, tomorrow, beginning_of_week, ago, etc.</p>\n\n<p>Examples:</p>\n\n<pre><code>Time.now.yesterday\nTime.now.ago(2.days).end_of_day\nTime.now.next_month.beginning_of_month\n</code></pre>\n"
},
{
"answer_id": 17667180,
"author": "Brett Shollenberger",
"author_id": 2081409,
"author_profile": "https://Stackoverflow.com/users/2081409",
"pm_score": 1,
"selected": false,
"text": "<p>I've written a gem that does this for Rails ActiveRecord objects. The example uses created_at, but it will also work on updated_at or anything with the class ActiveSupport::TimeWithZone.</p>\n\n<p>Just gem install and call the 'pretty' method on your TimeWithZone instance. </p>\n\n<p><a href=\"https://github.com/brettshollenberger/hublot\" rel=\"nofollow\">https://github.com/brettshollenberger/hublot</a></p>\n"
},
{
"answer_id": 18798641,
"author": "seo",
"author_id": 2446285,
"author_profile": "https://Stackoverflow.com/users/2446285",
"pm_score": 5,
"selected": false,
"text": "<p>Just to clarify Andrew Marshall's solution for using <b>time_ago_in_words</b>\n<br />(For Rails 3.0 and Rails 4.0)</p>\n\n<p>If you are in a view</p>\n\n<pre><code><%= time_ago_in_words(Date.today - 1) %>\n</code></pre>\n\n<p>If you are in a controller</p>\n\n<pre><code>include ActionView::Helpers::DateHelper\ndef index\n @sexy_date = time_ago_in_words(Date.today - 1)\nend\n</code></pre>\n\n<p>Controllers do not have the module <a href=\"http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html\" rel=\"noreferrer\"><strong>ActionView::Helpers::DateHelper</strong></a> imported by default.</p>\n\n<p>N.B. It is not \"the rails way\" to import helpers into your controllers. Helpers are for helping views. The <b>time_ago_in_words</b> method was decided to be a <b>view</b> entity in the <b>MVC</b> triad. (I don't agree but when in rome...)</p>\n"
},
{
"answer_id": 21495459,
"author": "Rahul garg",
"author_id": 985051,
"author_profile": "https://Stackoverflow.com/users/985051",
"pm_score": 3,
"selected": false,
"text": "<p>Since the most answer here suggests <strong>time_ago_in_words</strong>.</p>\n\n<p>Instead of using :</p>\n\n<pre><code><%= time_ago_in_words(comment.created_at) %>\n</code></pre>\n\n<p>In Rails, prefer:</p>\n\n<pre><code><abbr class=\"timeago\" title=\"<%= comment.created_at.getutc.iso8601 %>\">\n <%= comment.created_at.to_s %>\n</abbr>\n</code></pre>\n\n<p>along with a jQuery library <a href=\"http://timeago.yarp.com/\" rel=\"nofollow noreferrer\">http://timeago.yarp.com/</a>, with code:</p>\n\n<pre><code>$(\"abbr.timeago\").timeago();\n</code></pre>\n\n<p>Main advantage: caching</p>\n\n<p><a href=\"http://rails-bestpractices.com/posts/2012/02/10/not-use-time_ago_in_words/\" rel=\"nofollow noreferrer\">http://rails-bestpractices.com/posts/2012/02/10/not-use-time_ago_in_words/</a></p>\n"
},
{
"answer_id": 40204562,
"author": "The Whiz of Oz",
"author_id": 1700874,
"author_profile": "https://Stackoverflow.com/users/1700874",
"pm_score": 0,
"selected": false,
"text": "<p>Another approach is to unload some logic from the backend and maek the browser do the job by using Javascript plugins such as:</p>\n\n<p><a href=\"https://github.com/rmm5t/jquery-timeago\" rel=\"nofollow\">jQuery time ago</a> or its <a href=\"https://github.com/jgraichen/rails-timeago\" rel=\"nofollow\">Rails Gem adaptation</a></p>\n"
},
{
"answer_id": 48931665,
"author": "Zack Xu",
"author_id": 874283,
"author_profile": "https://Stackoverflow.com/users/874283",
"pm_score": 2,
"selected": false,
"text": "<p>If you're building a Rails application, you should use</p>\n\n<pre><code>Time.zone.now\nTime.zone.today\nTime.zone.yesterday\n</code></pre>\n\n<p>This gives you time or date in the timezone with which you've configured your Rails application.</p>\n\n<p>For example, if you configure your application to use UTC, then <code>Time.zone.now</code> will always be in UTC time (it won't be impacted by the change of British Summertime for example).</p>\n\n<p>Calculating relative time is easy, eg</p>\n\n<pre><code>Time.zone.now - 10.minute\nTime.zone.today.days_ago(5)\n</code></pre>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm writing a Rails application, but can't seem to find how to do relative time, i.e. if given a certain Time class, it can calculate "30 seconds ago" or "2 days ago" or if it's longer than a month "9/1/2008", etc.
|
Sounds like you're looking for the [`time_ago_in_words`](http://apidock.com/rails/ActionView/Helpers/DateHelper/time_ago_in_words) method (or [`distance_of_time_in_words`](http://apidock.com/rails/ActionView/Helpers/DateHelper/distance_of_time_in_words)), from ActiveSupport. Call it like this:
```
<%= time_ago_in_words(timestamp) %>
```
|
195,741 |
<p>I'm trying to compile/link a <strong>very</strong> old piece of software on a linux system and I can't for some reason link with a shared library that's installed on my system.</p>
<p>I get the following error from the linker:</p>
<pre><code>/usr/bin/ld: cannot find -lXaw
</code></pre>
<p>However, the lib itself is installed. If I run </p>
<pre><code>ldconfig -v | grep libXaw
</code></pre>
<p>I get (among other things) this hit:</p>
<pre><code>libXaw.so.7 -> libXaw7.so.7.0.0
</code></pre>
<p>The library and the links to it are in /usr/lib btw. So nothing special.</p>
<p>So the library is there and ldconfig finds it. What could ld cause ld from not finding the library during link-time? As you may have already guessed I'm quite new to the shared library stuff. </p>
<p>Any ideas?</p>
|
[
{
"answer_id": 195762,
"author": "ejgottl",
"author_id": 9808,
"author_profile": "https://Stackoverflow.com/users/9808",
"pm_score": 3,
"selected": true,
"text": "<p>The linker may be looking, literally, for \"libXaw.so\". Is that in /usr/lib? If not, you could try adding it as another soft link from libXaw7.so.7.0.0.</p>\n"
},
{
"answer_id": 195777,
"author": "MarkR",
"author_id": 13724,
"author_profile": "https://Stackoverflow.com/users/13724",
"pm_score": -1,
"selected": false,
"text": "<p>To link it, you need the .a file, NOT the .so file, which is the runtime library. The shared object is only useful to a program already linked against the non-shared parts of a library. This is typically distributed in a \".a\" file.</p>\n"
},
{
"answer_id": 195822,
"author": "HUAGHAGUAH",
"author_id": 27233,
"author_profile": "https://Stackoverflow.com/users/27233",
"pm_score": 0,
"selected": false,
"text": "<p>Are the -L library directories being overridden, and it's not looking in /usr/lib?</p>\n"
},
{
"answer_id": 848777,
"author": "Marco van de Voort",
"author_id": 99354,
"author_profile": "https://Stackoverflow.com/users/99354",
"pm_score": 2,
"selected": false,
"text": "<p>The reason for the symlink btw is to select the default version to link against in the case of multiple versions, keep in mind the name of the library is integrated into the binary. (which you can see with ldd).</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15955/"
] |
I'm trying to compile/link a **very** old piece of software on a linux system and I can't for some reason link with a shared library that's installed on my system.
I get the following error from the linker:
```
/usr/bin/ld: cannot find -lXaw
```
However, the lib itself is installed. If I run
```
ldconfig -v | grep libXaw
```
I get (among other things) this hit:
```
libXaw.so.7 -> libXaw7.so.7.0.0
```
The library and the links to it are in /usr/lib btw. So nothing special.
So the library is there and ldconfig finds it. What could ld cause ld from not finding the library during link-time? As you may have already guessed I'm quite new to the shared library stuff.
Any ideas?
|
The linker may be looking, literally, for "libXaw.so". Is that in /usr/lib? If not, you could try adding it as another soft link from libXaw7.so.7.0.0.
|
195,742 |
<p>I can run the server on my local machine and connect to it on the same machine, but when I try to connect to it from a different computer over the internet, there is not sign of activity on my server, nor a response from the server on the computer I'm testing it on. I've tried both XP and Vista, turn off firewalls, opened ports, ran as admin; nothing is working. :(</p>
<p><strong>Here is my code that I'm using to accept an incoming connection:</strong><pre><code>
int port = 3326;
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Any, port));
listener.Start();
Console.WriteLine("Server established\nListening on Port: {0}\n", port);
while (true)
{
socket = listener.AcceptSocket();
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, outime);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
socket.DontFragment = true;
NewConnection pxy = new NewConnection(socket);
Thread client = new Thread(new ThreadStart(pxy.Start));
client.IsBackground = true;
client.Start();
}
}</code></pre></p>
|
[
{
"answer_id": 195746,
"author": "Justin Bozonier",
"author_id": 9401,
"author_profile": "https://Stackoverflow.com/users/9401",
"pm_score": -1,
"selected": false,
"text": "<p>If you are trying to host at home, your ISP may be restricting you.</p>\n"
},
{
"answer_id": 195749,
"author": "hectorsq",
"author_id": 14755,
"author_profile": "https://Stackoverflow.com/users/14755",
"pm_score": 4,
"selected": true,
"text": "<p>I think that the problem is in your router, not your computer. When packets come from the Internet, it should be routed to an specific server. You have to configure your router to redirect the traffic on port <code>3326</code> to your server.</p>\n"
},
{
"answer_id": 195781,
"author": "MarkR",
"author_id": 13724,
"author_profile": "https://Stackoverflow.com/users/13724",
"pm_score": 2,
"selected": false,
"text": "<p>You've probably got something blocking the connection higher up. Try connecting from another host on the LAN. If you can do that, then the OS itself isn't firewalling the connection.</p>\n\n<p>If either you or your ISP run a NAT router, then your machine probably doesn't have a publicly accessible address, in which case it's impossible to connect directly to it.</p>\n\n<p>If there is no NAT router, something may still be blocking the connection upstream.</p>\n"
},
{
"answer_id": 195827,
"author": "Justin Bozonier",
"author_id": 9401,
"author_profile": "https://Stackoverflow.com/users/9401",
"pm_score": 0,
"selected": false,
"text": "<p><strong>I am serious:</strong> Many ISPs actively work to <em>stop</em> you from using your home connection as a web server. You might want to call them before you invest too much time.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22582/"
] |
I can run the server on my local machine and connect to it on the same machine, but when I try to connect to it from a different computer over the internet, there is not sign of activity on my server, nor a response from the server on the computer I'm testing it on. I've tried both XP and Vista, turn off firewalls, opened ports, ran as admin; nothing is working. :(
**Here is my code that I'm using to accept an incoming connection:**
```
int port = 3326;
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Any, port));
listener.Start();
Console.WriteLine("Server established\nListening on Port: {0}\n", port);
while (true)
{
socket = listener.AcceptSocket();
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, outime);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
socket.DontFragment = true;
NewConnection pxy = new NewConnection(socket);
Thread client = new Thread(new ThreadStart(pxy.Start));
client.IsBackground = true;
client.Start();
}
}
```
|
I think that the problem is in your router, not your computer. When packets come from the Internet, it should be routed to an specific server. You have to configure your router to redirect the traffic on port `3326` to your server.
|
195,764 |
<p>Here's the XML file i'm working on:</p>
<pre><code><list>
<activity>swimming</activity>
<activity>running</activity>
<activity>soccer</activity>
</list>
</code></pre>
<p>The index.php, page that shows the list of activities with checkboxes, a button to delete the checked activities, and a field to add new activities:</p>
<pre><code><html>
<head></head>
<body>
<?php
$xmldoc = new DOMDocument();
$xmldoc->load('sample.xml', LIBXML_NOBLANKS);
$count = 0;
$activities = $xmldoc->firstChild->firstChild;
//prints the list of activities, with checkboxes on the left for each item
//the $count variable is the id to each entry
if($activities!=null){
echo '<form name=\'erase\' action=\'delete.php\' method=\'post\'>' . "\n";
while($activities!=null){
$count++;
echo " <input type=\"checkbox\" name=\"activity[]\" value=\"$count\"/>";
echo ' '.$activities->textContent.'<br/>'."\n";
$activities = $activities->nextSibling;
}
echo ' <input type=\'submit\' value=\'erase selected\'>';
echo '</form>';
}
?>
//section used for inserting new entries. this feature is working as expected.
<form name='input' action='insert.php' method='post'>
insert activity:
<input type='text name='activity'/>
<input type='submit' value='send'/>
<br/>
</form>
</body>
</html>
</code></pre>
<p>the delete.php, which is not working as expected:</p>
<pre><code><?php
$xmldoc = new DOMDocument();
$xmldoc->load('sample.xml', LIBXML_NOBLANKS);
$atvID = $_POST['activity'];
foreach($atvID as $id){
$delnode = $xmldoc->getElementsByTagName('activity');
$xmldoc->firstChild->removeChild($delnode->item($id));
}
$xmldoc->save('sample.xml');
?>
</code></pre>
<p>I've tested the deletion routine without the loop, using an hard-coded arbitrary id, and it worked. I also tested the $atvID array, and it printed the selected id numbers correctly. When it is inside the loop, here's the error it outputs:</p>
<blockquote>
<p>Catchable fatal error: Argument 1
passed to DOMNode::removeChild() must
be an instance of DOMNode, null given
in
/directorypath/delete.php
on line 9</p>
</blockquote>
<p>What is wrong with my code?</p>
|
[
{
"answer_id": 195774,
"author": "Czimi",
"author_id": 3906,
"author_profile": "https://Stackoverflow.com/users/3906",
"pm_score": 3,
"selected": true,
"text": "<p>the DOMNodeList items are indexed starting with 0;\nYou need to move the $count++ to the end of the while loop in the output step.</p>\n"
},
{
"answer_id": 198955,
"author": "david",
"author_id": 27600,
"author_profile": "https://Stackoverflow.com/users/27600",
"pm_score": 1,
"selected": false,
"text": "<p>In addition to moving $count++ to the end of the while loop, it might be a good idea to have delete.php check to make sure the $_POST['activity'] is numeric and within the specified range, just to ensure there are no fatal error messages generated on your page.</p>\n"
},
{
"answer_id": 203430,
"author": "John ODonnell",
"author_id": 28072,
"author_profile": "https://Stackoverflow.com/users/28072",
"pm_score": 1,
"selected": false,
"text": "<p>The tricky thing about DOMNodeLists is that they are NOT arrays. If you delete a node, the list will re-index. This will cause your code to break if a user selects more than one item for deletion. If you selected swimming and running, swimming and soccer would be deleted.</p>\n\n<p>You might want to start by giving each activity a unique identifier you can search for, say an attribute called 'id' (this likely wouldn't be a real ID. The DOM's getElementByID() only works for XML that has a DTD, like an HTML page. I'm guessing you don't want to go there.)</p>\n\n<p>You might update you're XML to look like this.</p>\n\n<pre><code><list>\n <activity name=\"swimming\">swimming</activity>\n <activity name=\"running\">running</activity>\n <activity name=\"soccer\">soccer</activity>\n</list>\n</code></pre>\n\n<p>You'd use these name attributes instead of $count as the value inside your checkboxes.</p>\n\n<p>You can then use xPath to find items to remove inside your foreach.</p>\n\n<pre><code>$xpath = new DOMXPath($xmldoc);\n$xmldoc->firstChild->removeChild($xpath->query(\"/list/activity[@name='$id']\")->item(0));\n</code></pre>\n\n<p>Hope this helps get you started.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27090/"
] |
Here's the XML file i'm working on:
```
<list>
<activity>swimming</activity>
<activity>running</activity>
<activity>soccer</activity>
</list>
```
The index.php, page that shows the list of activities with checkboxes, a button to delete the checked activities, and a field to add new activities:
```
<html>
<head></head>
<body>
<?php
$xmldoc = new DOMDocument();
$xmldoc->load('sample.xml', LIBXML_NOBLANKS);
$count = 0;
$activities = $xmldoc->firstChild->firstChild;
//prints the list of activities, with checkboxes on the left for each item
//the $count variable is the id to each entry
if($activities!=null){
echo '<form name=\'erase\' action=\'delete.php\' method=\'post\'>' . "\n";
while($activities!=null){
$count++;
echo " <input type=\"checkbox\" name=\"activity[]\" value=\"$count\"/>";
echo ' '.$activities->textContent.'<br/>'."\n";
$activities = $activities->nextSibling;
}
echo ' <input type=\'submit\' value=\'erase selected\'>';
echo '</form>';
}
?>
//section used for inserting new entries. this feature is working as expected.
<form name='input' action='insert.php' method='post'>
insert activity:
<input type='text name='activity'/>
<input type='submit' value='send'/>
<br/>
</form>
</body>
</html>
```
the delete.php, which is not working as expected:
```
<?php
$xmldoc = new DOMDocument();
$xmldoc->load('sample.xml', LIBXML_NOBLANKS);
$atvID = $_POST['activity'];
foreach($atvID as $id){
$delnode = $xmldoc->getElementsByTagName('activity');
$xmldoc->firstChild->removeChild($delnode->item($id));
}
$xmldoc->save('sample.xml');
?>
```
I've tested the deletion routine without the loop, using an hard-coded arbitrary id, and it worked. I also tested the $atvID array, and it printed the selected id numbers correctly. When it is inside the loop, here's the error it outputs:
>
> Catchable fatal error: Argument 1
> passed to DOMNode::removeChild() must
> be an instance of DOMNode, null given
> in
> /directorypath/delete.php
> on line 9
>
>
>
What is wrong with my code?
|
the DOMNodeList items are indexed starting with 0;
You need to move the $count++ to the end of the while loop in the output step.
|
195,768 |
<p>I'm in search of a JavaScript month selection tool. I'm already using jQuery on the website, so if it were a jQuery plugin, that would fit nicely. I'm open to other options, as well.</p>
<p>Basically, I'm after a simplified version of the <a href="http://docs.jquery.com/UI/Datepicker" rel="noreferrer">jQuery UI Date Picker</a>. I don't care about the day of the month, just the month and year. Using the Date Picker control feels like overkill and a kludge. I know I could just use a pair of select boxes, but that feels cluttered, and then I also need a confirmation button.</p>
<p>I'm envisioning a grid of either two rows of six columns, or three rows of four columns, for month selection, and current and future years across the top. (Maybe the ability to list a few years? I can't see anyone ever needing to go more than a year or two ahead, so if I could list the current and next two years, that would be swell.)</p>
<p>It's really just a dumbed down version of the DatePicker. Does something like this exist?</p>
|
[
{
"answer_id": 196077,
"author": "Paolo Bergantino",
"author_id": 16417,
"author_profile": "https://Stackoverflow.com/users/16417",
"pm_score": 2,
"selected": false,
"text": "<p>I used <a href=\"http://www.mattkruse.com/javascript/calendarpopup/\" rel=\"nofollow noreferrer\">this script</a> in a program a while back. While it is ancient, it works on all browsers well. If you look down to \"Month-select calendar\" I believe that is what you are looking for. The example that is there has the calendar opening in a new window (ew) but 1 setting (like the 2nd example) makes it show ala jQuery. Good luck.</p>\n"
},
{
"answer_id": 854928,
"author": "jj.",
"author_id": 103131,
"author_profile": "https://Stackoverflow.com/users/103131",
"pm_score": 0,
"selected": false,
"text": "<p>I just had a pick a date picker the other day. I found two other interesting examples that <em>might</em> help you out, but I'm not sure how you are going to do this without showing the calendar. Most \"date pickers\" just assume you are going to want to see a calendar. You might do better to look for a custom dropdown that has some custom buttons you can configure.</p>\n\n<p>Here are the ones I looked at:</p>\n\n<p><a href=\"http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/index.html\" rel=\"nofollow noreferrer\">http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/index.html</a></p>\n\n<p>I ended up using this one:\n<a href=\"http://jqueryui.com/demos/datepicker/\" rel=\"nofollow noreferrer\">http://jqueryui.com/demos/datepicker/</a> </p>\n\n<p>If you are any good with JQuery, you might have come up with a good little project.</p>\n"
},
{
"answer_id": 3348217,
"author": "Cory",
"author_id": 8207,
"author_profile": "https://Stackoverflow.com/users/8207",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/users/11996/ben-koehler\">Ben Koehler</a> from <a href=\"https://stackoverflow.com/questions/2208480/jquery-date-picker-to-show-month-year-only\">this equivalent question</a> offers a jquery ui hack that works decently. Quoted here for convenience, all credit is his.</p>\n\n<p><a href=\"http://jsfiddle.net/yLjDH/\" rel=\"nofollow noreferrer\">JSFiddle of this solution</a></p>\n\n<p>-- \nHere's a hack (updated with entire .html file):</p>\n\n<pre><code><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n<head>\n <script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js\"></script>\n <script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js\"></script>\n <link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css\">\n<script type=\"text/javascript\">\n$(function() {\n $('.date-picker').datepicker( {\n changeMonth: true,\n changeYear: true,\n showButtonPanel: true,\n dateFormat: 'MM yy',\n onClose: function(dateText, inst) { \n var month = $(\"#ui-datepicker-div .ui-datepicker-month :selected\").val();\n var year = $(\"#ui-datepicker-div .ui-datepicker-year :selected\").val();\n $(this).datepicker('setDate', new Date(year, month, 1));\n }\n });\n});\n</script>\n<style>\n.ui-datepicker-calendar {\n display: none;\n }\n</style>\n</head>\n<body>\n <label for=\"startDate\">Date :</label>\n <input name=\"startDate\" id=\"startDate\" class=\"date-picker\" />\n</body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 13338634,
"author": "Ramon Tayag",
"author_id": 61018,
"author_profile": "https://Stackoverflow.com/users/61018",
"pm_score": 3,
"selected": false,
"text": "<p>Found one on <a href=\"https://github.com/lucianocosta/jquery.mtz.monthpicker\" rel=\"nofollow noreferrer\">lucianocosta.info</a>. It looks pretty good:</p>\n\n<p><img src=\"https://i.stack.imgur.com/WOmmC.png\" alt=\"Month Picker in action\"></p>\n\n<p>UPDATED 2016-02-13: link that works</p>\n"
},
{
"answer_id": 19389060,
"author": "gustavohenke",
"author_id": 2083599,
"author_profile": "https://Stackoverflow.com/users/2083599",
"pm_score": 5,
"selected": true,
"text": "<p>To anyone <em>still</em> looking forward into this (as I was), here is an beautiful, easy to use, jQuery UI compatible, well documented, tested alternative:</p>\n\n<p><img src=\"https://i.stack.imgur.com/o8h3F.gif\" alt=\"Month picker example\"></p>\n\n<p>Its default usage is simple as doing the following:</p>\n\n<pre><code>$(\"input[type='month']\").MonthPicker();\n</code></pre>\n\n<ul>\n<li><a href=\"https://github.com/KidSysco/jquery-ui-month-picker\">GitHub</a></li>\n<li><a href=\"http://jsfiddle.net/kidsysco/JeZap/\">Fiddle with Examples and tests</a></li>\n</ul>\n"
},
{
"answer_id": 32613585,
"author": "Apolo",
"author_id": 3484498,
"author_profile": "https://Stackoverflow.com/users/3484498",
"pm_score": 2,
"selected": false,
"text": "<p>Feel free to have a look on my own jQuery plugin :</p>\n\n<p><a href=\"https://i.stack.imgur.com/6FSWA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6FSWA.png\" alt=\"Monthpicker screenshot\"></a></p>\n\n<p>Easy to use :</p>\n\n<pre><code>$(\"#myTextInput\").Monthpicker();\n</code></pre>\n\n<p>There is not a lot of options yet, but you can bound the input to a restricted range of month.</p>\n\n<p>There are also events that provide a way of coding interdependency between two monthpicker (start & end date)</p>\n\n<p>You can find a live demo here : <a href=\"http://codepen.io/VincentCharpentier/full/WQrozB\" rel=\"nofollow noreferrer\">Codepen</a></p>\n\n<p>You are free to take the source code from Github and change whatever you want : <a href=\"https://github.com/VincentCharpentier/Simple-MonthPicker\" rel=\"nofollow noreferrer\">Github repository</a></p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/751/"
] |
I'm in search of a JavaScript month selection tool. I'm already using jQuery on the website, so if it were a jQuery plugin, that would fit nicely. I'm open to other options, as well.
Basically, I'm after a simplified version of the [jQuery UI Date Picker](http://docs.jquery.com/UI/Datepicker). I don't care about the day of the month, just the month and year. Using the Date Picker control feels like overkill and a kludge. I know I could just use a pair of select boxes, but that feels cluttered, and then I also need a confirmation button.
I'm envisioning a grid of either two rows of six columns, or three rows of four columns, for month selection, and current and future years across the top. (Maybe the ability to list a few years? I can't see anyone ever needing to go more than a year or two ahead, so if I could list the current and next two years, that would be swell.)
It's really just a dumbed down version of the DatePicker. Does something like this exist?
|
To anyone *still* looking forward into this (as I was), here is an beautiful, easy to use, jQuery UI compatible, well documented, tested alternative:

Its default usage is simple as doing the following:
```
$("input[type='month']").MonthPicker();
```
* [GitHub](https://github.com/KidSysco/jquery-ui-month-picker)
* [Fiddle with Examples and tests](http://jsfiddle.net/kidsysco/JeZap/)
|
195,794 |
<p>Assuming Visual C/C++ 6, I have a complex data structure of 22399 elements that looks like this:</p>
<pre><code>{
{ "(SAME", "AS", "U+4E18)", "HILLOCK", "OR", "MOUND"},
{ "TO", "LICK;", {1, 1, 0}, "TASTE,", "A", "MAT,", "BAMBOO", "BARK"},
{ "(J)", "NON-STANDARD", "FORM", "OF", "U+559C", ",", {1, 1, 0}, "LIKE,", "LOVE,", "ENJOY;", {1, 1, 4}, "JOYFUL", "THING"},
{ "(AN", "ANCIENT", {1, 2, 2}, {1, 2, 3}, "U+4E94)", "FIVE"},
...
}
</code></pre>
<p>What's the best way to declare this? I've tried things like </p>
<pre><code>char * abbrevs3[22399][] = { ... };
</code></pre>
<p>and </p>
<pre><code>char * abbrevs3[22399][][] = { ... };
</code></pre>
<p>but the compile whinges something chronic. </p>
<p><strong>EDIT</strong>: The data is a database of descriptions of certain Unihan characters. I've been exploring various ways of compacting the data. As it stands you have 22399 entries, each of which may contain a varying number of strings, or triplets of { abbrev marker, line where last seen, element of that line where last seen }. </p>
<p>By the way Greg's talking, I may need to have each line contain the same number of elements, even if some of them are empty strings. Is that the case?</p>
<p><strong>EDIT #2</strong>: And it occurs to me that some of the numeric values in the triplets are way outside the limits of char.</p>
|
[
{
"answer_id": 195805,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>In C, you can only leave out the <em>first</em> dimension when declaring an array:</p>\n\n<pre><code>char * abbrevs3[][22399] = { ... };\n</code></pre>\n\n<p>This is because the compiler wants to know how big each \"row\" is, so that it can lay out the \"columns\" properly. I put the dimensions in quotes because you are free to interpret the dimensions in whatever way you wish, but that is the usual convention for a two-dimensional array.</p>\n\n<p>That said, it is unclear what your data structure actually is or what you're trying to initialise it to. Your sample data doesn't seem to have any kind of pattern to it.</p>\n"
},
{
"answer_id": 195825,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "<p>I would look into storing the data in XML or some other structured form, then reading and parsing it instead of making the initialization in the code. The penalty that you pay at initialization will more than be made up in the ease of understanding and increase in maintainability of your code. I'd also consider designing a specific data structure to hold each entry. </p>\n\n<p>[EDIT] The example below attempts to replicate your subsequent description:</p>\n\n<pre><code>enum EntryType { string = 0, triple = 1 };\n\ntypedef struct {\n enum EntryType entry_type;\n union {\n char** string;\n int[3] *triple;\n }\n} Entry;\n\ntypedef struct {\n Entry *entries;\n} Abbreviation;\n\nAbbreviation *abbrevs3;\n\nabbrevs3 = parseAbbreviationData(\"path-to-abbreviations/abbrevs.xml\");\n</code></pre>\n"
},
{
"answer_id": 195860,
"author": "ryan_s",
"author_id": 13728,
"author_profile": "https://Stackoverflow.com/users/13728",
"pm_score": 1,
"selected": false,
"text": "<p>I think the question here is whether you can statically declare a multi-dimensional array of C style strings where there are a different number of strings on each row. So, something like this:</p>\n\n<pre><code>const char * arr[][3] =\n {\n {\"bla\", \"bla\", \"bla\"},\n {\"bla\", \"bla\" }\n };\n</code></pre>\n\n<p>In some languages this is referred to as a \"jagged array.\" In C and C++ you can do this, though the compiler will want to allocate space to store all the rows as though they're the same length, so you'll end up not initializing the 3rd item of the second array. When I tested this out on gcc the third item in that array was set to NULL, but I don't know if you can count on that.</p>\n\n<p>I don't think you'll be able to get the compiler to accept arrays declared like {1,2,3} as C style strings. Even if it did, and you treated these as strings, you'd have a problem since they're not null terminated.</p>\n\n<p>I'd agree with the other posters, a better approach is probably to store this data in XML, yaml, or possibly in the database you're taking them from, and access them there. If you do need to create these statically in a source file you'll probably be better off declaring a structure that makes sense for your data and initializing an array of those. Something like:</p>\n\n<pre><code>typedef struct\n{\n const char * somestring;\n const char * someotherstring;\n const unsigned int triple[3];\n} Abbreviation;\n\nconst Abbreviation abb[] =\n {\n {\"First Thing\", \"Second String\", {1,2,3} },\n {\"Other Thing\", \"Some String\", {4,5,6} }\n };\n</code></pre>\n"
},
{
"answer_id": 197921,
"author": "bugmagnet",
"author_id": 426,
"author_profile": "https://Stackoverflow.com/users/426",
"pm_score": 0,
"selected": false,
"text": "<p>The saga is not over yet it seems. I eventually ended up turning everything into a ragged array of <code>int</code>. But with that is lost the idea of items in a line which the self-referential mechanism behind the triplets was depending on.</p>\n\n<p>Am now looking into using <a href=\"http://rapideuphoria.com\" rel=\"nofollow noreferrer\">Euphoria</a> rather than C, because of its superior support for ragged arrays. One can build standard DLLs with Euphoria and, once I figure out how to hand back a variant array of BSTR and write a Typelib ...</p>\n\n<p>Mind you, I suppose I could stick with C and store triplets as just three ints in a row, and store the strings as pointers cast as integers. And that would save me a rather large rewrite of the VBScript that built the self-referential dictionary in the first place.</p>\n"
},
{
"answer_id": 198411,
"author": "ryan_s",
"author_id": 13728,
"author_profile": "https://Stackoverflow.com/users/13728",
"pm_score": 3,
"selected": true,
"text": "<p>I just read your new posts and re-read the original post, and I think I just fully understood the goal here. Sorry it took so long, I'm kind of slow.</p>\n\n<p>To paraphrase the question, on line 4 of the original example:</p>\n\n<pre><code>{ \"(AN\", \"ANCIENT\", {1, 2, 2}, {1, 2, 3}, \"U+4E94)\", \"FIVE\"},\n</code></pre>\n\n<p>You'd want to translate the triples into references to strings used earlier, in an attempt to compress the data. That line becomes:</p>\n\n<pre><code>{ \"(AN\", \"ANCIENT\", \"FORM\", \"OF\", \"U+4E94)\", \"FIVE\"},\n</code></pre>\n\n<p>If the goal is compression I don't think you'll see much gain here. The self-referencing triples are each 3 bytes, but the strings that are being substituted out are only 8 bytes total, counting null terminators, and you only save 2 bytes on this line. And that's for using chars. Since your structure is so big that you're going to need to use ints for references, your triple is actually 12 bytes, which is even worse. In this case you'll only ever save space by substituting for words that are 12 ascii characters or more.</p>\n\n<p>If I'm totally off base here then feel free to ignore me, but I think the approach of tokenizing on spaces and then removing duplicate words is just kind of a poor man's <a href=\"http://en.wikipedia.org/wiki/Huffman_coding\" rel=\"nofollow noreferrer\">Huffman compression</a>. Huffman where the alphabet is a list of <a href=\"http://en.wikipedia.org/wiki/Longest_common_substring_problem\" rel=\"nofollow noreferrer\">longest common substrings</a>, or some other standard text compression method would probably work well for this problem.</p>\n\n<p>If for some reason this isn't an option though, I think I would get a list of all unique words in your data and use that as a lookup table. Then store all strings as a list of indexes into that table. You'd have to use two tables, but in the end it might be simpler, and it would save you the space being used by the leading 1's you're using as the \"abbrev marker\" now. Basically, your abbreviation markers would become a single index instead of a triplet.</p>\n\n<p>So,</p>\n\n<pre><code>const char * words[] = {\n \"hello\", \"world\", \"goodbye\", \"cruel\"\n };\n\nconst int strings[] = {\n { 0, 1 },\n { 2, 3, 1 }\n };\n</code></pre>\n\n<p>You'd still lose a lot of space if your strings aren't of roughly uniform length though.</p>\n"
},
{
"answer_id": 199700,
"author": "bugmagnet",
"author_id": 426,
"author_profile": "https://Stackoverflow.com/users/426",
"pm_score": 1,
"selected": false,
"text": "<p>The original data is about 1.7MB which was derived from 2 other files, one from my employer and the other (Unihan.txt, at about 30MB) from the Unicode Consortium. Using the dictionary look-up technique, using a dictionary of the top 128 longest and most frequently occurring words, only brings the data size down to 1.5MB. I could probably improve that by being more intelligent with my word detection, which currently is just a VBScript Split() on space.</p>\n\n<p>I don't have any figures for how small I get with the quasi-Huffman approach, but my guess is that it's slightly less than 1MB. I was wanting to have all of this in the binary rather than as a separate file (despite what others may say about bad practice etc.) As it stands, however, it's all getting just a bit too hard, at least in C. If I can figure out how to create variant arrays of BSTR in Euphoria ...</p>\n\n<p><strong>EDIT</strong>: I have used the dictionary lookup with respect to standard UCNs and that works well due to the repetitive nature of glyph descriptions. The problem with the Unihan is that you end up with a description of what the glyph <em>means</em>; there's a qualitative (and quantitative!) difference between <code>\"VULGAR FRACTION ONE QUARTER\"</code> and <code>\"A KIND OF PUNISHMENT IN HAN DYNASTY, NAME OF CHESSMEN IN CHINESE CHESS GAME(SIMPLIFIED FORM, A VARIANT U+7F75) TO CURSE; TO REVILE; TO ABUSE, TO SCOLD\"</code></p>\n\n<p>Thus the move away from the dictionary look-up and toward some more-powerful \"compression\" technique. </p>\n\n<p>(And before anyone says, \"so what's the big deal with 1.7MB?\", I come from an era where 16K RAM was a lot. And I have space constraints in any case.)</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/426/"
] |
Assuming Visual C/C++ 6, I have a complex data structure of 22399 elements that looks like this:
```
{
{ "(SAME", "AS", "U+4E18)", "HILLOCK", "OR", "MOUND"},
{ "TO", "LICK;", {1, 1, 0}, "TASTE,", "A", "MAT,", "BAMBOO", "BARK"},
{ "(J)", "NON-STANDARD", "FORM", "OF", "U+559C", ",", {1, 1, 0}, "LIKE,", "LOVE,", "ENJOY;", {1, 1, 4}, "JOYFUL", "THING"},
{ "(AN", "ANCIENT", {1, 2, 2}, {1, 2, 3}, "U+4E94)", "FIVE"},
...
}
```
What's the best way to declare this? I've tried things like
```
char * abbrevs3[22399][] = { ... };
```
and
```
char * abbrevs3[22399][][] = { ... };
```
but the compile whinges something chronic.
**EDIT**: The data is a database of descriptions of certain Unihan characters. I've been exploring various ways of compacting the data. As it stands you have 22399 entries, each of which may contain a varying number of strings, or triplets of { abbrev marker, line where last seen, element of that line where last seen }.
By the way Greg's talking, I may need to have each line contain the same number of elements, even if some of them are empty strings. Is that the case?
**EDIT #2**: And it occurs to me that some of the numeric values in the triplets are way outside the limits of char.
|
I just read your new posts and re-read the original post, and I think I just fully understood the goal here. Sorry it took so long, I'm kind of slow.
To paraphrase the question, on line 4 of the original example:
```
{ "(AN", "ANCIENT", {1, 2, 2}, {1, 2, 3}, "U+4E94)", "FIVE"},
```
You'd want to translate the triples into references to strings used earlier, in an attempt to compress the data. That line becomes:
```
{ "(AN", "ANCIENT", "FORM", "OF", "U+4E94)", "FIVE"},
```
If the goal is compression I don't think you'll see much gain here. The self-referencing triples are each 3 bytes, but the strings that are being substituted out are only 8 bytes total, counting null terminators, and you only save 2 bytes on this line. And that's for using chars. Since your structure is so big that you're going to need to use ints for references, your triple is actually 12 bytes, which is even worse. In this case you'll only ever save space by substituting for words that are 12 ascii characters or more.
If I'm totally off base here then feel free to ignore me, but I think the approach of tokenizing on spaces and then removing duplicate words is just kind of a poor man's [Huffman compression](http://en.wikipedia.org/wiki/Huffman_coding). Huffman where the alphabet is a list of [longest common substrings](http://en.wikipedia.org/wiki/Longest_common_substring_problem), or some other standard text compression method would probably work well for this problem.
If for some reason this isn't an option though, I think I would get a list of all unique words in your data and use that as a lookup table. Then store all strings as a list of indexes into that table. You'd have to use two tables, but in the end it might be simpler, and it would save you the space being used by the leading 1's you're using as the "abbrev marker" now. Basically, your abbreviation markers would become a single index instead of a triplet.
So,
```
const char * words[] = {
"hello", "world", "goodbye", "cruel"
};
const int strings[] = {
{ 0, 1 },
{ 2, 3, 1 }
};
```
You'd still lose a lot of space if your strings aren't of roughly uniform length though.
|
195,802 |
<p>I was wondering if there was any difference in the way the following code was compiled into assembly. I've heard that switch-case is more efficient than if else, but in this example I am not quite sure if that would be the case.</p>
<pre><code>if(x==1){
...
}else if(x==2){
...
}else{
...
}
</code></pre>
<p>and</p>
<pre><code>switch(x){
case 1:
...
break;
case 2:
...
break;
default:
...
}
</code></pre>
|
[
{
"answer_id": 195810,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 2,
"selected": false,
"text": "<p>In <em>this</em> specific case, the <code>switch</code> can be turned into a jump table. The <code>if</code> statement (if you write your <code>=</code> as <code>==</code> :-P) could still do the same thing if the compiler could tell that <code>x</code> isn't changing between the <code>if</code> clauses (which is usually the case, unless <code>x</code> is <code>volatile</code> or something).</p>\n"
},
{
"answer_id": 195818,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>A compiler will sometimes turn a switch into a jump-table, if the entries are contiguous (or nearly so). Or it could theoretically use a binary search to find the case instead of a linear series of tests, which would be faster if you had a large number of cases.</p>\n\n<p>On the other hand, there's nothing stopping the compiler from doing the same optimisations on the same code converted into if/else.</p>\n\n<p>So on a good compiler, switch can be faster in some cases. On a very good compiler, they'd be the same.</p>\n"
},
{
"answer_id": 196655,
"author": "Moishe Lettvin",
"author_id": 23786,
"author_profile": "https://Stackoverflow.com/users/23786",
"pm_score": 2,
"selected": false,
"text": "<p>Note too that the if/else construct can be more efficient if you know certain cases are more likely than others.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17162/"
] |
I was wondering if there was any difference in the way the following code was compiled into assembly. I've heard that switch-case is more efficient than if else, but in this example I am not quite sure if that would be the case.
```
if(x==1){
...
}else if(x==2){
...
}else{
...
}
```
and
```
switch(x){
case 1:
...
break;
case 2:
...
break;
default:
...
}
```
|
A compiler will sometimes turn a switch into a jump-table, if the entries are contiguous (or nearly so). Or it could theoretically use a binary search to find the case instead of a linear series of tests, which would be faster if you had a large number of cases.
On the other hand, there's nothing stopping the compiler from doing the same optimisations on the same code converted into if/else.
So on a good compiler, switch can be faster in some cases. On a very good compiler, they'd be the same.
|
195,809 |
<p>I am thinking of developing a web search engine using Erlang, Mnesia & Yaws. Is it possible to make a powerful and the fastest web search engine using these software? What will it need to accomplish this and how what do I start with? </p>
|
[
{
"answer_id": 195828,
"author": "dimus",
"author_id": 23080,
"author_profile": "https://Stackoverflow.com/users/23080",
"pm_score": 2,
"selected": false,
"text": "<p>As far as I know <a href=\"http://www.powerset.com\" rel=\"nofollow noreferrer\">Powerset</a>'s natural language procesing search engine is developed using erlang.</p>\n\n<p>Did you look at <a href=\"http://incubator.apache.org/couchdb/\" rel=\"nofollow noreferrer\">couchdb</a> (which is written in erlang as well) as a possible tool to help you to solve few problems on your way? </p>\n"
},
{
"answer_id": 213571,
"author": "uwiger",
"author_id": 6834,
"author_profile": "https://Stackoverflow.com/users/6834",
"pm_score": 1,
"selected": false,
"text": "<p>In the <a href=\"http://jungerl.cvs.sourceforge.net/viewvc/jungerl/jungerl/lib/rdbms/src/\" rel=\"nofollow noreferrer\">'rdbms' contrib</a>, there is an implementation of the Porter Stemming Algorithm. It was never integrated into 'rdbms', so it's basically just sitting out there. We have used it internally, and it worked quite well, at least for datasets that weren't huge (I haven't tested it on huge data volumes).</p>\n\n<p>The relevant modules are:</p>\n\n<pre><code>rdbms_wsearch.erl\nrdbms_wsearch_idx.erl\nrdbms_wsearch_porter.erl\n</code></pre>\n\n<p>Then there is, of course, the <a href=\"http://discoproject.org/\" rel=\"nofollow noreferrer\">Disco Map-Reduce framework</a>.</p>\n\n<p>Whether or not you can make the fastest engine out there, I couldn't say. Is there a market for a <em>faster</em> search engine? I've never had problems with the speed of e.g. Google. But a search facility that increased my chances of finding good answers to my questions would interest me.</p>\n"
},
{
"answer_id": 283674,
"author": "bjnortier",
"author_id": 35448,
"author_profile": "https://Stackoverflow.com/users/35448",
"pm_score": 2,
"selected": false,
"text": "<p>I would recommend CouchDB instead of Mnesia.</p>\n\n<ul>\n<li>Mnesia doesn't have Map-Reduce, CouchDB does (correction - see comments)</li>\n<li>Mnesia is statically typed, CouchDB is a document database (and pages are documents, i.e. a better fit to the information model in my opinion)</li>\n<li><a href=\"http://www.erlang.org/faq/mnesia.html\" rel=\"nofollow noreferrer\">Mnesia is primarily intended to be a memory-resident database</a></li>\n</ul>\n\n<p>YAWS is pretty good. You should also consider MochiWeb.</p>\n\n<p>You won't go wrong with Erlang</p>\n"
},
{
"answer_id": 4004413,
"author": "Muzaaya Joshua",
"author_id": 431620,
"author_profile": "https://Stackoverflow.com/users/431620",
"pm_score": 5,
"selected": true,
"text": "<p>Erlang can make the most powerful web crawler today. Let me take you through my simple crawler.</p>\n\n<p>Step 1. I create a simple parallelism module, which i call <i> mapreduce</i></p>\n\n<pre>\n-module(mapreduce).\n-export([compute/2]).\n%%=====================================================================\n%% usage example\n%% Module = string\n%% Function = tokens\n%% List_of_arg_lists = [[\"file\\r\\nfile\",\"\\r\\n\"],[\"muzaaya_joshua\",\"_\"]]\n%% Ans = [[\"file\",\"file\"],[\"muzaaya\",\"joshua\"]]\n%% Job being done by two processes\n%% i.e no. of processes spawned = length(List_of_arg_lists)\n\ncompute({Module,Function},List_of_arg_lists)->\n S = self(),\n Ref = erlang:make_ref(),\n PJob = fun(Arg_list) -> erlang:apply(Module,Function,Arg_list) end,\n Spawn_job = fun(Arg_list) -> \n spawn(fun() -> execute(S,Ref,PJob,Arg_list) end)\n end,\n lists:foreach(Spawn_job,List_of_arg_lists),\n gather(length(List_of_arg_lists),Ref,[]).<br> \ngather(0, _, L) -> L;\ngather(N, Ref, L) ->\n receive\n {Ref,{'EXIT',_}} -> gather(N-1,Ref,L);\n {Ref, Result} -> gather(N-1, Ref, [Result|L])\n end.<br> \nexecute(Parent,Ref,Fun,Arg)->\n Parent ! {Ref,(catch Fun(Arg))}.\n</pre>\n\n<p>\nStep 2.<b> The HTTP Client</b><br><br>\nOne would normally use either <code>inets httpc module</code> built into erlang or <code><a href=\"https://github.com/cmullaparthi/ibrowse\" rel=\"noreferrer\">ibrowse</a></code>. However, for memory management and speed (getting the memory foot print as low as possible), a good erlang programmer would choose to use <code><a href=\"http://curl.haxx.se/docs/manual.html\" rel=\"noreferrer\">curl</a></code>. By applying the <code><a href=\"http://www.erlang.org/doc/man/os.html#cmd-1\" rel=\"noreferrer\">os:cmd/1</a></code> which takes that curl command line, one would get the output direct into the erlang calling function. Yet still, its better, to make curl throw its outputs into files and then our application has another thread (process) which reads and parses these files<pre>\n<b>Command</b>: curl \"http://www.erlang.org\" -o \"/downloaded_sites/erlang/file1.html\"<br>\n<b>In Erlang</b><br>\nos:cmd(\"curl \\\"http://www.erlang.org\\\" -o \\\"/downloaded_sites/erlang/file1.html\\\"\").\n</pre> So you can spawn many processes. You remember to escape the URL as well as the output file path as you execute that command. There is a process on the other hand whose work is to watch the directory of downloaded pages. These pages it reads and parses them, it may then delete after parsing or save in a different location or even better, archive them using the <code>zip module</code><pre>\nfolder_check()->\n spawn(fun() -> check_and_report() end),\n ok.\n\n-define(CHECK_INTERVAL,5).\n\ncheck_and_report()->\n %% avoid using\n %% filelib:list_dir/1\n %% if files are many, memory !!!\n case os:cmd(\"ls | wc -l\") of\n \"0\\n\" -> ok;\n \"0\" -> ok;\n _ -> ?MODULE:new_files_found()\n end,\n sleep(timer:seconds(?CHECK_INTERVAL)),\n %% keep checking\n check_and_report().\n\nnew_files_found()->\n %% inform our parser to pick files\n %% once it parses a file, it has to \n %% delete it or save it some\n %% where else\n gen_server:cast(?MODULE,files_detected).\n</pre>\n</p>\n\n<p><p>\nStep 3. <b>The html parser.</b><br>\nBetter use this <code><a href=\"http://ppolv.wordpress.com/2008/05/09/fun-with-mochiwebs-html-parser-and-xpath/\" rel=\"noreferrer\">mochiweb's html parser and XPATH</a></code>. This will help you parse and get all your favorite HTML tags, extract the contents and then good to go. The examples below, i focused on only the <code>Keywords</code>, <code>description</code> and <code>title</code> in the markup \n</p><br></p>\n\n<p>\n<b>Module Testing in shell...awesome results!!!</b>\n<pre>\n2> spider_bot:parse_url(\"http://erlang.org\").\n[[[],[],\n {\"keywords\",\n \"erlang, functional, programming, fault-tolerant, distributed, multi-platform, portable, software, multi-core, smp, concurrency \"},\n {\"description\",\"open-source erlang official website\"}],\n {title,\"erlang programming language, official website\"}]\n</pre>\n<br>\n<pre>\n3> spider_bot:parse_url(\"http://facebook.com\").\n[[{\"description\",\n \" facebook is a social utility that connects people with friends and others who work, study and live around them. people use facebook to keep up with friends, upload an unlimited number of photos, post links\n and videos, and learn more about the people they meet.\"},\n {\"robots\",\"noodp,noydir\"},\n [],[],[],[]],\n {title,\"incompatible browser | facebook\"}]\n</pre>\n<br>\n<pre>\n4> spider_bot:parse_url(\"http://python.org\").\n[[{\"description\",\n \" home page for python, an interpreted, interactive, object-oriented, extensible\\n programming language. it provides an extraordinary combination of clarity and\\n versatility, and is free and\ncomprehensively ported.\"},\n {\"keywords\",\n \"python programming language object oriented web free source\"},\n []],\n {title,\"python programming language – official website\"}]\n</pre><br>\n<pre>\n5> spider_bot:parse_url(\"http://www.house.gov/\").\n[[[],[],[],\n {\"description\",\n \"home page of the united states house of representatives\"},\n {\"description\",\n \"home page of the united states house of representatives\"},\n [],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],\n [],[],[]|...],\n {title,\"united states house of representatives, 111th congress, 2nd session\"}]\n</pre>\n</p>\n\n<p><br></p>\n\n<p>\nYou can now realise that, we can index the pages against their keywords, plus a good schedule of page revisists. Another challenge was how to make a crawler (something that will move around the entire web, from domain to domain), but that one is easy. Its possible by parsing an Html file for the href tags. Make the HTML Parser to extract all href tags and then you might need some regular expressions here and there to get the links right under a given domain.<br><br>\n<b>Running the crawler</b>\n<pre>\n7> spider_connect:conn2(\"http://erlang.org\"). \n\n Links: [\"http://www.erlang.org/index.html\",\n \"http://www.erlang.org/rss.xml\",\n \"http://erlang.org/index.html\",\"http://erlang.org/about.html\",\n \"http://erlang.org/download.html\",\n \"http://erlang.org/links.html\",\"http://erlang.org/faq.html\",\n \"http://erlang.org/eep.html\",\n \"http://erlang.org/starting.html\",\n \"http://erlang.org/doc.html\",\n \"http://erlang.org/examples.html\",\n \"http://erlang.org/user.html\",\n \"http://erlang.org/mirrors.html\",\n \"http://www.pragprog.com/titles/jaerlang/programming-erlang\",\n \"http://oreilly.com/catalog/9780596518189\",\n \"http://erlang.org/download.html\",\n \"http://www.erlang-factory.com/conference/ErlangUserConference2010/speakers\",\n \"http://erlang.org/download/otp_src_R14B.readme\",\n \"http://erlang.org/download.html\",\n \"https://www.erlang-factory.com/conference/ErlangUserConference2010/register\",\n \"http://www.erlang-factory.com/conference/ErlangUserConference2010/submit_talk\",\n \"http://www.erlang.org/workshop/2010/\",\n \"http://erlangcamp.com\",\"http://manning.com/logan\",\n \"http://erlangcamp.com\",\"http://twitter.com/erlangcamp\",\n \"http://www.erlang-factory.com/conference/London2010/speakers/joearmstrong/\",\n \"http://www.erlang-factory.com/conference/London2010/speakers/RobertVirding/\",\n \"http://www.erlang-factory.com/conference/London2010/speakers/MartinOdersky/\",\n \"http://www.erlang-factory.com/\",\n \"http://erlang.org/download/otp_src_R14A.readme\",\n \"http://erlang.org/download.html\",\n \"http://www.erlang-factory.com/conference/London2010\",\n \"http://github.com/erlang/otp\",\n \"http://erlang.org/download.html\",\n \"http://erlang.org/doc/man/erl_nif.html\",\n \"http://github.com/erlang/otp\",\n \"http://erlang.org/download.html\",\n \"http://www.erlang-factory.com/conference/ErlangUserConference2009\",\n \"http://erlang.org/doc/efficiency_guide/drivers.html\",\n \"http://erlang.org/download.html\",\n \"http://erlang.org/workshop/2009/index.html\",\n \"http://groups.google.com/group/erlang-programming\",\n \"http://www.erlang.org/eeps/eep-0010.html\",\n \"http://erlang.org/download/otp_src_R13B.readme\",\n \"http://erlang.org/download.html\",\n \"http://oreilly.com/catalog/9780596518189\",\n \"http://www.erlang-factory.com\",\n \"http://www.manning.com/logan\",\n \"http://www.erlang.se/euc/08/index.html\",\n \"http://erlang.org/download/otp_src_R12B-5.readme\",\n \"http://erlang.org/download.html\",\n \"http://erlang.org/workshop/2008/index.html\",\n \"http://www.erlang-exchange.com\",\n \"http://erlang.org/doc/highlights.html\",\n \"http://www.erlang.se/euc/07/\",\n \"http://www.erlang.se/workshop/2007/\",\n \"http://erlang.org/eep.html\",\n \"http://erlang.org/download/otp_src_R11B-5.readme\",\n \"http://pragmaticprogrammer.com/titles/jaerlang/index.html\",\n \"http://erlang.org/project/test_server\",\n \"http://erlang.org/download-stats/\",\n \"http://erlang.org/user.html#smtp_client-1.0\",\n \"http://erlang.org/user.html#xmlrpc-1.13\",\n \"http://erlang.org/EPLICENSE\",\n \"http://erlang.org/project/megaco/\",\n \"http://www.erlang-consulting.com/training_fs.html\",\n \"http://erlang.org/old_news.html\"]\nok\n</pre>\n<b><i>Storage:</i></b> Is one of the most important concepts for a search engine. Its a big mistake to store search engine data in an RDBMS like MySQL, Oracle, MS SQL e.t.c. Such systems are completely complex and the applications that interface with them employ heuristic algorithms. This brings us to <b><a href=\"http://cattell.net/datastores/Datastores.pdf\" rel=\"noreferrer\">Key-Value Stores</a></b>, of which the two of my best are <b><code><a href=\"http://www.couchbase.com/\" rel=\"noreferrer\">Couch Base Server</a></code></b> and <b><code><a href=\"http://basho.com/\" rel=\"noreferrer\">Riak</a></code></b>. These are great Cloud File Systems. Another important parameter is caching. Caching is attained using say <code><b><a href=\"http://memcached.org/\" rel=\"noreferrer\">Memcached</a></b></code>, of which the other two storage systems mentioned above have support for it. Storage systems for Search engines ought to be <code>schemaless DBMS</code>,which focuses on <code>Availability rather than Consistency</code>. Read more on Search Engines from here: <a href=\"http://en.wikipedia.org/wiki/Web_search_engine\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Web_search_engine</a><br>\n</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24813/"
] |
I am thinking of developing a web search engine using Erlang, Mnesia & Yaws. Is it possible to make a powerful and the fastest web search engine using these software? What will it need to accomplish this and how what do I start with?
|
Erlang can make the most powerful web crawler today. Let me take you through my simple crawler.
Step 1. I create a simple parallelism module, which i call *mapreduce*
```
-module(mapreduce).
-export([compute/2]).
%%=====================================================================
%% usage example
%% Module = string
%% Function = tokens
%% List_of_arg_lists = [["file\r\nfile","\r\n"],["muzaaya_joshua","_"]]
%% Ans = [["file","file"],["muzaaya","joshua"]]
%% Job being done by two processes
%% i.e no. of processes spawned = length(List_of_arg_lists)
compute({Module,Function},List_of_arg_lists)->
S = self(),
Ref = erlang:make_ref(),
PJob = fun(Arg_list) -> erlang:apply(Module,Function,Arg_list) end,
Spawn_job = fun(Arg_list) ->
spawn(fun() -> execute(S,Ref,PJob,Arg_list) end)
end,
lists:foreach(Spawn_job,List_of_arg_lists),
gather(length(List_of_arg_lists),Ref,[]).
gather(0, _, L) -> L;
gather(N, Ref, L) ->
receive
{Ref,{'EXIT',_}} -> gather(N-1,Ref,L);
{Ref, Result} -> gather(N-1, Ref, [Result|L])
end.
execute(Parent,Ref,Fun,Arg)->
Parent ! {Ref,(catch Fun(Arg))}.
```
Step 2. **The HTTP Client**
One would normally use either `inets httpc module` built into erlang or `[ibrowse](https://github.com/cmullaparthi/ibrowse)`. However, for memory management and speed (getting the memory foot print as low as possible), a good erlang programmer would choose to use `[curl](http://curl.haxx.se/docs/manual.html)`. By applying the `[os:cmd/1](http://www.erlang.org/doc/man/os.html#cmd-1)` which takes that curl command line, one would get the output direct into the erlang calling function. Yet still, its better, to make curl throw its outputs into files and then our application has another thread (process) which reads and parses these files
```
**Command**: curl "http://www.erlang.org" -o "/downloaded_sites/erlang/file1.html"
**In Erlang**
os:cmd("curl \"http://www.erlang.org\" -o \"/downloaded_sites/erlang/file1.html\"").
```
So you can spawn many processes. You remember to escape the URL as well as the output file path as you execute that command. There is a process on the other hand whose work is to watch the directory of downloaded pages. These pages it reads and parses them, it may then delete after parsing or save in a different location or even better, archive them using the `zip module`
```
folder_check()->
spawn(fun() -> check_and_report() end),
ok.
-define(CHECK_INTERVAL,5).
check_and_report()->
%% avoid using
%% filelib:list_dir/1
%% if files are many, memory !!!
case os:cmd("ls | wc -l") of
"0\n" -> ok;
"0" -> ok;
_ -> ?MODULE:new_files_found()
end,
sleep(timer:seconds(?CHECK_INTERVAL)),
%% keep checking
check_and_report().
new_files_found()->
%% inform our parser to pick files
%% once it parses a file, it has to
%% delete it or save it some
%% where else
gen_server:cast(?MODULE,files_detected).
```
Step 3. **The html parser.**
Better use this `[mochiweb's html parser and XPATH](http://ppolv.wordpress.com/2008/05/09/fun-with-mochiwebs-html-parser-and-xpath/)`. This will help you parse and get all your favorite HTML tags, extract the contents and then good to go. The examples below, i focused on only the `Keywords`, `description` and `title` in the markup
**Module Testing in shell...awesome results!!!**
```
2> spider_bot:parse_url("http://erlang.org").
[[[],[],
{"keywords",
"erlang, functional, programming, fault-tolerant, distributed, multi-platform, portable, software, multi-core, smp, concurrency "},
{"description","open-source erlang official website"}],
{title,"erlang programming language, official website"}]
```
```
3> spider_bot:parse_url("http://facebook.com").
[[{"description",
" facebook is a social utility that connects people with friends and others who work, study and live around them. people use facebook to keep up with friends, upload an unlimited number of photos, post links
and videos, and learn more about the people they meet."},
{"robots","noodp,noydir"},
[],[],[],[]],
{title,"incompatible browser | facebook"}]
```
```
4> spider_bot:parse_url("http://python.org").
[[{"description",
" home page for python, an interpreted, interactive, object-oriented, extensible\n programming language. it provides an extraordinary combination of clarity and\n versatility, and is free and
comprehensively ported."},
{"keywords",
"python programming language object oriented web free source"},
[]],
{title,"python programming language – official website"}]
```
```
5> spider_bot:parse_url("http://www.house.gov/").
[[[],[],[],
{"description",
"home page of the united states house of representatives"},
{"description",
"home page of the united states house of representatives"},
[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],
[],[],[]|...],
{title,"united states house of representatives, 111th congress, 2nd session"}]
```
You can now realise that, we can index the pages against their keywords, plus a good schedule of page revisists. Another challenge was how to make a crawler (something that will move around the entire web, from domain to domain), but that one is easy. Its possible by parsing an Html file for the href tags. Make the HTML Parser to extract all href tags and then you might need some regular expressions here and there to get the links right under a given domain.
**Running the crawler**
```
7> spider_connect:conn2("http://erlang.org").
Links: ["http://www.erlang.org/index.html",
"http://www.erlang.org/rss.xml",
"http://erlang.org/index.html","http://erlang.org/about.html",
"http://erlang.org/download.html",
"http://erlang.org/links.html","http://erlang.org/faq.html",
"http://erlang.org/eep.html",
"http://erlang.org/starting.html",
"http://erlang.org/doc.html",
"http://erlang.org/examples.html",
"http://erlang.org/user.html",
"http://erlang.org/mirrors.html",
"http://www.pragprog.com/titles/jaerlang/programming-erlang",
"http://oreilly.com/catalog/9780596518189",
"http://erlang.org/download.html",
"http://www.erlang-factory.com/conference/ErlangUserConference2010/speakers",
"http://erlang.org/download/otp_src_R14B.readme",
"http://erlang.org/download.html",
"https://www.erlang-factory.com/conference/ErlangUserConference2010/register",
"http://www.erlang-factory.com/conference/ErlangUserConference2010/submit_talk",
"http://www.erlang.org/workshop/2010/",
"http://erlangcamp.com","http://manning.com/logan",
"http://erlangcamp.com","http://twitter.com/erlangcamp",
"http://www.erlang-factory.com/conference/London2010/speakers/joearmstrong/",
"http://www.erlang-factory.com/conference/London2010/speakers/RobertVirding/",
"http://www.erlang-factory.com/conference/London2010/speakers/MartinOdersky/",
"http://www.erlang-factory.com/",
"http://erlang.org/download/otp_src_R14A.readme",
"http://erlang.org/download.html",
"http://www.erlang-factory.com/conference/London2010",
"http://github.com/erlang/otp",
"http://erlang.org/download.html",
"http://erlang.org/doc/man/erl_nif.html",
"http://github.com/erlang/otp",
"http://erlang.org/download.html",
"http://www.erlang-factory.com/conference/ErlangUserConference2009",
"http://erlang.org/doc/efficiency_guide/drivers.html",
"http://erlang.org/download.html",
"http://erlang.org/workshop/2009/index.html",
"http://groups.google.com/group/erlang-programming",
"http://www.erlang.org/eeps/eep-0010.html",
"http://erlang.org/download/otp_src_R13B.readme",
"http://erlang.org/download.html",
"http://oreilly.com/catalog/9780596518189",
"http://www.erlang-factory.com",
"http://www.manning.com/logan",
"http://www.erlang.se/euc/08/index.html",
"http://erlang.org/download/otp_src_R12B-5.readme",
"http://erlang.org/download.html",
"http://erlang.org/workshop/2008/index.html",
"http://www.erlang-exchange.com",
"http://erlang.org/doc/highlights.html",
"http://www.erlang.se/euc/07/",
"http://www.erlang.se/workshop/2007/",
"http://erlang.org/eep.html",
"http://erlang.org/download/otp_src_R11B-5.readme",
"http://pragmaticprogrammer.com/titles/jaerlang/index.html",
"http://erlang.org/project/test_server",
"http://erlang.org/download-stats/",
"http://erlang.org/user.html#smtp_client-1.0",
"http://erlang.org/user.html#xmlrpc-1.13",
"http://erlang.org/EPLICENSE",
"http://erlang.org/project/megaco/",
"http://www.erlang-consulting.com/training_fs.html",
"http://erlang.org/old_news.html"]
ok
```
***Storage:*** Is one of the most important concepts for a search engine. Its a big mistake to store search engine data in an RDBMS like MySQL, Oracle, MS SQL e.t.c. Such systems are completely complex and the applications that interface with them employ heuristic algorithms. This brings us to **[Key-Value Stores](http://cattell.net/datastores/Datastores.pdf)**, of which the two of my best are **`[Couch Base Server](http://www.couchbase.com/)`** and **`[Riak](http://basho.com/)`**. These are great Cloud File Systems. Another important parameter is caching. Caching is attained using say `**[Memcached](http://memcached.org/)**`, of which the other two storage systems mentioned above have support for it. Storage systems for Search engines ought to be `schemaless DBMS`,which focuses on `Availability rather than Consistency`. Read more on Search Engines from here: <http://en.wikipedia.org/wiki/Web_search_engine>
|
195,820 |
<p>I'm experimenting with the iPhone SDK and doing some TDD ala Dr. Nic's rbiPhoneTest project. I'm wondering how many, if any, have been successful using this or any other testing framework for iPhone/Cocoa? More important, I'd like to know how to best assert a proprietary binary request/response protocol. The idea is to send a binary request over the network and receive a binary response. Requests and responses are created using byte and'ing and or'ing. I'm using the golden copy pattern to test my request. Here's what I have so far. Don't laugh as I'm new to btoh Objective C and Ruby:</p>
<pre><code>require File.dirname(__FILE__) + '/test_helper'
require 'fileutils'
require 'io'
require "MyModel.bundle"
OSX::ns_import :MyModel
module MyTestExtensions
def is_absolute_path(path)
return /^\/.*/.match(path)
end
def parent_directory(file)
dir = file
if(! is_absolute_path(dir))
dir = File.expand_path(dir)
end
dir = File.dirname(dir)
assert is_absolute_path(dir), "Expecting an absolute path with #{dir}"
return dir
end
def assert_NSData_contains_bytes_from_file(file, data)
assert_not_nil data, "Data should not be nil."
assert data.bytes, "data should have bytes"
data.length.times { |i|
expected = file.getc
assert_not_nil expected, "Expected only #{i} bytes. Actual data contains more."
actual = data.bytes.int8_at(i)
assert_equal expected, actual, "Bytes should be equal at offset #{i} expected #{expected.chr} but was #{actual.chr}"
}
expected = file.getc
raise AssertionFailedError, "Expecting #{expected.chr} at offset #{data.length}" unless expected == nil
end
end
class TestMyModel < Test::Unit::TestCase
include OSX
include MyTestExtensions
def this_files_dir
return parent_directory(__FILE__)
end
def setup
@expectedReq = File.new("#{this_files_dir}/ExpectedMyReq")
# @expectedReq = File.new("#{this_files_dir}/hello.txt")
assert File.exist?("#{this_files_dir}/ExpectedMyReq"), "The file [#{@expectedReq.path}] should exist."
end
def test_my_model_class_exists
MyModel
end
def test_can_init_instance
assert MyModel.instancesRespondToSelector(:init), "MyModel Should define :init"
end
def test_my_model_can_request_my_data
myModel = MyModel.alloc.init
data = myModel.requestMyData 'Some query text'
assert_NSData_contains_bytes_from_file @expectedReq, data
end
end
</code></pre>
|
[
{
"answer_id": 195832,
"author": "zoul",
"author_id": 17279,
"author_profile": "https://Stackoverflow.com/users/17279",
"pm_score": 4,
"selected": false,
"text": "<p>I don’t know much about Ruby or binary protocols, but if You’re interested in unit testing on iPhone, You might want to check out the <a href=\"http://code.google.com/p/google-toolbox-for-mac/\" rel=\"nofollow noreferrer\">Google Toolbox for Mac</a>. I am having great success testing my OpenGL ES application with it.</p>\n"
},
{
"answer_id": 277777,
"author": "Dr Nic",
"author_id": 36170,
"author_profile": "https://Stackoverflow.com/users/36170",
"pm_score": 3,
"selected": false,
"text": "<p>Cliff, long term you're best investing time in pure ObjC TDD tools. I have used my own rbiphonetest lib in fmdb-migration-manager successfully, but its usefulness is probably limited to libraries etc. Even then there will undoubtly be enough 'works in Cocoa but fails in UIKit' scenarios to make rbiphonetest dubious to use. Hopefully one day RubyCocoa can be built against the Intel UIKit libraries and then it will be very useful and sturdy I think.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10631/"
] |
I'm experimenting with the iPhone SDK and doing some TDD ala Dr. Nic's rbiPhoneTest project. I'm wondering how many, if any, have been successful using this or any other testing framework for iPhone/Cocoa? More important, I'd like to know how to best assert a proprietary binary request/response protocol. The idea is to send a binary request over the network and receive a binary response. Requests and responses are created using byte and'ing and or'ing. I'm using the golden copy pattern to test my request. Here's what I have so far. Don't laugh as I'm new to btoh Objective C and Ruby:
```
require File.dirname(__FILE__) + '/test_helper'
require 'fileutils'
require 'io'
require "MyModel.bundle"
OSX::ns_import :MyModel
module MyTestExtensions
def is_absolute_path(path)
return /^\/.*/.match(path)
end
def parent_directory(file)
dir = file
if(! is_absolute_path(dir))
dir = File.expand_path(dir)
end
dir = File.dirname(dir)
assert is_absolute_path(dir), "Expecting an absolute path with #{dir}"
return dir
end
def assert_NSData_contains_bytes_from_file(file, data)
assert_not_nil data, "Data should not be nil."
assert data.bytes, "data should have bytes"
data.length.times { |i|
expected = file.getc
assert_not_nil expected, "Expected only #{i} bytes. Actual data contains more."
actual = data.bytes.int8_at(i)
assert_equal expected, actual, "Bytes should be equal at offset #{i} expected #{expected.chr} but was #{actual.chr}"
}
expected = file.getc
raise AssertionFailedError, "Expecting #{expected.chr} at offset #{data.length}" unless expected == nil
end
end
class TestMyModel < Test::Unit::TestCase
include OSX
include MyTestExtensions
def this_files_dir
return parent_directory(__FILE__)
end
def setup
@expectedReq = File.new("#{this_files_dir}/ExpectedMyReq")
# @expectedReq = File.new("#{this_files_dir}/hello.txt")
assert File.exist?("#{this_files_dir}/ExpectedMyReq"), "The file [#{@expectedReq.path}] should exist."
end
def test_my_model_class_exists
MyModel
end
def test_can_init_instance
assert MyModel.instancesRespondToSelector(:init), "MyModel Should define :init"
end
def test_my_model_can_request_my_data
myModel = MyModel.alloc.init
data = myModel.requestMyData 'Some query text'
assert_NSData_contains_bytes_from_file @expectedReq, data
end
end
```
|
I don’t know much about Ruby or binary protocols, but if You’re interested in unit testing on iPhone, You might want to check out the [Google Toolbox for Mac](http://code.google.com/p/google-toolbox-for-mac/). I am having great success testing my OpenGL ES application with it.
|
195,842 |
<p>I want to capture as a bitmap the system cursor on Windows OSes as accurately as possible.
The provided API for this is to my knowledge GetCursorInfo, DrawIconEx.</p>
<p>The simple chain of actions is:</p>
<ul>
<li>Get cursor by using GetCursorInfo</li>
<li>Paint the cursor in a memory DC by using DrawIconEx.</li>
</ul>
<p>Here is how the code looks roughly.</p>
<pre><code>CURSORINFO CursorInfo;
(VOID)memset(&CursorInfo, 0, sizeof(CursorInfo));
CursorInfo.cbSize = sizeof(CursorInfo);
if (GetCursorInfo(&CursorInfo) &&
CursorInfo.hCursor)
{
// ... create here the memory DC, memory bitmap
boError |= !DrawIconEx(hCursorDC, // device context
0, // xLeft
0, // yTop
CursorInfo.hCursor, // cursor handle
0, // width, use system default
0, // height, use system default
0, // step of animated cursor !!!!!!!!!
NULL, // flicker free brush, don't use it now
DI_MASK | DI_DEFAULTSIZE); // flags
// ... do whatever we want with the cursor in our memory DC
}
</code></pre>
<p>Now, anyone knows how I could get which step of the animated cursor is being drawn (I need the value that can be then passed to the istepIfAniCur parameter of DrawIconEx...)? Currently the above code obviously always renders only the first step of an animated cursor.</p>
<p>I suspect this can not be easily done, but it's worth asking anyway.</p>
|
[
{
"answer_id": 196879,
"author": "David L Morris",
"author_id": 3137,
"author_profile": "https://Stackoverflow.com/users/3137",
"pm_score": 0,
"selected": false,
"text": "<p>I suspect you are missing a step.</p>\n\n<p>You need to create a bitmap to select into your device context otherwise your bit map is just a single pixel. </p>\n\n<p>See CreateCompatibleBitmap in the MSDN documentation:</p>\n\n<pre>\nHBITMAP CreateCompatibleBitmap(\n HDC hdc, // handle to DC\n int nWidth, // width of bitmap, in pixels\n int nHeight // height of bitmap, in pixels\n);\n</pre>\n\n<p>With DrawIconEx the UINT istepIfAniCur parameter allows you to choose which frame to draw if it is an animated cursor.</p>\n\n<p>It says it there in your comments : </p>\n\n<pre>\n0, // step of animated cursor \n</pre>\n"
},
{
"answer_id": 809259,
"author": "Adrian McCarthy",
"author_id": 1386054,
"author_profile": "https://Stackoverflow.com/users/1386054",
"pm_score": 3,
"selected": true,
"text": "<p>Unfortunately, I don't think there's a Windows API that discloses the current frame of the cursor animation. I assume that's what you're after: the look of the cursor at the instant you make the snapshot.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24873/"
] |
I want to capture as a bitmap the system cursor on Windows OSes as accurately as possible.
The provided API for this is to my knowledge GetCursorInfo, DrawIconEx.
The simple chain of actions is:
* Get cursor by using GetCursorInfo
* Paint the cursor in a memory DC by using DrawIconEx.
Here is how the code looks roughly.
```
CURSORINFO CursorInfo;
(VOID)memset(&CursorInfo, 0, sizeof(CursorInfo));
CursorInfo.cbSize = sizeof(CursorInfo);
if (GetCursorInfo(&CursorInfo) &&
CursorInfo.hCursor)
{
// ... create here the memory DC, memory bitmap
boError |= !DrawIconEx(hCursorDC, // device context
0, // xLeft
0, // yTop
CursorInfo.hCursor, // cursor handle
0, // width, use system default
0, // height, use system default
0, // step of animated cursor !!!!!!!!!
NULL, // flicker free brush, don't use it now
DI_MASK | DI_DEFAULTSIZE); // flags
// ... do whatever we want with the cursor in our memory DC
}
```
Now, anyone knows how I could get which step of the animated cursor is being drawn (I need the value that can be then passed to the istepIfAniCur parameter of DrawIconEx...)? Currently the above code obviously always renders only the first step of an animated cursor.
I suspect this can not be easily done, but it's worth asking anyway.
|
Unfortunately, I don't think there's a Windows API that discloses the current frame of the cursor animation. I assume that's what you're after: the look of the cursor at the instant you make the snapshot.
|
195,849 |
<p>Is there a way to programmatically find the location of the current user's Outlook .pst file(s) through an API call or registry entry?</p>
|
[
{
"answer_id": 195876,
"author": "Node",
"author_id": 7190,
"author_profile": "https://Stackoverflow.com/users/7190",
"pm_score": 0,
"selected": false,
"text": "<p>The path should be somewhere under:</p>\n\n<blockquote>\n <p>[HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\n NT\\CurrentVersion\\Windows Messaging\n Subsystem\\Profiles\\Outlook]</p>\n</blockquote>\n\n<p>Maybe this helps a bit.</p>\n"
},
{
"answer_id": 197358,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 4,
"selected": true,
"text": "<p>With <a href=\"http://www.dimastr.com/redemption/\" rel=\"noreferrer\">Outlook Redemption</a>, you can iterate the message stores in VBA using <code>RDOStores</code>collection, accessible via the <code>RDOSession.Stores</code> property.</p>\n\n<p>I am looking into the possibility of doing something similar in out-of-the-box VBA...</p>\n\n<p>EDIT:</p>\n\n<p>Obviously, the path to the PST is encoded in the StoreId string. Google turned up <a href=\"http://www.devnewsgroups.net/group/microsoft.public.office.developer.outlook.vba/topic42609.aspx\" rel=\"noreferrer\">this</a>:</p>\n\n<pre><code>Sub PstFiles()\n Dim f As MAPIFolder\n\n For Each f In Session.Folders\n Debug.Print f.StoreID\n Debug.Print GetPathFromStoreID(f.StoreID)\n Next f\nEnd Sub\n\nPublic Function GetPathFromStoreID(sStoreID As String) As String\n On Error Resume Next\n Dim i As Long\n Dim lPos As Long\n Dim sRes As String\n\n For i = 1 To Len(sStoreID) Step 2\n sRes = sRes & Chr(\"&h\" & Mid$(sStoreID, i, 2))\n Next\n\n sRes = Replace(sRes, Chr(0), vbNullString)\n lPos = InStr(sRes, \":\\\")\n\n If lPos Then\n GetPathFromStoreID = Right$(sRes, (Len(sRes)) - (lPos - 2))\n End If\nEnd Function\n</code></pre>\n\n<p>Just tested, works as designed.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27236/"
] |
Is there a way to programmatically find the location of the current user's Outlook .pst file(s) through an API call or registry entry?
|
With [Outlook Redemption](http://www.dimastr.com/redemption/), you can iterate the message stores in VBA using `RDOStores`collection, accessible via the `RDOSession.Stores` property.
I am looking into the possibility of doing something similar in out-of-the-box VBA...
EDIT:
Obviously, the path to the PST is encoded in the StoreId string. Google turned up [this](http://www.devnewsgroups.net/group/microsoft.public.office.developer.outlook.vba/topic42609.aspx):
```
Sub PstFiles()
Dim f As MAPIFolder
For Each f In Session.Folders
Debug.Print f.StoreID
Debug.Print GetPathFromStoreID(f.StoreID)
Next f
End Sub
Public Function GetPathFromStoreID(sStoreID As String) As String
On Error Resume Next
Dim i As Long
Dim lPos As Long
Dim sRes As String
For i = 1 To Len(sStoreID) Step 2
sRes = sRes & Chr("&h" & Mid$(sStoreID, i, 2))
Next
sRes = Replace(sRes, Chr(0), vbNullString)
lPos = InStr(sRes, ":\")
If lPos Then
GetPathFromStoreID = Right$(sRes, (Len(sRes)) - (lPos - 2))
End If
End Function
```
Just tested, works as designed.
|
195,886 |
<p>I've searched around a bit, but haven't found a satisfactory answer, so I'd like to hear your opinions on this.</p>
<p>I have a couple of tools which I have to update and deploy to a few servers every now and then. The source is managed in a SVN repository.</p>
<p>To save myself the bother of copying the binaries to the production servers by ftp or similar means (I have no means of building the projects on the servers), I'm thinking of creating an area in the repository to commit them as well. I could then simply retrieve the most current version of the executables from the svn server whenever I need them.</p>
<p>Since I don't necessarily want to update/commit the binaries every time I work on the source, I would not create the folder for the binaries as a subfolder of my project. Committing the binaries would then (and should) be a separate, conscious act.</p>
<pre><code>--- trunk
--- project1
--- project2
--- built
--- project1
--- project2
</code></pre>
<p>As far as I can see, there should be no problems with this setup. What I'd really like is to then give both the source revision and the binaries a single tag, so as to be able to retrieve everything that belongs together at once.</p>
<pre><code>--- tags/project1/release2/
includes files from
--- trunk/project1/ revision 487 and
--- built/project1/ revision 488
</code></pre>
<p>Is what I'm after possible, and how would I achieve it?
Should I instead be looking at some other way of solving this problem?</p>
|
[
{
"answer_id": 195891,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure why you don't want to put the binaries under the trunk/project1/binaries tree? That said, nothing should stop you from having the tree look like this:</p>\n\n<ul>\n<li>trunk\n\n<ul>\n<li>project1</li>\n<li>project2</li>\n</ul></li>\n<li>built\n\n<ul>\n<li>project1</li>\n<li>project2</li>\n</ul></li>\n<li>tags\n\n<ul>\n<li>project1</li>\n<li><code><tag id</code>>\n\n<ul>\n<li><code><code as usual</code>></li>\n<li>binaries</li>\n</ul></li>\n</ul></li>\n</ul>\n"
},
{
"answer_id": 195892,
"author": "gbarry",
"author_id": 19512,
"author_profile": "https://Stackoverflow.com/users/19512",
"pm_score": 2,
"selected": false,
"text": "<p>I believe this handled by the use of \"externals\". There are pitfalls, though, and I have yet to find something that I feel comfortable with. I do what you suggest, with my source libraries, but I still do it manually.</p>\n"
},
{
"answer_id": 195893,
"author": "Mihai Limbășan",
"author_id": 14444,
"author_profile": "https://Stackoverflow.com/users/14444",
"pm_score": 4,
"selected": true,
"text": "<p>There's nothing weird about your setup (I'm doing similar things with both build tools and build artifacts when I need to preserve the exact bits.) The layout you want is definitely possible - to \"include\" specific versions of other branches or tags in your tags/project1/release2, all you need to do is set <a href=\"http://svnbook.red-bean.com/en/1.5/svn.advanced.externals.html\" rel=\"nofollow noreferrer\">svn:externals properties</a> on tags/project1/release2 referencing the URL of the sources and revisions you want to pull in, and you're set.</p>\n"
},
{
"answer_id": 195917,
"author": "OregonGhost",
"author_id": 20363,
"author_profile": "https://Stackoverflow.com/users/20363",
"pm_score": 3,
"selected": false,
"text": "<p>While I can't directly answer your question, I'll tell about an alternate approach.</p>\n\n<p>We have a separate file server for binary releases, with a backup strategy similar to the one for the SVN server, and there is a directory for each project with anything belonging to the project that is not in SVN, including a release directory. The entire history of binary releases is stored in this directory, so you can get the binary from everywhere (well, from within our network) without the need for SVN, i.e. copy it to some production server, send it to the customer or download for testing in a VM. No need to checkout or to rebuild.</p>\n\n<p>I found this setup easier to manage than comitting the binaries to SVN. If you need an exact binary with a specific version, it's just there, provided that the version has been given out to the client (but then, why would you need a binary that has never seen sun light?). </p>\n"
},
{
"answer_id": 195952,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 1,
"selected": false,
"text": "<p>While technically that approach will work just fine, I personally wouldn't use SVN to store binaries like that.</p>\n\n<p>I have 2 reasons why this is the case.\nInitially I thought that SVN followed in the wake of CVS and didn't store binary diffs, which it turns out I was wrong about. At any rate:</p>\n\n<p>0) \"Technically\" you don't need to store generated files as they can be re-built if neccessary. Obviously this is not practical in real life, but IMHO you still should be thinking 'how can I build a cache for the generated stuff.'<br>\nSVN doesn't really fit that usage model. This is not really a point on it's own, but what I'm trying to convey is \"putting something in SVN implies you care about it and want to archive it\" - if you don't, you shouldn't IMHO be conveying this message, implicitly or otherwise</p>\n\n<p>1) This is annoying. If someone checks out the top of your repo, they'll get all the binaries as well. If you have more than a meg or two, this is going to make people have to wait for that stuff (and use up their disk space) for no good reason. This can be solved by setting up a seperate repository, but once you do that IMHO you might as well just set up a seperate webserver instead.</p>\n\n<p>2) SVN is designed to keep all your files forever. <a href=\"http://subversion.tigris.org/faq.html#removal\" rel=\"nofollow noreferrer\">It is very painful and time consuming to completely remove things from the repository</a>, which makes it questionable to store things that you don't need to store.</p>\n\n<p>I'd recommend that instead you just use a web server to store your binaries on. (SVN is a web server after all**). Keep as many old binaries on the server as you like, and back it up, but you can then delete the old useless binaries once you don't need them any more.</p>\n\n<p>** Yes I know it uses DAV and it's therefore not really just a plain old webserver, but from the point of view of deploying to a production machine, the process is 'I download some files using http from <a href=\"http://blah\" rel=\"nofollow noreferrer\">http://blah</a>', so it might as well be one.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2899/"
] |
I've searched around a bit, but haven't found a satisfactory answer, so I'd like to hear your opinions on this.
I have a couple of tools which I have to update and deploy to a few servers every now and then. The source is managed in a SVN repository.
To save myself the bother of copying the binaries to the production servers by ftp or similar means (I have no means of building the projects on the servers), I'm thinking of creating an area in the repository to commit them as well. I could then simply retrieve the most current version of the executables from the svn server whenever I need them.
Since I don't necessarily want to update/commit the binaries every time I work on the source, I would not create the folder for the binaries as a subfolder of my project. Committing the binaries would then (and should) be a separate, conscious act.
```
--- trunk
--- project1
--- project2
--- built
--- project1
--- project2
```
As far as I can see, there should be no problems with this setup. What I'd really like is to then give both the source revision and the binaries a single tag, so as to be able to retrieve everything that belongs together at once.
```
--- tags/project1/release2/
includes files from
--- trunk/project1/ revision 487 and
--- built/project1/ revision 488
```
Is what I'm after possible, and how would I achieve it?
Should I instead be looking at some other way of solving this problem?
|
There's nothing weird about your setup (I'm doing similar things with both build tools and build artifacts when I need to preserve the exact bits.) The layout you want is definitely possible - to "include" specific versions of other branches or tags in your tags/project1/release2, all you need to do is set [svn:externals properties](http://svnbook.red-bean.com/en/1.5/svn.advanced.externals.html) on tags/project1/release2 referencing the URL of the sources and revisions you want to pull in, and you're set.
|
195,919 |
<p>When uninstalling my application, I'd like to configure the <a href="http://en.wikipedia.org/wiki/WiX" rel="noreferrer">Wix</a> setup to remove all the files that were added <strong>after the original installation</strong>. It seems like the uninstaller removes only the directories and files that were originally installed from the MSI file and it leaves everything else that was added later in the application folder. In another words, I'd like to purge the directory when uninstalling. How do I do that?</p>
|
[
{
"answer_id": 196149,
"author": "Pavel Chuchuva",
"author_id": 14131,
"author_profile": "https://Stackoverflow.com/users/14131",
"pm_score": 7,
"selected": true,
"text": "<p>Use <a href=\"http://wixtoolset.org/documentation/manual/v3/xsd/wix/removefile.html\" rel=\"noreferrer\">RemoveFile element</a> with On=\"<strong>uninstall</strong>\". Here's an example:\n</p>\n\n<pre><code><Directory Id=\"CommonAppDataFolder\" Name=\"CommonAppDataFolder\">\n <Directory Id=\"MyAppFolder\" Name=\"My\">\n <Component Id=\"MyAppFolder\" Guid=\"*\">\n <CreateFolder />\n <RemoveFile Id=\"PurgeAppFolder\" Name=\"*.*\" On=\"uninstall\" />\n </Component>\n </Directory>\n</Directory>\n</code></pre>\n\n<p><strong>Update</strong></p>\n\n<blockquote>\n <p>It didn't work 100%. It removed the files, however none of the additional directories - \n the ones created after the installation - were removed. Any thoughts on that? – pribeiro</p>\n</blockquote>\n\n<p>Unfortunately Windows Installer doesn't support deleting directories with subdirectories. In this case you have to resort to custom action. Or, if you know what subfolders are, create a bunch of RemoveFolder and RemoveFile elements.</p>\n"
},
{
"answer_id": 270396,
"author": "Friend Of George",
"author_id": 424,
"author_profile": "https://Stackoverflow.com/users/424",
"pm_score": 4,
"selected": false,
"text": "<p>To do this, I simply created a custom action to be called on uninstall.</p>\n\n<p>The WiX code will look like this:\n</p>\n\n<pre><code><Binary Id=\"InstallUtil\" src=\"InstallUtilLib.dll\" />\n\n<CustomAction Id=\"DIRCA_TARGETDIR\" Return=\"check\" Execute=\"firstSequence\" Property=\"TARGETDIR\" Value=\"[ProgramFilesFolder][Manufacturer]\\[ProductName]\" />\n<CustomAction Id=\"Uninstall\" BinaryKey=\"InstallUtil\" DllEntry=\"ManagedInstall\" Execute=\"deferred\" />\n<CustomAction Id=\"UninstallSetProp\" Property=\"Uninstall\" Value=\"/installtype=notransaction /action=uninstall /LogFile= /targetDir=&quot;[TARGETDIR]\\Bin&quot; &quot;[#InstallerCustomActionsDLL]&quot; &quot;[#InstallerCustomActionsDLLCONFIG]&quot;\" />\n\n<Directory Id=\"BinFolder\" Name=\"Bin\" >\n <Component Id=\"InstallerCustomActions\" Guid=\"*\">\n <File Id=\"InstallerCustomActionsDLL\" Name=\"SetupCA.dll\" LongName=\"InstallerCustomActions.dll\" src=\"InstallerCustomActions.dll\" Vital=\"yes\" KeyPath=\"yes\" DiskId=\"1\" Compressed=\"no\" />\n <File Id=\"InstallerCustomActionsDLLCONFIG\" Name=\"SetupCA.con\" LongName=\"InstallerCustomActions.dll.Config\" src=\"InstallerCustomActions.dll.Config\" Vital=\"yes\" DiskId=\"1\" />\n </Component>\n</Directory>\n\n<Feature Id=\"Complete\" Level=\"1\" ConfigurableDirectory=\"TARGETDIR\">\n <ComponentRef Id=\"InstallerCustomActions\" />\n</Feature>\n\n<InstallExecuteSequence>\n <Custom Action=\"UninstallSetProp\" After=\"MsiUnpublishAssemblies\">$InstallerCustomActions=2</Custom>\n <Custom Action=\"Uninstall\" After=\"UninstallSetProp\">$InstallerCustomActions=2</Custom>\n</InstallExecuteSequence>\n</code></pre>\n\n<p>The code for the OnBeforeUninstall method in InstallerCustomActions.DLL will look like this (in VB).</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Protected Overrides Sub OnBeforeUninstall(ByVal savedState As System.Collections.IDictionary)\n MyBase.OnBeforeUninstall(savedState)\n\n Try\n Dim CommonAppData As String = Me.Context.Parameters(\"CommonAppData\")\n If CommonAppData.StartsWith(\"\\\") And Not CommonAppData.StartsWith(\"\\\\\") Then\n CommonAppData = \"\\\" + CommonAppData\n End If\n Dim targetDir As String = Me.Context.Parameters(\"targetDir\")\n If targetDir.StartsWith(\"\\\") And Not targetDir.StartsWith(\"\\\\\") Then\n targetDir = \"\\\" + targetDir\n End If\n\n DeleteFile(\"<filename.extension>\", targetDir) 'delete from bin directory\n DeleteDirectory(\"*.*\", \"<DirectoryName>\") 'delete any extra directories created by program\n Catch\n End Try\nEnd Sub\n\nPrivate Sub DeleteFile(ByVal searchPattern As String, ByVal deleteDir As String)\n Try\n For Each fileName As String In Directory.GetFiles(deleteDir, searchPattern)\n File.Delete(fileName)\n Next\n Catch\n End Try\nEnd Sub\n\nPrivate Sub DeleteDirectory(ByVal searchPattern As String, ByVal deleteDir As String)\n Try\n For Each dirName As String In Directory.GetDirectories(deleteDir, searchPattern)\n Directory.Delete(dirName)\n Next\n Catch\n End Try\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 2184066,
"author": "tronda",
"author_id": 6896,
"author_profile": "https://Stackoverflow.com/users/6896",
"pm_score": 3,
"selected": false,
"text": "<p>Not an WIX expert, but could a possible (simpler?) solution to this be to run the <a href=\"http://wix.sourceforge.net/manual-wix3/qtexec.htm\" rel=\"noreferrer\">Quiet Execution Custom Action</a> which is part of the built in extensions of WIX?</p>\n\n<p>Could run the <a href=\"http://www.computerhope.com/rmdirhlp.htm\" rel=\"noreferrer\">rmdir</a> MS DOS command with the /S and /Q options.\n</p>\n\n<pre><code><Binary Id=\"CommandPrompt\" SourceFile=\"C:\\Windows\\System32\\cmd.exe\" />\n</code></pre>\n\n<p>And the custom action doing the job is simple:\n</p>\n\n<pre><code><CustomAction Id=\"DeleteFolder\" BinaryKey=\"CommandPrompt\" \n ExeCommand='/c rmdir /S /Q \"[CommonAppDataFolder]MyAppFolder\\PurgeAppFolder\"' \n Execute=\"immediate\" Return=\"check\" />\n</code></pre>\n\n<p>Then you'll have to modify the InstallExecuteSequence as documented many places.</p>\n\n<p><strong>Update:</strong>\nHad issues with this approach. Ended up making a custom task instead, but still considers this a viable solution, but without getting the details to work.</p>\n"
},
{
"answer_id": 10477561,
"author": "Alexey Ivanov",
"author_id": 572834,
"author_profile": "https://Stackoverflow.com/users/572834",
"pm_score": 5,
"selected": false,
"text": "<p>Use <a href=\"http://wix.sourceforge.net/manual-wix3/util_xsd_removefolderex.htm\" rel=\"noreferrer\"><strong><code>RemoveFolderEx</code></strong></a> element from Util extension in WiX.<br>\nWith this approach, all the subdirectories are also removed (as opposed to <a href=\"https://stackoverflow.com/a/196149/572834\">using <code>RemoveFile</code> element directly</a>). This element adds temporary rows to <code>RemoveFile</code> and <code>RemoveFolder</code> table in the MSI database.</p>\n"
},
{
"answer_id": 17513551,
"author": "Pierre",
"author_id": 282901,
"author_profile": "https://Stackoverflow.com/users/282901",
"pm_score": 4,
"selected": false,
"text": "<p>Here's a variation on @tronda's suggestion. I'm deleting a file \"install.log\" that gets created by another Custom Action, during Uninstall:</p>\n\n<pre><code><Product>\n <CustomAction Id=\"Cleanup_logfile\" Directory=\"INSTALLFOLDER\"\n ExeCommand=\"cmd /C &quot;del install.log&quot;\"\n Execute=\"deferred\" Return=\"ignore\" HideTarget=\"no\" Impersonate=\"no\" />\n\n <InstallExecuteSequence>\n <Custom Action=\"Cleanup_logfile\" Before=\"RemoveFiles\" >\n REMOVE=\"ALL\"\n </Custom>\n </InstallExecuteSequence>\n</Product>\n</code></pre>\n\n<p>As far as I understand, I can't use \"RemoveFile\" because this file is created after the installation, and is not part of a Component Group.</p>\n"
},
{
"answer_id": 33736356,
"author": "Eli",
"author_id": 2069294,
"author_profile": "https://Stackoverflow.com/users/2069294",
"pm_score": 3,
"selected": false,
"text": "<p>This would be a more complete answer for <a href=\"https://stackoverflow.com/a/196149/2069294\">@Pavel</a> suggestion, for me it's working 100%:</p>\n\n<pre><code><Fragment Id=\"FolderUninstall\">\n <?define RegDir=\"SYSTEM\\ControlSet001\\services\\[Manufacturer]:[ProductName]\"?>\n <?define RegValueName=\"InstallDir\"?>\n <Property Id=\"INSTALLFOLDER\">\n <RegistrySearch Root=\"HKLM\" Key=\"$(var.RegDir)\" Type=\"raw\" \n Id=\"APPLICATIONFOLDER_REGSEARCH\" Name=\"$(var.RegValueName)\" />\n </Property>\n\n <DirectoryRef Id='INSTALLFOLDER'>\n <Component Id=\"UninstallFolder\" Guid=\"*\">\n <CreateFolder Directory=\"INSTALLFOLDER\"/>\n <util:RemoveFolderEx Property=\"INSTALLFOLDER\" On=\"uninstall\"/>\n <RemoveFolder Id=\"INSTALLFOLDER\" On=\"uninstall\"/>\n <RegistryValue Root=\"HKLM\" Key=\"$(var.RegDir)\" Name=\"$(var.RegValueName)\" \n Type=\"string\" Value=\"[INSTALLFOLDER]\" KeyPath=\"yes\"/>\n </Component>\n </DirectoryRef>\n</Fragment>\n</code></pre>\n\n<p>And, under Product element:</p>\n\n<pre><code><Feature Id=\"Uninstall\">\n <ComponentRef Id=\"UninstallFolder\" Primary=\"yes\"/>\n</Feature>\n</code></pre>\n\n<p>This approach set a registry value with the desired path of the folder to be deleted on uninstall.\nAt the end, both INSTALLFOLDER and registry folder are removed from the system. Note that the path to the registry can be at other hive and other locations.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23609/"
] |
When uninstalling my application, I'd like to configure the [Wix](http://en.wikipedia.org/wiki/WiX) setup to remove all the files that were added **after the original installation**. It seems like the uninstaller removes only the directories and files that were originally installed from the MSI file and it leaves everything else that was added later in the application folder. In another words, I'd like to purge the directory when uninstalling. How do I do that?
|
Use [RemoveFile element](http://wixtoolset.org/documentation/manual/v3/xsd/wix/removefile.html) with On="**uninstall**". Here's an example:
```
<Directory Id="CommonAppDataFolder" Name="CommonAppDataFolder">
<Directory Id="MyAppFolder" Name="My">
<Component Id="MyAppFolder" Guid="*">
<CreateFolder />
<RemoveFile Id="PurgeAppFolder" Name="*.*" On="uninstall" />
</Component>
</Directory>
</Directory>
```
**Update**
>
> It didn't work 100%. It removed the files, however none of the additional directories -
> the ones created after the installation - were removed. Any thoughts on that? – pribeiro
>
>
>
Unfortunately Windows Installer doesn't support deleting directories with subdirectories. In this case you have to resort to custom action. Or, if you know what subfolders are, create a bunch of RemoveFolder and RemoveFile elements.
|
195,951 |
<p>How can I change the class of an HTML element in response to an <code>onclick</code> or any other events using JavaScript?</p>
|
[
{
"answer_id": 195961,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": -1,
"selected": false,
"text": "<p>This is easiest with a library like jQuery:</p>\n\n<pre><code><input type=\"button\" onClick=\"javascript:test_byid();\" value=\"id='second'\" />\n\n<script>\nfunction test_byid()\n{\n $(\"#second\").toggleClass(\"highlight\");\n}\n</script>\n</code></pre>\n"
},
{
"answer_id": 195977,
"author": "roenving",
"author_id": 23142,
"author_profile": "https://Stackoverflow.com/users/23142",
"pm_score": -1,
"selected": false,
"text": "<p>No offense, but it's unclever to change class on-the-fly as it forces the CSS interpreter to recalculate the visual presentation of the entire web page.</p>\n\n<p>The reason is that it is nearly impossible for the CSS interpreter to know if any inheritance or cascading could be changed, so the short answer is:</p>\n\n<p>Never ever change className on-the-fly !-)</p>\n\n<p>But usually you'll only need to change a property or two, and that is easily implemented:</p>\n\n<pre><code>function highlight(elm){\n elm.style.backgroundColor =\"#345\";\n elm.style.color = \"#fff\";\n}\n</code></pre>\n"
},
{
"answer_id": 196016,
"author": "Eric Wendelin",
"author_id": 25066,
"author_profile": "https://Stackoverflow.com/users/25066",
"pm_score": 7,
"selected": false,
"text": "<p>You can use <code>node.className</code> like so:</p>\n<pre><code>document.getElementById('foo').className = 'bar';\n</code></pre>\n<p>This should work in <a href=\"https://en.wikipedia.org/wiki/Internet_Explorer_5#Versions\" rel=\"noreferrer\">Internet Explorer 5.5</a> and up according to <a href=\"http://quirksmode.org/dom/w3c_html.html\" rel=\"noreferrer\">PPK</a>.</p>\n"
},
{
"answer_id": 196038,
"author": "Peter Boughton",
"author_id": 9360,
"author_profile": "https://Stackoverflow.com/users/9360",
"pm_score": 13,
"selected": true,
"text": "<h2>Modern HTML5 Techniques for changing classes</h2>\n<p>Modern browsers have added <a href=\"https://developer.mozilla.org/en-US/docs/DOM/element.classList\" rel=\"noreferrer\"><strong>classList</strong></a> which provides methods to make it easier to manipulate classes without needing a library:</p>\n<pre><code>document.getElementById("MyElement").classList.add('MyClass');\n\ndocument.getElementById("MyElement").classList.remove('MyClass');\n\nif ( document.getElementById("MyElement").classList.contains('MyClass') )\n\ndocument.getElementById("MyElement").classList.toggle('MyClass');\n</code></pre>\n<p>Unfortunately, these do not work in Internet Explorer prior to v10, though there is a <a href=\"http://en.wikipedia.org/wiki/Shim_(computing)\" rel=\"noreferrer\">shim</a> to add support for it to IE8 and IE9, available from <a href=\"https://developer.mozilla.org/en-US/docs/DOM/element.classList\" rel=\"noreferrer\">this page</a>. It is, though, getting more and more <a href=\"http://caniuse.com/#feat=classlist\" rel=\"noreferrer\">supported</a>.</p>\n<h2>Simple cross-browser solution</h2>\n<p>The standard JavaScript way to select an element is using <a href=\"https://developer.mozilla.org/en-US/docs/DOM/document.getElementById\" rel=\"noreferrer\"><code>document.getElementById("Id")</code></a>, which is what the following examples use - you can of course obtain elements in other ways, and in the right situation may simply use <code>this</code> instead - however, going into detail on this is beyond the scope of the answer.</p>\n<h3>To change all classes for an element:</h3>\n<p>To replace all existing classes with one or more new classes, set the className attribute:</p>\n<pre><code>document.getElementById("MyElement").className = "MyClass";\n</code></pre>\n<p>(You can use a space-delimited list to apply multiple classes.)</p>\n<h3>To add an additional class to an element:</h3>\n<p>To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so:</p>\n<pre><code>document.getElementById("MyElement").className += " MyClass";\n</code></pre>\n<h3>To remove a class from an element:</h3>\n<p>To remove a single class to an element, without affecting other potential classes, a simple regex replace is required:</p>\n<pre><code>document.getElementById("MyElement").className =\n document.getElementById("MyElement").className.replace\n ( /(?:^|\\s)MyClass(?!\\S)/g , '' )\n/* Code wrapped for readability - above is all one statement */\n</code></pre>\n<p>An explanation of this regex is as follows:</p>\n<pre><code>(?:^|\\s) # Match the start of the string or any single whitespace character\n\nMyClass # The literal text for the classname to remove\n\n(?!\\S) # Negative lookahead to verify the above is the whole classname\n # Ensures there is no non-space character following\n # (i.e. must be the end of the string or space)\n</code></pre>\n<p>The <code>g</code> flag tells the replace to repeat as required, in case the class name has been added multiple times.</p>\n<h3>To check if a class is already applied to an element:</h3>\n<p>The same regex used above for removing a class can also be used as a check as to whether a particular class exists:</p>\n<pre><code>if ( document.getElementById("MyElement").className.match(/(?:^|\\s)MyClass(?!\\S)/) )\n</code></pre>\n<br/>\n### Assigning these actions to onclick events:\n<p>Whilst it is possible to write JavaScript directly inside the HTML event attributes (such as <code>onclick="this.className+=' MyClass'"</code>) this is not recommended behaviour. Especially on larger applications, more maintainable code is achieved by separating HTML markup from JavaScript interaction logic.</p>\n<p>The first step to achieving this is by creating a function, and calling the function in the onclick attribute, for example:</p>\n<pre><code><script type="text/javascript">\n function changeClass(){\n // Code examples from above\n }\n</script>\n...\n<button onclick="changeClass()">My Button</button>\n</code></pre>\n<p><sub><em>(It is not required to have this code in script tags, this is simply for the brevity of example, and including the JavaScript in a distinct file may be more appropriate.)</em></sub></p>\n<p>The second step is to move the onclick event out of the HTML and into JavaScript, for example using <a href=\"https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener\" rel=\"noreferrer\">addEventListener</a></p>\n<pre><code><script type="text/javascript">\n function changeClass(){\n // Code examples from above\n }\n\n window.onload = function(){\n document.getElementById("MyElement").addEventListener( 'click', changeClass);\n }\n</script>\n...\n<button id="MyElement">My Button</button>\n</code></pre>\n<p>(Note that the window.onload part is required so that the contents of that function are executed <em>after</em> the HTML has finished loading - without this, the MyElement might not exist when the JavaScript code is called, so that line would fail.)</p>\n<br/>\n<h2>JavaScript Frameworks and Libraries</h2>\n<p>The above code is all in standard JavaScript, however, it is common practice to use either a framework or a library to simplify common tasks, as well as benefit from fixed bugs and edge cases that you might not think of when writing your code.</p>\n<p>Whilst some people consider it overkill to add a ~50 KB framework for simply changing a class, if you are doing any substantial amount of JavaScript work or anything that might have unusual cross-browser behavior, it is well worth considering.</p>\n<p><em>(Very roughly, a library is a set of tools designed for a specific task, whilst a framework generally contains multiple libraries and performs a complete set of duties.)</em></p>\n<p>The examples above have been reproduced below using <a href=\"http://jquery.com\" rel=\"noreferrer\">jQuery</a>, probably the most commonly used JavaScript library (though there are others worth investigating too).</p>\n<p>(Note that <code>$</code> here is the jQuery object.)</p>\n<h3>Changing Classes with jQuery:</h3>\n<pre><code>$('#MyElement').addClass('MyClass');\n\n$('#MyElement').removeClass('MyClass');\n\nif ( $('#MyElement').hasClass('MyClass') )\n</code></pre>\n<p>In addition, jQuery provides a shortcut for adding a class if it doesn't apply, or removing a class that does:</p>\n<pre><code>$('#MyElement').toggleClass('MyClass');\n</code></pre>\n<br/>\n### Assigning a function to a click event with jQuery:\n<pre><code>$('#MyElement').click(changeClass);\n</code></pre>\n<p>or, without needing an id:</p>\n<pre><code>$(':button:contains(My Button)').click(changeClass);\n</code></pre>\n<br/>\n"
},
{
"answer_id": 1870241,
"author": "Eric Bailey",
"author_id": 227530,
"author_profile": "https://Stackoverflow.com/users/227530",
"pm_score": 4,
"selected": false,
"text": "<p>The line</p>\n\n<pre><code>document.getElementById(\"MyElement\").className = document.getElementById(\"MyElement\").className.replace(/\\bMyClass\\b/','')\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>document.getElementById(\"MyElement\").className = document.getElementById(\"MyElement\").className.replace('/\\bMyClass\\b/','');\n</code></pre>\n"
},
{
"answer_id": 6160260,
"author": "Hiren Kansara",
"author_id": 774111,
"author_profile": "https://Stackoverflow.com/users/774111",
"pm_score": 4,
"selected": false,
"text": "<p>Change an element's CSS class with JavaScript in <a href=\"http://en.wikipedia.org/wiki/ASP.NET\" rel=\"noreferrer\">ASP.NET</a>:</p>\n\n<pre><code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n If Not Page.IsPostBack Then\n lbSave.Attributes.Add(\"onmouseover\", \"this.className = 'LinkButtonStyle1'\")\n lbSave.Attributes.Add(\"onmouseout\", \"this.className = 'LinkButtonStyle'\")\n lbCancel.Attributes.Add(\"onmouseover\", \"this.className = 'LinkButtonStyle1'\")\n lbCancel.Attributes.Add(\"onmouseout\", \"this.className = 'LinkButtonStyle'\")\n End If\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 6160317,
"author": "Andrew Orsich",
"author_id": 508601,
"author_profile": "https://Stackoverflow.com/users/508601",
"pm_score": 7,
"selected": false,
"text": "<p>In one of my old projects that did not use jQuery, I built the following functions for adding, removing and checking if an element has a class:</p>\n<pre><code>function hasClass(ele, cls) {\n return ele.className.match(new RegExp('(\\\\s|^)' + cls + '(\\\\s|$)'));\n}\n\nfunction addClass(ele, cls) {\n if (!hasClass(ele, cls))\n ele.className += " " + cls;\n}\n\nfunction removeClass(ele, cls) {\n if (hasClass(ele, cls)) {\n var reg = new RegExp('(\\\\s|^)' + cls + '(\\\\s|$)');\n ele.className = ele.className.replace(reg, ' ');\n }\n}\n</code></pre>\n<p>So, for example, if I want <code>onclick</code> to add some class to the button I can use this:</p>\n<pre><code><script type="text/javascript">\n function changeClass(btn, cls) {\n if(!hasClass(btn, cls)) {\n addClass(btn, cls);\n }\n }\n</script>\n...\n<button onclick="changeClass(this, "someClass")">My Button</button>\n</code></pre>\n<p>By now for sure it would just be better to use jQuery.</p>\n"
},
{
"answer_id": 6960449,
"author": "Tyilo",
"author_id": 640584,
"author_profile": "https://Stackoverflow.com/users/640584",
"pm_score": 9,
"selected": false,
"text": "<p>You could also just do:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>document.getElementById('id').classList.add('class');\ndocument.getElementById('id').classList.remove('class');\n</code></pre>\n\n<p>And to toggle a class (remove if exists else add it):</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>document.getElementById('id').classList.toggle('class');\n</code></pre>\n"
},
{
"answer_id": 7487686,
"author": "PseudoNinja",
"author_id": 588005,
"author_profile": "https://Stackoverflow.com/users/588005",
"pm_score": 6,
"selected": false,
"text": "<p>Using pure JavaScript code:</p>\n\n<pre><code>function hasClass(ele, cls) {\n return ele.className.match(new RegExp('(\\\\s|^)' + cls + '(\\\\s|$)'));\n}\n\nfunction addClass(ele, cls) {\n if (!this.hasClass(ele, cls)) ele.className += \" \" + cls;\n}\n\nfunction removeClass(ele, cls) {\n if (hasClass(ele, cls)) {\n var reg = new RegExp('(\\\\s|^)' + cls + '(\\\\s|$)');\n ele.className = ele.className.replace(reg, ' ');\n }\n}\n\nfunction replaceClass(ele, oldClass, newClass){\n if(hasClass(ele, oldClass)){\n removeClass(ele, oldClass);\n addClass(ele, newClass);\n }\n return;\n}\n\nfunction toggleClass(ele, cls1, cls2){\n if(hasClass(ele, cls1)){\n replaceClass(ele, cls1, cls2);\n }else if(hasClass(ele, cls2)){\n replaceClass(ele, cls2, cls1);\n }else{\n addClass(ele, cls1);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 8281605,
"author": "Ben Flynn",
"author_id": 449161,
"author_profile": "https://Stackoverflow.com/users/449161",
"pm_score": 5,
"selected": false,
"text": "<p>Just to add on information from another popular framework, Google Closures, see their <a href=\"http://closure-library.googlecode.com/svn/docs/closure_goog_dom_classes.js.html\" rel=\"nofollow noreferrer\">dom/classes</a> class:</p>\n<pre><code>goog.dom.classes.add(element, var_args)\n\ngoog.dom.classes.addRemove(element, classesToRemove, classesToAdd)\n\ngoog.dom.classes.remove(element, var_args)\n</code></pre>\n<p>One option for selecting the element is using <a href=\"http://closure-library.googlecode.com/svn/docs/closure_third_party_closure_goog_dojo_dom_query.js.html\" rel=\"nofollow noreferrer\">goog.dom.query</a> with a CSS 3 selector:</p>\n<pre><code>var myElement = goog.dom.query("#MyElement")[0];\n</code></pre>\n"
},
{
"answer_id": 8428872,
"author": "Gopal Krishna Ranjan",
"author_id": 1070666,
"author_profile": "https://Stackoverflow.com/users/1070666",
"pm_score": 5,
"selected": false,
"text": "<p>This is working for me:</p>\n\n<pre><code>function setCSS(eleID) {\n var currTabElem = document.getElementById(eleID);\n\n currTabElem.setAttribute(\"class\", \"some_class_name\");\n currTabElem.setAttribute(\"className\", \"some_class_name\");\n}\n</code></pre>\n"
},
{
"answer_id": 8748357,
"author": "Travis J",
"author_id": 1026459,
"author_profile": "https://Stackoverflow.com/users/1026459",
"pm_score": 6,
"selected": false,
"text": "<p>Wow, surprised there are so many overkill answers here...</p>\n\n<pre><code><div class=\"firstClass\" onclick=\"this.className='secondClass'\">\n</code></pre>\n"
},
{
"answer_id": 10407953,
"author": "Alex Robinson",
"author_id": 972805,
"author_profile": "https://Stackoverflow.com/users/972805",
"pm_score": 4,
"selected": false,
"text": "<p>A couple of minor notes and tweaks on the previous regexes:</p>\n\n<p>You'll want to do it globally in case the class list has the class name more than once. And, you'll probably want to strip spaces from the ends of the class list and convert multiple spaces to one space to keep from getting runs of spaces. None of these things should be a problem if the only code dinking with the class names uses the regex below and removes a name before adding it. But. Well, who knows who might be dinking with the class name list.</p>\n\n<p>This regex is case insensitive so that bugs in class names may show up before the code is used on a browser that doesn't care about case in class names.</p>\n\n<pre><code>var s = \"testing one four one two\";\nvar cls = \"one\";\nvar rg = new RegExp(\"(^|\\\\s+)\" + cls + \"(\\\\s+|$)\", 'ig');\nalert(\"[\" + s.replace(rg, ' ') + \"]\");\nvar cls = \"test\";\nvar rg = new RegExp(\"(^|\\\\s+)\" + cls + \"(\\\\s+|$)\", 'ig');\nalert(\"[\" + s.replace(rg, ' ') + \"]\");\nvar cls = \"testing\";\nvar rg = new RegExp(\"(^|\\\\s+)\" + cls + \"(\\\\s+|$)\", 'ig');\nalert(\"[\" + s.replace(rg, ' ') + \"]\");\nvar cls = \"tWo\";\nvar rg = new RegExp(\"(^|\\\\s+)\" + cls + \"(\\\\s+|$)\", 'ig');\nalert(\"[\" + s.replace(rg, ' ') + \"]\");\n</code></pre>\n"
},
{
"answer_id": 10458392,
"author": "shingokko",
"author_id": 557761,
"author_profile": "https://Stackoverflow.com/users/557761",
"pm_score": 4,
"selected": false,
"text": "<p>I would use jQuery and write something like this:</p>\n<pre><code>jQuery(function($) {\n $("#some-element").click(function() {\n $(this).toggleClass("clicked");\n });\n});\n</code></pre>\n<p>This code adds a function to be called when an element of the id <strong>some-element</strong> is clicked. The function appends <strong>clicked</strong> to the element's class attribute if it's not already part of it, and removes it if it's there.</p>\n<p>Yes, you do need to add a reference to the jQuery library in your page to use this code, but at least you can feel confident the most functions in the library would work on pretty much all the modern browsers, and it will save you time implementing your own code to do the same.</p>\n"
},
{
"answer_id": 12934226,
"author": "alfred",
"author_id": 345517,
"author_profile": "https://Stackoverflow.com/users/345517",
"pm_score": 4,
"selected": false,
"text": "<p>Here's my version, fully working:</p>\n\n<pre><code>function addHTMLClass(item, classname) {\n var obj = item\n if (typeof item==\"string\") {\n obj = document.getElementById(item)\n }\n obj.className += \" \" + classname\n}\n\nfunction removeHTMLClass(item, classname) {\n var obj = item\n if (typeof item==\"string\") {\n obj = document.getElementById(item)\n }\n var classes = \"\"+obj.className\n while (classes.indexOf(classname)>-1) {\n classes = classes.replace (classname, \"\")\n }\n obj.className = classes\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code><tr onmouseover='addHTMLClass(this,\"clsSelected\")'\nonmouseout='removeHTMLClass(this,\"clsSelected\")' >\n</code></pre>\n"
},
{
"answer_id": 15946168,
"author": "moka",
"author_id": 1312722,
"author_profile": "https://Stackoverflow.com/users/1312722",
"pm_score": 5,
"selected": false,
"text": "<p>As well you could extend HTMLElement object, in order to add methods to add, remove, toggle and check classes (<a href=\"https://gist.github.com/Maksims/5356227\" rel=\"noreferrer\">gist</a>):</p>\n\n<pre><code>HTMLElement = typeof(HTMLElement) != 'undefiend' ? HTMLElement : Element;\n\nHTMLElement.prototype.addClass = function(string) {\n if (!(string instanceof Array)) {\n string = string.split(' ');\n }\n for(var i = 0, len = string.length; i < len; ++i) {\n if (string[i] && !new RegExp('(\\\\s+|^)' + string[i] + '(\\\\s+|$)').test(this.className)) {\n this.className = this.className.trim() + ' ' + string[i];\n }\n }\n}\n\nHTMLElement.prototype.removeClass = function(string) {\n if (!(string instanceof Array)) {\n string = string.split(' ');\n }\n for(var i = 0, len = string.length; i < len; ++i) {\n this.className = this.className.replace(new RegExp('(\\\\s+|^)' + string[i] + '(\\\\s+|$)'), ' ').trim();\n }\n}\n\nHTMLElement.prototype.toggleClass = function(string) {\n if (string) {\n if (new RegExp('(\\\\s+|^)' + string + '(\\\\s+|$)').test(this.className)) {\n this.className = this.className.replace(new RegExp('(\\\\s+|^)' + string + '(\\\\s+|$)'), ' ').trim();\n } else {\n this.className = this.className.trim() + ' ' + string;\n }\n }\n}\n\nHTMLElement.prototype.hasClass = function(string) {\n return string && new RegExp('(\\\\s+|^)' + string + '(\\\\s+|$)').test(this.className);\n}\n</code></pre>\n\n<p>And then just use like this (on click will add or remove class):</p>\n\n<pre><code>document.getElementById('yourElementId').onclick = function() {\n this.toggleClass('active');\n}\n</code></pre>\n\n<p>Here is <a href=\"http://jsfiddle.net/5QMgR/\" rel=\"noreferrer\">demo</a>.</p>\n"
},
{
"answer_id": 21202309,
"author": "Salman A",
"author_id": 87015,
"author_profile": "https://Stackoverflow.com/users/87015",
"pm_score": 3,
"selected": false,
"text": "<p>I use the following vanilla JavaScript functions in my code. They use regular expressions and <code>indexOf</code> but do not require quoting special characters in regular expressions.</p>\n\n<pre><code>function addClass(el, cn) {\n var c0 = (\" \" + el.className + \" \").replace(/\\s+/g, \" \"),\n c1 = (\" \" + cn + \" \").replace(/\\s+/g, \" \");\n if (c0.indexOf(c1) < 0) {\n el.className = (c0 + c1).replace(/\\s+/g, \" \").replace(/^ | $/g, \"\");\n }\n}\n\nfunction delClass(el, cn) {\n var c0 = (\" \" + el.className + \" \").replace(/\\s+/g, \" \"),\n c1 = (\" \" + cn + \" \").replace(/\\s+/g, \" \");\n if (c0.indexOf(c1) >= 0) {\n el.className = c0.replace(c1, \" \").replace(/\\s+/g, \" \").replace(/^ | $/g, \"\");\n }\n}\n</code></pre>\n\n<p>You can also use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element.classList\" rel=\"noreferrer\">element.classList</a> in modern browsers.</p>\n"
},
{
"answer_id": 22890596,
"author": "uttamcafedeweb",
"author_id": 3078123,
"author_profile": "https://Stackoverflow.com/users/3078123",
"pm_score": -1,
"selected": false,
"text": "<p>Here is a simple jQuery code to do that:</p>\n<pre><code>$(".class1").click(function(argument) {\n $(".parentclass").removeClass("classtoremove");\n setTimeout(function (argument) {\n $(".parentclass").addClass("classtoadd");\n }, 100);\n});\n</code></pre>\n<p>Here,</p>\n<ul>\n<li>Class1 is a listener for an event.</li>\n<li>The parent class is the class which hosts the class you want to change</li>\n<li>Classtoremove is the old class you have.</li>\n<li>Class to add is the new class that you want to add.</li>\n<li>100 is the timeout delay during which the class is changed.</li>\n</ul>\n"
},
{
"answer_id": 29158446,
"author": "StackSlave",
"author_id": 2438423,
"author_profile": "https://Stackoverflow.com/users/2438423",
"pm_score": 2,
"selected": false,
"text": "<p>Just thought I'd throw this in:</p>\n\n<pre><code>function inArray(val, ary){\n for(var i=0,l=ary.length; i<l; i++){\n if(ary[i] === val){\n return true;\n }\n }\n return false;\n}\nfunction removeClassName(classNameS, fromElement){\n var x = classNameS.split(/\\s/), s = fromElement.className.split(/\\s/), r = [];\n for(var i=0,l=s.length; i<l; i++){\n if(!iA(s[i], x))r.push(s[i]);\n }\n fromElement.className = r.join(' ');\n}\nfunction addClassName(classNameS, toElement){\n var s = toElement.className.split(/\\s/);\n s.push(c); toElement.className = s.join(' ');\n}\n</code></pre>\n"
},
{
"answer_id": 33384795,
"author": "kofifus",
"author_id": 460084,
"author_profile": "https://Stackoverflow.com/users/460084",
"pm_score": 4,
"selected": false,
"text": "<p>Here's a toggleClass to toggle/add/remove a class on an element:</p>\n<pre><code>// If newState is provided add/remove theClass accordingly, otherwise toggle theClass\nfunction toggleClass(elem, theClass, newState) {\n var matchRegExp = new RegExp('(?:^|\\\\s)' + theClass + '(?!\\\\S)', 'g');\n var add=(arguments.length>2 ? newState : (elem.className.match(matchRegExp) == null));\n\n elem.className=elem.className.replace(matchRegExp, ''); // clear all\n if (add) elem.className += ' ' + theClass;\n}\n</code></pre>\n<p>See <a href=\"https://jsfiddle.net/dLuhp9se/\" rel=\"nofollow noreferrer\">the JSFiddle</a>.</p>\n<p>Also see my answer <a href=\"https://stackoverflow.com/a/42941303/460084\">here</a> for creating a new class dynamically.</p>\n"
},
{
"answer_id": 33528818,
"author": "Eugene Tiurin",
"author_id": 2676500,
"author_profile": "https://Stackoverflow.com/users/2676500",
"pm_score": 4,
"selected": false,
"text": "<h1>Change an element's class in vanilla JavaScript with Internet Explorer 6 support</h1>\n<p>You may try to use the node <code>attributes</code> property to keep compatibility with old browsers, even Internet Explorer 6:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function getClassNode(element) {\n for (var i = element.attributes.length; i--;)\n if (element.attributes[i].nodeName === 'class')\n return element.attributes[i];\n}\n\nfunction removeClass(classNode, className) {\n var index, classList = classNode.value.split(' ');\n if ((index = classList.indexOf(className)) > -1) {\n classList.splice(index, 1);\n classNode.value = classList.join(' ');\n }\n}\n\nfunction hasClass(classNode, className) {\n return classNode.value.indexOf(className) > -1;\n}\n\nfunction addClass(classNode, className) {\n if (!hasClass(classNode, className))\n classNode.value += ' ' + className;\n}\n\ndocument.getElementById('message').addEventListener('click', function() {\n var classNode = getClassNode(this);\n var className = hasClass(classNode, 'red') && 'blue' || 'red';\n\n removeClass(classNode, 'red');\n removeClass(classNode, 'blue');\n\n addClass(classNode, className);\n})</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.red {\n color: red;\n}\n.red:before {\n content: 'I am red! ';\n}\n.red:after {\n content: ' again';\n}\n.blue {\n color: blue;\n}\n.blue:before {\n content: 'I am blue! '\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><span id=\"message\" class=\"\">Click me</span></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 43533114,
"author": "Ronnie Royston",
"author_id": 4797603,
"author_profile": "https://Stackoverflow.com/users/4797603",
"pm_score": 2,
"selected": false,
"text": "<p>Just use <code>myElement.classList="new-class"</code> unless you need to maintain other existing classes in which case you can use the <code>classList.add, .remove</code> methods.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var doc = document;\nvar divOne = doc.getElementById(\"one\");\nvar goButton = doc.getElementById(\"go\");\n\ngoButton.addEventListener(\"click\", function() {\n divOne.classList=\"blue\";\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>div{\n min-height: 48px;\n min-width: 48px;\n}\n.bordered{\n border: 1px solid black;\n}\n.green{\n background: green;\n}\n.blue{\n background: blue;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><button id=\"go\">Change Class</button>\n\n<div id=\"one\" class=\"bordered green\">\n\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 44243730,
"author": "Alireza",
"author_id": 5423108,
"author_profile": "https://Stackoverflow.com/users/5423108",
"pm_score": 2,
"selected": false,
"text": "<p>OK, I think in this case you should use jQuery or write your own Methods in pure JavaScript. My preference is adding my own methods rather than injecting all jQuery to my application if I don't need that for other reasons.</p>\n<p>I'd like to do something like below as methods to my JavaScript framework to add few functionalities which handle adding classes, deleting classes, etc. Similar to jQuery, this is fully supported in IE9+. Also my code is written in ES6, so you need to make sure your browser support it or you using something like <a href=\"https://en.wikipedia.org/wiki/Babel_(transcompiler)\" rel=\"nofollow noreferrer\">Babel</a>, otherwise need to use ES5 syntax in your code. Also in this way, we finding element via ID, which means the element needs to have an ID to be selected:</p>\n<pre><code>// Simple JavaScript utilities for class management in ES6\nvar classUtil = {\n\n addClass: (id, cl) => {\n document.getElementById(id).classList.add(cl);\n },\n\n removeClass: (id, cl) => {\n document.getElementById(id).classList.remove(cl);\n },\n\n hasClass: (id, cl) => {\n return document.getElementById(id).classList.contains(cl);\n },\n\n toggleClass: (id, cl) => {\n document.getElementById(id).classList.toggle(cl);\n }\n\n}\n</code></pre>\n<p>And you can simply use them as below. Imagine your element has id of 'id' and class of 'class'. Make sure you pass them as a string. You can use the utility as below:</p>\n<pre><code>classUtil.addClass('myId', 'myClass');\nclassUtil.removeClass('myId', 'myClass');\nclassUtil.hasClass('myId', 'myClass');\nclassUtil.toggleClass('myId', 'myClass');\n</code></pre>\n"
},
{
"answer_id": 52440576,
"author": "Willem van der Veen",
"author_id": 8059459,
"author_profile": "https://Stackoverflow.com/users/8059459",
"pm_score": 2,
"selected": false,
"text": "<h2><code>classList</code> DOM API:</h2>\n<p>A very convenient manner of adding and removing classes is the <code>classList</code> DOM API. This API allows us to select all classes of a specific DOM element in order to modify the list using JavaScript. For example:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const el = document.getElementById(\"main\");\nconsole.log(el.classList);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"content wrapper animated\" id=\"main\"></div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>We can observe in the log that we are getting back an object with not only the classes of the element, but also many auxiliary methods and properties. This object inherits from the interface <strong>DOMTokenList</strong>, an interface which is used in the DOM to represent a set of space separated tokens (like classes).</p>\n<h2>Example:</h2>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const el = document.getElementById('container');\n\nfunction addClass () {\n el.classList.add('newclass');\n}\n\n\nfunction replaceClass () {\n el.classList.replace('foo', 'newFoo');\n}\n\n\nfunction removeClass () {\n el.classList.remove('bar');\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>button{\n margin: 20px;\n}\n\n.foo{\n color: red;\n}\n\n.newFoo {\n color: blue;\n}\n\n.bar{\n background-color: powderblue;\n}\n\n.newclass{\n border: 2px solid green;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"foo bar\" id=\"container\">\n \"Sed ut perspiciatis unde omnis\n iste natus error sit voluptatem accusantium doloremque laudantium,\n totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et\n quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam\n voluptatem quia voluptas\n </div>\n\n<button onclick=\"addClass()\">AddClass</button>\n\n<button onclick=\"replaceClass()\">ReplaceClass</button>\n\n<button onclick=\"removeClass()\">removeClass</button></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 54555429,
"author": "Danish Khan",
"author_id": 4619794,
"author_profile": "https://Stackoverflow.com/users/4619794",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, there are many ways to do this. In ES6 syntax we can achieve easily. Use this code toggle add and remove class.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const tabs=document.querySelectorAll('.menu li');\n\nfor(let tab of tabs){\n\n tab.onclick = function(){\n\n let activetab = document.querySelectorAll('li.active');\n\n activetab[0].classList.remove('active')\n\n tab.classList.add('active');\n }\n\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\n padding: 20px;\n font-family: sans-serif;\n}\n\nul {\n margin: 20px 0;\n list-style: none;\n}\n\nli {\n background: #dfdfdf;\n padding: 10px;\n margin: 6px 0;\n cursor: pointer;\n}\n\nli.active {\n background: #2794c7;\n font-weight: bold;\n color: #ffffff;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><i>Please click an item:</i>\n\n<ul class=\"menu\">\n <li class=\"active\"><span>Three</span></li>\n <li><span>Two</span></li>\n <li><span>One</span></li>\n</ul></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 54824928,
"author": "tfont",
"author_id": 1804013,
"author_profile": "https://Stackoverflow.com/users/1804013",
"pm_score": 2,
"selected": false,
"text": "<p><strong>TL;DR:</strong></p>\n<pre><code>document.getElementById('id').className = 'class'\n</code></pre>\n<p><em>OR</em></p>\n<pre><code>document.getElementById('id').classList.add('class');\ndocument.getElementById('id').classList.remove('class');\n</code></pre>\n<p><em><strong>That's it.</strong></em></p>\n<p>And, if you really want to know the why and educate yourself then I suggest reading <a href=\"https://stackoverflow.com/a/196038/1804013\">Peter Boughton's answer</a>. It's perfect.</p>\n<p><strong>Note:</strong><br/></p>\n<p>This is possible with (<em><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document\" rel=\"nofollow noreferrer\">document</a></em> or <em><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Event/target\" rel=\"nofollow noreferrer\">event</a></em>):</p>\n<ul>\n<li><code>getElementById()</code></li>\n<li><code>getElementsByClassName()</code></li>\n<li><code>querySelector()</code></li>\n<li><code>querySelectorAll()</code></li>\n</ul>\n"
},
{
"answer_id": 55674450,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 3,
"selected": false,
"text": "<p>Try:</p>\n<pre><code>element.className='second'\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function change(box) { box.className='second' }</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.first { width: 70px; height: 70px; background: #ff0 }\n.second { width: 150px; height: 150px; background: #f00; transition: 1s }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div onclick=\"change(this)\" class=\"first\">Click me</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 57615210,
"author": "Brian Nezhad",
"author_id": 2556515,
"author_profile": "https://Stackoverflow.com/users/2556515",
"pm_score": 3,
"selected": false,
"text": "<hr />\n<h1>THE OPTIONS.</h1>\n<p>Here is a little style vs. classList examples to get you to see what are the options you have available and how to use <code>classList</code> to do what you want.</p>\n<h1><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style\" rel=\"nofollow noreferrer\"><code>style</code></a> vs. <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/classList\" rel=\"nofollow noreferrer\"><code>classList</code></a></h1>\n<p>The difference between <code>style</code> and <code>classList</code> is that with <code>style</code> you're adding to the style properties of the element, but <code>classList</code> is kinda controlling the class(es) of the element (<code>add</code>, <code>remove</code>, <code>toggle</code>, <code>contain</code>), I will show you how to use the <code>add</code> and <code>remove</code> method since those are the popular ones.</p>\n<hr />\n<h2>Style Example</h2>\n<p>If you want to add <code>margin-top </code> property into an element, you would do in such:</p>\n<pre><code>// Get the Element\nconst el = document.querySelector('#element');\n\n// Add CSS property \nel.style.margintop = "0px"\nel.style.margintop = "25px" // This would add a 25px to the top of the element.\n</code></pre>\n<hr />\n<h2>classList Example</h2>\n<p>Let say we have a <code><div class="class-a class-b"></code>, in this case, we have 2 classes added to our div element already, <code>class-a</code> and <code>class-b</code>, and we want to control what classes <strong><code>remove</code></strong> and what class to <strong><code>add</code></strong>. This is where <code>classList</code> becomes handy.</p>\n<h3>Remove <code>class-b</code></h3>\n<pre><code>// Get the Element\nconst el = document.querySelector('#element');\n\n// Remove class-b style from the element\nel.classList.remove("class-b")\n\n</code></pre>\n<h3>Add <code>class-c</code></h3>\n<pre><code>// Get the Element\nconst el = document.querySelector('#element');\n\n// Add class-b style from the element\nel.classList.add("class-c")\n\n</code></pre>\n<hr />\n"
},
{
"answer_id": 57791625,
"author": "donatso",
"author_id": 7733202,
"author_profile": "https://Stackoverflow.com/users/7733202",
"pm_score": 2,
"selected": false,
"text": "<pre><code>function classed(el, class_name, add_class) {\n const re = new RegExp("(?:^|\\\\s)" + class_name + "(?!\\\\S)", "g");\n if (add_class && !el.className.match(re)) el.className += " " + class_name\n else if (!add_class) el.className = el.className.replace(re, '');\n}\n</code></pre>\n<p>Using <a href=\"https://stackoverflow.com/questions/195951/how-can-i-change-an-elements-class-with-javascript/196038#196038\">Peter Boughton's answer</a>, here is a simple cross-browser function to add and remove class.</p>\n<p>Add class:</p>\n<pre><code>classed(document.getElementById("denis"), "active", true)\n</code></pre>\n<p>Remove class:</p>\n<pre><code>classed(document.getElementById("denis"), "active", false)\n</code></pre>\n"
},
{
"answer_id": 60774130,
"author": "Jai Prakash",
"author_id": 12257880,
"author_profile": "https://Stackoverflow.com/users/12257880",
"pm_score": 2,
"selected": false,
"text": "<p>There is a property, <strong>className</strong>, in JavaScript to change the name of the class of an HTML element. The existing class value will be replaced with the new one, that you have assigned in className.</p>\n<pre><code><!DOCTYPE html>\n<html>\n<head>\n<title>How can I change the class of an HTML element in JavaScript?</title>\n<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">\n</head>\n<body>\n<h1 align="center"><i class="fa fa-home" id="icon"></i></h1><br />\n\n<center><button id="change-class">Change Class</button></center>\n\n<script>\nvar change_class = document.getElementById("change-class");\nchange_class.onclick = function()\n{\n var icon=document.getElementById("icon");\n icon.className = "fa fa-gear";\n}\n</script>\n</body>\n</html>\n</code></pre>\n<p>Credit - <em><a href=\"https://jaischool.com/javascript-lang/how-to-change-class-name-of-an-html-element-in-javascript.html\" rel=\"nofollow noreferrer\">How To Change Class Name of an HTML Element in JavaScript</a></em></p>\n"
},
{
"answer_id": 61582806,
"author": "timbo",
"author_id": 127660,
"author_profile": "https://Stackoverflow.com/users/127660",
"pm_score": 3,
"selected": false,
"text": "<p>The OP question was <em>How can I change an element's class with JavaScript?</em></p>\n<p>Modern browsers allow you to do this <strong>with one line of JavaScript</strong>:</p>\n<p><code>document.getElementById('id').classList.replace('span1', 'span2')</code></p>\n<p>The <code>classList</code> attribute provides a DOMTokenList which has a <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList\" rel=\"nofollow noreferrer\">variety of methods</a>. You can operate on an element's classList using simple manipulations like <em>add()</em>, <em>remove()</em> or <em>replace()</em>. Or get very sophisticated and manipulate classes like you would an object or Map with <em>keys()</em>, <em>values()</em>, and <em>entries()</em>.</p>\n<p><a href=\"https://stackoverflow.com/questions/195951/how-can-i-change-an-elements-class-with-javascript/196038#196038\">Peter Boughton's answer</a> is a great one, but it's now over a decade old. All modern browsers now support DOMTokenList - see <a href=\"https://caniuse.com/#search=classList\" rel=\"nofollow noreferrer\">https://caniuse.com/#search=classList</a> and even <a href=\"https://en.wikipedia.org/wiki/Internet_Explorer_11#Internet_Explorer_11\" rel=\"nofollow noreferrer\">Internet Explorer 11</a> supports some DOMTokenList methods.</p>\n"
},
{
"answer_id": 69060627,
"author": "Satish Chandra Gupta",
"author_id": 9445290,
"author_profile": "https://Stackoverflow.com/users/9445290",
"pm_score": 5,
"selected": false,
"text": "<h1>4 actions possible: Add, Remove, Check, and Toggle</h1>\n<p>Let's see multiple ways for each action.</p>\n<h2>1. Add class</h2>\n<p><strong>Method 1:</strong> Best way to add class in the modern browser is using <code>classList.add()</code> method of element.</p>\n<ul>\n<li><p><strong>Case 1</strong>: Adding single class</p>\n<pre class=\"lang-js prettyprint-override\"><code>function addClass() {\n let element = document.getElementById('id1');\n\n // adding class\n element.classList.add('beautify');\n}\n</code></pre>\n</li>\n<li><p><strong>Case 2</strong>: Adding multiple class</p>\n<p>To add multiple class saperate classes by a comma in the <code>add()</code> method</p>\n<pre class=\"lang-js prettyprint-override\"><code>function addClass() {\n let element = document.getElementById('id1');\n\n // adding multiple class\n element.classList.add('class1', 'class2', 'class3');\n}\n</code></pre>\n</li>\n</ul>\n<p><strong>Method 2</strong> - You can also add classes to HTML elements using <code>className</code> property.</p>\n<ul>\n<li><strong>Case 1</strong>: Overwriting pre-existing classes\nWhen you assign a new class to the <code>className</code> property it overwrites the previous class.\n<pre class=\"lang-js prettyprint-override\"><code>function addClass() {\n let element = document.getElementById('id1');\n\n // adding multiple class\n element.className = 'beautify';\n}\n</code></pre>\n</li>\n<li><strong>Case 2</strong>: Adding class without overwrite\nUse <code>+=</code> operator for class not to overwrite previous classes. Also add an extra space before new class.\n<pre class=\"lang-js prettyprint-override\"><code>function addClass() {\n let element = document.getElementById('id1');\n\n // adding single multiple class\n element.className += ' beautify';\n // adding multiple classes\n element.className += ' class1 class2 class3';\n}\n</code></pre>\n</li>\n</ul>\n<hr />\n<h2>2. Remove class</h2>\n<p><strong>Method 1</strong> - Best way to remove a class from an element is <code>classList.remove()</code> method.</p>\n<ul>\n<li><p><strong>Case 1</strong>: Remove single class</p>\n<p>Just pass the class name you want to remove from the element in the method.</p>\n<pre class=\"lang-js prettyprint-override\"><code>function removeClass() {\n let element = document.getElementById('id1');\n\n // removing class\n element.classList.remove('beautify');\n}\n</code></pre>\n</li>\n<li><p><strong>Case 2</strong>: Remove multiple class</p>\n<p>Pass multiple classes separated by a comma.</p>\n<pre class=\"lang-js prettyprint-override\"><code>function removeClass() {\n let element = document.getElementById('id1');\n\n // removing class\n element.classList.remove('class1', 'class2', 'class3');\n}\n</code></pre>\n</li>\n</ul>\n<p><strong>Method 2</strong> - You can also remove class using <code>className</code> method.</p>\n<ul>\n<li><strong>Case 1</strong>: Removing single class\nIf the element has only 1 class and you want to remove it then just assign an empty string to the <code>className</code> method.\n<pre class=\"lang-js prettyprint-override\"><code>function removeClass() {\n let element = document.getElementById('id1');\n\n // removing class\n element.className = '';\n}\n</code></pre>\n</li>\n<li><strong>Case 2</strong>: Removing multiple class\nIf the element multiple classes the first get all classes from the element using <code>className</code> property and use replace method and replace desired classes with empty string and finally assign it to element]s <code>className</code> property.\n<pre class=\"lang-js prettyprint-override\"><code>function removeClass() {\n let element = document.getElementById('id1');\n\n // removing class\n element.className = element.className.replace('class1', '');\n}\n</code></pre>\n</li>\n</ul>\n<hr />\n<h2>3. Checking class</h2>\n<p>To check if a class exists in the element you can simply use <strong><code>classList.contains()</code></strong> method. It returns <code>true</code> if the class exists else returns false.</p>\n<pre><code>function checkClass() {\n let element = document.getElementById('id1');\n\n // checking class\n if(element.classList.contains('beautify') {\n alert('Yes! class exists');\n }\n}\n</code></pre>\n<hr />\n<h2>4. Toggle class</h2>\n<p>To toggle a class use <strong><code>classList.toggle()</code></strong> method.</p>\n<pre class=\"lang-js prettyprint-override\"><code>function toggleClass() {\n let element = document.getElementById('id1');\n\n // toggle class\n element.classList.toggle('beautify');\n}\n</code></pre>\n"
},
{
"answer_id": 69131856,
"author": "gomn",
"author_id": 7347433,
"author_profile": "https://Stackoverflow.com/users/7347433",
"pm_score": 3,
"selected": false,
"text": "<p>For IE v6-9 (in which <code>classList</code> is not supported and you don't want to use polyfills):</p>\n<pre><code>var elem = document.getElementById('some-id');\n\n// don't forget the extra space before the class name\nvar classList = elem.getAttribute('class') + ' other-class-name';\n\nelem.setAttribute('class', classList);\n</code></pre>\n"
},
{
"answer_id": 74653402,
"author": "fatima hassan",
"author_id": 8891459,
"author_profile": "https://Stackoverflow.com/users/8891459",
"pm_score": 0,
"selected": false,
"text": "<pre><code> document.getElementById("MyTest").classList.add('TestClass');\n</code></pre>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4998/"
] |
How can I change the class of an HTML element in response to an `onclick` or any other events using JavaScript?
|
Modern HTML5 Techniques for changing classes
--------------------------------------------
Modern browsers have added [**classList**](https://developer.mozilla.org/en-US/docs/DOM/element.classList) which provides methods to make it easier to manipulate classes without needing a library:
```
document.getElementById("MyElement").classList.add('MyClass');
document.getElementById("MyElement").classList.remove('MyClass');
if ( document.getElementById("MyElement").classList.contains('MyClass') )
document.getElementById("MyElement").classList.toggle('MyClass');
```
Unfortunately, these do not work in Internet Explorer prior to v10, though there is a [shim](http://en.wikipedia.org/wiki/Shim_(computing)) to add support for it to IE8 and IE9, available from [this page](https://developer.mozilla.org/en-US/docs/DOM/element.classList). It is, though, getting more and more [supported](http://caniuse.com/#feat=classlist).
Simple cross-browser solution
-----------------------------
The standard JavaScript way to select an element is using [`document.getElementById("Id")`](https://developer.mozilla.org/en-US/docs/DOM/document.getElementById), which is what the following examples use - you can of course obtain elements in other ways, and in the right situation may simply use `this` instead - however, going into detail on this is beyond the scope of the answer.
### To change all classes for an element:
To replace all existing classes with one or more new classes, set the className attribute:
```
document.getElementById("MyElement").className = "MyClass";
```
(You can use a space-delimited list to apply multiple classes.)
### To add an additional class to an element:
To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so:
```
document.getElementById("MyElement").className += " MyClass";
```
### To remove a class from an element:
To remove a single class to an element, without affecting other potential classes, a simple regex replace is required:
```
document.getElementById("MyElement").className =
document.getElementById("MyElement").className.replace
( /(?:^|\s)MyClass(?!\S)/g , '' )
/* Code wrapped for readability - above is all one statement */
```
An explanation of this regex is as follows:
```
(?:^|\s) # Match the start of the string or any single whitespace character
MyClass # The literal text for the classname to remove
(?!\S) # Negative lookahead to verify the above is the whole classname
# Ensures there is no non-space character following
# (i.e. must be the end of the string or space)
```
The `g` flag tells the replace to repeat as required, in case the class name has been added multiple times.
### To check if a class is already applied to an element:
The same regex used above for removing a class can also be used as a check as to whether a particular class exists:
```
if ( document.getElementById("MyElement").className.match(/(?:^|\s)MyClass(?!\S)/) )
```
### Assigning these actions to onclick events:
Whilst it is possible to write JavaScript directly inside the HTML event attributes (such as `onclick="this.className+=' MyClass'"`) this is not recommended behaviour. Especially on larger applications, more maintainable code is achieved by separating HTML markup from JavaScript interaction logic.
The first step to achieving this is by creating a function, and calling the function in the onclick attribute, for example:
```
<script type="text/javascript">
function changeClass(){
// Code examples from above
}
</script>
...
<button onclick="changeClass()">My Button</button>
```
*(It is not required to have this code in script tags, this is simply for the brevity of example, and including the JavaScript in a distinct file may be more appropriate.)*
The second step is to move the onclick event out of the HTML and into JavaScript, for example using [addEventListener](https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener)
```
<script type="text/javascript">
function changeClass(){
// Code examples from above
}
window.onload = function(){
document.getElementById("MyElement").addEventListener( 'click', changeClass);
}
</script>
...
<button id="MyElement">My Button</button>
```
(Note that the window.onload part is required so that the contents of that function are executed *after* the HTML has finished loading - without this, the MyElement might not exist when the JavaScript code is called, so that line would fail.)
JavaScript Frameworks and Libraries
-----------------------------------
The above code is all in standard JavaScript, however, it is common practice to use either a framework or a library to simplify common tasks, as well as benefit from fixed bugs and edge cases that you might not think of when writing your code.
Whilst some people consider it overkill to add a ~50 KB framework for simply changing a class, if you are doing any substantial amount of JavaScript work or anything that might have unusual cross-browser behavior, it is well worth considering.
*(Very roughly, a library is a set of tools designed for a specific task, whilst a framework generally contains multiple libraries and performs a complete set of duties.)*
The examples above have been reproduced below using [jQuery](http://jquery.com), probably the most commonly used JavaScript library (though there are others worth investigating too).
(Note that `$` here is the jQuery object.)
### Changing Classes with jQuery:
```
$('#MyElement').addClass('MyClass');
$('#MyElement').removeClass('MyClass');
if ( $('#MyElement').hasClass('MyClass') )
```
In addition, jQuery provides a shortcut for adding a class if it doesn't apply, or removing a class that does:
```
$('#MyElement').toggleClass('MyClass');
```
### Assigning a function to a click event with jQuery:
```
$('#MyElement').click(changeClass);
```
or, without needing an id:
```
$(':button:contains(My Button)').click(changeClass);
```
|
195,975 |
<p>For example, how to avoid writing the 'func_name' twice?</p>
<pre><code>#ifndef TEST_FUN
# define TEST_FUN func_name
# define TEST_FUN_NAME "func_name"
#endif
</code></pre>
<p>I'd like to follow the <a href="http://en.wikipedia.org/wiki/Single_Point_of_Truth" rel="noreferrer">Single Point of Truth</a> rule.</p>
<p>Version of C preprocessor:</p>
<pre><code>$ cpp --version
cpp (GCC) 4.1.2 20070626 (Red Hat 4.1.2-14)
</code></pre>
|
[
{
"answer_id": 195980,
"author": "shoosh",
"author_id": 9611,
"author_profile": "https://Stackoverflow.com/users/9611",
"pm_score": -1,
"selected": false,
"text": "<p><code>#define TEST_FUN_NAME #FUNC_NAME</code></p>\n\n<p>see <a href=\"http://en.wikipedia.org/wiki/C_preprocessor#Indirectly_quoting_macro_arguments\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 195999,
"author": "Jason Weathered",
"author_id": 3736,
"author_profile": "https://Stackoverflow.com/users/3736",
"pm_score": 0,
"selected": false,
"text": "<pre><code>#include <stdio.h>\n\n#define QUOTEME(x) #x\n\n#ifndef TEST_FUN\n# define TEST_FUN func_name\n# define TEST_FUN_NAME QUOTEME(TEST_FUN)\n#endif\n\nint main(void)\n{\n puts(TEST_FUN_NAME);\n return 0;\n}\n</code></pre>\n\n<p>Reference: Wikipedia's <a href=\"http://en.wikipedia.org/wiki/C_preprocessor#Quoting_macro_arguments\" rel=\"nofollow noreferrer\">C preprocessor</a> page</p>\n"
},
{
"answer_id": 196018,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 7,
"selected": true,
"text": "<p><a href=\"https://stackoverflow.com/users/9611/shoosh\">He who is Shy</a><sup>*</sup> gave you the germ of an <a href=\"https://stackoverflow.com/a/195980/15168\">answer</a>, but only the germ. The basic technique for converting a value into a string in the C pre-processor is indeed via the '#' operator, but a simple transliteration of the proposed solution gets a compilation error:</p>\n\n<pre><code>#define TEST_FUNC test_func\n#define TEST_FUNC_NAME #TEST_FUNC\n\n#include <stdio.h>\nint main(void)\n{\n puts(TEST_FUNC_NAME);\n return(0);\n}\n</code></pre>\n\n<p>The syntax error is on the 'puts()' line - the problem is a 'stray #' in the source.</p>\n\n<p>In section 6.10.3.2 of the C standard, 'The # operator', it says:</p>\n\n<blockquote>\n <p>Each # preprocessing token in the\n replacement list for a function-like\n macro shall be followed by a parameter\n as the next preprocessing token in the\n replacement list.</p>\n</blockquote>\n\n<p>The trouble is that you can convert macro arguments to strings -- but you can't convert random items that are not macro arguments.</p>\n\n<p>So, to achieve the effect you are after, you most certainly have to do some extra work.</p>\n\n<pre><code>#define FUNCTION_NAME(name) #name\n#define TEST_FUNC_NAME FUNCTION_NAME(test_func)\n\n#include <stdio.h>\n\nint main(void)\n{\n puts(TEST_FUNC_NAME);\n return(0);\n}\n</code></pre>\n\n<p>I'm not completely clear on how you plan to use the macros, and how you plan to avoid repetition altogether. This slightly more elaborate example might be more informative. The use of a macro equivalent to STR_VALUE is an idiom that is necessary to get the desired result.</p>\n\n<pre><code>#define STR_VALUE(arg) #arg\n#define FUNCTION_NAME(name) STR_VALUE(name)\n\n#define TEST_FUNC test_func\n#define TEST_FUNC_NAME FUNCTION_NAME(TEST_FUNC)\n\n#include <stdio.h>\n\nstatic void TEST_FUNC(void)\n{\n printf(\"In function %s\\n\", TEST_FUNC_NAME);\n}\n\nint main(void)\n{\n puts(TEST_FUNC_NAME);\n TEST_FUNC();\n return(0);\n}\n</code></pre>\n\n<hr>\n\n<p><sup>* At the time when this answer was first written, <a href=\"https://stackoverflow.com/users/9611/shoosh\">shoosh</a>'s name used 'Shy' as part of the name.</sup></p>\n"
},
{
"answer_id": 196093,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 4,
"selected": false,
"text": "<p>@Jonathan Leffler: Thank you. Your solution works.</p>\n\n<p>A complete working example:</p>\n\n<pre><code>/** compile-time dispatch \n\n $ gcc -Wall -DTEST_FUN=another_func macro_sub.c -o macro_sub && ./macro_sub\n*/\n#include <stdio.h>\n\n#define QUOTE(name) #name\n#define STR(macro) QUOTE(macro)\n\n#ifndef TEST_FUN\n# define TEST_FUN some_func\n#endif\n\n#define TEST_FUN_NAME STR(TEST_FUN)\n\nvoid some_func(void)\n{\n printf(\"some_func() called\\n\");\n}\n\nvoid another_func(void)\n{\n printf(\"do something else\\n\");\n}\n\nint main(void)\n{\n TEST_FUN();\n printf(\"TEST_FUN_NAME=%s\\n\", TEST_FUN_NAME);\n return 0;\n}\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>$ gcc -Wall -DTEST_FUN=another_func macro_sub.c -o macro_sub && ./macro_sub\ndo something else\nTEST_FUN_NAME=another_func\n</code></pre>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4279/"
] |
For example, how to avoid writing the 'func\_name' twice?
```
#ifndef TEST_FUN
# define TEST_FUN func_name
# define TEST_FUN_NAME "func_name"
#endif
```
I'd like to follow the [Single Point of Truth](http://en.wikipedia.org/wiki/Single_Point_of_Truth) rule.
Version of C preprocessor:
```
$ cpp --version
cpp (GCC) 4.1.2 20070626 (Red Hat 4.1.2-14)
```
|
[He who is Shy](https://stackoverflow.com/users/9611/shoosh)\* gave you the germ of an [answer](https://stackoverflow.com/a/195980/15168), but only the germ. The basic technique for converting a value into a string in the C pre-processor is indeed via the '#' operator, but a simple transliteration of the proposed solution gets a compilation error:
```
#define TEST_FUNC test_func
#define TEST_FUNC_NAME #TEST_FUNC
#include <stdio.h>
int main(void)
{
puts(TEST_FUNC_NAME);
return(0);
}
```
The syntax error is on the 'puts()' line - the problem is a 'stray #' in the source.
In section 6.10.3.2 of the C standard, 'The # operator', it says:
>
> Each # preprocessing token in the
> replacement list for a function-like
> macro shall be followed by a parameter
> as the next preprocessing token in the
> replacement list.
>
>
>
The trouble is that you can convert macro arguments to strings -- but you can't convert random items that are not macro arguments.
So, to achieve the effect you are after, you most certainly have to do some extra work.
```
#define FUNCTION_NAME(name) #name
#define TEST_FUNC_NAME FUNCTION_NAME(test_func)
#include <stdio.h>
int main(void)
{
puts(TEST_FUNC_NAME);
return(0);
}
```
I'm not completely clear on how you plan to use the macros, and how you plan to avoid repetition altogether. This slightly more elaborate example might be more informative. The use of a macro equivalent to STR\_VALUE is an idiom that is necessary to get the desired result.
```
#define STR_VALUE(arg) #arg
#define FUNCTION_NAME(name) STR_VALUE(name)
#define TEST_FUNC test_func
#define TEST_FUNC_NAME FUNCTION_NAME(TEST_FUNC)
#include <stdio.h>
static void TEST_FUNC(void)
{
printf("In function %s\n", TEST_FUNC_NAME);
}
int main(void)
{
puts(TEST_FUNC_NAME);
TEST_FUNC();
return(0);
}
```
---
\* At the time when this answer was first written, [shoosh](https://stackoverflow.com/users/9611/shoosh)'s name used 'Shy' as part of the name.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.