qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
191,746
<p>Given the following HTML:</p> <pre><code>&lt;select name="my_dropdown" id="my_dropdown"&gt; &lt;option value="1"&gt;displayed text 1&lt;/option&gt; &lt;/select&gt; </code></pre> <p>How do I grab the string "displayed text 1" using Javascript/the DOM?</p>
[ { "answer_id": 191755, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 1, "selected": false, "text": "myOptionNode.childNodes[0];\n myOptionNode.text;\n" }, { "answer_id": 191767, "author": "Liam", "author_id": 18333, "author_profile": "https://Stackoverflow.com/users/18333", "pm_score": 4, "selected": true, "text": "var sel = document.getElementById(\"my_dropdown\");\n\n//get the selected option\nvar selectedText = sel.options[sel.selectedIndex].text;\n\n//or get the first option\nvar optionText = sel.options[0].text;\n\n//or get the option with value=\"1\"\nfor(var i=0; i<sel.options.length; i++){\n if(sel.options[i].value == \"1\"){\n var valueIsOneText = sel.options[i].text;\n }\n}\n" }, { "answer_id": 191778, "author": "Joe Scylla", "author_id": 25771, "author_profile": "https://Stackoverflow.com/users/25771", "pm_score": 2, "selected": false, "text": "var mySelect = document.forms[\"my_form\"].my_dropdown;\n// or if you select has a id\nvar mySelect = document.getElementById(\"my_dropdown\");\nvar text = mySelect.options[mySelect.selectedIndex].text;\n" }, { "answer_id": 191804, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 0, "selected": false, "text": "$$('#my_dropdown option[value=1]').each( function(elem){\n alert(elem.text);\n });\n" }, { "answer_id": 192176, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 2, "selected": false, "text": "var select = document.getElementById('my_dropdown');\nfor(var i = 0; i < select.options.length; i++) {\n if(select.options[i].selected) {\n break;\n }\n}\nvar selectText = select.options[i].text;\n var selectText = $$('#my_dropdown option[selected]')[0].text;\n var selectText = $('#my_dropdown option[selected]').get(0).text;\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26848/" ]
191,757
<p>I thought this would be really simple, but it's presenting some difficulties. If I have</p> <pre><code>std::string name = &quot;John&quot;; int age = 21; </code></pre> <p>How do I combine them to get a single string <code>&quot;John21&quot;</code>?</p>
[ { "answer_id": 191775, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 2, "selected": false, "text": "itoa" }, { "answer_id": 191776, "author": "tloach", "author_id": 14092, "author_profile": "https://Stackoverflow.com/users/14092", "pm_score": 6, "selected": false, "text": "#include <iostream>\n#include <string>\n#include <sstream>\nusing namespace std;\nstring itos(int i) // convert int to string\n{\n stringstream s;\n s << i;\n return s.str();\n}\n" }, { "answer_id": 191780, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 6, "selected": false, "text": "#include <iostream>\n#include <sstream>\n\nstd::ostringstream o;\no << name << age;\nstd::cout << o.str();\n" }, { "answer_id": 191785, "author": "Jay Conrod", "author_id": 1891, "author_profile": "https://Stackoverflow.com/users/1891", "pm_score": 7, "selected": false, "text": "boost::lexical_cast<std::string>(age) std::stringstream ss;\nss << age;\nstd::cout << name << ss.str() << std::endl;\n sprintf snprintf char buffer[128];\nsnprintf(buffer, sizeof(buffer), \"%s%d\", name.c_str(), age);\nstd::cout << buffer << std::endl;\n itoa" }, { "answer_id": 191794, "author": "Seb Rose", "author_id": 12405, "author_profile": "https://Stackoverflow.com/users/12405", "pm_score": 4, "selected": false, "text": "#include <string>\n#include <sstream>\nusing namespace std;\nstring concatenate(std::string const& name, int i)\n{\n stringstream s;\n s << name << i;\n return s.str();\n}\n" }, { "answer_id": 192017, "author": "user12576", "author_id": 12576, "author_profile": "https://Stackoverflow.com/users/12576", "pm_score": 4, "selected": false, "text": "sprintf sprintf(outString,\"%s%d\",name,age);\n" }, { "answer_id": 192290, "author": "bsruth", "author_id": 23504, "author_profile": "https://Stackoverflow.com/users/23504", "pm_score": 3, "selected": false, "text": "CString nameAge = \"\";\nnameAge.Format(\"%s%d\", \"John\", 21);\n" }, { "answer_id": 192821, "author": "Zing-", "author_id": 8883, "author_profile": "https://Stackoverflow.com/users/8883", "pm_score": 4, "selected": false, "text": "#include <sstream>\n\ntemplate <class T>\ninline std::string to_string (const T& t)\n{\n std::stringstream ss;\n ss << t;\n return ss.str();\n}\n std::string szName = \"John\";\n int numAge = 23;\n szName += to_string<int>(numAge);\n cout << szName << endl;\n" }, { "answer_id": 193198, "author": "Pyry Jahkola", "author_id": 26981, "author_profile": "https://Stackoverflow.com/users/26981", "pm_score": 2, "selected": false, "text": "#include <sstream>\n#define MAKE_STRING(tokens) /****************/ \\\n static_cast<std::ostringstream&>( \\\n std::ostringstream().flush() << tokens \\\n ).str() \\\n /**/\n int main() {\n int i = 123;\n std::string message = MAKE_STRING(\"i = \" << i);\n std::cout << message << std::endl; // prints: \"i = 123\"\n}\n" }, { "answer_id": 900035, "author": "DannyT", "author_id": 106673, "author_profile": "https://Stackoverflow.com/users/106673", "pm_score": 10, "selected": false, "text": "std::string name = \"John\";\nint age = 21;\nstd::string result;\n\n// 1. with Boost\nresult = name + boost::lexical_cast<std::string>(age);\n\n// 2. with C++11\nresult = name + std::to_string(age);\n\n// 3. with FastFormat.Format\nfastformat::fmt(result, \"{0}{1}\", name, age);\n\n// 4. with FastFormat.Write\nfastformat::write(result, name, age);\n\n// 5. with the {fmt} library\nresult = fmt::format(\"{}{}\", name, age);\n\n// 6. with IOStreams\nstd::stringstream sstm;\nsstm << name << age;\nresult = sstm.str();\n\n// 7. with itoa\nchar numstr[21]; // enough to hold all numbers up to 64-bits\nresult = name + itoa(age, numstr, 10);\n\n// 8. with sprintf\nchar numstr[21]; // enough to hold all numbers up to 64-bits\nsprintf(numstr, \"%d\", age);\nresult = name + numstr;\n\n// 9. with STLSoft's integer_to_string\nchar numstr[21]; // enough to hold all numbers up to 64-bits\nresult = name + stlsoft::integer_to_string(numstr, 21, age);\n\n// 10. with STLSoft's winstl::int_to_string()\nresult = name + winstl::int_to_string(age);\n\n// 11. With Poco NumberFormatter\nresult = name + Poco::NumberFormatter().format(age);\n #include <string> #include <sstream>" }, { "answer_id": 3854165, "author": "mloskot", "author_id": 151641, "author_profile": "https://Stackoverflow.com/users/151641", "pm_score": 2, "selected": false, "text": "#include <boost/format.hpp>\n#include <string>\nint main()\n{\n using boost::format;\n\n int age = 22;\n std::string str_age = str(format(\"age is %1%\") % age);\n}\n #include <boost/spirit/include/karma.hpp>\n#include <iterator>\n#include <string>\nint main()\n{\n using namespace boost::spirit;\n\n int age = 22;\n std::string str_age(\"age is \");\n std::back_insert_iterator<std::string> sink(str_age);\n karma::generate(sink, int_, age);\n\n return 0;\n}\n" }, { "answer_id": 7011581, "author": "leinir", "author_id": 232739, "author_profile": "https://Stackoverflow.com/users/232739", "pm_score": 2, "selected": false, "text": "QString string = QString(\"Some string %1 with an int somewhere\").arg(someIntVariable);\nstring.append(someOtherIntVariable);\n" }, { "answer_id": 7995673, "author": "uckelman", "author_id": 181106, "author_profile": "https://Stackoverflow.com/users/181106", "pm_score": 3, "selected": false, "text": "+ operator+ template <typename L, typename R> std::string operator+(L left, R right) {\n std::ostringstream os;\n os << left << right;\n return os.str();\n}\n std::string foo(\"the answer is \");\nint i = 42;\nstd::string bar(foo + i); \nstd::cout << bar << std::endl;\n the answer is 42\n" }, { "answer_id": 11860411, "author": "Jeremy", "author_id": 849506, "author_profile": "https://Stackoverflow.com/users/849506", "pm_score": 8, "selected": false, "text": "std::to_string auto result = name + std::to_string( age );\n" }, { "answer_id": 16781028, "author": "David G", "author_id": 701092, "author_profile": "https://Stackoverflow.com/users/701092", "pm_score": 5, "selected": false, "text": "std::to_string std::string name = \"John\";\nint age = 21;\n\nname += std::to_string(age);\n\nstd::cout << name;\n John21\n" }, { "answer_id": 18489238, "author": "Reda Lahdili", "author_id": 2724738, "author_profile": "https://Stackoverflow.com/users/2724738", "pm_score": 1, "selected": false, "text": "char intToChar(int num)\n{\n if (num < 10 && num >= 0)\n {\n return num + 48;\n //48 is the number that we add to an integer number to have its character equivalent (see the unsigned ASCII table)\n }\n else\n {\n return '*';\n }\n}\n\nstring intToString(int num)\n{\n int digits = 0, process, single;\n string numString;\n process = num;\n\n // The following process the number of digits in num\n while (process != 0)\n {\n single = process % 10; // 'single' now holds the rightmost portion of the int\n process = (process - single)/10;\n // Take out the rightmost number of the int (it's a zero in this portion of the int), then divide it by 10\n // The above combination eliminates the rightmost portion of the int\n digits ++;\n }\n\n process = num;\n\n // Fill the numString with '*' times digits\n for (int i = 0; i < digits; i++)\n {\n numString += '*';\n }\n\n\n for (int i = digits-1; i >= 0; i--)\n {\n single = process % 10;\n numString[i] = intToChar ( single);\n process = (process - single) / 10;\n }\n\n return numString;\n}\n" }, { "answer_id": 20194939, "author": "David G", "author_id": 701092, "author_profile": "https://Stackoverflow.com/users/701092", "pm_score": 2, "selected": false, "text": "#include <iostream>\n#include <locale>\n#include <string>\n\ntemplate <class Facet>\nstruct erasable_facet : Facet\n{\n erasable_facet() : Facet(1) { }\n ~erasable_facet() { }\n};\n\nvoid append_int(std::string& s, int n)\n{\n erasable_facet<std::num_put<char,\n std::back_insert_iterator<std::string>>> facet;\n std::ios str(nullptr);\n\n facet.put(std::back_inserter(s), str,\n str.fill(), static_cast<unsigned long>(n));\n}\n\nint main()\n{\n std::string str = \"ID: \";\n int id = 123;\n\n append_int(str, id);\n\n std::cout << str; // ID: 123\n}\n" }, { "answer_id": 27594181, "author": "Kevin", "author_id": 4383443, "author_profile": "https://Stackoverflow.com/users/4383443", "pm_score": 5, "selected": false, "text": "string s = name + std::to_string(age);\n" }, { "answer_id": 39754848, "author": "Sukhbir", "author_id": 5036543, "author_profile": "https://Stackoverflow.com/users/5036543", "pm_score": 2, "selected": false, "text": "string name = \"John\";\nint age = 5;\nchar temp = 5 + '0';\nname = name + temp;\ncout << name << endl;\n\nOutput: John5\n" }, { "answer_id": 50089264, "author": "vitaut", "author_id": 471164, "author_profile": "https://Stackoverflow.com/users/471164", "pm_score": 3, "selected": false, "text": "auto result = std::format(\"{}{}\", name, age);\n std::format auto result = fmt::format(\"{}{}\", name, age);\n std::format" }, { "answer_id": 51093935, "author": "lohith99", "author_id": 8638353, "author_profile": "https://Stackoverflow.com/users/8638353", "pm_score": 3, "selected": false, "text": "to_string(i) #include <string>\n#include <sstream>\n#include <bits/stdc++.h>\n#include <iostream>\nusing namespace std;\n\nint main() {\n string name = \"John\";\n int age = 21;\n\n string answer1 = \"\";\n // Method 1). string s1 = to_string(age).\n\n string s1=to_string(age); // Know the integer get converted into string\n // where as we know that concatenation can easily be done using '+' in C++\n\n answer1 = name + s1;\n\n cout << answer1 << endl;\n\n // Method 2). Using string streams\n\n ostringstream s2;\n\n s2 << age;\n\n string s3 = s2.str(); // The str() function will convert a number into a string\n\n string answer2 = \"\"; // For concatenation of strings.\n\n answer2 = name + s3;\n\n cout << answer2 << endl;\n\n return 0;\n}\n" }, { "answer_id": 51667112, "author": "Isma Rekathakusuma", "author_id": 8198089, "author_profile": "https://Stackoverflow.com/users/8198089", "pm_score": 2, "selected": false, "text": "#include <sstream>\n\nstd::ostringstream s;\ns << \"John \" << age;\nstd::string query(s.str());\n std::string query(\"John \" + std::to_string(age));\n #include <boost/lexical_cast.hpp>\n\nstd::string query(\"John \" + boost::lexical_cast<std::string>(age));\n" }, { "answer_id": 60929988, "author": "ant_dev", "author_id": 10728087, "author_profile": "https://Stackoverflow.com/users/10728087", "pm_score": 3, "selected": false, "text": "name += std::to_string(age);" }, { "answer_id": 67506608, "author": "PeterSom", "author_id": 779373, "author_profile": "https://Stackoverflow.com/users/779373", "pm_score": 1, "selected": false, "text": "auto make_string=[os=std::ostringstream{}](auto&& ...p) mutable \n{ \n (os << ... << std::forward<decltype(p)>(p) ); \n return std::move(os).str();\n};\n\nint main() {\nstd::cout << make_string(\"Hello world: \",4,2, \" is \", 42.0);\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23120/" ]
191,766
<p>When I get a java.io.InvalidClassException, it gives me the serialVersionUID that it wants, and the serialVersionUID that it got. Is there an easy way to tell which of my dozens of jars using the wrong serialVersionUID?</p> <p><strong>Update</strong>: I should mention that our intention is to update everything at the same time, but I'm trying to debug a problem in our build and deploy process.</p>
[ { "answer_id": 191822, "author": "entzik", "author_id": 12297, "author_profile": "https://Stackoverflow.com/users/12297", "pm_score": 2, "selected": false, "text": "java.io.ObjectStreamClass.getSerialVersionUID()" }, { "answer_id": 353985, "author": "user44722", "author_id": 44722, "author_profile": "https://Stackoverflow.com/users/44722", "pm_score": 2, "selected": false, "text": "f=/System/Library/Frameworks/JavaVM.framework/Versions/1.5/Classes/\nserialver -J-Xbootclasspath:.:$f/dt.jar:$f/classes.jar:$f/ui.jar javax.xml.namespace.QName\n javap -verbose -bootclasspath . javax.xml.namespace.QName | sed -n -e '/static.*serialVersionUID/{N;p;}'\n" }, { "answer_id": 26023514, "author": "KC Baltz", "author_id": 9910, "author_profile": "https://Stackoverflow.com/users/9910", "pm_score": 2, "selected": false, "text": "package jar;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.ObjectStreamClass;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.net.URLClassLoader;\nimport java.util.ArrayList;\nimport java.util.Enumeration;\nimport java.util.HashSet;\nimport java.util.jar.JarEntry;\nimport java.util.jar.JarFile;\n\n\n/**\n * Searches all the jars in a given directory for a class with the given UID.\n * Additional directories can be specified to support with loading the jars. \n * For example, you might want to load the lib dir from your app server to get\n * the Servlet API, etc. \n */\npublic class JarUidSearch\n{\n public static void main(String args[])\n throws IOException, ClassNotFoundException\n {\n if( args.length < 2)\n {\n System.err.println(\"Usage: <UID to search for> <directory with jars to search> [additional directories with jars]\");\n System.exit(-1);\n }\n\n long targetUID = Long.parseLong(args[0]);\n\n ArrayList<URL> urls = new ArrayList<URL>();\n\n File libDir = new File(args[1]);\n\n for (int i = 1; i < args.length; i++)\n {\n gatherJars(urls, new File(args[i]));\n }\n\n File[] files = libDir.listFiles();\n\n for (File file : files)\n {\n try\n {\n checkJar(targetUID, urls, file);\n }\n catch(Throwable t)\n {\n System.err.println(\"checkJar for \" + file + \" threw: \" + t);\n t.printStackTrace();\n } \n }\n }\n\n /**\n * \n * @param urls\n * @param libDir\n * @throws MalformedURLException\n */\n public static void gatherJars(ArrayList<URL> urls, File libDir)\n throws MalformedURLException\n {\n File[] files = libDir.listFiles();\n\n for (File file : files)\n {\n urls.add(file.toURL());\n }\n }\n\n /**\n * \n * @param urls\n * @param file\n * @throws IOException\n * @throws ClassNotFoundException\n */\n public static void checkJar(long targetUID, ArrayList<URL> urls, File file)\n throws IOException, ClassNotFoundException\n {\n System.out.println(\"Checking: \" + file);\n JarFile jarFile = new JarFile(file);\n Enumeration allEntries = jarFile.entries();\n while (allEntries.hasMoreElements())\n {\n JarEntry entry = (JarEntry) allEntries.nextElement();\n String name = entry.getName();\n\n if (!name.endsWith(\".class\"))\n {\n // System.out.println(\"Skipping: \" + name);\n continue;\n }\n\n try\n {\n URLClassLoader loader = URLClassLoader.newInstance((URL[]) urls.toArray(new URL[0]));\n String className = name.substring(0,\n name.length() - \".class\".length()).replaceAll(\"/\", \".\");\n Class<?> clazz = loader.loadClass(className);\n ObjectStreamClass lookup = ObjectStreamClass.lookup(clazz);\n\n if (lookup != null)\n {\n long uid = lookup.getSerialVersionUID();\n\n if (targetUID == uid)\n {\n System.out.println(file + \" has class: \" + clazz);\n }\n }\n }\n catch (Throwable e)\n {\n System.err.println(\"entry \" + name + \" caused Exception: \" + e);\n }\n }\n }\n}\n" }, { "answer_id": 67173493, "author": "Piotr", "author_id": 15531854, "author_profile": "https://Stackoverflow.com/users/15531854", "pm_score": 0, "selected": false, "text": "find . -type f -name \"*.jar\" -exec sh -c 'javap -verbose -p -constants -cp {} com.myCompany.myClass | grep serialVersionUID' \\;\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3333/" ]
191,787
<p>I want to find a sql command or something that can do this where I have a table named tblFoo and I want to name it tblFooBar. However, I want the primary key to also be change, for example, currently it is:</p> <pre><code>CONSTRAINT [PK_tblFoo] PRIMARY KEY CLUSTERED </code></pre> <p>And I want a name change to change it to:</p> <pre><code>CONSTRAINT [PK_tblFooBar] PRIMARY KEY CLUSTERED </code></pre> <p>Then, recursively go through and cascade this change on all tables that have a foreigh key relationship, eg. from this:</p> <pre><code>CHECK ADD CONSTRAINT [FK_tblContent_tblFoo] FOREIGN KEY([fooID]) </code></pre> <p>To this:</p> <pre><code> CHECK ADD CONSTRAINT [FK_tblContent_tblFooBar] FOREIGN KEY([fooID]) </code></pre> <p>Naturally, I am trying not to go through and do this all manually because a) it is an error prone process, and b)it doesn't scale.</p>
[ { "answer_id": 191888, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 4, "selected": true, "text": "DECLARE\n @old_name VARCHAR(100),\n @new_name VARCHAR(100)\n\nSET @old_name = 'tblFoo'\nSET @new_name = 'tblFooBar'\n\nSELECT\n 'EXEC sp_rename ''' + name + ''', ''' + REPLACE(name, @old_name, @new_name) + ''''\nFROM dbo.sysobjects\nWHERE name LIKE '%' + @old_name + '%'\n" }, { "answer_id": 8551632, "author": "Srinidhi", "author_id": 1068914, "author_profile": "https://Stackoverflow.com/users/1068914", "pm_score": 3, "selected": false, "text": "declare\n @old nvarchar(100),\n @new nvarchar(100)\n\nset @old = 'OldName'\nset @new = 'NewName'\n\nselect 'EXEC sp_rename ''' + name + ''', ''' + \n REPLACE(name, @old, @new) + ''''\n from sys.objects \n where name like '%' + @old + '%'\nunion -- index renames\nselect 'EXEC sp_rename ''' + (sys.objects.name + '.' + sys.indexes.name) + ''', ''' +\n REPLACE(sys.indexes.name, @old, @new) + ''', ''INDEX'''\n from sys.objects \n left join sys.indexes on sys.objects.object_id = sys.indexes.object_id\n where sys.indexes.name like '%' + @old + '%'\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7952/" ]
191,788
<p>In my c# app, I've got a list that I navigate with an Enumerator. It works great for moving forward through the list, but the Enumerator class doesn't have a MoveBack method. </p> <p>Is there different class that has a MoveBack method, or do I need to write my own?</p>
[ { "answer_id": 384510, "author": "Hosam Aly", "author_id": 41283, "author_profile": "https://Stackoverflow.com/users/41283", "pm_score": 0, "selected": false, "text": "IEnumerator<int> e1 = yourListOfInt.GetEnumerator();\nIEnumerator<int> e2 = e1;\nfor (int i = 0; i < 3; ++i) e2.MoveNext();\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26339/" ]
191,791
<p>I am hoping to find a way to do this in vb.net: </p> <p>Say you have function call getPaint(Color). You want the call to be limited to the parameter values of (red,green,yellow). When they enter that parameter, the user is provided the available options, like how a boolean parameter functions.</p> <p>Any ideas? </p>
[ { "answer_id": 191811, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 2, "selected": false, "text": "Enum Color\n Red = 1\n Green = 2\n Yellow = 3\nEnd Enum\n getPaint(Color" }, { "answer_id": 191832, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 3, "selected": true, "text": "List<Color> allow = new List<Color> { Color.Red, Color.Green, Color.Yellow };\nif (!allow.Contains(color))\n{\n throw new ArguementException(\"Invalid Color\");\n}\n Dim allow As New List(Of Color)()\nallow.Add(Color.Red)\nallow.Add(Color.Green)\nallow.Add(Color.Yellow)\nIf Not allow.Contains(color) Then\nThrow New ArguementException(\"Invalid Color\")\nEnd If\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44449/" ]
191,808
<p>I'm currently looking at ways to allow people to select multiple files at once to batch upload images. I'm evaluating these options for my ASP.NET web app:</p> <ul> <li><a href="http://developer.yahoo.com/yui/uploader/" rel="nofollow noreferrer">YUI Uploader</a></li> <li><a href="http://www.codeplex.com/FlajaxianFileUpload" rel="nofollow noreferrer">Flajaxian</a></li> <li><a href="http://swfupload.org/" rel="nofollow noreferrer">SWFUpload</a></li> <li><a href="http://www.sitepen.com/blog/2008/09/02/the-dojo-toolkit-multi-file-uploader/" rel="nofollow noreferrer">Dojo Toolkit Multi file uploader</a></li> </ul> <p>I'm leaning toward YUI because the documentation is clear and I basically already wrote the file uploaders and thumbnailers which Flajaxian provides, the javascript seems more compact too. I can't even begin evaluating Dojo because it's unclear to me how to get the parts that would integrate with .NET out of the PHP examples.</p> <p>Has anyone had really good or really bad experiences with any of these?</p>
[ { "answer_id": 1368939, "author": "dlamblin", "author_id": 459, "author_profile": "https://Stackoverflow.com/users/459", "pm_score": 2, "selected": true, "text": "flickr flickr flickr" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/459/" ]
191,812
<p>How can I create a custom property for my .Net assembly which would then be visible under the Details tab in Windows explorer?</p> <p>Something to sit parallel with "File Description", "Type", "Product Version"... etc</p> <p>Update: To quote my comment to Lars ... "Whilst I would have liked to do this from within Visual studio, that is certainly not my priority. Actually I hope to integrate any solution into an existing nant build process. So affecting the assemblies post compile is entirely acceptable. Have you ever heard of such a tool?"</p> <p>Further Update: I'm not sure if what I'm talking about is an attribute or not, to clarify a little what I would like to creat in an entry in the following property page...</p> <p><img src="https://i.stack.imgur.com/GgG90.png" alt="alt text" title="Nunit Properties"></p>
[ { "answer_id": 191996, "author": "KyleLanser", "author_id": 12923, "author_profile": "https://Stackoverflow.com/users/12923", "pm_score": 2, "selected": false, "text": "[assembly: AssemblyDescription(\"One Line of Content Here\")]\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11356/" ]
191,817
<p>I'm roughing a layout together and doing some browser testing. Never came across this issue before, check out the contact form in the footer of this page</p> <p><a href="http://staging.terrilynn.com/fundraising/" rel="nofollow noreferrer"><a href="http://staging.terrilynn.com/fundraising/" rel="nofollow noreferrer">http://staging.terrilynn.com/fundraising/</a></a></p> <p>There is a div with a width of 298px floated to the right that comes first in the source order. It is followed by several other divs, each with their child form elements floated left.</p> <p>The div's that should appear to the left of right-floated message div are disappearing.</p> <p>Page displays correctly in firefox. Any help would be appreciated.</p> <pre><code>&lt;div id='footer-contact-form'&gt; &lt;h1&gt;Request Information &lt;span class='note'&gt;(all fields required)&lt;/span&gt;&lt;/h1&gt; &lt;form class="monkForm" method="post" action="http://my.ekklesia360.com/FormBuilder/handleSubmit.php" id="footer-info-request"&gt; &lt;fieldset&gt; &lt;legend&gt;Footer Info Request&lt;/legend&gt; &lt;div class="textarea required" id="w2376"&gt; &lt;p class="data"&gt; &lt;label for="area_2376"&gt;Message&lt;/label&gt; &lt;textarea id="area_2376" name="e_2376" rows="5" cols="20"&gt;&lt;/textarea&gt; &lt;/p&gt; &lt;/div&gt; &lt;div class="text required" id="w2377"&gt; &lt;p class="data"&gt; &lt;label for="text_2377"&gt;Name&lt;/label&gt; &lt;input id="text_2377" type="text" name="e_2377" value="" /&gt; &lt;/p&gt; &lt;/div&gt; &lt;div class="text required" id="w2378"&gt; &lt;p class="data"&gt; &lt;label for="text_2378"&gt;Phone&lt;/label&gt; &lt;input id="text_2378" type="text" name="e_2378" value="" /&gt; &lt;/p&gt;&lt;/div&gt; &lt;div class="text" id="w2379"&gt; &lt;p class="data"&gt; &lt;label for="text_2379"&gt;Email&lt;/label&gt; &lt;input id="text_2379" type="text" name="e_2379" value="" /&gt; &lt;/p&gt; &lt;/div&gt; &lt;p id="formsubmit"&gt;&lt;input type="submit" name="submit" value="Send" /&gt;&lt;/p&gt; &lt;input type="hidden" name="token" value="8143f99c1d01b4d1207dbe7860e5586d" /&gt; &lt;input type="hidden" name="SITEID" value="2185" /&gt; &lt;input type="hidden" name="cpBID" value="367780" /&gt; &lt;input type="hidden" name="formslug" value="footer-info-request" /&gt; &lt;input type="hidden" name="CMSCODE" value="EKK" /&gt; &lt;input type="hidden" name="fkey" value="" /&gt; &lt;/fieldset&gt; &lt;/form&gt; &lt;/div&gt;&lt;!-- #footer-contact-form --&gt; </code></pre>
[ { "answer_id": 191878, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "<p>" }, { "answer_id": 192076, "author": "matte", "author_id": 25768, "author_profile": "https://Stackoverflow.com/users/25768", "pm_score": 2, "selected": true, "text": "#footer-contact-form div {\nmargin:0 300px 10px 0;\noverflow:hidden;\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26858/" ]
191,826
<p>I'm actually developing a Web Service in Java using Axis 2. I designed my service as a POJO (Plain Old Java Object) with public method throwing exceptions :</p> <pre><code>public class MyService { public Object myMethod() throws MyException { [...] } } </code></pre> <p>I then generated the WSDL using Axis2 ant task. With the WSDL I generate a client stub to test my service. The generated code contains a "MyExceptionException" and the "myMethod" in the stub declare to throw this :</p> <pre><code>public class MyServiceStub extends org.apache.axis2.client.Stub { [...] public MyServiceStub.MyMethodResponse myMethod(MyServiceStub.MyMethod myMethod) throws java.rmi.RemoteException, MyExceptionException0 { [...] } [...] } </code></pre> <p>But when calling the method surrounded by a catch, the "MyExceptionException" is never transmitted by the server which transmit an AxisFault instead (subclass of RemoteException).</p> <p>I assume the problem is server-side but don't find where. The service is deployed as an aar file in the axis2 webapp on a tomcat 5.5 server. The services.xml looks like this :</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;service name="MyService" scope="application"&gt; &lt;description&gt;&lt;/description&gt; &lt;messageReceivers&gt; &lt;messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-only" class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"/&gt; &lt;messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out" class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/&gt; &lt;/messageReceivers&gt; &lt;parameter name="ServiceClass"&gt;MyService&lt;/parameter&gt; &lt;parameter name="ServiceTCCL"&gt;composite&lt;/parameter&gt; &lt;/service&gt; </code></pre> <p>If the behavior is normal then I'll drop the use of Exceptions (which is not vital to my project) but I'm circumspect why Java2WSDL generate custom &lt;wsdl:fault&gt; in operation input &amp; output declaration and WSDL2Java generate an Exception class (and declare to throw it in the stub method) if this is not usable...</p>
[ { "answer_id": 2919955, "author": "Russell", "author_id": 351795, "author_profile": "https://Stackoverflow.com/users/351795", "pm_score": 1, "selected": false, "text": " MyFaultException ex = new MyFaultException(\"My Exception Message\");\n MyFault fault = new MyFault();\n fault.setMyFault(\"My Fault Message\");\n ex.setFaultMessage(fault);\n throw ex; \n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26859/" ]
191,842
<p>If I have a native C++ windows program (i.e. the entry point is WinMain) how do I view output from console functions like std::cout?</p>
[ { "answer_id": 191880, "author": "luke", "author_id": 16434, "author_profile": "https://Stackoverflow.com/users/16434", "pm_score": 5, "selected": false, "text": "#include <windows.h>\n#include <stdio.h>\n#include <fcntl.h>\n#include <io.h>\n#include <iostream>\n#include <fstream>\n#ifndef _USE_OLD_IOSTREAMS\nusing namespace std;\n#endif\n// maximum mumber of lines the output console should have\nstatic const WORD MAX_CONSOLE_LINES = 500;\n#ifdef _DEBUG\nvoid RedirectIOToConsole()\n{\n int hConHandle;\n long lStdHandle;\n CONSOLE_SCREEN_BUFFER_INFO coninfo;\n FILE *fp;\n\n // allocate a console for this app\n AllocConsole();\n\n // set the screen buffer to be big enough to let us scroll text\n GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo);\n coninfo.dwSize.Y = MAX_CONSOLE_LINES;\n SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize);\n\n // redirect unbuffered STDOUT to the console\n lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);\n hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);\n fp = _fdopen( hConHandle, \"w\" );\n *stdout = *fp;\n setvbuf( stdout, NULL, _IONBF, 0 );\n\n // redirect unbuffered STDIN to the console\n lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);\n hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);\n fp = _fdopen( hConHandle, \"r\" );\n *stdin = *fp;\n setvbuf( stdin, NULL, _IONBF, 0 );\n\n // redirect unbuffered STDERR to the console\n lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);\n hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);\n fp = _fdopen( hConHandle, \"w\" );\n *stderr = *fp;\n setvbuf( stderr, NULL, _IONBF, 0 );\n\n // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog\n // point to console as well\n ios::sync_with_stdio();\n}\n\n#endif\n//End of File\n #ifndef __GUICON_H__\n#define __GUICON_H__\n#ifdef _DEBUG\n\nvoid RedirectIOToConsole();\n\n#endif\n#endif\n\n// End of File\n #include <windows.h>\n#include <iostream>\n#include <fstream>\n#include <conio.h>\n#include <stdio.h>\n#ifndef _USE_OLD_OSTREAMS\nusing namespace std;\n#endif\n#include \"guicon.h\"\n\n\n#include <crtdbg.h>\n\nint APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)\n{\n #ifdef _DEBUG\n RedirectIOToConsole();\n #endif\n int iVar;\n\n // test stdio\n fprintf(stdout, \"Test output to stdout\\n\");\n fprintf(stderr, \"Test output to stderr\\n\");\n fprintf(stdout, \"Enter an integer to test stdin: \");\n scanf(\"%d\", &iVar);\n printf(\"You entered %d\\n\", iVar);\n\n //test iostreams\n cout << \"Test output to cout\" << endl;\n cerr << \"Test output to cerr\" << endl;\n clog << \"Test output to clog\" << endl;\n cout << \"Enter an integer to test cin: \";\n cin >> iVar;\n cout << \"You entered \" << iVar << endl;\n #ifndef _USE_OLD_IOSTREAMS\n\n // test wide iostreams\n wcout << L\"Test output to wcout\" << endl;\n wcerr << L\"Test output to wcerr\" << endl;\n wclog << L\"Test output to wclog\" << endl;\n wcout << L\"Enter an integer to test wcin: \";\n wcin >> iVar;\n wcout << L\"You entered \" << iVar << endl;\n #endif\n\n // test CrtDbg output\n _CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE );\n _CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDERR );\n _CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE );\n _CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDERR);\n _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );\n _CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDERR);\n _RPT0(_CRT_WARN, \"This is testing _CRT_WARN output\\n\");\n _RPT0(_CRT_ERROR, \"This is testing _CRT_ERROR output\\n\");\n _ASSERT( 0 && \"testing _ASSERT\" );\n _ASSERTE( 0 && \"testing _ASSERTE\" );\n Sleep(2000);\n return 0;\n}\n\n//End of File\n" }, { "answer_id": 191912, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 4, "selected": false, "text": "#include <iostream>\n#include <fstream>\n\nint main ()\n{\n std::ofstream file;\n file.open (\"cout.txt\");\n std::streambuf* sbuf = std::cout.rdbuf();\n std::cout.rdbuf(file.rdbuf());\n //cout is now pointing to a file\n return 0;\n}\n" }, { "answer_id": 433333, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": " HANDLE hRead ; // ConsoleStdInput\n HANDLE hWrite; // ConsoleStdOutput and ConsoleStdError\n\n STARTUPINFO stiConsole;\n SECURITY_ATTRIBUTES segConsole;\n PROCESS_INFORMATION priConsole;\n\n segConsole.nLength = sizeof(segConsole);\n segConsole.lpSecurityDescriptor = NULL;\n segConsole.bInheritHandle = TRUE;\n\nif(CreatePipe(&hRead,&hWrite,&segConsole,0) )\n{\n\n FillMemory(&stiConsole,sizeof(stiConsole),0);\n stiConsole.cb = sizeof(stiConsole);\nGetStartupInfo(&stiConsole);\nstiConsole.hStdOutput = hWrite;\nstiConsole.hStdError = hWrite;\nstiConsole.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;\nstiConsole.wShowWindow = SW_HIDE; // execute hide \n\n if(CreateProcess(NULL, \"c:\\\\teste.exe\",NULL,NULL,TRUE,NULL,\n NULL,NULL,&stiConsole,&priConsole) == TRUE)\n {\n //readfile and/or writefile\n} \n" }, { "answer_id": 45439182, "author": "Florian Winter", "author_id": 2279059, "author_profile": "https://Stackoverflow.com/users/2279059", "pm_score": 3, "selected": false, "text": "myprogram.exe > file.txt\nmyprogram.exe | anotherprogram.exe\n WinMain" }, { "answer_id": 46050762, "author": "Sev", "author_id": 1513612, "author_profile": "https://Stackoverflow.com/users/1513612", "pm_score": 3, "selected": false, "text": "void RedirectIOToConsole() {\n\n //Create a console for this application\n AllocConsole();\n\n // Get STDOUT handle\n HANDLE ConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);\n int SystemOutput = _open_osfhandle(intptr_t(ConsoleOutput), _O_TEXT);\n FILE *COutputHandle = _fdopen(SystemOutput, \"w\");\n\n // Get STDERR handle\n HANDLE ConsoleError = GetStdHandle(STD_ERROR_HANDLE);\n int SystemError = _open_osfhandle(intptr_t(ConsoleError), _O_TEXT);\n FILE *CErrorHandle = _fdopen(SystemError, \"w\");\n\n // Get STDIN handle\n HANDLE ConsoleInput = GetStdHandle(STD_INPUT_HANDLE);\n int SystemInput = _open_osfhandle(intptr_t(ConsoleInput), _O_TEXT);\n FILE *CInputHandle = _fdopen(SystemInput, \"r\");\n\n //make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog point to console as well\n ios::sync_with_stdio(true);\n\n // Redirect the CRT standard input, output, and error handles to the console\n freopen_s(&CInputHandle, \"CONIN$\", \"r\", stdin);\n freopen_s(&COutputHandle, \"CONOUT$\", \"w\", stdout);\n freopen_s(&CErrorHandle, \"CONOUT$\", \"w\", stderr);\n\n //Clear the error state for each of the C++ standard stream objects. We need to do this, as\n //attempts to access the standard streams before they refer to a valid target will cause the\n //iostream objects to enter an error state. In versions of Visual Studio after 2005, this seems\n //to always occur during startup regardless of whether anything has been read from or written to\n //the console or not.\n std::wcout.clear();\n std::cout.clear();\n std::wcerr.clear();\n std::cerr.clear();\n std::wcin.clear();\n std::cin.clear();\n\n}\n" }, { "answer_id": 52717331, "author": "John Blackburn", "author_id": 8966081, "author_profile": "https://Stackoverflow.com/users/8966081", "pm_score": 3, "selected": false, "text": "int main()\n{\n return WinMain(GetModuleHandle(NULL), NULL, GetCommandLineA(), SW_SHOWNORMAL);\n}\n cl /nologo /c /EHsc myprog.c\nlink /nologo /out:myprog.exe /subsystem:console myprog.obj user32.lib gdi32.lib\n printf gcc -o myprog.exe myprog.c -luser32 -lgdi32\n -mwindows" }, { "answer_id": 55875595, "author": "Chris Olsen", "author_id": 2118271, "author_profile": "https://Stackoverflow.com/users/2118271", "pm_score": 5, "selected": false, "text": "FILE FILE* fp = nullptr;\nfreopen_s(&fp, \"CONIN$\", \"r\", stdin);\nfreopen_s(&fp, \"CONOUT$\", \"w\", stdout);\nfreopen_s(&fp, \"CONOUT$\", \"w\", stderr);\n bool RedirectConsoleIO()\n{\n bool result = true;\n FILE* fp;\n\n // Redirect STDIN if the console has an input handle\n if (GetStdHandle(STD_INPUT_HANDLE) != INVALID_HANDLE_VALUE)\n if (freopen_s(&fp, \"CONIN$\", \"r\", stdin) != 0)\n result = false;\n else\n setvbuf(stdin, NULL, _IONBF, 0);\n\n // Redirect STDOUT if the console has an output handle\n if (GetStdHandle(STD_OUTPUT_HANDLE) != INVALID_HANDLE_VALUE)\n if (freopen_s(&fp, \"CONOUT$\", \"w\", stdout) != 0)\n result = false;\n else\n setvbuf(stdout, NULL, _IONBF, 0);\n\n // Redirect STDERR if the console has an error handle\n if (GetStdHandle(STD_ERROR_HANDLE) != INVALID_HANDLE_VALUE)\n if (freopen_s(&fp, \"CONOUT$\", \"w\", stderr) != 0)\n result = false;\n else\n setvbuf(stderr, NULL, _IONBF, 0);\n\n // Make C++ standard streams point to console as well.\n ios::sync_with_stdio(true);\n\n // Clear the error state for each of the C++ standard streams.\n std::wcout.clear();\n std::cout.clear();\n std::wcerr.clear();\n std::cerr.clear();\n std::wcin.clear();\n std::cin.clear();\n\n return result;\n}\n bool ReleaseConsole()\n{\n bool result = true;\n FILE* fp;\n\n // Just to be safe, redirect standard IO to NUL before releasing.\n\n // Redirect STDIN to NUL\n if (freopen_s(&fp, \"NUL:\", \"r\", stdin) != 0)\n result = false;\n else\n setvbuf(stdin, NULL, _IONBF, 0);\n\n // Redirect STDOUT to NUL\n if (freopen_s(&fp, \"NUL:\", \"w\", stdout) != 0)\n result = false;\n else\n setvbuf(stdout, NULL, _IONBF, 0);\n\n // Redirect STDERR to NUL\n if (freopen_s(&fp, \"NUL:\", \"w\", stderr) != 0)\n result = false;\n else\n setvbuf(stderr, NULL, _IONBF, 0);\n\n // Detach from console\n if (!FreeConsole())\n result = false;\n\n return result;\n}\n void AdjustConsoleBuffer(int16_t minLength)\n{\n // Set the screen buffer to be big enough to scroll some text\n CONSOLE_SCREEN_BUFFER_INFO conInfo;\n GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &conInfo);\n if (conInfo.dwSize.Y < minLength)\n conInfo.dwSize.Y = minLength;\n SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), conInfo.dwSize);\n}\n bool CreateNewConsole(int16_t minLength)\n{\n bool result = false;\n\n // Release any current console and redirect IO to NUL\n ReleaseConsole();\n\n // Attempt to create new console\n if (AllocConsole())\n {\n AdjustConsoleBuffer(minLength);\n result = RedirectConsoleIO();\n }\n\n return result;\n}\n bool AttachParentConsole(int16_t minLength)\n{\n bool result = false;\n\n // Release any current console and redirect IO to NUL\n ReleaseConsole();\n\n // Attempt to attach to parent process's console\n if (AttachConsole(ATTACH_PARENT_PROCESS))\n {\n AdjustConsoleBuffer(minLength);\n result = RedirectConsoleIO();\n }\n\n return result;\n}\n /SUBSYSTEM:Windows int APIENTRY WinMain(\n HINSTANCE /*hInstance*/,\n HINSTANCE /*hPrevInstance*/,\n LPTSTR /*lpCmdLine*/,\n int /*cmdShow*/)\n{\n if (CreateNewConsole(1024))\n {\n int i;\n\n // test stdio\n fprintf(stdout, \"Test output to stdout\\n\");\n fprintf(stderr, \"Test output to stderr\\n\");\n fprintf(stdout, \"Enter an integer to test stdin: \");\n scanf(\"%d\", &i);\n printf(\"You entered %d\\n\", i);\n\n // test iostreams\n std::cout << \"Test output to std::cout\" << std::endl;\n std::cerr << \"Test output to std::cerr\" << std::endl;\n std::clog << \"Test output to std::clog\" << std::endl;\n std::cout << \"Enter an integer to test std::cin: \";\n std::cin >> i;\n std::cout << \"You entered \" << i << std::endl;\n\n std::cout << endl << \"Press any key to continue...\" << endl;\n _getch();\n\n ReleaseConsole();\n }\n\n return 0;\n};\n" }, { "answer_id": 56834698, "author": "Slion", "author_id": 3969362, "author_profile": "https://Stackoverflow.com/users/3969362", "pm_score": 2, "selected": false, "text": "CONSOLE WINDOWS main WinMain main WinMain int main()\n{\ncout << \"Output standard\\n\";\ncerr << \"Output error\\n\";\n\nreturn WinMain(GetModuleHandle(NULL), NULL, GetCommandLineA(), SW_SHOWNORMAL);\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23120/" ]
191,844
<p>I have a Java array such as: </p> <pre><code>String[] arr = new String[] {"123","doc","projectReport.doc"}; </code></pre> <p>In my opinion the natural way to access would be: </p> <pre><code> #set($att_id = $arr[0]) #set($att_type = $arr[1]) #set($att_name = $arr[2]) </code></pre> <p>But that it is not working. I have come with this workaround. But it a bit too much code for such an easy task. </p> <pre><code>#set($counter = 0) #foreach($el in $arr) #if($counter==0) #set($att_id = $el) #elseif($counter==1) #set($att_type = $el) #elseif($counter==2) #set($att_name = $el) #end #set($counter = $counter + 1) #end </code></pre> <p>Is there any other way?</p>
[ { "answer_id": 192018, "author": "Brian", "author_id": 8959, "author_profile": "https://Stackoverflow.com/users/8959", "pm_score": 3, "selected": false, "text": "List Arrays.asList(T... a) $list.get(int index) Array.get(Object array, int index)" }, { "answer_id": 505343, "author": "Nathan Bubna", "author_id": 8131, "author_profile": "https://Stackoverflow.com/users/8131", "pm_score": 5, "selected": false, "text": "$array $array.get($index) $array[$index] $list[$index] $map[$key]" }, { "answer_id": 1944487, "author": "Rajesh Chowdary", "author_id": 236613, "author_profile": "https://Stackoverflow.com/users/236613", "pm_score": 2, "selected": false, "text": "String[] arr = new String[] {\"123\", \"doc\", \"projectReport.doc\"}; \n #set($att_id = $arr[0]) \n #set($att_type = $arr[1]) \n #set($att_name = $arr[2]) \n $array.get(\"arr\", 1) $att_id = $arr[0]" }, { "answer_id": 27402057, "author": "Valentino Ciciarelli", "author_id": 4345827, "author_profile": "https://Stackoverflow.com/users/4345827", "pm_score": 0, "selected": false, "text": "#set ( $Page = $additionalParams.get('Page') )\n#set ( $Pages = [] )\n#if ( $Page != $null && $Page != \"\" )\n #foreach($i in $Page.split(\";\"))\n $Pages.add($i)\n #end\n#end\n" }, { "answer_id": 54374469, "author": "trndjc", "author_id": 9086770, "author_profile": "https://Stackoverflow.com/users/9086770", "pm_score": 2, "selected": false, "text": "$myarray.isEmpty()\n$myarray.size()\n$myarray.get(2)\n$myarray.set(1, 'test')\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
191,845
<p>Currently, I've got images (max. 6MB) stored as BLOB in a InnoDB table. As the size of the data is growing, the nightly backup is growing slower and slower hindering normal performance.</p> <p>So, the binary data needs to go to the file system. (pointers to the files will be kept in the DB.)</p> <p>The data has a tree like relation:</p> <pre><code>- main site - user_0 - album_0 - album_1 - album_n - user_1 - user_n etc... </code></pre> <p>Now I want the data to be distributed evenly trough the directory structure. How should I accomplish this?</p> <p>I guess I could try <code>MD5('userId, albumId, imageId');</code> and slice up the resulting string to get my directory path:</p> <pre> /var/imageStorage/f/347e/013b/c042/51cf/985f7ad0daa987d.jpeg </pre> <p>This would allow me to map the first character to a server and evenly distribute the directory structure over multiple servers.</p> <p>This would however <em>not</em> keep images organised per user, likely spreading the images for 1 album over multiple servers.</p> <p>My question is:<br> What is the best way to store the image data in the file system in a balanced way, while keeping user/album data together ?</p> <p>Am I thinking in the right direction? or is this the wrong way of doing things altogether?</p> <p><strong>Update:</strong><br> I will go for the <code>md5(user_id)</code> string slicing for the split up on highest level. And then put all user data in that same bucket. This will ensure an even distribution of data while keeping user data stored close together.</p> <pre> /var - imageStorage - f/347e/013b - f347e013bc04251cf985f7ad0daa987d - 0 - album1_10 - picture_1.jpeg - 1 - album1_1 - picture_2.jpeg - picture_3.jpeg - album1_11 - picture_n.jpeg - n - album1_n </pre> <p>I think I will use albumId splitted up from behind (I like that idea!) as to keep the number of albums per directory smaller (although it won't be necessary for most users). </p> <p>Thanks!</p>
[ { "answer_id": 191863, "author": "Node", "author_id": 7190, "author_profile": "https://Stackoverflow.com/users/7190", "pm_score": 6, "selected": true, "text": "UserID = 6435624 \nPath = /images/24/56/6435624\n" }, { "answer_id": 21829997, "author": "fustaki", "author_id": 1578918, "author_profile": "https://Stackoverflow.com/users/1578918", "pm_score": 2, "selected": false, "text": "17 >> 71 >> /71.jpg\n163 >> 0361 >> /03/61.jpg\n6978 >> 8796 >> /87/96.jpg \n1687941 >> 01497861 >> /01/49/78/61.jpg\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22674/" ]
191,855
<p>If I have added/removed/modified a large number of files in my local ClearCase view, how can I be certain that all the files have been added to source control?</p>
[ { "answer_id": 191857, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 3, "selected": false, "text": "cleartool ls -view_only -r" }, { "answer_id": 191964, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 4, "selected": true, "text": "cleartool lsprivate\n for /F \"usebackq delims= \" %i in (`cleartool ls -r -nxn ^| find \"hijacked\"`) do @echo %i\n cleartool ls -r -nxn | grep hijacked\n cleartool lscheckout -recur\n cleartool lsprivate –co\n" }, { "answer_id": 9827214, "author": "MoMo", "author_id": 176728, "author_profile": "https://Stackoverflow.com/users/176728", "pm_score": 3, "selected": false, "text": "cleartool ls -recurse -view_only | findstr /vi \".dll$ .pdb$ .suo$ .keep$ .unloaded$ \\\\bin$ \\\\bin\\\\ \\\\debug$ \\\\debug\\\\ \\\\release$ \\\\release\\\\ \\\\obj$ \\\\obj\\\\ ^cleartool$\" > c:\\ItemsNotInSource.txt\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9254/" ]
191,879
<p>Eg.</p> <pre><code>ConnectionDetails cd = new ConnectionDetails (); cd.ProviderName = "System.Data.OleDb"; cd.DataSource = "serverAddress"; cd.Catalog = "database"; cd.UserId = "userId"; cd.Password = "password"; string connectionString = cs.CreateConnectionString(); // Should return: // "Provider=SQLOLEDB;Data Source=serverAddress;Initial Catalog=database;User Id=userId;Password=password;" </code></pre> <p>I'd write my own class but I'm not sure how to retrieve a connection string provider property (SQLOLEDB in this example) programmatically from an invariant db provider name (System.Data.OleDb).</p> <p>Edit:</p> <p>You can do a</p> <pre><code>DbProviderFactories.GetFactory("System.Data.OleDB").CreateConnectionStringBuilder() </code></pre> <p>But the DBConnectionStringBuilder that is returned still doesn't know it's connection string provider property, even though in this case it the derived class has a "Provider" property.</p>
[ { "answer_id": 191932, "author": "harpo", "author_id": 4525, "author_profile": "https://Stackoverflow.com/users/4525", "pm_score": 2, "selected": false, "text": "DbConnectionStringBuilder csb = new DbConnectionStringBuilder();\ncsb[\"ProviderName\"] = \"System.Data.OleDb\";\ncsb[\"DataSource\"] = \"serverAddress\";\ncsb[\"Catalog\"] = \"database\";\ncsb[\"UserId\"] = \"userId\";\ncsb[\"Password\"] = \"password\";\n\nstring connectionString = csb.ConnectionString;\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9825/" ]
191,881
<p>I need to <a href="https://en.wikipedia.org/wiki/Serialization" rel="noreferrer">serialize</a> an object to <a href="https://www.json.org/" rel="noreferrer">JSON</a>. I'm using <a href="https://api.jquery.com/" rel="noreferrer">jQuery</a>. Is there a "standard" way to do this?</p> <p>My specific situation: I have an array defined as shown below:</p> <pre><code>var countries = new Array(); countries[0] = 'ga'; countries[1] = 'cd'; ... </code></pre> <p>and I need to turn this into a string to pass to <a href="https://www.w3schools.com/jquery/ajax_ajax.asp" rel="noreferrer"><code>$.ajax()</code></a> like this:</p> <pre><code>$.ajax({ type: "POST", url: "Concessions.aspx/GetConcessions", data: "{'countries':['ga','cd']}", ... </code></pre>
[ { "answer_id": 191911, "author": "Tahir Akhtar", "author_id": 18027, "author_profile": "https://Stackoverflow.com/users/18027", "pm_score": 6, "selected": false, "text": "$.toJSON(value) $.parseJSON(json_str, [safe])" }, { "answer_id": 912247, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 11, "selected": true, "text": "JSON.stringify var json_text = JSON.stringify(your_object, null, 2);\n JSON.parse var your_object = JSON.parse(json_text);\n JSON.stringify JSON.parse" }, { "answer_id": 1829139, "author": "Kain Haart", "author_id": 222448, "author_profile": "https://Stackoverflow.com/users/222448", "pm_score": 4, "selected": false, "text": ".toSource()" }, { "answer_id": 4577642, "author": "jamesmortensen", "author_id": 552792, "author_profile": "https://Stackoverflow.com/users/552792", "pm_score": 5, "selected": false, "text": "$.fn.serializeObject = function(){\n var o = {};\n var a = this.serializeArray();\n $.each(a, function() {\n if (o[this.name]) {\n if (!o[this.name].push) {\n o[this.name] = [o[this.name]];\n }\n o[this.name].push(this.value || '');\n } else {\n o[this.name] = this.value || '';\n }\n });\n return o;\n};\n" }, { "answer_id": 6208070, "author": "Jay Taylor", "author_id": 293064, "author_profile": "https://Stackoverflow.com/users/293064", "pm_score": 8, "selected": false, "text": "var myObj = {foo: \"bar\", \"baz\": \"wockaflockafliz\"};\n$.toJSON(myObj);\n\n// Result: {\"foo\":\"bar\",\"baz\":\"wockaflockafliz\"}\n" }, { "answer_id": 7227040, "author": "pestatije", "author_id": 917318, "author_profile": "https://Stackoverflow.com/users/917318", "pm_score": 7, "selected": false, "text": "JSON.stringify(countries); \n" }, { "answer_id": 24289943, "author": "Tim Burkhart", "author_id": 1442652, "author_profile": "https://Stackoverflow.com/users/1442652", "pm_score": 3, "selected": false, "text": "<input type=\"hidden\" name=\"People\" value=\"Joe\" />\n {\n \"People\" : \"Joe\"\n}\n {\n \"People\" : [ \"Joe\" ]\n}\n <input type=\"hidden\" name=\"People[]\" value=\"Joe\" />\n $.fn.serializeObject = function() {\nvar o = {};\nvar a = this.serializeArray();\n$.each(a, function() {\n if (this.name.substr(-2) == \"[]\"){\n this.name = this.name.substr(0, this.name.length - 2);\n o[this.name] = [];\n }\n\n if (o[this.name]) {\n if (!o[this.name].push) {\n o[this.name] = [o[this.name]];\n }\n o[this.name].push(this.value || '');\n } else {\n o[this.name] = this.value || '';\n }\n});\nreturn o;\n};\n" }, { "answer_id": 29574586, "author": "jherax", "author_id": 2247494, "author_profile": "https://Stackoverflow.com/users/2247494", "pm_score": 3, "selected": false, "text": "// This is a reference to JSON.stringify and provides a polyfill for old browsers.\n// stringify serializes an object, array or primitive value and return it as JSON.\njQuery.stringify = (function ($) {\n var _PRIMITIVE, _OPEN, _CLOSE;\n if (window.JSON && typeof JSON.stringify === \"function\")\n return JSON.stringify;\n\n _PRIMITIVE = /string|number|boolean|null/;\n\n _OPEN = {\n object: \"{\",\n array: \"[\"\n };\n\n _CLOSE = {\n object: \"}\",\n array: \"]\"\n };\n\n //actions to execute in each iteration\n function action(key, value) {\n var type = $.type(value),\n prop = \"\";\n\n //key is not an array index\n if (typeof key !== \"number\") {\n prop = '\"' + key + '\":';\n }\n if (type === \"string\") {\n prop += '\"' + value + '\"';\n } else if (_PRIMITIVE.test(type)) {\n prop += value;\n } else if (type === \"array\" || type === \"object\") {\n prop += toJson(value, type);\n } else return;\n this.push(prop);\n }\n\n //iterates over an object or array\n function each(obj, callback, thisArg) {\n for (var key in obj) {\n if (obj instanceof Array) key = +key;\n callback.call(thisArg, key, obj[key]);\n }\n }\n\n //generates the json\n function toJson(obj, type) {\n var items = [];\n each(obj, action, items);\n return _OPEN[type] + items.join(\",\") + _CLOSE[type];\n }\n\n //exported function that generates the json\n return function stringify(obj) {\n if (!arguments.length) return \"\";\n var type = $.type(obj);\n if (_PRIMITIVE.test(type))\n return (obj === null ? type : obj.toString());\n //obj is array or object\n return toJson(obj, type);\n }\n}(jQuery));\n var myObject = {\n \"0\": null,\n \"total-items\": 10,\n \"undefined-prop\": void(0),\n sorted: true,\n images: [\"bg-menu.png\", \"bg-body.jpg\", [1, 2]],\n position: { //nested object literal\n \"x\": 40,\n \"y\": 300,\n offset: [{ top: 23 }]\n },\n onChange: function() { return !0 },\n pattern: /^bg-.+\\.(?:png|jpe?g)$/i\n};\n\nvar json = jQuery.stringify(myObject);\nconsole.log(json);\n" }, { "answer_id": 31116841, "author": "Shrish Shrivastava", "author_id": 2581488, "author_profile": "https://Stackoverflow.com/users/2581488", "pm_score": 3, "selected": false, "text": "var JSON_VAR = JSON.stringify(OBJECT_NAME, null, 2); \n string Object var obj = JSON.parse(JSON_VAR);\n" }, { "answer_id": 36192956, "author": "bruce", "author_id": 4903050, "author_profile": "https://Stackoverflow.com/users/4903050", "pm_score": 4, "selected": false, "text": "JSON.stringify JSON.parse Json_PostData $.ajax $.ajax({\n url: post_http_site, \n type: \"POST\", \n data: JSON.parse(JSON.stringify(Json_PostData)), \n cache: false,\n error: function (xhr, ajaxOptions, thrownError) {\n alert(\" write json item, Ajax error! \" + xhr.status + \" error =\" + thrownError + \" xhr.responseText = \" + xhr.responseText ); \n },\n success: function (data) {\n alert(\"write json item, Ajax OK\");\n\n } \n});\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
191,883
<p>I want to be able to do the following:</p> <pre><code>$normal_array = array(); $array_of_arrayrefs = array( &amp;$normal_array ); // Here I want to access the $normal_array reference **as a reference**, // but that doesn't work obviously. How to do it? end( $array_of_arrayrefs )["one"] = 1; // choking on this one print $normal_array["one"]; // should output 1 </code></pre> <p>Regards</p> <p>/R</p>
[ { "answer_id": 191939, "author": "Joe Scylla", "author_id": 25771, "author_profile": "https://Stackoverflow.com/users/25771", "pm_score": -1, "selected": false, "text": "error_reporting display_error $normal_array = array();\n$array_of_arrayrefs = array( &$normal_array );\n// Here I want to access the $normal_array reference **as a reference**,\n// but that doesn't work obviously. How to do it?\n$array_of_arrayrefs[0][\"one\"] = 1;\n//end($array_of_arrayrefs )[\"one\"] = 1; // choking on this one\nprint $normal_array[\"one\"]; // should output 1\n" }, { "answer_id": 191947, "author": "Andrew Moore", "author_id": 26210, "author_profile": "https://Stackoverflow.com/users/26210", "pm_score": 3, "selected": true, "text": "end() $normal_array = array();\n$array_of_arrayrefs = array( &$normal_array );\n\n$refArray = &end_byref( $array_of_arrayrefs );\n$refArray[\"one\"] = 1;\n\nprint $normal_array[\"one\"]; // should output 1\n\nfunction &end_byref( &$array ) {\n $lastKey = end(array_keys($array));\n end($array);\n return $array[$lastKey];\n}\n" }, { "answer_id": 192004, "author": "rewbs", "author_id": 6095, "author_profile": "https://Stackoverflow.com/users/6095", "pm_score": 1, "selected": false, "text": "<?php\n$normal_array = array();\n$array_of_arrayrefs = array( \"blah\", &$normal_array );\n\nforeach ($array_of_arrayrefs as &$v);\n$v[\"one\"] = 1;\n\necho $normal_array[\"one\"]; //prints 1\n?>\n\n\n<?php\n$normal_array = array();\n$array_of_arrayrefs = array( \"blah\", &$normal_array );\n\n$lastIndex = @end(array_keys($array_of_arrayrefs)); //raises E_STRICT because end() expects referable.\n$array_of_arrayrefs[$lastIndex][\"one\"] = 1;\n\necho $normal_array[\"one\"]; //prints 1\n?>\n" }, { "answer_id": 430284, "author": "Preston", "author_id": 25213, "author_profile": "https://Stackoverflow.com/users/25213", "pm_score": 0, "selected": false, "text": "$normal_array = array();\n$array_of_arrayrefs = array( &$normal_array );\n\nend($array_of_arrayrefs);\n$array_of_arrayrefs[ key($array_of_arrayrefs) ][\"one\"] = 1;\n\nprint $normal_array[\"one\"];\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7891/" ]
191,894
<p>I have the following component </p> <pre><code>public class MyTimer : IMyTimer { public MyTimer(TimeSpan timespan){...} } </code></pre> <p>Where timespan should be provided by the property ISettings.MyTimerFrequency.</p> <p>How do I wire this up in windsor container xml? I thought I could do something like this:</p> <pre><code> &lt;component id="settings" service="MySample.ISettings, MySample" type="MySample.Settings, MySample" factoryId="settings_dao" factoryCreate="GetSettingsForInstance"&gt; &lt;parameters&gt;&lt;instance_id&gt;1&lt;/instance_id&gt;&lt;/parameters&gt; &lt;/component&gt; &lt;component id="my_timer_frequency" type="System.TimeSpan" factoryId="settings" factoryCreate="MyTimerFrequency" /&gt; &lt;component id="my_timer" service="MySample.IMyTimer, MySample" type="MySample.MyTimer, MySample"&gt; &lt;parameters&gt;&lt;timespan&gt;${my_timer_frequency}&lt;/timespan&gt;&lt;/parameters&gt; </code></pre> <p>but I am getting an error because MyTimerFrequency is a property when the factory facility expects a method.</p> <p>Is there a simple resolution here? Am I approaching the whole thing the wrong way?</p> <p><strong>EDIT:</strong> There is definitely a solution, see my answer below.</p>
[ { "answer_id": 197501, "author": "George Mauer", "author_id": 5056, "author_profile": "https://Stackoverflow.com/users/5056", "pm_score": 3, "selected": true, "text": "public class MyClass {\n public object Item {\n get;\n }\n public object get_Item() {return null;}\n}\n <component id=\"my_timer_frequency\"\n type=\"System.TimeSpan\"\n factoryId=\"settings\" factoryCreate=\"get_MyTimerFrequency\" />\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
191,897
<p>I have around 3500 flood control facilities that I would like to represent as a network to determine flow paths (essentially a directed graph). I'm currently using SqlServer and a CTE to recursively examine all the nodes and their upstream components and this works as long as the upstream path doesn't fork alot. However, some queries take exponentially longer than others even when they are not much farther physically down the path (i.e. two or three segments "downstream") because of the added upstream complexity; in some cases I've let it go over ten minutes before killing the query. I'm using a simple two-column table, one column being the facility itself and the other being the facility that is upstream from the one listed in the first column.</p> <p>I tried adding an index using the current facility to help speed things up but that made no difference. And, as for the possible connections in the graph, any nodes could have multiple upstream connections and could be connected to from multiple "downstream" nodes.</p> <p>It is certainly possible that there are cycles in the data but I have not yet figured out a good way to verify this (other than when the CTE query reported a maximum recursive count hit; those were easy to fix).</p> <p>So, my question is, am I storing this information wrong? Is there a better way other than a CTE to query the upstream points? </p>
[ { "answer_id": 191986, "author": "oz10", "author_id": 14069, "author_profile": "https://Stackoverflow.com/users/14069", "pm_score": 1, "selected": false, "text": "vertex1 vertex2 {edge_label1}+\n vertex1 vertex2\nvertex2 vertex1\n" }, { "answer_id": 192020, "author": "Cervo", "author_id": 16219, "author_profile": "https://Stackoverflow.com/users/16219", "pm_score": 3, "selected": true, "text": "IF @@ROWCOUNT = 0\n BREAK\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16623/" ]
191,923
<p>I have an XML file loaded into a DOM document, I wish to iterate through all 'foo' tags, getting values from every tag below it. I know I can get values via </p> <pre><code>$element = $dom-&gt;getElementsByTagName('foo')-&gt;item(0); foreach($element-&gt;childNodes as $node){ $data[$node-&gt;nodeName] = $node-&gt;nodeValue; } </code></pre> <p>However, what I'm trying to do, is from an XML like, </p> <pre><code>&lt;stuff&gt; &lt;foo&gt; &lt;bar&gt;&lt;/bar&gt; &lt;value/&gt; &lt;pub&gt;&lt;/pub&gt; &lt;/foo&gt; &lt;foo&gt; &lt;bar&gt;&lt;/bar&gt; &lt;pub&gt;&lt;/pub&gt; &lt;/foo&gt; &lt;foo&gt; &lt;bar&gt;&lt;/bar&gt; &lt;pub&gt;&lt;/pub&gt; &lt;/foo&gt; &lt;/stuff&gt; </code></pre> <p>iterate over every <em>foo</em> tag, and get specific <em>bar</em> or <em>pub</em>, and get values from there. Now, how do I iterate over <em>foo</em> so that I can still access specific child nodes by name?</p>
[ { "answer_id": 192015, "author": "roryf", "author_id": 270, "author_profile": "https://Stackoverflow.com/users/270", "pm_score": 7, "selected": true, "text": "$elements = $dom->getElementsByTagName('foo');\n$data = array();\nforeach($elements as $node){\n foreach($node->childNodes as $child) {\n $data[] = array($child->nodeName => $child->nodeValue);\n }\n}\n" }, { "answer_id": 192909, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 2, "selected": false, "text": "xpath_eval" }, { "answer_id": 353364, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "$data[][$node->nodeName] = $node->nodeValue;\n" }, { "answer_id": 34971104, "author": "Daniele Orlando", "author_id": 1750243, "author_profile": "https://Stackoverflow.com/users/1750243", "pm_score": -1, "selected": false, "text": "$data = [];\n\n$store_child = function($i, $fooChild) use (&$data) {\n $data[] = [ $fooChild->nodeName => $fooChild->nodeValue ];\n};\n\nfluidxml($dom)->query('//foo/*')->each($store_child);\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4224/" ]
191,926
<p>I have a database on ms sql 2000 that is being hit by hundreds of users at a time. There are intense reports using reporting services 2005 hitting the same database.</p> <p>When there are lots of reports running and people using the database concurrently we see blocking processes to the level that the system starts to give time out to any transaction made after some time in that situation.</p> <p>Is there a global way of minimize blocking so the transaction can continue to flow.</p>
[ { "answer_id": 192007, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 1, "selected": false, "text": "WITH(NOLOCK)" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
191,929
<p>If I were to use more than one, what order should I use modifier keywords such as:</p> <p><code>public</code>, <code>private</code>, <code>protected</code>, <code>virtual</code>, <code>abstract</code>, <code>override</code>, <code>new</code>, <code>static</code>, <code>internal</code>, <code>sealed</code>, and any others I'm forgetting.</p>
[ { "answer_id": 18270569, "author": "Jeppe Stig Nielsen", "author_id": 1336654, "author_profile": "https://Stackoverflow.com/users/1336654", "pm_score": 1, "selected": false, "text": "C B public class B\n{\n public void X()\n {\n }\n}\npublic class C : B\n{\n protected internal new static readonly DateTime X;\n}\n DateTime C 5! == 5*4*3*2*1 == 120 protected internal new" }, { "answer_id": 33237262, "author": "Wai Ha Lee", "author_id": 1364007, "author_profile": "https://Stackoverflow.com/users/1364007", "pm_score": 6, "selected": true, "text": "###############################\n# C# Code Style Rules #\n###############################\n\n# Modifier preferences\ncsharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion\n { public / private / protected / internal / protected internal / private protected } // access modifiers\nstatic\nextern\nnew\n{ virtual / abstract / override / sealed override } // inheritance modifiers\nreadonly\nunsafe\nvolatile\nasync\n { public / protected / internal / private / protected internal / private protected } // access modifiers\nnew\n{ abstract / virtual / override / sealed override } // inheritance modifiers\nstatic\nreadonly\nextern\nunsafe\nvolatile\nasync\n {solution}.dotsettings \"/Default/CodeStyle/CodeFormatting/CSharpFormat/MODIFIERS_ORDER/@EntryValue\"\n <s:String x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/MODIFIERS_ORDER/@EntryValue\">\n public protected internal private new abstract virtual sealed override static readonly extern unsafe volatile async\n</s:String>\n private protected dotsettings new static static new i i static static new public class clx\n{\n public int i = 1;\n}\n\npublic class cly : clx\n{\n public static int i = 2; // CS0108, use the new keyword\n // Use the following line instead:\n // public static new int i = 2;\n}\n static static new i static static new sealed <s:String x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/MODIFIERS_ORDER/@EntryValue\">\n public protected internal private static new abstract virtual override sealed readonly extern unsafe volatile async\n</s:String>\n static sealed new static static new new static static new (in 2015) (in 2018)\nnew static 203 427\nstatic new 10 990\n static new" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16260/" ]
191,940
<p>Is it possible to define a class in C# such that</p> <pre><code>class GenericCollection&lt;T&gt; : SomeBaseCollection&lt;T&gt; where T : Delegate </code></pre> <p>I couldn't for the life of me accomplish this last night in .NET 3.5. I tried using</p> <p><code>delegate, Delegate, Action&lt;T&gt; and Func&lt;T, T&gt;</code></p> <p>It seems to me that this should be allowable in some way. I'm trying to implement my own EventQueue.</p> <p>I ended up just doing this [primitive approximation mind you].</p> <pre><code>internal delegate void DWork(); class EventQueue { private Queue&lt;DWork&gt; eventq; } </code></pre> <p>But then I lose the ability to reuse the same definition for different types of functions.</p> <p>Thoughts?</p>
[ { "answer_id": 191949, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 7, "selected": true, "text": "static GenericCollection()\n{\n if (!typeof(T).IsSubclassOf(typeof(Delegate)))\n {\n throw new InvalidOperationException(typeof(T).Name + \" is not a delegate type\");\n }\n}\n" }, { "answer_id": 191994, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 4, "selected": false, "text": "error CS0702: Constraint cannot be special class 'System.Delegate'\n" }, { "answer_id": 192531, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": false, "text": "public class EventQueueTests\n{\n public void Test1()\n {\n Action myAction = () => Console.WriteLine(\"foo\");\n myAction += () => Console.WriteLine(\"bar\");\n\n myAction();\n //foo\n //bar\n }\n\n public void Test2()\n {\n Action<int> myAction = x => Console.WriteLine(\"foo {0}\", x);\n myAction += x => Console.WriteLine(\"bar {0}\", x);\n myAction(3);\n //foo 3\n //bar 3\n }\n\n public void Test3()\n {\n Func<int, int> myFunc = x => { Console.WriteLine(\"foo {0}\", x); return x + 2; };\n myFunc += x => { Console.WriteLine(\"bar {0}\", x); return x + 1; };\n int y = myFunc(3);\n Console.WriteLine(y);\n\n //foo 3\n //bar 3\n //4\n }\n\n public void Test4()\n {\n Func<int, int> myFunc = x => { Console.WriteLine(\"foo {0}\", x); return x + 2; };\n Func<int, int> myNextFunc = x => { x = myFunc(x); Console.WriteLine(\"bar {0}\", x); return x + 1; };\n int y = myNextFunc(3);\n Console.WriteLine(y);\n\n //foo 3\n //bar 5\n //6\n }\n\n}\n" }, { "answer_id": 2088271, "author": "Justin Bailey", "author_id": 169359, "author_profile": "https://Stackoverflow.com/users/169359", "pm_score": 2, "selected": false, "text": "Delegate Handler Delegate public void AddHandler<Handler>(Control c, string eventName, Handler d) {\n c.GetType().GetEvent(eventName).AddEventHandler(c, (Delegate) d);\n}\n convert Handler Delegate public void AddHandler<Handler>(Control c, string eventName, \n Func<Delegate, Handler> convert, Handler d) {\n c.GetType().GetEvent(eventName).AddEventHandler(c, convert(d));\n}\n KeyPress AddHandler<KeyEventHandler>(someControl, \n \"KeyPress\", \n (h) => (KeyEventHandler) h,\n SomeControl_KeyPress);\n SomeControl_KeyPress public void AddHandler<Handler>(Control c, string eventName, Handler d) { \n c.GetType().GetEvent(eventName).AddEventHandler(c, d as Delegate); \n} \n" }, { "answer_id": 10846397, "author": "Simon", "author_id": 53158, "author_profile": "https://Stackoverflow.com/users/53158", "pm_score": 3, "selected": false, "text": "public class Sample\n{\n public void MethodWithDelegateConstraint<[DelegateConstraint] T> ()\n { \n }\n public void MethodWithEnumConstraint<[EnumConstraint] T>()\n {\n }\n} \n public class Sample\n{\n public void MethodWithDelegateConstraint<T>() where T: Delegate\n {\n }\n\n public void MethodWithEnumConstraint<T>() where T: struct, Enum\n {\n }\n}\n" }, { "answer_id": 23728873, "author": "maxspan", "author_id": 2209468, "author_profile": "https://Stackoverflow.com/users/2209468", "pm_score": 2, "selected": false, "text": "System.Object System.ValueType" }, { "answer_id": 50291345, "author": "mshwf", "author_id": 6197785, "author_profile": "https://Stackoverflow.com/users/6197785", "pm_score": 4, "selected": false, "text": "Enum Delegate unmanaged void M<D, E, T>(D d, E e, T* t) where D : Delegate where E : Enum where T : unmanaged\n {\n\n }\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8945/" ]
191,950
<p>In my project I have a class that is inherited by many other classes. We'll call it ClassBase.</p> <pre><code>public class ClassInheritFromBase : ClassBase </code></pre> <p>When ClassBase is being inherited, <a href="http://en.wikipedia.org/wiki/ReSharper" rel="noreferrer">ReSharper</a> throws an "Ambiguous reference" warning on the ClassBase, and anything inside the new class that inherited from ClassBase does not have IntelliSense and gets warnings that it cannot find it.</p> <p>The project compiles and runs fine.</p> <p>If I change the namespace ClassBase is in and then change the inheriting classes, they find it fine and ReSharper has no problem, IntelliSense works ... until it is compiled. After the compile it goes back to having the ambiguous reference warnings and everything else.</p> <p>Has this been seen before and how can it be fixed? I saw an entry in JetBrains bug tracking for an issue just like this, but they closed it as unable to reproduce.</p>
[ { "answer_id": 22411256, "author": "HiredMind", "author_id": 79648, "author_profile": "https://Stackoverflow.com/users/79648", "pm_score": 0, "selected": false, "text": "Copy Local = false Copy Local = true" }, { "answer_id": 31254550, "author": "Evan", "author_id": 4343254, "author_profile": "https://Stackoverflow.com/users/4343254", "pm_score": 2, "selected": false, "text": "XXX.YYY.ZZZ.myassembly\nZZZ.myassembly\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1215/" ]
191,952
<p>If I have the following Linq code:</p> <pre><code>context.Table1s.InsertOnSubmit(t); context.Table1s.InsertOnSubmit(t2); context.Table1s.InsertOnSubmit(t3); context.SubmitChanges(); </code></pre> <p>And I get a database error due to the 2nd insert, Linq throws an exception that there was an error. But, is there a way to find out that it was the 2nd insert that had the problem and not the 1st or 3rd?</p> <p>To clarify, there are business reasons that I would expect the 2nd to fail (I am using a stored procedure to do the insert and am also doing some validation and raising an error if it fails). I want to be able to tell the user which one failed and why. I know this validation would be better done in the C# code and not in the database, but that is currently not an option.</p>
[ { "answer_id": 22411256, "author": "HiredMind", "author_id": 79648, "author_profile": "https://Stackoverflow.com/users/79648", "pm_score": 0, "selected": false, "text": "Copy Local = false Copy Local = true" }, { "answer_id": 31254550, "author": "Evan", "author_id": 4343254, "author_profile": "https://Stackoverflow.com/users/4343254", "pm_score": 2, "selected": false, "text": "XXX.YYY.ZZZ.myassembly\nZZZ.myassembly\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3291/" ]
191,955
<p>What is the correct way to do this? For example, how would I change a stored procedure with this signature:</p> <pre><code>CREATE PROCEDURE dbo.MyProcedure @Param BIT = NULL AS SELECT * FROM dbo.SomeTable T WHERE T.SomeColumn = @Param </code></pre> <p>So that giving @Param with a value of 1 or 0 performs the filter, but not specifying it or passing NULL performs no filtering?</p>
[ { "answer_id": 191971, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 4, "selected": true, "text": "CREATE PROCEDURE dbo.MyProcedure \n @Param BIT = NULL\nAS\n SELECT *\n FROM dbo.SomeTable T\n WHERE T.SomeColumn = @Param OR @Param IS NULL\n" }, { "answer_id": 192156, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 0, "selected": false, "text": "SELECT * FROM TABLE WHERE column = ISNULL(@param, column)\n" }, { "answer_id": 192159, "author": "bart", "author_id": 19966, "author_profile": "https://Stackoverflow.com/users/19966", "pm_score": 1, "selected": false, "text": "SELECT *\n FROM dbo.SomeTable T\n WHERE T.SomeColumn = COALESCE(@Param, T.SomeColumn)\n SELECT *\n FROM dbo.SomeTable T\n WHERE T.SomeColumn = @Param OR @Param IS NULL\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6651/" ]
191,974
<p>The SQL implementation of relational databases has been around in their current form for something like 25 years (since System R and Ingres). Even the main (loosely adhered to) standard is ANSI-92 (although there were later updates) is a good 15 years old.</p> <p>What innovations can you think of with SQL based databases in the last ten years or so. I am specifically excluding OLAP, Columnar and other non-relational (or at least non SQL) innovations. I also want to exclude 'application server' type features and bundling (like reporting tools)</p> <p>Although the basic approach has remained fairly static, I can think of:</p> <ul> <li>Availability</li> <li>Ability to handle larger sets of data</li> <li>Ease of maintenance and configuration</li> <li>Support for more advanced data types (blob, xml, unicode etc)</li> </ul> <p>Any others that you can think of?</p>
[ { "answer_id": 192087, "author": "hova", "author_id": 2170, "author_profile": "https://Stackoverflow.com/users/2170", "pm_score": 2, "selected": false, "text": "SELECT (invoiceprice * detailweight) / SUM(weight) OVER(PARITTION BY invoice) as weighted, * \nFROM tblInvoiceDetails\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3893/" ]
191,980
<p>Should I create two <code>CFile</code> objects and copy one into the other character by character? Or is there something in the library that will do this for me?</p>
[ { "answer_id": 191992, "author": "jeffm", "author_id": 1544, "author_profile": "https://Stackoverflow.com/users/1544", "pm_score": 5, "selected": true, "text": "CopyFile CFile::Open CFile" }, { "answer_id": 200063, "author": "skst", "author_id": 4858, "author_profile": "https://Stackoverflow.com/users/4858", "pm_score": 2, "selected": false, "text": "CopyFile() CopyFileEx() SHFileOperation() IFileOperation SHFileOperation()" }, { "answer_id": 67078575, "author": "user8128167", "author_id": 351154, "author_profile": "https://Stackoverflow.com/users/351154", "pm_score": 0, "selected": false, "text": "FileOperations #include \"stdafx.h\"\n#include \"FileOperations.h\"\n//\n// this code copy 'c:\\source' directory and \n// all it's subdirectories and files\n// to the 'c:\\dest' directory. \n//\nCFileOperation fo; // create object\nfo.SetOverwriteMode(false); // reset OverwriteMode flag (optional)\nif (!fo.Copy(\"c:\\\\source\", \"c:\\\\dest\")) // do Copy\n{\n fo.ShowError(); // if copy fails show error message\n}\n//\n// this code delete 'c:\\source' directory and \n// all it's subdirectories and files.\n//\nfo.Setucancode.netIfReadOnly(); // set ucancode.netIfReadonly flag (optional)\nif (!fo.Delete(\"c:\\\\source\")) // do Copy\n{\n fo.ShowError(); // if copy fails show error message\n}\n #include \"resource.h\"\n\n#define PATH_ERROR -1\n#define PATH_NOT_FOUND 0\n#define PATH_IS_FILE 1\n#define PATH_IS_FOLDER 2\n\n\nclass CFExeption\n{\npublic:\n CFExeption(DWORD dwErrCode);\n CFExeption(CString sErrText);\n CString GetErrorText() {return m_sError;}\n DWORD GetErrorCode() {return m_dwError;}\n\nprivate:\n CString m_sError;\n DWORD m_dwError;\n};\n\n\n//*****************************************************************************************************\n\nclass CFileOperation\n{\npublic:\n CFileOperation(); // constructor\n bool Delete(CString sPathName); // delete file or folder\n bool Copy(CString sSource, CString sDest); // copy file or folder\n bool Replace(CString sSource, CString sDest); // move file or folder\n bool Rename(CString sSource, CString sDest); // rename file or folder\n CString GetErrorString() {return m_sError;} // return error description\n DWORD GetErrorCode() {return m_dwError;} // return error code\n void ShowError() // show error message\n {MessageBox(NULL, m_sError, _T(\"Error\"), MB_OK | MB_ICONERROR);}\n void SetAskIfReadOnly(bool bAsk = true) // sets behavior with readonly files(folders)\n {m_bAskIfReadOnly = bAsk;}\n bool IsAskIfReadOnly() // return current behavior with readonly files(folders)\n {return m_bAskIfReadOnly;}\n bool CanDelete(CString sPathName); // check attributes\n void SetOverwriteMode(bool bOverwrite = false) // sets overwrite mode on/off\n {m_bOverwriteMode = bOverwrite;}\n bool IsOverwriteMode() {return m_bOverwriteMode;} // return current overwrite mode\n int CheckPath(CString sPath);\n bool IsAborted() {return m_bAborted;}\n\nprotected:\n void DoDelete(CString sPathName);\n void DoCopy(CString sSource, CString sDest, bool bDelteAfterCopy = false);\n void DoFileCopy(CString sSourceFile, CString sDestFile, bool bDelteAfterCopy = false);\n void DoFolderCopy(CString sSourceFolder, CString sDestFolder, bool bDelteAfterCopy = false);\n void DoRename(CString sSource, CString sDest);\n bool IsFileExist(CString sPathName);\n void PreparePath(CString &sPath);\n void Initialize();\n void CheckSelfRecursion(CString sSource, CString sDest);\n bool CheckSelfCopy(CString sSource, CString sDest);\n CString ChangeFileName(CString sFileName);\n CString ParseFolderName(CString sPathName);\n\nprivate:\n CString m_sError;\n DWORD m_dwError;\n bool m_bAskIfReadOnly;\n bool m_bOverwriteMode;\n bool m_bAborted;\n int m_iRecursionLimit;\n};\n\n\n//*****************************************************************************************************\n #include \"stdafx.h\" \n#include \"resource.h\" \n#include \"FileOperations.h\" \n\n//************************************************************************************************************\nCFExeption::CFExeption(DWORD dwErrCode)\n{\n LPVOID lpMsgBuf;\n FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n NULL, dwErrCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL);\n m_sError = (LPTSTR)lpMsgBuf;\n LocalFree(lpMsgBuf);\n m_dwError = dwErrCode;\n}\n\n\nCFExeption::CFExeption(CString sErrText)\n{\n m_sError = sErrText;\n m_dwError = 0;\n}\n\n\n//************************************************************************************************************\n\nCFileOperation::CFileOperation()\n{\n Initialize();\n}\n\n\nvoid CFileOperation::Initialize()\n{\n m_sError = _T(\"No error\");\n m_dwError = 0;\n m_bAskIfReadOnly = true;\n m_bOverwriteMode = false;\n m_bAborted = false;\n m_iRecursionLimit = -1;\n}\n\n\nvoid CFileOperation::DoDelete(CString sPathName)\n{\n CFileFind ff;\n CString sPath = sPathName;\n\n if (CheckPath(sPath) == PATH_IS_FILE)\n {\n if (!CanDelete(sPath)) \n {\n m_bAborted = true;\n return;\n }\n if (!DeleteFile(sPath)) throw new CFExeption(GetLastError());\n return;\n }\n\n PreparePath(sPath);\n sPath += \"*.*\";\n\n BOOL bRes = ff.FindFile(sPath);\n while(bRes)\n {\n bRes = ff.FindNextFile();\n if (ff.IsDots()) continue;\n if (ff.IsDirectory())\n {\n sPath = ff.GetFilePath();\n DoDelete(sPath);\n }\n else DoDelete(ff.GetFilePath());\n }\n ff.Close();\n if (!RemoveDirectory(sPathName) && !m_bAborted) throw new CFExeption(GetLastError());\n}\n\n\nvoid CFileOperation::DoFolderCopy(CString sSourceFolder, CString sDestFolder, bool bDelteAfterCopy)\n{\n CFileFind ff;\n CString sPathSource = sSourceFolder;\n BOOL bRes = ff.FindFile(sPathSource);\n while (bRes)\n {\n bRes = ff.FindNextFile();\n if (ff.IsDots()) continue;\n if (ff.IsDirectory()) // source is a folder\n {\n if (m_iRecursionLimit == 0) continue;\n sPathSource = ff.GetFilePath() + CString(\"\\\\\") + CString(\"*.*\");\n CString sPathDest = sDestFolder + ff.GetFileName() + CString(\"\\\\\");\n if (CheckPath(sPathDest) == PATH_NOT_FOUND) \n {\n if (!CreateDirectory(sPathDest, NULL))\n {\n ff.Close();\n throw new CFExeption(GetLastError());\n }\n }\n if (m_iRecursionLimit > 0) m_iRecursionLimit --;\n DoFolderCopy(sPathSource, sPathDest, bDelteAfterCopy);\n }\n else // source is a file\n {\n CString sNewFileName = sDestFolder + ff.GetFileName();\n DoFileCopy(ff.GetFilePath(), sNewFileName, bDelteAfterCopy);\n }\n }\n ff.Close();\n}\n\n\nbool CFileOperation::Delete(CString sPathName)\n{\n try\n {\n DoDelete(sPathName);\n }\n catch(CFExeption* e)\n {\n m_sError = e->GetErrorText();\n m_dwError = e->GetErrorCode();\n delete e;\n if (m_dwError == 0) return true;\n return false;\n }\n return true;\n}\n\n\nbool CFileOperation::Rename(CString sSource, CString sDest)\n{\n try\n {\n DoRename(sSource, sDest);\n }\n catch(CFExeption* e)\n {\n m_sError = e->GetErrorText();\n m_dwError = e->GetErrorCode();\n delete e;\n return false;\n }\n return true;\n}\n\n\nvoid CFileOperation::DoRename(CString sSource, CString sDest)\n{\n if (!MoveFile(sSource, sDest)) throw new CFExeption(GetLastError());\n}\n\n\nvoid CFileOperation::DoCopy(CString sSource, CString sDest, bool bDelteAfterCopy)\n{\n CheckSelfRecursion(sSource, sDest);\n // source not found\n if (CheckPath(sSource) == PATH_NOT_FOUND)\n {\n CString sError = sSource + CString(\" not found\");\n throw new CFExeption(sError);\n }\n // dest not found\n if (CheckPath(sDest) == PATH_NOT_FOUND)\n {\n CString sError = sDest + CString(\" not found\");\n throw new CFExeption(sError);\n }\n // folder to file\n if (CheckPath(sSource) == PATH_IS_FOLDER && CheckPath(sDest) == PATH_IS_FILE) \n {\n throw new CFExeption(\"Wrong operation\");\n }\n // folder to folder\n if (CheckPath(sSource) == PATH_IS_FOLDER && CheckPath(sDest) == PATH_IS_FOLDER) \n {\n CFileFind ff;\n CString sError = sSource + CString(\" not found\");\n PreparePath(sSource);\n PreparePath(sDest);\n sSource += \"*.*\";\n if (!ff.FindFile(sSource)) \n {\n ff.Close();\n throw new CFExeption(sError);\n }\n if (!ff.FindNextFile()) \n {\n ff.Close();\n throw new CFExeption(sError);\n }\n CString sFolderName = ParseFolderName(sSource);\n if (!sFolderName.IsEmpty()) // the source is not drive\n {\n sDest += sFolderName;\n PreparePath(sDest);\n if (!CreateDirectory(sDest, NULL))\n {\n DWORD dwErr = GetLastError();\n if (dwErr != 183)\n {\n ff.Close();\n throw new CFExeption(dwErr);\n }\n }\n }\n ff.Close();\n DoFolderCopy(sSource, sDest, bDelteAfterCopy);\n }\n // file to file\n if (CheckPath(sSource) == PATH_IS_FILE && CheckPath(sDest) == PATH_IS_FILE) \n {\n DoFileCopy(sSource, sDest);\n }\n // file to folder\n if (CheckPath(sSource) == PATH_IS_FILE && CheckPath(sDest) == PATH_IS_FOLDER) \n {\n PreparePath(sDest);\n char drive[MAX_PATH], dir[MAX_PATH], name[MAX_PATH], ext[MAX_PATH];\n _splitpath(sSource, drive, dir, name, ext);\n sDest = sDest + CString(name) + CString(ext);\n DoFileCopy(sSource, sDest);\n }\n}\n\n\nvoid CFileOperation::DoFileCopy(CString sSourceFile, CString sDestFile, bool bDelteAfterCopy)\n{\n BOOL bOvrwriteFails = FALSE;\n if (!m_bOverwriteMode)\n {\n while (IsFileExist(sDestFile)) \n {\n sDestFile = ChangeFileName(sDestFile);\n }\n bOvrwriteFails = TRUE;\n }\n if (!CopyFile(sSourceFile, sDestFile, bOvrwriteFails)) throw new CFExeption(GetLastError());\n if (bDelteAfterCopy)\n {\n DoDelete(sSourceFile);\n }\n}\n\n\nbool CFileOperation::Copy(CString sSource, CString sDest)\n{\n if (CheckSelfCopy(sSource, sDest)) return true;\n bool bRes;\n try\n {\n DoCopy(sSource, sDest);\n bRes = true;\n }\n catch(CFExeption* e)\n {\n m_sError = e->GetErrorText();\n m_dwError = e->GetErrorCode();\n delete e;\n if (m_dwError == 0) bRes = true;\n bRes = false;\n }\n m_iRecursionLimit = -1;\n return bRes;\n}\n\n\nbool CFileOperation::Replace(CString sSource, CString sDest)\n{\n if (CheckSelfCopy(sSource, sDest)) return true;\n bool bRes;\n try\n {\n bool b = m_bAskIfReadOnly;\n m_bAskIfReadOnly = false;\n DoCopy(sSource, sDest, true);\n DoDelete(sSource);\n m_bAskIfReadOnly = b;\n bRes = true;\n }\n catch(CFExeption* e)\n {\n m_sError = e->GetErrorText();\n m_dwError = e->GetErrorCode();\n delete e;\n if (m_dwError == 0) bRes = true;\n bRes = false;\n }\n m_iRecursionLimit = -1;\n return bRes;\n}\n\n\nCString CFileOperation::ChangeFileName(CString sFileName)\n{\n CString sName, sNewName, sResult;\n char drive[MAX_PATH];\n char dir [MAX_PATH];\n char name [MAX_PATH];\n char ext [MAX_PATH];\n _splitpath((LPCTSTR)sFileName, drive, dir, name, ext);\n sName = name;\n\n int pos = sName.Find(\"Copy \");\n if (pos == -1)\n {\n sNewName = CString(\"Copy of \") + sName + CString(ext);\n }\n else\n {\n int pos1 = sName.Find('(');\n if (pos1 == -1)\n {\n sNewName = sName;\n sNewName.Delete(0, 8);\n sNewName = CString(\"Copy (1) of \") + sNewName + CString(ext);\n }\n else\n {\n CString sCount;\n int pos2 = sName.Find(')');\n if (pos2 == -1)\n {\n sNewName = CString(\"Copy of \") + sNewName + CString(ext);\n }\n else\n {\n sCount = sName.Mid(pos1 + 1, pos2 - pos1 - 1);\n sName.Delete(0, pos2 + 5);\n int iCount = atoi((LPCTSTR)sCount);\n iCount ++;\n sNewName.Format(\"%s%d%s%s%s\", \"Copy (\", iCount, \") of \", (LPCTSTR)sName, ext);\n }\n }\n }\n\n sResult = CString(drive) + CString(dir) + sNewName;\n\n return sResult;\n}\n\n\nbool CFileOperation::IsFileExist(CString sPathName)\n{\n HANDLE hFile;\n hFile = CreateFile(sPathName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);\n if (hFile == INVALID_HANDLE_VALUE) return false;\n CloseHandle(hFile);\n return true;\n}\n\n\nint CFileOperation::CheckPath(CString sPath)\n{\n DWORD dwAttr = GetFileAttributes(sPath);\n if (dwAttr == 0xffffffff) \n {\n if (GetLastError() == ERROR_FILE_NOT_FOUND || GetLastError() == ERROR_PATH_NOT_FOUND) \n return PATH_NOT_FOUND;\n return PATH_ERROR;\n }\n if (dwAttr & FILE_ATTRIBUTE_DIRECTORY) return PATH_IS_FOLDER;\n return PATH_IS_FILE;\n}\n\n\nvoid CFileOperation::PreparePath(CString &sPath)\n{\n if(sPath.Right(1) != \"\\\\\") sPath += \"\\\\\";\n}\n\n\nbool CFileOperation::CanDelete(CString sPathName)\n{\n DWORD dwAttr = GetFileAttributes(sPathName);\n if (dwAttr == -1) return false;\n if (dwAttr & FILE_ATTRIBUTE_READONLY)\n {\n if (m_bAskIfReadOnly)\n {\n CString sTmp = sPathName;\n int pos = sTmp.ReverseFind('\\\\');\n if (pos != -1) sTmp.Delete(0, pos + 1);\n CString sText = sTmp + CString(\" is read olny. Do you want delete it?\");\n int iRes = MessageBox(NULL, sText, _T(\"Warning\"), MB_YESNOCANCEL | MB_ICONQUESTION);\n switch (iRes)\n {\n case IDYES:\n {\n if (!SetFileAttributes(sPathName, FILE_ATTRIBUTE_NORMAL)) return false;\n return true;\n }\n case IDNO:\n {\n return false;\n }\n case IDCANCEL:\n {\n m_bAborted = true;\n throw new CFExeption(0);\n return false;\n }\n }\n }\n else\n {\n if (!SetFileAttributes(sPathName, FILE_ATTRIBUTE_NORMAL)) return false;\n return true;\n }\n }\n return true;\n}\n\n\nCString CFileOperation::ParseFolderName(CString sPathName)\n{\n CString sFolderName = sPathName;\n int pos = sFolderName.ReverseFind('\\\\');\n if (pos != -1) sFolderName.Delete(pos, sFolderName.GetLength() - pos);\n pos = sFolderName.ReverseFind('\\\\');\n if (pos != -1) sFolderName = sFolderName.Right(sFolderName.GetLength() - pos - 1);\n else sFolderName.Empty();\n return sFolderName;\n}\n\n\nvoid CFileOperation::CheckSelfRecursion(CString sSource, CString sDest)\n{\n if (sDest.Find(sSource) != -1)\n {\n int i = 0, count1 = 0, count2 = 0;\n for(i = 0; i < sSource.GetLength(); i ++) if (sSource[i] == '\\\\') count1 ++;\n for(i = 0; i < sDest.GetLength(); i ++) if (sDest[i] == '\\\\') count2 ++;\n if (count2 >= count1) m_iRecursionLimit = count2 - count1;\n }\n}\n\n\nbool CFileOperation::CheckSelfCopy(CString sSource, CString sDest)\n{\n bool bRes = false;\n if (CheckPath(sSource) == PATH_IS_FOLDER)\n {\n CString sTmp = sSource;\n int pos = sTmp.ReverseFind('\\\\');\n if (pos != -1)\n {\n sTmp.Delete(pos, sTmp.GetLength() - pos);\n if (sTmp.CompareNoCase(sDest) == 0) bRes = true;\n }\n }\n return bRes;\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11575/" ]
191,984
<p>I am writing a little application, which is writing jpeg images at a constant rate on a SD card. I choose an EXT3 filesystem, but the same behaviour was observed with an EXT2 filesystem.</p> <p>My writing loop looks like this :</p> <pre><code>get_image() fwrite() fsync() </code></pre> <p>Or like this :</p> <pre><code>get_image() fopen() fwrite() fsync() fclose() </code></pre> <p>I also display some timing statistics, and I can see my program is sometime blocked for several seconds. The average rate is still good, because if I keep the incoming images into a fifo, then I will write many image in a short period of time after such a stall. Do you know if it is a problem with the OS or if it is related to the SD card itself ? How could I move closer to realtime ? I don't need strong realtime, but being stalled for several seconds is not acceptable.</p> <p>Some precision : Yes it is necessary to fsync after every file, because I want the image to be on disk, not in some user or kernel buffer. Without fsyncing, I have much better throughoutput, but still unacceptable stall. I don't think it is a buffer problem, since the first stall happens after 50 Mbytes have been written. And according to the man page, fsync is here precisely to ensure there is no data buffered.</p> <p>Precision regarding the average write rate : I am writing at a rate that is sustainable by the card I am using. If I pile incoming image while waiting for an fsync to complete, then after this stall the write transfer rate will increase and I will quickly go back to the average rate. The average transfer rate is around 1.4 MBytes /s.</p> <p>The systeme is a modern laptop running ubuntu 8.04 with stock kee (2.6.24.19)</p>
[ { "answer_id": 192107, "author": "Matt J", "author_id": 18528, "author_profile": "https://Stackoverflow.com/users/18528", "pm_score": 2, "selected": false, "text": "fsync() extN" }, { "answer_id": 2098613, "author": "pierrotlefou", "author_id": 115722, "author_profile": "https://Stackoverflow.com/users/115722", "pm_score": 2, "selected": false, "text": "O_DIRECT O_DIRECT O_DIRECT write() fsync O_DIRECT write O_DIRECT O_DSYNC O_SYNC" }, { "answer_id": 21766889, "author": "jcarballo", "author_id": 1247192, "author_profile": "https://Stackoverflow.com/users/1247192", "pm_score": 0, "selected": false, "text": "/dev/sdb1 mkfs.ext4 /dev/sdb1 -L jp # Creates the ext4 filesystem\ntune2fs -o journal_data_writeback /dev/sdb1 # Set to writeback mode\ntune2fs -O ^has_journal /dev/sdb1 # Disable journaling\nsudo e2fsck -f /dev/sdb1 # Filesystem check is required\n /etc/fstab mount -t ext4 -O noatime,nodirame,data=writeback /dev/mmcblk0p1 /mnt/sd\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11589/" ]
191,998
<p>In Eclipse (Ganymede) I'm debugging some code that uses Apache Commons HttpClient and would like to step into the HttpClient code. I've downloaded the source code and tried to attach it in the normal fashion (CTRL-click on the method name and use the Attach Source button). I've tried to attach both as external file and external folder with no success. I've attached source before with no issues and can currently step into Hibernate source code successfully.</p> <p>I've even tried editing the .classpath file directly to add sourcepath manually. Still no luck. Refreshing the project, doing a clean build, closing and re-opening Eclipse do not solve the issue. Frustratingly, Eclipse provides no error message; it just does not attach the source.</p> <p>Here are the entries in .claspath:</p> <pre><code>&lt;!-- Hibernate. Works --&gt; &lt;classpathentry kind="lib" path="/myEAP/EarContent/APP-INF/lib/hibernate.jar" sourcepath="D:/Data/Download/hibernate-3.2.2.ga/hibernate-3.2/src"/&gt; &lt;!-- Commons HttpClient. Will not attach --&gt; &lt;classpathentry kind="lib" path="/myEAP/EarContent/APP-INF/lib/commons-httpclient.jar" sourcepath="D:/Data/Download/commons-httpclient-3.1/src/java"/&gt; </code></pre> <p>I've tried changing the path to D:/Data/Download/commons-httpclient-3.1/src and that does not work either.</p> <p>The directory structure is:</p> <pre><code>D Data Download commons-httpclient-3.1 src java org apache commons httpclient AutoCloseInputStream.java ... (and so forth) </code></pre>
[ { "answer_id": 193385, "author": "Dave L.", "author_id": 3093, "author_profile": "https://Stackoverflow.com/users/3093", "pm_score": 4, "selected": true, "text": "<classpathentry kind=\"lib\" path=\"/blib/java/commons-httpclient-3.1/commons-httpclient-3.1.jar\" sourcepath=\"/blib/java/commons-httpclient-3.1/commons-httpclient-3.1-src.zip\"/>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18995/" ]
192,028
<p>I am trying to use concat_ws inside a group_concat command. With a query, which simplified looks like: </p> <pre><code>SELECT item.title, GROUP_CONCAT( CONCAT_WS( ',', attachments.id, attachments.type, attachments.name ) ) as attachments FROM story AS item LEFT OUTER JOIN story_attachment AS attachments ON item.id = attachments.item_id GROUP BY item.id </code></pre> <p>I get the attachments column as a Blob type. is it it possible to get it as a string instead of Blob?</p>
[ { "answer_id": 192057, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 3, "selected": true, "text": "SELECT item.title, GROUP_CONCAT( CAST(CONCAT_WS(',', attachments.id, \nattachments.type, attachments.name ) as CHAR ) ) as attachments \nFROM story AS item \nLEFT OUTER JOIN story_attachment AS attachments \nON item.id = attachments.item_id GROUP BY item.id\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
192,048
<p>I understand that an id must be unique within an HTML/XHTML page.</p> <p>For a given element, can I assign multiple ids to it?</p> <pre><code>&lt;div id=&quot;nested_element_123 task_123&quot;&gt;&lt;/div&gt; </code></pre> <p>I realize I have an easy solution with simply using a class. I'm just curious about using ids in this manner.</p>
[ { "answer_id": 192064, "author": "tpower", "author_id": 18107, "author_profile": "https://Stackoverflow.com/users/18107", "pm_score": 2, "selected": false, "text": "name id" }, { "answer_id": 192071, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 4, "selected": false, "text": "<div id='enclosing_id_123'><span id='enclosed_id_123'></span></div>\n" }, { "answer_id": 193311, "author": "AmbroseChapel", "author_id": 242241, "author_profile": "https://Stackoverflow.com/users/242241", "pm_score": 4, "selected": false, "text": "<div id=\"foo\" class=\"bar baz bax\">\n" }, { "answer_id": 5685221, "author": "user123444555621", "author_id": 27862, "author_profile": "https://Stackoverflow.com/users/27862", "pm_score": 8, "selected": false, "text": "<p id=\"foo\" xml:id=\"bar\">\n id" }, { "answer_id": 10215524, "author": "James", "author_id": 1342195, "author_profile": "https://Stackoverflow.com/users/1342195", "pm_score": 2, "selected": false, "text": "<html>\n<head>\n</head>\n<body>\n <p id=\"hunkojunk1 hunkojunk2\"></p>\n\n <script type=\"text/javascript\">\n document.getElementById('hunkojunk2').innerHTML = \"JUNK JUNK JUNK JUNK JUNK JUNK\";\n </script>\n</body>\n</html>\n" }, { "answer_id": 22116772, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<html>\n<head>\n <style type=\"text/css\">\n .personal{\n height:100px;\n width: 100px;\n\n }\n .fam{\n border: 2px solid #ccc;\n }\n .x{\n background-color:#ccc;\n }\n\n </style>\n</head>\n\n<body>\n <div class=\"personal fam x\"></div>\n</body>\n</html>\n" }, { "answer_id": 47846045, "author": "corysimmons", "author_id": 175825, "author_profile": "https://Stackoverflow.com/users/175825", "pm_score": 1, "selected": false, "text": "id=\"a b\"" }, { "answer_id": 53072798, "author": "Samdom For Peace", "author_id": 8313078, "author_profile": "https://Stackoverflow.com/users/8313078", "pm_score": 2, "selected": false, "text": "<span></span> <p><a href=\"#exponentialEquationsCalculator\">Exponential Equations</a></p>\n\n<p><a href=\"#logarithmicExpressionsCalculator\"><Logarithmic Expressions</a></p>\n <!-- Exponential / Logarithmic Equations Calculator -->\n<div class=\"w3-container w3-card white w3-margin-bottom\">\n <span id=\"exponentialEquationsCalculator\"></span>\n <span id=\"logarithmicEquationsCalculator\"></span>\n</div>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6349/" ]
192,049
<p>...just like packages do.</p> <p>I use Emacs (maybe, it can offer some kind of solution).</p> <p>For example <code>(defun the-very-very-long-but-good-name () ...)</code> is not to useful later in code. But the name like <code>Fn-15</code> or the first letters abbreviation is not useful too. Is it possible either to have an alias like for packages or to access the documentation string while trying to recall the function's name?</p> <p>In other words, is it possible for functions to mix somehow self-documenting and short names?</p>
[ { "answer_id": 192293, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": -1, "selected": false, "text": "(defmacro ...)" }, { "answer_id": 192336, "author": "Allen", "author_id": 6043, "author_profile": "https://Stackoverflow.com/users/6043", "pm_score": 6, "selected": true, "text": "defalias (defalias 'newname 'oldname)" }, { "answer_id": 201951, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 2, "selected": false, "text": "abbrev-mode hippie-expand" }, { "answer_id": 21075628, "author": "muyinliu", "author_id": 2765530, "author_profile": "https://Stackoverflow.com/users/2765530", "pm_score": 3, "selected": false, "text": "(defmacro alias (new-name prev-name)\n `(defmacro ,new-name (&rest args)\n `(,',prev-name ,@args)))\n\n; use: (alias df defun)\n\n\n(defun group (source n)\n (if (zerop n) (error \"zero length\"))\n (labels ((rec (source acc)\n (let ((rest (nthcdr n source)))\n (if (consp rest)\n (rec rest (cons (subseq source 0 n) acc))\n (nreverse (cons source acc))))))\n (if source (rec source nil) nil)))\n\n(defmacro aliasx (&rest names)\n `(alias\n ,@(mapcar #'(lambda (pair)\n `(alias ,@pair))\n (group names 2))))\n\n; use: (aliasx df1 defun \n; df2 defun \n; df3 defun)\n" }, { "answer_id": 23332929, "author": "Thayne", "author_id": 2543666, "author_profile": "https://Stackoverflow.com/users/2543666", "pm_score": 3, "selected": false, "text": "setf (defmacro alias (new-name prev-name)\n `(setf (symbol-function ,new-name) (symbol-function ,prev-name))) \n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20514/" ]
192,055
<p>I want to create a component that allows us to have compound keyboard shortcuts associated with an arbitrary command, like the Visual Studio IDE and Microsoft Office do.</p> <p>That is, keyboard shortcuts consisting of a sequence of multiple keystrokes, such as <kbd>Ctrl</kbd> + <kbd>W</kbd> + <kbd>C</kbd>. In Visual Studio this opens the class-view. When the first set of the keys is pressed (<kbd>Ctrl</kbd> + <kbd>W</kbd>) the message "(Ctrl + W) was pressed. Waiting for the second key of the chord..." appears in the status bar.</p>
[ { "answer_id": 192170, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 2, "selected": false, "text": "// Handle the KeyDown event to determine the type of character entered into the control.\nprivate void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)\n{\n // Initialize the flag to false.\n nonNumberEntered = false;\n\n // Determine whether the keystroke is a number from the top of the keyboard.\n if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)\n {\n // Determine whether the keystroke is a number from the keypad.\n if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)\n {\n // Determine whether the keystroke is a backspace.\n if(e.KeyCode != Keys.Back)\n {\n // A non-numerical keystroke was pressed.\n // Set the flag to true and evaluate in KeyPress event.\n nonNumberEntered = true;\n }\n }\n }\n //If shift key was pressed, it's not a number.\n if (Control.ModifierKeys == Keys.Shift) {\n nonNumberEntered = true;\n }\n}\n" }, { "answer_id": 192806, "author": "Richard R", "author_id": 23502, "author_profile": "https://Stackoverflow.com/users/23502", "pm_score": 0, "selected": false, "text": "Form.KeyPreview = true;\n" }, { "answer_id": 193933, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 5, "selected": true, "text": "KeyboardChordProvider Form.KeyPreview true Form.KeyPress ChordPressed ChordPressed ChordPressed" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26877/" ]
192,073
<p>What are the differences between pipes in Windows and Linux?</p>
[ { "answer_id": 192187, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 6, "selected": true, "text": "mkfifo pipe.wav\ndecodeMP3 song.mp3 --out pipe.wav &\nencodeAVI video.mpeg pipe.wav --out video.avi\n" }, { "answer_id": 192728, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 3, "selected": false, "text": "fork()" }, { "answer_id": 38512452, "author": "lkreinitz", "author_id": 1738787, "author_profile": "https://Stackoverflow.com/users/1738787", "pm_score": 3, "selected": false, "text": "A | B | C \n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
192,077
<p>I created a simple class with a DependencyProperty. When setting the value, I observe that ValidateValueCallback is called before CoerceValueCallback.</p> <p>On <a href="http://wpftutorial.net/How+does+a+DependencyProperty+resolve+its+value.htm" rel="nofollow noreferrer">wpftutorial</a> and in other books, it is stated that coercion is called before validation.</p>
[ { "answer_id": 192187, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 6, "selected": true, "text": "mkfifo pipe.wav\ndecodeMP3 song.mp3 --out pipe.wav &\nencodeAVI video.mpeg pipe.wav --out video.avi\n" }, { "answer_id": 192728, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 3, "selected": false, "text": "fork()" }, { "answer_id": 38512452, "author": "lkreinitz", "author_id": 1738787, "author_profile": "https://Stackoverflow.com/users/1738787", "pm_score": 3, "selected": false, "text": "A | B | C \n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1624/" ]
192,078
<p>Shouldn't this be a pretty straightforward operation? However, I see there's neither a <code>size()</code> nor <code>length()</code> method.</p>
[ { "answer_id": 192094, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": 7, "selected": false, "text": "ResultSet rs = ps.executeQuery();\nint rowcount = 0;\nif (rs.last()) {\n rowcount = rs.getRow();\n rs.beforeFirst(); // not rs.first() because the rs.next() below will move on, missing the first element\n}\nwhile (rs.next()) {\n // do your standard per row stuff\n}\n" }, { "answer_id": 192104, "author": "finnw", "author_id": 12048, "author_profile": "https://Stackoverflow.com/users/12048", "pm_score": 9, "selected": true, "text": "SELECT COUNT(*) FROM ... int size =0;\nif (rs != null) \n{\n rs.last(); // moves cursor to the last row\n size = rs.getRow(); // get row id \n}\n" }, { "answer_id": 12658004, "author": "CounterSpell", "author_id": 1398114, "author_profile": "https://Stackoverflow.com/users/1398114", "pm_score": 2, "selected": false, "text": "ResultSet rs = job.getSearchedResult(stmt);\nint rsCount = 0;\n\n//but notice that you'll only get correct ResultSet size after end of the while loop\nwhile(rs.next())\n{\n //do your other per row stuff \n rsCount = rsCount + 1;\n}//end while\n" }, { "answer_id": 13598630, "author": "Dan", "author_id": 941711, "author_profile": "https://Stackoverflow.com/users/941711", "pm_score": 4, "selected": false, "text": "rs.last() if(rs.last()){\n rowCount = rs.getRow(); \n rs.beforeFirst();\n}\n java.sql.SQLException: Invalid operation for forward only resultset\n ResultSet.TYPE_FORWARD_ONLY rs.next() stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,\n ResultSet.CONCUR_READ_ONLY); \n" }, { "answer_id": 15389446, "author": "Ben", "author_id": 2166111, "author_profile": "https://Stackoverflow.com/users/2166111", "pm_score": 1, "selected": false, "text": "theStatement=theConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);\n\nResultSet theResult=theStatement.executeQuery(query); \n\n//Get the size of the data returned\ntheResult.last(); \nint size = theResult.getRow() * theResult.getMetaData().getColumnCount(); \ntheResult.beforeFirst();\n" }, { "answer_id": 15919915, "author": "Unai Vivi", "author_id": 1018783, "author_profile": "https://Stackoverflow.com/users/1018783", "pm_score": 4, "selected": false, "text": "ResultSet ResultSet.TYPE_FORWARD_ONLY ResultSet.TYPE_SCROLL_INSENSITIVE ResultSet.TYPE_SCROLL_INSENSITIVE .last() select MYBOOL,MYINT,MYCHAR,MYSMALLINT,MYVARCHAR\nfrom MYTABLE\nwhere ...blahblah...\n true 65537 \"Hey\" -32768 \"The quick brown fox\"\nfalse 123456 \"Sup\" 300 \"The lazy dog\"\nfalse -123123 \"Yo\" 0 \"Go ahead and jump\"\nfalse 3 \"EVH\" 456 \"Might as well jump\"\n...\n[1000 total rows]\n Statement s=myConnection.createStatement(ResultSet.TYPE_FORWARD_ONLY,\n ResultSet.CONCUR_READ_ONLY);\nString from_where=\"FROM myTable WHERE ...blahblah... \";\n//h4x\nResultSet rs=s.executeQuery(\"select count(*)as RECORDCOUNT,\"\n + \"cast(null as boolean)as MYBOOL,\"\n + \"cast(null as int)as MYINT,\"\n + \"cast(null as char(1))as MYCHAR,\"\n + \"cast(null as smallint)as MYSMALLINT,\"\n + \"cast(null as varchar(1))as MYVARCHAR \"\n +from_where\n +\"UNION ALL \"//the \"ALL\" part prevents internal re-sorting to prevent duplicates (and we do not want that)\n +\"select cast(null as int)as RECORDCOUNT,\"\n + \"MYBOOL,MYINT,MYCHAR,MYSMALLINT,MYVARCHAR \"\n +from_where);\n 1000 null null null null null\nnull true 65537 \"Hey\" -32768 \"The quick brown fox\"\nnull false 123456 \"Sup\" 300 \"The lazy dog\"\nnull false -123123 \"Yo\" 0 \"Go ahead and jump\"\nnull false 3 \"EVH\" 456 \"Might as well jump\"\n...\n[1001 total rows]\n if(rs.next())\n System.out.println(\"Recordcount: \"+rs.getInt(\"RECORDCOUNT\"));//hack: first record contains the record count\nwhile(rs.next())\n //do your stuff\n" }, { "answer_id": 16885165, "author": "clausavram", "author_id": 1820666, "author_profile": "https://Stackoverflow.com/users/1820666", "pm_score": 1, "selected": false, "text": "getUpdateCount() ResultSet resultSet = executeQuery(sqlQuery); double rowCount = ((ResultSetImpl)resultSet).getUpdateCount()" }, { "answer_id": 18457100, "author": "Peter.Chu", "author_id": 2720180, "author_profile": "https://Stackoverflow.com/users/2720180", "pm_score": 2, "selected": false, "text": "String sql = \"select count(*) from message\";\nps = cn.prepareStatement(sql);\n\nrs = ps.executeQuery();\nint rowCount = 0;\nwhile(rs.next()) {\n rowCount = Integer.parseInt(rs.getString(\"count(*)\"));\n System.out.println(Integer.parseInt(rs.getString(\"count(*)\")));\n}\nSystem.out.println(\"Count : \" + rowCount);\n" }, { "answer_id": 23157858, "author": "bhaskar", "author_id": 3549459, "author_profile": "https://Stackoverflow.com/users/3549459", "pm_score": 4, "selected": false, "text": "int i = 0;\nwhile(rs.next()) {\n i++;\n}\n" }, { "answer_id": 25543677, "author": "Anptk", "author_id": 3876141, "author_profile": "https://Stackoverflow.com/users/3876141", "pm_score": 2, "selected": false, "text": "int size =0; \nif (rs != null) \n{ \nrs.beforeFirst(); \n rs.last(); \nsize = rs.getRow();\n}\n rs.beforeFirst(); \n" }, { "answer_id": 26782970, "author": "Israel Hernández", "author_id": 4223435, "author_profile": "https://Stackoverflow.com/users/4223435", "pm_score": 0, "selected": false, "text": "ResultSet.first() if(rs.first()){\n // Do your job\n} else {\n // No rows take some actions\n}\n boolean first()\n throws SQLException\n ResultSet true false SQLException TYPE_FORWARD_ONLY SQLFeatureNotSupportedException" }, { "answer_id": 30384597, "author": "Vit Bernatik", "author_id": 1093607, "author_profile": "https://Stackoverflow.com/users/1093607", "pm_score": 3, "selected": false, "text": "ResultSet.last() ResultSet.TYPE_SCROLL_INSENSITIVE ResultSet.TYPE_FORWARD_ONLY SELECT COUNT(*)" }, { "answer_id": 47134143, "author": "parksangdonews", "author_id": 7773143, "author_profile": "https://Stackoverflow.com/users/7773143", "pm_score": 1, "selected": false, "text": "int chkSize = 0;\nif (rs.next()) {\n do { ..... blah blah\n enter code here for each rs.\n chkSize++;\n } while (rs.next());\n} else {\n enter code here for rs size = 0 \n}\n// good luck to u.\n" }, { "answer_id": 50299498, "author": "ReMaX", "author_id": 3835403, "author_profile": "https://Stackoverflow.com/users/3835403", "pm_score": -1, "selected": false, "text": "String query = \"SELECT COUNT(*) as count FROM\n PreparedStatement statement = connection.prepareStatement(query);\nstatement.setString(1, item.getProductId());\nResultSet resultSet = statement.executeQuery();\nwhile (resultSet.next()) {\n int count = resultSet.getInt(\"count\");\n if (count >= 1) {\n System.out.println(\"Product ID already exists.\");\n } else {\n System.out.println(\"New Product ID.\");\n }\n}\n" }, { "answer_id": 58162602, "author": "user7120462", "author_id": 7120462, "author_profile": "https://Stackoverflow.com/users/7120462", "pm_score": 0, "selected": false, "text": "ResultSet rs = statement.executeQuery(\"Select Count(*) from your_db\");\nif(rs.next()) {\n int count = rs.getString(1).toInt()\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10675/" ]
192,080
<p>I have a .asp application where image files (.PDF) are stored in a directory (fed by a copier/scanner). The created file names are stored in a database table. When a query is launched from the web page a link to the file is created. When clicked the image should be displayed. This functionality works 100% in Internet Explorer. No such luck in Firefox (and I have some Firefox users). The created hyperlink looks like this <code>file://Server/Scanner/XYZ.pdf</code></p> <p>The Firefox helps suggest the reason is this: </p> <blockquote> <p>Links to local or network pages do not work. As a security precaution, Firefox forbids sites on the Internet to link to files that are stored in your local computing environment. These files may include files on your computer, mapped network drives, and UNC network paths</p> </blockquote> <p>None of the suggestions for a workaround seem to work (or I am not understanding the steps to create the image display) Any Suggestions?</p>
[ { "answer_id": 192284, "author": "alexandrul", "author_id": 19756, "author_profile": "https://Stackoverflow.com/users/19756", "pm_score": 4, "selected": false, "text": "<a href=\"file://N:/path/to/file.ext\">test</a> user.js user_pref(\"capability.policy.default.checkloaduri.enabled\", \"allAccess\"); <img src=\"file://///server/share/image.png\" /> <img src=\"file://\\\\\\server\\share\\image.png\" /> <img src=\"file://d:\\image.png\" /> <img src=\"file:///d:\\image.png\" /> <img src=\"file://d:/image.png\" /> <img src=\"file:///d:/image.png\" /> <img src=\"file://localhost/d:/image.png\" />" }, { "answer_id": 1946255, "author": "sunny", "author_id": 236857, "author_profile": "https://Stackoverflow.com/users/236857", "pm_score": 1, "selected": false, "text": "* type \"about:config\" in the address bar and accept \"i'll be careful\"\n* find \"security.checkloaduri\" in older versions or \"security.fileuri.strict_origin_policy\" in newer versions of firefox and change the value to \"false\"\n* restart firefox\n" }, { "answer_id": 10275262, "author": "Alex L", "author_id": 1129194, "author_profile": "https://Stackoverflow.com/users/1129194", "pm_score": -1, "selected": false, "text": "file://localhost///servername/share/file.txt file:///C:/index.html" }, { "answer_id": 10928425, "author": "Nicolas C.", "author_id": 917312, "author_profile": "https://Stackoverflow.com/users/917312", "pm_score": 3, "selected": false, "text": "user_pref(\"capability.policy.localfilelinks.checkloaduri.enabled\", \"allAccess\");\nuser_pref(\"capability.policy.localfilelinks.sites\", \"http://localhost\");\nuser_pref(\"capability.policy.maonoscript.javascript.enabled\", \"allAccess\");\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26883/" ]
192,083
<p>We have PHP 5.2.6 deployed to c:\php and in that folder there is the php.ini file. On Windows, can a website override these settings similar to the way that apache has .htaccess? e.g.</p> <pre><code>DirectoryIndex index.php index.html &lt;IfModule mod_php5.c&gt; php_flag magic_quotes_gpc off php_flag register_globals off &lt;/IfModule&gt; &lt;IfModule mod_php4.c&gt; php_flag magic_quotes_gpc off php_flag register_globals off &lt;/IfModule&gt; </code></pre> <p><strong><em>Update:</em></strong> </p> <p>I was aware of ini_set() but wondered if there was a declarative way to do this in a configuration file in the website rather than in script.</p>
[ { "answer_id": 192093, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 3, "selected": true, "text": "egister_globals init_set()" }, { "answer_id": 192361, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 1, "selected": false, "text": "$option = 'magic_quotes_gpc';\necho \"Value of $option => \", ini_get($option);\nini_set($option,0);\necho \"New value of $option => \", ini_get($option);\n register_globals" }, { "answer_id": 192425, "author": "flamingLogos", "author_id": 8161, "author_profile": "https://Stackoverflow.com/users/8161", "pm_score": 2, "selected": false, "text": "PHP_INI_USER ini_set() PHP_INI_PERDIR php_value php_flag PHP_INI_SYSTEM PHP_INI_ALL" }, { "answer_id": 1037622, "author": "r_honey", "author_id": 172396, "author_profile": "https://Stackoverflow.com/users/172396", "pm_score": 1, "selected": false, "text": " $fsrc = fopen($pathToIni,'r');\n $fdest = fopen($myHostingDir,'w+');\n $len = stream_copy_to_stream($fsrc,$fdest);\n fclose($fsrc);\n fclose($fdest);\n echo $len;\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/419/" ]
192,085
<p>I am writing a diagnostic page for SiteScope and one area we need to test is if the connection to the file/media assets are accesible from the web server. One way I think I can do this is load the image via code behind and test to see if the IIS status message is 200. </p> <p>So basically I should be able to navigate to within the site to a folder like this: /media/1/image.jpg and see if it returns 200...if not throw exception.</p> <p>I am struggling to figure out how to write this code.</p> <p>Any help is greatly appreciated.</p> <p>Thanks</p>
[ { "answer_id": 192141, "author": "Greg Dean", "author_id": 1200558, "author_profile": "https://Stackoverflow.com/users/1200558", "pm_score": 7, "selected": true, "text": "HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(\"url\");\nrequest.Method = \"HEAD\";\n\nbool exists;\ntry\n{\n request.GetResponse();\n exists = true;\n}\ncatch\n{\n exists = false;\n}\n" }, { "answer_id": 192161, "author": "beno", "author_id": 649, "author_profile": "https://Stackoverflow.com/users/649", "pm_score": 3, "selected": false, "text": "try\n{\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(\"http://somewhere/picture.jpg\");\n request.Credentials = System.Net.CredentialCache.DefaultCredentials;\n HttpWebResponse response = (HttpWebResponse)request.GetResponse();\n myImg.ImageUrl = \"http://somewhere/picture.jpg\";\n}\ncatch (Exception ex)\n{\n // image doesn't exist, set to default picture\n myImg.ImageUrl = \"http://somewhere/default.jpg\";\n}\n" }, { "answer_id": 192667, "author": "Anjisan", "author_id": 25304, "author_profile": "https://Stackoverflow.com/users/25304", "pm_score": 5, "selected": false, "text": "public bool doesImageExistRemotely(string uriToImage, string mimeType)\n{\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriToImage);\n request.Method = \"HEAD\";\n\n try\n {\n HttpWebResponse response = (HttpWebResponse)request.GetResponse();\n\n if (response.StatusCode == HttpStatusCode.OK && response.ContentType == mimeType)\n {\n return true;\n }\n else\n {\n return false;\n } \n }\n catch\n {\n return false;\n }\n}\n" }, { "answer_id": 236312, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": " public bool DoesImageExistRemotely(string uriToImage)\n {\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriToImage);\n\n request.Method = \"HEAD\";\n\n try\n {\n using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())\n {\n\n if (response.StatusCode == HttpStatusCode.OK)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n }\n catch (WebException) { return false; }\n catch\n {\n return false;\n }\n }\n" }, { "answer_id": 7978922, "author": "jhamm", "author_id": 103927, "author_profile": "https://Stackoverflow.com/users/103927", "pm_score": 1, "selected": false, "text": "request.Credentials = new NetworkCredential(username, password);\n" }, { "answer_id": 19228306, "author": "Paulos02", "author_id": 1625208, "author_profile": "https://Stackoverflow.com/users/1625208", "pm_score": 1, "selected": false, "text": " public static void GetPictureSize(string url, ref float width, ref float height, ref string err)\n {\n System.Net.HttpWebRequest wreq;\n System.Net.HttpWebResponse wresp;\n System.IO.Stream mystream;\n System.Drawing.Bitmap bmp;\n\n bmp = null;\n mystream = null;\n wresp = null;\n try\n {\n wreq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);\n wreq.AllowWriteStreamBuffering = true;\n\n wresp = (HttpWebResponse)wreq.GetResponse();\n\n if ((mystream = wresp.GetResponseStream()) != null)\n bmp = new System.Drawing.Bitmap(mystream);\n }\n catch (Exception er)\n {\n err = er.Message;\n return;\n }\n finally\n {\n if (mystream != null)\n mystream.Close();\n\n if (wresp != null)\n wresp.Close();\n }\n width = bmp.Width;\n height = bmp.Height;\n}\n\npublic static bool ImageUrlExists(string url)\n{\n\n float width = 0;\n float height = 0;\n string err = null;\n GetPictureSize(url, ref width, ref height, ref err);\n return width > 0;\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/648/" ]
192,092
<p>When calling php via cli, the current directory is NOT changed to the one of the script. All the scripts i have running in crontab run via the CLI, so this is an issue.</p> <p>I'm currently <em>fixing</em> the problem by doing a chdir() with the absolute path where the script is, but i REALLY dont like hardcoding paths into stuff like that.</p> <p>I'm looking for the most portable/reliable method for ensuring that the current working directory is the one where the script it is at.</p>
[ { "answer_id": 192112, "author": "hasseg", "author_id": 4111, "author_profile": "https://Stackoverflow.com/users/4111", "pm_score": 2, "selected": false, "text": "__FILE__ <?php\necho \"I'm here: \".__FILE__.\"\\n\";\n?>\n" }, { "answer_id": 192145, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 6, "selected": true, "text": "chdir(dirname(__FILE__));\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/314/" ]
192,100
<p>.NET Framework 3.5 SP1 installs the .NET Framework 2.0 SP2 and the .NET Framework 3.0 SP2 behind the scenes. These installation packages (especially .NET Framework 2.0 SP2) are not available directly from Microsoft.</p> <p>Is there a way to extract them from the .NET Framework 3.5 SP1 installation package?</p>
[ { "answer_id": 392647, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "FL_FL_NetFx20SP2_x86.exe.3643236F_FC70_11D3_A536_0090278A1BB8 NetFx20SP2_x86.exe FL_NetFx20SP2_x64.3643236F_FC70_11D3_A536_0090278A1BB8" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23372/" ]
192,109
<p>So what I'm looking for here is something like PHP's <a href="http://us2.php.net/print_r" rel="noreferrer">print_r</a> function.</p> <p>This is so I can debug my scripts by seeing what's the state of the object in question.</p>
[ { "answer_id": 192116, "author": "Joe Skora", "author_id": 14057, "author_profile": "https://Stackoverflow.com/users/14057", "pm_score": 5, "selected": false, "text": ">>> import sys\n>>> dir(sys)\n['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdo\nt__', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder\n, 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'exc_clear', 'exc_info'\n 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval', 'getdefault\nncoding', 'getfilesystemencoding', 'getrecursionlimit', 'getrefcount', 'getwindowsversion', 'he\nversion', 'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_\nache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setprofile', 'setrecursionlimit\n, 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoption\n', 'winver']\n>>>\n >>> help(sys)\nHelp on built-in module sys:\n\nNAME\n sys\n\nFILE\n (built-in)\n\nMODULE DOCS\n http://www.python.org/doc/current/lib/module-sys.html\n\nDESCRIPTION\n This module provides access to some objects used or maintained by the\n interpreter and to functions that interact strongly with the interpreter.\n\n Dynamic objects:\n\n argv -- command line arguments; argv[0] is the script pathname if known\n" }, { "answer_id": 192184, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 8, "selected": false, "text": "def dump(obj):\n for attr in dir(obj):\n print(\"obj.%s = %r\" % (attr, getattr(obj, attr)))\n" }, { "answer_id": 192207, "author": "eduffy", "author_id": 7536, "author_profile": "https://Stackoverflow.com/users/7536", "pm_score": 7, "selected": false, "text": "dir __dict__ class O:\n def __init__ (self):\n self.value = 3\n\no = O()\n >>> o.__dict__\n\n{'value': 3}\n" }, { "answer_id": 192365, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 11, "selected": true, "text": "dir() vars() inspect __builtins__ >>> l = dir(__builtins__)\n>>> d = __builtins__.__dict__\n >>> print l\n['ArithmeticError', 'AssertionError', 'AttributeError',...\n >>> from pprint import pprint\n>>> pprint(l)\n['ArithmeticError',\n 'AssertionError',\n 'AttributeError',\n 'BaseException',\n 'DeprecationWarning',\n...\n\n>>> pprint(d, indent=2)\n{ 'ArithmeticError': <type 'exceptions.ArithmeticError'>,\n 'AssertionError': <type 'exceptions.AssertionError'>,\n 'AttributeError': <type 'exceptions.AttributeError'>,\n...\n '_': [ 'ArithmeticError',\n 'AssertionError',\n 'AttributeError',\n 'BaseException',\n 'DeprecationWarning',\n...\n (Pdb) pp vars()\n{'__builtins__': {'ArithmeticError': <type 'exceptions.ArithmeticError'>,\n 'AssertionError': <type 'exceptions.AssertionError'>,\n 'AttributeError': <type 'exceptions.AttributeError'>,\n 'BaseException': <type 'exceptions.BaseException'>,\n 'BufferError': <type 'exceptions.BufferError'>,\n ...\n 'zip': <built-in function zip>},\n '__file__': 'pass.py',\n '__name__': '__main__'}\n" }, { "answer_id": 193539, "author": "Jeremy Cantrell", "author_id": 18866, "author_profile": "https://Stackoverflow.com/users/18866", "pm_score": 10, "selected": false, "text": "vars() pprint() from pprint import pprint\npprint(vars(your_object))\n" }, { "answer_id": 193808, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 5, "selected": false, "text": ">>> obj # in an interpreter\n print repr(obj) # in a script\n print obj\n __str__ __repr__ __repr__(self) repr() __str__() __repr__() __str__(self) str() __repr__()" }, { "answer_id": 193827, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 3, "selected": false, "text": "#!/usr/bin/python\nimport sys\nif len(sys.argv) > 2:\n module, metaklass = sys.argv[1:3]\n m = __import__(module, globals(), locals(), [metaklass])\n __metaclass__ = getattr(m, metaklass)\n\nclass Data:\n def __init__(self):\n self.num = 38\n self.lst = ['a','b','c']\n self.str = 'spam'\n dumps = lambda self: repr(self)\n __str__ = lambda self: self.dumps()\n\ndata = Data()\nprint data\n <__main__.Data instance at 0x00A052D8>\n <?xml version=\"1.0\"?>\n<!DOCTYPE PyObject SYSTEM \"PyObjects.dtd\">\n<PyObject module=\"__main__\" class=\"Data\" id=\"11038416\">\n<attr name=\"lst\" type=\"list\" id=\"11196136\" >\n <item type=\"string\" value=\"a\" />\n <item type=\"string\" value=\"b\" />\n <item type=\"string\" value=\"c\" />\n</attr>\n<attr name=\"num\" type=\"numeric\" value=\"38\" />\n<attr name=\"str\" type=\"string\" value=\"spam\" />\n</PyObject>\n" }, { "answer_id": 205037, "author": "William McVey", "author_id": 27642, "author_profile": "https://Stackoverflow.com/users/27642", "pm_score": 4, "selected": false, "text": "__dict__ dir() dir() __dict__ inspect" }, { "answer_id": 17105170, "author": "Michael Thamm", "author_id": 1964121, "author_profile": "https://Stackoverflow.com/users/1964121", "pm_score": 2, "selected": false, "text": "for key,value in obj.__dict__.iteritems():\n print key,value\n" }, { "answer_id": 17372369, "author": "DaOneTwo", "author_id": 2063339, "author_profile": "https://Stackoverflow.com/users/2063339", "pm_score": 2, "selected": false, "text": "DO = DemoObject()\n\nitemDir = DO.__dict__\n\nfor i in itemDir:\n print '{0} : {1}'.format(i, itemDir[i])\n" }, { "answer_id": 24435471, "author": "Clark", "author_id": 264391, "author_profile": "https://Stackoverflow.com/users/264391", "pm_score": 2, "selected": false, "text": "from bson import json_util\nimport json\n\nprint(json.dumps(myObject, default=json_util.default, sort_keys=True, indent=4, separators=(',', ': ')))\n" }, { "answer_id": 24739571, "author": "32ndghost", "author_id": 3837425, "author_profile": "https://Stackoverflow.com/users/3837425", "pm_score": 3, "selected": false, "text": "from pprint import pprint\n\ndef print_r(the_object):\n print (\"CLASS: \", the_object.__class__.__name__, \" (BASE CLASS: \", the_object.__class__.__bases__,\")\")\n pprint(vars(the_object))\n" }, { "answer_id": 27094448, "author": "Adam Cath", "author_id": 1026601, "author_profile": "https://Stackoverflow.com/users/1026601", "pm_score": 4, "selected": false, "text": "__str__ import json\nprint(json.dumps(YOUR_OBJECT, \n default=lambda obj: vars(obj),\n indent=1))\n" }, { "answer_id": 35804583, "author": "wisbucky", "author_id": 1081043, "author_profile": "https://Stackoverflow.com/users/1081043", "pm_score": 3, "selected": false, "text": "import jsonpickle # pip install jsonpickle\nimport json\nimport yaml # pip install pyyaml\n\nserialized = jsonpickle.encode(obj, max_depth=2) # max_depth is optional\nprint json.dumps(json.loads(serialized), indent=4)\nprint yaml.dump(yaml.load(serialized), indent=4)\n" }, { "answer_id": 35849201, "author": "Slipstream", "author_id": 1866389, "author_profile": "https://Stackoverflow.com/users/1866389", "pm_score": 0, "selected": false, "text": "from flask import Flask\nfrom flask_debugtoolbar import DebugToolbarExtension\n\napp = Flask(__name__)\n\n# the toolbar is only enabled in debug mode:\napp.debug = True\n\n# set a 'SECRET_KEY' to enable the Flask session cookies\napp.config['SECRET_KEY'] = '<replace with a secret key>'\n\ntoolbar = DebugToolbarExtension(app)\n" }, { "answer_id": 38629453, "author": "Symon", "author_id": 3973163, "author_profile": "https://Stackoverflow.com/users/3973163", "pm_score": 3, "selected": false, "text": "from ppretty import ppretty\n\n\nclass A(object):\n s = 5\n\n def __init__(self):\n self._p = 8\n\n @property\n def foo(self):\n return range(10)\n\n\nprint ppretty(A(), show_protected=True, show_static=True, show_properties=True)\n __main__.A(_p = 8, foo = [0, 1, ..., 8, 9], s = 5)\n" }, { "answer_id": 39535966, "author": "Anyany Pan", "author_id": 4683349, "author_profile": "https://Stackoverflow.com/users/4683349", "pm_score": 2, "selected": false, "text": "class(NormalClassNewStyle):\n dicts: {\n },\n lists: [],\n static_props: 1,\n tupl: (1, 2)\n" }, { "answer_id": 43783454, "author": "Evhz", "author_id": 5476782, "author_profile": "https://Stackoverflow.com/users/5476782", "pm_score": -1, "selected": false, "text": "o.keys()\n o.values()\n" }, { "answer_id": 46095449, "author": "Robert Hönig", "author_id": 5723681, "author_profile": "https://Stackoverflow.com/users/5723681", "pm_score": 2, "selected": false, "text": "vars() dir() obj for attr in dir(obj):\n try:\n print(\"obj.{} = {}\".format(attr, getattr(obj, attr)))\n except AttributeError:\n print(\"obj.{} = ?\".format(attr))\n" }, { "answer_id": 46461051, "author": "Nagev", "author_id": 5362795, "author_profile": "https://Stackoverflow.com/users/5362795", "pm_score": 2, "selected": false, "text": "from pprint import pprint\npprint(my_var)\n pprint(vars(my_var)) <someobject.ExampleClass object at 0x7f739267f400> __str__ object vars() vars() TypeError: vars() argument must have __dict__ attribute" }, { "answer_id": 53668012, "author": "prosti", "author_id": 5884955, "author_profile": "https://Stackoverflow.com/users/5884955", "pm_score": 4, "selected": false, "text": "help(your_object) help(dir) If called without an argument, return the names in the current scope.\n Else, return an alphabetized list of names comprising (some of) the attributes\n of the given object, and of attributes reachable from it.\n If the object supplies a method named __dir__, it will be used; otherwise\n the default dir() logic is used and returns:\n for a module object: the module's attributes.\n for a class object: its attributes, and recursively the attributes\n of its bases.\n for any other object: its attributes, its class's attributes, and\n recursively the attributes of its class's base classes.\n help(vars) Without arguments, equivalent to locals().\nWith an argument, equivalent to object.__dict__.\n" }, { "answer_id": 59128615, "author": "Russia Must Remove Putin", "author_id": 541136, "author_profile": "https://Stackoverflow.com/users/541136", "pm_score": 6, "selected": false, "text": "from pprint import pprint\nfrom inspect import getmembers\nfrom types import FunctionType\n\ndef attributes(obj):\n disallowed_names = {\n name for name, value in getmembers(type(obj)) \n if isinstance(value, FunctionType)}\n return {\n name: getattr(obj, name) for name in dir(obj) \n if name[0] != '_' and name not in disallowed_names and hasattr(obj, name)}\n\ndef print_attributes(obj):\n pprint(attributes(obj))\n from pprint import pprint\n\nclass Obj:\n __slots__ = 'foo', 'bar', '__dict__'\n def __init__(self, baz):\n self.foo = ''\n self.bar = 0\n self.baz = baz\n @property\n def quux(self):\n return self.foo * self.bar\n\nobj = Obj('baz')\npprint(vars(obj))\n {'baz': 'baz'}\n vars __dict__ __dict__ vars(obj)['quux'] = 'WHAT?!'\nvars(obj)\n {'baz': 'baz', 'quux': 'WHAT?!'}\n >>> dir(obj)\n['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', 'bar', 'baz', 'foo', 'quux']\n dir inspect.getmembers def api(obj):\n return [name for name in dir(obj) if name[0] != '_']\n __slots__ from types import FunctionType\nfrom inspect import getmembers\n\ndef attrs(obj):\n disallowed_properties = {\n name for name, value in getmembers(type(obj)) \n if isinstance(value, (property, FunctionType))\n }\n return {\n name: getattr(obj, name) for name in api(obj) \n if name not in disallowed_properties and hasattr(obj, name)\n }\n\n >>> attrs(obj)\n{'bar': 0, 'baz': 'baz', 'foo': ''}\n" }, { "answer_id": 60033193, "author": "Carl Cheung", "author_id": 10860732, "author_profile": "https://Stackoverflow.com/users/10860732", "pm_score": 2, "selected": false, "text": "your_obj = YourObj()\nattrs_with_value = {attr: getattr(your_obj, attr) for attr in dir(your_obj)}\n" }, { "answer_id": 68827085, "author": "Vishnu", "author_id": 1779027, "author_profile": "https://Stackoverflow.com/users/1779027", "pm_score": 0, "selected": false, "text": "def getAttributes(obj):\n from pprint import pprint\n from inspect import getmembers\n from types import FunctionType\n \n def attributes(obj):\n disallowed_names = {\n name for name, value in getmembers(type(obj)) \n if isinstance(value, FunctionType)}\n return {\n name for name in dir(obj) \n if name[0] != '_' and name not in disallowed_names and hasattr(obj, name)}\n pprint(attributes(obj))\n" }, { "answer_id": 69186290, "author": "MichaelMoser", "author_id": 3034482, "author_profile": "https://Stackoverflow.com/users/3034482", "pm_score": 0, "selected": false, "text": "__repr__ pip install printex" }, { "answer_id": 69432736, "author": "Allohvk", "author_id": 14642180, "author_profile": "https://Stackoverflow.com/users/14642180", "pm_score": 2, "selected": false, "text": "(str(vars(config)).split(\",\")[1:])\n" }, { "answer_id": 70403363, "author": "yrnr", "author_id": 10272780, "author_profile": "https://Stackoverflow.com/users/10272780", "pm_score": 1, "selected": false, "text": "In [1]: class Aaa():\n...: def __init__(self, name, age):\n...: self.name = name\n...: self.age = age\n...:\nIn [2]: class Bbb(Aaa):\n...: def __init__(self, name, age, job):\n...: super().__init__(name, age)\n...: self.job = job\n...:\nIn [3]: a = Aaa('Pullayya',42)\n\nIn [4]: b = Bbb('Yellayya',41,'Cop')\n\nIn [5]: vars(a)\nOut[5]: {'name': 'Pullayya', 'age': 42}\n\nIn [6]: vars(b)\nOut[6]: {'name': 'Yellayya', 'age': 41, 'job': 'Cop'}\n\nIn [7]: dir(a)\nOut[7]:\n['__class__',\n '__delattr__',\n '__dict__',\n '__dir__',\n '__doc__',\n '__eq__',\n ...\n ...\n '__subclasshook__',\n '__weakref__',\n 'age',\n 'name']\n" }, { "answer_id": 74031715, "author": "Timothy C. Quinn", "author_id": 286807, "author_profile": "https://Stackoverflow.com/users/286807", "pm_score": 0, "selected": false, "text": "# If core==False, ignore __k__ entries\ndef obj_props(obj, core=False) -> list:\n assert not obj is None, f\"obj must not be null (None)\"\n _props = []\n _use_dir=False\n def _add(p):\n if not core and p.find('__') == 0: return\n _props.append(p)\n if hasattr(obj, '__dict__'): \n for p in obj.__dict__.keys(): _add(p)\n elif hasattr(obj, '__slots__'):\n for p in obj.__slots__: _add(p)\n elif hasattr(obj, 'keys'):\n try:\n for p in obj.keys(): _add(p)\n except Exception as ex:\n _props = []\n _use_dir = True\n else:\n _use_dir = True\n if _use_dir:\n # fall back to slow and steady\n for p in dir(obj):\n if not core and p.find('__') == 0: continue\n v = getattr(obj, p)\n v_t = type(v).__name__\n if v_t in ('function', 'method', 'builtin_function_or_method', 'method-wrapper'): continue\n _props.append(p)\n\n return _props\n __dict__ __slots__ dir(obj)" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10708/" ]
192,111
<p>In PHP, I am able to use a normal function as a variable without problem, but I haven't figured out how to use a static method. Am I just missing the right syntax, or is this not possible?</p> <p>(EDIT: the first suggested answer does not seem to work. I've extended my example to show the errors returned.)</p> <pre><code>function foo1($a,$b) { return $a/$b; } class Bar { static function foo2($a,$b) { return $a/$b; } public function UseReferences() { // WORKS FINE: $fn = foo1; print $fn(1,1); // WORKS FINE: print self::foo2(2,1); print Bar::foo2(3,1); // DOES NOT WORK ... error: Undefined class constant 'foo2' //$fn = self::foo2; //print $fn(4,1); // DOES NOT WORK ... error: Call to undefined function self::foo2() //$fn = 'self::foo2'; //print $fn(5,1); // DOES NOT WORK ... error: Call to undefined function Bar::foo2() //$fn = 'Bar::foo2'; //print $fn(5,1); } } $x = new Bar(); $x-&gt;UseReferences(); </code></pre> <p>(I am using PHP v5.2.6 -- does the answer change depending on version too?)</p>
[ { "answer_id": 192123, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 6, "selected": true, "text": "<?php\n\nfunction foo1($a,$b) { return $a/$b; }\n\nclass Bar\n{\n public static function foo2($a,$b) { return $a/$b; }\n\n public function UseReferences()\n {\n $fn = 'foo1';\n echo $fn(6,3);\n\n $fn = array( 'self', 'foo2' );\n print call_user_func( $fn, 6, 2 );\n }\n}\n\n$b = new Bar;\n$b->UseReferences();\n" }, { "answer_id": 192569, "author": "rewbs", "author_id": 6095, "author_profile": "https://Stackoverflow.com/users/6095", "pm_score": 3, "selected": false, "text": "class Bar\n{\n public static function foo2($a,$b) { return $a/$b; }\n\n public function UseReferences()\n {\n $method = 'foo2';\n print Bar::$method(6,2); // works in php 5.2.6\n\n $class = 'Bar';\n print $class::$method(6,2); // works in php 5.3\n }\n}\n\n$b = new Bar;\n$b->UseReferences();\n?>\n" }, { "answer_id": 193888, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<?php\n\nclass Foo{\n static function Calc($x,$y){\n return $x + $y;\n }\n\n public function Test(){\n $z = self::Calc(3,4);\n\n echo(\"z = \".$z);\n }\n}\n\n$foo = new Foo();\n$foo->Test();\n\n?>\n" }, { "answer_id": 3528322, "author": "dwallace", "author_id": 425995, "author_profile": "https://Stackoverflow.com/users/425995", "pm_score": 1, "selected": false, "text": "<?php\n\nclass Foo {\n static function Bar($a, $b) {\n if ($a == $b)\n return 0;\n\n return ($a < $b) ? -1 : 1;\n }\n function RBar($a, $b) {\n if ($a == $b)\n return 0;\n\n return ($a < $b) ? 1 : -1;\n }\n}\n\n$vals = array(3,2,6,4,1);\n$cmpFunc = array('Foo', 'Bar');\nusort($vals, $cmpFunc);\n\n// This would also work:\n$fooInstance = new Foo();\n$cmpFunc = array('fooInstance', 'RBar');\n// Or\n// $cmpFunc = array('fooInstance', 'Bar');\nusort($vals, $cmpFunc);\n\n?>\n" }, { "answer_id": 11114157, "author": "Jiangge Zhang", "author_id": 718453, "author_profile": "https://Stackoverflow.com/users/718453", "pm_score": 3, "selected": false, "text": "<?php\n function foo($method)\n {\n return $method('argument');\n }\n\n foo('YourClass::staticMethod');\n foo('Namespace\\YourClass::staticMethod');\n array('YourClass', 'staticMethod')" }, { "answer_id": 14208014, "author": "hek2mgl", "author_id": 171318, "author_profile": "https://Stackoverflow.com/users/171318", "pm_score": 0, "selected": false, "text": "class Bar {\n\n public static function foo($foo, $bar) {\n return $foo . ' ' . $bar;\n }\n\n\n public function useReferences () {\n $method = new ReflectionMethod($this, 'foo');\n // Note NULL as the first argument for a static call\n $result = $method->invoke(NULL, '123', 'xyz');\n }\n\n}\n" }, { "answer_id": 20649422, "author": "Camilo Martin", "author_id": 124119, "author_profile": "https://Stackoverflow.com/users/124119", "pm_score": 1, "selected": false, "text": "function staticFunctionReference($name)\n{\n return function() use ($name)\n {\n $className = strstr($name, '::', true);\n if (class_exists(__NAMESPACE__.\"\\\\$className\")) $name = __NAMESPACE__.\"\\\\$name\";\n return call_user_func_array($name, func_get_args());\n };\n}\n $foo = staticFunctionReference('Foo::bar');\n$foo('some', 'parameters');\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4540/" ]
192,117
<p>I am writing in C#.<br> How can i find out which methods/functions I can use in an unmanaged dll that doesn't belong to windows?<br> Exmaple : I have some installed software on my computer, it has a dll, and i want to know what my options are as to creating code to connect to that software?</p>
[ { "answer_id": 12727656, "author": "Mike Perrenoud", "author_id": 1195080, "author_profile": "https://Stackoverflow.com/users/1195080", "pm_score": 0, "selected": false, "text": "Object Explorer" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
192,121
<p>I want to use the DateTime.TryParse method to get the datetime value of a string into a Nullable. But when I try this:</p> <pre><code>DateTime? d; bool success = DateTime.TryParse("some date text", out (DateTime)d); </code></pre> <p>the compiler tells me </p> <blockquote> <p>'out' argument is not classified as a variable</p> </blockquote> <p>Not sure what I need to do here. I've also tried: </p> <pre><code>out (DateTime)d.Value </code></pre> <p>and that doesn't work either. Any ideas?</p>
[ { "answer_id": 192146, "author": "Jason Kealey", "author_id": 20893, "author_profile": "https://Stackoverflow.com/users/20893", "pm_score": 8, "selected": true, "text": "DateTime? d=null;\nDateTime d2;\nbool success = DateTime.TryParse(\"some date text\", out d2);\nif (success) d=d2;\n" }, { "answer_id": 192178, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": false, "text": "public static DateTime? TryParse(string text)\n{\n DateTime date;\n if (DateTime.TryParse(text, out date))\n {\n return date;\n }\n else\n {\n return null;\n }\n}\n public static DateTime? TryParse(string text)\n{\n DateTime date;\n return DateTime.TryParse(text, out date) ? date : (DateTime?) null;\n}\n public static DateTime? TryParse(string text) =>\n DateTime.TryParse(text, out var date) ? date : (DateTime?) null;\n" }, { "answer_id": 192214, "author": "Binary Worrier", "author_id": 18797, "author_profile": "https://Stackoverflow.com/users/18797", "pm_score": 4, "selected": false, "text": "Nullable<DateTime> DateTime public bool TryParse(string text, out Nullable<DateTime> nDate)\n{\n DateTime date;\n bool isParsed = DateTime.TryParse(text, out date);\n if (isParsed)\n nDate = new Nullable<DateTime>(date);\n else\n nDate = new Nullable<DateTime>();\n return isParsed;\n}\n" }, { "answer_id": 255045, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "DateTime? d; DateTime dt;\nd = DateTime.TryParse(DateTime.Now.ToString(), out dt)? dt : (DateTime?)null;\n" }, { "answer_id": 1556090, "author": "JStrahl", "author_id": 139271, "author_profile": "https://Stackoverflow.com/users/139271", "pm_score": 1, "selected": false, "text": " public static bool NullableValueTryParse(string text, out int? nInt)\n {\n int value;\n if (int.TryParse(text, out value))\n {\n nInt = value;\n return true;\n }\n else\n {\n nInt = null;\n return false;\n }\n }\n" }, { "answer_id": 11181584, "author": "user2687864", "author_id": 2687864, "author_profile": "https://Stackoverflow.com/users/2687864", "pm_score": 2, "selected": false, "text": "public static class NullableExtensions\n{\n public static bool TryParse(this DateTime? dateTime, string dateString, out DateTime? result)\n {\n DateTime tempDate;\n if(! DateTime.TryParse(dateString,out tempDate))\n {\n result = null;\n return false;\n }\n\n result = tempDate;\n return true;\n\n }\n}\n" }, { "answer_id": 51734376, "author": "monsieurgutix", "author_id": 8548824, "author_profile": "https://Stackoverflow.com/users/8548824", "pm_score": -1, "selected": false, "text": "DateTime? d = DateTime.Parse(\"some valid text\");\n" }, { "answer_id": 58456514, "author": "cpcolella", "author_id": 7724517, "author_profile": "https://Stackoverflow.com/users/7724517", "pm_score": 3, "selected": false, "text": "DateTime? d = DateTime.TryParse(\"some date text\", out DateTime dt) ? dt : null;\n public static bool TryParse(string text, out DateTime? dt)\n{\n if (DateTime.TryParse(text, out DateTime date))\n {\n dt = date;\n return true;\n }\n else\n {\n dt = null;\n return false;\n }\n}\n" }, { "answer_id": 60289544, "author": "user1267054", "author_id": 1267054, "author_profile": "https://Stackoverflow.com/users/1267054", "pm_score": 1, "selected": false, "text": "DateTime? d = DateTime.TryParse(\"text\", out DateTime parseDate) ? parseDate : (DateTime?)null;\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/767/" ]
192,122
<p>This may seem a bit trivial, but I have not been able to figure it out. I am opening up a SPSite and then trying to open up a SPWeb under that SPSite. This is working fine on the VPC, which has the same Site Collection/Site hierarchy, but on production, I get an exception telling me that the URL is invalid when I try the SPSite.OpenWeb(webUrl);. I have verified that the URL’s are correct.</p> <p>The Code:</p> <pre><code> try { SPSite scheduleSiteCol = new SPSite(branchScheduleURL); lblError.Text += Environment.NewLine + "Site Collection URL: " + scheduleSiteCol.Url; SPWeb scheduleWeb = scheduleSiteCol.OpenWeb(branchScheduleURL.Replace(scheduleSiteCol.Url, "")); //&lt;--- Throws error on this line SPList scheduleList = scheduleWeb.GetList(branchScheduleURL + "/lists/" + SPContext.Current.List.Title); return scheduleList.GetItemById(int.Parse(testID)); } catch (System.Exception ex) { lblError.Text += Environment.NewLine + ex.ToString(); return null; } </code></pre> <p>Note:<br> branchScheduleURL is actually the whole URL that includes the URL of the Web as well.</p> <p>The output + exception:</p> <blockquote> <p>Site Collection URL: <a href="https://ourSite.com/mocc" rel="nofollow noreferrer">https://ourSite.com/mocc</a> <br>System.ArgumentException: Invalid URL: /internal/scheduletool. at Microsoft.SharePoint.SPSite.OpenWeb(String strUrl, Boolean requireExactUrl) at Microsoft.SharePoint.SPSite.OpenWeb(String strUrl) at MOCCBranchScheduleListWeb.MOCCBranchScheduleListV3.GetConflictListItem(String branchScheduleURL, String testID)System.NullReferenceException: Object reference not set to an instance of an object. at MOCCBranchScheduleListWeb.MOCCBranchScheduleListV3.CheckForConflicts(String[] cfcFlags1, DateTime startTime, DateTime endTime, String[] cfcFlags2)</p> </blockquote> <p>Note:<br><a href="https://ourSite.com/mocc/internal/scheduletool" rel="nofollow noreferrer">https://ourSite.com/mocc/internal/scheduletool</a> is the SPWeb I am trying to open.</p> <p>Am I missing something obvious? Any help would be greatly appreciated.</p> <p>Thanks.</p>
[ { "answer_id": 198885, "author": "Peter Seale", "author_id": 25911, "author_profile": "https://Stackoverflow.com/users/25911", "pm_score": 0, "selected": false, "text": "string webServerRelativeUrl = site.ServerRelativeUrl + \"/internal/scheduletool\"" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22426/" ]
192,124
<p>I need specifically to load a JPG image that was saved as a blob. GDI+ makes it very easy to retrieve images from files but not from databases...</p>
[ { "answer_id": 192139, "author": "Jason Kealey", "author_id": 20893, "author_profile": "https://Stackoverflow.com/users/20893", "pm_score": 0, "selected": false, "text": "public static Image CreateImage(byte[] pict)\n{\n System.Drawing.Image img = null;\n using (System.IO.MemoryStream stream = new System.IO.MemoryStream(pict)) {\n img = System.Drawing.Image.FromStream(stream);\n }\n return img;\n}\n" }, { "answer_id": 192568, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 3, "selected": true, "text": "shared_ptr<Image> CreateImage(BYTE *blob, size_t blobSize)\n{\n HGLOBAL hMem = ::GlobalAlloc(GMEM_MOVEABLE,blobSize);\n BYTE *pImage = (BYTE*)::GlobalLock(hMem);\n\n for (size_t iBlob = 0; iBlob < blobSize; ++iBlob)\n pImage[iBlob] = blob[iBlob];\n\n ::GlobalUnlock(hMem);\n\n CComPtr<IStream> spStream;\n HRESULT hr = ::CreateStreamOnHGlobal(hMem,TRUE,&spStream);\n\n shared_ptr<Image> image = new Image(spStream); \n return image;\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4880/" ]
192,126
<p>I have a method that needs to accept an array of country names, and return a list of records that match one of those country names. I'm trying this</p> <pre><code>Public Shared Function GetConcessions(ByVal Countries As String()) As IEnumerable Dim CountryList As String = Utility.JoinArray(Countries) ' turns string array into comma-separated string Return (From t In New Db().Concessions _ Where CountryList Like t.Country _ Select t.ConcessionID, t.Title, t.Country) End Function </code></pre> <p>but I get this error</p> <pre><code> *Only arguments that can be evaluated on the client are supported for the LIKE method </code></pre> <p>In plain SQL, this would be simple:</p> <pre><code> Select ConcessionID,Title from Concessions c where @CountryList like '%' + c.Country + '%' </code></pre> <p>How can I achieve this result in Linq to SQL?</p> <h3>Edit (clarification)</h3> <p>I get the same message with string.Contains. It would be fine with</p> <pre><code>t.Country.contains(CountryList) </code></pre> <p>but I need</p> <pre><code>CountryList.contains(t.Country) </code></pre> <p>and that throws the same error I listed above.</p>
[ { "answer_id": 192167, "author": "sepang", "author_id": 25930, "author_profile": "https://Stackoverflow.com/users/25930", "pm_score": 3, "selected": false, "text": "Where SqlMethods.Like(t.country, \"%Sweden%\")\n" }, { "answer_id": 192172, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": true, "text": "List<string> ListOfCountries = new List(Countries)\n\n...ListOfCountries.Contains(t.Country)\n t.Country IN ('yyy','zzz',...)\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
192,128
<p>I am working on an Actionscript 2 project - trying to use the XML object to find a url which is returned as a 302 redirect. Is there a way to do this in actionscript 2?</p> <p>code:</p> <pre><code>var urlone:XML = new XML(); urlone.load("http://mydomain.com/file.py"); urlone.onLoad = function (success) { trace("I want to print the 302 redirect url here, how do I access it?"); }; </code></pre>
[ { "answer_id": 192167, "author": "sepang", "author_id": 25930, "author_profile": "https://Stackoverflow.com/users/25930", "pm_score": 3, "selected": false, "text": "Where SqlMethods.Like(t.country, \"%Sweden%\")\n" }, { "answer_id": 192172, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": true, "text": "List<string> ListOfCountries = new List(Countries)\n\n...ListOfCountries.Contains(t.Country)\n t.Country IN ('yyy','zzz',...)\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26888/" ]
192,134
<p>I have to check some code and run it. I have the URL:</p> <pre><code>svn+ssh://myuser@www.myclient.com/home/svn/project/trunk </code></pre> <p>I have a file with their private key. What do I do to get this code?</p>
[ { "answer_id": 192186, "author": "Swaroop C H", "author_id": 4869, "author_profile": "https://Stackoverflow.com/users/4869", "pm_score": 1, "selected": false, "text": "~/.ssh/ ssh-agent $SHELL; ssh-add; svn co" }, { "answer_id": 192221, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 4, "selected": true, "text": "~/.ssh/id_rsa ~/.ssh/id_dsa ~/.ssh/identity ssh -i path/to/private.key ~/.ssh/authorized_keys" }, { "answer_id": 4455449, "author": "David", "author_id": 136832, "author_profile": "https://Stackoverflow.com/users/136832", "pm_score": 6, "selected": false, "text": "SVN_SSH=\"ssh -i /path/to/key_name\" export SVN_SSH svn commands" }, { "answer_id": 5204421, "author": "Zied", "author_id": 455229, "author_profile": "https://Stackoverflow.com/users/455229", "pm_score": 4, "selected": false, "text": "Host YOUR_SERVER\nIdentityFile YOUR_PRIVATE_KEY_PATH # (ex: ~/.ssh/rsa)\nUser USER_NAME\n" }, { "answer_id": 7084825, "author": "ryatkins", "author_id": 823676, "author_profile": "https://Stackoverflow.com/users/823676", "pm_score": 1, "selected": false, "text": "ssh-keygen -b 1024 -t dsa -f mykey (creates mykey and mkey.pub files)\n chmod 600 mkey (the next step won't run otherwise)\nsvn-add mkey (enter your passphrase)\n svn co svn+ssh://user@server.com/repos/path\n" }, { "answer_id": 12223656, "author": "kay am see", "author_id": 567345, "author_profile": "https://Stackoverflow.com/users/567345", "pm_score": 3, "selected": false, "text": "ssh-add PATH_TO_YOUR_PRIVATE_JEY\ne.g. ssh-add ~/.ssh/myPrivateKey.key\n ssh-add -l\n" }, { "answer_id": 55861200, "author": "Legolas Bloom", "author_id": 5204664, "author_profile": "https://Stackoverflow.com/users/5204664", "pm_score": 0, "selected": false, "text": "SVN_SSH=\"ssh -i /xxx/xxx/id_rsa\" svn checkout svn+ssh://username@svn.xxx.com/data\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/577/" ]
192,153
<p>I would like to access the Rails session secret programmatically (I am using it to generate a sign-on token).</p> <p>Here's what I've come up with:</p> <pre><code>ActionController::Base.session.first[:secret] </code></pre> <p>This returns the session secret. However, every time you call ActionController::Base.session it adds another entry to an array so you end up with something like this:</p> <pre><code>[{:session_key=&gt;"_new_app_session", :secret=&gt;"totally-secret-you-guys"}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}] </code></pre> <p>This strikes me as being no good.</p> <p>Is there a better way to access the session secret?</p>
[ { "answer_id": 192270, "author": "whoisjake", "author_id": 2609, "author_profile": "https://Stackoverflow.com/users/2609", "pm_score": 3, "selected": true, "text": "ActionController::Base.session_options_for(request,params[:action])[:secret]\n" }, { "answer_id": 192298, "author": "Luke Francl", "author_id": 17965, "author_profile": "https://Stackoverflow.com/users/17965", "pm_score": 2, "selected": false, "text": "ActionController::Base.session_options_for(nil,nil)[:secret]\n" }, { "answer_id": 578732, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "ActionController::Base.session_options[:secret]\n" }, { "answer_id": 4859245, "author": "choonkeat", "author_id": 136558, "author_profile": "https://Stackoverflow.com/users/136558", "pm_score": 4, "selected": false, "text": "Rails.configuration.secret_token\nRails.configuration.secret_key_base\n Rails.configuration.secret_token\n ActionController::Base.session_options[:secret]\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17965/" ]
192,200
<p>I have to do a cross site POST (with a redirection, so not using a XMLHTTPRequest), and the base platform is ASP.NET. I don't want to POST all of the controls in the ASP.NET FORM to this other site, so I was considering dynamicly creating a new form element using javascript and just posting that.</p> <p>Has anyone tried this trick? Is there any caveats?</p>
[ { "answer_id": 192212, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": " <asp:TemplateField HeaderText=\"Station\" SortExpression=\"Name\">\n <ItemTemplate>\n <a href=\"javascript:void(0);\" onclick='Redirector.redirect_with_id(\"StationDetail.aspx\", <%# Eval(\"StationID\") != null ? Eval(\"StationID\") : \"-1\" %>);return false;'>\n <asp:Label ID=\"nameLabel\" runat=\"server\" Text='<%# Bind(\"Name\") %>' /></a>\n </ItemTemplate>\n </asp:TemplateField>\n // JScript File\n\n var Redirector = Class.create();\n\n Redirector.prototype = {\n initialize: function(url,target) {\n this.url = url;\n this.parameters = new Hash();\n this.target = target;\n }, \n\n addParameter: function(id,value) {\n this.parameters.set(id, value);\n },\n\n redirect: function() {\n var form = document.createElement('form');\n document.body.appendChild(form);\n form.action = this.url;\n form.method = \"post\";\n if (this.target) {\n form.target = this.target;\n }\n this.parameters.each( function(pair) {\n var input = document.createElement('input');\n input.id = pair.key;\n input.name = pair.key;\n input.value = pair.value;\n input.style.display = 'none';\n form.appendChild(input);\n });\n form.submit();\n }\n};\n\nRedirector.redirect_with_id = function(url,id,target) {\n var redirector = new Redirector( url, target );\n redirector.addParameter( 'ID', id );\n redirector.redirect();\n};\n\nRedirector.redirect_with_tag = function(url,tag_name,tag,target) {\n var redirector = new Redirector( url, target );\n redirector.addParameter( tag_name, tag );\n redirector.redirect();\n};\n\nRedirector.redirect_with_tags = function(url,tag_names_comma_separated,tag_values_comma_separated,target) {\n var redirector = new Redirector( url, target );\n var tags = tag_names_comma_separated.split( \",\" );\n var values = tag_values_comma_separated.split( \",\");\n for( var i = 0; i< tags.length; i++ )\n {\n redirector.addParameter( tags[i], values[i] );\n }\n redirector.redirect();\n};\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
192,203
<p>How do I do this</p> <pre><code>Select top 10 Foo from MyTable </code></pre> <p>in Linq to SQL?</p>
[ { "answer_id": 192209, "author": "David Alpert", "author_id": 8997, "author_profile": "https://Stackoverflow.com/users/8997", "pm_score": 8, "selected": true, "text": "from m in MyTable\ntake 10\nselect m.Foo\n" }, { "answer_id": 192222, "author": "Adam Lassek", "author_id": 1249, "author_profile": "https://Stackoverflow.com/users/1249", "pm_score": 8, "selected": false, "text": "var foo = (from t in MyTable\n select t.Foo).Take(10);\n Dim foo = From t in MyTable _\n Take 10 _\n Select t.Foo\n Take<TSource> source count source count source source" }, { "answer_id": 192224, "author": "amcoder", "author_id": 26898, "author_profile": "https://Stackoverflow.com/users/26898", "pm_score": 5, "selected": false, "text": "Take(int n) var q = query.Take(10);\n" }, { "answer_id": 2022116, "author": "spdrcr911", "author_id": 245727, "author_profile": "https://Stackoverflow.com/users/245727", "pm_score": 3, "selected": false, "text": "var q = from m in MyTable.Take(10)\n select m.Foo\n" }, { "answer_id": 2140235, "author": "Janei Vieira", "author_id": 259315, "author_profile": "https://Stackoverflow.com/users/259315", "pm_score": 2, "selected": false, "text": " var dados = from d in dc.tbl_News.Take(4) \n orderby d.idNews descending\n\n select new \n {\n d.idNews,\n d.titleNews,\n d.textNews,\n d.dateNews,\n d.imgNewsThumb\n };\n" }, { "answer_id": 3462817, "author": "Yann", "author_id": 417714, "author_profile": "https://Stackoverflow.com/users/417714", "pm_score": 4, "selected": false, "text": "var dados = from d in dc.tbl_News.Take(4) \n orderby d.idNews descending\n select new \n {\n d.idNews,\n d.titleNews,\n d.textNews,\n d.dateNews,\n d.imgNewsThumb\n };\n var dados = (from d in dc.tbl_News\n orderby d.idNews descending\n select new \n {\n d.idNews,\n d.titleNews,\n d.textNews,\n d.dateNews,\n d.imgNewsThumb\n }).Take(4);\n" }, { "answer_id": 15425617, "author": "minhnguyen", "author_id": 2138384, "author_profile": "https://Stackoverflow.com/users/2138384", "pm_score": 2, "selected": false, "text": "Array oList = ((from m in dc.Reviews\n join n in dc.Users on m.authorID equals n.userID\n orderby m.createdDate descending\n where m.foodID == _id \n select new\n {\n authorID = m.authorID,\n createdDate = m.createdDate,\n review = m.review1,\n author = n.username,\n profileImgUrl = n.profileImgUrl\n }).Take(2)).ToArray();\n" }, { "answer_id": 16465885, "author": "apollosoftware.org", "author_id": 937222, "author_profile": "https://Stackoverflow.com/users/937222", "pm_score": 0, "selected": false, "text": " var listTest = (from x in table1\n join y in table2\n on x.field1 equals y.field1\n orderby x.id descending\n select new tempList()\n {\n field1 = y.field1,\n active = x.active\n }).Take(10).ToList();\n" }, { "answer_id": 33175323, "author": "Inc33", "author_id": 986419, "author_profile": "https://Stackoverflow.com/users/986419", "pm_score": 5, "selected": false, "text": "var foo = (From t In MyTable\n Select t.Foo).Skip(30).Take(30);\n" }, { "answer_id": 46514591, "author": "Gladson Reis", "author_id": 2304714, "author_profile": "https://Stackoverflow.com/users/2304714", "pm_score": 0, "selected": false, "text": "var noticias = from n in db.Noticias.Take(6)\n where n.Atv == 1\n orderby n.DatHorLan descending\n select n;\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
192,206
<p>Is there a method, or some other light-weight way, to check if a reference is to a disposed object?</p> <p>P.S. - This is just a curiousity (sleep well, not in production code). Yes, I know I can catch the <code>ObjectDisposedException</code> upon trying to access a member of the object.</p>
[ { "answer_id": 192226, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 5, "selected": false, "text": "System.Windows.Forms.Control IsDisposed Dispose()" }, { "answer_id": 211470, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 4, "selected": false, "text": "public class SimpleCleanup : IDisposable\n{\n private bool disposed = false;\n\n public bool IsDisposed\n {\n get\n {\n return disposed;\n }\n }\n\n public SimpleCleanup()\n {\n this.handle = /*...*/;\n }\n\n protected virtual void Dispose(bool disposing)\n {\n if (!disposed)\n {\n if (disposing)\n {\n // free only managed resources here\n }\n\n // free unmanaged resources here\n disposed = true;\n }\n }\n\n public void Dispose()\n {\n Dispose(true);\n }\n}\n" }, { "answer_id": 20446395, "author": "JeffreyDurham", "author_id": 3078486, "author_profile": "https://Stackoverflow.com/users/3078486", "pm_score": -1, "selected": false, "text": "Nothing If anObject IsNot Nothing Then anObject.Dispose()\n Public Sub Example()\n Dim inputPdf As PdfReader = Nothing, inputDoc As Document = Nothing, outputWriter As PdfWriter = Nothing\n\n 'code goes here that may or may not end up using all three objects, \n ' such as when I see that there aren't enough pages in the pdf once I open \n ' the pdfreader and then abort by jumping to my cleanup routine using a goto ..\n\nGoodExit:\n If inputPdf IsNot Nothing Then inputPdf.Dispose()\n If inputDoc IsNot Nothing Then inputDoc.Dispose()\n If outputWriter IsNot Nothing Then outputWriter.Dispose()\nEnd Sub\n Try Finally Private Sub Test()\n Dim aForm As System.Windows.Forms.Form = Nothing\n Try\n Dim sName As String = aForm.Name 'null ref should occur\n Catch ex As Exception\n 'got null exception, no doubt\n Finally\n 'proper disposal occurs, error or no error, initialized or not..\n If aForm IsNot Nothing Then aForm.Dispose()\n End Try\nEnd Sub\n" }, { "answer_id": 33021420, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 1, "selected": false, "text": "Dispose Dispose IDisposable IDisposable Dispose" }, { "answer_id": 52323611, "author": "Moses", "author_id": 5832055, "author_profile": "https://Stackoverflow.com/users/5832055", "pm_score": 1, "selected": false, "text": "class DisposeSample : IDisposable\n{\n DataSet myDataSet = new DataSet();\n private bool _isDisposed;\n\n public DisposeSample()\n {\n // attach dispose event for myDataSet\n myDataSet.Disposed += MyDataSet_Disposed;\n }\n\n private void MyDataSet_Disposed(object sender, EventArgs e)\n {\n //Event triggers when myDataSet is disposed\n _isDisposed = true; // set private bool variable as true \n }\n\n\n public void Dispose()\n {\n if (!_isDisposed) // only dispose if has not been disposed;\n myDataSet?.Dispose(); // only dispose if myDataSet is not null;\n }\n}\n" }, { "answer_id": 68571423, "author": "Asad Mehmood", "author_id": 5152449, "author_profile": "https://Stackoverflow.com/users/5152449", "pm_score": 0, "selected": false, "text": "public static class ObjectExtensions \n{\n public static bool IsDisposed(this object obj)\n {\n try\n {\n obj.ToString();\n return false;\n }\n catch (ObjectDisposedException)\n {\n return true;\n }\n }\n\n}\n\n//Usage\nif(myObject.IsDisposed()){ \n /* Do your Stuff */ \n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9642/" ]
192,213
<p>This is the SQL that I want to accomplish:</p> <pre><code>WHERE domain_nm + '\' + group_nm in ('DOMAINNAME\USERNAME1','DOMAINNAME2\USERNAME2') </code></pre> <p>I can't for the life of me find an appropriate Expression for this. And I don't think I can use two expressions as the domain name and the group name need to be concatenated.</p> <p>Thanks!</p>
[ { "answer_id": 214260, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 2, "selected": false, "text": "criteria\n .Add(Expression.In(\"DomainName\", new string[] { \"DOMAINNAME\", \"DOMAINNAME2\" }))\n .Add(Expression.In(\"GroupName\", new string[] { \"USERNAME1\", \"USERNAME2\" })\n" }, { "answer_id": 219082, "author": "Ahoapap", "author_id": 26896, "author_profile": "https://Stackoverflow.com/users/26896", "pm_score": 2, "selected": false, "text": ".Add(Expression.Sql(String.Format(\"{{alias}}.domain_nm + '\\' + {{alias}}.group_nm in ({0})\", getSqlInString(userGroups))))\n" }, { "answer_id": 33300297, "author": "Ross Jones", "author_id": 1298331, "author_profile": "https://Stackoverflow.com/users/1298331", "pm_score": 0, "selected": false, "text": "Map(x => x.FullName).Formula(\"[domain_nm] + '\\' + [group_nm]\")\n criteria.Add(Expression.In(\"FullName\", new string[] { \"DOMAINNAME\\USERNAME1\", \"DOMAINNAME2\\USERNAME2\" }))\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26896/" ]
192,220
<p>Assume you have a flat table that stores an ordered tree hierarchy:</p> <pre><code>Id Name ParentId Order 1 'Node 1' 0 10 2 'Node 1.1' 1 10 3 'Node 2' 0 20 4 'Node 1.1.1' 2 10 5 'Node 2.1' 3 10 6 'Node 1.2' 1 20 </code></pre> <p>Here's a diagram, where we have <code>[id] Name</code>. Root node 0 is fictional.</p> <pre> [0] ROOT / \ [1] Node 1 [3] Node 2 / \ \ [2] Node 1.1 [6] Node 1.2 [5] Node 2.1 / [4] Node 1.1.1 </pre> <p>What minimalistic approach would you use to output that to HTML (or text, for that matter) as a correctly ordered, correctly indented tree? </p> <p>Assume further you only have basic data structures (arrays and hashmaps), no fancy objects with parent/children references, no ORM, no framework, just your two hands. The table is represented as a result set, which can be accessed randomly. </p> <p>Pseudo code or plain English is okay, this is purely a conceptional question.</p> <p>Bonus question: Is there a fundamentally better way to store a tree structure like this in a RDBMS?</p> <hr> <p><strong>EDITS AND ADDITIONS</strong></p> <p>To answer one commenter's (<a href="https://stackoverflow.com/users/17826/mark-bessey">Mark Bessey</a>'s) question: A root node is not necessary, because it is never going to be displayed anyway. ParentId = 0 is the convention to express "these are top level". The Order column defines how nodes with the same parent are going to be sorted.</p> <p>The "result set" I spoke of can be pictured as an array of hashmaps (to stay in that terminology). For my example was meant to be already there. Some answers go the extra mile and construct it first, but thats okay.</p> <p>The tree can be arbitrarily deep. Each node can have N children. I did not exactly have a "millions of entries" tree in mind, though.</p> <p>Don't mistake my choice of node naming ('Node 1.1.1') for something to rely on. The nodes could equally well be called 'Frank' or 'Bob', no naming structure is implied, this was merely to make it readable.</p> <p><em>I have posted my own solution so you guys can pull it to pieces.</em></p>
[ { "answer_id": 192252, "author": "wcm", "author_id": 2173, "author_profile": "https://Stackoverflow.com/users/2173", "pm_score": 2, "selected": false, "text": "function PrintLevel (int curr, int level)\n //print the indents\n for (i=1; i<=level; i++)\n print a tab\n print curr \\n;\n for each child in the table with a parent of curr\n PrintLevel (child, level+1)\n\n\nfor each elementID where the parentid is zero\n PrintLevel(elementID, 0)\n" }, { "answer_id": 192394, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 3, "selected": false, "text": "children function PrintLine(int pID, int level)\n foreach record where ParentID == pID\n print level*tabs + record-data\n PrintLine(record.ID, level + 1)\n\nPrintLine(0, 0)\n" }, { "answer_id": 192462, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 10, "selected": true, "text": "WITH RECURSIVE MyTree AS (\n SELECT * FROM MyTable WHERE ParentId IS NULL\n UNION ALL\n SELECT m.* FROM MyTABLE AS m JOIN MyTree AS t ON m.ParentId = t.Id\n)\nSELECT * FROM MyTree;\n CREATE TABLE ClosureTable (\n ancestor_id INT NOT NULL REFERENCES FlatTable(id),\n descendant_id INT NOT NULL REFERENCES FlatTable(id),\n PRIMARY KEY (ancestor_id, descendant_id)\n);\n INSERT INTO ClosureTable (ancestor_id, descendant_id) VALUES\n (1,1), (1,2), (1,4), (1,6),\n (2,2), (2,4),\n (3,3), (3,5),\n (4,4),\n (5,5),\n (6,6);\n SELECT f.* \nFROM FlatTable f \n JOIN ClosureTable a ON (f.id = a.descendant_id)\nWHERE a.ancestor_id = 1;\n +----+\n| id |\n+----+\n| 1 | \n| 2 | \n| 4 | \n| 6 | \n+----+\n path_length ClosureTable INSERT INTO ClosureTable (ancestor_id, descendant_id, path_length) VALUES\n (1,1,0), (1,2,1), (1,4,2), (1,6,1),\n (2,2,0), (2,4,1),\n (3,3,0), (3,5,1),\n (4,4,0),\n (5,5,0),\n (6,6,0);\n path_length SELECT f.* \nFROM FlatTable f \n JOIN ClosureTable a ON (f.id = a.descendant_id)\nWHERE a.ancestor_id = 1\n AND path_length = 1;\n\n+----+\n| id |\n+----+\n| 2 | \n| 6 | \n+----+\n name SELECT f.name\nFROM FlatTable f \nJOIN ClosureTable a ON (f.id = a.descendant_id)\nWHERE a.ancestor_id = 1\nORDER BY f.name;\n SELECT f.name, GROUP_CONCAT(b.ancestor_id order by b.path_length desc) AS breadcrumbs\nFROM FlatTable f \nJOIN ClosureTable a ON (f.id = a.descendant_id) \nJOIN ClosureTable b ON (b.descendant_id = a.descendant_id) \nWHERE a.ancestor_id = 1 \nGROUP BY a.descendant_id \nORDER BY f.name\n\n+------------+-------------+\n| name | breadcrumbs |\n+------------+-------------+\n| Node 1 | 1 |\n| Node 1.1 | 1,2 |\n| Node 1.1.1 | 1,2,4 |\n| Node 1.2 | 1,6 |\n+------------+-------------+\n ORDER BY b.path_length, f.name" }, { "answer_id": 192550, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 3, "selected": false, "text": "int Integer public class Node {\n\n private Node parent = null;\n\n private List<Node> children;\n\n private String name;\n\n private int id = -1;\n\n public Node(Node parent, int id, String name) {\n this.parent = parent;\n this.children = new ArrayList<Node>();\n this.name = name;\n this.id = id;\n }\n\n public int getId() {\n return this.id;\n }\n\n public String getName() {\n return this.name;\n }\n\n public void addChild(Node child) {\n children.add(child);\n }\n\n public List<Node> getChildren() {\n return children;\n }\n\n public boolean isRoot() {\n return (this.parent == null);\n }\n\n @Override\n public String toString() {\n return \"id=\" + id + \", name=\" + name + \", parent=\" + parent;\n }\n}\n\npublic class NodeBuilder {\n\n public static Node build(List<Map<String, String>> input) {\n\n // maps id of a node to it's Node object\n Map<Integer, Node> nodeMap = new HashMap<Integer, Node>();\n\n // maps id of a node to the id of it's parent\n Map<Integer, Integer> childParentMap = new HashMap<Integer, Integer>();\n\n // create special 'root' Node with id=0\n Node root = new Node(null, 0, \"root\");\n nodeMap.put(root.getId(), root);\n\n // iterate thru the input\n for (Map<String, String> map : input) {\n\n // expect each Map to have keys for \"id\", \"name\", \"parent\" ... a\n // real implementation would read from a SQL object or resultset\n int id = Integer.parseInt(map.get(\"id\"));\n String name = map.get(\"name\");\n int parent = Integer.parseInt(map.get(\"parent\"));\n\n Node node = new Node(null, id, name);\n nodeMap.put(id, node);\n\n childParentMap.put(id, parent);\n }\n\n // now that each Node is created, setup the child-parent relationships\n for (Map.Entry<Integer, Integer> entry : childParentMap.entrySet()) {\n int nodeId = entry.getKey();\n int parentId = entry.getValue();\n\n Node child = nodeMap.get(nodeId);\n Node parent = nodeMap.get(parentId);\n parent.addChild(child);\n }\n\n return root;\n }\n}\n\npublic class NodePrinter {\n\n static void printRootNode(Node root) {\n printNodes(root, 0);\n }\n\n static void printNodes(Node node, int indentLevel) {\n\n printNode(node, indentLevel);\n // recurse\n for (Node child : node.getChildren()) {\n printNodes(child, indentLevel + 1);\n }\n }\n\n static void printNode(Node node, int indentLevel) {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < indentLevel; i++) {\n sb.append(\"\\t\");\n }\n sb.append(node);\n\n System.out.println(sb.toString());\n }\n\n public static void main(String[] args) {\n\n // setup dummy data\n List<Map<String, String>> resultSet = new ArrayList<Map<String, String>>();\n resultSet.add(newMap(\"1\", \"Node 1\", \"0\"));\n resultSet.add(newMap(\"2\", \"Node 1.1\", \"1\"));\n resultSet.add(newMap(\"3\", \"Node 2\", \"0\"));\n resultSet.add(newMap(\"4\", \"Node 1.1.1\", \"2\"));\n resultSet.add(newMap(\"5\", \"Node 2.1\", \"3\"));\n resultSet.add(newMap(\"6\", \"Node 1.2\", \"1\"));\n\n Node root = NodeBuilder.build(resultSet);\n printRootNode(root);\n\n }\n\n //convenience method for creating our dummy data\n private static Map<String, String> newMap(String id, String name, String parentId) {\n Map<String, String> row = new HashMap<String, String>();\n row.put(\"id\", id);\n row.put(\"name\", name);\n row.put(\"parent\", parentId);\n return row;\n }\n}\n" }, { "answer_id": 192603, "author": "Newtopian", "author_id": 25812, "author_profile": "https://Stackoverflow.com/users/25812", "pm_score": 1, "selected": false, "text": "String[] nodeArray = [L0root, L1child1, L1child2, L2Child1, L2Child2, L2Child3, L2Child4] ...\n" }, { "answer_id": 192874, "author": "Eric Weilnau", "author_id": 13342, "author_profile": "https://Stackoverflow.com/users/13342", "pm_score": 4, "selected": false, "text": "SELECT LPAD(' ', (LEVEL - 1) * 4) || \"Name\" AS \"Name\"\nFROM (SELECT * FROM TMP_NODE ORDER BY \"Order\")\nCONNECT BY PRIOR \"Id\" = \"ParentId\"\nSTART WITH \"Id\" IN (SELECT \"Id\" FROM TMP_NODE WHERE \"ParentId\" = 0)\n WITH [NodeList] (\n [Id]\n , [ParentId]\n , [Level]\n , [Order]\n) AS (\n SELECT [Node].[Id]\n , [Node].[ParentId]\n , 0 AS [Level]\n , CONVERT([varchar](MAX), [Node].[Order]) AS [Order]\n FROM [Node]\n WHERE [Node].[ParentId] = 0\n UNION ALL\n SELECT [Node].[Id]\n , [Node].[ParentId]\n , [NodeList].[Level] + 1 AS [Level]\n , [NodeList].[Order] + '|'\n + CONVERT([varchar](MAX), [Node].[Order]) AS [Order]\n FROM [Node]\n INNER JOIN [NodeList] ON [NodeList].[Id] = [Node].[ParentId]\n) SELECT REPLICATE(' ', [NodeList].[Level] * 4) + [Node].[Name] AS [Name]\nFROM [Node]\n INNER JOIN [NodeList] ON [NodeList].[Id] = [Node].[Id]\nORDER BY [NodeList].[Order]\n" }, { "answer_id": 193140, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 0, "selected": false, "text": "delimiter = '.'\nstack = []\nfor item in items:\n while stack and not item.startswith(stack[-1]+delimiter):\n print \"</div>\"\n stack.pop()\n print \"<div>\"\n print item\n stack.append(item)\n print \" \" * len(stack)\n idx = {}\nidx[0] = []\nfor node in results:\n child_list = []\n idx[node.Id] = child_list\n idx[node.ParentId].append((node, child_list))\n" }, { "answer_id": 194031, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 6, "selected": false, "text": "id lft rght lft rght lft rght level tree_id lft rght lft rght tree_item_iterator" }, { "answer_id": 4506178, "author": "bobobobo", "author_id": 111307, "author_profile": "https://Stackoverflow.com/users/111307", "pm_score": 3, "selected": false, "text": "leftSibling Order" }, { "answer_id": 22376973, "author": "Michał Kołodziejski", "author_id": 3350927, "author_profile": "https://Stackoverflow.com/users/3350927", "pm_score": 5, "selected": false, "text": "CREATE TABLE tree (\n id int NOT NULL,\n name varchar(32) NOT NULL,\n parent_id int NULL,\n node_order int NOT NULL,\n CONSTRAINT tree_pk PRIMARY KEY (id),\n CONSTRAINT tree_tree_fk FOREIGN KEY (parent_id) \n REFERENCES tree (id) NOT DEFERRABLE\n);\n\n\ninsert into tree values\n (0, 'ROOT', NULL, 0),\n (1, 'Node 1', 0, 10),\n (2, 'Node 1.1', 1, 10),\n (3, 'Node 2', 0, 20),\n (4, 'Node 1.1.1', 2, 10),\n (5, 'Node 2.1', 3, 10),\n (6, 'Node 1.2', 1, 20);\n WITH RECURSIVE \ntree_search (id, name, level, parent_id, node_order) AS (\n SELECT \n id, \n name,\n 0,\n parent_id, \n 1 \n FROM tree\n WHERE parent_id is NULL\n\n UNION ALL \n SELECT \n t.id, \n t.name,\n ts.level + 1, \n ts.id, \n t.node_order \n FROM tree t, tree_search ts \n WHERE t.parent_id = ts.id \n) \nSELECT * FROM tree_search \nWHERE level > 0 \nORDER BY level, parent_id, node_order;\n id | name | level | parent_id | node_order \n ----+------------+-------+-----------+------------\n 1 | Node 1 | 1 | 0 | 10\n 3 | Node 2 | 1 | 0 | 20\n 2 | Node 1.1 | 2 | 1 | 10\n 6 | Node 1.2 | 2 | 1 | 20\n 5 | Node 2.1 | 2 | 3 | 10\n 4 | Node 1.1.1 | 3 | 2 | 10\n (6 rows)\n" }, { "answer_id": 42781302, "author": "Konchog", "author_id": 5678653, "author_profile": "https://Stackoverflow.com/users/5678653", "pm_score": 3, "selected": false, "text": "CREATE TABLE `node` (\n `id` int(10) unsigned NOT NULL AUTO_INCREMENT,\n `name` varchar(255) NOT NULL,\n `tw` int(10) unsigned NOT NULL,\n `pa` int(10) unsigned DEFAULT NULL,\n `sz` int(10) unsigned DEFAULT NULL,\n `nc` int(11) GENERATED ALWAYS AS (tw+sz) STORED,\n PRIMARY KEY (`id`),\n KEY `node_tw_index` (`tw`),\n KEY `node_pa_index` (`pa`),\n KEY `node_nc_index` (`nc`),\n CONSTRAINT `node_pa_fk` FOREIGN KEY (`pa`) REFERENCES `node` (`tw`) ON DELETE CASCADE\n)\n +-----+---------+----+------+------+------+\n| id | name | tw | pa | sz | nc |\n+-----+---------+----+------+------+------+\n| 1 | Root | 1 | NULL | 24 | 25 |\n| 2 | A | 2 | 1 | 14 | 16 |\n| 3 | AA | 3 | 2 | 1 | 4 |\n| 4 | AB | 4 | 2 | 7 | 11 |\n| 5 | ABA | 5 | 4 | 1 | 6 |\n| 6 | ABB | 6 | 4 | 3 | 9 |\n| 7 | ABBA | 7 | 6 | 1 | 8 |\n| 8 | ABBB | 8 | 6 | 1 | 9 |\n| 9 | ABC | 9 | 4 | 2 | 11 |\n| 10 | ABCD | 10 | 9 | 1 | 11 |\n| 11 | AC | 11 | 2 | 4 | 15 |\n| 12 | ACA | 12 | 11 | 2 | 14 |\n| 13 | ACAA | 13 | 12 | 1 | 14 |\n| 14 | ACB | 14 | 11 | 1 | 15 |\n| 15 | AD | 15 | 2 | 1 | 16 |\n| 16 | B | 16 | 1 | 1 | 17 |\n| 17 | C | 17 | 1 | 6 | 23 |\n| 359 | C0 | 18 | 17 | 5 | 23 |\n| 360 | C1 | 19 | 18 | 4 | 23 |\n| 361 | C2(res) | 20 | 19 | 3 | 23 |\n| 362 | C3 | 21 | 20 | 2 | 23 |\n| 363 | C4 | 22 | 21 | 1 | 23 |\n| 18 | D | 23 | 1 | 1 | 24 |\n| 19 | E | 24 | 1 | 1 | 25 |\n+-----+---------+----+------+------+------+\n select anc.* from node me,node anc \nwhere me.tw=22 and anc.nc >= me.tw and anc.tw <= me.tw \norder by anc.tw;\n+-----+---------+----+------+------+------+\n| id | name | tw | pa | sz | nc |\n+-----+---------+----+------+------+------+\n| 1 | Root | 1 | NULL | 24 | 25 |\n| 17 | C | 17 | 1 | 6 | 23 |\n| 359 | C0 | 18 | 17 | 5 | 23 |\n| 360 | C1 | 19 | 18 | 4 | 23 |\n| 361 | C2(res) | 20 | 19 | 3 | 23 |\n| 362 | C3 | 21 | 20 | 2 | 23 |\n| 363 | C4 | 22 | 21 | 1 | 23 |\n+-----+---------+----+------+------+------+\n select des.* from node me,node des \nwhere me.tw=17 and des.tw < me.nc and des.tw >= me.tw \norder by des.tw;\n+-----+---------+----+------+------+------+\n| id | name | tw | pa | sz | nc |\n+-----+---------+----+------+------+------+\n| 17 | C | 17 | 1 | 6 | 23 |\n| 359 | C0 | 18 | 17 | 5 | 23 |\n| 360 | C1 | 19 | 18 | 4 | 23 |\n| 361 | C2(res) | 20 | 19 | 3 | 23 |\n| 362 | C3 | 21 | 20 | 2 | 23 |\n| 363 | C4 | 22 | 21 | 1 | 23 |\n+-----+---------+----+------+------+------+\n update node me, node anc set anc.sz = anc.sz - me.sz from \nnode me, node anc where me.tw=18 \nand ((anc.nc >= me.tw and anc.tw < me.pa) or (anc.tw=me.pa));\n update node me, node anc set anc.tw = anc.tw - me.sz from \nnode me, node anc where me.tw=18 and anc.tw >= me.tw;\n update node me, node anc set anc.pa = anc.pa - me.sz from \nnode me, node anc where me.tw=18 and anc.pa >= me.tw;\n" }, { "answer_id": 73741684, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 1, "selected": false, "text": "CREATE TABLE \"ParentIndexTree\" (\n \"id\" INTEGER PRIMARY KEY,\n \"parentId\" INTEGER,\n \"childIndex\" INTEGER NOT NULL,\n \"value\" INTEGER NOT NULL,\n \"name\" TEXT NOT NULL,\n FOREIGN KEY (\"parentId\") REFERENCES \"ParentIndexTree\"(id)\n)\n;\nINSERT INTO \"ParentIndexTree\" VALUES\n (0, NULL, 0, 1, 'one' ),\n (1, 0, 0, 2, 'two' ),\n (2, 0, 1, 3, 'three'),\n (3, 1, 0, 4, 'four' ),\n (4, 1, 1, 5, 'five' )\n;\n 1\n / \\\n 2 3\n / \\\n4 5\n WITH RECURSIVE \"TreeSearch\" (\n \"id\",\n \"parentId\",\n \"childIndex\",\n \"value\",\n \"name\",\n \"prefix\"\n) AS (\n SELECT\n \"id\",\n \"parentId\",\n \"childIndex\",\n \"value\",\n \"name\",\n array[0]\n FROM \"ParentIndexTree\"\n WHERE \"parentId\" IS NULL\n\n UNION ALL\n\n SELECT\n \"child\".\"id\",\n \"child\".\"parentId\",\n \"child\".\"childIndex\",\n \"child\".\"value\",\n \"child\".\"name\",\n array_append(\"parent\".\"prefix\", \"child\".\"childIndex\")\n FROM \"ParentIndexTree\" AS \"child\"\n JOIN \"TreeSearch\" AS \"parent\"\n ON \"child\".\"parentId\" = \"parent\".\"id\"\n)\nSELECT * FROM \"TreeSearch\"\nORDER BY \"prefix\"\n;\n 1 -> 0\n2 -> 0, 0\n3 -> 0, 1\n4 -> 0, 0, 0\n5 -> 0, 0, 1\n 1 -> 0\n2 -> 0, 0\n4 -> 0, 0, 0\n5 -> 0, 0, 1\n3 -> 0, 1\n WITH RECURSIVE \"TreeSearch\" (\n \"id\",\n \"parentId\",\n \"childIndex\",\n \"value\",\n \"name\",\n \"prefix\"\n) AS (\n SELECT\n \"id\",\n \"parentId\",\n \"childIndex\",\n \"value\",\n \"name\",\n '000000'\n FROM \"ParentIndexTree\"\n WHERE \"parentId\" IS NULL\n\n UNION ALL\n\n SELECT\n \"child\".\"id\",\n \"child\".\"parentId\",\n \"child\".\"childIndex\",\n \"child\".\"value\",\n \"child\".\"name\",\n \"parent\".\"prefix\" || printf('%06x', \"child\".\"childIndex\")\n FROM \"ParentIndexTree\" AS \"child\"\n JOIN \"TreeSearch\" AS \"parent\"\n ON \"child\".\"parentId\" = \"parent\".\"id\"\n)\nSELECT * FROM \"TreeSearch\"\nORDER BY \"prefix\"\n;\n __________________________________________________________________________\n| Root 1 |\n| ________________________________ ________________________________ |\n| | Child 1.1 | | Child 1.2 | |\n| | ___________ ___________ | | ___________ ___________ | |\n| | | C 1.1.1 | | C 1.1.2 | | | | C 1.2.1 | | C 1.2.2 | | |\n1 2 3___________4 5___________6 7 8 9___________10 11__________12 13 14\n| |________________________________| |________________________________| |\n|__________________________________________________________________________|\n __________________________________________________________________________\n| Root 1 |\n| ________________________________ _______________________________ |\n| | Child 1.1 | | Child 1.2 | |\n| | ___________ ___________ | | ___________ ___________ | |\n| | | C 1.1.1 | | C 1.1.2 | | | | C 1.2.1 | | C 1.2.2 | | |\n1 2 3___________| 4___________| | 5 6___________| 7___________| | | \n| |________________________________| |_______________________________| |\n|_________________________________________________________________________|\n left < curLeft AND right > curLeft\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18771/" ]
192,228
<p>I'm not much of a coder, but I need to write a simple <em>preg_replace</em> statement in PHP that will help me with a WordPress plugin. Basically, I need some code that will search for a string, pull out the video ID, and return the embed code with the video id inserted into it. </p> <p>In other words, I'm searching for this: </p> <pre><code>[youtube=http://www.youtube.com/watch?v=VIDEO_ID_HERE&amp;hl=en&amp;fs=1] </code></pre> <p>And want to replace it with this (keeping the video id the same): </p> <pre><code>param name="movie" value="http://www.youtube.com/v/VIDEO_ID_HERE&amp;hl=en&amp;fs=1&amp;rel=0 </code></pre> <p>If possible, I'd be forever grateful if you could explain how you've used the various slashes, carets, and Kleene stars in the search pattern, i.e. translate it from grep to English so I can learn. :-)</p> <p>Thanks!<br> Mike</p>
[ { "answer_id": 192239, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "$str = preg_replace('/\\[youtube=.*?v=([a-z0-9_-]+?)&.*?\\]/i', 'param name=\"movie\" value=\"http://www.youtube.com/v/$1&hl=en&fs=1&rel=0', $str);\n\n / - Start of RE\n \\[ - A literal [ ([ is a special character so it needs escaping)\n youtube= - Make sure we've got the right tag\n .*? - Any old rubbish, but don't be greedy; stop when we reach...\n v= - ...this text\n ([a-z0-9_-]+?) - Take some more text (just z-a 0-9 _ and -), and don't be greedy. Capture it using (). This will get put in $1\n &.*?\\] - the junk up to the ending ]\n /i - end the RE and make it case-insensitive for the hell of it\n" }, { "answer_id": 192255, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 0, "selected": false, "text": "$embedString = 'youtube=http://www.youtube.com/watch?v=VIDEO_ID_HERE&hl=en&fs=1';\npreg_match('/v=([^&]*)/',$embedstring,$matches);\necho 'param name=\"movie\" value=\"http://www.youtube.com/v/'.$matches[1].'&hl=en&fs=1&rel=0';\n /v=([^&]*)/ v= $matches [^&] *" }, { "answer_id": 192279, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 0, "selected": false, "text": ".*? [youtube...] [^\\]]*? $str = preg_replace('/\\[youtube=[^\\]]*?v=([^\\]]*?)&[^\\]]*?\\]/i', ...)\n [^\\]] ']'" }, { "answer_id": 192309, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 3, "selected": false, "text": "<?php\n\n$input = \"[youtube=http://www.youtube.com/watch?v=VIDEO_ID_HERE&hl=en&fs=1]\";\n\nif ( preg_match('/\\[youtube=.*?v=(.*?)&.*?\\]/i', $input, $matches ) )\n{\n $sanitizedVideoId = urlencode( strip_tags( $matches[1] ) );\n echo 'param name=\"movie\" value=\"http://www.youtube.com/v/' . $sanitizedVideoId . '&hl=en&fs=1&rel=0';\n} else {\n // Not valid input\n}\n <?php\n\n$input = \"[youtube=http://www.youtube.com/watch?v=\\\"><script src=\\\"http://example.com/xss.js\\\"></script>&hl=en&fs=1]\";\n\n// Is vulnerable to XSS\necho preg_replace('/\\[youtube=.*?v=(.*?)&.*?\\]/i', 'param name=\"movie\" value=\"http://www.youtube.com/v/$1&hl=en&fs=1&rel=0', $input );\necho \"\\n\";\n\n// Prevents XSS\nif ( preg_match('/\\[youtube=.*?v=(.*?)&.*?\\]/i', $input, $matches ) )\n{\n $sanitizedVideoId = urlencode( strip_tags( $matches[1] ) );\n echo 'param name=\"movie\" value=\"http://www.youtube.com/v/' . $sanitizedVideoId . '&hl=en&fs=1&rel=0';\n} else {\n // Not valid input\n}\n" }, { "answer_id": 196364, "author": "Kris", "author_id": 18565, "author_profile": "https://Stackoverflow.com/users/18565", "pm_score": 1, "selected": false, "text": "parse_url($originalURL, PHP-URL-QUERY); $originalURL = 'http://www.youtube.com/watch?v=VIDEO_ID_HERE&hl=en&fs=1';\n\nforeach( parse_url( $originalURL, PHP_URL_QUERY) as $keyvalue )\n{\n if ( strlen( $keyvalue ) > 2 && substr( $keyvalue, 0, 2 ) == 'v=' )\n {\n $videoId = substr( $keyvalue, 2 );\n break;\n }\n}\n\n$newURL = sprintf( 'http://www.youtube.com/v/%s/whatever/else', url_encode( $videoId ) );\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
192,249
<p>Say, I have a script that gets called with this line:</p> <pre><code>./myscript -vfd ./foo/bar/someFile -o /fizz/someOtherFile </code></pre> <p>or this one:</p> <pre><code>./myscript -v -f -d -o /fizz/someOtherFile ./foo/bar/someFile </code></pre> <p>What's the accepted way of parsing this such that in each case (or some combination of the two) <code>$v</code>, <code>$f</code>, and <code>$d</code> will all be set to <code>true</code> and <code>$outFile</code> will be equal to <code>/fizz/someOtherFile</code>?</p>
[ { "answer_id": 192266, "author": "Matt J", "author_id": 18528, "author_profile": "https://Stackoverflow.com/users/18528", "pm_score": 7, "selected": false, "text": "getopt() getopts() #!/bin/bash\necho \"Before getopt\"\nfor i\ndo\n echo $i\ndone\nargs=`getopt abc:d $*`\nset -- $args\necho \"After getopt\"\nfor i\ndo\n echo \"-->$i\"\ndone\n bash-2.05a$ ./g -abc foo\nBefore getopt\n-abc\nfoo\nAfter getopt\n-->-a\n-->-b\n-->-c\n-->foo\n-->--\n" }, { "answer_id": 9518714, "author": "Alek", "author_id": 1243005, "author_profile": "https://Stackoverflow.com/users/1243005", "pm_score": 4, "selected": false, "text": "#!/bin/bash\n#\n\nreadopt='getopts $opts opt;rc=$?;[ \"$rc$opt\" = \"0?\" ]&&exit 1;[ $rc = 0 ]||{ shift $[OPTIND-1];false; }'\n\nopts=vfdo:\n\n# Enumerating options\nwhile eval \"$readopt\"\ndo\n echo OPT:$opt ${OPTARG+OPTARG:$OPTARG}\ndone\n\n# Enumerating arguments\nfor arg\ndo\n echo ARG:$arg\ndone\n ./myscript -v -do /fizz/someOtherFile -f ./foo/bar/someFile\nOPT:v \nOPT:d \nOPT:o OPTARG:/fizz/someOtherFile\nOPT:f \nARG:./foo/bar/someFile\n" }, { "answer_id": 13359121, "author": "guneysus", "author_id": 1766716, "author_profile": "https://Stackoverflow.com/users/1766716", "pm_score": 7, "selected": false, "text": " myscript.sh -p=my_prefix -s=dirname -l=libname #!/bin/bash\nfor i in \"$@\"\ndo\ncase $i in\n -p=*|--prefix=*)\n PREFIX=\"${i#*=}\"\n\n ;;\n -s=*|--searchpath=*)\n SEARCHPATH=\"${i#*=}\"\n ;;\n -l=*|--lib=*)\n DIR=\"${i#*=}\"\n ;;\n --default)\n DEFAULT=YES\n ;;\n *)\n # unknown option\n ;;\nesac\ndone\necho PREFIX = ${PREFIX}\necho SEARCH PATH = ${SEARCHPATH}\necho DIRS = ${DIR}\necho DEFAULT = ${DEFAULT}\n ${i#*=} `sed 's/[^=]*=//' <<< \"$i\"` `echo \"$i\" | sed 's/[^=]*=//'`" }, { "answer_id": 14203146, "author": "Bruno Bronosky", "author_id": 117471, "author_profile": "https://Stackoverflow.com/users/117471", "pm_score": 13, "selected": true, "text": "--option argument cat >/tmp/demo-space-separated.sh <<'EOF'\n#!/bin/bash\n\nPOSITIONAL_ARGS=()\n\nwhile [[ $# -gt 0 ]]; do\n case $1 in\n -e|--extension)\n EXTENSION=\"$2\"\n shift # past argument\n shift # past value\n ;;\n -s|--searchpath)\n SEARCHPATH=\"$2\"\n shift # past argument\n shift # past value\n ;;\n --default)\n DEFAULT=YES\n shift # past argument\n ;;\n -*|--*)\n echo \"Unknown option $1\"\n exit 1\n ;;\n *)\n POSITIONAL_ARGS+=(\"$1\") # save positional arg\n shift # past argument\n ;;\n esac\ndone\n\nset -- \"${POSITIONAL_ARGS[@]}\" # restore positional parameters\n\necho \"FILE EXTENSION = ${EXTENSION}\"\necho \"SEARCH PATH = ${SEARCHPATH}\"\necho \"DEFAULT = ${DEFAULT}\"\necho \"Number files in SEARCH PATH with EXTENSION:\" $(ls -1 \"${SEARCHPATH}\"/*.\"${EXTENSION}\" | wc -l)\n\nif [[ -n $1 ]]; then\n echo \"Last line of file specified as non-opt/last argument:\"\n tail -1 \"$1\"\nfi\nEOF\n\nchmod +x /tmp/demo-space-separated.sh\n\n/tmp/demo-space-separated.sh -e conf -s /etc /etc/hosts\n FILE EXTENSION = conf\nSEARCH PATH = /etc\nDEFAULT =\nNumber files in SEARCH PATH with EXTENSION: 14\nLast line of file specified as non-opt/last argument:\n#93.184.216.34 example.com\n demo-space-separated.sh -e conf -s /etc /etc/hosts\n --option=argument cat >/tmp/demo-equals-separated.sh <<'EOF'\n#!/bin/bash\n\nfor i in \"$@\"; do\n case $i in\n -e=*|--extension=*)\n EXTENSION=\"${i#*=}\"\n shift # past argument=value\n ;;\n -s=*|--searchpath=*)\n SEARCHPATH=\"${i#*=}\"\n shift # past argument=value\n ;;\n --default)\n DEFAULT=YES\n shift # past argument with no value\n ;;\n -*|--*)\n echo \"Unknown option $i\"\n exit 1\n ;;\n *)\n ;;\n esac\ndone\n\necho \"FILE EXTENSION = ${EXTENSION}\"\necho \"SEARCH PATH = ${SEARCHPATH}\"\necho \"DEFAULT = ${DEFAULT}\"\necho \"Number files in SEARCH PATH with EXTENSION:\" $(ls -1 \"${SEARCHPATH}\"/*.\"${EXTENSION}\" | wc -l)\n\nif [[ -n $1 ]]; then\n echo \"Last line of file specified as non-opt/last argument:\"\n tail -1 $1\nfi\nEOF\n\nchmod +x /tmp/demo-equals-separated.sh\n\n/tmp/demo-equals-separated.sh -e=conf -s=/etc /etc/hosts\n FILE EXTENSION = conf\nSEARCH PATH = /etc\nDEFAULT =\nNumber files in SEARCH PATH with EXTENSION: 14\nLast line of file specified as non-opt/last argument:\n#93.184.216.34 example.com\n demo-equals-separated.sh -e=conf -s=/etc /etc/hosts\n ${i#*=} `sed 's/[^=]*=//' <<< \"$i\"` `echo \"$i\" | sed 's/[^=]*=//'` getopt getopt getopts getopts cat >/tmp/demo-getopts.sh <<'EOF'\n#!/bin/sh\n\n# A POSIX variable\nOPTIND=1 # Reset in case getopts has been used previously in the shell.\n\n# Initialize our own variables:\noutput_file=\"\"\nverbose=0\n\nwhile getopts \"h?vf:\" opt; do\n case \"$opt\" in\n h|\\?)\n show_help\n exit 0\n ;;\n v) verbose=1\n ;;\n f) output_file=$OPTARG\n ;;\n esac\ndone\n\nshift $((OPTIND-1))\n\n[ \"${1:-}\" = \"--\" ] && shift\n\necho \"verbose=$verbose, output_file='$output_file', Leftovers: $@\"\nEOF\n\nchmod +x /tmp/demo-getopts.sh\n\n/tmp/demo-getopts.sh -vf /etc/hosts foo bar\n verbose=1, output_file='/etc/hosts', Leftovers: foo bar\n demo-getopts.sh -vf /etc/hosts foo bar\n getopts dash -vf filename getopts -h --help help getopts" }, { "answer_id": 17553853, "author": "Volodymyr M. Lisivka", "author_id": 196559, "author_profile": "https://Stackoverflow.com/users/196559", "pm_score": 2, "selected": false, "text": "#!/bin/bash\n. import.sh log arguments\n\nNAME=\"world\"\n\nparse_arguments \"-n|--name)NAME;S\" -- \"$@\" || {\n error \"Cannot parse command line.\"\n exit 1\n}\n\ninfo \"Hello, $NAME!\"\n" }, { "answer_id": 17740813, "author": "akostadinov", "author_id": 520567, "author_profile": "https://Stackoverflow.com/users/520567", "pm_score": 3, "selected": false, "text": "function waitForWeb () {\n local OPTIND=1 OPTARG OPTION\n local host=localhost port=8080 proto=http\n while getopts \"h:p:r:\" OPTION; do\n case \"$OPTION\" in\n h)\n host=\"$OPTARG\"\n ;;\n p)\n port=\"$OPTARG\"\n ;;\n r)\n proto=\"$OPTARG\"\n ;;\n esac\n done\n...\n}\n" }, { "answer_id": 24121652, "author": "unsynchronized", "author_id": 830899, "author_profile": "https://Stackoverflow.com/users/830899", "pm_score": 4, "selected": false, "text": "command -x=myfilename.ext --another_switch \n command -x myfilename.ext --another_switch\n STD_IN=0\n\nprefix=\"\"\nkey=\"\"\nvalue=\"\"\nfor keyValue in \"$@\"\ndo\n case \"${prefix}${keyValue}\" in\n -i=*|--input_filename=*) key=\"-i\"; value=\"${keyValue#*=}\";; \n -ss=*|--seek_from=*) key=\"-ss\"; value=\"${keyValue#*=}\";;\n -t=*|--play_seconds=*) key=\"-t\"; value=\"${keyValue#*=}\";;\n -|--stdin) key=\"-\"; value=1;;\n *) value=$keyValue;;\n esac\n case $key in\n -i) MOVIE=$(resolveMovie \"${value}\"); prefix=\"\"; key=\"\";;\n -ss) SEEK_FROM=\"${value}\"; prefix=\"\"; key=\"\";;\n -t) PLAY_SECONDS=\"${value}\"; prefix=\"\"; key=\"\";;\n -) STD_IN=${value}; prefix=\"\"; key=\"\";; \n *) prefix=\"${keyValue}=\";;\n esac\ndone\n" }, { "answer_id": 24222736, "author": "Mike Q", "author_id": 1618630, "author_profile": "https://Stackoverflow.com/users/1618630", "pm_score": 1, "selected": false, "text": "myscript.sh -f ./serverlist.txt ./myscript.sh #!/bin/bash\n # --- set the value, if there is inputs, override the defaults.\n\n HOME_FOLDER=\"${HOME}/owned_id_checker\"\n SERVER_FILE_LIST=\"${HOME_FOLDER}/server_list.txt\"\n\n while [[ $# > 1 ]]\n do\n key=\"$1\"\n shift\n \n case $key in\n -i|--inputlist)\n SERVER_FILE_LIST=\"$1\"\n shift\n ;;\n esac\n done\n\n \n echo \"SERVER LIST = ${SERVER_FILE_LIST}\"\n" }, { "answer_id": 24501190, "author": "Shane Day", "author_id": 3792174, "author_profile": "https://Stackoverflow.com/users/3792174", "pm_score": 5, "selected": false, "text": "#!/usr/bin/env bash\n\n# NOTICE: Uncomment if your script depends on bashisms.\n#if [ -z \"$BASH_VERSION\" ]; then bash $0 $@ ; exit $? ; fi\n\necho \"Before\"\nfor i ; do echo - $i ; done\n\n\n# Code template for parsing command line parameters using only portable shell\n# code, while handling both long and short params, handling '-f file' and\n# '-f=file' style param data and also capturing non-parameters to be inserted\n# back into the shell positional parameters.\n\nwhile [ -n \"$1\" ]; do\n # Copy so we can modify it (can't modify $1)\n OPT=\"$1\"\n # Detect argument termination\n if [ x\"$OPT\" = x\"--\" ]; then\n shift\n for OPT ; do\n REMAINS=\"$REMAINS \\\"$OPT\\\"\"\n done\n break\n fi\n # Parse current opt\n while [ x\"$OPT\" != x\"-\" ] ; do\n case \"$OPT\" in\n # Handle --flag=value opts like this\n -c=* | --config=* )\n CONFIGFILE=\"${OPT#*=}\"\n shift\n ;;\n # and --flag value opts like this\n -c* | --config )\n CONFIGFILE=\"$2\"\n shift\n ;;\n -f* | --force )\n FORCE=true\n ;;\n -r* | --retry )\n RETRY=true\n ;;\n # Anything unknown is recorded for later\n * )\n REMAINS=\"$REMAINS \\\"$OPT\\\"\"\n break\n ;;\n esac\n # Check for multiple short options\n # NOTICE: be sure to update this pattern to match valid options\n NEXTOPT=\"${OPT#-[cfr]}\" # try removing single short opt\n if [ x\"$OPT\" != x\"$NEXTOPT\" ] ; then\n OPT=\"-$NEXTOPT\" # multiple short opts, keep going\n else\n break # long form, exit inner loop\n fi\n done\n # Done with that param. move to next\n shift\ndone\n# Set the non-parameters back into the positional parameters ($1 $2 ..)\neval set -- $REMAINS\n\n\necho -e \"After: \\n configfile='$CONFIGFILE' \\n force='$FORCE' \\n retry='$RETRY' \\n remains='$REMAINS'\"\nfor i ; do echo - $i ; done\n" }, { "answer_id": 28488486, "author": "vangorra", "author_id": 1267536, "author_profile": "https://Stackoverflow.com/users/1267536", "pm_score": 4, "selected": false, "text": "./script --arg1=value1 --arg2 value2 --shouldClean\n\n# parse the arguments.\nCOUNTER=0\nARGS=(\"$@\")\nwhile [ $COUNTER -lt $# ]\ndo\n arg=${ARGS[$COUNTER]}\n let COUNTER=COUNTER+1\n nextArg=${ARGS[$COUNTER]}\n\n if [[ $skipNext -eq 1 ]]; then\n echo \"Skipping\"\n skipNext=0\n continue\n fi\n\n argKey=\"\"\n argVal=\"\"\n if [[ \"$arg\" =~ ^\\- ]]; then\n # if the format is: -key=value\n if [[ \"$arg\" =~ \\= ]]; then\n argVal=$(echo \"$arg\" | cut -d'=' -f2)\n argKey=$(echo \"$arg\" | cut -d'=' -f1)\n skipNext=0\n\n # if the format is: -key value\n elif [[ ! \"$nextArg\" =~ ^\\- ]]; then\n argKey=\"$arg\"\n argVal=\"$nextArg\"\n skipNext=1\n\n # if the format is: -key (a boolean flag)\n elif [[ \"$nextArg\" =~ ^\\- ]] || [[ -z \"$nextArg\" ]]; then\n argKey=\"$arg\"\n argVal=\"\"\n skipNext=0\n fi\n # if the format has not flag, just a value.\n else\n argKey=\"\"\n argVal=\"$arg\"\n skipNext=0\n fi\n\n case \"$argKey\" in \n --source-scmurl)\n SOURCE_URL=\"$argVal\"\n ;;\n --dest-scmurl)\n DEST_URL=\"$argVal\"\n ;;\n --version-num)\n VERSION_NUM=\"$argVal\"\n ;;\n -c|--clean)\n CLEAN_BEFORE_START=\"1\"\n ;;\n -h|--help|-help|--h)\n showUsage\n exit\n ;;\n esac\ndone\n" }, { "answer_id": 29754866, "author": "Robert Siemer", "author_id": 825924, "author_profile": "https://Stackoverflow.com/users/825924", "pm_score": 10, "selected": false, "text": "-⁠vfd getopt getopt_long() getopt script.sh -o outFile file1 file2 -v getopts = script.sh --outfile=fileOut --infile fileIn -vfd -oOutfile -vfdoOutfile getopt --test getopt getopts myscript -vfd ./foo/bar/someFile -o /fizz/someOtherFile\nmyscript -v -f -d -o/fizz/someOtherFile -- ./foo/bar/someFile\nmyscript --verbose --force --debug ./foo/bar/someFile -o/fizz/someOtherFile\nmyscript --output=/fizz/someOtherFile ./foo/bar/someFile -vfd\nmyscript ./foo/bar/someFile -df -v --output /fizz/someOtherFile\n verbose: y, force: y, debug: y, in: ./foo/bar/someFile, out: /fizz/someOtherFile\n myscript #!/bin/bash\n# More safety, by turning some bugs into errors.\n# Without `errexit` you don’t need ! and can replace\n# ${PIPESTATUS[0]} with a simple $?, but I prefer safety.\nset -o errexit -o pipefail -o noclobber -o nounset\n\n# -allow a command to fail with !’s side effect on errexit\n# -use return value from ${PIPESTATUS[0]}, because ! hosed $?\n! getopt --test > /dev/null \nif [[ ${PIPESTATUS[0]} -ne 4 ]]; then\n echo 'I’m sorry, `getopt --test` failed in this environment.'\n exit 1\nfi\n\n# option --output/-o requires 1 argument\nLONGOPTS=debug,force,output:,verbose\nOPTIONS=dfo:v\n\n# -regarding ! and PIPESTATUS see above\n# -temporarily store output to be able to check for errors\n# -activate quoting/enhanced mode (e.g. by writing out “--options”)\n# -pass arguments only via -- \"$@\" to separate them correctly\n! PARSED=$(getopt --options=$OPTIONS --longoptions=$LONGOPTS --name \"$0\" -- \"$@\")\nif [[ ${PIPESTATUS[0]} -ne 0 ]]; then\n # e.g. return value is 1\n # then getopt has complained about wrong arguments to stdout\n exit 2\nfi\n# read getopt’s output this way to handle the quoting right:\neval set -- \"$PARSED\"\n\nd=n f=n v=n outFile=-\n# now enjoy the options in order and nicely split until we see --\nwhile true; do\n case \"$1\" in\n -d|--debug)\n d=y\n shift\n ;;\n -f|--force)\n f=y\n shift\n ;;\n -v|--verbose)\n v=y\n shift\n ;;\n -o|--output)\n outFile=\"$2\"\n shift 2\n ;;\n --)\n shift\n break\n ;;\n *)\n echo \"Programming error\"\n exit 3\n ;;\n esac\ndone\n\n# handle non-option arguments\nif [[ $# -ne 1 ]]; then\n echo \"$0: A single input file is required.\"\n exit 4\nfi\n\necho \"verbose: $v, force: $f, debug: $d, in: $1, out: $outFile\"\n sudo port install getopt exec()" }, { "answer_id": 29886343, "author": "Mark Fox", "author_id": 934195, "author_profile": "https://Stackoverflow.com/users/934195", "pm_score": 2, "selected": false, "text": "./script.sh dumbo 127.0.0.1 --environment=production -q -d\n./script.sh dumbo --environment=production 127.0.0.1 --quiet -d\n # process flags\npointer=1\nwhile [[ $pointer -le $# ]]; do\n param=${!pointer}\n if [[ $param != \"-\"* ]]; then ((pointer++)) # not a parameter flag so advance pointer\n else\n case $param in\n # paramter-flags with arguments\n -e=*|--environment=*) environment=\"${param#*=}\";;\n --another=*) another=\"${param#*=}\";;\n\n # binary flags\n -q|--quiet) quiet=true;;\n -d) debug=true;;\n esac\n\n # splice out pointer frame from positional list\n [[ $pointer -gt 1 ]] \\\n && set -- ${@:1:((pointer - 1))} ${@:((pointer + 1)):$#} \\\n || set -- ${@:((pointer + 1)):$#};\n fi\ndone\n\n# positional remain\nnode_name=$1\nip_address=$2\n --flag=value --flag value ./script.sh dumbo 127.0.0.1 --environment production -q -d\n ./script.sh dumbo --environment production 127.0.0.1 --quiet -d\n # process flags\npointer=1\nwhile [[ $pointer -le $# ]]; do\n if [[ ${!pointer} != \"-\"* ]]; then ((pointer++)) # not a parameter flag so advance pointer\n else\n param=${!pointer}\n ((pointer_plus = pointer + 1))\n slice_len=1\n\n case $param in\n # paramter-flags with arguments\n -e|--environment) environment=${!pointer_plus}; ((slice_len++));;\n --another) another=${!pointer_plus}; ((slice_len++));;\n\n # binary flags\n -q|--quiet) quiet=true;;\n -d) debug=true;;\n esac\n\n # splice out pointer frame from positional list\n [[ $pointer -gt 1 ]] \\\n && set -- ${@:1:((pointer - 1))} ${@:((pointer + $slice_len)):$#} \\\n || set -- ${@:((pointer + $slice_len)):$#};\n fi\ndone\n\n# positional remain\nnode_name=$1\nip_address=$2\n" }, { "answer_id": 31024664, "author": "galmok", "author_id": 946979, "author_profile": "https://Stackoverflow.com/users/946979", "pm_score": 3, "selected": false, "text": "-s p1\n--stage p1\n-w somefolder\n--workfolder somefolder\n-sw p1 somefolder\n-e=hello\n -s--workfolder p1 somefolder\n-se=hello p1\n-swe=hello p1 somefolder\n while [[ $# > 0 ]]\ndo\n key=\"$1\"\n while [[ ${key+x} ]]\n do\n case $key in\n -s*|--stage)\n STAGE=\"$2\"\n shift # option has parameter\n ;;\n -w*|--workfolder)\n workfolder=\"$2\"\n shift # option has parameter\n ;;\n -e=*)\n EXAMPLE=\"${key#*=}\"\n break # option has been fully handled\n ;;\n *)\n # unknown option\n echo Unknown option: $key #1>&2\n exit 10 # either this: my preferred way to handle unknown options\n break # or this: do this to signal the option has been handled (if exit isn't used)\n ;;\n esac\n # prepare for next option in this key, if any\n [[ \"$key\" = -? || \"$key\" == --* ]] && unset key || key=\"${key/#-?/-}\"\n done\n shift # option(s) fully processed, proceed to next input argument\ndone\n" }, { "answer_id": 31443098, "author": "bronson", "author_id": 912602, "author_profile": "https://Stackoverflow.com/users/912602", "pm_score": 7, "selected": false, "text": "while [ \"$#\" -gt 0 ]; do\n case \"$1\" in\n -n) name=\"$2\"; shift 2;;\n -p) pidfile=\"$2\"; shift 2;;\n -l) logfile=\"$2\"; shift 2;;\n\n --name=*) name=\"${1#*=}\"; shift 1;;\n --pidfile=*) pidfile=\"${1#*=}\"; shift 1;;\n --logfile=*) logfile=\"${1#*=}\"; shift 1;;\n --name|--pidfile|--logfile) echo \"$1 requires an argument\" >&2; exit 1;;\n \n -*) echo \"unknown option: $1\" >&2; exit 1;;\n *) handle_argument \"$1\"; shift 1;;\n esac\ndone\n -n arg --name=arg" }, { "answer_id": 32965658, "author": "Masadow", "author_id": 2836899, "author_profile": "https://Stackoverflow.com/users/2836899", "pm_score": 1, "selected": false, "text": "#!/bin/bash\n\necho $@\n\nPARAMS=()\nSOFT=0\nSKIP=()\nfor i in \"$@\"\ndo\ncase $i in\n -n=*|--skip=*)\n SKIP+=(\"${i#*=}\")\n ;;\n -s|--soft)\n SOFT=1\n ;;\n *)\n # unknown option\n PARAMS+=(\"$i\")\n ;;\nesac\ndone\necho \"SKIP = ${SKIP[@]}\"\necho \"SOFT = $SOFT\"\n echo \"Parameters:\"\n echo ${PARAMS[@]}\n $ ./test.sh parameter -s somefile --skip=.c --skip=.obj\nparameter -s somefile --skip=.c --skip=.obj\nSKIP = .c .obj\nSOFT = 1\nParameters:\nparameter somefile\n" }, { "answer_id": 33191693, "author": "phk", "author_id": 2261442, "author_profile": "https://Stackoverflow.com/users/2261442", "pm_score": 1, "selected": false, "text": "getopt(s) tar -xzf foo.tar.gz tar -x -z -f foo.tar.gz tar ps #!/bin/sh\n\necho\necho \"POSIX-compliant getopt(s)-free old-style-supporting option parser from phk@[se.unix]\"\necho\n\nprint_usage() {\n echo \"Usage:\n\n $0 {a|b|c} [ARG...]\n\nOptions:\n\n --aaa-0-args\n -a\n Option without arguments.\n\n --bbb-1-args ARG\n -b ARG\n Option with one argument.\n\n --ccc-2-args ARG1 ARG2\n -c ARG1 ARG2\n Option with two arguments.\n\n\" >&2\n}\n\nif [ $# -le 0 ]; then\n print_usage\n exit 1\nfi\n\nopt=\nwhile :; do\n\n if [ $# -le 0 ]; then\n\n # no parameters remaining -> end option parsing\n break\n\n elif [ ! \"$opt\" ]; then\n\n # we are at the beginning of a fresh block\n # remove optional leading hyphen and strip trailing whitespaces\n opt=$(echo \"$1\" | sed 's/^-\\?\\([a-zA-Z0-9\\?-]*\\)/\\1/')\n\n fi\n\n # get the first character -> check whether long option\n first_chr=$(echo \"$opt\" | awk '{print substr($1, 1, 1)}')\n [ \"$first_chr\" = - ] && long_option=T || long_option=F\n\n # note to write the options here with a leading hyphen less\n # also do not forget to end short options with a star\n case $opt in\n\n -)\n\n # end of options\n shift\n break\n ;;\n\n a*|-aaa-0-args)\n\n echo \"Option AAA activated!\"\n ;;\n\n b*|-bbb-1-args)\n\n if [ \"$2\" ]; then\n echo \"Option BBB with argument '$2' activated!\"\n shift\n else\n echo \"BBB parameters incomplete!\" >&2\n print_usage\n exit 1\n fi\n ;;\n\n c*|-ccc-2-args)\n\n if [ \"$2\" ] && [ \"$3\" ]; then\n echo \"Option CCC with arguments '$2' and '$3' activated!\"\n shift 2\n else\n echo \"CCC parameters incomplete!\" >&2\n print_usage\n exit 1\n fi\n ;;\n\n h*|\\?*|-help)\n\n print_usage\n exit 0\n ;;\n\n *)\n\n if [ \"$long_option\" = T ]; then\n opt=$(echo \"$opt\" | awk '{print substr($1, 2)}')\n else\n opt=$first_chr\n fi\n printf 'Error: Unknown option: \"%s\"\\n' \"$opt\" >&2\n print_usage\n exit 1\n ;;\n\n esac\n\n if [ \"$long_option\" = T ]; then\n\n # if we had a long option then we are going to get a new block next\n shift\n opt=\n\n else\n\n # if we had a short option then just move to the next character\n opt=$(echo \"$opt\" | awk '{print substr($1, 2)}')\n\n # if block is now empty then shift to the next one\n [ \"$opt\" ] || shift\n\n fi\n\ndone\n\necho \"Doing something...\"\n\nexit 0\n tar f tar xzf bar.tar.gz tar xfz bar.tar.gz abc X Y Z -abc X Y Z Option AAA activated!\nOption BBB with argument 'X' activated!\nOption CCC with arguments 'Y' and 'Z' activated!\n -cba Z Y X cba Z Y X -cb-aaa-0-args Z Y X -c-bbb-1-args Z Y X -a --ccc-2-args Z Y -ba X c Z Y b X a -c Z Y -b X -a --ccc-2-args Z Y --bbb-1-args X --aaa-0-args Option CCC with arguments 'Z' and 'Y' activated!\nOption BBB with argument 'X' activated!\nOption AAA activated!\nDoing something...\n --long-with-arg=?* cut head getopts" }, { "answer_id": 33216429, "author": "schily", "author_id": 5298132, "author_profile": "https://Stackoverflow.com/users/5298132", "pm_score": 2, "selected": false, "text": "getopt(1) getopt getopt(1) \"$*\" \"$@\" getopts(1) getopt(3) ksh93 ksh93 Bourne Shell getopts getopts \"f:(file)(input-file)o:(output-file)\" OPTX \"$@\"" }, { "answer_id": 33826763, "author": "Inanc Gumus", "author_id": 115363, "author_profile": "https://Stackoverflow.com/users/115363", "pm_score": 9, "selected": false, "text": "#!/bin/bash\n\nwhile [[ \"$#\" -gt 0 ]]; do\n case $1 in\n -t|--target) target=\"$2\"; shift ;;\n -u|--uglify) uglify=1 ;;\n *) echo \"Unknown parameter passed: $1\"; exit 1 ;;\n esac\n shift\ndone\n\necho \"Where to deploy: $target\"\necho \"Should uglify : $uglify\"\n ./deploy.sh -t dev -u\n\n# OR:\n\n./deploy.sh --target dev --uglify\n" }, { "answer_id": 38153758, "author": "Oleksii Chekulaiev", "author_id": 1359178, "author_profile": "https://Stackoverflow.com/users/1359178", "pm_score": 4, "selected": false, "text": "parse_params --all -all all=all show_use parse_params -d 1 --any-param -anyparam eval $(parse_params \"$@\") #!/bin/bash\n\n# Universal Bash parameter parsing\n# Parse equal sign separated params into named local variables\n# Standalone named parameter value will equal its param name (--force creates variable $force==\"force\")\n# Parses multi-valued named params into an array (--path=path1 --path=path2 creates ${path[*]} array)\n# Puts un-named params as-is into ${ARGV[*]} array\n# Additionally puts all named params as-is into ${ARGN[*]} array\n# Additionally puts all standalone \"option\" params as-is into ${ARGO[*]} array\n# @author Oleksii Chekulaiev\n# @version v1.4.1 (Jul-27-2018)\nparse_params ()\n{\n local existing_named\n local ARGV=() # un-named params\n local ARGN=() # named params\n local ARGO=() # options (--params)\n echo \"local ARGV=(); local ARGN=(); local ARGO=();\"\n while [[ \"$1\" != \"\" ]]; do\n # Escape asterisk to prevent bash asterisk expansion, and quotes to prevent string breakage\n _escaped=${1/\\*/\\'\\\"*\\\"\\'}\n _escaped=${_escaped//\\'/\\\\\\'}\n _escaped=${_escaped//\\\"/\\\\\\\"}\n # If equals delimited named parameter\n nonspace=\"[^[:space:]]\"\n if [[ \"$1\" =~ ^${nonspace}${nonspace}*=..* ]]; then\n # Add to named parameters array\n echo \"ARGN+=('$_escaped');\"\n # key is part before first =\n local _key=$(echo \"$1\" | cut -d = -f 1)\n # Just add as non-named when key is empty or contains space\n if [[ \"$_key\" == \"\" || \"$_key\" =~ \" \" ]]; then\n echo \"ARGV+=('$_escaped');\"\n shift\n continue\n fi\n # val is everything after key and = (protect from param==value error)\n local _val=\"${1/$_key=}\"\n # remove dashes from key name\n _key=${_key//\\-}\n # skip when key is empty\n # search for existing parameter name\n if (echo \"$existing_named\" | grep \"\\b$_key\\b\" >/dev/null); then\n # if name already exists then it's a multi-value named parameter\n # re-declare it as an array if needed\n if ! (declare -p _key 2> /dev/null | grep -q 'declare \\-a'); then\n echo \"$_key=(\\\"\\$$_key\\\");\"\n fi\n # append new value\n echo \"$_key+=('$_val');\"\n else\n # single-value named parameter\n echo \"local $_key='$_val';\"\n existing_named=\" $_key\"\n fi\n # If standalone named parameter\n elif [[ \"$1\" =~ ^\\-${nonspace}+ ]]; then\n # remove dashes\n local _key=${1//\\-}\n # Just add as non-named when key is empty or contains space\n if [[ \"$_key\" == \"\" || \"$_key\" =~ \" \" ]]; then\n echo \"ARGV+=('$_escaped');\"\n shift\n continue\n fi\n # Add to options array\n echo \"ARGO+=('$_escaped');\"\n echo \"local $_key=\\\"$_key\\\";\"\n # non-named parameter\n else\n # Escape asterisk to prevent bash asterisk expansion\n _escaped=${1/\\*/\\'\\\"*\\\"\\'}\n echo \"ARGV+=('$_escaped');\"\n fi\n shift\n done\n}\n\n#--------------------------- DEMO OF THE USAGE -------------------------------\n\nshow_use ()\n{\n eval $(parse_params \"$@\")\n # --\n echo \"${ARGV[0]}\" # print first unnamed param\n echo \"${ARGV[1]}\" # print second unnamed param\n echo \"${ARGN[0]}\" # print first named param\n echo \"${ARG0[0]}\" # print first option param (--force)\n echo \"$anyparam\" # print --anyparam value\n echo \"$k\" # print k=5 value\n echo \"${multivalue[0]}\" # print first value of multi-value\n echo \"${multivalue[1]}\" # print second value of multi-value\n [[ \"$force\" == \"force\" ]] && echo \"\\$force is set so let the force be with you\"\n}\n\nshow_use \"param 1\" --anyparam=\"my value\" param2 k=5 --force --multi-value=test1 --multi-value=test2\n" }, { "answer_id": 38829557, "author": "Daniel Bigham", "author_id": 226539, "author_profile": "https://Stackoverflow.com/users/226539", "pm_score": 1, "selected": false, "text": "boolean_arg=\"\"\narg_with_value=\"\"\n\nwhile [[ $# -gt 0 ]]\ndo\nkey=\"$1\"\ncase $key in\n -b|--boolean-arg)\n boolean_arg=true\n shift\n ;;\n -a|--arg-with-value)\n arg_with_value=\"$2\"\n shift\n shift\n ;;\n -*)\n echo \"Unknown option: $1\"\n exit 1\n ;;\n *)\n arg_num=$(( $arg_num + 1 ))\n case $arg_num in\n 1)\n first_normal_arg=\"$1\"\n shift\n ;;\n 2)\n second_normal_arg=\"$1\"\n shift\n ;;\n *)\n bad_args=TRUE\n esac\n ;;\nesac\ndone\n\n# Handy to have this here when adding arguments to\n# see if they're working. Just edit the '0' to be '1'.\nif [[ 0 == 1 ]]; then\n echo \"first_normal_arg: $first_normal_arg\"\n echo \"second_normal_arg: $second_normal_arg\"\n echo \"boolean_arg: $boolean_arg\"\n echo \"arg_with_value: $arg_with_value\"\n exit 0\nfi\n\nif [[ $bad_args == TRUE || $arg_num < 2 ]]; then\n echo \"Usage: $(basename \"$0\") <first-normal-arg> <second-normal-arg> [--boolean-arg] [--arg-with-value VALUE]\"\n exit 1\nfi\n" }, { "answer_id": 39198204, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "./myscript -flag flagvariable -otherflag flagvar2 ./myscript -flag flagvariable -otherflag flagvar2\necho $flag $otherflag\nflagvariable flagvar2\n #!/usr/bin/env bash\n#shebang.io\nvalidflags=\"rate time number\"\ncount=1\nfor arg in $@\ndo\n match=0\n argval=$1\n for flag in $validflags\n do\n sflag=\"-\"$flag\n if [ \"$argval\" == \"$sflag\" ]\n then\n declare $flag=$2\n match=1\n fi\n done\n if [ \"$match\" == \"1\" ]\n then\n shift 2\n else\n leftovers=$(echo $leftovers $argval)\n shift\n fi\n count=$(($count+1))\ndone\n#Cleanup then restore the leftovers\nshift $#\nset -- $leftovers\n #!/usr/bin/env bash\n#shebang.io\nrate=30\ntime=30\nnumber=30\necho \"all args\n$@\"\nvalidflags=\"rate time number\"\ncount=1\nfor arg in $@\ndo\n match=0\n argval=$1\n# argval=$(echo $@ | cut -d ' ' -f$count)\n for flag in $validflags\n do\n sflag=\"-\"$flag\n if [ \"$argval\" == \"$sflag\" ]\n then\n declare $flag=$2\n match=1\n fi\n done\n if [ \"$match\" == \"1\" ]\n then\n shift 2\n else\n leftovers=$(echo $leftovers $argval)\n shift\n fi\n count=$(($count+1))\ndone\n\n#Cleanup then restore the leftovers\necho \"pre final clear args:\n$@\"\nshift $#\necho \"post final clear args:\n$@\"\nset -- $leftovers\necho \"all post set args:\n$@\"\necho arg1: $1 arg2: $2\n\necho leftovers: $leftovers\necho rate $rate time $time number $number\n #!/usr/bin/env bash\n#shebang.io\nrate=30\ntime=30\nnumber=30\nvalidflags=\"rate time number\"\ncount=1\nfor arg in $@\ndo\n argval=$1\n match=0\n if [ \"${argval:0:1}\" == \"-\" ]\n then\n for flag in $validflags\n do\n sflag=\"-\"$flag\n if [ \"$argval\" == \"$sflag\" ]\n then\n declare $flag=$2\n match=1\n fi\n done\n if [ \"$match\" == \"0\" ]\n then\n echo \"Bad argument: $argval\"\n exit 1\n fi\n shift 2\n else\n leftovers=$(echo $leftovers $argval)\n shift\n fi\n count=$(($count+1))\ndone\n#Cleanup then restore the leftovers\nshift $#\nset -- $leftovers\necho rate $rate time $time number $number\necho leftovers: $leftovers\n" }, { "answer_id": 39376824, "author": "phyatt", "author_id": 999943, "author_profile": "https://Stackoverflow.com/users/999943", "pm_score": 5, "selected": false, "text": "getopt eval HEREDOC shift #!/usr/bin/env bash\n\n# usage function\nfunction usage()\n{\n cat << HEREDOC\n\n Usage: $progname [--num NUM] [--time TIME_STR] [--verbose] [--dry-run]\n\n optional arguments:\n -h, --help show this help message and exit\n -n, --num NUM pass in a number\n -t, --time TIME_STR pass in a time string\n -v, --verbose increase the verbosity of the bash script\n --dry-run do a dry run, dont change any files\n\nHEREDOC\n} \n\n# initialize variables\nprogname=$(basename $0)\nverbose=0\ndryrun=0\nnum_str=\ntime_str=\n\n# use getopt and store the output into $OPTS\n# note the use of -o for the short options, --long for the long name options\n# and a : for any option that takes a parameter\nOPTS=$(getopt -o \"hn:t:v\" --long \"help,num:,time:,verbose,dry-run\" -n \"$progname\" -- \"$@\")\nif [ $? != 0 ] ; then echo \"Error in command line arguments.\" >&2 ; usage; exit 1 ; fi\neval set -- \"$OPTS\"\n\nwhile true; do\n # uncomment the next line to see how shift is working\n # echo \"\\$1:\\\"$1\\\" \\$2:\\\"$2\\\"\"\n case \"$1\" in\n -h | --help ) usage; exit; ;;\n -n | --num ) num_str=\"$2\"; shift 2 ;;\n -t | --time ) time_str=\"$2\"; shift 2 ;;\n --dry-run ) dryrun=1; shift ;;\n -v | --verbose ) verbose=$((verbose + 1)); shift ;;\n -- ) shift; break ;;\n * ) break ;;\n esac\ndone\n\nif (( $verbose > 0 )); then\n\n # print out all the parameters we read in\n cat <<EOM\n num=$num_str\n time=$time_str\n verbose=$verbose\n dryrun=$dryrun\nEOM\nfi\n\n# The rest of your script below\n OPTS=$(getopt -o \"hn:t:v\" --long \"help,num:,time:,verbose,dry-run\" -n \"$progname\" -- \"$@\")\nif [ $? != 0 ] ; then echo \"Error in command line arguments.\" >&2 ; exit 1 ; fi\neval set -- \"$OPTS\"\n\nwhile true; do\n case \"$1\" in\n -h | --help ) usage; exit; ;;\n -n | --num ) num_str=\"$2\"; shift 2 ;;\n -t | --time ) time_str=\"$2\"; shift 2 ;;\n --dry-run ) dryrun=1; shift ;;\n -v | --verbose ) verbose=$((verbose + 1)); shift ;;\n -- ) shift; break ;;\n * ) break ;;\n esac\ndone\n" }, { "answer_id": 39398359, "author": "Ponyboy47", "author_id": 1478580, "author_profile": "https://Stackoverflow.com/users/1478580", "pm_score": 5, "selected": false, "text": "# As long as there is at least one more argument, keep looping\nwhile [[ $# -gt 0 ]]; do\n key=\"$1\"\n case \"$key\" in\n # This is a flag type option. Will catch either -f or --foo\n -f|--foo)\n FOO=1\n ;;\n # Also a flag type option. Will catch either -b or --bar\n -b|--bar)\n BAR=1\n ;;\n # This is an arg value type option. Will catch -o value or --output-file value\n -o|--output-file)\n shift # past the key and to the value\n OUTPUTFILE=\"$1\"\n ;;\n # This is an arg=value type option. Will catch -o=value or --output-file=value\n -o=*|--output-file=*)\n # No need to shift here since the value is part of the same string\n OUTPUTFILE=\"${key#*=}\"\n ;;\n *)\n # Do whatever you want with extra options\n echo \"Unknown option '$key'\"\n ;;\n esac\n # Shift after checking all the cases to get the next option\n shift\ndone\n ./myscript --foo -b -o /fizz/file.txt\n ./myscript -f --bar -o=/fizz/file.txt\n" }, { "answer_id": 42354567, "author": "Emeric Verschuur", "author_id": 3132486, "author_profile": "https://Stackoverflow.com/users/3132486", "pm_score": 2, "selected": false, "text": "#!/bin/bash -ei\n\n# load the library\n. bashopts.sh\n\n# Enable backtrace dusplay on error\ntrap 'bashopts_exit_handle' ERR\n\n# Initialize the library\nbashopts_setup -n \"$0\" -d \"This is myapp tool description displayed on help message\" -s \"$HOME/.config/myapprc\"\n\n# Declare the options\nbashopts_declare -n first_name -l first -o f -d \"First name\" -t string -i -s -r\nbashopts_declare -n last_name -l last -o l -d \"Last name\" -t string -i -s -r\nbashopts_declare -n display_name -l display-name -t string -d \"Display name\" -e \"\\$first_name \\$last_name\"\nbashopts_declare -n age -l number -d \"Age\" -t number\nbashopts_declare -n email_list -t string -m add -l email -d \"Email adress\"\n\n# Parse arguments\nbashopts_parse_args \"$@\"\n\n# Process argument\nbashopts_process_args\n NAME:\n ./example.sh - This is myapp tool description displayed on help message\n\nUSAGE:\n [options and commands] [-- [extra args]]\n\nOPTIONS:\n -h,--help Display this help\n -n,--non-interactive true Non interactive mode - [$bashopts_non_interactive] (type:boolean, default:false)\n -f,--first \"John\" First name - [$first_name] (type:string, default:\"\")\n -l,--last \"Smith\" Last name - [$last_name] (type:string, default:\"\")\n --display-name \"John Smith\" Display name - [$display_name] (type:string, default:\"$first_name $last_name\")\n --number 0 Age - [$age] (type:number, default:0)\n --email Email adress - [$email_list] (type:string, default:\"\")\n" }, { "answer_id": 42811119, "author": "a_z", "author_id": 7462070, "author_profile": "https://Stackoverflow.com/users/7462070", "pm_score": 2, "selected": false, "text": "-qwerty -q -w -e --qwerty = --q=qwe ty qwe ty -o a -op attr ibute --option=att ribu te --op-tion attribute --option att-ribute #!/usr/bin/env sh\n\nhelp_menu() {\n echo \"Usage:\n\n ${0##*/} [-h][-l FILENAME][-d]\n\nOptions:\n\n -h, --help\n display this help and exit\n\n -l, --logfile=FILENAME\n filename\n\n -d, --debug\n enable debug\n \"\n}\n\nparse_options() {\n case $opt in\n h|help)\n help_menu\n exit\n ;;\n l|logfile)\n logfile=${attr}\n ;;\n d|debug)\n debug=true\n ;;\n *)\n echo \"Unknown option: ${opt}\\nRun ${0##*/} -h for help.\">&2\n exit 1\n esac\n}\noptions=$@\n\nuntil [ \"$options\" = \"\" ]; do\n if [[ $options =~ (^ *(--([a-zA-Z0-9-]+)|-([a-zA-Z0-9-]+))(( |=)(([\\_\\.\\?\\/\\\\a-zA-Z0-9]?[ -]?[\\_\\.\\?a-zA-Z0-9]+)+))?(.*)|(.+)) ]]; then\n if [[ ${BASH_REMATCH[3]} ]]; then # for --option[=][attribute] or --option[=][attribute]\n opt=${BASH_REMATCH[3]}\n attr=${BASH_REMATCH[7]}\n options=${BASH_REMATCH[9]}\n elif [[ ${BASH_REMATCH[4]} ]]; then # for block options -qwert[=][attribute] or single short option -a[=][attribute]\n pile=${BASH_REMATCH[4]}\n while (( ${#pile} > 1 )); do\n opt=${pile:0:1}\n attr=\"\"\n pile=${pile/${pile:0:1}/}\n parse_options\n done\n opt=$pile\n attr=${BASH_REMATCH[7]}\n options=${BASH_REMATCH[9]}\n else # leftovers that don't match\n opt=${BASH_REMATCH[10]}\n options=\"\"\n fi\n parse_options\n fi\ndone\n" }, { "answer_id": 46677167, "author": "John", "author_id": 6815248, "author_profile": "https://Stackoverflow.com/users/6815248", "pm_score": 2, "selected": false, "text": "test_args.sh #!/bin/sh\nuntil [ $# -eq 0 ]\ndo\n name=${1:1}; shift;\n if [[ -z \"$1\" || $1 == -* ]] ; then eval \"export $name=true\"; else eval \"export $name=$1\"; shift; fi \ndone\necho \"year=$year month=$month day=$day flag=$flag\"\n sh test_args.sh -year 2017 -flag -month 12 -day 22 \n year=2017 month=12 day=22 flag=true\n" }, { "answer_id": 52356831, "author": "Thanh Trung", "author_id": 509916, "author_profile": "https://Stackoverflow.com/users/509916", "pm_score": 3, "selected": false, "text": "source argparser.sh\nparse_args \"$@\"\n" }, { "answer_id": 53800415, "author": "terijo001", "author_id": 10460822, "author_profile": "https://Stackoverflow.com/users/10460822", "pm_score": 1, "selected": false, "text": "for arg in \"$@\"\ndo\n key=$(echo $arg | cut -f1 -d=)`\n value=$(echo $arg | cut -f2 -d=)`\n case \"$key\" in\n name|-name) read_name=$value;;\n id|-id) read_id=$value;;\n *) echo \"I dont know what to do with this\"\n ease\ndone\n" }, { "answer_id": 55008165, "author": "jchook", "author_id": 554406, "author_profile": "https://Stackoverflow.com/users/554406", "pm_score": 5, "selected": false, "text": "--longopt=val --longopt val -xyz -x -y -z -- #!/bin/bash\n\n# Report usage\nusage() {\n echo \"Usage:\"\n echo \"$(basename \"$0\") [options] [--] [file1, ...]\"\n}\n\ninvalid() {\n echo \"ERROR: Unrecognized argument: $1\" >&2\n usage\n exit 1\n}\n\n# Pre-process options to:\n# - expand -xyz into -x -y -z\n# - expand --longopt=arg into --longopt arg\nARGV=()\nEND_OF_OPT=\nwhile [[ $# -gt 0 ]]; do\n arg=\"$1\"; shift\n case \"${END_OF_OPT}${arg}\" in\n --) ARGV+=(\"$arg\"); END_OF_OPT=1 ;;\n --*=*)ARGV+=(\"${arg%%=*}\" \"${arg#*=}\") ;;\n --*) ARGV+=(\"$arg\") ;;\n -*) for i in $(seq 2 ${#arg}); do ARGV+=(\"-${arg:i-1:1}\"); done ;;\n *) ARGV+=(\"$arg\") ;;\n esac\ndone\n\n# Apply pre-processed options\nset -- \"${ARGV[@]}\"\n\n# Parse options\nEND_OF_OPT=\nPOSITIONAL=()\nwhile [[ $# -gt 0 ]]; do\n case \"${END_OF_OPT}${1}\" in\n -h|--help) usage; exit 0 ;;\n -p|--password) shift; PASSWORD=\"$1\" ;;\n -u|--username) shift; USERNAME=\"$1\" ;;\n -n|--name) shift; names+=(\"$1\") ;;\n -q|--quiet) QUIET=1 ;;\n -C|--copy) COPY=1 ;;\n -N|--notify) NOTIFY=1 ;;\n --stdin) READ_STDIN=1 ;;\n --) END_OF_OPT=1 ;;\n -*) invalid \"$1\" ;;\n *) POSITIONAL+=(\"$1\") ;;\n esac\n shift\ndone\n\n# Restore positional parameters\nset -- \"${POSITIONAL[@]}\"\n" }, { "answer_id": 59124908, "author": "mjs", "author_id": 961018, "author_profile": "https://Stackoverflow.com/users/961018", "pm_score": 2, "selected": false, "text": "eval \"local key='val'\" function myrsync() {\n\n local backup=(\"${@}\") args=(); while [[ $# -gt 0 ]]; do k=\"$1\";\n case \"$k\" in\n ---sourceuser|---sourceurl|---targetuser|---targeturl|---file|---exclude|---include)\n eval \"local ${k:3}='${2}'\"; shift; shift # Past two arguments\n ;;\n *) # Unknown option \n args+=(\"$1\"); shift; # Past argument only\n ;; \n esac \n done; set -- \"${backup[@]}\" # Restore $@\n\n\n echo \"${sourceurl}\"\n}\n myrsync ---sourceurl http://abc.def.g ---sourceuser myuser ... \n ---" }, { "answer_id": 59463093, "author": "tmoschou", "author_id": 547569, "author_profile": "https://Stackoverflow.com/users/547569", "pm_score": 3, "selected": false, "text": "= -vxf --color --color=always -- # flag\n-f\n--foo\n\n# option with required argument\n-b\"Hello World\"\n-b \"Hello World\"\n--bar \"Hello World\"\n--bar=\"Hello World\"\n\n# option with optional argument\n--baz\n--baz=\"Optional Hello\"\n #!/usr/bin/env bash\n\nusage() {\n cat - >&2 <<EOF\nNAME\n program-name.sh - Brief description\n \nSYNOPSIS\n program-name.sh [-h|--help]\n program-name.sh [-f|--foo]\n [-b|--bar <arg>]\n [--baz[=<arg>]]\n [--]\n FILE ...\n\nREQUIRED ARGUMENTS\n FILE ...\n input files\n\nOPTIONS\n -h, --help\n Prints this and exits\n\n -f, --foo\n A flag option\n \n -b, --bar <arg>\n Option requiring an argument <arg>\n\n --baz[=<arg>]\n Option that has an optional argument <arg>. If <arg>\n is not specified, defaults to 'DEFAULT'\n -- \n Specify end of options; useful if the first non option\n argument starts with a hyphen\n\nEOF\n}\n\nfatal() {\n for i; do\n echo -e \"${i}\" >&2\n done\n exit 1\n}\n\n# For long option processing\nnext_arg() {\n if [[ $OPTARG == *=* ]]; then\n # for cases like '--opt=arg'\n OPTARG=\"${OPTARG#*=}\"\n else\n # for cases like '--opt arg'\n OPTARG=\"${args[$OPTIND]}\"\n OPTIND=$((OPTIND + 1))\n fi\n}\n\n# ':' means preceding option character expects one argument, except\n# first ':' which make getopts run in silent mode. We handle errors with\n# wildcard case catch. Long options are considered as the '-' character\noptspec=\":hfb:-:\"\nargs=(\"\" \"$@\") # dummy first element so $1 and $args[1] are aligned\nwhile getopts \"$optspec\" optchar; do\n case \"$optchar\" in\n h) usage; exit 0 ;;\n f) foo=1 ;;\n b) bar=\"$OPTARG\" ;;\n -) # long option processing\n case \"$OPTARG\" in\n help)\n usage; exit 0 ;;\n foo)\n foo=1 ;;\n bar|bar=*) next_arg\n bar=\"$OPTARG\" ;;\n baz)\n baz=DEFAULT ;;\n baz=*) next_arg\n baz=\"$OPTARG\" ;;\n -) break ;;\n *) fatal \"Unknown option '--${OPTARG}'\" \"see '${0} --help' for usage\" ;;\n esac\n ;;\n *) fatal \"Unknown option: '-${OPTARG}'\" \"See '${0} --help' for usage\" ;;\n esac\ndone\n\nshift $((OPTIND-1))\n\nif [ \"$#\" -eq 0 ]; then\n fatal \"Expected at least one required argument FILE\" \\\n \"See '${0} --help' for usage\"\nfi\n\necho \"foo=$foo, bar=$bar, baz=$baz, files=${@}\"\n" }, { "answer_id": 61139993, "author": "Mihir Luthra", "author_id": 11498773, "author_profile": "https://Stackoverflow.com/users/11498773", "pm_score": 2, "selected": false, "text": "fruit fruit <fruit-name> ...\n [-e|—-eat|—-chew]\n [-c|--cut <how> <why>]\n <command> [<args>] \n -e -c fruit <command> apple orange git commit push parse_options \\\n 'fruit' '1 ...' \\\n '-e' , '--eat' , '--chew' '0' \\\n '-c' , '--cut' '1 1' \\\n 'apple' 'S' \\\n 'orange' 'S' \\\n ';' \\\n \"$@\"\n option_parser_error_msg retval=$?\n\nif [ $retval -ne 0 ]; then\n # this will manage error messages if\n # insufficient or extra args are supplied\n\n option_parser_error_msg \"$retval\"\n\n # This will print the usage\n print_usage 'fruit'\n exit 1\nfi\n if [ -n \"${OPTIONS[-c]}\" ]\nthen\n echo \"-c was passed\"\n\n # args can be accessed in a 2D-array-like format\n echo \"Arg1 to -c = ${ARGS[-c,0]}\"\n echo \"Arg2 to -c = ${ARGS[-c,1]}\"\n\nfi\n $shift_count parse_options_detailed" }, { "answer_id": 62616466, "author": "leogama", "author_id": 3738764, "author_profile": "https://Stackoverflow.com/users/3738764", "pm_score": 4, "selected": false, "text": "getopt(s) -n [arg] -abn [arg] --name [arg] --name=arg $@ -- getopt(s) sed # Convenience functions.\nusage_error () { echo >&2 \"$(basename $0): $1\"; exit 2; }\nassert_argument () { test \"$1\" != \"$EOL\" || usage_error \"$2 requires an argument\"; }\n\n# One loop, nothing more.\nif [ \"$#\" != 0 ]; then\n EOL=$(printf '\\1\\3\\3\\7')\n set -- \"$@\" \"$EOL\"\n while [ \"$1\" != \"$EOL\" ]; do\n opt=\"$1\"; shift\n case \"$opt\" in\n\n # Your options go here.\n -f|--flag) flag='true';;\n -n|--name) assert_argument \"$1\" \"$opt\"; name=\"$1\"; shift;;\n\n # Arguments processing. You may remove any unneeded line after the 1st.\n -|''|[!-]*) set -- \"$@\" \"$opt\";; # positional argument, rotate to the end\n --*=*) set -- \"${opt%%=*}\" \"${opt#*=}\" \"$@\";; # convert '--name=arg' to '--name' 'arg'\n -[!-]?*) set -- $(echo \"${opt#-}\" | sed 's/\\(.\\)/ -\\1/g') \"$@\";; # convert '-abc' to '-a' '-b' '-c'\n --) while [ \"$1\" != \"$EOL\" ]; do set -- \"$@\" \"$1\"; shift; done;; # process remaining arguments as positional\n -*) usage_error \"unknown option: '$opt'\";; # catch misspelled options\n *) usage_error \"this should NEVER happen ($opt)\";; # sanity test for previous patterns\n\n esac\n done\n shift # $EOL\nfi\n\n# Do something cool with \"$@\"... \\o/\n 0x01030307" }, { "answer_id": 63044632, "author": "Meir Gabay", "author_id": 5285732, "author_profile": "https://Stackoverflow.com/users/5285732", "pm_score": 2, "selected": false, "text": "$ bash example.sh -n Willy --gender male -a 99\nName: Willy\nAge: 99\nGender: male\nLocation: chocolate-factory\n $ bash example.sh -n Meir --gender male\n[ERROR] Required argument: age\n\nUsage: bash example.sh -n Willy --gender male -a 99\n\n--person_name | -n [Willy] What is your name?\n--age | -a [Required]\n--gender | -g [Required]\n--location | -l [chocolate-factory] insert your location\n $ bash example.sh -h\n\nUsage: bash example.sh -n Willy --gender male -a 99\n--person_name | -n [Willy] What is your name?\n--age | -a [Required]\n--gender | -g [Required]\n--location | -l [chocolate-factory] insert your location\n" }, { "answer_id": 63413837, "author": "Koichi Nakashima", "author_id": 11267590, "author_profile": "https://Stackoverflow.com/users/11267590", "pm_score": 4, "selected": false, "text": "-a +a -abc -vvv -p VALUE -pVALUE --flag --no-flag --with-flag --without-flag --param VALUE --param=VALUE --option[=VALUE] --no-option -- #!/bin/sh\n\nVERSION=\"0.1\"\n\nparser_definition() {\n setup REST help:usage -- \"Usage: example.sh [options]... [arguments]...\" ''\n msg -- 'Options:'\n flag FLAG -f --flag -- \"takes no arguments\"\n param PARAM -p --param -- \"takes one argument\"\n option OPTION -o --option on:\"default\" -- \"takes one optional argument\"\n disp :usage -h --help\n disp VERSION --version\n}\n\neval \"$(getoptions parser_definition) exit 1\"\n\necho \"FLAG: $FLAG, PARAM: $PARAM, OPTION: $OPTION\"\nprintf '%s\\n' \"$@\" # rest arguments\n example.sh -f --flag -p VALUE --param VALUE -o --option -oVALUE --option=VALUE 1 2 3\n $ example.sh --help\n\nUsage: example.sh [options]... [arguments]...\n\nOptions:\n -f, --flag takes no arguments\n -p, --param PARAM takes one argument\n -o, --option[=OPTION] takes one optional argument\n -h, --help\n --version\n getoptions FLAG=''\nPARAM=''\nOPTION=''\nREST=''\ngetoptions_parse() {\n OPTIND=$(($#+1))\n while OPTARG= && [ $# -gt 0 ]; do\n case $1 in\n --?*=*) OPTARG=$1; shift\n eval 'set -- \"${OPTARG%%\\=*}\" \"${OPTARG#*\\=}\"' ${1+'\"$@\"'}\n ;;\n --no-*|--without-*) unset OPTARG ;;\n -[po]?*) OPTARG=$1; shift\n eval 'set -- \"${OPTARG%\"${OPTARG#??}\"}\" \"${OPTARG#??}\"' ${1+'\"$@\"'}\n ;;\n -[fh]?*) OPTARG=$1; shift\n eval 'set -- \"${OPTARG%\"${OPTARG#??}\"}\" -\"${OPTARG#??}\"' ${1+'\"$@\"'}\n OPTARG= ;;\n esac\n case $1 in\n '-f'|'--flag')\n [ \"${OPTARG:-}\" ] && OPTARG=${OPTARG#*\\=} && set \"noarg\" \"$1\" && break\n eval '[ ${OPTARG+x} ] &&:' && OPTARG='1' || OPTARG=''\n FLAG=\"$OPTARG\"\n ;;\n '-p'|'--param')\n [ $# -le 1 ] && set \"required\" \"$1\" && break\n OPTARG=$2\n PARAM=\"$OPTARG\"\n shift ;;\n '-o'|'--option')\n set -- \"$1\" \"$@\"\n [ ${OPTARG+x} ] && {\n case $1 in --no-*|--without-*) set \"noarg\" \"${1%%\\=*}\"; break; esac\n [ \"${OPTARG:-}\" ] && { shift; OPTARG=$2; } || OPTARG='default'\n } || OPTARG=''\n OPTION=\"$OPTARG\"\n shift ;;\n '-h'|'--help')\n usage\n exit 0 ;;\n '--version')\n echo \"${VERSION}\"\n exit 0 ;;\n --)\n shift\n while [ $# -gt 0 ]; do\n REST=\"${REST} \\\"\\${$(($OPTIND-$#))}\\\"\"\n shift\n done\n break ;;\n [-]?*) set \"unknown\" \"$1\"; break ;;\n *)\n REST=\"${REST} \\\"\\${$(($OPTIND-$#))}\\\"\"\n esac\n shift\n done\n [ $# -eq 0 ] && { OPTIND=1; unset OPTARG; return 0; }\n case $1 in\n unknown) set \"Unrecognized option: $2\" \"$@\" ;;\n noarg) set \"Does not allow an argument: $2\" \"$@\" ;;\n required) set \"Requires an argument: $2\" \"$@\" ;;\n pattern:*) set \"Does not match the pattern (${1#*:}): $2\" \"$@\" ;;\n notcmd) set \"Not a command: $2\" \"$@\" ;;\n *) set \"Validation error ($1): $2\" \"$@\"\n esac\n echo \"$1\" >&2\n exit 1\n}\nusage() {\ncat<<'GETOPTIONSHERE'\nUsage: example.sh [options]... [arguments]...\n\nOptions:\n -f, --flag takes no arguments\n -p, --param PARAM takes one argument\n -o, --option[=OPTION] takes one optional argument\n -h, --help\n --version\nGETOPTIONSHERE\n}\n" }, { "answer_id": 66573181, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "#!/bin/sh\n\na=$(($#-1))\nb=$(($#))\nwhile [ $a -gt 0 ]; do\n eval 'key=\"$'$a'\"; value=\"$'$b'\"'\n echo \"$key => $value\"\n b=$(($b-2))\n a=$(($a-2))\ndone\nunset a b key value\n\n[ $(($#%2)) -ne 0 ] && echo \"first_arg = $1\"\n\n #!/bin/sh\n\na=$((1+$#%2))\nb=$((1+$a))\n\n[ $(($#%2)) -ne 0 ] && echo \"first_arg = $1\"\n\nwhile [ $a -lt $# ]; do\n eval 'key=\"$'$a'\"; value=\"$'$b'\"'\n echo \"$key => $value\"\n b=$(($b+2))\n a=$(($a+2))\ndone\n\nunset a b key value\n\n #!/bin/sh\n\na=$(($#%2))\nb=0\n\n[ $a -eq 1 ] && echo \"first_arg = $1\"\n\nfor value; do\n if [ $b -gt $a -a $(($b%2)) -ne $a ]; then\n echo \"$key => $value\"\n fi\n key=\"$value\"\n b=$((1+$b))\ndone\n\nunset a b key value\n\n" }, { "answer_id": 67963449, "author": "Top-Master", "author_id": 8740349, "author_profile": "https://Stackoverflow.com/users/8740349", "pm_score": 2, "selected": false, "text": "dash /bin/sh while [[ $# -gt 0 ]]; do\n case \"$1\" in\n -v|--verbose) verbose=1; shift;;\n -o|--output) if [[ $# -gt 1 && \"$2\" != -* ]]; then\n file=$2; shift 2\n else\n echo \"-o requires file-path\" 1>&2; exit 1\n fi ;;\n --)\n while [[ $# -gt 0 ]]; do BACKUP=\"$BACKUP;$1\"; shift; done\n break;;\n *)\n BACKUP=\"$BACKUP;$1\"\n shift\n ;;\n esac\ndone\n# Restore unused arguments.\nwhile [ -n \"$BACKUP\" ] ; do\n [ ! -z \"${BACKUP%%;*}\" ] && set -- \"$@\" \"${BACKUP%%;*}\"\n [ \"$BACKUP\" = \"${BACKUP/;/}\" ] && break\n BACKUP=\"${BACKUP#*;}\"\ndone\n" }, { "answer_id": 69736953, "author": "CIsForCookies", "author_id": 3512538, "author_profile": "https://Stackoverflow.com/users/3512538", "pm_score": 3, "selected": false, "text": "#!/bin/bash\nset -e\n\nfunction parse() {\n for arg in \"$@\"; do # transform long options to short ones\n shift\n case \"$arg\" in\n \"--name\") set -- \"$@\" \"-n\" ;;\n \"--verbose\") set -- \"$@\" \"-v\" ;;\n *) set -- \"$@\" \"$arg\"\n esac\n done\n\n while getopts \"n:v\" optname # left to \":\" are flags that expect a value, right to the \":\" are flags that expect nothing\n do\n case \"$optname\" in\n \"n\") name=${OPTARG} ;;\n \"v\") verbose=true ;;\n esac\n done\n shift \"$((OPTIND-1))\" # shift out all the already processed options\n}\n\n\nparse \"$@\"\necho \"hello $name\"\nif [ ! -z $verbose ]; then echo 'nice to meet you!'; fi\n $ ./parse.sh\nhello\n$ ./parse.sh -n YOUR_NAME\nhello YOUR_NAME\n$ ./parse.sh -n YOUR_NAME -v\nhello YOUR_NAME\nnice to meet you!\n$ ./parse.sh -v -n YOUR_NAME\nhello YOUR_NAME\nnice to meet you!\n$ ./parse.sh -v\nhello \nnice to meet you!\n" }, { "answer_id": 72242057, "author": "mgutt", "author_id": 318765, "author_profile": "https://Stackoverflow.com/users/318765", "pm_score": 1, "selected": false, "text": "optget optgets - -- # catch wrong options and move non-options to the end of the string\nargs=$(getopt -l \"$opt_long\" \"$opt_short\" \"$@\" 2> >(sed -e 's/^/stderr/g')) || echo -n \"Error: \" && echo \"$args\" | grep -oP \"(?<=^stderr).*\" && exit 1\nmapfile -t args < <(xargs -n1 <<< \"$(echo \"$args\" | sed -E \"s/(--[^ ]+) /\\1=/g\")\" )\nset -- \"${args[@]}\"\n\n# parse short and long options\nwhile getopts \"$opt_short-:\" opt; do\n ...\ndone\n\n# remove all parsed options from $@\nshift $((OPTIND-1)\n $opt_verbose $1 $2 echo \"help:$opt_help\"\necho \"file:$opt_file\"\necho \"verbose:$opt_verbose\"\necho \"long_only:$opt_long_only\"\necho \"short_only:$opt_s\"\necho \"path:$1\"\necho \"mail:$2\"\n # $opt_file $1 $2 $opt_... $opt_... $opt_...\n# /demo.sh --file=file.txt /dir info@example.com -V -h --long_only=yes -s\nhelp:1\nfile:file.txt\nverbose:1\nlong_only:yes\nshort_only:1\npath:/dir\nmail:info@example.com\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1512/" ]
192,256
<p>What would be the best method to implement extra functionality in a database layer that uses Linq-to-SQL? Currently I'm looking at implementing functions for adding information based on presets and similar tasks?</p> <p>Inserts, updates and deletes requires access to the <code>DataContext</code> and in the <code>Table</code> classes you don't have access to the context. I've seen solutions that uses Singletons but it seems like a hack and I wonder if anyone else has run into this problem and what your solutions were? Is there a better way all together to implement similar functionality.</p> <p>The reason for me looking to add this functionality to the database layer is that I have several applications that all use the same database objects and I want to be able to use these functions from all applications so I don't have to rewrite a lot of code.</p> <hr> <p>That's not quite what I meant. I want to be able to do complex actions like updating one table and adding a record to another table based on information from the first one.</p> <p>Say I have selected a Customer record and I want to update this with information, and when this happens I want it to add another record to the "Updates" table to keep track of when updates happened and who did them. This is only an example of course. Things needed to be done can be more complex.</p> <p>Basically I want to add a method to a table object to perform modifications to a specific row in that table and then do inserts and updates on other objects. I know that you can use partial classes and I do that extensively already.</p> <p>Example:</p> <pre><code>db.Customers.Where(c =&gt; c.CustomerID == 5).AddOrder(orderDetails); </code></pre> <p>I feel that I can't really put my problem into words to make it understandable :)</p>
[ { "answer_id": 7253842, "author": "dougajmcdonald", "author_id": 777733, "author_profile": "https://Stackoverflow.com/users/777733", "pm_score": 1, "selected": false, "text": "public static class StringExtensions \n{\n public static int ToInt(this string oString)\n {\n return int.Parse(oString);\n }\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26746/" ]
192,260
<p>I am currently working on a website to track projects. In it, it is possible to create Service Level Agreements (SLAs). These are configurable with days of the week that a project can be worked on and also the timespan on each of those days. Eg. on Monday it might be between 08:00 and 16:00 and then on friday from 10:00 to 14:00. They are also configured with a deadline time depending on priority. Eg. a project created with the "Low" priority has a deadline time of two weeks, and a project with "High" priority has a deadline of four hours.</p> <p>The problem I'm having is calculating the deadline AROUND the hours described earlier. Say I create a project on Monday at 14:00 with a "High" priority. That means I have four hours for this project. But because of the working hours, I have two hours on monday (untill 16:00) and then another two hours on Friday. That means the Deadline must be set for Friday at 12:00.</p> <p>I've spent quite some time googling this, and I can find quite a few examples of finding out how many working hours there are between a given start end ending date. I just can't figure out how to convert it into FINDING the ending datetime, given a starting time and an amount of time untill the deadline.</p> <p>The day/timespans are stored in an sql database in the format:</p> <p>Day(Eg. 1 for Monday) StartHour EndHour</p> <p>The StartHour/EndHour are saved as DateTimes, but of course only the time part is important.</p> <p>The way I figure it is, I have to somehow iterate through these times and do some datetime calculations. I just can't quite figure out what those calculations should be, what the best way is.</p> <p>I found <a href="https://stackoverflow.com/questions/5260/what-is-the-best-way-to-wrap-time-around-the-work-day">this Question</a> here on the site as I was writing this. It is sort of what I want and I'm playing with it right now, but I'm still lost on how exactly to make it work around my dynamic work days/hours.</p>
[ { "answer_id": 192307, "author": "Ian Jacobs", "author_id": 22818, "author_profile": "https://Stackoverflow.com/users/22818", "pm_score": 1, "selected": false, "text": "public DateTime getDeadline(SubmitTime, ProjectTimeAllowed)\n{\n if (SubmitTime+ProjectTimeAllowed >= DayEndTime)\n return getDeadline(NextDayStart, ProjectTimeAllowed-DayEndTime-SubmitTime)\n else\n return SubmitTime + ProjectTimeAllowed\n}\n" }, { "answer_id": 192791, "author": "Loscas", "author_id": 22706, "author_profile": "https://Stackoverflow.com/users/22706", "pm_score": 1, "selected": false, "text": "CREATE PROCEDURE [dbo].[IsInBusinessHours]\n @MyDate DateTime \nAS\nBEGIN\n SELECT CASE Count(*) WHEN 0 THEN 0 ELSE 1 END AS IsBusinessHour\nFROM WorkHours\nWHERE (DATEPART(hour, StartHours) <= DATEPART(hour, @MyDate)) AND (DATEPART(hour, EndHours) > DATEPART(hour, @MyDate)) AND (Day = DATEPART(WEEKDAY, \n @MyDate))\nEND\n" }, { "answer_id": 192800, "author": "Esteban Brenes", "author_id": 14177, "author_profile": "https://Stackoverflow.com/users/14177", "pm_score": 2, "selected": false, "text": " class Program\n {\n static void Main(string[] args)\n {\n // Test\n DateTime deadline = DeadlineManager.CalculateDeadline(DateTime.Now, new TimeSpan(4, 0, 0));\n Console.WriteLine(deadline);\n Console.ReadLine();\n }\n }\n\n static class DeadlineManager\n {\n public static DateTime CalculateDeadline(DateTime start, TimeSpan workhours)\n {\n DateTime current = new DateTime(start.Year, start.Month, start.Day, start.Hour, start.Minute, 0);\n while(workhours.TotalMinutes > 0)\n {\n DayOfWeek dayOfWeek = current.DayOfWeek;\n Workday workday = Workday.GetWorkday(dayOfWeek);\n if(workday == null)\n {\n DayOfWeek original = dayOfWeek;\n while (workday == null)\n {\n current = current.AddDays(1);\n dayOfWeek = current.DayOfWeek;\n workday = Workday.GetWorkday(dayOfWeek);\n if (dayOfWeek == original)\n {\n throw new InvalidOperationException(\"no work days\");\n }\n }\n current = current.AddHours(workday.startTime.Hour - current.Hour);\n current = current.AddMinutes(workday.startTime.Minute - current.Minute);\n }\n\n TimeSpan worked = Workday.WorkHours(workday, current);\n if (workhours > worked)\n {\n workhours = workhours - worked;\n // Add one day and reset hour/minutes\n current = current.Add(new TimeSpan(1, current.Hour * -1, current.Minute * -1, 0));\n }\n else\n {\n current.Add(workhours);\n return current;\n }\n }\n return DateTime.MinValue;\n }\n }\n\n class Workday\n {\n private static readonly Dictionary<DayOfWeek, Workday> Workdays = new Dictionary<DayOfWeek, Workday>(7);\n static Workday()\n {\n Workdays.Add(DayOfWeek.Monday, new Workday(DayOfWeek.Monday, new DateTime(1, 1, 1, 10, 0, 0), new DateTime(1, 1, 1, 16, 0, 0)));\n Workdays.Add(DayOfWeek.Tuesday, new Workday(DayOfWeek.Tuesday, new DateTime(1, 1, 1, 10, 0, 0), new DateTime(1, 1, 1, 16, 0, 0)));\n Workdays.Add(DayOfWeek.Wednesday, new Workday(DayOfWeek.Wednesday, new DateTime(1, 1, 1, 10, 0, 0), new DateTime(1, 1, 1, 16, 0, 0)));\n Workdays.Add(DayOfWeek.Thursday, new Workday(DayOfWeek.Thursday, new DateTime(1, 1, 1, 10, 0, 0), new DateTime(1, 1, 1, 16, 0, 0)));\n Workdays.Add(DayOfWeek.Friday, new Workday(DayOfWeek.Friday, new DateTime(1, 1, 1, 10, 0, 0), new DateTime(1, 1, 1, 14, 0, 0)));\n }\n\n public static Workday GetWorkday(DayOfWeek dayofWeek)\n {\n if (Workdays.ContainsKey(dayofWeek))\n {\n return Workdays[dayofWeek];\n }\n else return null;\n }\n\n public static TimeSpan WorkHours(Workday workday, DateTime time)\n {\n DateTime sTime = new DateTime(time.Year, time.Month, time.Day,\n workday.startTime.Hour, workday.startTime.Millisecond, workday.startTime.Second);\n DateTime eTime = new DateTime(time.Year, time.Month, time.Day,\n workday.endTime.Hour, workday.endTime.Millisecond, workday.endTime.Second);\n if (sTime < time)\n {\n sTime = time;\n }\n TimeSpan span = eTime - sTime;\n return span;\n }\n\n public static DayOfWeek GetNextWeekday(DayOfWeek dayOfWeek)\n {\n int i = (dayOfWeek == DayOfWeek.Saturday) ? 0 : ((int)dayOfWeek) + 1;\n return (DayOfWeek)i;\n }\n\n\n private Workday(DayOfWeek dayOfWeek, DateTime start, DateTime end)\n {\n this.dayOfWeek = dayOfWeek;\n this.startTime = start;\n this.endTime = end;\n }\n\n public DayOfWeek dayOfWeek;\n public DateTime startTime;\n public DateTime endTime;\n }\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26841/" ]
192,261
<p>Using something like this:</p> <pre><code>try: # Something... except Exception as excep: logger = logging.getLogger("component") logger.warning("something raised an exception: " + excep) logger.info("something raised an exception: " + excep) </code></pre> <p>I would rather not have it on the error-level cause in my special case it is not an error.</p>
[ { "answer_id": 193153, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": 8, "selected": true, "text": "kwargs exc_info stack_info extra exc_info sys.exc_info() sys.exc_info() logger.warning(\"something raised an exception:\", exc_info=True)\n" }, { "answer_id": 4909282, "author": "Scubahubby", "author_id": 604684, "author_profile": "https://Stackoverflow.com/users/604684", "pm_score": 2, "selected": false, "text": "logger.critical(\"caught exception, traceback =\", exc_info=True)\n" }, { "answer_id": 49975391, "author": "Benyamin Jafari - aGn", "author_id": 3702377, "author_profile": "https://Stackoverflow.com/users/3702377", "pm_score": 1, "selected": false, "text": "from logging import getLogger\n\nlogger = getLogger('warning')\n\ntry:\n # Somethings that is wrong.\n\nexcept Exception as exp:\n logger.warning(\"something raised an exception: \" , exc_info=True)\n logger.warning(\"something raised an exception: {}\".format(exp)) # another way\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26905/" ]
192,264
<p>I have a page that is hitting a webservice every 5 seconds to update the information on the page. I'm using the DynamicPopulateExtender from the Ajax Control Toolkit to just populate a panel with some text.</p> <p>What I was wanting to do, is if a certain condition is met, to refresh the page completely. </p> <p>Am I going to be able to do this in the current method that I have? here's my current stuff:</p> <hr> <p>ASP.NET</p> <pre><code>&lt;cc1:DynamicPopulateExtender ID="DynamicPopulateExtender1" runat="server" ClearContentsDuringUpdate="true" TargetControlID="panelQueue" BehaviorID="dp1" ServiceMethod="GetQueueTable" UpdatingCssClass="dynamicPopulate_Updating" /&gt; </code></pre> <p>Javascript</p> <pre><code>Sys.Application.add_load(function(){updateQueue();}); function updateQueue() { var queueShown = document.getElementById('&lt;%= hiddenFieldQueueShown.ClientID %&gt;').value; if(queueShown == 1) { var behavior = $find('dp1'); if (behavior) { behavior.populate(); setTimeout('updateQueue()', 5000); } } } </code></pre> <p>SERVER (C#)</p> <pre><code>[System.Web.Services.WebMethod] [System.Web.Script.Services.ScriptMethod] public static string GetQueueTable() { System.Text.StringBuilder builder = new System.Text.StringBuilder(); try { // do stuff } catch (Exception ex) { // do stuff } return builder.ToString(); } </code></pre>
[ { "answer_id": 192393, "author": "Alfred B. Thordarson", "author_id": 3379, "author_profile": "https://Stackoverflow.com/users/3379", "pm_score": 2, "selected": false, "text": "<html xmlns=\"http://www.w3.org/1999/xhtml\" >\n<head runat=\"server\">\n <title>Untitled Page</title>\n\n <script type=\"text/javascript\" language=\"javascript\">\n function forcePostback()\n {\n <%=getPostBackJavascriptCode()%>;\n }\n </script>\n\n</head>\n\n<body onload=\"javascript:forcePostback()\">\n <form id=\"form1\" runat=\"server\">\n <div>\n <asp:Label ID=\"Label1\" runat=\"server\" Text=\"Postbacking right now...\"></asp:Label>\n </div>\n </form>\n</body>\n</html>\n namespace ForcingApostback\n{\n public partial class _Default : System.Web.UI.Page\n {\n protected void Page_Load(object sender, EventArgs e)\n {\n if (IsPostBack) Label1.Text = \"Done postbacking!!!\";\n }\n\n protected string getPostBackJavascriptCode()\n {\n return ClientScript.GetPostBackEventReference(this, null);\n\n }\n }\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21828/" ]
192,292
<p>The way you would normally include a script is with "source"</p> <p>eg:</p> <p>main.sh:</p> <pre><code>#!/bin/bash source incl.sh echo "The main script" </code></pre> <p>incl.sh:</p> <pre><code>echo "The included script" </code></pre> <p>The output of executing "./main.sh" is:</p> <pre><code>The included script The main script </code></pre> <p>... Now, if you attempt to execute that shell script from another location, it can't find the include unless it's in your path.</p> <p>What's a good way to ensure that your script can find the include script, especially if for instance, the script needs to be portable?</p>
[ { "answer_id": 192305, "author": "Chris Boran", "author_id": 25660, "author_profile": "https://Stackoverflow.com/users/25660", "pm_score": 9, "selected": true, "text": "#!/bin/sh\n\nmy_dir=\"$(dirname \"$0\")\"\n\n\"$my_dir/other_script.sh\"\n" }, { "answer_id": 192306, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 6, "selected": false, "text": "dirname $0 #!/bin/bash\n\nsource $(dirname $0)/incl.sh\n\necho \"The main script\"\n" }, { "answer_id": 192381, "author": "Steve Baker", "author_id": 13566, "author_profile": "https://Stackoverflow.com/users/13566", "pm_score": 3, "selected": false, "text": "#!/bin/bash\ninstallpath=/where/your/scripts/are\n\n. $installpath/incl.sh\n\necho \"The main script\"\n" }, { "answer_id": 192524, "author": "tardate", "author_id": 6329, "author_profile": "https://Stackoverflow.com/users/6329", "pm_score": 6, "selected": false, "text": "scriptPath=$(dirname $0)\n scriptPath=${0%/*}\n" }, { "answer_id": 193988, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 2, "selected": false, "text": ". ${installpath}/incl.sh\n" }, { "answer_id": 992855, "author": "Max Arnold", "author_id": 65523, "author_profile": "https://Stackoverflow.com/users/65523", "pm_score": 5, "selected": false, "text": "SRC=$(cd $(dirname \"$0\"); pwd)\nsource \"${SRC}/incl.sh\"\n" }, { "answer_id": 3692080, "author": "konsolebox", "author_id": 445221, "author_profile": "https://Stackoverflow.com/users/445221", "pm_score": 2, "selected": false, "text": "#!/bin/sh\n\n# load loader.sh\n. loader.sh\n\n# include directories to search path\nloader_addpath /usr/lib/sh deps source\n\n# load main script\nload main.sh\n include a.sh\ninclude b.sh\n\necho '---- main.sh ----'\n\n# remove loader from shellspace since\n# we no longer need it\nloader_finish\n\n# main procedures go from here\n\n# ...\n include main.sh\ninclude a.sh\ninclude b.sh\n\necho '---- a.sh ----'\n include main.sh\ninclude a.sh\ninclude b.sh\n\necho '---- b.sh ----'\n ---- b.sh ----\n---- a.sh ----\n---- main.sh ----\n eval" }, { "answer_id": 4047714, "author": "phreed", "author_id": 345427, "author_profile": "https://Stackoverflow.com/users/345427", "pm_score": 2, "selected": false, "text": "while read file; do source \"${file}\"; done <<HERE\n$(find ${HOME}/.bashrc.d -type f)\nHERE\n for file in ${HOME}/.bashrc.d/*.sh; do source ${file};done\n find ${HOME}/.bashrc.d -type f | while read file; do source ${file}; done\n" }, { "answer_id": 4226925, "author": "Django", "author_id": 513726, "author_profile": "https://Stackoverflow.com/users/513726", "pm_score": -1, "selected": false, "text": "PWD=$(pwd)\nsource \"$PWD/inc.sh\"\n" }, { "answer_id": 7533252, "author": "Mat131", "author_id": 850780, "author_profile": "https://Stackoverflow.com/users/850780", "pm_score": 5, "selected": false, "text": "#!/bin/sh\nMY_DIR=$(dirname $(readlink -f $0))\n$MY_DIR/other_script.sh\n readlink - display value of a symbolic link\n\n...\n\n -f, --canonicalize\n canonicalize by following every symlink in every component of the given \n name recursively; all but the last component must exist\n MY_DIR $PATH" }, { "answer_id": 12694189, "author": "sacii", "author_id": 1714902, "author_profile": "https://Stackoverflow.com/users/1714902", "pm_score": 8, "selected": false, "text": "DIR=\"${BASH_SOURCE%/*}\"\nif [[ ! -d \"$DIR\" ]]; then DIR=\"$PWD\"; fi\n. \"$DIR/incl.sh\"\n. \"$DIR/main.sh\"\n . source $PWD BASH_SOURCE ${string%substring}" }, { "answer_id": 13222994, "author": "francoisrv", "author_id": 754522, "author_profile": "https://Stackoverflow.com/users/754522", "pm_score": 1, "selected": false, "text": "ls -l /proc/$$/fd | \ngrep \"255 ->\" |\nsed -e 's/^.\\+-> //'\n" }, { "answer_id": 21163311, "author": "fastrizwaan", "author_id": 3189318, "author_profile": "https://Stackoverflow.com/users/3189318", "pm_score": 0, "selected": false, "text": "#!/bin/bash\n\nSCRIPT_NAME=$(basename $0)\nSCRIPT_DIR=\"$(echo $0| sed \"s/$SCRIPT_NAME//g\")\"\nsource $SCRIPT_DIR/incl.sh\n\necho \"The main script\"\n" }, { "answer_id": 26727011, "author": "modulitos", "author_id": 1884158, "author_profile": "https://Stackoverflow.com/users/1884158", "pm_score": 1, "selected": false, "text": "scriptdir=`dirname \"$BASH_SOURCE\"`\nsource $scriptdir/incl.sh\n\necho \"The main script\"\n" }, { "answer_id": 30654404, "author": "PSkocik", "author_id": 1084774, "author_profile": "https://Stackoverflow.com/users/1084774", "pm_score": 2, "selected": false, "text": "source_relative() {\n local dir=\"${BASH_SOURCE%/*}\"\n [[ -z \"$dir\" ]] && dir=\"$PWD\"\n source \"$dir/$1\"\n}\n\nsource_relative incl.sh\n" }, { "answer_id": 31960707, "author": "Alessandro Pezzato", "author_id": 786186, "author_profile": "https://Stackoverflow.com/users/786186", "pm_score": 4, "selected": false, "text": "source \"$( dirname \"${BASH_SOURCE[0]}\" )/incl.sh\"\n" }, { "answer_id": 34208365, "author": "Brian Cannard", "author_id": 84661, "author_profile": "https://Stackoverflow.com/users/84661", "pm_score": 5, "selected": false, "text": "readlink ${BASH_SOURCE[0]} $0" }, { "answer_id": 49706459, "author": "Alexar", "author_id": 257479, "author_profile": "https://Stackoverflow.com/users/257479", "pm_score": 4, "selected": false, "text": "script_root=$(dirname $(readlink -f $0)) $PATH # Copyright https://stackoverflow.com/a/13222994/257479\nscript_root=$(ls -l /proc/$$/fd | grep \"255 ->\" | sed -e 's/^.\\+-> //')\n # Copyright http://stackoverflow.com/a/7400673/257479\nmyreadlink() { [ ! -h \"$1\" ] && echo \"$1\" || (local link=\"$(expr \"$(command ls -ld -- \"$1\")\" : '.*-> \\(.*\\)$')\"; cd $(dirname $1); myreadlink \"$link\" | sed \"s|^\\([^/].*\\)\\$|$(dirname $1)/\\1|\"); }\nwhereis() { echo $1 | sed \"s|^\\([^/].*/.*\\)|$(pwd)/\\1|;s|^\\([^/]*\\)$|$(which -- $1)|;s|^$|$1|\"; } \nwhereis_realpath() { local SCRIPT_PATH=$(whereis $1); myreadlink ${SCRIPT_PATH} | sed \"s|^\\([^/].*\\)\\$|$(dirname ${SCRIPT_PATH})/\\1|\"; } \n\nscript_root=$(dirname $(whereis_realpath \"$0\"))\n taskrunner" }, { "answer_id": 51783337, "author": "Xaqron", "author_id": 313421, "author_profile": "https://Stackoverflow.com/users/313421", "pm_score": 1, "selected": false, "text": "lib import script.sh # Imports '.sh' files from 'lib' directory\nfunction import()\n{\n local file=\"./lib/$1.sh\"\n local error=\"\\e[31mError: \\e[0mCannot find \\e[1m$1\\e[0m library at: \\e[2m$file\\e[0m\"\n if [ -f \"$file\" ]; then\n source \"$file\"\n if [ -z $IMPORTED ]; then\n echo -e $error\n exit 1\n fi\n else\n echo -e $error\n exit 1\n fi\n}\n import \"utils\"\nimport \"requirements\"\n IMPORTED=\"$BASH_SOURCE\"\n utils.sh requirements.sh script.sh sh" }, { "answer_id": 56917434, "author": "Alexander Yancharuk", "author_id": 2648942, "author_profile": "https://Stackoverflow.com/users/2648942", "pm_score": 0, "selected": false, "text": "man hier /usr/local/lib/ /usr/local/lib/bash/includes #!/bin/bash\n\n. /usr/local/lib/bash/includes/bash-helpers.sh\n\ninclude api-client || exit 1 # include shared functions\ninclude mysql-status/query-builder || exit 1 # include script functions\n\n# include script functions with status message\ninclude mysql-status/process-checker; status 'process-checker' $? || exit 1\ninclude mysql-status/nonexists; status 'nonexists' $? || exit 1\n" }, { "answer_id": 66371711, "author": "Joaommp", "author_id": 6421961, "author_profile": "https://Stackoverflow.com/users/6421961", "pm_score": 0, "selected": false, "text": "FULLPATH=$(readlink -f $0)\nINCPATH=${FULLPATH%/*}\n . $INCPATH/file_to_include.sh\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16258/" ]
192,294
<p>Background: We develop win32 applications, and use the "Thompson Toolkit" on windows to give us a unix-like shell that we use as our command-line.</p> <p>We have a GUI program (with a WinMain and message loop) that we want to write to the console, but printf and so on don't work, even when we launch the program from the console. How can we write to the console from a GUI program? We need to print text there so that an automated build system can display error messages and so on.</p> <p>Thanks.</p>
[ { "answer_id": 4990664, "author": "bkausbk", "author_id": 575491, "author_profile": "https://Stackoverflow.com/users/575491", "pm_score": 1, "selected": false, "text": "AllocConsole AttachConsole GetStdHandle _open_osfhandle stdin stdout printf" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13500/" ]
192,313
<p>I'm writing a Windows Forms Application in C#.NET</p> <p>On startup, the application displays a splash screen which is running in a separate thread. Whilst the splash screen is showing, the main application is initialising.</p> <p>Once the main application has finished initialising, the main form of the application is displayed, and the splash screen still shows over the top.</p> <p>Everything so far is as expected.</p> <p>Then, the Splash screen is closed, which causes that thread to exit. For some reason, at the point, the main application windows gets sent behind all other open Windows, notably the Windows Explorer window where you clicked the .exe file to run the application in the first place!</p> <p>What could be causing the windows to suddenly jump "behind" like this?</p>
[ { "answer_id": 192523, "author": "Jack Bolding", "author_id": 5882, "author_profile": "https://Stackoverflow.com/users/5882", "pm_score": 0, "selected": false, "text": "private void button1_Click(object sender, System.EventArgs e)\n{\n this.DialogResult = DialogResult.Abort;\n this.Hide();\n}\n" }, { "answer_id": 2933533, "author": "khoa", "author_id": 297124, "author_profile": "https://Stackoverflow.com/users/297124", "pm_score": -1, "selected": false, "text": "private void button1_Click(object sender, System.EventArgs e)\n{\n this.DialogResult = DialogResult.Abort;\n this.Hide();\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26906/" ]
192,319
<p>How can I determine the name of the Bash script file inside the script itself?</p> <p>Like if my script is in file <code>runme.sh</code>, then how would I make it to display "You are running runme.sh" message without hardcoding that?</p>
[ { "answer_id": 192337, "author": "Tanktalus", "author_id": 23512, "author_profile": "https://Stackoverflow.com/users/23512", "pm_score": 11, "selected": true, "text": "me=`basename \"$0\"`\n me=\"$(basename \"$(test -L \"$0\" && readlink \"$0\" || echo \"$0\")\")\"\n foo.sh bar.sh bar.sh foo.sh" }, { "answer_id": 192344, "author": "VolkA", "author_id": 25472, "author_profile": "https://Stackoverflow.com/users/25472", "pm_score": 3, "selected": false, "text": "basename $0\n" }, { "answer_id": 192358, "author": "Josh Lee", "author_id": 19750, "author_profile": "https://Stackoverflow.com/users/19750", "pm_score": 6, "selected": false, "text": "\"$0\" \"$(basename \"$0\")\" \"$(basename \\\"$0\\\")\"" }, { "answer_id": 192533, "author": "Travis B. Hartwell", "author_id": 10873, "author_profile": "https://Stackoverflow.com/users/10873", "pm_score": 5, "selected": false, "text": "echo $(basename $(readlink -nf $0))\n" }, { "answer_id": 192699, "author": "Mr. Muskrat", "author_id": 2657951, "author_profile": "https://Stackoverflow.com/users/2657951", "pm_score": 5, "selected": false, "text": "${0##*/}" }, { "answer_id": 639500, "author": "Dimitre Radoulov", "author_id": 430749, "author_profile": "https://Stackoverflow.com/users/430749", "pm_score": 8, "selected": false, "text": "$ ./s\n0 is: ./s\nBASH_SOURCE is: ./s\n$ . ./s\n0 is: bash\nBASH_SOURCE is: ./s\n\n$ cat s\n#!/bin/bash\n\nprintf '$0 is: %s\\n$BASH_SOURCE is: %s\\n' \"$0\" \"$BASH_SOURCE\"\n" }, { "answer_id": 3588939, "author": "Bill Hernandez", "author_id": 433461, "author_profile": "https://Stackoverflow.com/users/433461", "pm_score": 8, "selected": false, "text": "\n#!/bin/bash\n\necho\necho \"# arguments called with ----> ${@} \"\necho \"# \\$1 ----------------------> $1 \"\necho \"# \\$2 ----------------------> $2 \"\necho \"# path to me ---------------> ${0} \"\necho \"# parent path --------------> ${0%/*} \"\necho \"# my name ------------------> ${0##*/} \"\necho\nexit\n" }, { "answer_id": 3939695, "author": "simon", "author_id": 88411, "author_profile": "https://Stackoverflow.com/users/88411", "pm_score": 3, "selected": false, "text": "me=$(readlink --canonicalize --no-newline $0)\n me=$(readlink --canonicalize --no-newline $BASH_SOURCE)\n" }, { "answer_id": 5816258, "author": "Koter84", "author_id": 372131, "author_profile": "https://Stackoverflow.com/users/372131", "pm_score": 0, "selected": false, "text": "DIRECTORY=$(cd `dirname $0` && pwd)\n" }, { "answer_id": 6355632, "author": "Zainka", "author_id": 799290, "author_profile": "https://Stackoverflow.com/users/799290", "pm_score": 7, "selected": false, "text": "$BASH_SOURCE $(basename $BASH_SOURCE) \n" }, { "answer_id": 13382923, "author": "jcalfee314", "author_id": 766233, "author_profile": "https://Stackoverflow.com/users/766233", "pm_score": 3, "selected": false, "text": "this=\"$(dirname \"$(realpath \"$BASH_SOURCE\")\")\"\n" }, { "answer_id": 25596257, "author": "gkb0986", "author_id": 1988435, "author_profile": "https://Stackoverflow.com/users/1988435", "pm_score": 4, "selected": false, "text": "echo \"${BASH_SOURCE[${#BASH_SOURCE[@]} - 1]}\"\n readlink BASH_SOURCE FUNCNAME" }, { "answer_id": 28655324, "author": "linxuser", "author_id": 4593132, "author_profile": "https://Stackoverflow.com/users/4593132", "pm_score": 1, "selected": false, "text": "#!/bin/bash\nfunction Usage(){\n echo \" Usage: show_parameters [ arg1 ][ arg2 ]\"\n}\n[[ ${#2} -eq 0 ]] && Usage || {\n echo\n echo \"# arguments called with ----> ${@} \"\n echo \"# \\$1 -----------------------> $1 \"\n echo \"# \\$2 -----------------------> $2 \"\n echo \"# path to me ---------------> ${0} \" | sed \"s/$USER/\\$USER/g\"\n echo \"# parent path --------------> ${0%/*} \" | sed \"s/$USER/\\$USER/g\"\n echo \"# my name ------------------> ${0##*/} \"\n echo\n}\n" }, { "answer_id": 29672098, "author": "hynt", "author_id": 4723557, "author_profile": "https://Stackoverflow.com/users/4723557", "pm_score": -1, "selected": false, "text": "export LC_ALL=en_US.UTF-8\n#!/bin/bash\n#!/bin/sh\n\n#----------------------------------------------------------------------\nstart_trash(){\nver=\"htrash.sh v0.0.4\"\n$TRASH_DIR # url to trash $MY_USER\n$TRASH_SIZE # Show Trash Folder Size\n\necho \"Would you like to empty Trash [y/n]?\"\nread ans\nif [ $ans = y -o $ans = Y -o $ans = yes -o $ans = Yes -o $ans = YES ]\nthen\necho \"'yes'\"\ncd $TRASH_DIR && $EMPTY_TRASH\nfi\nif [ $ans = n -o $ans = N -o $ans = no -o $ans = No -o $ans = NO ]\nthen\necho \"'no'\"\nfi\n return $TRUE\n} \n#-----------------------------------------------------------------------\n\nstart_help(){\necho \"HELP COMMANDS-----------------------------\"\necho \"htest www open a homepage \"\necho \"htest trash empty trash \"\n return $TRUE\n} #end Help\n#-----------------------------------------------#\n\nhomepage=\"\"\n\nreturn $TRUE\n} #end cpdebtemp\n\n# -Case start\n# if no command line arg given\n# set val to Unknown\nif [ -z $1 ]\nthen\n val=\"*** Unknown ***\"\nelif [ -n $1 ]\nthen\n# otherwise make first arg as val\n val=$1\nfi\n# use case statement to make decision for rental\ncase $val in\n \"trash\") start_trash ;;\n \"help\") start_help ;;\n \"www\") firefox $homepage ;;\n *) echo \"Sorry, I can not get a $val for you!\";;\nesac\n# Case stop\n" }, { "answer_id": 41842579, "author": "LawrenceLi", "author_id": 2338372, "author_profile": "https://Stackoverflow.com/users/2338372", "pm_score": 3, "selected": false, "text": "/home/mike/runme.sh\n /home/mike/runme.sh\n runme.sh\n filename=$(basename $0)\n echo \"You are running $filename\"\n /home/mike/runme.sh\n#!/bin/bash \nfilename=$(basename $0)\necho \"You are running $filename\"\n" }, { "answer_id": 45658001, "author": "ecwpz91", "author_id": 7497692, "author_profile": "https://Stackoverflow.com/users/7497692", "pm_score": 2, "selected": false, "text": "echo \"$(basename \"`test -L ${BASH_SOURCE[0]} \\\n && readlink ${BASH_SOURCE[0]} \\\n || echo ${BASH_SOURCE[0]}`\")\"\n" }, { "answer_id": 48344019, "author": "rashok", "author_id": 596370, "author_profile": "https://Stackoverflow.com/users/596370", "pm_score": 2, "selected": false, "text": "bash $0 $1 $2 $0 #!/bin/bash\necho \"You are running $0\"\n...\n...\n /path/to/script.sh $0 $(basename $0)" }, { "answer_id": 48628868, "author": "Simon Mattes", "author_id": 3687883, "author_profile": "https://Stackoverflow.com/users/3687883", "pm_score": 4, "selected": false, "text": "FileName=${0##*/}\nFileNameWithoutExtension=${FileName%.*}\n" }, { "answer_id": 53457925, "author": "Salathiel Genèse", "author_id": 3748178, "author_profile": "https://Stackoverflow.com/users/3748178", "pm_score": 0, "selected": false, "text": "script=\"$BASH_SOURCE\"\n[ -z \"$BASH_SOURCE\" ] && script=\"$0\"\n\necho \"Called $script with $# argument(s)\"\n . path/to/script.sh\n ./path/to/script.sh\n" }, { "answer_id": 57553697, "author": "Bơ Loong A Nhứi", "author_id": 4728084, "author_profile": "https://Stackoverflow.com/users/4728084", "pm_score": 2, "selected": false, "text": "my_script.sh #!/bin/bash\n\nrunning_file_name=$(basename \"$0\")\n\necho \"You are running '$running_file_name' file.\"\n ./my_script.sh\nYou are running 'my_script.sh' file.\n" }, { "answer_id": 64516836, "author": "Nishant", "author_id": 452102, "author_profile": "https://Stackoverflow.com/users/452102", "pm_score": 3, "selected": false, "text": "./self.sh ~/self.sh source self.sh source ~/self.sh #!/usr/bin/env bash\n\nself=$(readlink -f \"${BASH_SOURCE[0]}\")\nbasename=$(basename \"$self\")\n\necho \"$self\"\necho \"$basename\"\n" }, { "answer_id": 68599693, "author": "Ali Yar Khan", "author_id": 9138027, "author_profile": "https://Stackoverflow.com/users/9138027", "pm_score": 0, "selected": false, "text": "#!/bin/bash\necho \"Name of the file is $0\"\n ./file_name.sh\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20390/" ]
192,329
<p>I have boiled down an issue I'm seeing in one of my applications to an incredibly simple reproduction sample. I need to know if there's something amiss or something I'm missing.</p> <p>Anyway, below is the code. The behavior is that the code runs and steadily grows in memory until it crashes with an OutOfMemoryException. That takes a while, but the behavior is that objects are being allocated and are not being garbage collected. </p> <p>I've taken memory dumps and ran !gcroot on some things as well as used ANTS to figure out what the problem is, but I've been at it for a while and need some new eyes.</p> <p>This reproduction sample is a simple console application that creates a Canvas and adds a Line to it. It does this continually. This is all the code does. It sleeps every now and again to ensure that the CPU is not so taxed that your system is unresponsive (and to ensure there's no weirdness with the GC not being able to run). </p> <p>Anyone have any thoughts? I've tried this with .NET 3.0 only, .NET 3.5 and also .NET 3.5 SP1 and the same behavior occurred in all three environments.</p> <p>Also note that I've put this code in a WPF application project as well and triggered the code in a button click and it occurs there too.</p> <pre> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Controls; using System.Windows.Shapes; using System.Windows; namespace SimplestReproSample { class Program { [STAThread] static void Main(string[] args) { long count = 0; while (true) { if (count++ % 100 == 0) { // sleep for a while to ensure we aren't using up the whole CPU System.Threading.Thread.Sleep(50); } BuildCanvas(); } } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void BuildCanvas() { Canvas c = new Canvas(); Line line = new Line(); line.X1 = 1; line.Y1 = 1; line.X2 = 100; line.Y2 = 100; line.Width = 100; c.Children.Add(line); c.Measure(new Size(300, 300)); c.Arrange(new Rect(0, 0, 300, 300)); } } } </pre> <p>NOTE: the first answer below is a bit off-base since I explicitly stated already that this same behavior occurs during a WPF application's button click event. I did not explicitly state, however, that in that app I only do a limited number of iterations (say 1000). Doing it that way would allow the GC to run as you click around the application. Also note that I explicitly said I've taken a memory dump and found my objects were rooted via !gcroot. I also disagree that the GC would not be able to run. The GC does not run on my console application's main thread, especially since I'm on a dual core machine which means the Concurrent Workstation GC is active. Message pump, however, yes.</p> <p>To prove the point, here's a WPF application version that runs the test on a DispatcherTimer. It performs 1000 iterations during a 100ms timer interval. More than enough time to process any messages out of the pump and keep the CPU usage low.</p> <pre> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Shapes; namespace SimpleReproSampleWpfApp { public partial class Window1 : Window { private System.Windows.Threading.DispatcherTimer _timer; public Window1() { InitializeComponent(); _timer = new System.Windows.Threading.DispatcherTimer(); _timer.Interval = TimeSpan.FromMilliseconds(100); _timer.Tick += new EventHandler(_timer_Tick); _timer.Start(); } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] void RunTest() { for (int i = 0; i &lt; 1000; i++) { BuildCanvas(); } } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void BuildCanvas() { Canvas c = new Canvas(); Line line = new Line(); line.X1 = 1; line.Y1 = 1; line.X2 = 100; line.Y2 = 100; line.Width = 100; c.Children.Add(line); c.Measure(new Size(300, 300)); c.Arrange(new Rect(0, 0, 300, 300)); } void _timer_Tick(object sender, EventArgs e) { _timer.Stop(); RunTest(); _timer.Start(); } } } </pre> <p>NOTE2: I used the code from the first answer and my memory grew very slowly. Note that 1ms is much slower and less iterations than my example. You have to let it run for a couple minutes before you start to notice growth. After 5 minutes it's at 46MB from a starting point of 30MB. </p> <p>NOTE3: Removing the call to .Arrange completely eliminates the growth. Unfortunately, that call is pretty vital to my use since in many cases I'm creating PNG files from the Canvas (via the RenderTargetBitmap class). Without the call to .Arrange it doesn't layout the canvas at all.</p>
[ { "answer_id": 192421, "author": "Joel B Fant", "author_id": 22211, "author_profile": "https://Stackoverflow.com/users/22211", "pm_score": 0, "selected": false, "text": "Timer public partial class Window1 : Window {\n Class1 c;\n DispatcherTimer t;\n int count = 0;\n public Window1() {\n InitializeComponent();\n\n t = new DispatcherTimer();\n t.Interval = TimeSpan.FromMilliseconds( 1 );\n t.Tick += new EventHandler( t_Tick );\n t.Start();\n }\n\n void t_Tick( object sender, EventArgs e ) {\n count++;\n BuildCanvas();\n }\n\n private static void BuildCanvas() {\n Canvas c = new Canvas();\n\n Line line = new Line();\n line.X1 = 1;\n line.Y1 = 1;\n line.X2 = 100;\n line.Y2 = 100;\n line.Width = 100;\n c.Children.Add( line );\n\n c.Measure( new Size( 300, 300 ) );\n c.Arrange( new Rect( 0, 0, 300, 300 ) );\n }\n}\n" }, { "answer_id": 193609, "author": "Bradley Grainger", "author_id": 23633, "author_profile": "https://Stackoverflow.com/users/23633", "pm_score": 5, "selected": true, "text": "c.UpdateLayout()\n BuildCanvas Canvas UIElement" }, { "answer_id": 3614625, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "App.xaml.cs public partial class App : Application\n{\n public App() \n { \n new HwndSource(new HwndSourceParameters()); \n } \n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13322/" ]
192,332
<p>What I am looking for is a way to call a method after another method has been invoked but before it is entered. Example:</p> <pre><code>public class Test { public void Tracer ( ... ) { } public int SomeFunction( string str ) { return 0; } public void TestFun() { SomeFunction( "" ); } } </code></pre> <p>In the example above I would like to have Tracer() called after SomeFunction() has been invoked by TestFun() but before SomeFunction() is entered. I'd also like to get reflection data on SomeFunction().</p> <hr> <p>I found something interesting in everyone's answers. The <strong>best answer to the question</strong> is to use Castle's DynamicProxy; however, this is not that I'm going to use to solve my problem because it requires adding a library to my project. I have only a few methods that I need to "trace" so I've chosen to go with a modified "core" methodology mixed with the way Dynamic Proxy is implemented. I explain this in my answer to my own question below.</p> <p>Just as a note I'm going to be looking into AOP and the ContextBoundObject class for some other applications.</p>
[ { "answer_id": 192355, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 2, "selected": false, "text": "public int SomeFunction(string str)\n{\n Tracer();\n return SomeFunctionCore(str);\n}\n\nprivate int SomeFunctionCore(string str)\n{\n return 0;\n}\n" }, { "answer_id": 193587, "author": "jr.", "author_id": 2415, "author_profile": "https://Stackoverflow.com/users/2415", "pm_score": 0, "selected": false, "text": "public class TestClass {\n\n public virtual void int SomeFunction( string /*str*/ )\n {\n return 0;\n }\n\n\n public void TestFun()\n {\n SomeFunction( \"\" );\n }\n\n}\n\n\npublic class TestClassTracer : TestClass {\n\n public override void int SomeFunction( string str )\n {\n // do something\n return base.SomeFunction( str );\n }\n\n}\n" }, { "answer_id": 194287, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "delegate void SomeFunctionDelegate(string s);\n\nvoid Start()\n{\n TraceAndThenCallMethod(SomeFunction, \"hoho\");\n}\n\nvoid SomeFunction(string str)\n{\n //Do stuff with str\n}\n\nvoid TraceAndThenCallMethod(SomeFunctionDelegate sfd, string parameter)\n{\n Trace();\n sfd(parameter);\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2415/" ]
192,345
<p>I would like to use Pylons with Elixir, however, I am not sure what is the best way to get about doing this. There are several blog posts (<a href="http://cleverdevil.org/computing/68/" rel="nofollow noreferrer" title="cleverdevil&#39;s technique">cleverdevil</a>, <a href="http://beachcoder.wordpress.com/2007/05/11/using-elixir-with-pylons/" rel="nofollow noreferrer" title="beachcoder&#39;s technique">beachcoder</a>, <a href="http://hoscilo.pypla.net/2007/03/19/sqlalchemy-elixir-and-pylons-round-one/" rel="nofollow noreferrer" title="adam hoscilo&#39;s technique">adam hoscilo</a>) and even an <a href="http://code.google.com/p/tesla-pylons-elixir/" rel="nofollow noreferrer" title="tesla">entire new framework</a> about how to go about doing this; however, I am not certain about the differences between them. Which one is the best to use? Am I going to run into issues using one over the other? </p> <p>I would prefer not to have to use SQLAlchemy directly because of its verbosity and repetitiveness. </p>
[ { "answer_id": 192355, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 2, "selected": false, "text": "public int SomeFunction(string str)\n{\n Tracer();\n return SomeFunctionCore(str);\n}\n\nprivate int SomeFunctionCore(string str)\n{\n return 0;\n}\n" }, { "answer_id": 193587, "author": "jr.", "author_id": 2415, "author_profile": "https://Stackoverflow.com/users/2415", "pm_score": 0, "selected": false, "text": "public class TestClass {\n\n public virtual void int SomeFunction( string /*str*/ )\n {\n return 0;\n }\n\n\n public void TestFun()\n {\n SomeFunction( \"\" );\n }\n\n}\n\n\npublic class TestClassTracer : TestClass {\n\n public override void int SomeFunction( string str )\n {\n // do something\n return base.SomeFunction( str );\n }\n\n}\n" }, { "answer_id": 194287, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "delegate void SomeFunctionDelegate(string s);\n\nvoid Start()\n{\n TraceAndThenCallMethod(SomeFunction, \"hoho\");\n}\n\nvoid SomeFunction(string str)\n{\n //Do stuff with str\n}\n\nvoid TraceAndThenCallMethod(SomeFunctionDelegate sfd, string parameter)\n{\n Trace();\n sfd(parameter);\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12682/" ]
192,366
<p>Is it possible to grab activedirectory credentials for the user on a client machine from within a web application?</p> <p>To clarify, I am designing a web application which will be hosted on a client's intranet. </p> <p>There is a requirement that the a user of the application not be prompted for credentials when accessing the application, and that instead the credentials of the user logged onto the client machine should be grabbed automatically, without user interaction.</p>
[ { "answer_id": 192414, "author": "Sean Hanley", "author_id": 7290, "author_profile": "https://Stackoverflow.com/users/7290", "pm_score": 3, "selected": false, "text": "using System.DirectoryServices;\n\n/// <summary>\n/// Gets the email address, if defined, of a user from Active Directory.\n/// </summary>\n/// <param name=\"userid\">The userid of the user in question. Make\n/// sure the domain has been stripped first!</param>\n/// <returns>A string containing the user's email address, or null\n/// if one was not defined or found.</returns>\npublic static string GetEmail(string userid)\n{\n DirectorySearcher searcher;\n SearchResult result;\n string email;\n\n // Check first if there is a slash in the userid\n // If there is, domain has not been stripped\n if (!userid.Contains(\"\\\\\"))\n {\n searcher = new DirectorySearcher();\n searcher.Filter = String.Format(\"(SAMAccountName={0})\", userid);\n searcher.PropertiesToLoad.Add(\"mail\");\n result = searcher.FindOne();\n if (result != null)\n {\n email = result.Properties[\"mail\"][0].ToString();\n }\n }\n\n return email;\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26527/" ]
192,367
<p>I have the following two models:</p> <pre><code>class Activity(models.Model): name = models.CharField(max_length=50, help_text='Some help.') entity = models.ForeignKey(CancellationEntity) ... class Cancellation(models.Model): activity = models.ForeignKey(Activity) date = models.DateField(default=datetime.now().date()) description = models.CharField(max_length=250) ... </code></pre> <p>I would like the Activity model to be aware when a Cancellation related to it is saved (both inserted or updated).</p> <p>What is the best way to go about this?</p>
[ { "answer_id": 192525, "author": "willurd", "author_id": 1943957, "author_profile": "https://Stackoverflow.com/users/1943957", "pm_score": 5, "selected": true, "text": "from django.db.models.signals import post_save\n\nclass Activity(models.Model):\n name = models.CharField(max_length=50, help_text='Some help.')\n entity = models.ForeignKey(CancellationEntity)\n\n @classmethod\n def cancellation_occurred (sender, instance, created, raw):\n # grab the current instance of Activity\n self = instance.activity_set.all()[0]\n # do something\n ...\n\n\nclass Cancellation(models.Model):\n activity = models.ForeignKey(Activity)\n date = models.DateField(default=datetime.now().date())\n description = models.CharField(max_length=250)\n ...\n\npost_save.connect(Activity.cancellation_occurred, sender=Cancellation)" }, { "answer_id": 193217, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 3, "selected": false, "text": "class Cancellation( models.Model ):\n blah\n blah\n def save( self, **kw ):\n for a in self.activity_set.all():\n a.somethingChanged( self )\n super( Cancellation, self ).save( **kw )\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10825/" ]
192,373
<p>Is it possible to programmatically force a full garbage collection run in ActionScript 3.0?</p> <p>Let's say I've created a bunch of Display objects with eventListeners and some of the DO's have been removed, some of the eventListeners have been triggered and removed etc... Is there a way to force garbage collection to run and collect everything that is available to be collected?</p>
[ { "answer_id": 192418, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 6, "selected": true, "text": "System.gc()" }, { "answer_id": 2295438, "author": "FredV", "author_id": 30829, "author_profile": "https://Stackoverflow.com/users/30829", "pm_score": 2, "selected": false, "text": "<mx:DataGrid id=\"mygrid\" dataProvider=\"{DataCacher.instance().result('method').data}\" ... />\n" }, { "answer_id": 5719310, "author": "Sean", "author_id": 715571, "author_profile": "https://Stackoverflow.com/users/715571", "pm_score": 2, "selected": false, "text": "try {\n new LocalConnection().connect('foo');\n new LocalConnection().connect('foo');\n} catch (e:*){\n trace(\"Forcing Garbage Collection :\"+e.toString());\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10875/" ]
192,375
<p>When using <code>before_filter :login_required</code> to protect a particular page, the <code>link_to_unless_current</code> method in the application layout template renders the "Login" link for the login page as a hyperlink instead of just text.</p> <p>The "Login" text/link problem only occurs when redirected to the Login Page via the <code>before_filter</code> machinery, otherwise, the <code>link_to_unless_current</code> method operates as expected.</p> <p>It seems that <code>link_to_unless_current</code> is using the old page data as the "current" instead of the login page (when redirecting).</p>
[ { "answer_id": 527112, "author": "Toby Hede", "author_id": 14971, "author_profile": "https://Stackoverflow.com/users/14971", "pm_score": 1, "selected": false, "text": " redirect_to login_url\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
192,398
<p>I am selecting from a table that has an XML column using T-SQL. I would like to select a certain type of node and have a row created for each one.</p> <p>For instance, suppose I am selecting from a <em>people</em> table. This table has an XML column for <em>addresses</em>. The XML is formated similar to the following:</p> <pre><code>&lt;address&gt; &lt;street&gt;Street 1&lt;/street&gt; &lt;city&gt;City 1&lt;/city&gt; &lt;state&gt;State 1&lt;/state&gt; &lt;zipcode&gt;Zip Code 1&lt;/zipcode&gt; &lt;/address&gt; &lt;address&gt; &lt;street&gt;Street 2&lt;/street&gt; &lt;city&gt;City 2&lt;/city&gt; &lt;state&gt;State 2&lt;/state&gt; &lt;zipcode&gt;Zip Code 2&lt;/zipcode&gt; &lt;/address&gt; </code></pre> <p>How can I get results like this:</p> <p><strong>Name</strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>City</strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>State</strong></p> <p>Joe Baker&nbsp;&nbsp;&nbsp;Seattle&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;WA</p> <p>Joe Baker&nbsp;&nbsp;&nbsp;Tacoma&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;WA</p> <p>Fred Jones&nbsp;&nbsp;Vancouver&nbsp;BC</p>
[ { "answer_id": 192445, "author": "Wyatt", "author_id": 26626, "author_profile": "https://Stackoverflow.com/users/26626", "pm_score": -1, "selected": false, "text": "var addresses = dataContext.People.Addresses\n .Elements(\"address\")\n .Select(address => new { \n street = address.Element(\"street\").Value, \n city = address.Element(\"city\").Value, \n state = address.Element(\"state\").Value, \n zipcode = address.Element(\"zipcode\").Value, \n });\n" }, { "answer_id": 193625, "author": "leoinfo", "author_id": 6948, "author_profile": "https://Stackoverflow.com/users/6948", "pm_score": 6, "selected": true, "text": "/* TEST TABLE */\nDECLARE @PEOPLE AS TABLE ([Name] VARCHAR(20), [Address] XML )\nINSERT INTO @PEOPLE SELECT \n 'Joel', \n '<address>\n <street>Street 1</street>\n <city>City 1</city>\n <state>State 1</state>\n <zipcode>Zip Code 1</zipcode>\n </address>\n <address>\n <street>Street 2</street>\n <city>City 2</city>\n <state>State 2</state>\n <zipcode>Zip Code 2</zipcode>\n </address>'\nUNION ALL SELECT\n 'Kim', \n '<address>\n <street>Street 3</street>\n <city>City 3</city>\n <state>State 3</state>\n <zipcode>Zip Code 3</zipcode>\n </address>'\n\nSELECT * FROM @PEOPLE\n\n-- BUILD XML\nDECLARE @x XML\nSELECT @x = \n( SELECT \n [Name]\n , [Address].query('\n for $a in //address\n return <address \n street=\"{$a/street}\" \n city=\"{$a/city}\" \n state=\"{$a/state}\" \n zipcode=\"{$a/zipcode}\" \n />\n ') \n FROM @PEOPLE AS people \n FOR XML AUTO\n) \n\n-- RESULTS\nSELECT [Name] = T.Item.value('../@Name', 'varchar(20)'),\n street = T.Item.value('@street' , 'varchar(20)'),\n city = T.Item.value('@city' , 'varchar(20)'),\n state = T.Item.value('@state' , 'varchar(20)'),\n zipcode = T.Item.value('@zipcode', 'varchar(20)')\nFROM @x.nodes('//people/address') AS T(Item)\n\n/* OUTPUT*/\n\nName | street | city | state | zipcode\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nJoel | Street 1 | City 1 | State 1 | Zip Code 1\nJoel | Street 2 | City 2 | State 2 | Zip Code 2\nKim | Street 3 | City 3 | State 3 | Zip Code 3\n" }, { "answer_id": 194657, "author": "6eorge Jetson", "author_id": 23422, "author_profile": "https://Stackoverflow.com/users/23422", "pm_score": 1, "selected": false, "text": "\n\nDECLARE @xmlEntityList xml\nSET @xmlEntityList =\n'\n<ArbitrarilyNamedXmlListElement>\n <ArbitrarilyNamedXmlItemElement><SomeVeryImportantInteger>1</SomeVeryImportantInteger></ArbitrarilyNamedXmlItemElement>\n <ArbitrarilyNamedXmlItemElement><SomeVeryImportantInteger>2</SomeVeryImportantInteger></ArbitrarilyNamedXmlItemElement>\n <ArbitrarilyNamedXmlItemElement><SomeVeryImportantInteger>3</SomeVeryImportantInteger></ArbitrarilyNamedXmlItemElement>\n</ArbitrarilyNamedXmlListElement>\n'\n\n DECLARE @tblEntityList TABLE(\n SomeVeryImportantInteger int\n )\n\n INSERT @tblEntityList(SomeVeryImportantInteger)\n SELECT \n XmlItem.query('//SomeVeryImportantInteger[1]').value('.','int') as SomeVeryImportantInteger\n FROM\n [dbo].[tvfShredGetOneColumnedTableOfXmlItems] (@xmlEntityList)\n\n\n \n/* Example Inputs */\n/*\nDECLARE @xmlListFormat xml\nSET @xmlListFormat =\n '\n <ArbitrarilyNamedXmlListElement>\n <ArbitrarilyNamedXmlItemElement>004421UB7</ArbitrarilyNamedXmlItemElement>\n <ArbitrarilyNamedXmlItemElement>59020UH24</ArbitrarilyNamedXmlItemElement>\n <ArbitrarilyNamedXmlItemElement>542514NA8</ArbitrarilyNamedXmlItemElement>\n </ArbitrarilyNamedXmlListElement>\n '\ndeclare @tblResults TABLE \n(\n XmlItem xml\n)\n\n*/\n\n-- =============================================\n-- Author: 6eorge Jetson\n-- Create date: 01/02/3003\n-- Description: Shreds a list of XML items conforming to\n-- the expected generic @xmlListFormat\n-- =============================================\nCREATE FUNCTION [dbo].[tvfShredGetOneColumnedTableOfXmlItems] \n(\n -- Add the parameters for the function here\n @xmlListFormat xml\n)\nRETURNS \n@tblResults TABLE \n(\n -- Add the column definitions for the TABLE variable here\n XmlItem xml\n)\nAS\nBEGIN\n\n -- Fill the table variable with the rows for your result set\n INSERT @tblResults\n SELECT\n tblShredded.colXmlItem.query('.') as XmlItem\n FROM\n @xmlListFormat.nodes('/child::*/child::*') as tblShredded(colXmlItem)\n\n RETURN \nEND\n\n--SELECT * FROM @tblResults\n\n" }, { "answer_id": 33355283, "author": "JohnLBevan", "author_id": 361842, "author_profile": "https://Stackoverflow.com/users/361842", "pm_score": 0, "selected": false, "text": ";with cte as \n(\n select id, name, addresses, addresses.value('count(/address/city)','int') cnt\n from @demo\n)\n, cte2 as\n(\n select id, name, addresses, addresses.value('((/address/city)[sql:column(\"cnt\")])[1]','nvarchar(256)') city, cnt-1 idx \n from cte \n where cnt > 0\n\n union all\n\n select cte.id, cte.name, cte.addresses, cte.addresses.value('((/address/city)[sql:column(\"cte2.idx\")])[1]','nvarchar(256)'), cte2.idx-1 \n from cte2 \n inner join cte on cte.id = cte2.id and cte2.idx > 0\n)\nselect id, name, city \nfrom cte2 \norder by id, city\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3645/" ]
192,413
<p>I have a RichTextBox where I need to update the Text property frequently, but when I do so the RichTextBox "blinks" annoyingly as it refreshes all throughout a method call.</p> <p>I was hoping to find an easy way to temporarily suppress the screen refresh until my method is done, but the only thing I've found on the web is to override the WndProc method. I've employed this approach, but with some difficulty and side effects, and it makes debugging harder, too. It just seems like there's got to be a better way of doing this. Can someone point me to a better solution?</p>
[ { "answer_id": 192423, "author": "BKimmel", "author_id": 13776, "author_profile": "https://Stackoverflow.com/users/13776", "pm_score": -1, "selected": false, "text": "myRichTextBox.SuspendLayout();\nDoStuff();\nmyRichTextBox.ResumeLayout();\n" }, { "answer_id": 192461, "author": "BoltBait", "author_id": 20848, "author_profile": "https://Stackoverflow.com/users/20848", "pm_score": 2, "selected": false, "text": "protected override void WndProc(ref Message m)\n{\n if (m.Msg == paint)\n {\n if (!highlighting)\n {\n base.WndProc(ref m); // if we decided to paint this control, just call the RichTextBox WndProc\n }\n else\n {\n m.Result = IntPtr.Zero; // not painting, must set this to IntPtr.Zero if not painting otherwise serious problems.\n }\n }\n else\n {\n base.WndProc(ref m); // message other than paint, just do what you normally do.\n }\n}\n" }, { "answer_id": 192499, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "\n[DllImport(\"user32.dll\", EntryPoint=\"LockWindowUpdate\", SetLastError=true,\nExactSpelling=true, CharSet=CharSet.Auto,\nCallingConvention=CallingConvention.StdCall)]\n" }, { "answer_id": 194500, "author": "JohnnyM", "author_id": 27109, "author_profile": "https://Stackoverflow.com/users/27109", "pm_score": 4, "selected": false, "text": " private void StopRepaint()\n {\n // Stop redrawing:\n SendMessage(this.Handle, WM_SETREDRAW, 0, IntPtr.Zero);\n // Stop sending of events:\n eventMask = SendMessage(this.Handle, EM_GETEVENTMASK, 0, IntPtr.Zero);\n }\n\n private void StartRepaint()\n {\n // turn on events\n SendMessage(this.Handle, EM_SETEVENTMASK, 0, eventMask);\n // turn on redrawing\n SendMessage(this.Handle, WM_SETREDRAW, 1, IntPtr.Zero);\n // this forces a repaint, which for some reason is necessary in some cases.\n this.Invalidate();\n }\n" }, { "answer_id": 26088349, "author": "puch4tek", "author_id": 1456212, "author_profile": "https://Stackoverflow.com/users/1456212", "pm_score": 4, "selected": false, "text": " private const int WM_USER = 0x0400;\n private const int EM_SETEVENTMASK = (WM_USER + 69);\n private const int WM_SETREDRAW = 0x0b;\n private IntPtr OldEventMask; \n\n [DllImport(\"user32.dll\", CharSet=CharSet.Auto)]\n private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);\n\n public void BeginUpdate()\n {\n SendMessage(this.Handle, WM_SETREDRAW, IntPtr.Zero, IntPtr.Zero);\n OldEventMask = (IntPtr)SendMessage(this.Handle, EM_SETEVENTMASK, IntPtr.Zero, IntPtr.Zero);\n } \n\n public void EndUpdate()\n {\n SendMessage(this.Handle, WM_SETREDRAW, (IntPtr)1, IntPtr.Zero);\n SendMessage(this.Handle, EM_SETEVENTMASK, IntPtr.Zero, OldEventMask);\n }\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
192,417
<p>Personally, I find the range of functionality provided by java.util.Iterator to be fairly pathetic. At a minimum, I'd like to have methods such as:</p> <ul> <li>peek() returns next element without moving the iterator forward</li> <li>previous() returns the previous element</li> </ul> <p>Though there are lots of other possibilities such as first() and last().</p> <p>Does anyone know if such a 3rd party iterator exists? It would probably need to be implemented as a decorator of java.util.Iterator so that it can work with the existing java collections. Ideally, it should be "generics aware".</p> <p>Thanks in advance, Don</p>
[ { "answer_id": 192449, "author": "William", "author_id": 9193, "author_profile": "https://Stackoverflow.com/users/9193", "pm_score": 4, "selected": false, "text": "previous() java.util.ListIterator public <T> T peek(ListIterator<T> iter) throws NoSuchElementException {\n T obj = iter.next();\n iter.previous();\n return obj;\n}\n MyListIterator" }, { "answer_id": 192623, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 2, "selected": false, "text": "previous ListIterator<>" }, { "answer_id": 613702, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "public class Iterazor<T> {\n private Iterator<T> it;\n public T top;\n public Iterazor(Collection<T> co) {\n this.it = co.iterator(); \n top = it.hasNext()? it.next(): null; \n }\n public void advance() { \n top = it.hasNext()? it.next(): null; \n }\n}\n\n// usage\n\nfor(Iterazor<MyObject> iz = new Iterazor<MyObject>(MyCollection); \n iz.top!=null; iz.advance())\n iz.top.doStuff();\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
192,432
<p>I've tried to use the new <a href="http://groovy.codehaus.org/Grape" rel="noreferrer">Groovy Grape</a> capability in Groovy 1.6-beta-2 but I get an error message;</p> <pre><code>unable to resolve class com.jidesoft.swing.JideSplitButton </code></pre> <p>from the Groovy Console (/opt/groovy/groovy-1.6-beta-2/bin/groovyConsole) when running the stock example;</p> <pre><code>import com.jidesoft.swing.JideSplitButton @Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,)') public class TestClassAnnotation { public static String testMethod () { return JideSplitButton.class.name } } </code></pre> <p>I even tried running the grape command line tool to ensure the library is imported. Like this;</p> <pre><code> $ /opt/groovy/groovy-1.6-beta-2/bin/grape install com.jidesoft jide-oss </code></pre> <p>which does install the library just fine. How do I get the code to run/compile correctly from the groovyConsole?</p>
[ { "answer_id": 194403, "author": "shemnon", "author_id": 8020, "author_profile": "https://Stackoverflow.com/users/8020", "pm_score": 4, "selected": true, "text": "groovy.grape.Grape.initGrape()\n import com.jidesoft.swing.JideSplitButton\n\n@Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,2.3.0)')\npublic class TestClassAnnotation {\n public static String testMethod () {\n return JideSplitButton.class.name\n }\n}\n\nnew TestClassAnnotation().testMethod()\n" }, { "answer_id": 194439, "author": "Bob Herrmann", "author_id": 6580, "author_profile": "https://Stackoverflow.com/users/6580", "pm_score": 2, "selected": false, "text": "groovy.grape.Grape.initGrape()\n@Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,2.3.0)')\npublic class UsedToExposeAnnotationToComplier {}\ncom.jidesoft.swing.JideSplitButton.class.name\n" }, { "answer_id": 473172, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "// create and use a primitive array\nimport org.apache.commons.collections.primitives.ArrayIntList\n\n@Grab(group='commons-primitives', module='commons-primitives', version='1.0')\ndef createEmptyInts() { new ArrayIntList() }\n\ndef ints = createEmptyInts()\nints.add(0, 42)\nassert ints.size() == 1\nassert ints.get(0) == 42\n" }, { "answer_id": 498908, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "// find the PDF links in the Java 1.5.0 documentation\n@Grab(group='org.ccil.cowan.tagsoup', module='tagsoup', version='0.9.7')\ndef getHtml() {\n def parser = new XmlParser(new org.ccil.cowan.tagsoup.Parser())\n parser.parse(\"http://java.sun.com/j2se/1.5.0/download-pdf.html\")\n}\nhtml.body.'**'.a.@href.grep(~/.*\\.pdf/).each{ println it }\n" }, { "answer_id": 498942, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "Grab getFruit // Google Collections example\nimport com.google.common.collect.HashBiMap\n@Grab(group='com.google.code.google-collections', module='google-collect', version='snapshot-20080530')\ndef getFruit() { [grape:'purple', lemon:'yellow', orange:'orange'] as HashBiMap }\nassert fruit.inverse().yellow == 'lemon'\n" }, { "answer_id": 1628995, "author": "Jim Morris", "author_id": 197091, "author_profile": "https://Stackoverflow.com/users/197091", "pm_score": 3, "selected": false, "text": "groovy:000> import groovy.grape.Grape\ngroovy:000> Grape.grab(group:'org.codehaus.groovy.modules.http-builder', module:'http-builder', version:'0.5.0-RC2')\ngroovy:000> def http= new groovyx.net.http.HTTPBuilder('http://rovio')\n===> groovyx.net.http.HTTPBuilder@91520\n" }, { "answer_id": 20473287, "author": "Daniel Ribeiro", "author_id": 1790092, "author_profile": "https://Stackoverflow.com/users/1790092", "pm_score": 0, "selected": false, "text": "@Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,)')\nimport com.jidesoft.swing.JideSplitButton\npublic class TestClassAnnotation {\n public static String testMethod () {\n return JideSplitButton.class.name\n }\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6580/" ]
192,454
<p>I have TortoiseSVN set up to use KDiff3 as the conflict resolution tool (I find it shows more information useful to the merge than the built-in TortoiseMerge does).</p> <p>When I open a file with Tortoise's "Edit Conflicts" command it shows me the three files and I have to select "Merge->Merge Current File" manually. The problem is that KDiff3 saves the result to <code>source_file.working</code> instead of to <code>source_file</code>. So without doing a Save As, the real file with the conflict doesn't get modified. Is there a way around doing this manual Save As every time?</p> <p>I know this isn't strictly a programming question but it's about an ancillary process common enough to programmers that it should be useful here. I couldn't find the answer to this elsewhere.</p>
[ { "answer_id": 192558, "author": "Owen", "author_id": 4790, "author_profile": "https://Stackoverflow.com/users/4790", "pm_score": 3, "selected": false, "text": "kdiff3.exe -o C:\\Program Files\\KDiff3\\kdiff3.exe %base %theirs %mine -o %merged\n" }, { "answer_id": 200657, "author": "Milen A. Radev", "author_id": 15785, "author_profile": "https://Stackoverflow.com/users/15785", "pm_score": 6, "selected": true, "text": "\"C:\\Program Files\\KDiff3\\kdiff3.exe\" %base %mine %theirs -o %merged --L1 Base --L2 Mine --L3 Theirs\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4790/" ]
192,456
<p>I would like to set the log file name for a log4j and log4net appender to have the current date. We are doing Daily rollovers but the current log file does not have a date. The log file name format would be </p> <pre><code>logname.2008-10-10.log </code></pre> <p>Anyone know the best way for me to do this?</p> <p>edit: I forgot to mention that we would want to do this in log4net as well. Plus any solution would need to be usable in JBoss.</p>
[ { "answer_id": 192548, "author": "gedevan", "author_id": 20225, "author_profile": "https://Stackoverflow.com/users/20225", "pm_score": 7, "selected": true, "text": "<appender name=\"roll\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n <param name=\"File\" value=\"application.log\" />\n <param name=\"DatePattern\" value=\".yyyy-MM-dd\" />\n <layout class=\"org.apache.log4j.PatternLayout\"> \n <param name=\"ConversionPattern\" \n value=\"%d{yyyy-MMM-dd HH:mm:ss,SSS} [%t] %c %x%n %-5p %m%n\"/>\n </layout>\n </appender>\n" }, { "answer_id": 192632, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 4, "selected": false, "text": "DatePattern" }, { "answer_id": 192744, "author": "James A. N. Stauffer", "author_id": 6770, "author_profile": "https://Stackoverflow.com/users/6770", "pm_score": 4, "selected": false, "text": "/*\n * Copyright (C) The Apache Software Foundation. All rights reserved.\n *\n * This software is published under the terms of the Apache Software\n * License version 1.1, a copy of which has been included with this\n * distribution in the LICENSE.txt file. */\n\npackage sps.log.log4j;\n\nimport java.io.IOException;\nimport java.io.File;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\n\nimport org.apache.log4j.*;\nimport org.apache.log4j.helpers.LogLog;\nimport org.apache.log4j.spi.LoggingEvent;\n\n/**\n * DateFormatFileAppender is a log4j Appender and extends \n * {@link FileAppender} so each log is \n * named based on a date format defined in the File property.\n *\n * Sample File: 'logs/'yyyy/MM-MMM/dd-EEE/HH-mm-ss-S'.log'\n * Makes a file like: logs/2004/04-Apr/13-Tue/09-45-15-937.log\n * @author James Stauffer\n */\npublic class DateFormatFileAppender extends FileAppender {\n\n /**\n * The default constructor does nothing.\n */\n public DateFormatFileAppender() {\n }\n\n /**\n * Instantiate a <code>DailyRollingFileAppender</code> and open the\n * file designated by <code>filename</code>. The opened filename will\n * become the ouput destination for this appender.\n */\n public DateFormatFileAppender (Layout layout, String filename) throws IOException {\n super(layout, filename, true);\n }\n\n private String fileBackup;//Saves the file pattern\n private boolean separate = false;\n\n public void setFile(String file) {\n super.setFile(file);\n this.fileBackup = getFile();\n }\n\n /**\n * If true each LoggingEvent causes that file to close and open.\n * This is useful when the file is a pattern that would often\n * produce a different filename.\n */\n public void setSeparate(boolean separate) {\n this.separate = separate;\n }\n\n protected void subAppend(LoggingEvent event) {\n if(separate) {\n try {//First reset the file so each new log gets a new file.\n setFile(getFile(), getAppend(), getBufferedIO(), getBufferSize());\n } catch(IOException e) {\n LogLog.error(\"Unable to reset fileName.\");\n }\n }\n super.subAppend(event);\n }\n\n\n public\n synchronized\n void setFile(String fileName, boolean append, boolean bufferedIO, int bufferSize)\n throws IOException {\n SimpleDateFormat sdf = new SimpleDateFormat(fileBackup);\n String actualFileName = sdf.format(new Date());\n makeDirs(actualFileName);\n super.setFile(actualFileName, append, bufferedIO, bufferSize);\n }\n\n /**\n * Ensures that all of the directories for the given path exist.\n * Anything after the last / or \\ is assumed to be a filename.\n */\n private void makeDirs (String path) {\n int indexSlash = path.lastIndexOf(\"/\");\n int indexBackSlash = path.lastIndexOf(\"\\\\\");\n int index = Math.max(indexSlash, indexBackSlash);\n if(index > 0) {\n String dirs = path.substring(0, index);\n// LogLog.debug(\"Making \" + dirs);\n File dir = new File(dirs);\n if(!dir.exists()) {\n boolean success = dir.mkdirs();\n if(!success) {\n LogLog.error(\"Unable to create directories for \" + dirs);\n }\n }\n }\n }\n\n}\n" }, { "answer_id": 773871, "author": "Lars Corneliussen", "author_id": 11562, "author_profile": "https://Stackoverflow.com/users/11562", "pm_score": 4, "selected": false, "text": "<staticLogFileName value=\"false\"/>\n <appender name=\"DefaultFileAppender\" type=\"log4net.Appender.RollingFileAppender\">\n <file value=\"application\"/>\n <staticLogFileName value=\"false\"/>\n <appendToFile value=\"true\" />\n <rollingStyle value=\"Date\" />\n <datePattern value=\"yyyy-MM-dd&quot;.log&quot;\" />\n <layout type=\"log4net.Layout.PatternLayout\">\n <conversionPattern value=\"%date [%thread] %-5level %logger [%property{NDC}] - %message%newline\" />\n </layout>\n</appender>\n &quot;.log&quot;" }, { "answer_id": 8888867, "author": "shinds", "author_id": 990216, "author_profile": "https://Stackoverflow.com/users/990216", "pm_score": 6, "selected": false, "text": "log4j.appender.LOGFILE=org.apache.log4j.rolling.RollingFileAppender\nlog4j.appender.LOGFILE.RollingPolicy=org.apache.log4j.rolling.TimeBasedRollingPolicy\nlog4j.appender.LOGFILE.RollingPolicy.FileNamePattern=/logs/application_%d{yyyy-MM-dd}.log\n" }, { "answer_id": 11226717, "author": "codder", "author_id": 1485653, "author_profile": "https://Stackoverflow.com/users/1485653", "pm_score": 2, "selected": false, "text": "DatePattern <appender name=\"ASYNC\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n <param name=\"File\" value=\"./applogs/logger.log\" />\n <param name=\"Append\" value=\"true\" />\n <param name=\"Threshold\" value=\"debug\" />\n <appendToFile value=\"true\" />\n <param name=\"DatePattern\" value=\"'.'yyyy_MM_dd_HH_mm\"/>\n <rollingPolicy class=\"org.apache.log4j.rolling.TimeBasedRollingPolicy\">\n <param name=\"fileNamePattern\" value=\"./applogs/logger_%d{ddMMMyyyy HH:mm:ss}.log\"/>\n <param name=\"rollOver\" value=\"TRUE\"/>\n </rollingPolicy>\n <layout class=\"org.apache.log4j.PatternLayout\">\n <param name=\"ConversionPattern\" value=\"%d{ddMMMyyyy HH:mm:ss,SSS}^[%X{l4j_mdc_key}]^[%c{1}]^ %-5p %m%n\" />\n </layout>\n</appender>\n<root>\n <level value=\"info\" />\n <appender-ref ref=\"ASYNC\" />\n</root>\n" }, { "answer_id": 21250314, "author": "SANN3", "author_id": 1173495, "author_profile": "https://Stackoverflow.com/users/1173495", "pm_score": 2, "selected": false, "text": "SimpleLayout layout = new SimpleLayout(); \nFileAppender appender = new FileAppender(layout,\"logname.\"+new Date().toLocaleString(),false);\nlogger.addAppender(appender); \n" }, { "answer_id": 51557735, "author": "rpajaziti", "author_id": 3657024, "author_profile": "https://Stackoverflow.com/users/3657024", "pm_score": 0, "selected": false, "text": "DailyRollingFileAppender logname.log.2008-10-10 DatePattern log4j.appender.file.DatePattern='.'yyyy-MM-dd-HH-mm'.log'" }, { "answer_id": 67695369, "author": "john ktejik", "author_id": 396483, "author_profile": "https://Stackoverflow.com/users/396483", "pm_score": 0, "selected": false, "text": " String dateFile = LocalDate.now().toString() + \".log\";\n Enumeration enm = Logger.getRootLogger().getAllAppenders();\n Appender appender = null;\n while(enm.hasMoreElements()){\n appender = (Appender)enm.nextElement();\n String c = appender.getClass().toString();\n if(c.contains(\"FileAppender\")){\n String f = ((FileAppender)appender).getFile();\n ((FileAppender)appender).setFile(f+dateFile);\n System.out.println(\"From:\"+f+\" to:\"+dateFile);\n }\n }\n" }, { "answer_id": 72253926, "author": "jimmybow", "author_id": 19124264, "author_profile": "https://Stackoverflow.com/users/19124264", "pm_score": 1, "selected": false, "text": " <appender name=\"pdi-execution-appender\" class=\"org.apache.log4j.rolling.RollingFileAppender\"> \n <!-- The active file to log to; this example is for Pentaho Server.-->\n <param name=\"Append\" value=\"true\" />\n <param name=\"Threshold\" value=\"INFO\"/>\n <rollingPolicy class=\"org.apache.log4j.rolling.TimeBasedRollingPolicy\">\n <!-- See javadoc for TimeBasedRollingPolicy -->\n <param name=\"FileNamePattern\" value=\"logs/ETL-LogFile.%d{yyyyMMdd}.log\" />\n </rollingPolicy>\n <layout class=\"org.apache.log4j.PatternLayout\">\n <param name=\"ConversionPattern\" value='%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p [%t] %m'/>\n </layout>\n </appender>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/387361/" ]
192,527
<p>I've been researching memory mapped files for a project and would appreciate any thoughts from people who have either used them before, or decided against using them, and why?</p> <p>In particular, I am concerned about the following, in order of importance:</p> <ul> <li>concurrency</li> <li>random access</li> <li>performance</li> <li>ease of use</li> <li>portability</li> </ul>
[ { "answer_id": 192672, "author": "bog", "author_id": 20909, "author_profile": "https://Stackoverflow.com/users/20909", "pm_score": 5, "selected": false, "text": "11111111\n22222222\n11112222\n22221111\n" }, { "answer_id": 192674, "author": "Brian Ensink", "author_id": 1254, "author_profile": "https://Stackoverflow.com/users/1254", "pm_score": 6, "selected": false, "text": "C struct" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10184/" ]
192,539
<p>I have a .NET application that processes around 300,000 records in a batch import, and it takes a few seconds per record so I would like to parallelize this. In the following code, what's the difference between <code>ProcessWithAnsycDelegates()</code> and <code>ProcessWithThreadPool()</code>?</p> <pre><code>public class ResultNotification { public EventHandler event Success; public EventHandler event Fail; internal void Notify(bool sucess) {if (success) Success(); else Fail();} } public static class Processor { public ResultNotification ProcessWithAnsycDelegates(Record record) { var r = new ResultNotification(); Func&lt;Record,bool&gt; processRecord=new RecordProcessor().ProcessRecord; processRecord.BeginInvoke ( record ,ar =&gt; result.Notify(processRecord.EndInvoke(ar)) ,null); return r; } public ResultNotification ProcessWithThreadPool(Record r) { var r = new ResultNotification(); var rp = new RecordProcessor(); ThreadPool.QueueWorkUserItem(_=&gt;result.Notify(rp.ProcessRecord(r))); return r; } } </code></pre>
[ { "answer_id": 192580, "author": "chadmyers", "author_id": 10862, "author_profile": "https://Stackoverflow.com/users/10862", "pm_score": 4, "selected": true, "text": "QueueUserWorkItem() BeginInvoke()" }, { "answer_id": 194648, "author": "Thomas Bratt", "author_id": 15985, "author_profile": "https://Stackoverflow.com/users/15985", "pm_score": 3, "selected": false, "text": "for (int i = 0; i < 100; i++) { \n a[i] = a[i]*a[i]; \n}\n Parallel.For(0, 100, delegate(int i) { \n a[i] = a[i]*a[i]; \n});\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1659/" ]
192,549
<p>I have a controller method that returns a list for a drop down that gets rendered in a partial, but depending on where the partial is being used, the RJS template needs to be different. Can I pass a parameter to the controller that will determine which RJS gets used?</p> <p>Here is the controller method, it is very simple:</p> <pre><code>def services respond_to do |format| format.js { @type = HospitalCriteria.find_by_id(params[:type_id]) @services = @type.children.all } end end </code></pre> <p>And here is the rjs template the gets rendered automatically</p> <pre><code>page.replace_html 'select_service', :partial =&gt; 'hospital/services' page.replace_html 'select_condition', :partial =&gt; 'hospital/conditions' page.replace_html 'select_procedure', :partial =&gt; 'hospital/procedures' page &lt;&lt; 'if ($("chosenType") != null) {' page.replace_html 'chosenType', @type.name page.replace_html 'chosenService', 'Selected Service' page.replace_html 'chosenCondition', 'Selected Condition' page.replace_html 'chosenProcedure', 'Selected Procedure' page &lt;&lt; '}' </code></pre>
[ { "answer_id": 192867, "author": "Mike Breen", "author_id": 22346, "author_profile": "https://Stackoverflow.com/users/22346", "pm_score": 1, "selected": false, "text": "if params[:use_alternate]\n render :template => alternate.rjs and return\nend\n" }, { "answer_id": 192910, "author": "danpickett", "author_id": 21788, "author_profile": "https://Stackoverflow.com/users/21788", "pm_score": 2, "selected": false, "text": "if params[:use_alternate]\n render :partial => \"case_1.rjs\"\nelse\n render :partial => \"case_2.rjs\"\nend\n" }, { "answer_id": 197094, "author": "JasonOng", "author_id": 6048, "author_profile": "https://Stackoverflow.com/users/6048", "pm_score": 3, "selected": true, "text": "# services.rjs\n\nif @type == \"your conditions\"\n # your rjs updates\nelse\n # your other rjs updates\nend\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1486/" ]
192,553
<p>I am currently in the process of making a new ASP.net MVC website, and find myself using Html.Encode all over the place, which is good practice, but gets pretty messy. I think a good way to clean this up would be if I could overload an operator to automatically do Html encoding. </p> <p>Previously:</p> <pre><code>&lt;%= Html.Encode( ViewData['username'] ) %&gt; </code></pre> <p>Would be equivalent to:</p> <pre><code>&lt;%=h ViewData['username'] %&gt; </code></pre> <p>Anyone have any ideas how I could do this, maybe using an extension method or something?</p>
[ { "answer_id": 192564, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": -1, "selected": false, "text": "public static String h (this System.Object o, System.Object viewData)\n{\n return Html.Encode(viewData);\n}\n <%=h(ViewData['username']) %>\n" }, { "answer_id": 192594, "author": "Wyatt", "author_id": 26626, "author_profile": "https://Stackoverflow.com/users/26626", "pm_score": 4, "selected": true, "text": "public static string Safe(this string sz)\n{\n return HttpUtility.HtmlEncode(sz);\n}\n <%= this.ViewData[\"username\"].Safe() %>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24841/" ]
192,570
<p>The project I'm working on uses a window.onerror event handler to report user problems. I've noticed a single user that just cannot seem to load the Google Analytics script. Our site doesn't see a lot of traffic so I'm not sure how widespread this is, but so far it seems to just effect one user. </p> <p>His user agent is: "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.17) Gecko/20080829 Firefox/2.0.0.17".<br> The error message Firefox gives is: "Error loading script".</p> <p><strong>Additional note</strong>: The site references several other javascript files. However, the analytics reference is the only one to an external domain and the only script reference at the bottom of the page, just before the closing body tag.</p> <p>Has anybody else run across this, or have any idea what could be the issue? Thanks!</p>
[ { "answer_id": 7686057, "author": "Karl Bartel", "author_id": 114926, "author_profile": "https://Stackoverflow.com/users/114926", "pm_score": 3, "selected": false, "text": "[11:35:57.428] uncaught exception: [Exception... \"prompt aborted by user\" nsresult: \"0x80040111 (NS_ERROR_NOT_AVAILABLE)\" location: \"JS frame :: resource:///components/nsPrompter.js :: openTabPrompt :: line 462\" data: no]\n if (navigator.userAgent.search('Firefox') != -1 && message === 'Error loading script') {\n // Firefox generates this error when leaving a page before all scripts have finished loading\n return;\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1423/" ]
192,575
<p>How do I transfer the users of a vBulletin forum to a new installation of IceBB?</p>
[ { "answer_id": 7686057, "author": "Karl Bartel", "author_id": 114926, "author_profile": "https://Stackoverflow.com/users/114926", "pm_score": 3, "selected": false, "text": "[11:35:57.428] uncaught exception: [Exception... \"prompt aborted by user\" nsresult: \"0x80040111 (NS_ERROR_NOT_AVAILABLE)\" location: \"JS frame :: resource:///components/nsPrompter.js :: openTabPrompt :: line 462\" data: no]\n if (navigator.userAgent.search('Firefox') != -1 && message === 'Error loading script') {\n // Firefox generates this error when leaving a page before all scripts have finished loading\n return;\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5509/" ]
192,584
<p>I have a listbox that is databound to a Collection of objects. The listbox is configured to display an identifier property of each object. I would like to show a tooltip with information specific to the item within the listbox that is being hovered over rather than one tooltip for the listbox as a whole.</p> <p>I am working within WinForms and thanks to some helpful blog posts put together a pretty nice solution, which I wanted to share.</p> <p>I'd be interested in seeing if there's any other elegant solutions to this problem, or how this may be done in WPF.</p>
[ { "answer_id": 192654, "author": "Michael Lang", "author_id": 19452, "author_profile": "https://Stackoverflow.com/users/19452", "pm_score": 5, "selected": true, "text": "private ITypeOfObjectsBoundToListBox DetermineHoveredItem()\n{\n Point screenPosition = ListBox.MousePosition;\n Point listBoxClientAreaPosition = listBox.PointToClient(screenPosition);\n\n int hoveredIndex = listBox.IndexFromPoint(listBoxClientAreaPosition);\n if (hoveredIndex != -1)\n {\n return listBox.Items[hoveredIndex] as ITypeOfObjectsBoundToListBox;\n }\n else\n {\n return null;\n }\n}\n TrackMouseEvent ResetMouseHover public static class MouseInput\n{\n // TME_HOVER\n // The caller wants hover notification. Notification is delivered as a \n // WM_MOUSEHOVER message. If the caller requests hover tracking while \n // hover tracking is already active, the hover timer will be reset.\n\n private const int TME_HOVER = 0x1;\n\n private struct TRACKMOUSEEVENT\n {\n // Size of the structure - calculated in the constructor\n public int cbSize;\n\n // value that we'll set to specify we want to start over Mouse Hover and get\n // notification when the hover has happened\n public int dwFlags;\n\n // Handle to what's interested in the event\n public IntPtr hwndTrack;\n\n // How long it takes for a hover to occur\n public int dwHoverTime;\n\n // Setting things up specifically for a simple reset\n public TRACKMOUSEEVENT(IntPtr hWnd)\n {\n this.cbSize = Marshal.SizeOf(typeof(TRACKMOUSEEVENT));\n this.hwndTrack = hWnd;\n this.dwHoverTime = SystemInformation.MouseHoverTime;\n this.dwFlags = TME_HOVER;\n }\n }\n\n // Declaration of the Win32API function\n [DllImport(\"user32\")]\n private static extern bool TrackMouseEvent(ref TRACKMOUSEEVENT lpEventTrack);\n\n public static void ResetMouseHover(IntPtr windowTrackingMouseHandle)\n {\n // Set up the parameter collection for the API call so that the appropriate\n // control fires the event\n TRACKMOUSEEVENT parameterBag = new TRACKMOUSEEVENT(windowTrackingMouseHandle);\n\n // The actual API call\n TrackMouseEvent(ref parameterBag);\n }\n}\n ResetMouseHover(listBox.Handle)" }, { "answer_id": 853369, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<ListBox Width=\"400\" Margin=\"10\" \n ItemsSource=\"{Binding Source={StaticResource myTodoList}}\">\n <ListBox.ItemTemplate>\n <DataTemplate>\n <TextBlock Text=\"{Binding Path=TaskName}\" \n ToolTipService.ToolTip=\"{Binding Path=TaskName}\"/>\n </DataTemplate>\n </ListBox.ItemTemplate>\n</ListBox>\n" }, { "answer_id": 1275983, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "ListItem li = new ListItem(\"text\",\"key\");\nli.Attributes.Add(\"title\",\"tool tip text\");\n" }, { "answer_id": 3029107, "author": "BSalita", "author_id": 317797, "author_profile": "https://Stackoverflow.com/users/317797", "pm_score": 0, "selected": false, "text": " <Style x:Key=\"radioListBox\" TargetType=\"ListBox\" BasedOn=\"{StaticResource {x:Type ListBox}}\">\n <Setter Property=\"BorderThickness\" Value=\"0\" />\n <Setter Property=\"Margin\" Value=\"5\" />\n <Setter Property=\"Background\" Value=\"{x:Null}\" />\n <Setter Property=\"ItemContainerStyle\">\n <Setter.Value>\n <Style TargetType=\"ListBoxItem\" BasedOn=\"{StaticResource {x:Type ListBoxItem}}\">\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"ListBoxItem\">\n <Grid Background=\"Transparent\">\n <RadioButton Focusable=\"False\" IsHitTestVisible=\"False\" IsChecked=\"{TemplateBinding IsSelected}\" Content=\"{Binding MyName}\"/>\n </Grid>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n <Setter Property=\"ToolTip\" Value=\"{Binding MyToolTip}\" />\n </Style>\n </Setter.Value>\n </Setter>\n</Style>\n" }, { "answer_id": 6848465, "author": "Michael", "author_id": 865925, "author_profile": "https://Stackoverflow.com/users/865925", "pm_score": 4, "selected": false, "text": " class Car\n {\n // Main properties:\n public string Model { get; set; }\n public string Make { get; set; }\n public int InsuranceGroup { get; set; }\n public string OwnerName { get; set; }\n // Read only property combining all the other informaiton:\n public string Info { get { return string.Format(\"{0} {1}\\nOwner: {2}\\nInsurance group: {3}\", Make, Model, OwnerName, InsuranceGroup); } }\n }\n private void Form1_Load(object sender, System.EventArgs e)\n {\n // Set up a list of cars:\n List<Car> allCars = new List<Car>();\n allCars.Add(new Car { Make = \"Toyota\", Model = \"Yaris\", InsuranceGroup = 6, OwnerName = \"Joe Bloggs\" });\n allCars.Add(new Car { Make = \"Mercedes\", Model = \"AMG\", InsuranceGroup = 50, OwnerName = \"Mr Rich\" });\n allCars.Add(new Car { Make = \"Ford\", Model = \"Escort\", InsuranceGroup = 10, OwnerName = \"Fred Normal\" });\n\n // Attach the list of cars to the ListBox:\n lstCars.DataSource = allCars;\n lstCars.DisplayMember = \"Model\";\n }\n // Class variable to keep track of which row is currently selected:\n int hoveredIndex = -1;\n\n private void lstCars_MouseMove(object sender, MouseEventArgs e)\n {\n // See which row is currently under the mouse:\n int newHoveredIndex = lstCars.IndexFromPoint(e.Location);\n\n // If the row has changed since last moving the mouse:\n if (hoveredIndex != newHoveredIndex)\n {\n // Change the variable for the next time we move the mouse:\n hoveredIndex = newHoveredIndex;\n\n // If over a row showing data (rather than blank space):\n if (hoveredIndex > -1)\n {\n //Set tooltip text for the row now under the mouse:\n tt1.Active = false;\n tt1.SetToolTip(lstCars, ((Car)lstCars.Items[hoveredIndex]).Info);\n tt1.Active = true;\n }\n }\n }\n" }, { "answer_id": 26881134, "author": "Satheesh ponugoti", "author_id": 4242026, "author_profile": "https://Stackoverflow.com/users/4242026", "pm_score": 0, "selected": false, "text": "onmouseover ToolTip onmouseover=\"doTooltipProd(event,'');\n\nfunction doTooltipProd(e,tipObj)\n{\n\n Tooltip.init();\n if ( typeof Tooltip == \"undefined\" || !Tooltip.ready ) {\n return;\n }\n mCounter = 1;\n for (m=1;m<=document.getElementById('lobProductId').length;m++) {\n\n var mCurrent = document.getElementById('lobProductId').options[m];\n if(mCurrent != null && mCurrent != \"null\") {\n if (mCurrent.selected) {\n mText = mCurrent.text;\n Tooltip.show(e, mText);\n }\n } \n } \n}\n" }, { "answer_id": 47886511, "author": "Shalom", "author_id": 9117042, "author_profile": "https://Stackoverflow.com/users/9117042", "pm_score": 2, "selected": false, "text": "private void ListBoxOnMouseMove(object sender, MouseEventArgs mouseEventArgs)\n{\n var listbox = sender as ListBox;\n if (listbox == null) return;\n\n // set tool tip for listbox\n var strTip = string.Empty;\n var index = listbox.IndexFromPoint(mouseEventArgs.Location);\n\n if ((index >= 0) && (index < listbox.Items.Count))\n strTip = listbox.Items[index].ToString();\n\n if (_toolTip.GetToolTip(listbox) != strTip)\n {\n _toolTip.SetToolTip(listbox, strTip);\n }\n}\n _toolTip = new ToolTip\n{\n AutoPopDelay = 5000,\n InitialDelay = 1000,\n ReshowDelay = 500,\n ShowAlways = true\n};\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19452/" ]
192,641
<p>I recently wrote a DLL in C# (.Net 2.0) which contains a class that requires an IP address. A co-worker of mine altered the class to retrieve the IP from a ".dll.config" (XML) file -- This apparently is automatically generated by the "Application Settings" file he created (Settings1.settings). The benefit of this was to allow the end-user to change the IP address in the XML/config file at will.</p> <p>Unfortunately, when I check his code out of the tree and try to compile (or use) this new code, any application calling this DLL only gets the default value, rather than the value from the file.</p> <p>The constructor that calls the config file looks like this:</p> <pre><code> public class form : System.Windows.Forms.Form { public form() { // This call is required by the Windows Form Designer. InitializeComponent(); IP = IPAddress.Parse(Settings1.Default.IPAddress); } } </code></pre> <p>I found <a href="http://social.msdn.microsoft.com/Forums/en-US/clr/thread/f3a4b138-6e6c-42e3-86e8-1f86c90f8fb4/" rel="noreferrer">a reference to this problem on the MSDN forums</a> where a user said:</p> <blockquote> <p>the 'old' values (the ones you define at development time) are hard coded. If the franework isn't able to access or open the config file it will use the defaults instead. This will always happen if you use settings in a dll.</p> </blockquote> <ol> <li><p>Does this mean that I cannot store an external value for a DLL in a config file? (My co-worker has somehow made this work...)</p></li> <li><p>Since my framework appears to be unable to access or open the config file, how do I figure out why it's failing? Or even detect when this happens?</p></li> </ol> <p><b>Decker</b>: That helps a bit. Unfortunately, I am writing this DLL to a specification, so I don't actually have access to the Application's config file. As you'll note above, my co-worker created a "Settings<b>1</b>.settings" file. I didn't understand this at the time, but it seems now that adding the "1" keeps it out of the settings space of any application that calls it. </p> <p>I guess what I'm trying to figure out is why the DLL doesn't seem to find the config file sitting next to it in the same directory. Tracing thru the code step-by-step reveals nothing.</p> <p>As an aside, I can change the "Output Type" of my assembly from "Class Library" to "Windows Application" and add the following lines at the beginning of my DLL code:</p> <pre><code> [STAThread] public static void Main(string[] args) { System.Windows.Forms.Application.Run(new form()); } </code></pre> <p>When I run this, it generates a different config file (a ".exe.config") and that one I can alter and have it pull the new data from the file. So I'm a bit confused. Any ideas?</p>
[ { "answer_id": 192828, "author": "Howard Pinsley", "author_id": 7961, "author_profile": "https://Stackoverflow.com/users/7961", "pm_score": 3, "selected": false, "text": " [global::System.Configuration.ApplicationScopedSettingAttribute()]\n [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n [global::System.Configuration.DefaultSettingValueAttribute(\"InternalTCP\")]\n\n public string ConcordanceServicesEndpointName {\n get {\n return ((string)(this[\"ConcordanceServicesEndpointName\"]));\n }\n }\n <configSections>\n <sectionGroup name=\"applicationSettings\" type=\"System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" >\n <section name=\"LitigationPortal.Documents.BLL.DocumentsBLLSettings\" type=\"System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" requirePermission=\"false\" />\n </sectionGroup>\n </configSections>\n <applicationSettings>\n <LitigationPortal.Documents.BLL.DocumentsBLLSettings>\n <setting name=\"ConcordanceServicesEndpointName\" serializeAs=\"String\">\n <value>InternalTCP</value>\n </setting>\n </KayeScholer.LitigationPortal.Documents.BLL.DocumentsBLLSettings>\n </applicationSettings>\n <configSections>\n <sectionGroup name=\"applicationSettings\" type=\"System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" >\n <section name=\"LitigationPortal.Documents.BLL.DocumentsBLLSettings\" type=\"System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" requirePermission=\"false\" />\n </sectionGroup>\n </configSections>\n <applicationSettings>\n <LitigationPortal.Documents.BLL.DocumentsBLLSettings>\n <setting name=\"ConcordanceServicesEndpointName\" serializeAs=\"String\">\n <value>InternalTCP</value>\n </setting>\n </KayeScholer.LitigationPortal.Documents.BLL.DocumentsBLLSettings>\n </applicationSettings>\n" }, { "answer_id": 11991195, "author": "MRHIMAN", "author_id": 1603772, "author_profile": "https://Stackoverflow.com/users/1603772", "pm_score": -1, "selected": false, "text": "Settings1.Default.IPAddress Settings1.IPAddress Settings1.Default.IPAddress Settings1.IPAddress .dll.config IP = IPAddress.Parse(Settings1.Default.IPAddress);\n *IP = IPAddress.Parse(Settings1.IPAddress);\n" }, { "answer_id": 42715640, "author": "Kflexior", "author_id": 1290233, "author_profile": "https://Stackoverflow.com/users/1290233", "pm_score": 0, "selected": false, "text": " string configFile = Assembly.GetExecutingAssembly().Location + \".config\";\n XDocument.Load(configFile).Root.Element(\"appSettings\")....\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21244/" ]
192,643
<p>How do I determine if a <code>Nullable(of Enum)</code> is indeed an <code>Enum</code> by means of reflection?</p> <p>I'm working with a method that dynamically populates an object of type <code>T</code> with an <code>IDataReader</code> retrieved from a database call. At its essence, it loops through the datareader's ordinals, and all the properties of <code>T</code> and populates the properties that match the name of the ordinals (also some attribute magic is thrown to change column names). In every other circumstance, it works great, but when I check the property's <code>BaseType</code> for <code>System.Enum</code> I find instead, <code>System.ValueType</code> Thusly, my Enum check fails and the method bombs.</p> <p>[Edit: <code>Type.IsEnum</code> doesn't work how I need it. The main issue here, is that nothing in <code>T</code>'s BaseType hierarchy says that it is an <code>Enum</code>. It's as if making it a <code>Nullable</code> type forfeits my <code>Enum</code> rights.]</p> <p>Any ideas?</p>
[ { "answer_id": 192706, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 4, "selected": true, "text": "PropertyInfo.PropertyType IsGenericType GetGenericTypeDefinition() typeof(Nullable<>) Enum Nullable.GetUnderlyingType(propertyInfo.PropertyType)" }, { "answer_id": 192709, "author": "Dan Goldstein", "author_id": 23427, "author_profile": "https://Stackoverflow.com/users/23427", "pm_score": 0, "selected": false, "text": ".HasValue" }, { "answer_id": 192735, "author": "Zachary Yates", "author_id": 8360, "author_profile": "https://Stackoverflow.com/users/8360", "pm_score": 0, "selected": false, "text": "AnEnum? enumObj;\nif (enumObj.HasValue)\n{\n enumObj.Value.GetType().IsEnum();\n}\n" }, { "answer_id": 810106, "author": "GregC", "author_id": 90475, "author_profile": "https://Stackoverflow.com/users/90475", "pm_score": 0, "selected": false, "text": "class Base\n{\n enum BaseEnum\n {\n Val1,\n Val2,\n LastVal\n }\n}\n\nclass Derived\n{\n enum DerivedEnum\n {\n Val3 = BaseEnum.LastVal,\n Val4,\n LastVal\n }\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13611/" ]
192,648
<p>OK, so I'm trying to teach myself the CakePHP framework, and I'm trying to knock up a simple demo app for myself.</p> <p>I have the controllers, views and models all set up and working, but I want to do something slightly more than the basic online help shows.</p> <p>I have a guitars_controller.php file as follows...</p> <pre><code>&lt;?php class GuitarsController extends AppController { var $name = 'Guitars'; function index() { $this-&gt;set('Guitars', $this-&gt;Guitar-&gt;findAll()); $this-&gt;pageTitle = "All Guitars"; } function view($id = null) { $this-&gt;Guitar-&gt;id = $id; $this-&gt;set('guitar', $this-&gt;Guitar-&gt;read()); // Want to set the title here. } } ?&gt; </code></pre> <p>The 'Guitar' object contains an attribute called 'Name', and I'd like to be able to set that as the pageTitle for the individual page views. </p> <p>Can anyone point out how I'd do that, please? </p> <p><strong>NB</strong>: I know that there is general disagreement about where in the application to set this kind of data, but to me, it is data related.</p>
[ { "answer_id": 192657, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "$this->pageTitle = $this->Guitar->Name;\n" }, { "answer_id": 192737, "author": "Paolo Bergantino", "author_id": 16417, "author_profile": "https://Stackoverflow.com/users/16417", "pm_score": 2, "selected": false, "text": "function view($id = null) {\n $guitar = $this->Guitar->read(null, $id);\n $this->set('guitar', $guitar);\n $this->pageTitle = $guitar['Guitar']['name'];\n}\n <? $this->pageTitle = $guitar['Guitar']['name']; ?>\n <?php echo h( $title_for_layout ); ?>\n" }, { "answer_id": 192916, "author": "ZombieSheep", "author_id": 377, "author_profile": "https://Stackoverflow.com/users/377", "pm_score": 0, "selected": false, "text": "$this->pageTitle = $this->viewVars['guitar']['Guitar']['Name'];\n echo \"<pre>\"; print_r($this);echo \"</pre>\";\n" }, { "answer_id": 193897, "author": "neilcrookes", "author_id": 9968, "author_profile": "https://Stackoverflow.com/users/9968", "pm_score": 4, "selected": true, "text": "<?php\nclass AppController extends Controller {\n function index() {\n $this->set(Inflector::variable($this->name), $this->{$this->modelClass}->findAll());\n $this->pageTitle = 'All '.Inflector::humanize($this->name);\n }\n function view($id = null) {\n $data = $this->{$this->modelClass}->findById($id);\n $this->set(Inflector::variable($this->modelClass), $data);\n $this->pageTitle = $data[$this->modelClass][$this->{$this->modelClass}->displayField];\n }\n}\n?>\n" }, { "answer_id": 196102, "author": "Alexander Morland", "author_id": 4013, "author_profile": "https://Stackoverflow.com/users/4013", "pm_score": 1, "selected": false, "text": "function view($id) {\n $this->Guitar->id = $id;\n $this->Guitar->read();\n $this->pageTitle = $this->Guitar->data['Guitar']['name'];\n $this->set('data', $this->Guitar->data);\n}\n" }, { "answer_id": 672496, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "echo \"<pre>\"; print_r($this);echo \"</pre>\";\n pr( $this );\n" }, { "answer_id": 6004551, "author": "windmaomao", "author_id": 288096, "author_profile": "https://Stackoverflow.com/users/288096", "pm_score": 0, "selected": false, "text": "class CustomersController extends AppController {\n\n var $name = 'Customers';\n\n function beforeFilter() {\n parent::beforeFilter();\n $this->set('menu',$this->name);\n switch ($this->action) {\n case 'index':\n $this->title = 'List Customer';\n break;\n case 'view':\n $this->title = 'View Customer';\n break;\n case 'edit':\n $this->title = 'Edit Customer';\n break;\n case 'add':\n $this->title = 'Add New Customer';\n break;\n default:\n $title = 'Welcome to '.$name;\n break;\n }\n $this->set('title',$this->title);\n }\n $this->title beforeFilter" }, { "answer_id": 6804991, "author": "Tarik", "author_id": 44852, "author_profile": "https://Stackoverflow.com/users/44852", "pm_score": 1, "selected": false, "text": "$this->pageTitle = \"Title\"; //deprecated\n\n$this->set(\"title_for_layout\",Inflector::humanize($this->name)); // new way of setting title\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/377/" ]
192,649
<p>Ruby can add methods to the Number class and other core types to get effects like this:</p> <pre class="lang-rb prettyprint-override"><code>1.should_equal(1) </code></pre> <p>But it seems like Python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that <em>type</em> can't be modified?</p> <p><em>Rather than talking about different definitions of monkey patching, I would like to just focus on the example above. I have already concluded that it cannot be done as a few of you have answered. But I would like a more detailed explanation of why it cannot be done, and maybe what feature, if available in Python, would allow this.</em></p> <p>To answer some of you: The reason I <em>might</em> want to do this is simply aesthetics/readability.</p> <pre><code> item.price.should_equal(19.99) </code></pre> <p>This reads more like English and clearly indicates which is the tested value and which is the expected value, as supposed to:</p> <pre><code>should_equal(item.price, 19.99) </code></pre> <p>This concept is what <a href="http://rspec.info/" rel="nofollow noreferrer">Rspec</a> and some other Ruby frameworks are based on.</p>
[ { "answer_id": 192681, "author": "HanClinto", "author_id": 26933, "author_profile": "https://Stackoverflow.com/users/26933", "pm_score": 2, "selected": false, "text": "import TelnetConnection\n import TelnetConnectionExtended as TelnetConnection\n" }, { "answer_id": 192703, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 7, "selected": true, "text": "class Foo:\n pass # dummy class\n\nFoo.bar = lambda self: 42\n\nx = Foo()\nprint x.bar()\n class Foo:\n pass # dummy class\n\nx = Foo()\n\nFoo.bar = lambda self: 42\n\nprint x.bar()\n int float" }, { "answer_id": 193660, "author": "zaphod", "author_id": 13871, "author_profile": "https://Stackoverflow.com/users/13871", "pm_score": 4, "selected": false, "text": ">>> int.frobnicate = lambda self: whatever()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: can't set attributes of built-in/extension type 'int'\n >>> class MyInt(int):\n... def frobnicate(self):\n... print 'frobnicating %r' % self\n... \n>>> five = MyInt(5)\n>>> five.frobnicate()\nfrobnicating 5\n>>> five + 8\n13\n MyInt os.stat() tuple >>> import os\n>>> st = os.stat('.')\n>>> st\n(16877, 34996226, 65024L, 69, 1000, 1000, 4096, 1223697425, 1223699268, 1223699268)\n>>> st[6]\n4096\n>>> st.st_size\n4096\n float item.price price_should_equal() item should_equal(observed=item.price, expected=19.99)\n should_equal() int float" }, { "answer_id": 830114, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "should_equal True False item.price == 19.99\n should_equal 18.99 19.99 item.price_should_equal(19.99)\n item.should_equal('price', 19.99)\n" }, { "answer_id": 838000, "author": "Ryan Ginstrom", "author_id": 10658, "author_profile": "https://Stackoverflow.com/users/10658", "pm_score": 2, "selected": false, "text": "item.price.should_equal class Price(float):\n def __init__(self, val=None):\n float.__init__(self)\n if val is not None:\n self = val\n\n def should_equal(self, val):\n assert self == val, (self, val)\n\nclass Item(object):\n def __init__(self, name, price=None):\n self.name = name\n self.price = Price(price)\n\nitem = Item(\"spam\", 3.99)\nitem.price.should_equal(3.99)\n" }, { "answer_id": 4025310, "author": "Jonathan", "author_id": 487810, "author_profile": "https://Stackoverflow.com/users/487810", "pm_score": 5, "selected": false, "text": "def should_equal_def(self, value):\n if self != value:\n raise ValueError, \"%r should equal %r\" % (self, value)\n\nclass MyPatchedInt(int):\n should_equal=should_equal_def\n\nclass MyPatchedStr(str):\n should_equal=should_equal_def\n\nimport __builtin__\n__builtin__.str = MyPatchedStr\n__builtin__.int = MyPatchedInt\n\nint(1).should_equal(1)\nstr(\"44\").should_equal(\"44\")\n" }, { "answer_id": 5988122, "author": "Lvsoft", "author_id": 751878, "author_profile": "https://Stackoverflow.com/users/751878", "pm_score": 3, "selected": false, "text": "from pipe import *\n\n@Pipe\ndef should_equal(obj, val):\n if obj==val: return True\n return False\n\nclass dummy: pass\nitem=dummy()\nitem.value=19.99\n\nprint item.value | should_equal(19.99)\n" }, { "answer_id": 6245617, "author": "Petr Viktorin", "author_id": 99057, "author_profile": "https://Stackoverflow.com/users/99057", "pm_score": 1, "selected": false, "text": "assert item.price == 19.99\n assert item.price == Decimal(19.99)" }, { "answer_id": 10891256, "author": "mdwhatcott", "author_id": 605022, "author_profile": "https://Stackoverflow.com/users/605022", "pm_score": -1, "selected": false, "text": "result = calculate_result('blah') # some method defined somewhere else\n\nthe(result).should.equal(42)\n the(result).should_NOT.equal(41)\n @should_expectation\ndef be_42(self)\n self._assert(\n action=lambda: self._value == 42,\n report=lambda: \"'{0}' should equal '5'.\".format(self._value)\n )\n\nresult = 42\n\nthe(result).should.be_42()\n" }, { "answer_id": 13971038, "author": "Dima Tisnek", "author_id": 705086, "author_profile": "https://Stackoverflow.com/users/705086", "pm_score": 0, "selected": false, "text": "__new__ 1.somemethod() # invalid\n (1).__eq__(1) # valid\n" }, { "answer_id": 17246179, "author": "alcalde", "author_id": 2128279, "author_profile": "https://Stackoverflow.com/users/2128279", "pm_score": 5, "selected": false, "text": "from forbiddenfruit import curse\ncurse(int, \"should_equal\", should_equal)\n" }, { "answer_id": 72763352, "author": "electroJo", "author_id": 19420844, "author_profile": "https://Stackoverflow.com/users/19420844", "pm_score": 0, "selected": false, "text": "class MyStrClass(str):\n\n def __init__(self, arg: str):\n self.arg_one = arg\n\n def my_str_method(self):\n return self.arg_one\n\n def my_str_multiple_arg_method(self, arg_two):\n return self.arg_one + arg_two\n\nclass MyIntClass(int):\n\n def __init__(self, arg: int):\n self.arg_one = arg\n\n def my_int_method(self):\n return self.arg_one * 2\n\n\nmyString = MyStrClass(\"StackOverflow\")\nmyInteger = MyIntClass(15)\n\nprint(myString.count(\"a\")) # Output: 1\nprint(myString.my_str_method()) # Output: StackOverflow\nprint(myString.my_str_multiple_arg_method(\" is cool!\")) # Output: StackOverflow is cool!\nprint(myInteger.my_int_method()) # Output: 30\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5304/" ]
192,653
<p>I'm using .NET 3.5 and I have a class, A, marked as internal sealed partial and it derives from System.Configuration.ApplicationSettingsBase. I then use an instance of this class in the following manner:</p> <pre><code>A A_Instance = new A(); A_Instance.Default.Save(); </code></pre> <p>Why would the Visual C# compiler be complaining:</p> <pre><code>error CS0117: 'A' does not contain a definition for 'Default' </code></pre> <p>?</p>
[ { "answer_id": 192690, "author": "Greg Dean", "author_id": 1200558, "author_profile": "https://Stackoverflow.com/users/1200558", "pm_score": 3, "selected": true, "text": "private static ServerSettings defaultInstance = ((ServerSettings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new ServerSettings())));\n\npublic static ServerSettings Default \n {\n get { return defaultInstance; }\n}\n" }, { "answer_id": 192982, "author": "Mike Caron", "author_id": 2836, "author_profile": "https://Stackoverflow.com/users/2836", "pm_score": 1, "selected": false, "text": "private static A defaultInstance = new A();\npublic static A Default \n{\n get\n {\n return defaultInstance;\n }\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2836/" ]
192,686
<p>Difficult question. The answer is probably no, if all I found in the Intertubes is right, but it is worth a try. I need to override the <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Esc</kbd> and the <kbd>Ctrl</kbd> + <kbd>Esc</kbd> combinations. It would be good to be able to override the <kbd>Win</kbd> key combinations, but I have a low level hook that does such, I only wish I didn't need it. If I can manage to block the start menu and the task manager entirely by policy, the overrides will no longer be needed but I couldn't find the correct policy to do so.</p>
[ { "answer_id": 43309345, "author": "Michael Z.", "author_id": 4114591, "author_profile": "https://Stackoverflow.com/users/4114591", "pm_score": 0, "selected": false, "text": "RegisterHotKey HookManager //It's worth noting here that if you subscribe to the Key_Press event then it will break the international accent keys.\nHookManager.KeyPress += HookManager_KeyPress;\nHookManager.KeyDown += HookManager_KeyDown;\nHookManager.KeyUp += HookManager_KeyUp;\n KeyUp public static List<Keys> keysDown = new List<Keys>();\nprivate static void HookManager_KeyDown(object sender, KeyEventArgs e)\n {\n //Used for overriding the Windows default hotkeys\n if(keysDown.Contains(e.KeyCode) == false)\n {\n keysDown.Add(e.KeyCode);\n }\n\n if (e.KeyCode == Keys.Right && WIN())\n {\n e.Handled = true;\n //Do what you want when this key combination is pressed\n }\n else if (e.KeyCode == Keys.Left && WIN())\n {\n e.Handled = true;\n //Do what you want when this key combination is pressed\n }\n\n }\n\n private static void HookManager_KeyUp(object sender, KeyEventArgs e)\n {\n //Used for overriding the Windows default hotkeys\n while(keysDown.Contains(e.KeyCode))\n {\n keysDown.Remove(e.KeyCode);\n }\n }\n\n private static void HookManager_KeyPress(object sender, KeyPressEventArgs e)\n {\n //Used for overriding the Windows default hotkeys\n\n }\n\n public static bool CTRL()\n {\n //return keysDown.Contains(Keys.LShiftKey)\n if (keysDown.Contains(Keys.LControlKey) || \n keysDown.Contains(Keys.RControlKey) || \n keysDown.Contains(Keys.Control) || \n keysDown.Contains(Keys.ControlKey))\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n\n public static bool SHIFT()\n {\n //return keysDown.Contains(Keys.LShiftKey)\n if (keysDown.Contains(Keys.LShiftKey) || \n keysDown.Contains(Keys.RShiftKey) ||\n keysDown.Contains(Keys.Shift) ||\n keysDown.Contains(Keys.ShiftKey))\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n\n public static bool WIN()\n {\n //return keysDown.Contains(Keys.LShiftKey)\n if (keysDown.Contains(Keys.LWin) || \n keysDown.Contains(Keys.RWin))\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n\n public static bool ALT()\n {\n //return keysDown.Contains(Keys.LShiftKey)\n if (keysDown.Contains(Keys.Alt))\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5954/" ]
192,693
<p>I'm writing a routine that validates data before inserting it into a database, and one of the steps is to see if numeric values fit the precision and scale of a Numeric(x,y) SQL-Server type. </p> <p>I have the precision and scale from SQL-Server already, but what's the most efficient way in C# to get the precision and scale of a CLR value, or at least to test if it fits a given constraint?</p> <p>At the moment, I'm converting the CLR value to a string, then looking for the location of the decimal point with .IndexOf(). Is there a faster way?</p>
[ { "answer_id": 192906, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 5, "selected": true, "text": "System.Data.SqlTypes.SqlDecimal.ConvertToPrecScale( new SqlDecimal (1234.56789), 8, 2)\n" }, { "answer_id": 38383700, "author": "Craig", "author_id": 525558, "author_profile": "https://Stackoverflow.com/users/525558", "pm_score": 3, "selected": false, "text": "private static bool IsValid(decimal value, byte precision, byte scale)\n{\n var sqlDecimal = new SqlDecimal(value);\n\n var actualDigitsToLeftOfDecimal = sqlDecimal.Precision - sqlDecimal.Scale;\n\n var allowedDigitsToLeftOfDecimal = precision - scale;\n\n return \n actualDigitsToLeftOfDecimal <= allowedDigitsToLeftOfDecimal && \n sqlDecimal.Scale <= scale;\n}\n" }, { "answer_id": 48912609, "author": "Evil Pigeon", "author_id": 404089, "author_profile": "https://Stackoverflow.com/users/404089", "pm_score": 2, "selected": false, "text": "private static bool IsValidSqlDecimal(decimal value, int precision, int scale)\n{\n var minOverflowValue = (decimal)Math.Pow(10, precision - scale) - (decimal)Math.Pow(10, -scale) / 2;\n return Math.Abs(value) < minOverflowValue;\n}\n DECLARE @value decimal(10,2)\nSET @value = 99999999.99499 -- Works\nSET @value = 99999999.995 -- Error\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5548/" ]
192,697
<p>How do you fix a names mismatch problem, if the client-side names are keywords or reserved words in the server-side language you are using?</p> <p>The DOJO JavaScript toolkit has a QueryReadStore class that you can subclass to submit REST patterned queries to the server. I'm using this in conjunction w/ the FilteringSelect Dijit.</p> <p>I can subclass the QueryReadStore and specify the parameters and arguments getting passed to the server. But somewhere along the way, a "start" and "count" parameter are being passed from the client to the server. I went into the API and discovered that the QueryReadStore.js is sending those parameter names.</p> <p>I'm using Fiddler to confirm what's actually being sent and brought back. The server response is telling me I have a parameter names mismatch, because of the "start" and "count" parameters. The problem is, I can't use "start" and "count" in PL/SQL.</p> <p>Workaround or correct implementation advice would be appreciated...thx.</p> <p>//I tried putting the code snippet in here, but since it's largely HTML, that didn't work so well.</p>
[ { "answer_id": 452537, "author": "MojoMark", "author_id": 56056, "author_profile": "https://Stackoverflow.com/users/56056", "pm_score": 0, "selected": false, "text": "create or replace package pkg_name\n TYPE plsqltable\n IS\n TABLE OF VARCHAR2 (32000)\n INDEX BY BINARY_INTEGER;\n\n empty plsqltable;\n PROCEDURE api (name_array IN plsqltable DEFAULT empty ,\n value_array IN plsqltable DEFAULT empty\n );\nEND pkg_name;\n CREATE OR REPLACE PACKAGE BODY pkg_name AS\n l_count_value number;\n l_start_value number;\n PROCEDURE proc_name (name_array IN plsqltable DEFAULT empty,\n value_array IN plsqltable DEFAULT empty) is\n ------------\n FUNCTION get_value (p_name IN VARCHAR) RETURN VARCHAR2 IS \n BEGIN\n FOR i IN 1..name_array.COUNT LOOP\n IF UPPER(name_array(i)) = UPPER(p_name) THEN\n RETURN value_array(i);\n END IF;\n END LOOP;\n RETURN NULL;\n END get_value;\n ----------------------\n begin\n l_count_value := get_value('count');\n l_start_value := get_value('start');\n end api;\n end pkg_name;\n http://server/dad/!pkg_name.api?start=3&count=3\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
192,715
<p>Take this non-compiling code for instance:</p> <pre><code>public string GetPath(string basefolder, string[] extraFolders) { string version = Versioner.GetBuildAndDotNetVersions(); string callingModule = StackCrawler.GetCallingModuleName(); return AppendFolders(basefolder, version, callingModule, extraFolders); } private string AppendFolders(params string[] folders) { string outstring = folders[0]; for (int i = 1; i &lt; folders.Length; i++) { string fixedPath = folders[i][0] == '\\' ? folders[i].Substring(1) : folders[i]; Path.Combine(outstring, fixedPath); } return outstring; } </code></pre> <p>This example is a somewhat simplified version of testing code I am using. Please, I am only interested in solutions having directly to do with the param keyword. I know how lists and other similar things work.</p> <p>Is there a way to "explode" the extraFolders array so that it's contents can be passed into AppendFolders along with other parameters?</p>
[ { "answer_id": 192758, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": "AppendFolders(extraFolders);\n List<string> lstFolders = new List<string>(extraFolders);\nlstFolder.Insert(0, callingModule);\nlstFolder.Insert(0, version);\nlstFolder.Insert(0, basefolder);\nreturn AppendFolders(lstFolders.ToArray());\n" }, { "answer_id": 192797, "author": "MojoFilter", "author_id": 93, "author_profile": "https://Stackoverflow.com/users/93", "pm_score": 1, "selected": false, "text": "public string GetPath(string basefolder, string[] extraFolders)\n{\n string version = Versioner.GetBuildAndDotNetVersions();\n string callingModule = StackCrawler.GetCallingModuleName();\n\n List<string> parameters = new List<string>(extraFolders.Length + 3);\n parameters.Add(basefolder);\n parameters.Add(version);\n parameters.Add(callingModule);\n parameters.AddRange(extraFolders);\n return AppendFolders(parameters.ToArray());\n}\n" }, { "answer_id": 192817, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 2, "selected": false, "text": "return AppendFolders(new string[] { basefolder, version, callingModule }.Concat(extraFolders).ToArray());\n return AppendFolders(new string[] { baseFolder, callingModuleName, version }.Concat(extraFolders));\n\npublic static T[] Concat<T>(this T[] a, T[] b) {\n return ((IEnumerable<T>)a).Concat(b).ToArray();\n}\n return AppendFolders(new Params<string>() { baseFolder, callingModuleName, version, extraFolders });\n\nclass Params<T> : List<T> {\n public void Add(IEnumerable<T> collection) {\n base.AddRange(collection);\n }\n\n public static implicit operator T[](Params<T> a) {\n return a.ToArray();\n }\n}\n" }, { "answer_id": 193050, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": true, "text": "params object[] static string appendFolders(params object[] folders)\n { return (string) folders.Aggregate(\"\",(output, f) => \n Path.Combine( (string)output\n ,(f is string[]) \n ? appendFolders((object[])f)\n : ((string)f).TrimStart('\\\\')));\n }\n static string appendFolders(params StringOrArray[] folders)\n { return folders.SelectMany(x=>x.AsEnumerable())\n .Aggregate(\"\",\n (output, f)=>Path.Combine(output,f.TrimStart('\\\\')));\n }\n\n class StringOrArray\n { string[] array;\n\n public IEnumerable<string> AsEnumerable()\n { return soa.array;}\n\n public static implicit operator StringOrArray(string s) \n { return new StringOrArray{array=new[]{s}};}\n\n public static implicit operator StringOrArray(string[] s) \n { return new StringOrArray{array=s};}\n }\n appendFolders(\"base\", \"v1\", \"module\", new[]{\"debug\",\"bin\"});\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9251/" ]
192,718
<p>I need to run a JNDI provider without the overhead of a J2EE container. I've tried to follow the directions in this <a href="http://www.javaworld.com/javaworld/jw-04-2002/jw-0419-jndi.html" rel="noreferrer">article</a>, which describes (on page 3) exactly what I want to do. Unfortunately, these directions fail. I had to add the jboss-common.jar to my classpath too. Once I did that, I get a stack trace:</p> <pre><code>$ java org.jnp.server.Main 0 [main] DEBUG org.jboss.naming.Naming - Creating NamingServer stub, theServer=null,rmiPort=0,clientSocketFactory=null,serverSocketFactory=org.jboss.net.sockets.DefaultSocketFactory@ad093076[bindAddress=null] Exception in thread "main" java.lang.NullPointerException at org.jnp.server.Main.getNamingInstance(Main.java:301) at org.jnp.server.Main.initJnpInvoker(Main.java:354) at org.jnp.server.Main.start(Main.java:316) at org.jnp.server.Main.main(Main.java:104) </code></pre> <p>I'm hoping to make this work, but I would also be open to other lightweight standalone JNDI providers. All of this is to make ActiveMQ work, and if somebody can suggest another lightweight JMS provider that works well outside of the vm the clients are in without a full blown app server that would work too. </p>
[ { "answer_id": 192936, "author": "KC Baltz", "author_id": 9910, "author_profile": "https://Stackoverflow.com/users/9910", "pm_score": 2, "selected": false, "text": "java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory\n\n# use the following property to configure the default connector\njava.naming.provider.url=tcp://jmshost:61616\n\n# use the following property to specify the JNDI name the connection factory\n# should appear as. \n#connectionFactoryNames = connectionFactory, queueConnectionFactory, topicConnectionFactry\n\n# register some queues in JNDI using the form\n# queue.[jndiName] = [physicalName]\n#queue.MyQueue = example.MyQueue\n\n\n# register some topics in JNDI using the form\n# topic.[jndiName] = [physicalName]\ntopic.myTopic = MY.TOPIC\n context = new InitialContext(properties);\n\ncontext = (Context) context.lookup(\"java:comp/env/jms\");\n\ntopicConnectionFactory = (TopicConnectionFactory) context.lookup(\"ConnectionFactory\");\n\ntopic = (Topic) context.lookup(\"myTopic\");\n" }, { "answer_id": 197073, "author": "James Strachan", "author_id": 2068211, "author_profile": "https://Stackoverflow.com/users/2068211", "pm_score": 4, "selected": true, "text": "java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory\n\n# use the following property to configure the default connector\njava.naming.provider.url = failover:tcp://localhost:61616\n\n# use the following property to specify the JNDI name the connection factory\n# should appear as. \n#connectionFactoryNames = connectionFactory, queueConnectionFactory, topicConnectionFactry\n\n# register some queues in JNDI using the form\n# queue.[jndiName] = [physicalName]\nqueue.MyQueue = example.MyQueue\n\n\n# register some topics in JNDI using the form\n# topic.[jndiName] = [physicalName]\ntopic.MyTopic = example.MyTopic\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13816/" ]
192,721
<p>In <a href="https://stackoverflow.com/users/23233/mmalc">@mmalc's</a> <a href="https://stackoverflow.com/questions/155964/what-are-best-practices-that-you-use-when-writing-objective-c-and-cocoa#156288">response</a> to <a href="https://stackoverflow.com/questions/155964/what-are-best-practices-that-you-use-when-writing-objective-c-and-cocoa">this question</a> he states that "In general you should <em>not</em> use accessor methods in dealloc (or init)." Why does mmalc say this?</p> <p>The only really reasons I can think of are performance and avoiding unknown side-effects of @dynamic setters.</p> <p>Discussion?</p>
[ { "answer_id": 192852, "author": "Andrew Grant", "author_id": 1043, "author_profile": "https://Stackoverflow.com/users/1043", "pm_score": 5, "selected": false, "text": "@implementation Example\n\n-(void) setFoo:(Foo*)foo\n{\n _foo = foo;\n [_observer onPropertyChange:self object:foo];\n}\n\n-(void) dealloc\n{\n ...\n self.foo = nil;\n}\n\n@end\n" }, { "answer_id": 227555, "author": "Louis Gerbarg", "author_id": 30506, "author_profile": "https://Stackoverflow.com/users/30506", "pm_score": 5, "selected": true, "text": "- (NSMutableDictionary *) myMutableDict {\n if (!myMutableDict) {\n myMutableDict = [[NSMutableDictionary alloc] init];\n }\n\n return myMutableDict;\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23113/" ]
192,725
<p>I have just started learning Erlang and am trying out some Project Euler problems to get started. However, I seem to be able to do any operations on large sequences without crashing the erlang shell.</p> <p>Ie.,even this:</p> <pre><code>list:seq(1,64000000). </code></pre> <p>crashes erlang, with the error:</p> <p>eheap_alloc: Cannot allocate 467078560 bytes of memory (of type "heap").</p> <p>Actually # of bytes varies of course.</p> <p>Now half a gig is a lot of memory, but a system with 4 gigs of RAM and plenty of space for virtual memory should be able to handle it.</p> <p>Is there a way to let erlang use more memory?</p>
[ { "answer_id": 193804, "author": "Darius Bacon", "author_id": 27024, "author_profile": "https://Stackoverflow.com/users/27024", "pm_score": 5, "selected": true, "text": "-module(lazy).\n-export([seq/2]).\n\nseq(M, N) when M =< N ->\n fun() -> [M | seq(M+1, N)] end;\nseq(_, _) ->\n fun () -> [] end.\n\n1> Ns = lazy:seq(1, 64000000).\n#Fun<lazy.0.26378159>\n2> hd(Ns()).\n1\n3> Ns2 = tl(Ns()).\n#Fun<lazy.0.26378159>\n4> hd(Ns2()).\n2\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7856/" ]
192,736
<p>A word of warning: I'm a n00b to <code>git</code> in general. My team uses feature branches in <code>svn</code>, and I'd like to use <code>git-svn</code> to track my work on a particular feature branch. I've been (roughly) following <a href="http://andy.delcambre.com/2008/03/04/git-svn-workflow.html" rel="noreferrer">Andy Delcambre's post</a> to set up my local <code>git</code> repo, but those instructions seem to have led <code>git</code> to pick the <code>svn</code> branch that had changed most recently as the remote repository; the problem is that's not the branch I care about. How do I control which branch <code>git-svn</code> uses? Or am I approaching this completely wrong?</p> <p>UPDATE: I did use the <code>-T</code>, <code>-b</code>, and <code>-t</code> options (in my case because the <code>svn</code> repo has multiple projects, but I want the <code>git</code> repo to contain only the project I'm working on).</p>
[ { "answer_id": 197453, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 7, "selected": true, "text": "git git checkout -b git-topic-branch-foo foo\n foo" }, { "answer_id": 696304, "author": "Sam Mulube", "author_id": 84492, "author_profile": "https://Stackoverflow.com/users/84492", "pm_score": 5, "selected": false, "text": "git branch -r\n git reset --hard remotes/svn-branch-name\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4203/" ]