qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
124,647
<p>Say I have an array that represents a set of points:</p> <pre><code>x = [2, 5, 8, 33, 58] </code></pre> <p>How do I generate an array of all the pairwise distances? </p>
[ { "answer_id": 124734, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 4, "selected": true, "text": "x = [2, 5, 8, 33, 58]\nprint x.collect {|n| x.collect {|i| (n-i).abs}}.flatten\n" }, { "answer_id": 129558, "author": "AShelly", "author_id": 10396, "author_profile": "https://Stackoverflow.com/users/10396", "pm_score": 0, "selected": false, "text": "result=[]\nx.each_index{|i| (i+1).upto(x.size-1){|j| result<<(x[i]-x[j]).abs}}\n" }, { "answer_id": 131228, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 0, "selected": false, "text": "x.map{|i| x.map{|j| (i-j).abs } }\n x.map{|i| x.map{|j| (i-j).abs } }.flatten\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ]
124,649
<p>In my Silverlight application, I can't seem to bring focus to a TextBox control. On the recommendation of various posts, I've set the IsTabStop property to True and I'm using TextBox.Focus(). Though the UserControl_Loaded event is firing, the TextBox control isn't getting focus. I've included my very simple code below. What am I missing? Thanks.</p> <p><strong><em>Page.xaml</em></strong> </p> <pre><code>&lt;UserControl x:Class="TextboxFocusTest.Page" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Loaded="UserControl_Loaded" Width="400" Height="300"&gt; &lt;Grid x:Name="LayoutRoot" Background="White"&gt; &lt;StackPanel Width="150" VerticalAlignment="Center"&gt; &lt;TextBox x:Name="RegularTextBox" IsTabStop="True" /&gt; &lt;/StackPanel&gt; &lt;/Grid&gt; &lt;/UserControl&gt; </code></pre> <p><strong><em>Page.xaml.cs</em></strong></p> <pre><code>using System.Windows; using System.Windows.Controls; namespace PasswordTextboxTest { public partial class Page : UserControl { public Page() { InitializeComponent(); } private void UserControl_Loaded(object sender, RoutedEventArgs e) { RegularTextBox.Focus(); } } } </code></pre>
[ { "answer_id": 124778, "author": "Bryant", "author_id": 10893, "author_profile": "https://Stackoverflow.com/users/10893", "pm_score": 1, "selected": false, "text": "<StackPanel Width=\"150\" VerticalAlignment=\"Center\">\n <TextBox x:Name=\"RegularTextBox\" IsTabStop=\"True\" />\n <Button Click=\"UserControl_Loaded\">\n <TextBlock Text=\"Test\"/>\n </Button>\n</StackPanel>\n Width=\"400\" Height=\"300\" Loaded=\"UserControl_Loaded\" KeyDown=\"UserControl_KeyDown\">\n" }, { "answer_id": 129167, "author": "Jim B-G", "author_id": 21833, "author_profile": "https://Stackoverflow.com/users/21833", "pm_score": 6, "selected": true, "text": " private void UserControl_Loaded(object sender, RoutedEventArgs e)\n { \n System.Windows.Browser.HtmlPage.Plugin.Focus();\n RegularTextBox.Focus();\n }\n" }, { "answer_id": 1892895, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 1, "selected": false, "text": "System.Windows.Browser.HtmlPage.Plugin.Focus();" }, { "answer_id": 2638530, "author": "rekle", "author_id": 10809, "author_profile": "https://Stackoverflow.com/users/10809", "pm_score": 5, "selected": false, "text": "Plugin.Focus(); \n Dispatcher.BeginInvoke(() => { tbNewText.Focus();});\n" }, { "answer_id": 4459503, "author": "user544583", "author_id": 544583, "author_profile": "https://Stackoverflow.com/users/544583", "pm_score": 1, "selected": false, "text": " System.Windows.Browser.HtmlPage.Plugin.Focus();\n txtUserName.IsTabStop = true;\n txtPassword.IsTabStop = true;\n\n if (txtUserName.Text.Trim().Length != 0)\n {\n txtPassword.UpdateLayout();\n txtPassword.Focus();\n txtPassword.TabIndex = 0;\n }\n else\n {\n txtUserName.UpdateLayout();\n txtUserName.Focus();\n txtUserName.TabIndex = 0;\n }\n" }, { "answer_id": 8857517, "author": "Matthew Steven Monkan", "author_id": 1399567, "author_profile": "https://Stackoverflow.com/users/1399567", "pm_score": 0, "selected": false, "text": "BusyIndicator Dispatcher.BeginInvoke(() => { myControl.Focus();}); \n" }, { "answer_id": 12121886, "author": "Jonathan S.", "author_id": 1624484, "author_profile": "https://Stackoverflow.com/users/1624484", "pm_score": 0, "selected": false, "text": " Me.Focus()\n Me.UpdateLayout()\n\n Me.tbx_user_num.Focus()\n Me.tbx_user_num.UpdateLayout()\n" }, { "answer_id": 12912633, "author": "Luca", "author_id": 1749709, "author_profile": "https://Stackoverflow.com/users/1749709", "pm_score": 2, "selected": false, "text": "this.TargetTextBox.Loaded += (o, e) => { this.TargetTextBox.Focus(); };\n" }, { "answer_id": 16315884, "author": "harryhazza", "author_id": 1278807, "author_profile": "https://Stackoverflow.com/users/1278807", "pm_score": 1, "selected": false, "text": "System.Windows.Browser.HtmlPage.Plugin.Focus();\n<YourTextBox>.UpdateLayout()\n<YourTextBox>.Focus();\n" }, { "answer_id": 42622158, "author": "Talha Imam", "author_id": 5863938, "author_profile": "https://Stackoverflow.com/users/5863938", "pm_score": 0, "selected": false, "text": "this.Loaded += new RoutedEventHandler(MainPage_Loaded);\n void MainPage_Loaded(object sender, RoutedEventArgs e)\n {\n System.Windows.Browser.HtmlPage.Plugin.Focus();\n RegularTextBox.Focus();\n }\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4115/" ]
124,650
<p>I do mostly Windows development. We use <a href="http://www.mantisbt.org/" rel="noreferrer">Mantis</a> and <a href="http://subversion.tigris.org/" rel="noreferrer">Subversion</a> for our development but they aren't integrated together, in fact they are on different servers.</p> <p>I did a little googling about integrating the two together and came across <a href="http://alt-tag.com/blog/archives/2006/11/integrating-mantis-and-subversion/" rel="noreferrer">this post</a>. It looked interesting.</p> <p>I was wondering if anyone is doing this or has done this and what your experience has been. If you've got a different solution, I'd be interested in knowing that too!</p> <p>Thanks!</p>
[ { "answer_id": 941080, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 3, "selected": false, "text": "c:\\tools\\perl c:\\tools\\mantis_urlencode.pl %1 %2 > c:\\temp\\postcommit_mantis.txt\nif %ERRORLEVEL% NEQ 0 exit /b 0\n\nc:\\tools\\curl -s -d user=svn -d @c:\\temp\\postcommit_mantis.txt http://swi-sgi-l-web1.ingrnet.com/mantis/core/checkincurl.php\n $url = `svnlook log -r $ARGV[1] $ARGV[0]`;\n\n# check the string contains the matching regexp, \n# quit if it doesn't so we don't waste time contacting the webserver\n# this is the g_source_control_regexp value in mantis.\n\nexit 1 if not $url =~ /\\b(?:bug|issue|mantis)\\s*[#]{0,1}(\\d+)\\b/i;\n\n$url = $url . \"\\n\" . `svnlook dirs-changed -r $ARGV[1] $ARGV[0]`;\n\n#urlencode the string\n$url =~ s/([^\\w\\-\\.\\@])/$1 eq \" \"?\"+\": sprintf(\"%%%2.2x\",ord($1))/eg;\n\nprint \"log=$url\";\n\nexit 0;\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7862/" ]
124,667
<p>This is probably a really stupid newbie-sounding question to you developer type people, but I'm at a loss :( I've been trying to learn how to use Subversion for keeping the history of my code, but I'm finding it pretty confusing. I read the 'book' that comes with Subversion, but I didn't find it all that helpful. I'm using Windows, and I downloaded the TortoiseSVN GUI for it. </p> <p>All I really want to know how to do is to create a new project, put a file in it (any old file), and then update that file, just so I can see how it works. I created a 'repository' (in svn_repository/test), and if anyone could tell me how I'm supposed to go about creating a new file/putting a file in it, and then updating that file I'd be really happy :) Knowing my luck it'll be something as simple as "drag and drop the file into the directory". Apologies for asking such a stupid question! </p> <p>Also if anyone could tell me how to go about making it work with Zend Studio, that would be extra awesome-points. Thanks!</p>
[ { "answer_id": 124836, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 3, "selected": false, "text": "# create an empty repository\nsvnadmin create myrepos\n\n# check out a working copy of the empty repository\nsvn co file://full/path/to/myrepos workingcopy\n\n# create an empty file in workingcopy (nothing to do with SVN - use \n# File > New > Text Document if you like)\ncd workingcopy\ntouch mycode\n\n# place it under version control, then tell the repository what you've done.\nsvn add mycode\nsvn ci -m \"My first ever checkin comment! File created.\"\n\n# Now we're developing. Go edit the file. Come back when you're done.\n\n# Check it back in\nsvn ci -m \"First version of project\"\n\n# Go edit it again\n\n# Check it in again\nsvn ci -m \"Made my project better\"\n\n# See what we've done so far\nsvn log mycode\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21442/" ]
124,671
<p>How do I pick a random element from a set? I'm particularly interested in picking a random element from a HashSet or a LinkedHashSet, in Java. Solutions for other languages are also welcome. </p>
[ { "answer_id": 124687, "author": "Swaroop C H", "author_id": 4869, "author_profile": "https://Stackoverflow.com/users/4869", "pm_score": 1, "selected": false, "text": ">>> import random\n>>> random.choice([1,2,3,4,5,6])\n3\n>>> random.choice([1,2,3,4,5,6])\n4\n" }, { "answer_id": 124691, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 3, "selected": false, "text": "Set<Integer> set = new LinkedHashSet<Integer>(3);\nset.add(1);\nset.add(2);\nset.add(3);\n\nRandom rand = new Random(System.currentTimeMillis());\nint[] setArray = (int[]) set.toArray();\nfor (int i = 0; i < 10; ++i) {\n System.out.println(setArray[rand.nextInt(set.size())]);\n}\n" }, { "answer_id": 124693, "author": "Khoth", "author_id": 20686, "author_profile": "https://Stackoverflow.com/users/20686", "pm_score": 8, "selected": true, "text": "int size = myHashSet.size();\nint item = new Random().nextInt(size); // In real life, the Random object should be rather more shared than this\nint i = 0;\nfor(Object obj : myhashSet)\n{\n if (i == item)\n return obj;\n i++;\n}\n" }, { "answer_id": 124699, "author": "matt lohkamp", "author_id": 14026, "author_profile": "https://Stackoverflow.com/users/14026", "pm_score": 1, "selected": false, "text": "function randFromSet(target){\n var targetLength:uint = target.length()\n var randomIndex:uint = random(0,targetLength);\n return target[randomIndex];\n}\n" }, { "answer_id": 124700, "author": "dirtside", "author_id": 20903, "author_profile": "https://Stackoverflow.com/users/20903", "pm_score": 1, "selected": false, "text": "$foo = array(\"alpha\", \"bravo\", \"charlie\");\n$index = array_rand($foo);\n$val = $foo[$index];\n" }, { "answer_id": 124735, "author": "da5id", "author_id": 14979, "author_profile": "https://Stackoverflow.com/users/14979", "pm_score": 0, "selected": false, "text": "$items_array = array(\"alpha\", \"bravo\", \"charlie\");\n$last_pos = count($items_array) - 1;\n$random_pos = mt_rand(0, $last_pos);\n$random_item = $items_array[$random_pos];\n" }, { "answer_id": 124749, "author": "Mathew Byrne", "author_id": 10942, "author_profile": "https://Stackoverflow.com/users/10942", "pm_score": 1, "selected": false, "text": "function choose (set) {\n return set[Math.floor(Math.random() * set.length)];\n}\n\nvar set = [1, 2, 3, 4], rand = choose (set);\n Array.prototype.choose = function () {\n return this[Math.floor(Math.random() * this.length)];\n};\n\n[1, 2, 3, 4].choose();\n" }, { "answer_id": 124769, "author": "chickeninabiscuit", "author_id": 3966, "author_profile": "https://Stackoverflow.com/users/3966", "pm_score": 6, "selected": false, "text": "java.util.Collections Collections.shuffle(List<?>) Collections.shuffle(List<?> list, Random rnd)" }, { "answer_id": 124791, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 2, "selected": false, "text": "@hash_keys = (keys %hash);\n$rand = int(rand(@hash_keys));\nprint $hash{$hash_keys[$rand]};\n" }, { "answer_id": 124942, "author": "Hugh Allen", "author_id": 15069, "author_profile": "https://Stackoverflow.com/users/15069", "pm_score": 1, "selected": false, "text": "? set( [1, 2, 3, 4, 5] )\n randomize()" }, { "answer_id": 125270, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 1, "selected": false, "text": " Random random = new Random((int)DateTime.Now.Ticks);\n\n OrderedDictionary od = new OrderedDictionary();\n\n od.Add(\"abc\", 1);\n od.Add(\"def\", 2);\n od.Add(\"ghi\", 3);\n od.Add(\"jkl\", 4);\n\n\n int randomIndex = random.Next(od.Count);\n\n Console.WriteLine(od[randomIndex]);\n\n // Can access via index or key value:\n Console.WriteLine(od[1]);\n Console.WriteLine(od[\"def\"]);\n" }, { "answer_id": 125416, "author": "inglesp", "author_id": 10439, "author_profile": "https://Stackoverflow.com/users/10439", "pm_score": 1, "selected": false, "text": "(defun pick-random (set)\n (nth (random (length set)) set))\n" }, { "answer_id": 388128, "author": "pjb3", "author_id": 41984, "author_profile": "https://Stackoverflow.com/users/41984", "pm_score": 2, "selected": false, "text": "(defn pick-random [set] (let [sq (seq set)] (nth sq (rand-int (count sq)))))\n" }, { "answer_id": 1964730, "author": "Thomas Ahle", "author_id": 205521, "author_profile": "https://Stackoverflow.com/users/205521", "pm_score": 0, "selected": false, "text": "import random\n\nclass Node:\n def __init__(self, object):\n self.object = object\n self.value = hash(object)\n self.size = 1\n self.a = self.b = None\n\nclass RandomSet:\n def __init__(self):\n self.top = None\n\n def add(self, object):\n \"\"\" Add any hashable object to the set.\n Notice: In this simple implementation you shouldn't add two\n identical items. \"\"\"\n new = Node(object)\n if not self.top: self.top = new\n else: self._recursiveAdd(self.top, new)\n def _recursiveAdd(self, top, new):\n top.size += 1\n if new.value < top.value:\n if not top.a: top.a = new\n else: self._recursiveAdd(top.a, new)\n else:\n if not top.b: top.b = new\n else: self._recursiveAdd(top.b, new)\n\n def pickRandom(self):\n \"\"\" Pick a random item in O(log2) time.\n Does a maximum of O(log2) calls to random as well. \"\"\"\n return self._recursivePickRandom(self.top)\n def _recursivePickRandom(self, top):\n r = random.randrange(top.size)\n if r == 0: return top.object\n elif top.a and r <= top.a.size: return self._recursivePickRandom(top.a)\n return self._recursivePickRandom(top.b)\n\nif __name__ == '__main__':\n s = RandomSet()\n for i in [5,3,7,1,4,6,9,2,8,0]:\n s.add(i)\n\n dists = [0]*10\n for i in xrange(10000):\n dists[s.pickRandom()] += 1\n print dists\n" }, { "answer_id": 3290573, "author": "Aaron McDaid", "author_id": 146041, "author_profile": "https://Stackoverflow.com/users/146041", "pm_score": 2, "selected": false, "text": "//#include <boost/unordered_set.hpp> \n//using namespace boost;\n#include <tr1/unordered_set>\nusing namespace std::tr1;\n#include <iostream>\n#include <stdlib.h>\n#include <assert.h>\nusing namespace std;\n\nint main() {\n unordered_set<int> u;\n u.max_load_factor(40);\n for (int i=0; i<40; i++) {\n u.insert(i);\n cout << ' ' << i;\n }\n cout << endl;\n cout << \"Number of buckets: \" << u.bucket_count() << endl;\n\n for(size_t b=0; b<u.bucket_count(); b++)\n cout << \"Bucket \" << b << \" has \" << u.bucket_size(b) << \" elements. \" << endl;\n\n for(size_t i=0; i<20; i++) {\n size_t x = rand() % u.size();\n cout << \"we'll quickly get the \" << x << \"th item in the unordered set. \";\n size_t b;\n for(b=0; b<u.bucket_count(); b++) {\n if(x < u.bucket_size(b)) {\n break;\n } else\n x -= u.bucket_size(b);\n }\n cout << \"it'll be in the \" << b << \"th bucket at offset \" << x << \". \";\n unordered_set<int>::const_local_iterator l = u.begin(b);\n while(x>0) {\n l++;\n assert(l!=u.end(b));\n x--;\n }\n cout << \"random item is \" << *l << \". \";\n cout << endl;\n }\n}\n" }, { "answer_id": 5162675, "author": "Dustin Getz", "author_id": 20003, "author_profile": "https://Stackoverflow.com/users/20003", "pm_score": -1, "selected": false, "text": "static Random random = new Random(System.currentTimeMillis());\npublic static <T> T randomChoice(T[] choices)\n{\n int index = random.nextInt(choices.length);\n return choices[index];\n}\n" }, { "answer_id": 5669034, "author": "fandrew", "author_id": 708633, "author_profile": "https://Stackoverflow.com/users/708633", "pm_score": 5, "selected": false, "text": "ArrayList HashMap RandomAccess pollRandom public class RandomSet<E> extends AbstractSet<E> {\n\n List<E> dta = new ArrayList<E>();\n Map<E, Integer> idx = new HashMap<E, Integer>();\n\n public RandomSet() {\n }\n\n public RandomSet(Collection<E> items) {\n for (E item : items) {\n idx.put(item, dta.size());\n dta.add(item);\n }\n }\n\n @Override\n public boolean add(E item) {\n if (idx.containsKey(item)) {\n return false;\n }\n idx.put(item, dta.size());\n dta.add(item);\n return true;\n }\n\n /**\n * Override element at position <code>id</code> with last element.\n * @param id\n */\n public E removeAt(int id) {\n if (id >= dta.size()) {\n return null;\n }\n E res = dta.get(id);\n idx.remove(res);\n E last = dta.remove(dta.size() - 1);\n // skip filling the hole if last is removed\n if (id < dta.size()) {\n idx.put(last, id);\n dta.set(id, last);\n }\n return res;\n }\n\n @Override\n public boolean remove(Object item) {\n @SuppressWarnings(value = \"element-type-mismatch\")\n Integer id = idx.get(item);\n if (id == null) {\n return false;\n }\n removeAt(id);\n return true;\n }\n\n public E get(int i) {\n return dta.get(i);\n }\n\n public E pollRandom(Random rnd) {\n if (dta.isEmpty()) {\n return null;\n }\n int id = rnd.nextInt(dta.size());\n return removeAt(id);\n }\n\n @Override\n public int size() {\n return dta.size();\n }\n\n @Override\n public Iterator<E> iterator() {\n return dta.iterator();\n }\n}\n" }, { "answer_id": 5683228, "author": "Mr.Wizard", "author_id": 618728, "author_profile": "https://Stackoverflow.com/users/618728", "pm_score": 1, "selected": false, "text": "a = {1, 2, 3, 4, 5}\n\na[[ ⌈ Length[a] Random[] ⌉ ]]\n RandomChoice[a]\n Random[] a a = {\"Badger\" -> 5, \"Bird\" -> 1, \"Fox\" -> 3, \"Frog\" -> 2, \"Wolf\" -> 4};\n" }, { "answer_id": 13712946, "author": "Ben Noland", "author_id": 32899, "author_profile": "https://Stackoverflow.com/users/32899", "pm_score": 3, "selected": false, "text": "List asList = new ArrayList(mySet);\nCollections.shuffle(asList);\nreturn asList.get(0);\n" }, { "answer_id": 13941507, "author": "Daniel Lubarov", "author_id": 714009, "author_profile": "https://Stackoverflow.com/users/714009", "pm_score": 1, "selected": false, "text": "public static <A> A getRandomElement(Collection<A> c, Random r) {\n return new ArrayList<A>(c).get(r.nextInt(c.size()));\n}\n" }, { "answer_id": 20730236, "author": "Thomas Ahle", "author_id": 205521, "author_profile": "https://Stackoverflow.com/users/205521", "pm_score": 1, "selected": false, "text": "class RandomHashSet<V> extends AbstractSet<V> {\n private Map<Object,V> map = new HashMap<>();\n public boolean add(V v) {\n return map.put(new WrapKey<V>(v),v) == null;\n }\n @Override\n public Iterator<V> iterator() {\n return new Iterator<V>() {\n RandKey key = new RandKey();\n @Override public boolean hasNext() {\n return true;\n }\n @Override public V next() {\n while (true) {\n key.next();\n V v = map.get(key);\n if (v != null)\n return v;\n }\n }\n @Override public void remove() {\n throw new NotImplementedException();\n }\n };\n }\n @Override\n public int size() {\n return map.size();\n }\n static class WrapKey<V> {\n private V v;\n WrapKey(V v) {\n this.v = v;\n }\n @Override public int hashCode() {\n return v.hashCode();\n }\n @Override public boolean equals(Object o) {\n if (o instanceof RandKey)\n return true;\n return v.equals(o);\n }\n }\n static class RandKey {\n private Random rand = new Random();\n int key = rand.nextInt();\n public void next() {\n key = rand.nextInt();\n }\n @Override public int hashCode() {\n return key;\n }\n @Override public boolean equals(Object o) {\n return true;\n }\n }\n}\n" }, { "answer_id": 25410520, "author": "Sean Van Gorder", "author_id": 2643425, "author_profile": "https://Stackoverflow.com/users/2643425", "pm_score": 5, "selected": false, "text": "int index = rand.nextInt(set.size());\nIterator<Object> iter = set.iterator();\nfor (int i = 0; i < index; i++) {\n iter.next();\n}\nreturn iter.next();\n Iterator.hasNext() index < set.size() public static <E> E choice(Collection<? extends E> coll, Random rand) {\n if (coll.size() == 0) {\n return null; // or throw IAE, if you prefer\n }\n\n int index = rand.nextInt(coll.size());\n if (coll instanceof List) { // optimization\n return ((List<? extends E>) coll).get(index);\n } else {\n Iterator<? extends E> iter = coll.iterator();\n for (int i = 0; i < index; i++) {\n iter.next();\n }\n return iter.next();\n }\n}\n" }, { "answer_id": 26873174, "author": "sivi", "author_id": 1984636, "author_profile": "https://Stackoverflow.com/users/1984636", "pm_score": 0, "selected": false, "text": "Object[] arr = set.toArray();\n\nint v = (int) arr[rnd.nextInt(arr.length)];\n" }, { "answer_id": 27352828, "author": "Jason Hartley", "author_id": 1301891, "author_profile": "https://Stackoverflow.com/users/1301891", "pm_score": 3, "selected": false, "text": "size i int random = new Random().nextInt(myhashSet.size());\n for(Object obj : myhashSet) {\n if (random-- == 0) {\n return obj;\n }\n }\n 0" }, { "answer_id": 28325603, "author": "Philipp", "author_id": 76024, "author_profile": "https://Stackoverflow.com/users/76024", "pm_score": 0, "selected": false, "text": "Set Set<Integer> s = ...\n Iterator<Integer> it = s.iterator();\n if(it.hasNext()){\n Integer i = it.next();\n // i is a \"random\" object from set\n }\n" }, { "answer_id": 28705520, "author": "Nicu Marasoiu", "author_id": 4602906, "author_profile": "https://Stackoverflow.com/users/4602906", "pm_score": 1, "selected": false, "text": "outbound.stream().skip(n % outbound.size()).findFirst().get()\n n for(elem: Col)" }, { "answer_id": 29298987, "author": "stivlo", "author_id": 445543, "author_profile": "https://Stackoverflow.com/users/445543", "pm_score": 0, "selected": false, "text": "/**\n * @param set a Set in which to look for a random element\n * @param <T> generic type of the Set elements\n * @return a random element in the Set or null if the set is empty\n */\npublic <T> T randomElement(Set<T> set) {\n int size = set.size();\n int item = random.nextInt(size);\n int i = 0;\n for (T obj : set) {\n if (i == item) {\n return obj;\n }\n i++;\n }\n return null;\n}\n" }, { "answer_id": 34594139, "author": "BHARAT ARYA", "author_id": 3913846, "author_profile": "https://Stackoverflow.com/users/3913846", "pm_score": -1, "selected": false, "text": "int random;\nHashSet someSet;\n<Type>[] randData;\nrandom = new Random(System.currentTimeMillis).nextInt(someSet.size());\nrandData = someSet.toArray();\n<Type> sResult = randData[random];\n" }, { "answer_id": 36918972, "author": "dimo414", "author_id": 113632, "author_profile": "https://Stackoverflow.com/users/113632", "pm_score": 1, "selected": false, "text": "public static E random(Set<E> set) {\n int index = random.nextInt(set.size();\n if (set instanceof ImmutableSet) {\n // ImmutableSet.asList() is O(1), as is .get() on the returned list\n return set.asList().get(index);\n }\n return Iterables.get(set, index);\n}\n" }, { "answer_id": 45556911, "author": "RKumsher", "author_id": 1660607, "author_profile": "https://Stackoverflow.com/users/1660607", "pm_score": 0, "selected": false, "text": "Set<Object> set = new HashSet<>();\nset.add(...);\n...\nObject random = IterableUtils.randomFrom(set);\n <dependency>\n <groupId>com.github.rkumsher</groupId>\n <artifactId>utils</artifactId>\n <version>1.3</version>\n</dependency>\n" }, { "answer_id": 51412979, "author": "Joshua Bone", "author_id": 9910647, "author_profile": "https://Stackoverflow.com/users/9910647", "pm_score": 5, "selected": false, "text": "static <E> E getRandomSetElement(Set<E> set) {\n return set.stream().skip(new Random().nextInt(set.size())).findFirst().orElse(null);\n}\n" }, { "answer_id": 68640122, "author": "hub", "author_id": 2239025, "author_profile": "https://Stackoverflow.com/users/2239025", "pm_score": 2, "selected": false, "text": " static <E> Optional<E> getRandomElement(Collection<E> collection) {\n return collection\n .stream()\n .skip(ThreadLocalRandom.current()\n .nextInt(collection.size()))\n .findAny();\n }\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21445/" ]
124,682
<p>Can you have custom client-side javascript Validation for standard ASP.NET Web Form Validators?</p> <p>For instance use a asp:RequiredFieldValidator leave the server side code alone but implement your own client notification using jQuery to highlight the field or background color for example.</p>
[ { "answer_id": 125127, "author": "sontek", "author_id": 17176, "author_profile": "https://Stackoverflow.com/users/17176", "pm_score": 1, "selected": false, "text": " <script type=\"text/javascript\">\n rfv.evaluationfunction = validator;\n\n function validator(sender, e) {\n alert('rawr');\n }\n </script>\n <asp:CustomValidator ControlToValidate=\"txtBox\" ClientValidationFunction=\"onValidate\" />\n\n<script type='text/javascript'>\nfunction onValidate(sender, e)\n { \n alert('do validation');\n }\n</script>\n" }, { "answer_id": 125158, "author": "Geoff", "author_id": 10427, "author_profile": "https://Stackoverflow.com/users/10427", "pm_score": 5, "selected": false, "text": "/**\n * Re-assigns a couple of the ASP.NET validation JS functions to\n * provide a more flexible approach\n */\nfunction UpgradeASPNETValidation(){\n // Hi-jack the ASP.NET error display only if required\n if (typeof(Page_ClientValidate) != \"undefined\") {\n ValidatorUpdateDisplay = NicerValidatorUpdateDisplay;\n AspPage_ClientValidate = Page_ClientValidate;\n Page_ClientValidate = NicerPage_ClientValidate;\n }\n}\n\n/**\n * Extends the classic ASP.NET validation to add a class to the parent span when invalid\n */\nfunction NicerValidatorUpdateDisplay(val){\n if (val.isvalid){\n // do custom removing\n $(val).fadeOut('slow');\n } else {\n // do custom show\n $(val).fadeIn('slow');\n }\n}\n\n/**\n * Extends classic ASP.NET validation to include parent element styling\n */\nfunction NicerPage_ClientValidate(validationGroup){\n var valid = AspPage_ClientValidate(validationGroup);\n\n if (!valid){\n // do custom styling etc\n // I added a background colour to the parent object\n $(this).parent().addClass('invalidField');\n }\n}\n" }, { "answer_id": 125193, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 5, "selected": true, "text": "<asp:CustomValidator ControlToValidate=\"Text1\" \n ClientValidationFunction=\"onValidate\" />\n\n<script type='text/javascript'>\nfunction onValidate(validatorSpan, eventArgs)\n { eventArgs.IsValid = (eventArgs.Value.length > 0);\n if (!eventArgs.IsValid) highlight(validatorSpan);\n }\n</script>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3747/" ]
124,722
<p>When writing GUIs, I've frequently come over the following problem: Assume you have a model and a controller. The controller has a widget <code>W</code> that is used to show a property <code>X</code> of the model.</p> <p>Because the model might be changed from outside the controller (there might be other controllers using the same model, undo operations etc), the controller listens to changes on the model. The controller also listens to events on the widget <code>W</code> and updates the property <code>X</code> accordingly.</p> <p>Now, the following happens:</p> <ol> <li>the value in <code>W</code> is changed</li> <li>an event is generated, the handler in the <strong>controller</strong> is invoked</li> <li>the <strong>controller</strong> sets the new value for <code>X</code> in the <strong>model</strong></li> <li>the <strong>model</strong> emits events because it has been changed</li> <li>the <strong>controller</strong> receives a change event from the <strong>model</strong></li> <li>the <strong>controller</strong> gets the value of <code>X</code> and sets it in the widget</li> <li>goto 1.</li> </ol> <p>There are several possible solutions for that:</p> <ol> <li>Modify the controller to set a flag when the model is updated, and not react to any events from the model if this flag is set. </li> <li>Disconnect the controller temporarily (or tell the model not to send any events for some time)</li> <li>Freeze any updates from the widget</li> </ol> <p>In the past, I usually went for option 1., because it's the simplest thing. It has the drawback of cluttering your classes with flags, but the other methods have their drawbacks, too.</p> <p>Just for the record, I've had this problem with several GUI toolkits, including GTK+, Qt and SWT, so I think it's pretty toolkit-agnostic.</p> <p>Any best practices? Or is the architecture I use simply wrong?</p> <p>@Shy: That's a solution for some cases, but you still get a round of superfluous events if <code>X</code> is changed from outside the controller (for instance, when using the command pattern for undo/redo), because then the value has changed, <code>W</code> is updated and fires an event. In order to prevent another (useless) update to the model, the event generated by the widget has to be swallowed.<br> In other cases, the model might be more complex and a simple check on what exactly has changed might not be feasible, e.g. a complex tree view.</p>
[ { "answer_id": 124740, "author": "shoosh", "author_id": 9611, "author_profile": "https://Stackoverflow.com/users/9611", "pm_score": 3, "selected": false, "text": "valueChanged()" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9567/" ]
124,742
<p>Is there a documented max to the length of the string data you can use in the send method of an <code>XMLHttpRequest</code> for the major browser implementations?</p> <p>I am running into an issue with a JavaScript <code>XMLHttpRequest</code> Post failing in FireFox 3 when the data is over approx 3k. I was assuming the Post would behave the same as a conventional Form Post.</p> <p>The W3C docs mention the data param of the send method is a DOMString but I am not sure how the major browsers implement that.</p> <p>Here is a simplified version of my JavaScript, if bigText is over about 3k it fails, otherwise it works...</p> <pre><code>var xhReq = createXMLHttpRequest(); function createXMLHttpRequest() { try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {} try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} try { return new XMLHttpRequest(); } catch(e) {} alert("XMLHttpRequest not supported"); return null; } function mySubmit(id, bigText) { var url = "SubmitPost.cfm"; var params = "id=" + id + "&amp;bigtext=" + encodeURI(bigText); xhReq.open("POST", url, true); //Send the header information along with the request xhReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhReq.setRequestHeader("Content-length", params.length); xhReq.setRequestHeader("Connection", "close"); xhReq.onreadystatechange = onPostSubmit; xhReq.send(params); } function onPostSubmit() { if (xhReq.readyState==4 || xhReq.readyState=="complete") { if (xhReq.status != 200) { alert('BadStatus'); return; } } } </code></pre>
[ { "answer_id": 54392713, "author": "Yones", "author_id": 10899806, "author_profile": "https://Stackoverflow.com/users/10899806", "pm_score": 0, "selected": false, "text": "vim /etc/nginx/nginx.conf\n /usr/sbin/nginx -t\n/usr/sbin/nginx -s reload\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7121/" ]
124,764
<p>I have seen this link: <a href="http://www.developer.com/lang/jscript/article.php/3592016" rel="noreferrer">Implementing Mutual Exclusion in JavaScript</a>. On the other hand, I have read that there are no threads in javascript, but what exactly does that mean? </p> <p>When events occur, where in the code can they interrupt?</p> <p>And if there are no threads in JS, do I need to use mutexes in JS or not?</p> <p>Specifically, I am wondering about the effects of using functions called by <code>setTimeout()</code> and <code>XmlHttpRequest</code>'s <code>onreadystatechange</code> on globally accessible variables. </p>
[ { "answer_id": 124832, "author": "William", "author_id": 9193, "author_profile": "https://Stackoverflow.com/users/9193", "pm_score": 8, "selected": true, "text": "setTimeout()" }, { "answer_id": 6760039, "author": "alzclarke", "author_id": 662049, "author_profile": "https://Stackoverflow.com/users/662049", "pm_score": 3, "selected": false, "text": "var save_lock = false;\n$('#save_button').click(function(){\n if(!save_lock){\n //lock\n save_lock=true;\n $.ajax({\n success:function()\n //unlock\n save_lock = false; \n }\n });\n }\n}\n" }, { "answer_id": 48691541, "author": "decates", "author_id": 792525, "author_profile": "https://Stackoverflow.com/users/792525", "pm_score": 3, "selected": false, "text": "function appendToList(item) {\n var list = localStorage[\"myKey\"];\n if (list) {\n list += \",\" + item;\n }\n else {\n list = item;\n }\n localStorage[\"myKey\"] = list;\n}\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3751/" ]
124,841
<p>I have written the following simple test in trying to learn Castle Windsor's Fluent Interface:</p> <pre><code>using NUnit.Framework; using Castle.Windsor; using System.Collections; using Castle.MicroKernel.Registration; namespace WindsorSample { public class MyComponent : IMyComponent { public MyComponent(int start_at) { this.Value = start_at; } public int Value { get; private set; } } public interface IMyComponent { int Value { get; } } [TestFixture] public class ConcreteImplFixture { [Test] public void ResolvingConcreteImplShouldInitialiseValue() { IWindsorContainer container = new WindsorContainer(); container.Register(Component.For&lt;IMyComponent&gt;().ImplementedBy&lt;MyComponent&gt;().Parameters(Parameter.ForKey("start_at").Eq("1"))); IMyComponent resolvedComp = container.Resolve&lt;IMyComponent&gt;(); Assert.AreEqual(resolvedComp.Value, 1); } } } </code></pre> <p>When I execute the test through TestDriven.NET I get the following error:</p> <pre><code>System.TypeLoadException : Could not load type 'Castle.MicroKernel.Registration.IRegistration' from assembly 'Castle.MicroKernel, Version=1.0.3.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc'. at WindsorSample.ConcreteImplFixture.ResolvingConcreteImplShouldInitialiseValue() </code></pre> <p>When I execute the test through the NUnit GUI I get:</p> <pre><code>WindsorSample.ConcreteImplFixture.ResolvingConcreteImplShouldInitialiseValue: System.IO.FileNotFoundException : Could not load file or assembly 'Castle.Windsor, Version=1.0.3.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc' or one of its dependencies. The system cannot find the file specified. </code></pre> <p>If I open the Assembly that I am referencing in Reflector I can see its information is:</p> <pre><code>Castle.MicroKernel, Version=1.0.3.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc </code></pre> <p>and that it definitely contains <strong>Castle.MicroKernel.Registration.IRegistration</strong></p> <p>What could be going on? </p> <p>I should mention that the binaries are taken from the <a href="http://builds.castleproject.org/cruise/DownloadBuild.castle?number=956" rel="noreferrer">latest build of Castle</a> though I have never worked with nant so I didn't bother re-compiling from source and just took the files in the bin directory. I should also point out that my project compiles with no problem.</p>
[ { "answer_id": 2531775, "author": "Brian Moeskau", "author_id": 108348, "author_profile": "https://Stackoverflow.com/users/108348", "pm_score": 4, "selected": false, "text": "HttpHandler web.config web.config" }, { "answer_id": 27803235, "author": "smirkingman", "author_id": 338101, "author_profile": "https://Stackoverflow.com/users/338101", "pm_score": 2, "selected": false, "text": "C:\\Users\\[yourname]\\AppData\\Local\\Microsoft\\VisualStudio\\10.0\\ProjectAssemblies" }, { "answer_id": 28864984, "author": "CJSewell", "author_id": 2461632, "author_profile": "https://Stackoverflow.com/users/2461632", "pm_score": 3, "selected": false, "text": "Could not load type 'Namspace.OldClassName' from assembly 'Assembly name...'. Temporary ASP.NET Files Temporary ASP.NET Files %systemroot%\\Microsoft.NET\\Framework64\\{.netversion}\\Temporary ASP.NET Files\\ %systemroot%\\Microsoft.NET\\Framework\\{.netversion}\\Temporary ASP.NET Files\\ %temp%\\Temporary ASP.NET Files" }, { "answer_id": 35480489, "author": "gaurav", "author_id": 5945615, "author_profile": "https://Stackoverflow.com/users/5945615", "pm_score": 2, "selected": false, "text": "Start -> programs -> Microsoft Visual studio 2010 -> Visual Studio Tools -> Visual Studio Command Prompt (2010) gacutil /u myDLL\n\ngacutil /i \"C:\\Program Files\\Custom\\mydllname.dll\"\n" }, { "answer_id": 52116544, "author": "JBartlau", "author_id": 2854011, "author_profile": "https://Stackoverflow.com/users/2854011", "pm_score": 2, "selected": false, "text": "using System.Reflection\nstatic Program()\n{\n AppDomain.CurrentDomain.AssemblyResolve += (sender, e) => {\n AssemblyName requestedName = new AssemblyName(e.Name);\n\n if (requestedName.Name == \"<AssemblyName>\")\n {\n // Load assembly from startup path\n return Assembly.LoadFile($\"{Application.StartupPath}\\\\<AssemblyName>.dll\");\n }\n else\n {\n return null;\n }\n };\n}\n" }, { "answer_id": 65641138, "author": "lifestyle", "author_id": 5353338, "author_profile": "https://Stackoverflow.com/users/5353338", "pm_score": 0, "selected": false, "text": "System.TypeLoadException struct Nullable<T> System.TypeLoadException: 'Could not load type 'SomeInfo' from assembly ... ' public struct SomeInfo\n{\n public SomeInfo? Parent { get; } \n \n public string info { get; }\n}\n struct class web.config" }, { "answer_id": 68492319, "author": "Serj Sagan", "author_id": 550975, "author_profile": "https://Stackoverflow.com/users/550975", "pm_score": 0, "selected": false, "text": "Blazor .NET 5 C# MVC Blazor Blazor AspNetCore.Mvc Blazor MVC View <component type=\"typeof(My.Client.Components.MyComponent)\" render-mode=\"WebAssemblyPrerendered\"\n param-OpenYearMonth=\"Model.OpenYearMonth?.ToDTO()\" />\n <component type=\"typeof(My.Client.Components.MyComponent)\" render-mode=\"WebAssemblyPrerendered\"\n param-Whatever=\"new List<My.DTO.Models.Whatever>()\"\n param-OpenYearMonth=\"Model.OpenYearMonth?.ToDTO()\" />\n MVC Blazor Task.Delay View Model.OpenYearMonth?.ToDTO()" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
124,844
<p>I am asking this out of a curiosity. Basically my question is when you have a database which needs a row entry to have things which act like flags, what is the best practice? A good example of this would be the badges on stack overflow, or the operating system field in bugzilla. Any subset of the flags may be set for a given entry.</p> <p>Usually, I do c and c++ work, so my gut reaction is to use an unsigned integer field as a set of bits which can be flipped... But i know that isn't a good solution for several reasons. The most obvious of which is scale-ability, there will be a hard upper limit on how many flags I can have.</p> <p>I can also think of a couple of other solutions which scale better but would have performance issues because they would require multiple selects to get all the information.</p> <p>So, what is the "right" way to do this?</p>
[ { "answer_id": 124872, "author": "Jeremiah Peschka", "author_id": 11780, "author_profile": "https://Stackoverflow.com/users/11780", "pm_score": 5, "selected": false, "text": "\nCREATE TABLE Users (\n UserId INT IDENTITY(1, 1) PRIMARY KEY,\n FirstName VARCHAR(50),\n LastName VARCHAR(50),\n EmailAddress VARCHAR(255)\n);\n\nCREATE TABLE Badges (\n BadgeId INT IDENTITY(1, 1) PRIMARY KEY,\n [Name] VARCHAR(50),\n [Description] VARCHAR(255)\n);\n\nCREATE TABLE UserBadges (\n UserId INT REFERENCES Users(UserId),\n BadgeId INT REFERENCES Badges(BadgeId)\n);\n" }, { "answer_id": 128723, "author": "vog", "author_id": 19163, "author_profile": "https://Stackoverflow.com/users/19163", "pm_score": 2, "selected": false, "text": "BOOLEAN CREATE TABLE ... (\n warnings INTEGER,\n errors INTEGER,\n ...\n)\n CREATE TABLE ... (\n warning_foo BOOLEAN,\n warning_bar BOOLEAN,\n warning_...\n error_foo BOOLEAN,\n error_bar BOOLEAN,\n error_... BOOLEAN,\n ...\n)\n" }, { "answer_id": 131627, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 2, "selected": false, "text": "SELECT COUNT(1), SUM(ActiveFlag)\nFROM myusers;\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13430/" ]
124,854
<p>I have an <code>&lt;img&gt;</code> in an HTML document that I would like to highlight as though the user had highlighted it using the mouse. Is there a way to do that using JavaScript?</p> <p>I only need it to work in Mozilla, but any and all information is welcome.</p> <p><em>EDIT: The reason I want to select the image is actually not so that it appears highlighted, but so that I can then copy the selected image to the clipboard using XPCOM. So the img actually has to be selected for this to work.</em></p>
[ { "answer_id": 124867, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": -1, "selected": false, "text": "<html>\n<body>\n<script language=\"javascript\">\nfunction swap(name) {\n document.getElementById(\"image\").src = name;\n}\n</script>\n<img id=\"image\" src=\"test1.png\"\n onmouseover=\"javascript:swap('test0.png');\"\n onmouseout=\"javascript:swap('test1.png');\">\n</body>\n</html>\n" }, { "answer_id": 124893, "author": "oglester", "author_id": 2017, "author_profile": "https://Stackoverflow.com/users/2017", "pm_score": -1, "selected": false, "text": "<script type=\"text/javascript\" language=\"javascript\">\nfunction highLight()\n{\n var img = document.getElementById('myImage');\n img.style.border = \"inset 2px black\";\n}\n</script>\n<img src=\"whatever.gif\" id=\"myImage\" onclick=\"hightLight()\" />\n" }, { "answer_id": 124929, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 5, "selected": true, "text": "var s = window.getSelection()\nvar r = document.createRange();\nr.selectNode(document.images[0]);\ns.addRange(r)\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7441/" ]
124,856
<p>I'd like to ensure my RAII class is always allocated on the stack.</p> <p>How do I prevent a class from being allocated via the 'new' operator?</p>
[ { "answer_id": 124857, "author": "Kevin", "author_id": 6386, "author_profile": "https://Stackoverflow.com/users/6386", "pm_score": 6, "selected": false, "text": "class X\n{\n private: \n // Prevent heap allocation\n void * operator new (size_t);\n void * operator new[] (size_t);\n void operator delete (void *);\n void operator delete[] (void*);\n\n // ...\n // The rest of the implementation for X\n // ...\n}; \n class X\n{\n// public, protected, private ... does not matter\n static void *operator new (size_t) = delete;\n static void *operator new[] (size_t) = delete;\n static void operator delete (void*) = delete;\n static void operator delete[](void*) = delete;\n};\n" }, { "answer_id": 125076, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 3, "selected": false, "text": "unique_ptr unique_ptr<lock> l;\nif(needs_lock)\n{\n l.reset(new lock(mtx));\n}\nrender();\n" }, { "answer_id": 125601, "author": "Kevin", "author_id": 6386, "author_profile": "https://Stackoverflow.com/users/6386", "pm_score": 2, "selected": false, "text": "class optional_lock\n{\n mutex& m;\n bool dolock;\n\npublic:\n optional_lock(mutex& m_, bool dolock_)\n : m(m_)\n , dolock(dolock_)\n {\n if (dolock) m.lock();\n }\n ~optional_lock()\n {\n if (dolock) m.unlock();\n }\n};\n optional_lock l(mtx, needs_lock);\nrender(); \n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6386/" ]
124,865
<p>At the office we are currently writing an application that will generate XML files against a schema that we were given. We have the schema in an .XSD file.</p> <p>Are there tool or libraries that we can use for automated testing to check that the generated XML matches the schema?</p> <p>We would prefer free tools that are appropriate for commercial use although we won't be bundling the schema checker so it only needs to be usable by devs during development.</p> <p>Our development language is C++ if that makes any difference, although I don't think it should as we could generate the xml file and then do validation by calling a separate program in the test.</p>
[ { "answer_id": 124947, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 5, "selected": false, "text": "xmlstarlet val --xsd your_schema.xsd your_file.xml\n" }, { "answer_id": 129401, "author": "Adrian Mouat", "author_id": 4332, "author_profile": "https://Stackoverflow.com/users/4332", "pm_score": 9, "selected": true, "text": "xmllint --noout --schema XSD_FILE XML_FILE\n" }, { "answer_id": 10708237, "author": "Andrew Stern", "author_id": 425208, "author_profile": "https://Stackoverflow.com/users/425208", "pm_score": 0, "selected": false, "text": "# Function:\n# verifyschemas - Will validate all xml files in a configuration directory against the schemas in the passed in directory\n# Parameters:\n# The directory where the schema *.xsd files are located. Must be using dos pathing like: VerifySchemas \"c:\\\\XMLSchemas\\\\\"\n# Requirements:\n# Must be in the directory where the configuration files are located\n#\nverifyschemas()\n{\n for FILENAME in $(find . -name '*.xml' -print0 | xargs -0)\n do\n local SchemaFile=$1$(getconfignamefromxml $FILENAME).xsd\n altovaxml /validate $FILENAME /schema $SchemaFile > ~/temp.txt 2> /dev/null\n if [ $? -ne 0 ]; then\n printf \"Failed to verify: \"\n cat ~/temp.txt | tail -1 | tr -d '\\r'\n printf \" - $FILENAME with $SchemaFile\\n\"\n fi\n done\n}\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5113/" ]
124,871
<p>I'm a long-time Windows developer, having cut my teeth on win32 and early COM. I've been working with .NET since 2001, so I'm pretty fluent in C# and the CLR. I'd never heard of Castle Windsor until I started participating in Stack Overflow. I've read the Castle Windsor "Getting Started" guide, but it's not clicking.</p> <p>Teach this old dog new tricks, and tell me why I should be integrating Castle Windsor into my enterprise apps.</p>
[ { "answer_id": 124898, "author": "Matt Hinze", "author_id": 2676, "author_profile": "https://Stackoverflow.com/users/2676", "pm_score": 10, "selected": true, "text": "new EmailSender().Send(emailMessage); new new WorkflowStepper(emailSender).Step() new WorkflowStepper(emailSender, alertRegistry, databaseConnection).Step() EmailSender WorkflowStepper AlertRegistry WorkflowStepper stepper = Container.Get<WorkflowStepper>(); WorkflowStepper new" }, { "answer_id": 42655294, "author": "Rakesh Burbure", "author_id": 1997983, "author_profile": "https://Stackoverflow.com/users/1997983", "pm_score": 2, "selected": false, "text": "Dependency Injection container." } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1181217/" ]
124,880
<p>Is it possible to prevent stack allocation of an object and only allow it to be instiated with 'new' on the heap?</p>
[ { "answer_id": 124903, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 4, "selected": false, "text": "private public" }, { "answer_id": 124904, "author": "Dominik Grabiec", "author_id": 3719, "author_profile": "https://Stackoverflow.com/users/3719", "pm_score": 7, "selected": true, "text": "class Foo\n{\npublic:\n ~Foo();\n static Foo* createFoo()\n {\n return new Foo();\n }\nprivate:\n Foo();\n Foo(const Foo&);\n Foo& operator=(const Foo&);\n};\n" }, { "answer_id": 124914, "author": "user18476", "author_id": 18476, "author_profile": "https://Stackoverflow.com/users/18476", "pm_score": -1, "selected": false, "text": "// Header file\n\nclass IAbstract\n{\n virtual void AbstractMethod() = 0;\n\npublic:\n virtual ~IAbstract();\n};\n\nIAbstract* CreateSubClassA();\nIAbstract* CreateSubClassB();\n\n// Source file\n\nclass SubClassA : public IAbstract\n{\n void AbstractMethod() {}\n};\n\nclass SubClassB : public IAbstract\n{\n void AbstractMethod() {}\n};\n\nIAbstract* CreateSubClassA()\n{\n return new SubClassA;\n}\n\nIAbstract* CreateSubClassB()\n{\n return new SubClassB;\n}\n" }, { "answer_id": 12697481, "author": "NebulaFox", "author_id": 398640, "author_profile": "https://Stackoverflow.com/users/398640", "pm_score": 5, "selected": false, "text": "class Foo\n{\n public:\n ~Foo();\n static Foo* createFoo()\n {\n return new Foo();\n }\n\n Foo(const Foo &) = delete; // if needed, put as private\n Foo & operator=(const Foo &) = delete; // if needed, put as private\n Foo(Foo &&) = delete; // if needed, put as private\n Foo & operator=(Foo &&) = delete; // if needed, put as private\n\n private:\n Foo();\n};\n" }, { "answer_id": 20086483, "author": "spiderlama", "author_id": 341725, "author_profile": "https://Stackoverflow.com/users/341725", "pm_score": 3, "selected": false, "text": "thread_local class NoStackBase {\n static thread_local bool _heap;\nprotected:\n NoStackBase() {\n bool _stack = _heap;\n _heap = false;\n if (_stack)\n throw std::logic_error(\"heap allocations only\");\n }\npublic:\n void* operator new(size_t size) throw (std::bad_alloc) { \n _heap = true;\n return ::operator new(size);\n }\n void* operator new(size_t size, const std::nothrow_t& nothrow_value) throw () {\n _heap = true;\n return ::operator new(size, nothrow_value);\n }\n void* operator new(size_t size, void* ptr) throw () {\n _heap = true;\n return ::operator new(size, ptr);\n }\n void* operator new[](size_t size) throw (std::bad_alloc) {\n _heap = true;\n return ::operator new[](size);\n }\n void* operator new[](size_t size, const std::nothrow_t& nothrow_value) throw () {\n _heap = true;\n return ::operator new[](size, nothrow_value);\n }\n void* operator new[](size_t size, void* ptr) throw () {\n _heap = true;\n return ::operator new[](size, ptr);\n }\n};\n\nbool thread_local NoStackBase::_heap = false;\n" }, { "answer_id": 51972019, "author": "cmeerw", "author_id": 76919, "author_profile": "https://Stackoverflow.com/users/76919", "pm_score": 2, "selected": false, "text": "#include <new>\n\nclass C\n{\nprivate:\n ~C() = default;\npublic:\n void operator delete(C *c, std::destroying_delete_t)\n {\n c->~C();\n ::operator delete(c);\n }\n};\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
124,886
<p>I need to change the functionality of an application based on the executable name. Nothing huge, just changing strings that are displayed and some internal identifiers. The application is written in a mixture of native and .Net C++-CLI code. </p> <p>Two ways that I have looked at are to parse the GetCommandLine() function in Win32 and stuffing around with the AppDomain and other things in .Net. However using GetCommandLine won't always work as when run from the debugger the command line is empty. And the .Net AppDomain stuff seems to require a lot of stuffing around.</p> <p>So what is the nicest/simplest/most efficient way of determining the executable name in C++/CLI? (I'm kind of hoping that I've just missed something simple that is available in .Net.)</p> <p>Edit: One thing that I should mention is that this is a Windows GUI application using C++/CLI, therefore there's no access to the traditional C style main function, it uses the Windows WinMain() function.</p>
[ { "answer_id": 124901, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 6, "selected": true, "text": "argv[0] GetCommandLine() GetModuleFileName()" }, { "answer_id": 124908, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "argv main int main(int argc, char* argv[])\n{\n printf(\"%s\\n\", argv[0]); //argv[0] will contain the name of the app.\n return 0;\n}\n" }, { "answer_id": 124937, "author": "Brian ONeil", "author_id": 21371, "author_profile": "https://Stackoverflow.com/users/21371", "pm_score": 2, "selected": false, "text": "Assembly.GetEntryAssembly().FullName\n Assembly.GetEntryAssembly().CodeBase\n" }, { "answer_id": 125079, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 4, "selected": false, "text": "TCHAR exepath[MAX_PATH+1];\n\nif(0 == GetModuleFileName(0, exepath, MAX_PATH+1))\n MessageBox(_T(\"Error!\"));\n\nMessageBox(exepath, _T(\"My executable name\"));\n" }, { "answer_id": 52445809, "author": "ingconti", "author_id": 927333, "author_profile": "https://Stackoverflow.com/users/927333", "pm_score": 0, "selected": false, "text": "TCHAR szFileName[MAX_PATH + 1];\nGetModuleFileName(NULL, szFileName, MAX_PATH + 1);\nauto exe = CString(szFileName);\n" }, { "answer_id": 62212668, "author": "Serge Rogatch", "author_id": 1915854, "author_profile": "https://Stackoverflow.com/users/1915854", "pm_score": 0, "selected": false, "text": "_pgmptr" }, { "answer_id": 72398895, "author": "Jamie", "author_id": 645431, "author_profile": "https://Stackoverflow.com/users/645431", "pm_score": 0, "selected": false, "text": "_pgmptr _get_pgmptr() char *exe;\n_get_pgmptr(&exe);\nstd::cout << \"This executable is [\" << exe << \"].\" << std::endl;\n wchar_t* wexe;\n_get_wpgmptr(&wexe);\nstd::wcout << L\"This executable is [\" << wexe << L\"].\" << std::endl;\n #define _CRT_SECURE_NO_WARNINGS 1\n#include <iostream>\n\nint main(int argc, char** argv)\n{\n std::cout << \"This executable is [\" << _pgmptr << \"].\" << std::endl;\n}\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3719/" ]
124,932
<p>I have a bit of code that basically reads an XML document using the XMLDocument.Load(uri) method which works fine, but doesn't work so well if the call is made through a proxy.</p> <p>I was wondering if anyone knew of a way to make this call (or achieve the same effect) through a proxy?</p>
[ { "answer_id": 125286, "author": "lomaxx", "author_id": 493, "author_profile": "https://Stackoverflow.com/users/493", "pm_score": 4, "selected": false, "text": "WebProxy wp = new WebProxy(Settings.Default.ProxyAddress);\nwp.Credentials = new NetworkCredential(Settings.Default.ProxyUsername, Settings.Default.ProxyPassword);\nWebClient wc = new WebClient();\nwc.Proxy = wp;\n\nMemoryStream ms = new MemoryStream(wc.DownloadData(url));\nXmlTextReader rdr = new XmlTextReader(ms);\nreturn XDocument.Load(rdr); \n" }, { "answer_id": 654213, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "MemoryStream ms = new MemoryStream(wc.DownloadData(url));\nXmlTextReader rdr = new XmlTextReader(url);\n MemoryStream ms = new MemoryStream(wc.DownloadData(url));\nXmlTextReader rdr = new XmlTextReader(ms);\n" }, { "answer_id": 63148438, "author": "Joshua Knight", "author_id": 14014244, "author_profile": "https://Stackoverflow.com/users/14014244", "pm_score": 0, "selected": false, "text": "IWebProxy wp = WebRequest.GetSystemWebProxy(); \nwp.Credentials = WebRequest.GetSystemWebProxy().Credentials; \nWebClient wc = new WebClient();\nwc.Proxy = wp;\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/493/" ]
124,935
<p>I'm using scriptaculous's Ajax.Autocompleter for a search with different filters. </p> <p><a href="http://github.com/madrobby/scriptaculous/wikis/ajax-autocompleter" rel="nofollow noreferrer">http://github.com/madrobby/scriptaculous/wikis/ajax-autocompleter</a></p> <p>The filters are requiring me to pass data into the autocompleter dynamically, which I've successfully learned to do from the following link. </p> <p><a href="http://www.simpltry.com/2007/01/30/ajaxautocompleter-dynamic-parameters/" rel="nofollow noreferrer">http://www.simpltry.com/2007/01/30/ajaxautocompleter-dynamic-parameters/</a></p> <p>Now, I have multiple filters and one search box. How do I get the autocompleter to make the request <em>without</em> typing into the input, but by clicking a new filter?</p> <p>Here's a use case to clarify. The page loads, there are multiple filters (just links with onclicks), and one input field with the autocompleter attached. I type a query and the autocompleter request is performed. Then, I click on a different filter, and I'd like another request to be performed with the same query, but different filter. </p> <p>Or more succinctly, how do I make the autocompleter perform the request <em>when I want</em>, instead of depending on typing to trigger it?</p>
[ { "answer_id": 125027, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 1, "selected": false, "text": "onObserverEvent() var autoCompleter = new Ajax.Autocompleter(/* exercise for the reader */);\n// Magic happens\nautoCompleter.onObserverEvent();\n" }, { "answer_id": 129644, "author": "Steve", "author_id": 21456, "author_profile": "https://Stackoverflow.com/users/21456", "pm_score": 2, "selected": false, "text": " function fakeKeyPress(input_id) {\n var input = $(input_id);\n if(input.fireEvent) {\n // ie stuff\n var evt = document.createEventObject();\n evt.keyCode = 67;\n $(input_id).fireEvent(\"onKeyDown\", evt);\n } else { \n // firefox stuff\n var evt = document.createEvent(\"KeyboardEvent\");\n evt.initKeyEvent('keydown', true, true, null, false, false, false, false, 27, 0);\n var canceled = !$(input_id).dispatchEvent(evt);\n }\n }\n" }, { "answer_id": 1689650, "author": "Philippe Rathé", "author_id": 159478, "author_profile": "https://Stackoverflow.com/users/159478", "pm_score": 1, "selected": false, "text": "var autoCompleter = new Ajax.Autocompleter(/* exercise for the reader */);\n// Magic happens\nautoCompleter.activate();\n" }, { "answer_id": 2211062, "author": "Dale C. Anderson", "author_id": 267455, "author_profile": "https://Stackoverflow.com/users/267455", "pm_score": 2, "selected": false, "text": "<script type=\"text/javascript\">\n /*<![CDATA[*/\n\n var autocomp1 = new Ajax.Autocompleter(\"search\", \"AjaxResultsListPlaceholder\", \"ajaxServerSideSearchHandler.php\", {\n frequency: 1,\n minChars: 10,\n indicator: \"AjaxWorkingPleaseWaitPlaceholder\",\n } );\n\n\n /*]]>*/\n</script>\n\n<form id=\"theform\">\n <input type=\"text\" id=\"search\" name=\"search\" value=\"\" />\n <input type=\"button\" id=\"btn_search\" name=\"btn_search\" value=\"Search\" onclick=\"autocomp1.activate();\" />\n <div id=\"AjaxWorkingPleaseWaitPlaceholder\" style=\"display: none; border: 1px solid #ffaaaa;\">\n </div>\n <div id=\"AjaxResultsListPlaceholder\" style=\"display: none;; border: 1px solid #aaffaa;\">\n </div>\n\n</form>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21456/" ]
124,946
<p>My question is based off of inheriting a great deal of legacy code that I can't do very much about. Basically, I have a device that will produce a block of data. A library which will call the device to create that block of data, for some reason I don't entirely understand and cannot change even if I wanted to, writes that block of data to disk.</p> <p>This write is not instantaneous, but can take up to 90 seconds. In that time, the user wants to get a partial view of the data that's being produced, so I want to have a consumer thread which reads the data that the other library is writing to disk.</p> <p>Before I even touch this legacy code, I want to mimic the problem using code I entirely control. I'm using C#, ostensibly because it provides a lot of the functionality I want.</p> <p>In the producer class, I have this code creating a random block of data:</p> <pre><code>FileStream theFS = new FileStream(this.ScannerRawFileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read); //note that I need to be able to read this elsewhere... BinaryWriter theBinaryWriter = new BinaryWriter(theFS); int y, x; for (y = 0; y &lt; imheight; y++){ ushort[] theData= new ushort[imwidth]; for(x = 0; x &lt; imwidth;x++){ theData[x] = (ushort)(2*y+4*x); } byte[] theNewArray = new byte[imwidth * 2]; Buffer.BlockCopy(theImage, 0, theNewArray, 0, imwidth * 2); theBinaryWriter.Write(theNewArray); Thread.Sleep(mScanThreadWait); //sleep for 50 milliseconds Progress = (float)(y-1 &gt;= 0 ? y-1 : 0) / (float)imheight; } theFS.Close(); </code></pre> <p>So far, so good. This code works. The current version (using FileStream and BinaryWriter) appears to be equivalent (though slower, because of the copy) to using File.Open with the same options and a BinaryFormatter on the ushort[] being written to disk.</p> <p>But then I add a consumer thread:</p> <pre><code>FileStream theFS; if (!File.Exists(theFileName)) { //do error handling return; } else { theFS = new FileStream(theFileName, FileMode.Open, FileAccess.Read, FileShare.Read); //very relaxed file opening } BinaryReader theReader = new BinaryReader(theFS); //gotta do this copying in order to handle byte array swaps //frustrating, but true. byte[] theNewArray = theReader.ReadBytes( (int)(imheight * imwidth * inBase.Progress) * 2); ushort[] theData = new ushort[((int)(theNewArray.Length/2))]; Buffer.BlockCopy(theNewArray, 0, theData, 0, theNewArray.Length); </code></pre> <p>Now, it's possible that the declaration of theNewArray is broken, and will cause some kind of read overflow. However, this code never gets that far, because it always always always breaks on trying to open the new FileStream with a System.IO.IOException that states that another process has opened the file.</p> <p>I'm setting the FileAccess and FileShare enumerations as stated in the FileStream documentation on MSDN, but it appears that I just can't do what I want to do (ie, write in one thread, read in another). I realize that this application is a bit unorthodox, but when I get the actual device involved, I'm going to have to do the same thing, but using MFC.</p> <p>In any event, What am I forgetting? Is what I'm wanting to do possible, since it's specified as possible in the documentation? </p> <p>Thanks! mmr</p>
[ { "answer_id": 125059, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "FileStream theFS = new FileStream(this.ScannerRawFileName, \n FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);\n//note that I need to be able to read this elsewhere...\nBinaryWriter theBinaryWriter = new BinaryWriter(theFS);\nint y, x;\nfor (y = 0; y < imheight; y++){\n ushort[] theData= new ushort[imwidth];\n for(x = 0; x < imwidth;x++){\n theData[x] = (ushort)(2*y+4*x);\n }\n byte[] theNewArray = new byte[imwidth * 2];\n Buffer.BlockCopy(theImage, 0, theNewArray, 0, imwidth * 2);\n theBinaryWriter.Write(theNewArray);\n Thread.Sleep(mScanThreadWait); //sleep for 50 milliseconds\n Progress = (float)(y-1 >= 0 ? y-1 : 0) / (float)imheight;\n theBinaryWriter.Flush();\n}\ntheFS.Close();\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
124,958
<p>I'm trying to display an array of files in order of date (last modified).</p> <p>I have done this buy looping through the array and sorting it into another array, but is there an easier (more efficient) way to do this?</p>
[ { "answer_id": 125047, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 8, "selected": true, "text": "create_function() <?php\n\n$myarray = glob(\"*.*\");\nusort($myarray, create_function('$a,$b', 'return filemtime($a) - filemtime($b);'));\n\n?>\n" }, { "answer_id": 3298787, "author": "Alf Eaton", "author_id": 145899, "author_profile": "https://Stackoverflow.com/users/145899", "pm_score": 6, "selected": false, "text": "<?php\n$items = glob('*', GLOB_NOSORT);\narray_multisort(array_map('filemtime', $items), SORT_NUMERIC, SORT_DESC, $items);\n" }, { "answer_id": 35925596, "author": "fusion3k", "author_id": 3294262, "author_profile": "https://Stackoverflow.com/users/3294262", "pm_score": 5, "selected": false, "text": "$myarray = glob(\"*.*\");\n\nusort( $myarray, function( $a, $b ) { return filemtime($a) - filemtime($b); } );\n" }, { "answer_id": 54444988, "author": "Sebastian", "author_id": 1212623, "author_profile": "https://Stackoverflow.com/users/1212623", "pm_score": 2, "selected": false, "text": "usort() filemtime() 1.39*n*lg(n) filemtime() exec ( stripos ( PHP_OS, 'WIN' ) === 0 ? 'dir /B /O-D *.*' : 'ls -td1 *.*' , $myarray );\n" }, { "answer_id": 60476123, "author": "Dharman", "author_id": 1839439, "author_profile": "https://Stackoverflow.com/users/1839439", "pm_score": 3, "selected": false, "text": "usort($myarray, fn($a, $b) => filemtime($a) - filemtime($b));\n usort($myarray, fn($a, $b) => filemtime($a) <=> filemtime($b));\n usort($myarray, fn($a, $b) => -(filemtime($a) - filemtime($b)));\n// or \nusort($myarray, fn($a, $b) => -(filemtime($a) <=> filemtime($b)));\n filemtime()" }, { "answer_id": 62802499, "author": "Stefano", "author_id": 3626361, "author_profile": "https://Stackoverflow.com/users/3626361", "pm_score": 2, "selected": false, "text": "glob() exec() scandir() readdir() glob() \"mydir/*\" \"mydir/*.jpg\" glob() scandir() readdir() scandir() readdir() scandir() usort( $myarray, function( $a, $b ) { return filemtime($a) - filemtime($b); } ); usort($myarray, fn($a, $b) => filemtime($a) - filemtime($b)); <?php\nfunction files_attachment_list($id, $sort_by_date = false, $allowed_extensions = ['png', 'jpg', 'jpeg', 'gif', 'doc', 'docx', 'pdf', 'zip', 'rar', '7z'])\n{\n if (empty($id) or !is_dir(sprintf('files/%s/', $id))) {\n return false;\n }\n $out = [];\n foreach (new DirectoryIterator(sprintf('files/%s/', $id)) as $file) {\n if ($file->isFile() == false || !in_array($file->getExtension(), $allowed_extensions)) {\n continue;\n }\n\n $datetime = new DateTime();\n $datetime->setTimestamp($file->getMTime());\n $out[] = [\n 'title' => $file->getFilename(),\n 'size' => human_filesize($file->getSize()),\n 'modified' => $datetime->format('Y-m-d H:i:s'),\n 'extension' => $file->getExtension(),\n 'url' => $file->getPathname()\n ];\n }\n\n $sort_by_date && usort($out, function ($a, $b) {\n return $a['modified'] > $b['modified'];\n });\n\n return $out;\n}\n\nfunction human_filesize($bytes, $decimals = 2)\n{\n $sz = 'BKMGTP';\n $factor = floor((strlen($bytes) - 1) / 3);\n return sprintf(\"%.{$decimals}f\", $bytes / pow(1024, $factor)) . @$sz[$factor];\n}\n\n// returns a file info array from path like '/files/123/*.extensions'\n// extensions = 'png', 'jpg', 'jpeg', 'gif', 'doc', 'docx', 'pdf', 'zip', 'rar', '7z'\n// OS specific sorting\nprint_r( files_attachment_list(123) );\n\n// returns a file info array from the folder '/files/456/*.extensions'\n// extensions = 'txt', 'zip'\n// sorting by modified date (newest first)\nprint_r( files_attachment_list(456, true, ['txt','zip']) );\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/910/" ]
124,959
<p>Whats the available solutions for PHP to create word document in linux environment?</p>
[ { "answer_id": 125009, "author": "Sergey Kornilov", "author_id": 10969, "author_profile": "https://Stackoverflow.com/users/10969", "pm_score": 5, "selected": false, "text": "header(\"Content-type: application/vnd.ms-word\");\nheader(\"Content-Disposition: attachment; filename=document_name.doc\");\n\necho \"<html>\";\necho \"<meta http-equiv=\\\"Content-Type\\\" content=\\\"text/html; charset=Windows-1252\\\">\";\necho \"<body>\";\necho \"<b>Fake word document</b>\";\necho \"</body>\";\necho \"</html>\"\n .doc Content-Type" }, { "answer_id": 3323519, "author": "hoang", "author_id": 400809, "author_profile": "https://Stackoverflow.com/users/400809", "pm_score": 2, "selected": false, "text": "<?php\nfunction fWriteFile($sFileName,$sFileContent=\"No Data\",$ROOT)\n {\n $word = new COM(\"word.application\") or die(\"Unable to instantiate Word\");\n //bring it to front\n $word->Visible = 1;\n //open an empty document\n $word->Documents->Add();\n //do some weird stuff\n $word->Selection->TypeText($sFileContent);\n $word->Documents[1]->SaveAs($ROOT.\"/\".$sFileName.\".doc\");\n //closing word\n $word->Quit();\n //free the object\n $word = null;\n return $sFileName;\n }\n?>\n\n\n\n<?php\n$PATH_ROOT=dirname(__FILE__);\n$Return =\"<table>\";\n$Return .=\"<tr><td>Row[0]</td></tr>\";\n $Return .=\"<tr><td>Row[1]</td></tr>\";\n$sReturn .=\"</table>\";\nfWriteFile(\"test\",$Return,$PATH_ROOT);\n?> \n" }, { "answer_id": 4138895, "author": "Matiaan", "author_id": 502442, "author_profile": "https://Stackoverflow.com/users/502442", "pm_score": 3, "selected": false, "text": "function mailMerge($templateFile, $newFile, $row)\n{\n if (!copy($templateFile, $newFile)) // make a duplicate so we dont overwrite the template\n return false; // could not duplicate template\n $zip = new ZipArchive();\n if ($zip->open($newFile, ZIPARCHIVE::CHECKCONS) !== TRUE)\n return false; // probably not a docx file\n $file = substr($templateFile, -4) == '.odt' ? 'content.xml' : 'word/document.xml';\n $data = $zip->getFromName($file);\n foreach ($row as $key => $value)\n $data = str_replace($key, $value, $data);\n $zip->deleteName($file);\n $zip->addFromString($file, $data);\n $zip->close();\n return true;\n}\n $replacements = array('[Person Name]' => 'Mina', '[Person Last Name]' => 'Mooo');\n$newFile = tempnam_sfx(sys_get_temp_dir(), '.dat');\n$templateName = 'personinfo.docx';\nif (mailMerge($templateName, $newFile, $replacements))\n{\n header('Content-type: application/msword');\n header('Content-Disposition: attachment; filename=' . $templateName);\n header('Accept-Ranges: bytes');\n header('Content-Length: '. filesize($file));\n readfile($newFile);\n unlink($newFile);\n}\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
124,966
<p>I want something like an <a href="http://en.wikipedia.org/wiki/Map_%28C++%29" rel="nofollow noreferrer">std::map</a>, but I only want to see if the item exists or not, I don't actually need a key AND a value. What should I use?</p>
[ { "answer_id": 124994, "author": "David Dibben", "author_id": 5022, "author_profile": "https://Stackoverflow.com/users/5022", "pm_score": 3, "selected": false, "text": "std::map std::set std::set std::vector" }, { "answer_id": 125002, "author": "Cyber Oliveira", "author_id": 9793, "author_profile": "https://Stackoverflow.com/users/9793", "pm_score": 2, "selected": false, "text": "D:\\Temp>type vectorbool.cpp\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n vector<bool> vb(10);\n vb[5] = true;\n\n for (vector<bool>::const_iterator ci = vb.begin(); ci != vb.end(); ++ci) {\n cout << *ci << endl;\n }\n}\n\nD:\\Temp>cl /nologo /W4 /EHsc vectorbool.cpp\nvectorbool.cpp\n\nD:\\Temp>vectorbool.exe\n0\n0\n0\n0\n0\n1\n0\n0\n0\n0\n" }, { "answer_id": 125784, "author": "VarunGupta", "author_id": 6561, "author_profile": "https://Stackoverflow.com/users/6561", "pm_score": 1, "selected": false, "text": "if (mapObj.count(item) != 0)\n{\n // item exists\n}\n" }, { "answer_id": 127990, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 2, "selected": false, "text": "unordered_set" }, { "answer_id": 132539, "author": "Harald Scheirich", "author_id": 22080, "author_profile": "https://Stackoverflow.com/users/22080", "pm_score": 2, "selected": false, "text": "stl::set stl::bitset set set bitset int true bitset" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4946/" ]
124,975
<p>I'm looking for a free winforms component for an application I'm writing. I basicly need a textbox that contains line numbers in a side column. Being able to tabulate data within it would be a major plus too.</p> <p>Does anyone know of a premade component that could do this?</p>
[ { "answer_id": 125115, "author": "ine", "author_id": 4965, "author_profile": "https://Stackoverflow.com/users/4965", "pm_score": 4, "selected": true, "text": "Public Sub New()\n MyBase.New()\n\n 'This call is required by the Windows Form Designer.\n InitializeComponent()\n\n 'Add any initialization after the InitializeComponent() call\n SetStyle(ControlStyles.UserPaint, True)\n SetStyle(ControlStyles.AllPaintingInWmPaint, True)\n SetStyle(ControlStyles.DoubleBuffer, True)\n SetStyle(ControlStyles.ResizeRedraw, True)\nEnd Sub\n\nPrivate Sub RichTextBox1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RichTextBox1.SelectionChanged\n FindLine()\n Invalidate()\nEnd Sub\n\nPrivate Sub FindLine()\n Dim intChar As Integer\n\n intChar = RichTextBox1.GetCharIndexFromPosition(New Point(0, 0))\n intLine = RichTextBox1.GetLineFromCharIndex(intChar)\nEnd Sub\n\nPrivate Sub DrawLines(ByVal g As Graphics, ByVal intLine As Integer)\n Dim intCounter As Integer, intY As Integer\n\n g.Clear(Color.Black)\n\n intCounter = intLine + 1\n intY = 2\n Do\n g.DrawString(intCounter.ToString(), Font, Brushes.White, 3, intY)\n intCounter += 1\n\n intY += Font.Height + 1\n If intY > ClientRectangle.Height - 15 Then Exit Do\n Loop\nEnd Sub\n\nProtected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)\n DrawLines(e.Graphics, intLine)\nEnd Sub\n\nPrivate Sub RichTextBox1_VScroll(ByVal sender As Object, ByVal e As System.EventArgs) Handles RichTextBox1.VScroll\n FindLine()\n Invalidate()\nEnd Sub\n\nPrivate Sub RichTextBox1_UserScroll() Handles RichTextBox1.UserScroll\n FindLine()\n Invalidate()\nEnd Sub\n Public Class UserControl1\nInherits System.Windows.Forms.RichTextBox\n\nPublic Event UserScroll()\n\nProtected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)\n If m.Msg = &H115 Then\n RaiseEvent UserScroll()\n End If\n\n MyBase.WndProc(m)\nEnd Sub\nEnd Class\n" }, { "answer_id": 4961388, "author": "Phil Hayward", "author_id": 208174, "author_profile": "https://Stackoverflow.com/users/208174", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Drawing;\nusing System.Data;\nusing System.Text;\nusing System.Windows.Forms;\n\nnamespace NumberedTextBoxLib {\n public partial class NumberedTextBox : UserControl {\n private int lineIndex = 0;\n\n new public String Text {\n get {\n return editBox.Text;\n }\n set {\n editBox.Text = value;\n }\n }\n\n public NumberedTextBox() {\n InitializeComponent();\n SetStyle(ControlStyles.UserPaint, true);\n SetStyle(ControlStyles.AllPaintingInWmPaint, true);\n SetStyle(ControlStyles.OptimizedDoubleBuffer, true);\n SetStyle(ControlStyles.ResizeRedraw, true);\n editBox.SelectionChanged += new EventHandler(selectionChanged);\n editBox.VScroll += new EventHandler(OnVScroll);\n }\n\n private void selectionChanged(object sender, EventArgs args) {\n FindLine();\n Invalidate();\n }\n\n private void FindLine() {\n int charIndex = editBox.GetCharIndexFromPosition(new Point(0, 0));\n lineIndex = editBox.GetLineFromCharIndex(charIndex);\n }\n\n private void DrawLines(Graphics g) {\n int counter, y;\n g.Clear(BackColor);\n counter = lineIndex + 1;\n y = 2;\n int max = 0;\n while (y < ClientRectangle.Height - 15) {\n SizeF size = g.MeasureString(counter.ToString(), Font);\n g.DrawString(counter.ToString(), Font, new SolidBrush(ForeColor), new Point(3, y));\n counter++;\n y += (int)size.Height;\n if (max < size.Width) {\n max = (int) size.Width;\n }\n }\n max += 6;\n editBox.Location = new Point(max, 0);\n editBox.Size = new Size(ClientRectangle.Width - max, ClientRectangle.Height);\n }\n\n protected override void OnPaint(PaintEventArgs e) {\n DrawLines(e.Graphics);\n e.Graphics.TranslateTransform(50, 0);\n editBox.Invalidate();\n base.OnPaint(e);\n }\n\n ///Redraw the numbers when the editor is scrolled vertically\n private void OnVScroll(object sender, EventArgs e) {\n FindLine();\n Invalidate();\n }\n\n }\n}\n \nnamespace NumberedTextBoxLib {\n partial class NumberedTextBox {\n /// Required designer variable.\n private System.ComponentModel.IContainer components = null;\n\n /// Clean up any resources being used.\n protected override void Dispose(bool disposing) {\n if (disposing && (components != null)) {\n components.Dispose();\n }\n base.Dispose(disposing);\n }\n\n /// Required method for Designer support - do not modify \n /// the contents of this method with the code editor.\n private void InitializeComponent() {\n this.editBox = new System.Windows.Forms.RichTextBox();\n this.SuspendLayout();\n // \n // editBox\n // \n this.editBox.AcceptsTab = true;\n this.editBox.Anchor = ((System.Windows.Forms.AnchorStyles) ((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)\n | System.Windows.Forms.AnchorStyles.Left)\n | System.Windows.Forms.AnchorStyles.Right)));\n this.editBox.Location = new System.Drawing.Point(27, 3);\n this.editBox.Name = \"editBox\";\n this.editBox.Size = new System.Drawing.Size(122, 117);\n this.editBox.TabIndex = 0;\n this.editBox.Text = \"\";\n this.editBox.WordWrap = false;\n // \n // NumberedTextBox\n // \n this.Controls.Add(this.editBox);\n this.Name = \"NumberedTextBox\";\n this.Size = new System.Drawing.Size(152, 123);\n this.ResumeLayout(false);\n\n }\n\n private System.Windows.Forms.RichTextBox editBox;\n }\n}\n" }, { "answer_id": 17973520, "author": "EliSherer", "author_id": 678780, "author_profile": "https://Stackoverflow.com/users/678780", "pm_score": 1, "selected": false, "text": "public partial class NumberedTextBox : UserControl\n{\n private int _lines = 0;\n\n [Browsable(true), \n EditorAttribute(\"System.ComponentModel.Design.MultilineStringEditor, System.Design\",\"System.Drawing.Design.UITypeEditor\")]\n new public String Text\n {\n get\n {\n return editBox.Text;\n }\n set\n {\n editBox.Text = value;\n Invalidate();\n }\n }\n\n private Color _lineNumberColor = Color.LightSeaGreen;\n\n [Browsable(true), DefaultValue(typeof(Color), \"LightSeaGreen\")]\n public Color LineNumberColor {\n get{\n return _lineNumberColor;\n }\n set\n {\n _lineNumberColor = value;\n Invalidate();\n }\n }\n\n public NumberedTextBox()\n {\n InitializeComponent();\n\n SetStyle(ControlStyles.UserPaint, true);\n SetStyle(ControlStyles.AllPaintingInWmPaint, true);\n SetStyle(ControlStyles.OptimizedDoubleBuffer, true);\n SetStyle(ControlStyles.ResizeRedraw, true);\n editBox.SelectionChanged += new EventHandler(selectionChanged);\n editBox.VScroll += new EventHandler(OnVScroll);\n }\n\n private void selectionChanged(object sender, EventArgs args)\n {\n Invalidate();\n }\n\n private void DrawLines(Graphics g)\n {\n g.Clear(BackColor);\n int y = - editBox.ScrollPos.Y;\n for (var i = 1; i < _lines + 1; i++)\n {\n var size = g.MeasureString(i.ToString(), Font);\n g.DrawString(i.ToString(), Font, new SolidBrush(LineNumberColor), new Point(3, y));\n y += Font.Height + 2;\n }\n var max = (int)g.MeasureString((_lines + 1).ToString(), Font).Width + 6;\n editBox.Location = new Point(max, 0);\n editBox.Size = new Size(ClientRectangle.Width - max, ClientRectangle.Height);\n }\n\n protected override void OnPaint(PaintEventArgs e)\n {\n _lines = editBox.Lines.Count();\n DrawLines(e.Graphics);\n e.Graphics.TranslateTransform(50, 0);\n editBox.Invalidate();\n base.OnPaint(e);\n }\n\n private void OnVScroll(object sender, EventArgs e)\n {\n Invalidate();\n }\n\n public void Select(int start, int length)\n {\n editBox.Select(start, length);\n }\n\n public void ScrollToCaret()\n {\n editBox.ScrollToCaret();\n }\n\n private void editBox_TextChanged(object sender, EventArgs e)\n {\n Invalidate();\n }\n}\n\npublic class RichTextBoxEx : System.Windows.Forms.RichTextBox\n{\n private double _Yfactor = 1.0d;\n\n [DllImport(\"user32.dll\")]\n static extern IntPtr SendMessage(IntPtr hWnd, Int32 wMsg, Int32 wParam, ref Point lParam);\n\n private enum WindowsMessages\n {\n WM_USER = 0x400,\n EM_GETSCROLLPOS = WM_USER + 221,\n EM_SETSCROLLPOS = WM_USER + 222\n }\n\n public Point ScrollPos\n {\n get\n {\n var scrollPoint = new Point();\n SendMessage(this.Handle, (int)WindowsMessages.EM_GETSCROLLPOS, 0, ref scrollPoint);\n return scrollPoint;\n }\n set\n {\n var original = value;\n if (original.Y < 0)\n original.Y = 0;\n if (original.X < 0)\n original.X = 0;\n\n var factored = value;\n factored.Y = (int)((double)original.Y * _Yfactor);\n\n var result = value;\n\n SendMessage(this.Handle, (int)WindowsMessages.EM_SETSCROLLPOS, 0, ref factored);\n SendMessage(this.Handle, (int)WindowsMessages.EM_GETSCROLLPOS, 0, ref result);\n\n var loopcount = 0;\n var maxloop = 100;\n while (result.Y != original.Y)\n {\n // Adjust the input.\n if (result.Y > original.Y)\n factored.Y -= (result.Y - original.Y) / 2 - 1;\n else if (result.Y < original.Y)\n factored.Y += (original.Y - result.Y) / 2 + 1;\n\n // test the new input.\n SendMessage(this.Handle, (int)WindowsMessages.EM_SETSCROLLPOS, 0, ref factored);\n SendMessage(this.Handle, (int)WindowsMessages.EM_GETSCROLLPOS, 0, ref result);\n\n // save new factor, test for exit.\n loopcount++;\n if (loopcount >= maxloop || result.Y == original.Y)\n {\n _Yfactor = (double)factored.Y / (double)original.Y;\n break;\n }\n }\n }\n }\n}\n partial class NumberedTextBox\n{\n /// <summary> \n /// Required designer variable.\n /// </summary>\n private System.ComponentModel.IContainer components = null;\n\n /// <summary> \n /// Clean up any resources being used.\n /// </summary>\n /// <param name=\"disposing\">true if managed resources should be disposed; otherwise, false.</param>\n protected override void Dispose(bool disposing)\n {\n if (disposing && (components != null))\n {\n components.Dispose();\n }\n base.Dispose(disposing);\n }\n\n #region Component Designer generated code\n\n /// <summary> \n /// Required method for Designer support - do not modify \n /// the contents of this method with the code editor.\n /// </summary>\n private void InitializeComponent()\n {\n this.editBox = new WebTools.Controls.RichTextBoxEx();\n this.SuspendLayout();\n // \n // editBox\n // \n this.editBox.AcceptsTab = true;\n this.editBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) \n | System.Windows.Forms.AnchorStyles.Left) \n | System.Windows.Forms.AnchorStyles.Right)));\n this.editBox.BorderStyle = System.Windows.Forms.BorderStyle.None;\n this.editBox.Location = new System.Drawing.Point(27, 3);\n this.editBox.Name = \"editBox\";\n this.editBox.ScrollPos = new System.Drawing.Point(0, 0);\n this.editBox.Size = new System.Drawing.Size(120, 115);\n this.editBox.TabIndex = 0;\n this.editBox.Text = \"\";\n this.editBox.WordWrap = false;\n this.editBox.TextChanged += new System.EventHandler(this.editBox_TextChanged);\n // \n // NumberedTextBox\n // \n this.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;\n this.Controls.Add(this.editBox);\n this.Name = \"NumberedTextBox\";\n this.Size = new System.Drawing.Size(150, 121);\n this.ResumeLayout(false);\n\n }\n\n private RichTextBoxEx editBox;\n\n #endregion\n}\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/124975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
125,022
<p>I am trying to install PHP onto my development box (XP SP3 / IIS 5.1) I've got PHP 5.2.6 stable downloaded (the MSI installer package) and I am getting an error "Cannot find httpd.conf". After that the install seems to breeze by quickly (more quickly than I would have expected) and when I try to execute a simple PHP script from my localhost test directory that I created, I get a slew of missing DLL errors. I have seen posts out there which indicate that its possible and has been done. I dont see any bug reports for this MSI at PHP.NET support. Any ideas?</p>
[ { "answer_id": 125092, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 1, "selected": false, "text": "c:\\Program Files\\php php5ts.dll c:\\windows\\system32 php.ini.dist c:\\windows php.ini c:\\windows\\php.ini c:\\Program Files\\php\\extensions .php php5ts.dll" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14728/" ]
125,034
<p>In Python, I want to make <strong>selected</strong> instance attributes of a class be readonly to code outside of the class. I want there to be no way outside code can alter the attribute, except indirectly by invoking methods on the instance. I want the syntax to be concise. What is the best way? (I give my current best answer below...)</p>
[ { "answer_id": 125058, "author": "Kevin Little", "author_id": 14028, "author_profile": "https://Stackoverflow.com/users/14028", "pm_score": 2, "selected": false, "text": "class C(object):\n\n def __init__(self):\n\n self.fullaccess = 0\n self.__readonly = 22 # almost invisible to outside code...\n\n # define a publicly visible, read-only version of '__readonly':\n readonly = property(lambda self: self.__readonly)\n\n def inc_readonly( self ):\n self.__readonly += 1\n\nc=C()\n\n# prove regular attribute is RW...\nprint \"c.fullaccess = %s\" % c.fullaccess\nc.fullaccess = 1234\nprint \"c.fullaccess = %s\" % c.fullaccess\n\n# prove 'readonly' is a read-only attribute\nprint \"c.readonly = %s\" % c.readonly\ntry:\n c.readonly = 3\nexcept AttributeError:\n print \"Can't change c.readonly\"\nprint \"c.readonly = %s\" % c.readonly\n\n# change 'readonly' indirectly...\nc.inc_readonly()\nprint \"c.readonly = %s\" % c.readonly\n @readonly\n self.readonly = 22\n" }, { "answer_id": 125061, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": 4, "selected": true, "text": "@property >>> class a(object):\n... def __init__(self, x):\n... self.x = x\n... @property\n... def xval(self):\n... return self.x\n... \n>>> b = a(5)\n>>> b.xval\n5\n>>> b.xval = 6\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: can't set attribute\n" }, { "answer_id": 125136, "author": "Ryan", "author_id": 8819, "author_profile": "https://Stackoverflow.com/users/8819", "pm_score": 0, "selected": false, "text": "class autoprop(type):\n def __init__(cls, name, bases, dict):\n super(autoprop, cls).__init__(name, bases, dict)\n props = {}\n for name in dict.keys():\n if name.startswith(\"_get_\") or name.startswith(\"_set_\"):\n props[name[5:]] = 1\n for name in props.keys():\n fget = getattr(cls, \"_get_%s\" % name, None)\n fset = getattr(cls, \"_set_%s\" % name, None)\n setattr(cls, name, property(fget, fset))\n class A:\n __metaclass__ = autosuprop\n def _readonly(self):\n return __x\n" }, { "answer_id": 125739, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 2, "selected": false, "text": "class whatever(object):\n def __init__(self, a, b, c, ...):\n self.__foobar = 1\n self.__blahblah = 2\n\n foobar = property(lambda self: self.__foobar)\n blahblah = property(lambda self: self.__blahblah)\n foobar blahblah property" }, { "answer_id": 2704300, "author": "Ivan", "author_id": 61522, "author_profile": "https://Stackoverflow.com/users/61522", "pm_score": 0, "selected": false, "text": "class readonly(object):\n def __init__(self, attribute_name):\n self.attribute_name = attribute_name\n\n def __get__(self, instance, instance_type):\n if instance != None:\n return getattr(instance, self.attribute_name)\n else:\n raise AttributeError(\"class %s has no attribute %s\" % \n (instance_type.__name__, self.attribute_name))\n\n def __set__(self, instance, value):\n raise AttributeError(\"attribute %s is readonly\" % \n self.attribute_name)\n class a(object):\n def __init__(self, x):\n self.x = x\n xval = readonly(\"x\")\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14028/" ]
125,050
<p>...or are they the same thing? I notice that each has its own Wikipedia entry: <a href="http://en.wikipedia.org/wiki/Polymorphism_(computer_science)" rel="noreferrer">Polymorphism</a>, <a href="http://en.wikipedia.org/wiki/Multiple_dispatch" rel="noreferrer">Multiple Dispatch</a>, but I'm having trouble seeing how the concepts differ.</p> <p><strong>Edit:</strong> And how does <a href="http://en.wikipedia.org/wiki/Overloaded" rel="noreferrer">Overloading</a> fit into all this?</p>
[ { "answer_id": 125064, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 0, "selected": false, "text": "this" }, { "answer_id": 125095, "author": "CodeRedick", "author_id": 17145, "author_profile": "https://Stackoverflow.com/users/17145", "pm_score": 2, "selected": false, "text": "Car Truck Vehicle Vehicle void* Start() StartObject(Object C) Start() StartObject() Start() Car.Start(Key carKey) Missile.Start(int launchCode) StartObject(theCar) StartObject(theMissile)" }, { "answer_id": 125108, "author": "Purfideas", "author_id": 4615, "author_profile": "https://Stackoverflow.com/users/4615", "pm_score": 1, "selected": false, "text": "(obj_1, obj_2, ..., obj_n)->method\n" }, { "answer_id": 125162, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "List<T>" }, { "answer_id": 125337, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 7, "selected": true, "text": "this self using NUnit.Framework;\n\nnamespace SanityCheck.UnitTests.StackOverflow\n{\n [TestFixture]\n public class DispatchTypes\n {\n [Test]\n public void Polymorphism()\n {\n Baz baz = new Baz();\n Foo foo = new Foo();\n\n // overloading - parameter type is known during compile time\n Assert.AreEqual(\"zap object\", baz.Zap(\"hello\"));\n Assert.AreEqual(\"zap foo\", baz.Zap(foo));\n\n\n // virtual call - single dispatch. Baz is used.\n Zapper zapper = baz;\n Assert.AreEqual(\"zap object\", zapper.Zap(\"hello\"));\n Assert.AreEqual(\"zap foo\", zapper.Zap(foo));\n\n\n // C# has doesn't support multiple dispatch so it doesn't\n // know that oFoo is actually of type Foo.\n //\n // In languages with multiple dispatch, the type of oFoo will \n // also be used in runtime so Baz.Zap(Foo) will be called\n // instead of Baz.Zap(object)\n object oFoo = foo;\n Assert.AreEqual(\"zap object\", zapper.Zap(oFoo));\n }\n\n public class Zapper\n {\n public virtual string Zap(object o) { return \"generic zapper\" ; }\n public virtual string Zap(Foo f) { return \"generic zapper\"; }\n }\n\n public class Baz : Zapper\n {\n public override string Zap(object o) { return \"zap object\"; }\n public override string Zap(Foo f) { return \"zap foo\"; }\n }\n\n public class Foo { }\n }\n}\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
125,094
<p>I have a 2D character array:<br> <code>char nm[MAX1][MAX2] = { "john", "bob", "david" };</code><br> I want to swap two of these elements (without <code>std::swap</code>) by simply writing<br> <code>swapPointers(nm[0], nm[1]);</code><br> where <code>swapPointers</code> looks like this </p> <pre><code>void swapPointers(char *&amp;a, char *&amp;b) { char *temp = a; a = b; b = a; } </code></pre> <p>However, this does not compile (and while adding casts makes it compile, the pointers end up pointing to wrong/weird locations). </p> <p>Can anybody help?<br> Thanks!</p>
[ { "answer_id": 125103, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": 0, "selected": false, "text": "void swapPointers(char** ppa, char** ppb)\n{\n char* ptemp = *ppa;\n *ppb = *ppa;\n *ppa = ptemp;\n}\n\nswapPointers(&nm[0], &nm[1]);\n" }, { "answer_id": 125183, "author": "Zan Lynx", "author_id": 13422, "author_profile": "https://Stackoverflow.com/users/13422", "pm_score": 2, "selected": false, "text": "const const swap(char *a, char *b)\n{\n char temp[MAX1];\n memcpy(temp, a, MAX1);\n memcpy(b, a, MAX1);\n memcpy(a, temp, MAX1);\n}\n" }, { "answer_id": 125255, "author": "Hugh Allen", "author_id": 15069, "author_profile": "https://Stackoverflow.com/users/15069", "pm_score": 2, "selected": false, "text": "swapPointers() char nm[MAX1][MAX2]\n char *nm[MAX1]\n swapPointers() b = temp;" }, { "answer_id": 125454, "author": "Kevin", "author_id": 6386, "author_profile": "https://Stackoverflow.com/users/6386", "pm_score": 3, "selected": true, "text": "void swap(char (&x)[MAX2], char (&y)[MAX2])\n{\n char temp[MAX2];\n\n memcpy(temp, x, MAX2);\n memcpy(x, y, MAX2);\n memcpy(y, temp, MAX2);\n}\n" }, { "answer_id": 125554, "author": "graham.reeds", "author_id": 342, "author_profile": "https://Stackoverflow.com/users/342", "pm_score": 1, "selected": false, "text": "std::vector<std::string> nm;\nnm.push_back( \"john\" );\nnm.push_back( \"bob\" );\nnm.push_back( \"david\" );\nstd::swap( nm[0], nm[1] );\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21475/" ]
125,096
<p>I have an app that has impersonation used throughout. But when a user is logged in as an admin, a few operation require them to write to the server itself. Now if these users do not have rights on the actual server (some don't) it will not let them write. </p> <p>What I want to do is turn off impersonation for just a couple commands.</p> <p>Is there a way to do something like this?</p> <pre><code>using(HostingEnvironment.Impersonate.Off()) //I know this isn't a command, but you get the idea? </code></pre> <p>Thank you.</p>
[ { "answer_id": 217452, "author": "Maxime Rouiller", "author_id": 24975, "author_profile": "https://Stackoverflow.com/users/24975", "pm_score": 6, "selected": true, "text": "private WindowsImpersonationContext context = null;\npublic void RevertToAppPool()\n{\n try\n {\n if (!WindowsIdentity.GetCurrent().IsSystem)\n {\n context = WindowsIdentity.Impersonate(System.IntPtr.Zero);\n }\n }\n catch { }\n}\npublic void UndoImpersonation()\n{\n try\n {\n if (context != null)\n {\n context.Undo();\n }\n }\n catch { }\n}\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14777/" ]
125,099
<p>Anyone know the formula used to control the movement of a simple tank-like vehicle?</p> <p>To 'steer' it, you need to alter the force applied the left and right "wheels". Eg. 1 unit of force on both wheels makes it go forward. -1 units of force on both wheels makes it go backwards. Apply more force to one wheel than the other and it turns.</p> <p>How would you calculate the amount of force needed on both wheels to turn the tank a certain number of degrees either way?</p> <p>Or am I thinking about this in the wrong way?</p> <p>edit: As William Keller mentioned I missed out the speed of the tank. Assume 1 unit of force on both wheels moves the tank forward at 1 unit per second.</p> <p>For anyone who's interested, I just found this thread on gamedev.net: <a href="http://66.102.9.104/search?q=cache:wSn5t58ACJwJ:www.gamedev.net/community/forums/topic.asp%3Ftopic_id%3D407491+tank+track+radius+velocity&amp;hl=en&amp;ct=clnk&amp;cd=1&amp;gl=za&amp;client=firefox-a" rel="nofollow noreferrer">http://66.102.9.104/search?q=cache:wSn5t58ACJwJ:www.gamedev.net/community/forums/topic.asp%3Ftopic_id%3D407491+tank+track+radius+velocity&amp;hl=en&amp;ct=clnk&amp;cd=1&amp;gl=za&amp;client=firefox-a</a></p> <p>Another thread: <a href="http://www.physicsforums.com/showthread.php?t=220317" rel="nofollow noreferrer">http://www.physicsforums.com/showthread.php?t=220317</a></p> <p>It turns out the key to finding the formula was just knowing the correct terminology ("skid steer") :P</p>
[ { "answer_id": 125154, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": 2, "selected": false, "text": "Change in angle (in radians/sec) = (l-r)/(radius between treads)\nVelocity = l+r\n" }, { "answer_id": 39111386, "author": "Paul Carew", "author_id": 1892952, "author_profile": "https://Stackoverflow.com/users/1892952", "pm_score": 3, "selected": true, "text": "So = Si * ((r+d)/r)\n c1 = 2*PI*r\n'r' is radius of circle origin to track/wheel\n c2 = 2*PI*(r+d)\n'r' is radius of circle origin to inner track/wheel\n'd' is the distance between the Inner and Outer wheels/track.\n X = c2 / c1\nX = 2*PI*(r+d) / 2*PI*r\nX = (r+d)/r\n So = Si * ((r+d)/r)\n 'So' = Speed of outer track\n'Si' = Speed of inner track\n'r' = turn radius from inner track\n'd' = distance between vehicle tracks.\n\n\n ********* <---------------- Outer Track\n **** | **** \n ** |<--------**----------- 'd' Distance between tracks\n * *******<-------*---------- Inner Track\n * *** ^ *** * \n * * |<-----*------*-------- 'r' Radius of Turn\n * * | * * \n * * O * * \n * * * * \n * * * * \n * *** *** * \n * ******* * \n ** ** \n **** **** \n ********* \n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9825/" ]
125,102
<p>Say I have the following string:</p> <pre><code>"I am the most foo h4ck3r ever!!" </code></pre> <p>I'm trying to write a makeSpecial(foo) function where the foo substring would be wrapped in a new span element, resulting in:</p> <pre><code>"I am the most &lt;span class="special"&gt;foo&gt;&lt;/span&gt; h4ck3r ever!!" </code></pre> <p>BeautifulSoup seemed like the way to go, but I haven't been able to make it work.</p> <p>I could also pass this to the browser and do it with javascript, but that doesn't seem like a great idea.</p> <p>Some advice for this would be really useful, especially in python. </p>
[ { "answer_id": 125122, "author": "fuentesjr", "author_id": 10708, "author_profile": "https://Stackoverflow.com/users/10708", "pm_score": 3, "selected": true, "text": "Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on\nwin32\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> def makeSpecial(mystring, special_substr):\n... return mystring.replace(special_substr, '<span class=\"special\">%s</span>\n' % special_substr)\n...\n>>> makeSpecial(\"I am the most foo h4ck3r ever!!\", \"foo\")\n'I am the most <span class=\"special\">foo</span> h4ck3r ever!!'\n>>>\n" }, { "answer_id": 125134, "author": "Swati", "author_id": 12682, "author_profile": "https://Stackoverflow.com/users/12682", "pm_score": 1, "selected": false, "text": "replace(old, new[, count]) \n myStr.replace(\"foo\", \"<span>foo</span>\") \n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9106/" ]
125,109
<p>I'm trying to bind a <code>List&lt;T&gt;</code> to a DataGridView control, and I'm not having any luck creating custom bindings.</p> <p>I have tried:</p> <pre><code>gvProgramCode.DataBindings.Add(new Binding("Opcode",code,"Opcode")); </code></pre> <p>It throws an exception, saying that nothing was found by that property name.</p> <p>The name of the column in question is "Opcode". The name of the property in the <code>List&lt;T&gt;</code> is Opcode.</p> <p><strong>ANSWER EDIT</strong>: the problem was that I did not have the bindable fields in my class as properties, just public fields...Apparently it doesn't reflect on fields, just properties.</p>
[ { "answer_id": 125132, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 4, "selected": false, "text": " class MyObject\n {\n public string Something { get; set; }\n public string Text { get; set; }\n public string Other { get; set; }\n }\n\n public Form1()\n {\n InitializeComponent();\n\n List<MyObject> myList = new List<MyObject>();\n\n for (int i = 0; i < 200; i++)\n {\n string num = i.ToString();\n myList.Add(new MyObject { Something = \"Something \" + num , Text = \"Some Row \" + num , Other = \"Other \" + num });\n }\n\n dataGridView1.DataSource = myList;\n }\n" }, { "answer_id": 125165, "author": "Jared", "author_id": 7388, "author_profile": "https://Stackoverflow.com/users/7388", "pm_score": 3, "selected": false, "text": " private BindingSource _gridSource;\n\n private BindingSource GridSource\n {\n get\n {\n if (_gridSource == null)\n _gridSource = new BindingSource();\n return _gridSource;\n }\n }\n\n private void Form1_Load(object sender, EventArgs e)\n {\n List<FluffyBunny> list = new List<FluffyBunny>();\n list.Add(new FluffyBunny { Color = \"White\", EarType = \"Long\", Name = \"Stan\" });\n list.Add(new FluffyBunny { Color = \"Brown\", EarType = \"Medium\", Name = \"Mike\" });\n list.Add(new FluffyBunny { Color = \"Mottled\", EarType = \"Short\", Name = \"Torvald\" });\n\n GridSource.DataSource = list;\n dataGridView1.Columns[\"EarType\"].Visible = false; //Optionally hide a column\n dataGridView1.DataSource = GridSource;\n\n }\n" }, { "answer_id": 1728974, "author": "Nikola Stjelja", "author_id": 32582, "author_profile": "https://Stackoverflow.com/users/32582", "pm_score": 2, "selected": false, "text": "\n\nprivate void Form1_Load(object sender, EventArgs e)\n{\n BindingList people= new BindingList {\n new Person {Name=\"John\",Age=23},\n new Person {Name=\"Lucy\",Age=16}\n };\n\n dataGridView1.DataSource= people;\n}\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
125,113
<p>What is the most efficient way to convert a MySQL query to CSV in PHP please?</p> <p>It would be best to avoid temp files as this reduces portability (dir paths and setting file-system permissions required).</p> <p>The CSV should also include one top line of field names.</p>
[ { "answer_id": 125118, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 2, "selected": false, "text": "// Export to CSV\nif($_GET['action'] == 'export') {\n\n $rsSearchResults = mysql_query($sql, $db) or die(mysql_error());\n\n $out = '';\n $fields = mysql_list_fields('database','table',$db);\n $columns = mysql_num_fields($fields);\n\n // Put the name of all fields\n for ($i = 0; $i < $columns; $i++) {\n $l=mysql_field_name($fields, $i);\n $out .= '\"'.$l.'\",';\n }\n $out .=\"\\n\";\n\n // Add all values in the table\n while ($l = mysql_fetch_array($rsSearchResults)) {\n for ($i = 0; $i < $columns; $i++) {\n $out .='\"'.$l[\"$i\"].'\",';\n }\n $out .=\"\\n\";\n }\n // Output to browser with appropriate mime type, you choose ;)\n header(\"Content-type: text/x-csv\");\n //header(\"Content-type: text/csv\");\n //header(\"Content-type: application/csv\");\n header(\"Content-Disposition: attachment; filename=search_results.csv\");\n echo $out;\n exit;\n}\n" }, { "answer_id": 125120, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 4, "selected": false, "text": "SELECT a,b,a+b INTO OUTFILE '/tmp/result.txt'\n FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'\n LINES TERMINATED BY '\\n'\n FROM test_table;\n" }, { "answer_id": 125125, "author": "Geoff", "author_id": 10427, "author_profile": "https://Stackoverflow.com/users/10427", "pm_score": 8, "selected": true, "text": "SELECT * INTO OUTFILE \"c:/mydata.csv\"\nFIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'\nLINES TERMINATED BY \"\\n\"\nFROM my_table;\n $select = \"SELECT * FROM table_name\";\n\n$export = mysql_query ( $select ) or die ( \"Sql error : \" . mysql_error( ) );\n\n$fields = mysql_num_fields ( $export );\n\nfor ( $i = 0; $i < $fields; $i++ )\n{\n $header .= mysql_field_name( $export , $i ) . \"\\t\";\n}\n\nwhile( $row = mysql_fetch_row( $export ) )\n{\n $line = '';\n foreach( $row as $value )\n { \n if ( ( !isset( $value ) ) || ( $value == \"\" ) )\n {\n $value = \"\\t\";\n }\n else\n {\n $value = str_replace( '\"' , '\"\"' , $value );\n $value = '\"' . $value . '\"' . \"\\t\";\n }\n $line .= $value;\n }\n $data .= trim( $line ) . \"\\n\";\n}\n$data = str_replace( \"\\r\" , \"\" , $data );\n\nif ( $data == \"\" )\n{\n $data = \"\\n(0) Records Found!\\n\"; \n}\n\nheader(\"Content-type: application/octet-stream\");\nheader(\"Content-Disposition: attachment; filename=your_desired_name.xls\");\nheader(\"Pragma: no-cache\");\nheader(\"Expires: 0\");\nprint \"$header\\n$data\";\n" }, { "answer_id": 125578, "author": "Jrgns", "author_id": 6681, "author_profile": "https://Stackoverflow.com/users/6681", "pm_score": 7, "selected": false, "text": "$result = $db_con->query('SELECT * FROM `some_table`');\nif (!$result) die('Couldn\\'t fetch records');\n$num_fields = mysql_num_fields($result);\n$headers = array();\nfor ($i = 0; $i < $num_fields; $i++) {\n $headers[] = mysql_field_name($result , $i);\n}\n$fp = fopen('php://output', 'w');\nif ($fp && $result) {\n header('Content-Type: text/csv');\n header('Content-Disposition: attachment; filename=\"export.csv\"');\n header('Pragma: no-cache');\n header('Expires: 0');\n fputcsv($fp, $headers);\n while ($row = $result->fetch_array(MYSQLI_NUM)) {\n fputcsv($fp, array_values($row));\n }\n die;\n}\n" }, { "answer_id": 837194, "author": "John Douthat", "author_id": 2774, "author_profile": "https://Stackoverflow.com/users/2774", "pm_score": 3, "selected": false, "text": "function setExcelContentType() {\n if(headers_sent())\n return false;\n\n header('Content-type: application/vnd.ms-excel');\n return true;\n}\n\nfunction setDownloadAsHeader($filename) {\n if(headers_sent())\n return false;\n\n header('Content-disposition: attachment; filename=' . $filename);\n return true;\n}\n function csvFromResult($stream, $result, $showColumnHeaders = true) {\n if($showColumnHeaders) {\n $columnHeaders = array();\n $nfields = mysql_num_fields($result);\n for($i = 0; $i < $nfields; $i++) {\n $field = mysql_fetch_field($result, $i);\n $columnHeaders[] = $field->name;\n }\n fputcsv($stream, $columnHeaders);\n }\n\n $nrows = 0;\n while($row = mysql_fetch_row($result)) {\n fputcsv($stream, $row);\n $nrows++;\n }\n\n return $nrows;\n}\n function csvFileFromResult($filename, $result, $showColumnHeaders = true) {\n $fp = fopen($filename, 'w');\n $rc = csvFromResult($fp, $result, $showColumnHeaders);\n fclose($fp);\n return $rc;\n}\n function csvToExcelDownloadFromResult($result, $showColumnHeaders = true, $asFilename = 'data.csv') {\n setExcelContentType();\n setDownloadAsHeader($asFilename);\n return csvFileFromResult('php://output', $result, $showColumnHeaders);\n}\n $result = mysql_query(\"SELECT foo, bar, shazbot FROM baz WHERE boo = 'foo'\");\ncsvToExcelDownloadFromResult($result);\n" }, { "answer_id": 7125198, "author": "John M", "author_id": 127776, "author_profile": "https://Stackoverflow.com/users/127776", "pm_score": 4, "selected": false, "text": "$result = mysql_query('SELECT * FROM `some_table`'); \nif (!$result) die('Couldn\\'t fetch records'); \n$num_fields = mysql_num_fields($result); \n$headers = array(); \nfor ($i = 0; $i < $num_fields; $i++) \n{ \n $headers[] = mysql_field_name($result , $i); \n} \n$fp = fopen('php://output', 'w'); \nif ($fp && $result) \n{ \n header('Content-Type: text/csv');\n header('Content-Disposition: attachment; filename=\"export.csv\"');\n header('Pragma: no-cache'); \n header('Expires: 0');\n fputcsv($fp, $headers); \n while ($row = mysql_fetch_row($result)) \n {\n fputcsv($fp, array_values($row)); \n }\ndie; \n} \n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5165/" ]
125,117
<p>I was looking at how some site implemented rounded corners, and the CSS had these odd tags that I've never really seen before.</p> <pre><code>-moz-border-radius-topright: 5px; -webkit-border-top-right-radius: 5px; -moz-border-radius-bottomright: 5px; -webkit-border-bottom-right-radius: 5px; </code></pre> <p>I googled it, and they seem to be Firefox specific tags? </p> <p><b>Update</b></p> <p>The site I was looking at was twitter, it's wierd how a site like that would alienate their IE users.</p>
[ { "answer_id": 125128, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 4, "selected": true, "text": "-moz-* -webkit-*" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
125,124
<p>How do you pass options to an executable? Is there an easier way than making the options boolean arguments?</p> <p>EDIT: The last two answers have suggested using arguments. I know I can code a workable solution like that, but I'd rather have them be options.</p> <p>EDIT2: Per requests for clarification, I'll use this simple example: It's fairly easy to handle arguments because they automatically get parsed into an array.</p> <pre><code>./printfile file.txt 1000 </code></pre> <p>If I want to know what the name of the file the user wants to print, I access it via argv[1].</p> <p>Now about how this situation:</p> <pre><code>./printfile file.txt 1000 --nolinebreaks </code></pre> <p>The user wants to print the file with no line breaks. This is not required for the program to be able to run (as the filename and number of lines to print are), but the user has the option of using if if s/he would like. Now I could do this using:</p> <pre><code>./printfile file.txt 1000 true </code></pre> <p>The usage prompt would inform the user that the third argument is used to determine whether to print the file with line breaks or not. However, this seems rather clumsy. </p>
[ { "answer_id": 125225, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 3, "selected": true, "text": "-- getopt() getopt_long() --number-of-line-breaks 47" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7545/" ]
125,143
<p>I am developing a forms app (not web) for Windows Mobile, using .NET CF 3.5. I need an HTML editor control. I'm looking for something along the lines of a simple FCKEditor, but for using in a forms app (EXE).</p> <p>Any suggestions?</p>
[ { "answer_id": 125297, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 0, "selected": false, "text": "webBrowser1.Document.GetType().GetProperty(\"designmode\").SetValue(webBrowser1.Document, true, null);\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1664/" ]
125,146
<p>I'm trying to write an app using Ruby on Rails and I'm trying to achieve the following:</p> <blockquote> <p>The app needs to receive UDP messages coming in on a specific port (possibly 1 or more per second) and store them in the database so that the rest of my Rails app can access it. </p> </blockquote> <p>I was thinking of writing a separate daemon that would receive these messages and shell out to a ruby script on my rails app that will store the message in the database using the right model. The problem with this approach is that the ruby script will be run very often. It would be better performance-wise if I could just have a long-running ruby process that can constantly receive the UDP messages store them in the database. </p> <p>Is this the right way to do it? Is there something in the Rails framework that can help with this?</p>
[ { "answer_id": 125179, "author": "Nate", "author_id": 12779, "author_profile": "https://Stackoverflow.com/users/12779", "pm_score": 3, "selected": true, "text": "include" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
125,157
<p>Is it possible to specify a relative path reference in connectionstring, attachDbFileName property in a web.config?</p> <p>For example, In my database is located in the App_data folder, I can easily specify the AttachDBFilename as|DataDirectory|\mydb.mdf and the |Datadirectory| will automatically resolve to the correct path.</p> <p>Now, suppose that web.config file is located in A folder, but the database is located in B\App_data folder, where A and B folder is located in the same folder. Is there anyway to use relative path reference to resolve to the correct path?</p>
[ { "answer_id": 2522135, "author": "jbandi", "author_id": 32749, "author_profile": "https://Stackoverflow.com/users/32749", "pm_score": 4, "selected": false, "text": "<appSettings>\n <add key=\"DataDirectory\" value=\"..\\..\\..\\BookShop\\App_Data\\\"/>\n</appSettings>\n var dataDirectory = ConfigurationManager.AppSettings[\"DataDirectory\"]; \n var absoluteDataDirectory = Path.GetFullPath(dataDirectory); \n AppDomain.CurrentDomain.SetData(\"DataDirectory\", absoluteDataDirectory); \n" }, { "answer_id": 5627794, "author": "JohnSpin", "author_id": 702988, "author_profile": "https://Stackoverflow.com/users/702988", "pm_score": 1, "selected": false, "text": "[DeploymentItem(\"..\\\\TestSolutionDir\\\\TestProjedtDir\\\\TestDataFolder\\\\TestAutomationSpreadsheet.xlsx\")]\n[DataSource(\"System.Data.Odbc\", \"Dsn=Excel Files;dbq=|DataDirectory|\\\\TestAutomationSpreadsheet.xlsx\", \"SpreadsheetTabName$\", DataAccessMethod.Sequential)]\n |DataDirctory|" }, { "answer_id": 60204426, "author": "Unni Krishnan SJ Nair", "author_id": 11082833, "author_profile": "https://Stackoverflow.com/users/11082833", "pm_score": 0, "selected": false, "text": " <appSettings>\n <add key=\"FilePath\" value=\"App_Data\\SavedFiles\\\"/>\n </appSettings>\n string filePath = AppDomain.CurrentDomain.BaseDirectory + (ConfigurationManager.AppSettings[\"FilePath\"]);\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
125,171
<p>I need to pass a regex substitution as a variable:</p> <pre><code>sub proc { my $pattern = shift; my $txt = &quot;foo baz&quot;; $txt =~ $pattern; } my $pattern = 's/foo/bar/'; proc($pattern); </code></pre> <p>This, of course, doesn't work. I tried eval'ing the substitution:</p> <pre><code>eval(&quot;$txt =~ $pattern;&quot;); </code></pre> <p>but that didn't work either. What horribly obvious thing am I missing here?</p>
[ { "answer_id": 125212, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 3, "selected": false, "text": "$pattern = qr/foo/;\n\nprint \"match!\\n\" if $text =~ $pattern;\n proc('$text =~ s/foo/bar');\n\nsub proc {\n my $code = shift;\n\n ...\n\n eval $code;\n}\n proc(sub {my $text = shift; $text =~ s/foo/bar});\n\nsub proc {\n my $code = shift;\n\n ...\n\n $code->(\"some text\");\n}\n" }, { "answer_id": 125240, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": false, "text": "sub proc {\n my($match, $subst) = @_;\n my $txt = \"foo baz\";\n $txt =~ s/$match/$subst/;\n print \"$txt\\n\";\n}\n\nmy $matcher = qr/foo/;\nmy $sub_str = \"bar\";\n\nproc($matcher, $sub_str);\n input: datetime year to second,decimal(16,6), integer\n #!/bin/perl -w\nuse strict;\nwhile (<>)\n{\n chomp;\n print \"Read: <$_>\\n\";\n my($r1) = qr%^input\\s*:\\s*%i;\n if ($_ =~ $r1)\n {\n print \"Found input:\\n\";\n s%$r1%%;\n print \"Residue: <$_>\\n\";\n my($r3) = qr%(?:year|month|day|hour|minute|second|fraction(?:\\([1-5]\\))?)%;\n my($r2) = qr%\n (?:\\s*,?\\s*)? # Commas and spaces\n (\n (?:money|numeric|decimal)(?:\\(\\d+(?:,\\d+)?\\))? |\n int(?:eger)? |\n smallint |\n datetime\\s+$r3\\s+to\\s+$r3\n )\n %ix;\n while ($_ =~ m/$r2/)\n {\n print \"Got type: <$1>\\n\";\n s/$r2//;\n }\n print \"Residue 2: <$_>\\n\";\n }\n else\n {\n print \"No match:\\n\";\n }\n print \"Next?\\n\";\n}\n" }, { "answer_id": 125266, "author": "John Siracusa", "author_id": 164, "author_profile": "https://Stackoverflow.com/users/164", "pm_score": 6, "selected": true, "text": "sub modify\n{\n my($text, $code) = @_;\n $code->($text);\n return $text;\n}\n\nmy $new_text = modify('foo baz', sub { $_[0] =~ s/foo/bar/ });\n" }, { "answer_id": 125329, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 3, "selected": false, "text": "eval \"$txt =~ $pattern\";\n eval \"\\\"foo baz\\\" =~ s/foo/bar/\"\n eval \"\\$txt =~ $pattern\"\n sub proc {\n my $pattern = shift;\n my $code = shift;\n my $txt = \"foo baz\";\n $txt =~ s/$pattern/$code->()/e;\n print \"$txt\\n\";\n}\n\nmy $pattern = qr/foo/;\nproc($pattern, sub { \"bar\" }); # ==> bar baz\nproc($pattern, sub { \"\\U$&\" }); # ==> FOO baz\n" }, { "answer_id": 126457, "author": "rjray", "author_id": 6421, "author_profile": "https://Stackoverflow.com/users/6421", "pm_score": 2, "selected": false, "text": "s/foo/bar/ eval eval sub apply_regex {\n my $regex = shift;\n my $subst = shift || ''; # No subst string will mean matches are \"deleted\"\n\n # Some setup and processing happens...\n\n # Time to make use of the regex that was passed in:\n while (defined($_ = <$some_filehandle>)) {\n s/$regex/$subst/g; # You can decide if you want to use /g etc.\n }\n\n # The rest of the processing...\n}\n apply_regex('foo', 'bar');\n qr// apply_regex(qr{(foo|bar)}, 'baz');\napply_regex(qr/[ab]+/, '(one or more of \"a\" or \"b\")');\napply_regex(qr|\\d+|); # Delete any sequences of digits\n eval" }, { "answer_id": 128321, "author": "bart", "author_id": 19966, "author_profile": "https://Stackoverflow.com/users/19966", "pm_score": 3, "selected": false, "text": "s/// eval qr// s/(\\w+)/\\u\\L$1/g;\n replace($string, qr/(\\w+)/, sub { \"\\u\\L$1\" }, 'g');\n sub replace {\n my($string, $find, $replace, $global) = @_;\n unless($global) {\n $string =~ s($find){ $replace->() }e;\n } else {\n $string =~ s($find){ $replace->() }ge;\n }\n return $string;\n}\n print replace('content-TYPE', qr/(\\w+)/, sub { \"\\u\\L$1\" }, 'g');\n" }, { "answer_id": 4046820, "author": "pevgeniev", "author_id": 408821, "author_profile": "https://Stackoverflow.com/users/408821", "pm_score": -1, "selected": false, "text": "eval('$txt =~ ' . \"$pattern;\");\n" }, { "answer_id": 10691133, "author": "Jeff Burdges", "author_id": 667457, "author_profile": "https://Stackoverflow.com/users/667457", "pm_score": 0, "selected": false, "text": "#!/opt/local/bin/perl\nsub oops { die \"Usage : sednames s/old/new [files ..]\\n\"; }\noops if ($#ARGV < 0);\n\n$regex = eval 'sub { $_ = $_[0]; ' . shift(@ARGV) . '; return $_; }';\nsub regex_rename { foreach (<$_[0]>) {\n rename(\"$_\", &$regex($_));\n} }\n\nif ($#ARGV < 0) { regex_rename(\"*\"); }\nelse { regex_rename(@ARGV); }\n $_ s/old/new eval eval $_ eval 'sub { ' . shift(@ARGV) . ' }';\n &$regex $_ \"$_\" $_ rename eval" }, { "answer_id": 46698295, "author": "Aloso", "author_id": 3393058, "author_profile": "https://Stackoverflow.com/users/3393058", "pm_score": 0, "selected": false, "text": "sub proc {\n my ($pattern, $replacement) = @_;\n my $txt = \"foo baz\";\n\n $txt =~ s/$pattern/$replacement/g; # This substitution is global.\n}\n\nmy $pattern = qr/foo/; # qr means the regex is pre-compiled.\nmy $replacement = 'bar';\n\nproc($pattern, $replacement);\n sub proc {\n my ($pattern, $replacement, $flags) = @_;\n my $txt = \"foo baz\";\n\n eval('$txt =~ s/$pattern/$replacement/' . $flags);\n}\n\nproc(qr/foo/, 'bar', 'g');\n /" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8130/" ]
125,192
<p>A common pattern with STL containers is this:</p> <pre><code>map&lt;Key, Value&gt; map; for(map&lt;Key, Value&gt;::iterator iter = map.begin(); iter != map.end(); ++iter) { ... } </code></pre> <p>So in order to avoid writing the declaration of the template parameters we can do this somewhere:</p> <pre><code>typedef map&lt;Key, Value&gt; TNiceNameForAMap; </code></pre> <p>But if this map is only used in a single function or for a single iteration this is an annoying overhead.</p> <p>Is there any way around this typedef?</p>
[ { "answer_id": 125201, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 3, "selected": false, "text": "int totalSize() {\n typedef std::map<Key, Value> DeDuplicator;\n DeDuplicator everything;\n\n // Run around the universe finding everything. If we encounter a key\n // more than once it's only added once.\n\n // now compute the total\n int total = 0;\n for(DeDuplicator::iterator i = everything.begin(); i <= everything.end(); ++i) {\n total += i->second.size(); // yeah, yeah, overflow. Whatever.\n }\n return total;\n}\n BOOST_FOREACH(DeDuplicator::pair p, everything) {\n total += p.second.size();\n}\n std::map<Key, Value> everything;\n// snipped code to run around...\nint total = 0;\nBOOST_FOREACH(auto p, everything) {\n total += p.second.size();\n}\n" }, { "answer_id": 125296, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 2, "selected": false, "text": "auto map<Key, Value> map;\nfor(auto iter = map.begin(); iter != map.end(); ++iter)\n{\n ...\n}\n" }, { "answer_id": 125918, "author": "Richard Corden", "author_id": 11698, "author_profile": "https://Stackoverflow.com/users/11698", "pm_score": 0, "selected": false, "text": "struct DoLoopBody {\n template <typename ValueType>\n inline void operator()(ValueType v) const {\n // ...\n }\n};\n\nstd::for_each (map.begin(), map.end(), DoLoopBody ());\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9611/" ]
125,222
<p>for working with MS word files in python, there is python win32 extensions, which can be used in windows. How do I do the same in linux? Is there any library?</p>
[ { "answer_id": 404378, "author": "David", "author_id": 49460, "author_profile": "https://Stackoverflow.com/users/49460", "pm_score": 3, "selected": false, "text": "import commands\n\nexe = 'wvText ' + word_file + ' ' + output_txt_file\nout = commands.getoutput(exe)\nexe = 'cat ' + output_txt_file\nout = commands.getoutput(exe)\n" }, { "answer_id": 1258599, "author": "Ben Williams", "author_id": 36098, "author_profile": "https://Stackoverflow.com/users/36098", "pm_score": 2, "selected": false, "text": "unzip -p file.docx | grep '<w:t' | sed 's/<[^<]*>//g' | grep -v '^[[:space:]]*$'\n" }, { "answer_id": 1723437, "author": "benjamin", "author_id": 209753, "author_profile": "https://Stackoverflow.com/users/209753", "pm_score": 2, "selected": false, "text": "content = \"\"\n# Load DocX into zipfile\ndocx = zipfile.ZipFile('/home/whateverdocument.docx')\n# Unpack zipfile\nunpacked = docx.infolist()\n# Find the /word/document.xml file in the package and assign it to variable\nfor item in unpacked:\n if item.orig_filename == 'word/document.xml':\n content = docx.read(item.orig_filename)\n\n else:\n pass\n # Clean the content string from xml tags for better search\nfullyclean = []\nhalfclean = content.split('<')\nfor item in halfclean:\n if '>' in item:\n bad_good = item.split('>')\n if bad_good[-1] != '':\n fullyclean.append(bad_good[-1])\n else:\n pass\n else:\n pass\n\n# Assemble a new string with all pure content\ncontent = \" \".join(fullyclean)\n" }, { "answer_id": 1967869, "author": "Chad", "author_id": 239382, "author_profile": "https://Stackoverflow.com/users/239382", "pm_score": 4, "selected": false, "text": "import zipfile, re\n\ndocx = zipfile.ZipFile('/path/to/file/mydocument.docx')\ncontent = docx.read('word/document.xml').decode('utf-8')\ncleaned = re.sub('<(.|\\n)*?>','',content)\nprint(cleaned)\n" }, { "answer_id": 1979906, "author": "mikemaccana", "author_id": 123671, "author_profile": "https://Stackoverflow.com/users/123671", "pm_score": 5, "selected": false, "text": "document = docx.Document(filename)\ndocText = '\\n\\n'.join(\n paragraph.text for paragraph in document.paragraphs\n)\nprint(docText)\n" }, { "answer_id": 30582548, "author": "Dalen", "author_id": 2247264, "author_profile": "https://Stackoverflow.com/users/2247264", "pm_score": 2, "selected": false, "text": "\ndoc2text module:\n\"\"\"\nThis is Python implementation of C# algorithm proposed in:\nhttp://b2xtranslator.sourceforge.net/howtos/How_to_retrieve_text_from_a_binary_doc_file.pdf\n\nPython implementation author is Dalen Bernaca.\nCode needs refining and probably bug fixing!\nAs I am not a C# expert I would like some code rechecks by one.\nParts of which I am uncertain are:\n * Did the author of original algorithm used uint32 and int32 when unpacking correctly?\n I copied each occurence as in original algo.\n * Is the FIB length for MS Word 97 1472 bytes as in MS Word 2000, and would it make any difference if it is not?\n * Did I interpret each C# command correctly?\n I think I did!\n\"\"\"\n\nfrom compoundfiles import CompoundFileReader, CompoundFileError\nfrom struct import unpack\n\n__all__ = [\"doc2text\"]\n\ndef doc2text (path):\n text = u\"\"\n cr = CompoundFileReader(path)\n # Load WordDocument stream:\n try:\n f = cr.open(\"WordDocument\")\n doc = f.read()\n f.close()\n except: cr.close(); raise CompoundFileError, \"The file is corrupted or it is not a Word document at all.\"\n # Extract file information block and piece table stream informations from it:\n fib = doc[:1472]\n fcClx = unpack(\"L\", fib[0x01a2l:0x01a6l])[0]\n lcbClx = unpack(\"L\", fib[0x01a6l:0x01a6+4l])[0]\n tableFlag = unpack(\"L\", fib[0x000al:0x000al+4l])[0] & 0x0200l == 0x0200l\n tableName = (\"0Table\", \"1Table\")[tableFlag]\n # Load piece table stream:\n try:\n f = cr.open(tableName)\n table = f.read()\n f.close()\n except: cr.close(); raise CompoundFileError, \"The file is corrupt. '%s' piece table stream is missing.\" % tableName\n cr.close()\n # Find piece table inside a table stream:\n clx = table[fcClx:fcClx+lcbClx]\n pos = 0\n pieceTable = \"\"\n lcbPieceTable = 0\n while True:\n if clx[pos]==\"\\x02\":\n # This is piece table, we store it:\n lcbPieceTable = unpack(\"l\", clx[pos+1:pos+5])[0]\n pieceTable = clx[pos+5:pos+5+lcbPieceTable]\n break\n elif clx[pos]==\"\\x01\":\n # This is beggining of some other substructure, we skip it:\n pos = pos+1+1+ord(clx[pos+1])\n else: break\n if not pieceTable: raise CompoundFileError, \"The file is corrupt. Cannot locate a piece table.\"\n # Read info from pieceTable, about each piece and extract it from WordDocument stream:\n pieceCount = (lcbPieceTable-4)/12\n for x in xrange(pieceCount):\n cpStart = unpack(\"l\", pieceTable[x*4:x*4+4])[0]\n cpEnd = unpack(\"l\", pieceTable[(x+1)*4:(x+1)*4+4])[0]\n ofsetDescriptor = ((pieceCount+1)*4)+(x*8)\n pieceDescriptor = pieceTable[ofsetDescriptor:ofsetDescriptor+8]\n fcValue = unpack(\"L\", pieceDescriptor[2:6])[0]\n isANSII = (fcValue & 0x40000000) == 0x40000000\n fc = fcValue & 0xbfffffff\n cb = cpEnd-cpStart\n enc = (\"utf-16\", \"cp1252\")[isANSII]\n cb = (cb*2, cb)[isANSII]\n text += doc[fc:fc+cb].decode(enc, \"ignore\")\n return \"\\n\".join(text.splitlines())\n" }, { "answer_id": 38750949, "author": "Antoine Dusséaux", "author_id": 5285608, "author_profile": "https://Stackoverflow.com/users/5285608", "pm_score": 2, "selected": false, "text": "from docx import Document\ndocument = Document('existing-document-file.docx')\ndocument.save('new-file-name.docx')\n sudo apt-get install antiword\n import os\ninput_word_file = \"input_file.doc\"\noutput_text_file = \"output_file.txt\"\nos.system('antiword %s > %s' % (input_word_file, output_text_file))\n" }, { "answer_id": 65670786, "author": "Tilal Ahmad", "author_id": 1368028, "author_profile": "https://Stackoverflow.com/users/1368028", "pm_score": -1, "selected": false, "text": "# For complete examples and data files, please go to https://github.com/aspose-words-cloud/aspose-words-cloud-python\n# Import module\nimport asposewordscloud\nimport asposewordscloud.models.requests\nfrom shutil import copyfile\n\n# Please get your Client ID and Secret from https://dashboard.aspose.cloud.\nclient_id='xxxxxxx-xxxx-xxxx-xxxxx-xxxxxxxxxx'\nclient_secret='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'\n\nwords_api = asposewordscloud.WordsApi(client_id,client_secret)\nwords_api.api_client.configuration.host='https://api.aspose.cloud'\n\nfilename = 'C:/Temp/02_pages.docx'\ndest_name = 'C:/Temp/02_pages.txt'\n#Convert RTF to text\nrequest = asposewordscloud.models.requests.ConvertDocumentRequest(document=open(filename, 'rb'), format='txt')\nresult = words_api.convert_document(request)\ncopyfile(result, dest_name)\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21480/" ]
125,230
<p>What MySQL query will do a text search and replace in one particular field in a table?</p> <p>I.e. search for <code>foo</code> and replace with <code>bar</code> so a record with a field with the value <code>hello foo</code> becomes <code>hello bar</code>.</p>
[ { "answer_id": 125243, "author": "thesmallprint", "author_id": 12765, "author_profile": "https://Stackoverflow.com/users/12765", "pm_score": 7, "selected": false, "text": "UPDATE table_name \nSET field = replace(field, 'string-to-find', 'string-that-will-replace-it');\n" }, { "answer_id": 125249, "author": "Joe Skora", "author_id": 14057, "author_profile": "https://Stackoverflow.com/users/14057", "pm_score": 10, "selected": true, "text": "table_name field UPDATE table_name SET field = REPLACE(field, 'foo', 'bar') WHERE INSTR(field, 'foo') > 0;\n" }, { "answer_id": 10460455, "author": "basdog22", "author_id": 190898, "author_profile": "https://Stackoverflow.com/users/190898", "pm_score": 3, "selected": false, "text": "update table_name set `field_name` = replace(`field_name`,'YOUR_OLD_STRING',CONCAT('NEW_STRING',`OTHER_FIELD_VALUE`,'AFTER_IF_NEEDED'));\n" }, { "answer_id": 24629959, "author": "Umesh Patil", "author_id": 1200323, "author_profile": "https://Stackoverflow.com/users/1200323", "pm_score": 4, "selected": false, "text": " UPDATE table SET field = replace(field, text_needs_to_be_replaced, text_required);\n UPDATE student SET student_name = replace(student_name, 'John', 'Mark');\n" }, { "answer_id": 49674425, "author": "Gaspy", "author_id": 498105, "author_profile": "https://Stackoverflow.com/users/498105", "pm_score": 4, "selected": false, "text": "UPDATE table_name SET field = REPLACE(field, 'foo', 'bar') WHERE field LIKE '%foo%';\n INSTR() WHERE" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16536/" ]
125,265
<p>In reading about Perl 6, I see a feature being trumpeted about, where you no longer have to do:</p> <pre><code>return "0 but true"; </code></pre> <p>...but can instead do:</p> <pre><code>return 0 but True; </code></pre> <p>If that's the case, how does truth work in Perl 6? In Perl 5, it was pretty simple: 0, "", and undef are false, everything else is true.</p> <p>What are the rules in Perl 6 when it comes to boolean context?</p>
[ { "answer_id": 125881, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 4, "selected": false, "text": ".true $stuff but True" }, { "answer_id": 23433786, "author": "kovacsbv", "author_id": 1106586, "author_profile": "https://Stackoverflow.com/users/1106586", "pm_score": 1, "selected": false, "text": "> if ( \"0\" ) { say \"True\" } else { say \"False\" }\nFalse\n $ perl -e '$x = \"0\"; $x ||= \"\"; print \">>$x<<\\n\";'\n>><<\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
125,268
<p>Is it possible to chain static methods together using a static class? Say I wanted to do something like this:</p> <pre><code>$value = TestClass::toValue(5)::add(3)::subtract(2)::add(8)::result(); </code></pre> <p>. . . and obviously I would want $value to be assigned the number 14. Is this possible?</p> <p><strong>Update</strong>: It doesn't work (you can't return "self" - it's not an instance!), but this is where my thoughts have taken me:</p> <pre><code>class TestClass { public static $currentValue; public static function toValue($value) { self::$currentValue = $value; } public static function add($value) { self::$currentValue = self::$currentValue + $value; return self; } public static function subtract($value) { self::$currentValue = self::$currentValue - $value; return self; } public static function result() { return self::$value; } } </code></pre> <p>After working that out, I think it would just make more sense to simply work with a class instance rather than trying to chain static function calls (which doesn't look possible, unless the above example could be tweaked somehow).</p>
[ { "answer_id": 125299, "author": "jW.", "author_id": 8880, "author_profile": "https://Stackoverflow.com/users/8880", "pm_score": 0, "selected": false, "text": ":: TestClass::toValue(5) ::add(3) toValue(5) int(5)::add(3)" }, { "answer_id": 125317, "author": "Camilo Díaz Repka", "author_id": 861, "author_profile": "https://Stackoverflow.com/users/861", "pm_score": 4, "selected": false, "text": "$value = TestClass::toValue(5)->add(3)->substract(2)->add(8);\n" }, { "answer_id": 125388, "author": "Mathew Byrne", "author_id": 10942, "author_profile": "https://Stackoverflow.com/users/10942", "pm_score": 7, "selected": true, "text": "class TestClass\n{ \n public static $currentValue;\n\n private static $_instance = null;\n\n private function __construct () { }\n\n public static function getInstance ()\n {\n if (self::$_instance === null) {\n self::$_instance = new self;\n }\n\n return self::$_instance;\n }\n\n public function toValue($value) {\n self::$currentValue = $value;\n return $this;\n }\n\n public function add($value) {\n self::$currentValue = self::$currentValue + $value;\n return $this;\n }\n\n public function subtract($value) {\n self::$currentValue = self::$currentValue - $value;\n return $this;\n }\n\n public function result() {\n return self::$currentValue;\n }\n}\n\n// Example Usage:\n$result = TestClass::getInstance ()\n ->toValue(5)\n ->add(3)\n ->subtract(2)\n ->add(8)\n ->result();\n" }, { "answer_id": 125433, "author": "Phobis", "author_id": 19854, "author_profile": "https://Stackoverflow.com/users/19854", "pm_score": 2, "selected": false, "text": "$value = Math::toValue(5)->add(3)->subtract(2)->add(8)->result();\n $value = Math::eval(Math::value(5)->add(3)->subtract(2)->add(8));\n\nclass Math {\n public $operation;\n public $operationValue;\n public $args;\n public $allOperations = array();\n\n public function __construct($aOperation, $aValue, $theArgs)\n {\n $this->operation = $aOperation;\n $this->operationValue = $aValue;\n $this->args = $theArgs;\n }\n\n public static function eval($math) {\n if(strcasecmp(get_class($math), \"Math\") == 0){\n $newValue = $math->operationValue;\n foreach ($math->allOperations as $operationKey=>$currentOperation) {\n switch($currentOperation->operation){\n case \"add\":\n $newvalue = $currentOperation->operationValue + $currentOperation->args;\n break;\n case \"subtract\":\n $newvalue = $currentOperation->operationValue - $currentOperation->args;\n break;\n }\n }\n return $newValue;\n }\n return null;\n }\n\n public function add($number){\n $math = new Math(\"add\", null, $number);\n $this->allOperations[count($this->allOperations)] &= $math;\n return $this;\n }\n\n public function subtract($number){\n $math = new Math(\"subtract\", null, $number);\n $this->allOperations[count($this->allOperations)] &= $math;\n return $this;\n }\n\n public static function value($number){\n return new Math(\"value\", $number, null);\n }\n }\n" }, { "answer_id": 11338446, "author": "sectus", "author_id": 1503018, "author_profile": "https://Stackoverflow.com/users/1503018", "pm_score": 5, "selected": false, "text": "namespace chaining;\nclass chain\n {\n static public function one()\n {return get_called_class();}\n\n static public function two()\n {return get_called_class();}\n }\n\n${${${${chain::one()} = chain::two()}::one()}::two()}::one();\n" }, { "answer_id": 11907348, "author": "Ariful Islam", "author_id": 559483, "author_profile": "https://Stackoverflow.com/users/559483", "pm_score": 6, "selected": false, "text": "class oop{\n public static $val;\n\n public static function add($var){\n static::$val+=$var;\n return new static;\n }\n\n public static function sub($var){\n static::$val-=$var;\n return new static;\n }\n\n public static function out(){\n return static::$val;\n }\n\n public static function init($var){\n static::$val=$var;\n return new static; \n }\n}\n\necho oop::init(5)->add(2)->out();\n" }, { "answer_id": 18343691, "author": "jsdeveloper", "author_id": 1057013, "author_profile": "https://Stackoverflow.com/users/1057013", "pm_score": 1, "selected": false, "text": "class S\n{\n public static function __callStatic($name,$args)\n {\n echo 'called S::'.$name . '( )<p>';\n return '_t';\n }\n}\n\n$_t='S';\n${${S::X()}::F()}::C();\n" }, { "answer_id": 25623368, "author": "George G", "author_id": 3172092, "author_profile": "https://Stackoverflow.com/users/3172092", "pm_score": 3, "selected": false, "text": "class Calculator\n{ \n public static $value = 0;\n\n protected static $onlyInstance;\n\n protected function __construct () \n {\n // disable creation of public instances \n }\n\n protected static function getself()\n {\n if (static::$onlyInstance === null) \n {\n static::$onlyInstance = new Calculator;\n }\n\n return static::$onlyInstance;\n }\n\n /**\n * add to value\n * @param numeric $num \n * @return \\Calculator\n */\n public static function add($num) \n {\n static::$value += $num;\n return static::getself();\n }\n\n /**\n * substruct\n * @param string $num\n * @return \\Calculator\n */\n public static function subtract($num) \n {\n static::$value -= $num;\n return static::getself();\n }\n\n /**\n * multiple by\n * @param string $num\n * @return \\Calculator\n */\n public static function multiple($num) \n {\n static::$value *= $num;\n return static::getself();\n }\n\n /**\n * devide by\n * @param string $num\n * @return \\Calculator\n */\n public static function devide($num) \n {\n static::$value /= $num;\n return static::getself();\n }\n\n public static function result()\n {\n return static::$value;\n }\n}\n echo Calculator::add(5)\n ->subtract(2)\n ->multiple(2.1)\n ->devide(10)\n ->result();\n" }, { "answer_id": 32343888, "author": "sectus", "author_id": 1503018, "author_profile": "https://Stackoverflow.com/users/1503018", "pm_score": 5, "selected": false, "text": "<?php\n\nabstract class TestClass {\n\n public static $currentValue;\n\n public static function toValue($value) {\n self::$currentValue = $value;\n return __CLASS__;\n }\n\n public static function add($value) {\n self::$currentValue = self::$currentValue + $value;\n return __CLASS__;\n }\n\n public static function subtract($value) {\n self::$currentValue = self::$currentValue - $value;\n return __CLASS__;\n }\n\n public static function result() {\n return self::$currentValue;\n }\n\n}\n\n$value = TestClass::toValue(5)::add(3)::subtract(2)::add(8)::result();\necho $value;\n" }, { "answer_id": 44523323, "author": "Pratik Soni", "author_id": 3357538, "author_profile": "https://Stackoverflow.com/users/3357538", "pm_score": 0, "selected": false, "text": "<?php\n\nnamespace App\\Utils;\n\nuse Session;\n\nuse Illuminate\\Support\\HtmlString;\n\nclass Toaster\n{\n private static $options = [\n\n \"closeButton\" => false,\n\n \"debug\" => false,\n\n \"newestOnTop\" => false,\n\n \"progressBar\" => false,\n\n \"positionClass\" => \"toast-top-right\",\n\n \"preventDuplicates\" => false,\n\n \"onclick\" => null,\n\n \"showDuration\" => \"3000\",\n\n \"hideDuration\" => \"1000\",\n\n \"timeOut\" => \"5000\",\n\n \"extendedTimeOut\" => \"1000\",\n\n \"showEasing\" => \"swing\",\n\n \"hideEasing\" => \"linear\",\n\n \"showMethod\" => \"fadeIn\",\n\n \"hideMethod\" => \"fadeOut\"\n ];\n\n private static $toastType = \"success\";\n\n private static $instance;\n\n private static $title;\n\n private static $message;\n\n private static $toastTypes = [\"success\", \"info\", \"warning\", \"error\"];\n\n public function __construct($options = [])\n {\n self::$options = array_merge(self::$options, $options);\n }\n\n public static function setOptions(array $options = [])\n {\n self::$options = array_merge(self::$options, $options);\n\n return self::getInstance();\n }\n\n public static function setOption($option, $value)\n {\n self::$options[$option] = $value;\n\n return self::getInstance();\n }\n\n private static function getInstance()\n {\n if(empty(self::$instance) || self::$instance === null)\n {\n self::setInstance();\n }\n\n return self::$instance;\n }\n\n private static function setInstance()\n {\n self::$instance = new static();\n }\n\n public static function __callStatic($method, $args)\n {\n if(in_array($method, self::$toastTypes))\n {\n self::$toastType = $method;\n\n return self::getInstance()->initToast($method, $args);\n }\n\n throw new \\Exception(\"Ohh my god. That toast doesn't exists.\");\n }\n\n public function __call($method, $args)\n {\n return self::__callStatic($method, $args);\n }\n\n private function initToast($method, $params=[])\n {\n if(count($params)==2)\n {\n self::$title = $params[0];\n\n self::$message = $params[1];\n }\n elseif(count($params)==1)\n {\n self::$title = ucfirst($method);\n\n self::$message = $params[0];\n }\n\n $toasters = [];\n\n if(Session::has('toasters'))\n {\n $toasters = Session::get('toasters');\n }\n\n $toast = [\n\n \"options\" => self::$options,\n\n \"type\" => self::$toastType,\n\n \"title\" => self::$title,\n\n \"message\" => self::$message\n ];\n\n $toasters[] = $toast;\n\n Session::forget('toasters');\n\n Session::put('toasters', $toasters);\n\n return $this;\n }\n\n public static function renderToasters()\n {\n $toasters = Session::get('toasters');\n\n $string = '';\n\n if(!empty($toasters))\n {\n $string .= '<script type=\"application/javascript\">';\n\n $string .= \"$(function() {\\n\";\n\n foreach ($toasters as $toast)\n {\n $string .= \"\\n toastr.options = \" . json_encode($toast['options'], JSON_PRETTY_PRINT) . \";\";\n\n $string .= \"\\n toastr['{$toast['type']}']('{$toast['message']}', '{$toast['title']}');\";\n }\n\n $string .= \"\\n});\";\n\n $string .= '</script>';\n }\n\n Session::forget('toasters');\n\n return new HtmlString($string);\n }\n}\n Toaster::success(\"Success Message\", \"Success Title\")\n\n ->setOption('showDuration', 5000)\n\n ->warning(\"Warning Message\", \"Warning Title\")\n\n ->error(\"Error Message\");\n" }, { "answer_id": 49113525, "author": "Evehne", "author_id": 9021574, "author_profile": "https://Stackoverflow.com/users/9021574", "pm_score": -1, "selected": false, "text": "final class TestClass {\n public static $currentValue;\n\n public static function toValue($value) {\n self::$currentValue = $value;\n return __CLASS__;\n }\n\n public static function add($value) {\n self::$currentValue = self::$currentValue + $value;\n return __CLASS__;\n }\n\n public static function subtract($value) {\n self::$currentValue = self::$currentValue - $value;\n return __CLASS__;\n }\n\n public static function result() {\n return self::$currentValue;\n }\n}\n $value = TestClass::toValue(5)::add(3)::subtract(2)::add(8)::result();\n\nvar_dump($value);\n int(14)\n" }, { "answer_id": 52912172, "author": "sanmai", "author_id": 93540, "author_profile": "https://Stackoverflow.com/users/93540", "pm_score": 2, "selected": false, "text": "$object::method() return self final class TestClass {\n public static $currentValue;\n\n public static function toValue($value) {\n self::$currentValue = $value;\n return new static();\n }\n\n public static function add($value) {\n self::$currentValue = self::$currentValue + $value;\n return new static();\n }\n\n public static function subtract($value) {\n self::$currentValue = self::$currentValue - $value;\n return new static();\n }\n\n public static function result() {\n return self::$currentValue;\n }\n}\n\n$value = TestClass::toValue(5)::add(3)::subtract(2)::add(8)::result();\n\nvar_dump($value);\n int(14) __CLASS__" }, { "answer_id": 54139898, "author": "boctulus", "author_id": 980631, "author_profile": "https://Stackoverflow.com/users/980631", "pm_score": 0, "selected": false, "text": "<?php\n\n\nclass Response\n{\n static protected $headers = [];\n static protected $http_code = 200;\n static protected $http_code_msg = '';\n static protected $instance = NULL;\n\n\n protected function __construct() { }\n\n static function getInstance(){\n if(static::$instance == NULL){\n static::$instance = new static();\n }\n return static::$instance;\n }\n\n public function addHeaders(array $headers)\n {\n static::$headers = $headers;\n return static::getInstance();\n }\n\n public function addHeader(string $header)\n {\n static::$headers[] = $header;\n return static::getInstance();\n }\n\n public function code(int $http_code, string $msg = NULL)\n {\n static::$http_code_msg = $msg;\n static::$http_code = $http_code;\n return static::getInstance();\n }\n\n public function send($data, int $http_code = NULL){\n $http_code = $http_code != NULL ? $http_code : static::$http_code;\n\n if ($http_code != NULL)\n header(trim(\"HTTP/1.0 \".$http_code.' '.static::$http_code_msg));\n\n if (is_array($data) || is_object($data))\n $data = json_encode($data);\n\n echo $data; \n exit(); \n }\n\n function sendError(string $msg_error, int $http_code = null){\n $this->send(['error' => $msg_error], $http_code);\n }\n}\n Response::getInstance()->code(400)->sendError(\"Lacks id in request\");\n" }, { "answer_id": 59297989, "author": "kdion4891", "author_id": 11962169, "author_profile": "https://Stackoverflow.com/users/11962169", "pm_score": 3, "selected": false, "text": "class OopClass\n{\n public $first;\n public $second;\n public $third;\n\n public static function make($first)\n {\n return new OopClass($first);\n }\n\n public function __construct($first)\n {\n $this->first = $first;\n }\n\n public function second($second)\n {\n $this->second = $second;\n return $this;\n }\n\n public function third($third)\n {\n $this->third = $third;\n return $this;\n }\n}\n OopClass::make('Hello')->second('To')->third('World');\n" }, { "answer_id": 64444897, "author": "Dan", "author_id": 6394404, "author_profile": "https://Stackoverflow.com/users/6394404", "pm_score": 0, "selected": false, "text": "getInstance class TestClass\n{\n private $result = 0;\n\n public function __call($method, $args)\n {\n return $this->call($method, $args);\n }\n\n public static function __callStatic($method, $args)\n {\n return (new static())->call($method, $args);\n }\n\n private function call($method, $args)\n {\n if (! method_exists($this , '_' . $method)) {\n throw new Exception('Call undefined method ' . $method);\n }\n\n return $this->{'_' . $method}(...$args);\n }\n\n private function _add($num)\n {\n $this->result += $num;\n\n return $this;\n }\n\n private function _subtract($num)\n {\n $this->result -= $num;\n\n return $this;\n }\n\n public function result()\n {\n return $this->result;\n }\n}\n $res1 = TestClass::add(5)\n ->add(3)\n ->subtract(2)\n ->add(8)\n ->result();\n\necho $res1 . PHP_EOL; // 14\n\n$res2 = TestClass::subtract(1)->add(10)->result();\necho $res2 . PHP_EOL; // 9\n" }, { "answer_id": 71172373, "author": "Samir Mammadhasanov", "author_id": 11387497, "author_profile": "https://Stackoverflow.com/users/11387497", "pm_score": 0, "selected": false, "text": "ExampleClass::withBanners()->withoutTranslations()->collection($values)\n new static(self::class); public static function withoutTranslations(): self\n{\n self::$withoutTranslations = true;\n \n return new static(self::class);\n}\n\npublic static function withBanners(): self\n{\n return new static(self::class);\n}\n\npublic static function collection(values): self\n{\n return $values;\n}\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291/" ]
125,272
<p>I'm relatively new to Mercurial and my team is trying it out right now as a replacement for Subversion. </p> <p>How can I commit and push a single file out to another repository while leaving other modifications in my working directory uncommitted (or at least not pushed to the other repository)?</p> <p>This happens for us with database migrations. We want to commit the migration to source control so a DBA can view and edit it while we're working on the code modifications to go along with that database migration. The changes aren't yet ready to go so we don't want to push all of them out.</p> <p>In subversion, I'd simply do:</p> <pre><code>svn add my_migration.sql # commit only the migration, but not the other files I'm working on svn commit -m "migration notes" my_mygration.sql </code></pre> <p>and continue working locally.</p> <p>This doesn't work with mercurial as when I'm pushing it out to the other repository, if there are changes to it that I haven't pulled down, it wants me to pull them down, merge them, and commit that merge to the repository. Commits after a merge don't allow you to omit files so it forces you to commit everything in your local repository.</p> <p>The easiest thing that I can figure out is to commit the file to my local repository, clone my local repository, fetch any new changes from the actual repository, merge them and commit that merge, and them push my changes out.</p> <pre><code>hg add my_migration.sql hg commit -m "migration notes" my_migration.sql cd .. hg clone project project-clone cd project-clone hg fetch http://hg/project hg push http://hg/project </code></pre> <p>This works, but it feels like I'm missing something easier, some way to tell mercurial to ignore the files already in my working directory, just do the merge and send the files along. I suspect mercurial queues can do this, but I don't fully grok mq yet.</p>
[ { "answer_id": 125301, "author": "Josh Matthews", "author_id": 3830, "author_profile": "https://Stackoverflow.com/users/3830", "pm_score": 6, "selected": true, "text": "hg shelve hg unshelve hg clone http://freehg.org/u/tksoh/hgshelve/ hgshelve\n [extensions] \nhgshelve=/Users/ted/Documents/workspace/hgshelve/hgshelve.py\n" }, { "answer_id": 569429, "author": "Kobold", "author_id": 36092, "author_profile": "https://Stackoverflow.com/users/36092", "pm_score": 3, "selected": false, "text": "$ hg qnew -m \"migration notes\" -f migration my_migration.sql\n$ hg qnew -f working-code\n# make some changes to your code\n$ hg qrefresh # update the patch with the changes you just made\n$ hg qfinish -a # turn all the applied patches into normal hg commits\n # create a patch called migration containing your migration\n$ hg qnew -m \"migration notes\" -f migration.patch my_migration.sql\n$ hg qseries -v # the current state of the patch queue, A means applied\n0 A migration.patch\n$ hg qnew -f working-code.patch # put the rest of the code in a patch\n$ hg qseries -v\n0 A migration.patch\n1 A working-code.patch\n qseries $ hg qtop # show the patch we're currently editing\nworking-code.patch\n$ ...hack, hack, hack...\n$ hg diff # show the changes that have not been incorporated into the patch\nblah, blah\n$ hg qrefresh # update the patch with the changes you just made\n$ hg qdiff # show the top patch's diff\n hg qpop -a $ hg qpop # unapply the top patch, U means unapplied\n$ hg qseries -v\n0 A migration.patch\n1 U working-code.patch\n$ hg qtop\nmigration.patch\n$ hg qpop\n$ hg qseries -v\n0 U migration.patch\n1 U working-code.patch\n hg fetch $ hg qpush # put the first patch back on\n$ hg qseries -v\n0 A migration.patch\n1 U working-code.patch\n$ hg qfinish -a # turn all the applied patches into normal hg commits\n$ hg qseries -v\n0 U working-code.patch\n$ hg out\nmigration.patch commit info... blah, blah\n$ hg push # push out your changes\n $ hg qpush\n$ hg qseries -v\n0 A working-code.patch\n$ hg export qtip > temp.diff\n$ rm -r .hg/patches # get rid of mq from the repository entirely\n$ hg import --no-commit temp.diff # apply the changes to the working directory\n$ rm temp.diff\n mq" }, { "answer_id": 3239782, "author": "Ted Naleid", "author_id": 8912, "author_profile": "https://Stackoverflow.com/users/8912", "pm_score": 5, "selected": false, "text": "hg commit -m \"commit message\" filename\n hg push\n hg push --rev .\n" }, { "answer_id": 28309560, "author": "Shweta", "author_id": 2242019, "author_profile": "https://Stackoverflow.com/users/2242019", "pm_score": 2, "selected": false, "text": " hg commit -m \"commit message\" filename\n hg diff > changes.patch\n hg revert --all\n hg pull -u\nhg merge\nhg commit -m \"local merge\"\n hg import --no-commit changes.patch\n" }, { "answer_id": 47931757, "author": "studgeek", "author_id": 255961, "author_profile": "https://Stackoverflow.com/users/255961", "pm_score": 1, "selected": false, "text": "hg commit -i --interactive hg push hg commit --interactive" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8912/" ]
125,281
<p>Given a string file path such as <code>/foo/fizzbuzz.bar</code>, how would I use bash to extract just the <code>fizzbuzz</code> portion of said string?</p>
[ { "answer_id": 125287, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 8, "selected": false, "text": "NAME=\"$(basename /foo/fizzbuzz.bar .bar)\"\n .bar NAME=fizzbuzz" }, { "answer_id": 125292, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": false, "text": "~$ x=\"/foo/bar/fizzbuzz.bar.quux.zoom\"; \n~$ y=${x/\\/*\\//}; \n~$ echo ${y/.*/}; \nfizzbuzz\n" }, { "answer_id": 125294, "author": "mopoke", "author_id": 14054, "author_profile": "https://Stackoverflow.com/users/14054", "pm_score": 2, "selected": false, "text": "perl -pe 's/\\..*$//;s{^.*/}{}'\n" }, { "answer_id": 125298, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 4, "selected": false, "text": "mystring=/foo/fizzbuzz.bar\necho basename: $(basename \"${mystring}\")\necho basename + remove .bar: $(basename \"${mystring}\" .bar)\necho dirname: $(dirname \"${mystring}\")\n basename: fizzbuzz.bar\nbasename + remove .bar: fizzbuzz\ndirname: /foo\n" }, { "answer_id": 125340, "author": "Zan Lynx", "author_id": 13422, "author_profile": "https://Stackoverflow.com/users/13422", "pm_score": 10, "selected": true, "text": "$ x=\"/foo/fizzbuzz.bar\"\n$ y=${x%.bar}\n$ echo ${y##*/}\nfizzbuzz\n ${x%.bar} ${x%.*} ${x%%.*} $ x=\"/foo/fizzbuzz.bar.quux\"\n$ y=${x%.*}\n$ echo $y\n/foo/fizzbuzz.bar\n$ y=${x%%.*}\n$ echo $y\n/foo/fizzbuzz\n ${parameter%word} ${parameter%%word}" }, { "answer_id": 125511, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 3, "selected": false, "text": "basename \n #!/usr/bin/perl\n $fullname = $ARGV[0];\n ($path,$name) = $fullname =~ /^(.*[^\\\\]\\/)*(.*)$/;\n ($basename,$extension) = $name =~ /^(.*)(\\.[^.]*)$/;\n print $basename . \"\\n\";\n" }, { "answer_id": 126534, "author": "nymacro", "author_id": 10499, "author_profile": "https://Stackoverflow.com/users/10499", "pm_score": 2, "selected": false, "text": "echo '/foo/fizzbuzz.bar' | sed 's|.*\\/\\([^\\.]*\\)\\(\\..*\\)$|\\1|g'\n" }, { "answer_id": 3075186, "author": "mivk", "author_id": 111036, "author_profile": "https://Stackoverflow.com/users/111036", "pm_score": 2, "selected": false, "text": "$ echo some.file.with.dots | perl -pe 's/\\..*$//;s{^.*/}{}'\nsome\n $ echo some.file.with.dots | perl -pe 's/(.*)\\..*$/$1/;s{^.*/}{}'\nsome.file.with\n y=${x%.*} basename \"$x\" .ext" }, { "answer_id": 23018588, "author": "mike", "author_id": 3524685, "author_profile": "https://Stackoverflow.com/users/3524685", "pm_score": 4, "selected": false, "text": "for file in *; do\n ext=${file##*.}\n fname=`basename $file $ext`\n\n # Do things with $fname\ndone;\n basename" }, { "answer_id": 23497364, "author": "Param", "author_id": 2034354, "author_profile": "https://Stackoverflow.com/users/2034354", "pm_score": 6, "selected": false, "text": "path=/foo/bar/bim/baz/file.gif\n\nfile=${path##*/} \n#$file is now 'file.gif'\n base=${file%.*}\n#${base} is now 'file'.\n" }, { "answer_id": 25411974, "author": "c.gutierrez", "author_id": 1546381, "author_profile": "https://Stackoverflow.com/users/1546381", "pm_score": 1, "selected": false, "text": "$ x=\"/foo/fizzbuzz.bar.quux\"\n$ y=(`basename ${x%%.*}`)\n$ echo $y\nfizzbuzz\n" }, { "answer_id": 52978500, "author": "Benjamin W.", "author_id": 3266847, "author_profile": "https://Stackoverflow.com/users/3266847", "pm_score": 3, "selected": false, "text": "basename string [suffix] basename /foo/fizzbuzz.bar .bar\n basename basename -s .bar /foo/fizzbuzz.bar\n -s -a $ basename -s .bar /foo/fizzbuzz.bar /baz/foobar.bar\nfizzbuzz\nfoobar\n -z ls $ ls has*\n'has'$'\\n''newline.bar' 'has space.bar' 'has*.bar'\n $ readarray -d $'\\0' arr < <(basename -zs .bar has*)\n$ declare -p arr\ndeclare -a arr=([0]=$'has\\nnewline' [1]=\"has space\" [2]=\"has*\")\n readarray -d while IFS= read -r -d '' fname; do arr+=(\"$fname\"); done < <(basename -zs .bar has*)\n" }, { "answer_id": 68437453, "author": "sblive", "author_id": 14295103, "author_profile": "https://Stackoverflow.com/users/14295103", "pm_score": -1, "selected": false, "text": "mv *<PATTERN>.jar \"$(basename *<PATTERN>.jar <PATTERN>.jar).jar\"\n -SNAPSHOT mv *-SNAPSHOT.jar \"$(basename *-SNAPSHOT.jar -SNAPSHOT.jar).jar\"\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1512/" ]
125,306
<p>I'm writing an iPhone app that takes a photo and then uploads it to a server. How do I upload a photo to a server with Cocoa? I suppose I use NSUrl somewhere.</p> <p>Thanks!</p>
[ { "answer_id": 136516, "author": "Jon Gilkison", "author_id": 22428, "author_profile": "https://Stackoverflow.com/users/22428", "pm_score": 6, "selected": false, "text": "@interface EPUploader : NSObject {\n NSURL *serverURL;\n NSString *filePath;\n id delegate;\n SEL doneSelector;\n SEL errorSelector;\n\n BOOL uploadDidSucceed;\n}\n\n- (id)initWithURL: (NSURL *)serverURL \n filePath: (NSString *)filePath \n delegate: (id)delegate \n doneSelector: (SEL)doneSelector \n errorSelector: (SEL)errorSelector;\n\n- (NSString *)filePath;\n\n@end\n #import \"EPUploader.h\"\n#import <zlib.h>\n\nstatic NSString * const BOUNDRY = @\"0xKhTmLbOuNdArY\";\nstatic NSString * const FORM_FLE_INPUT = @\"uploaded\";\n\n#define ASSERT(x) NSAssert(x, @\"\")\n\n@interface EPUploader (Private)\n\n- (void)upload;\n- (NSURLRequest *)postRequestWithURL: (NSURL *)url\n boundry: (NSString *)boundry\n data: (NSData *)data;\n\n- (NSData *)compress: (NSData *)data;\n- (void)uploadSucceeded: (BOOL)success;\n- (void)connectionDidFinishLoading:(NSURLConnection *)connection;\n\n@end\n\n@implementation EPUploader\n\n\n\n/*\n *-----------------------------------------------------------------------------\n *\n * -[Uploader initWithURL:filePath:delegate:doneSelector:errorSelector:] --\n *\n * Initializer. Kicks off the upload. Note that upload will happen on a\n * separate thread.\n *\n * Results:\n * An instance of Uploader.\n *\n * Side effects:\n * None\n *\n *-----------------------------------------------------------------------------\n */\n\n- (id)initWithURL: (NSURL *)aServerURL // IN\n filePath: (NSString *)aFilePath // IN\n delegate: (id)aDelegate // IN\n doneSelector: (SEL)aDoneSelector // IN\n errorSelector: (SEL)anErrorSelector // IN\n{\n if ((self = [super init])) {\n ASSERT(aServerURL);\n ASSERT(aFilePath);\n ASSERT(aDelegate);\n ASSERT(aDoneSelector);\n ASSERT(anErrorSelector);\n\n serverURL = [aServerURL retain];\n filePath = [aFilePath retain];\n delegate = [aDelegate retain];\n doneSelector = aDoneSelector;\n errorSelector = anErrorSelector;\n\n [self upload];\n }\n return self;\n}\n\n\n/*\n *-----------------------------------------------------------------------------\n *\n * -[Uploader dealloc] --\n *\n * Destructor.\n *\n * Results:\n * None\n *\n * Side effects:\n * None\n *\n *-----------------------------------------------------------------------------\n */\n\n- (void)dealloc\n{\n [serverURL release];\n serverURL = nil;\n [filePath release];\n filePath = nil;\n [delegate release];\n delegate = nil;\n doneSelector = NULL;\n errorSelector = NULL;\n\n [super dealloc];\n}\n\n\n/*\n *-----------------------------------------------------------------------------\n *\n * -[Uploader filePath] --\n *\n * Gets the path of the file this object is uploading.\n *\n * Results:\n * Path to the upload file.\n *\n * Side effects:\n * None\n *\n *-----------------------------------------------------------------------------\n */\n\n- (NSString *)filePath\n{\n return filePath;\n}\n\n\n@end // Uploader\n\n\n@implementation EPUploader (Private)\n\n\n/*\n *-----------------------------------------------------------------------------\n *\n * -[Uploader(Private) upload] --\n *\n * Uploads the given file. The file is compressed before beign uploaded.\n * The data is uploaded using an HTTP POST command.\n *\n * Results:\n * None\n *\n * Side effects:\n * None\n *\n *-----------------------------------------------------------------------------\n */\n\n- (void)upload\n{\n NSData *data = [NSData dataWithContentsOfFile:filePath];\n ASSERT(data);\n if (!data) {\n [self uploadSucceeded:NO];\n return;\n }\n if ([data length] == 0) {\n // There's no data, treat this the same as no file.\n [self uploadSucceeded:YES];\n return;\n }\n\n// NSData *compressedData = [self compress:data];\n// ASSERT(compressedData && [compressedData length] != 0);\n// if (!compressedData || [compressedData length] == 0) {\n// [self uploadSucceeded:NO];\n// return;\n// }\n\n NSURLRequest *urlRequest = [self postRequestWithURL:serverURL\n boundry:BOUNDRY\n data:data];\n if (!urlRequest) {\n [self uploadSucceeded:NO];\n return;\n }\n\n NSURLConnection * connection =\n [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];\n if (!connection) {\n [self uploadSucceeded:NO];\n }\n\n // Now wait for the URL connection to call us back.\n}\n\n\n/*\n *-----------------------------------------------------------------------------\n *\n * -[Uploader(Private) postRequestWithURL:boundry:data:] --\n *\n * Creates a HTML POST request.\n *\n * Results:\n * The HTML POST request.\n *\n * Side effects:\n * None\n *\n *-----------------------------------------------------------------------------\n */\n\n- (NSURLRequest *)postRequestWithURL: (NSURL *)url // IN\n boundry: (NSString *)boundry // IN\n data: (NSData *)data // IN\n{\n // from http://www.cocoadev.com/index.pl?HTTPFileUpload\n NSMutableURLRequest *urlRequest =\n [NSMutableURLRequest requestWithURL:url];\n [urlRequest setHTTPMethod:@\"POST\"];\n [urlRequest setValue:\n [NSString stringWithFormat:@\"multipart/form-data; boundary=%@\", boundry]\n forHTTPHeaderField:@\"Content-Type\"];\n\n NSMutableData *postData =\n [NSMutableData dataWithCapacity:[data length] + 512];\n [postData appendData:\n [[NSString stringWithFormat:@\"--%@\\r\\n\", boundry] dataUsingEncoding:NSUTF8StringEncoding]];\n [postData appendData:\n [[NSString stringWithFormat:\n @\"Content-Disposition: form-data; name=\\\"%@\\\"; filename=\\\"file.bin\\\"\\r\\n\\r\\n\", FORM_FLE_INPUT]\n dataUsingEncoding:NSUTF8StringEncoding]];\n [postData appendData:data];\n [postData appendData:\n [[NSString stringWithFormat:@\"\\r\\n--%@--\\r\\n\", boundry] dataUsingEncoding:NSUTF8StringEncoding]];\n\n [urlRequest setHTTPBody:postData];\n return urlRequest;\n}\n\n/*\n *-----------------------------------------------------------------------------\n *\n * -[Uploader(Private) compress:] --\n *\n * Uses zlib to compress the given data.\n *\n * Results:\n * The compressed data as a NSData object.\n *\n * Side effects:\n * None\n *\n *-----------------------------------------------------------------------------\n */\n\n- (NSData *)compress: (NSData *)data // IN\n{\n if (!data || [data length] == 0)\n return nil;\n\n // zlib compress doc says destSize must be 1% + 12 bytes greater than source.\n uLong destSize = [data length] * 1.001 + 12;\n NSMutableData *destData = [NSMutableData dataWithLength:destSize];\n\n int error = compress([destData mutableBytes],\n &destSize,\n [data bytes],\n [data length]);\n if (error != Z_OK) {\n NSLog(@\"%s: self:0x%p, zlib error on compress:%d\\n\",__func__, self, error);\n return nil;\n }\n\n [destData setLength:destSize];\n return destData;\n}\n\n\n/*\n *-----------------------------------------------------------------------------\n *\n * -[Uploader(Private) uploadSucceeded:] --\n *\n * Used to notify the delegate that the upload did or did not succeed.\n *\n * Results:\n * None\n *\n * Side effects:\n * None\n *\n *-----------------------------------------------------------------------------\n */\n\n- (void)uploadSucceeded: (BOOL)success // IN\n{\n [delegate performSelector:success ? doneSelector : errorSelector\n withObject:self];\n}\n\n\n/*\n *-----------------------------------------------------------------------------\n *\n * -[Uploader(Private) connectionDidFinishLoading:] --\n *\n * Called when the upload is complete. We judge the success of the upload\n * based on the reply we get from the server.\n *\n * Results:\n * None\n *\n * Side effects:\n * None\n *\n *-----------------------------------------------------------------------------\n */\n\n- (void)connectionDidFinishLoading:(NSURLConnection *)connection // IN\n{\n NSLog(@\"%s: self:0x%p\\n\", __func__, self);\n [connection release];\n [self uploadSucceeded:uploadDidSucceed];\n}\n\n\n/*\n *-----------------------------------------------------------------------------\n *\n * -[Uploader(Private) connection:didFailWithError:] --\n *\n * Called when the upload failed (probably due to a lack of network\n * connection).\n *\n * Results:\n * None\n *\n * Side effects:\n * None\n *\n *-----------------------------------------------------------------------------\n */\n\n- (void)connection:(NSURLConnection *)connection // IN\n didFailWithError:(NSError *)error // IN\n{\n NSLog(@\"%s: self:0x%p, connection error:%s\\n\",\n __func__, self, [[error description] UTF8String]);\n [connection release];\n [self uploadSucceeded:NO];\n}\n\n\n/*\n *-----------------------------------------------------------------------------\n *\n * -[Uploader(Private) connection:didReceiveResponse:] --\n *\n * Called as we get responses from the server.\n *\n * Results:\n * None\n *\n * Side effects:\n * None\n *\n *-----------------------------------------------------------------------------\n */\n\n-(void) connection:(NSURLConnection *)connection // IN\n didReceiveResponse:(NSURLResponse *)response // IN\n{\n NSLog(@\"%s: self:0x%p\\n\", __func__, self);\n}\n\n\n/*\n *-----------------------------------------------------------------------------\n *\n * -[Uploader(Private) connection:didReceiveData:] --\n *\n * Called when we have data from the server. We expect the server to reply\n * with a \"YES\" if the upload succeeded or \"NO\" if it did not.\n *\n * Results:\n * None\n *\n * Side effects:\n * None\n *\n *-----------------------------------------------------------------------------\n */\n\n- (void)connection:(NSURLConnection *)connection // IN\n didReceiveData:(NSData *)data // IN\n{\n NSLog(@\"%s: self:0x%p\\n\", __func__, self);\n\n NSString *reply = [[[NSString alloc] initWithData:data\n encoding:NSUTF8StringEncoding]\n autorelease];\n NSLog(@\"%s: data: %s\\n\", __func__, [reply UTF8String]);\n\n if ([reply hasPrefix:@\"YES\"]) {\n uploadDidSucceed = YES;\n }\n}\n\n\n@end\n [[EPUploader alloc] initWithURL:[NSURL URLWithString:@\"http://yourserver.com/uploadDB.php\"]\n filePath:@\"path/to/some/file\"\n delegate:self\n doneSelector:@selector(onUploadDone:)\n errorSelector:@selector(onUploadError:)]; \n" }, { "answer_id": 6521021, "author": "Kapil Mandlik", "author_id": 758960, "author_profile": "https://Stackoverflow.com/users/758960", "pm_score": 3, "selected": false, "text": "'ImageUploadURL' NSDateFormatter *format = [[NSDateFormatter alloc] init];\n [format setDateFormat:@\"yyyyMMddHHmmss\"];\n\nNSDate *now = [[NSDate alloc] init];\n\nNSString *imageName = [NSString stringWithFormat:@\"Image_%@\", [format stringFromDate:now]];\n\n[now release];\n[format release];\n\nNSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];\n[request setURL:[NSURL URLWithString:ImageUploadURL]];\n[request setHTTPMethod:@\"POST\"];\n\n/*\n Set Header and content type of your request.\n */\nNSString *boundary = [NSString stringWithString:@\"---------------------------Boundary Line---------------------------\"];\nNSString *contentType = [NSString stringWithFormat:@\"multipart/form-data; boundary=%@\",boundary];\n[request addValue:contentType forHTTPHeaderField: @\"Content-Type\"];\n\n/*\n now lets create the body of the request.\n */\nNSMutableData *body = [NSMutableData data];\n[body appendData:[[NSString stringWithFormat:@\"\\r\\n--%@\\r\\n\",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; \n[body appendData:[[NSString stringWithFormat:@\"Content-Disposition: form-data; name=\\\"userfile\\\"; filename=\\\"%@.jpg\\\"\\r\\n\", imageName] dataUsingEncoding:NSUTF8StringEncoding]];\n[body appendData:[[NSString stringWithString:@\"Content-Type: application/octet-stream\\r\\n\\r\\n\"] dataUsingEncoding:NSUTF8StringEncoding]];\n[body appendData:[NSData dataWithData:UIImageJPEGRepresentation(image, 90)]];\n[body appendData:[[NSString stringWithFormat:@\"\\r\\n--%@--\\r\\n\",boundary] dataUsingEncoding:NSUTF8StringEncoding]];\n[body appendData:[[NSString stringWithFormat:@\"geotag=%@&\", [self _currentLocationMetadata]] dataUsingEncoding:NSUTF8StringEncoding]];\n[body appendData:[[NSString stringWithFormat:@\"\\r\\n--%@--\\r\\n\",boundary] dataUsingEncoding:NSUTF8StringEncoding]];\n\n// set body with request.\n[request setHTTPBody:body];\n[request addValue:[NSString stringWithFormat:@\"%d\", [body length]] forHTTPHeaderField:@\"Content-Length\"];\n\n// now lets make the connection to the web\n[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];\n" }, { "answer_id": 10514454, "author": "sinh99", "author_id": 694561, "author_profile": "https://Stackoverflow.com/users/694561", "pm_score": 2, "selected": false, "text": "- (void) uploadImage :(NSString *) strRequest\n{\nif([appdel checkNetwork]==TRUE)\n{\n\nNSString *urlString =[NSString stringWithFormat:@\"Enter Url.........\"];\n NSLog(@\"Upload %@\",urlString);\n// setting up the request object now\n\nisUploadImage=TRUE;\ntotalsize=[[strRequest dataUsingEncoding:NSUTF8StringEncoding]length];\n\nNSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];\n[request setURL:[NSURL URLWithString:urlString]];\n[request setHTTPMethod:@\"POST\"];\n\nNSString *boundary = [NSString stringWithString:@\"_1_19330907_1317415362628\"];\nNSString *contentType = [NSString stringWithFormat:@\"multipart/mixed; boundary=%@\",boundary];\n[request setValue:contentType forHTTPHeaderField: @\"Content-Type\"];\n[request setValue:@\"text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2\" forHTTPHeaderField:@\"Accept\"];\n[request setValue:@\"2667\" forHTTPHeaderField:@\"Content-Length\"];\n\n\n/*\n now lets create the body of the post\n */\nNSMutableData *body = [NSMutableData data];\n[body appendData:[[NSString stringWithFormat:@\"\\r\\n--%@\\r\\n\",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; \n\n\n[body appendData:[[NSString stringWithString:@\"Content-Type: application/json\\r\\n\\r\\n\"] dataUsingEncoding:NSUTF8StringEncoding]];\n\n//[body appendData:[NSData dataWithData:imageData]];\n\n[body appendData:[strRequest dataUsingEncoding:NSUTF8StringEncoding]];\n\n[body appendData:[[NSString stringWithFormat:@\"\\r\\n--%@--\\r\\n\",boundary] dataUsingEncoding:NSUTF8StringEncoding]];\n\n\n// setting the body of the post to the reqeust\n[request setHTTPBody:body];\n\n\n\ntheConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];\nif (theConnection) \n webData = [[NSMutableData data] retain];\nelse \n NSLog(@\"No Connection\"); \n}\n\n}\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
125,313
<p>I'm running programs from Eclipse (on Windows) that eat a lot of CPU time. To avoid bogging down my whole machine, I set the priority to Low with the Task Manager. However, this is a cumbersome manual process. Is there a way Eclipse can set this priority automatically?</p> <p>EDIT: I realized that each particular launcher (Java, Python etc) has its own configuration method, so I will restrict this question to the Java domain, which is what I need most.</p>
[ { "answer_id": 129536, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 2, "selected": false, "text": "start /low start /low" }, { "answer_id": 41046469, "author": "George Forman", "author_id": 2069400, "author_profile": "https://Stackoverflow.com/users/2069400", "pm_score": 3, "selected": false, "text": "wmic process where name=\"javaw.exe\" CALL setpriority \"below normal\" public static void lowerMyProcessPriority() throws IOException {\n String pid = ManagementFactory.getRuntimeMXBean().getName();\n int p = pid.indexOf(\"@\");\n if (p > 0) pid = pid.substring(0,p);\n String cmd = \"wmic process where processid=<pid> CALL setpriority\".replace(\"<pid>\", pid);\n List<String> ls = new ArrayList<>(Arrays.asList(cmd.split(\" \")));\n ls.add(\"\\\"below normal\\\"\");\n ProcessBuilder pb = new ProcessBuilder(ls);\n pb.start();\n}\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9871/" ]
125,314
<p>Selenium Remote Control has a method of "get_html_source", which returns the source of the current page as a string.</p> <p>AFAIK, this method works in all cases in Firefox and Safari. But when it's invoked in Internet Explorer, it returns an incorrect source.</p> <p>Does anyone know if this is a bug with Selenium or Internet Explorer, and if there's a fix?</p>
[ { "answer_id": 125361, "author": "Alan Storm", "author_id": 4668, "author_profile": "https://Stackoverflow.com/users/4668", "pm_score": 2, "selected": false, "text": "onload=\"var oArea = document.createElement('textarea');oArea.rows=80;oArea.cols=80;oArea.value = document.getElementsByTagName('html')[0].innerHTML;document.getElementsByTagName('body')[0].appendChild(oArea)\"\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21479/" ]
125,319
<p>I have been running <a href="http://en.wikipedia.org/wiki/StyleCop" rel="noreferrer">StyleCop</a> over some C# code, and it keeps reporting that my <code>using</code> directives should be inside the namespace.</p> <p>Is there a technical reason for putting the <code>using</code> directives inside instead of outside the namespace?</p>
[ { "answer_id": 125330, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 8, "selected": false, "text": "using ThisNamespace.IsImported.InAllNamespaces.Here;\n\nnamespace Namespace1\n{ \n using ThisNamespace.IsImported.InNamespace1.AndNamespace2;\n\n namespace Namespace2\n { \n using ThisNamespace.IsImported.InJustNamespace2;\n } \n}\n\nnamespace Namespace3\n{ \n using ThisNamespace.IsImported.InJustNamespace3;\n}\n" }, { "answer_id": 151560, "author": "Charlie", "author_id": 18529, "author_profile": "https://Stackoverflow.com/users/18529", "pm_score": 12, "selected": true, "text": "// File1.cs\nusing System;\nnamespace Outer.Inner\n{\n class Foo\n {\n static void Bar()\n {\n double d = Math.PI;\n }\n }\n}\n // File2.cs\nnamespace Outer\n{\n class Math\n {\n }\n}\n Outer using Outer.Math System.Math Outer.Math PI using // File1b.cs\nnamespace Outer.Inner\n{\n using System;\n class Foo\n {\n static void Bar()\n {\n double d = Math.PI;\n }\n }\n}\n System Outer System.Math Math System Foo Outer Outer.Inner Outer.Math using using" }, { "answer_id": 1422218, "author": "JaredCacurak", "author_id": 16254, "author_profile": "https://Stackoverflow.com/users/16254", "pm_score": 6, "selected": false, "text": "using System;\nusing Guid = System.Guid;\n\nnamespace Microsoft.Sample\n{\n public class Program\n {\n }\n}\n namespace Microsoft.Sample\n{\n using System;\n using Guid = System.Guid;\n\n public class Program\n {\n }\n}\n namespace Microsoft.Sample\n{\n using Guid = System.Guid;\n public class Guid\n {\n public Guid(string s)\n {\n }\n }\n\n public class Program\n {\n public static void Main(string[] args)\n {\n Guid g = new Guid(\"hello\");\n }\n }\n}\n Guid g = new Guid(\"hello\");" }, { "answer_id": 12826266, "author": "Neo", "author_id": 197591, "author_profile": "https://Stackoverflow.com/users/197591", "pm_score": 5, "selected": false, "text": "using namespace MyNamespace\n{\n using System;\n using MyAlias = System.DateTime;\n\n class MyClass\n {\n }\n}\n using System;\n\nnamespace MyNamespace\n{\n using MyAlias = DateTime;\n\n class MyClass\n {\n }\n}\n using MyAlias = Tuple<Expression<Func<DateTime, object>>, Expression<Func<TimeSpan, object>>>;\n using using MyAlias = System.Tuple<System.Linq.Expressions.Expression<System.Func<System.DateTime, object>>, System.Linq.Expressions.Expression<System.Func<System.TimeSpan, object>>>;\n" }, { "answer_id": 16092975, "author": "Jeppe Stig Nielsen", "author_id": 1336654, "author_profile": "https://Stackoverflow.com/users/1336654", "pm_score": 9, "selected": false, "text": "namespace MyCorp.TheProduct.SomeModule.Utilities\n{\n ...\n}\n namespace MyCorp\n{\n namespace TheProduct\n {\n namespace SomeModule\n {\n namespace Utilities\n {\n ...\n }\n }\n }\n}\n using using using System;\nusing System.Collections.Generic;\nusing System.Linq;\n//using MyCorp.TheProduct; <-- uncommenting this would change nothing\nusing MyCorp.TheProduct.OtherModule;\nusing MyCorp.TheProduct.OtherModule.Integration;\nusing ThirdParty;\n\nnamespace MyCorp.TheProduct.SomeModule.Utilities\n{\n class C\n {\n Ambiguous a;\n }\n}\n Ambiguous C MyCorp.TheProduct.SomeModule.Utilities MyCorp.TheProduct.SomeModule MyCorp.TheProduct MyCorp System System.Collections.Generic System.Linq MyCorp.TheProduct.OtherModule MyCorp.TheProduct.OtherModule.Integration ThirdParty namespace MyCorp.TheProduct.SomeModule.Utilities\n{\n using System;\n using System.Collections.Generic;\n using System.Linq;\n using MyCorp.TheProduct; // MyCorp can be left out; this using is NOT redundant\n using MyCorp.TheProduct.OtherModule; // MyCorp.TheProduct can be left out\n using MyCorp.TheProduct.OtherModule.Integration; // MyCorp.TheProduct can be left out\n using ThirdParty;\n\n class C\n {\n Ambiguous a;\n }\n}\n Ambiguous C MyCorp.TheProduct.SomeModule.Utilities System System.Collections.Generic System.Linq MyCorp.TheProduct MyCorp.TheProduct.OtherModule MyCorp.TheProduct.OtherModule.Integration ThirdParty MyCorp.TheProduct.SomeModule MyCorp MyCorp.TheProduct [assembly: ComVisible(false)] [assembly: System.Runtime.InteropServices.ComVisible(false)] using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing MyCorp.TheProduct.OtherModule;\nusing MyCorp.TheProduct.OtherModule.Integration;\nusing ThirdParty;\n\nnamespace MyCorp.TheProduct.SomeModule.Utilities;\n\nclass C\n{\n Ambiguous a;\n}\n namespace MyCorp.TheProduct.SomeModule.Utilities;\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing MyCorp.TheProduct;\nusing MyCorp.TheProduct.OtherModule;\nusing MyCorp.TheProduct.OtherModule.Integration;\nusing ThirdParty;\n\nclass C\n{\n Ambiguous a;\n}\n" }, { "answer_id": 39545780, "author": "Biscuits", "author_id": 2707705, "author_profile": "https://Stackoverflow.com/users/2707705", "pm_score": 3, "selected": false, "text": "using Foo Bar Outer namespace Outer.Inner\n{\n class Foo { }\n}\n namespace Outer\n{\n using Outer.Inner;\n\n class Bar\n {\n public Foo foo;\n }\n}\n using namespace Outer\n{\n using Inner;\n\n class Bar\n {\n public Foo foo;\n }\n}\n" }, { "answer_id": 50666521, "author": "sotn", "author_id": 944592, "author_profile": "https://Stackoverflow.com/users/944592", "pm_score": 3, "selected": false, "text": ".cs using using stylecop.json {\n \"$schema\": \"https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json\",\n \"orderingRules\": {\n \"usingDirectivesPlacement\": \"outsideNamespace\"\n }\n }\n}\n" }, { "answer_id": 52007574, "author": "Ben Gardner", "author_id": 6898634, "author_profile": "https://Stackoverflow.com/users/6898634", "pm_score": 3, "selected": false, "text": "//file1.cs\nnamespace Foo\n{\n class Foo\n {\n }\n}\n\n//file2.cs\nnamespace ConsoleApp3\n{\n using Foo;\n class Program\n {\n static void Main(string[] args)\n {\n //This will allow you to use the class\n Foo test = new Foo();\n }\n }\n}\n\n//file3.cs\nusing Foo; //Unused and redundant \nnamespace Bar\n{\n class Bar\n {\n Bar()\n {\n Foo.Foo test = new Foo.Foo();\n Foo test = new Foo(); //will give you an error that a namespace is being used like a class.\n }\n }\n}\n" }, { "answer_id": 56457715, "author": "Hans Kesting", "author_id": 121309, "author_profile": "https://Stackoverflow.com/users/121309", "pm_score": 4, "selected": false, "text": "using Something.Other namespace Parent global:: namespace Parent\n{\n using global::Something.Other;\n // etc\n}\n" }, { "answer_id": 63193100, "author": "Yrth", "author_id": 14028710, "author_profile": "https://Stackoverflow.com/users/14028710", "pm_score": 2, "selected": false, "text": "using namespace using using namespace" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490/" ]
125,333
<p>I'm looking for the simplest, most straightforward way to implement the following:</p> <ul> <li>The main program instantiates worker threads to do a task.</li> <li>Only <code>n</code> tasks can be running at once.</li> <li>When <code>n</code> is reached, no more workers are started until the count of running threads drops back below <code>n</code>.</li> </ul>
[ { "answer_id": 125354, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 7, "selected": true, "text": " Collection<YourTask> tasks = new ArrayList<YourTask>();\n YourTask yt1 = new YourTask();\n ...\n tasks.add(yt1);\n ...\n ExecutorService exec = Executors.newFixedThreadPool(5);\n List<Future<YourResultType>> results = exec.invokeAll(tasks);\n execute(Runnable)" }, { "answer_id": 125358, "author": "Matt", "author_id": 20630, "author_profile": "https://Stackoverflow.com/users/20630", "pm_score": 3, "selected": false, "text": "Executor executor = Executors.newFixedThreadPool(n);\n\nRunnable runnable = new Runnable() {\n public void run() {\n // do your thing here\n }\n}\n\nexecutor.execute(runnable);\n" }, { "answer_id": 125370, "author": "rjohnston", "author_id": 246, "author_profile": "https://Stackoverflow.com/users/246", "pm_score": 0, "selected": false, "text": "private static final int MAX_WORKERS = n;\nprivate List<Worker> workers = new ArrayList<Worker>(MAX_WORKERS);\n\nprivate boolean roomLeft() {\n synchronized (workers) {\n return (workers.size() < MAX_WORKERS);\n }\n}\n\nprivate void addWorker() {\n synchronized (workers) {\n workers.add(new Worker(this));\n }\n}\n\npublic void removeWorker(Worker worker) {\n synchronized (workers) {\n workers.remove(worker);\n }\n}\n\npublic Example() {\n while (true) {\n if (roomLeft()) {\n addWorker();\n } \n }\n}\n" }, { "answer_id": 125390, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 0, "selected": false, "text": "Task[] tasks = getTasks(); // array of tasks to complete\nThreadGroup group = new ThreadGroup();\nint i=0;\nwhile( i<tasks.length || group.activeCount()>0 ) {\n if( group.activeCount()<N && i<tasks.length ) {\n new TaskThread(group, tasks[i]).start();\n i++;\n } else {\n Thread.sleep(100);\n }\n}\n" }, { "answer_id": 126283, "author": "Fabian Steeg", "author_id": 18154, "author_profile": "https://Stackoverflow.com/users/18154", "pm_score": 5, "selected": false, "text": "/* Get an executor service that will run a maximum of 5 threads at a time: */\nExecutorService exec = Executors.newFixedThreadPool(5);\n/* For all the 100 tasks to be done altogether... */\nfor (int i = 0; i < 100; i++) {\n /* ...execute the task to run concurrently as a runnable: */\n exec.execute(new Runnable() {\n public void run() {\n /* do the work to be done in its own thread */\n System.out.println(\"Running in: \" + Thread.currentThread());\n }\n });\n}\n/* Tell the executor that after these 100 steps above, we will be done: */\nexec.shutdown();\ntry {\n /* The tasks are now running concurrently. We wait until all work is done, \n * with a timeout of 50 seconds: */\n boolean b = exec.awaitTermination(50, TimeUnit.SECONDS);\n /* If the execution timed out, false is returned: */\n System.out.println(\"All done: \" + b);\n} catch (InterruptedException e) { e.printStackTrace(); }\n" }, { "answer_id": 35117224, "author": "Ravindra babu", "author_id": 4999394, "author_profile": "https://Stackoverflow.com/users/4999394", "pm_score": 1, "selected": false, "text": "Executors.newFixedThreadPool(n) ExecutorService work stealing ExecutorService newWorkStealingPool ThreadPoolExecutor ThreadPoolExecutor(int corePoolSize, \n int maximumPoolSize, \n long keepAliveTime, \n TimeUnit unit, \n BlockingQueue<Runnable> workQueue, \n ThreadFactory threadFactory,\n RejectedExecutionHandler handler)\n corePoolSize and maximumPoolSize as N" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/292/" ]
125,341
<p>Is there a simple out of the box way to impersonate a user in .NET?</p> <p>So far I've been using <a href="http://www.codeproject.com/KB/cs/zetaimpersonator.aspx" rel="noreferrer">this class from code project</a> for all my impersonation requirements.</p> <p>Is there a better way to do it by using .NET Framework?</p> <p>I have a user credential set, (username, password, domain name) which represents the identity I need to impersonate.</p>
[ { "answer_id": 125364, "author": "Esteban Araya", "author_id": 781, "author_profile": "https://Stackoverflow.com/users/781", "pm_score": 4, "selected": false, "text": "using System.Security.Principal;\nusing(WindowsIdentity.GetCurrent().Impersonate())\n{\n //your code goes here\n}\n" }, { "answer_id": 7250145, "author": "Matt Johnson-Pint", "author_id": 634824, "author_profile": "https://Stackoverflow.com/users/634824", "pm_score": 8, "selected": false, "text": "System.Security.Principal WindowsIdentity.RunImpersonated Action Func<T> WindowsIdentity.RunImpersonated(userHandle, () =>\n{\n // do whatever you want as this user.\n});\n var result = WindowsIdentity.RunImpersonated(userHandle, () =>\n{\n // do whatever you want as this user.\n return result;\n});\n WindowsIdentity.RunImpersonatedAsync await WindowsIdentity.RunImpersonatedAsync(userHandle, async () =>\n{\n // do whatever you want as this user.\n});\n var result = await WindowsIdentity.RunImpersonated(userHandle, async () =>\n{\n // do whatever you want as this user.\n return result;\n});\n WindowsIdentity.Impersonate WindowsImpersonationContext IDisposable using using (WindowsImpersonationContext context = WindowsIdentity.Impersonate(userHandle))\n{\n // do whatever you want as this user.\n}\n LogonUser [DllImport(\"advapi32.dll\", SetLastError = true, CharSet = CharSet.Unicode)]\ninternal static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);\n SecureString LogonUser using System.Security.Principal;\nusing Microsoft.Win32.SafeHandles;\nusing SimpleImpersonation;\n\nvar credentials = new UserCredentials(domain, username, password);\nusing SafeAccessTokenHandle userHandle = credentials.LogonUser(LogonType.Interactive); // or another LogonType\n userHandle LogonUser" }, { "answer_id": 26872651, "author": "toddmo", "author_id": 1045881, "author_profile": "https://Stackoverflow.com/users/1045881", "pm_score": 3, "selected": false, "text": "LOGON32_LOGON_INTERACTIVE <PermissionSet(SecurityAction.Demand, Name:=\"FullTrust\")> _\n Public Class Impersonation\n Implements IDisposable\n\n Public Enum LogonTypes\n ''' <summary>\n ''' This logon type is intended for users who will be interactively using the computer, such as a user being logged on \n ''' by a terminal server, remote shell, or similar process.\n ''' This logon type has the additional expense of caching logon information for disconnected operations; \n ''' therefore, it is inappropriate for some client/server applications,\n ''' such as a mail server.\n ''' </summary>\n LOGON32_LOGON_INTERACTIVE = 2\n\n ''' <summary>\n ''' This logon type is intended for high performance servers to authenticate plaintext passwords.\n ''' The LogonUser function does not cache credentials for this logon type.\n ''' </summary>\n LOGON32_LOGON_NETWORK = 3\n\n ''' <summary>\n ''' This logon type is intended for batch servers, where processes may be executing on behalf of a user without \n ''' their direct intervention. This type is also for higher performance servers that process many plaintext\n ''' authentication attempts at a time, such as mail or Web servers. \n ''' The LogonUser function does not cache credentials for this logon type.\n ''' </summary>\n LOGON32_LOGON_BATCH = 4\n\n ''' <summary>\n ''' Indicates a service-type logon. The account provided must have the service privilege enabled. \n ''' </summary>\n LOGON32_LOGON_SERVICE = 5\n\n ''' <summary>\n ''' This logon type is for GINA DLLs that log on users who will be interactively using the computer. \n ''' This logon type can generate a unique audit record that shows when the workstation was unlocked. \n ''' </summary>\n LOGON32_LOGON_UNLOCK = 7\n\n ''' <summary>\n ''' This logon type preserves the name and password in the authentication package, which allows the server to make \n ''' connections to other network servers while impersonating the client. A server can accept plaintext credentials \n ''' from a client, call LogonUser, verify that the user can access the system across the network, and still \n ''' communicate with other servers.\n ''' NOTE: Windows NT: This value is not supported. \n ''' </summary>\n LOGON32_LOGON_NETWORK_CLEARTEXT = 8\n\n ''' <summary>\n ''' This logon type allows the caller to clone its current token and specify new credentials for outbound connections.\n ''' The new logon session has the same local identifier but uses different credentials for other network connections. \n ''' NOTE: This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider.\n ''' NOTE: Windows NT: This value is not supported. \n ''' </summary>\n LOGON32_LOGON_NEW_CREDENTIALS = 9\n End Enum\n\n <DllImport(\"advapi32.dll\", SetLastError:=True, CharSet:=CharSet.Unicode)> _\n Private Shared Function LogonUser(lpszUsername As [String], lpszDomain As [String], lpszPassword As [String], dwLogonType As Integer, dwLogonProvider As Integer, ByRef phToken As SafeTokenHandle) As Boolean\n End Function\n\n Public Sub New(Domain As String, UserName As String, Password As String, Optional LogonType As LogonTypes = LogonTypes.LOGON32_LOGON_INTERACTIVE)\n Dim ok = LogonUser(UserName, Domain, Password, LogonType, 0, _SafeTokenHandle)\n If Not ok Then\n Dim errorCode = Marshal.GetLastWin32Error()\n Throw New ApplicationException(String.Format(\"Could not impersonate the elevated user. LogonUser returned error code {0}.\", errorCode))\n End If\n\n WindowsImpersonationContext = WindowsIdentity.Impersonate(_SafeTokenHandle.DangerousGetHandle())\n End Sub\n\n Private ReadOnly _SafeTokenHandle As New SafeTokenHandle\n Private ReadOnly WindowsImpersonationContext As WindowsImpersonationContext\n\n Public Sub Dispose() Implements System.IDisposable.Dispose\n Me.WindowsImpersonationContext.Dispose()\n Me._SafeTokenHandle.Dispose()\n End Sub\n\n Public NotInheritable Class SafeTokenHandle\n Inherits SafeHandleZeroOrMinusOneIsInvalid\n\n <DllImport(\"kernel32.dll\")> _\n <ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)> _\n <SuppressUnmanagedCodeSecurity()> _\n Private Shared Function CloseHandle(handle As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean\n End Function\n\n Public Sub New()\n MyBase.New(True)\n End Sub\n\n Protected Overrides Function ReleaseHandle() As Boolean\n Return CloseHandle(handle)\n End Function\n End Class\n\n End Class\n Using" }, { "answer_id": 35426713, "author": "Cedric Michel", "author_id": 1220754, "author_profile": "https://Stackoverflow.com/users/1220754", "pm_score": 3, "selected": false, "text": " string login = \"\";\n string domain = \"\";\n string password = \"\";\n\n using (UserImpersonation user = new UserImpersonation(login, domain, password))\n {\n if (user.ImpersonateValidUser())\n {\n File.WriteAllText(\"test.txt\", \"your text\");\n Console.WriteLine(\"File writed\");\n }\n else\n {\n Console.WriteLine(\"User not connected\");\n }\n }\n using System;\nusing System.Runtime.InteropServices;\nusing System.Security.Principal;\n\n\n/// <summary>\n/// Object to change the user authticated\n/// </summary>\npublic class UserImpersonation : IDisposable\n{\n /// <summary>\n /// Logon method (check athetification) from advapi32.dll\n /// </summary>\n /// <param name=\"lpszUserName\"></param>\n /// <param name=\"lpszDomain\"></param>\n /// <param name=\"lpszPassword\"></param>\n /// <param name=\"dwLogonType\"></param>\n /// <param name=\"dwLogonProvider\"></param>\n /// <param name=\"phToken\"></param>\n /// <returns></returns>\n [DllImport(\"advapi32.dll\")]\n private static extern bool LogonUser(String lpszUserName,\n String lpszDomain,\n String lpszPassword,\n int dwLogonType,\n int dwLogonProvider,\n ref IntPtr phToken);\n\n /// <summary>\n /// Close\n /// </summary>\n /// <param name=\"handle\"></param>\n /// <returns></returns>\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto)]\n public static extern bool CloseHandle(IntPtr handle);\n\n private WindowsImpersonationContext _windowsImpersonationContext;\n private IntPtr _tokenHandle;\n private string _userName;\n private string _domain;\n private string _passWord;\n\n const int LOGON32_PROVIDER_DEFAULT = 0;\n const int LOGON32_LOGON_INTERACTIVE = 2;\n\n /// <summary>\n /// Initialize a UserImpersonation\n /// </summary>\n /// <param name=\"userName\"></param>\n /// <param name=\"domain\"></param>\n /// <param name=\"passWord\"></param>\n public UserImpersonation(string userName, string domain, string passWord)\n {\n _userName = userName;\n _domain = domain;\n _passWord = passWord;\n }\n\n /// <summary>\n /// Valiate the user inforamtion\n /// </summary>\n /// <returns></returns>\n public bool ImpersonateValidUser()\n {\n bool returnValue = LogonUser(_userName, _domain, _passWord,\n LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,\n ref _tokenHandle);\n\n if (false == returnValue)\n {\n return false;\n }\n\n WindowsIdentity newId = new WindowsIdentity(_tokenHandle);\n _windowsImpersonationContext = newId.Impersonate();\n return true;\n }\n\n #region IDisposable Members\n\n /// <summary>\n /// Dispose the UserImpersonation connection\n /// </summary>\n public void Dispose()\n {\n if (_windowsImpersonationContext != null)\n _windowsImpersonationContext.Undo();\n if (_tokenHandle != IntPtr.Zero)\n CloseHandle(_tokenHandle);\n }\n\n #endregion\n}\n" }, { "answer_id": 47162514, "author": "Federico Navarrete", "author_id": 1928691, "author_profile": "https://Stackoverflow.com/users/1928691", "pm_score": 2, "selected": false, "text": "private const string LOGIN = \"mamy\";\nprivate const string DOMAIN = \"mongo\";\nprivate const string PASSWORD = \"HelloMongo2017\";\n\nprivate void DBConnection()\n{\n using (Impersonator user = new Impersonator(LOGIN, DOMAIN, PASSWORD, LogonType.LOGON32_LOGON_NEW_CREDENTIALS, LogonProvider.LOGON32_PROVIDER_WINNT50))\n {\n }\n}\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1909/" ]
125,359
<p>In Java, web apps are bundled in to WARs. By default, many servlet containers will use the WAR name as the context name for the application.</p> <p>Thus myapp.war gets deployed to <a href="http://example.com/myapp" rel="noreferrer">http://example.com/myapp</a>.</p> <p>The problem is that the webapp considers its "root" to be, well, "root", or simply "/", whereas HTML would consider the root of your application to be "/myapp".</p> <p>The Servlet API and JSP have facilities to help manage this. For example, if, in a servlet, you do: response.sendRedirect("/mypage.jsp"), the container will prepend the context and create the url: <a href="http://example.com/myapp/mypage.jsp" rel="noreferrer">http://example.com/myapp/mypage.jsp</a>".</p> <p>However, you can't do that with, say, the IMG tag in HTML. If you do &lt;img src="/myimage.gif"/> you will likely get a 404, because what you really wanted was "/myapp/myimage.gif".</p> <p>Many frameworks have JSP tags that are context aware as well, and there are different ways of making correct URLs within JSP (none particularly elegantly).</p> <p>It's a nitty problem for coders to jump in an out of when to use an "App Relative" url, vs an absolute url.</p> <p>Finally, there's the issue of Javascript code that needs to create URLs on the fly, and embedded URLs within CSS (for background images and the like).</p> <p>I'm curious what techniques others use to mitigate and work around this issue. Many simply punt and hard code it, either to server root or to whatever context they happen to be using. I already know that answer, that's not what I'm looking for.</p> <p>What do you do?</p>
[ { "answer_id": 125420, "author": "Swati", "author_id": 12682, "author_profile": "https://Stackoverflow.com/users/12682", "pm_score": 0, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<paths>\n <path name=\"account\" parent=\"home\">Account/</path>\n <path name=\"css\">css/</path>\n <path name=\"home\">servlet/</path>\n <path name=\"icons\" parent=\"images\">icons/</path>\n <path name=\"images\">images/</path>\n <path name=\"js\">js/</path>\n</paths>\n <ilink name=\"link to icons\" type=\"icons\">link to icons</ilink>\n <xsl:template match=\"ilink\">\n <xsl:variable name=\"temp\">\n <xsl:value-of select=\"$rootpath\" />\n <xsl:call-template name=\"paths\">\n <xsl:with-param name=\"path-name\"><xsl:value-of select=\"@type\" /></xsl:with-param>\n </xsl:call-template>\n <xsl:value-of select=\"@file\" />\n </xsl:variable>\n <a href=\"{$temp}\" title=\"{@name}\" ><xsl:value-of select=\".\" /></a>\n</xsl:template>\n $rootPath ${applicationScope.contextPath} ${applicationScope.contextPath}" }, { "answer_id": 126017, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": true, "text": "<c:url value=\"/images/header.jpg\" /> <script type=\"text/javascript\">\nvar CONTEXT_ROOT = '<%= request.getContextPath() %>';\n</script>\n" }, { "answer_id": 128569, "author": "Scott Stanchfield", "author_id": 12541, "author_profile": "https://Stackoverflow.com/users/12541", "pm_score": 1, "selected": false, "text": "<img src=\"myimage.gif\"/>\n <img src=\"/myimage.gif\"/>\n" }, { "answer_id": 128750, "author": "Travis Wilson", "author_id": 8735, "author_profile": "https://Stackoverflow.com/users/8735", "pm_score": 1, "selected": false, "text": "/myapp/user/email.jsp:\nEmail: <a href=\"../sendmail.jsp\">${user.email}</a>\n\n/myapp/browse/profile.jsp:\n<jsp:include page=\"../user/email.jsp\" />\n\n/myapp/home.jsp:\n<jsp:include page=\"../user/email.jsp\" />\n email.jsp sendmail.jsp /myapp/browse/profile.jsp /myapp/home.jsp /myapp/ <%= request.getContextPath() %>" }, { "answer_id": 4955473, "author": "Demwis", "author_id": 537246, "author_profile": "https://Stackoverflow.com/users/537246", "pm_score": 2, "selected": false, "text": "<rule>\n <from>^.+/resources/(.*)$</from>\n <to>/resources/$1</to>\n</rule>\n" }, { "answer_id": 4956614, "author": "BalusC", "author_id": 157882, "author_profile": "https://Stackoverflow.com/users/157882", "pm_score": 3, "selected": false, "text": "<base> / HttpServletRequest <%@taglib prefix=\"c\" uri=\"http://java.sun.com/jsp/jstl/core\" %>\n<%@taglib prefix=\"fn\" uri=\"http://java.sun.com/jsp/jstl/functions\" %>\n<c:set var=\"req\" value=\"${pageContext.request}\" />\n<c:set var=\"url\">${req.requestURL}</c:set>\n<c:set var=\"uri\">${req.requestURI}</c:set>\n\n<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <base href=\"${fn:substring(url, 0, fn:length(url) - fn:length(uri))}${req.contextPath}/\" />\n <link rel=\"stylesheet\" href=\"css/default.css\">\n <script src=\"js/default.js\"></script>\n </head>\n <body>\n <img src=\"img/logo.png\" />\n <a href=\"other.jsp\">link</a>\n </body>\n</html>\n #identifier <a href=\"#identifier\">jump</a>\n <a href=\"${uri}#identifier\">jump</a>\n <base> var base = document.getElementsByTagName(\"base\")[0].href;\n var base = $(\"base\").attr(\"href\");\n /css/style.css\n/css/images/foo.png\n background-image: url('images/foo.png');\n /css/style.css\n/images/foo.png\n ../ background-image: url('../images/foo.png');\n <base>" }, { "answer_id": 39394912, "author": "Brett Ryan", "author_id": 140037, "author_profile": "https://Stackoverflow.com/users/140037", "pm_score": 0, "selected": false, "text": "(function (APP) {\n var ctx;\n APP.setContext = function (val) {\n // protect rogue JS from setting the context.\n if (ctx) {\n return;\n }\n val = val || val.trim();\n // Don't allow a double slash for a context.\n if (val.charAt(0) === '/' && val.charAt(1) === '/') {\n return;\n }\n // Context must both start and end in /.\n if (val.length === 0 || val === '/') {\n val = '/';\n } else {\n if (val.charAt(0) !== '/') {\n val = '/' + val;\n }\n if (val.slice(-1) !== '/') {\n val += '/';\n }\n }\n ctx = val;\n };\n APP.getContext = function () {\n return ctx || '/';\n };\n APP.getUrl = function (val) {\n if (val && val.length > 0) {\n return APP.getContext() + (val.charAt(0) === '/' ? val.substring(1) : val);\n }\n return APP.getContext();\n };\n})(window.APP = window.APP || {});\n <script type=\"text/javascript\">\n APP.setContext('${pageContext.request['contextPath']}');\n // If preferred use JSTL cor, but it must be available and declared.\n //APP.setContext('<c:url value='/'/>');\n</script>\n getUrl(path) getUrl var path = APP.getUrl(\"/some/path\");\nvar path2 = APP.getUrl(\"some/path\");\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13663/" ]
125,367
<p>What are the advantages and limitations of dynamic type languages compared to static type languages?</p> <p><strong>See also</strong>: <a href="https://stackoverflow.com/questions/42934/whats-with-the-love-of-dynamic-languages">whats with the love of dynamic languages</a> (a far more argumentative thread...)</p>
[ { "answer_id": 125538, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 7, "selected": false, "text": "PersistentVector" }, { "answer_id": 3185924, "author": "Zorf", "author_id": 2281094, "author_profile": "https://Stackoverflow.com/users/2281094", "pm_score": 5, "selected": false, "text": "3 + [4,7] 3 + [4,7] if(1) a = 3; else a = \"string\"; \"string\" + \"string\" 3 + 3 + print(\"string\") length(3) string error: function 'length' expects array as argument. \"error: the first character of this string should be a 'z'\"" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11034/" ]
125,369
<p>I come across this problem when i am writing an event handler in SharePoint. My event handler has a web reference. When i create this web reference, the URL of the web service will be added in the .config file of the assembly. If i have to change the web reference URL i just have to change the link in the config file. </p> <p>Problem comes when I try to GAC the dll. When i GAC the DLL, the config file cannot be GACed along with the dll, and hence, there is no way for me to update the web reference. </p> <p>One workaround i have found is to modify the constructor method Reference.cs class which is autogenerated by visual studio when i add a reference, so that the constructor reads the web service url from some other location, say a registry or an XML file in some predetermined location. But this poses a problem sometimes, as when i update the web referenc using visual studio, this Reference.cs file gets regenerated, and all my modifications would be lost.</p> <p>Is there a better way to solve this problem?</p>
[ { "answer_id": 125375, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": true, "text": "public partial class WebServiceReference\n { public WebServiceReference(ExampleConfigurationClass config) \n { /* ... */\n }\n }\n\nWebServiceReference svc = new WebServiceReference(myConfig);\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1909/" ]
125,389
<p>I am writing a custom maven2 MOJO. I need to access the runtime configuration of another plugin, from this MOJO.</p> <p>What is the best way to do this?</p>
[ { "answer_id": 130171, "author": "Mike Deck", "author_id": 1247, "author_profile": "https://Stackoverflow.com/users/1247", "pm_score": 0, "selected": false, "text": "<project>\n ...\n <properties>\n <foo>value</foo>\n </properties>\n ...\n</project>\n <somePluginProperty>${foo}</somePluginProperty>\n" }, { "answer_id": 130872, "author": "npellow", "author_id": 2767300, "author_profile": "https://Stackoverflow.com/users/2767300", "pm_score": 2, "selected": false, "text": "private Plugin lookupPlugin(String key) {\n\n List plugins = getProject().getBuildPlugins();\n\n for (Iterator iterator = plugins.iterator(); iterator.hasNext();) {\n Plugin plugin = (Plugin) iterator.next();\n if(key.equalsIgnoreCase(plugin.getKey())) {\n return plugin;\n }\n }\n return null;\n}\n\n\n/**\n * Extracts nested values from the given config object into a List.\n * \n * @param childname the name of the first subelement that contains the list\n * @param config the actual config object\n */\nprivate List extractNestedStrings(String childname, Xpp3Dom config) {\n\n final Xpp3Dom subelement = config.getChild(childname);\n if (subelement != null) {\n List result = new LinkedList();\n final Xpp3Dom[] children = subelement.getChildren();\n for (int i = 0; i < children.length; i++) {\n final Xpp3Dom child = children[i];\n result.add(child.getValue());\n }\n getLog().info(\"Extracted strings: \" + result);\n return result;\n }\n\n return null;\n}\n" }, { "answer_id": 1073554, "author": "Kingamajick", "author_id": 131693, "author_profile": "https://Stackoverflow.com/users/131693", "pm_score": 2, "selected": false, "text": "/**\n * The maven project.\n * \n * @parameter expression=\"${project}\"\n * @readonly\n */\n private MavenProject project;\n mavenProject.getBuildPlugins()\n plugin.getConfiguration()\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2767300/" ]
125,394
<p>I've seen several question on here about <a href="https://stackoverflow.com/questions/tagged/exception?sort=votes">exceptions</a>, and some of them hint at <a href="https://stackoverflow.com/search?s=interrupt+exception">interrupts as exceptions</a>, but none make the connection clear.</p> <ul> <li><p>What is an interrupt?</p></li> <li><p>What is an exception? (please explain what exceptions are for each language you know, as there are some differences)</p></li> <li><p>When is an exception an interrupt and vice-versa?</p></li> </ul>
[ { "answer_id": 125417, "author": "Ron Savage", "author_id": 12476, "author_profile": "https://Stackoverflow.com/users/12476", "pm_score": 2, "selected": false, "text": "Try\n {\n ... various code steps that \"throw exceptions\" on error ...\n }\ncatch (exception e)\n {\n print 'Crap! Something bad happened.' + e.toString()\n }\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ]
125,399
<p>I have code that references a web service, and I'd like the address of that web service to be dynamic (read from a database, config file, etc.) so that it is easily changed. One major use of this will be to deploy to multiple environments where machine names and IP addresses are different. The web service signature will be the same across all deployments, just located elsewhere.</p> <p>Maybe I've just been spoiled by the Visual Studio "Add Web Reference" wizard - seems like this should be something relatively easy, though.</p>
[ { "answer_id": 17343678, "author": "John Kocktoasten", "author_id": 2119931, "author_profile": "https://Stackoverflow.com/users/2119931", "pm_score": 3, "selected": false, "text": "// Web Service Wrapper to override constructor to use custom ConfigSection \n// app.config values for URL/User/Pass\nnamespace myprogram.webservice\n{\n public partial class MyWebService\n {\n public MyWebService(string szURL)\n {\n this.Url = szURL;\n if ((this.IsLocalFileSystemWebService(this.Url) == true))\n {\n this.UseDefaultCredentials = true;\n this.useDefaultCredentialsSetExplicitly = false;\n }\n else\n {\n this.useDefaultCredentialsSetExplicitly = true;\n }\n }\n }\n}\n" }, { "answer_id": 35563881, "author": "mesutpiskin", "author_id": 2647294, "author_profile": "https://Stackoverflow.com/users/2647294", "pm_score": 0, "selected": false, "text": "public Service1() {\n this.Url = \"URL\"; // etc. string variable this.Url = ConfigClass.myURL\n }\n" }, { "answer_id": 37163548, "author": "djciko", "author_id": 6162435, "author_profile": "https://Stackoverflow.com/users/6162435", "pm_score": 0, "selected": false, "text": "<system.serviceModel>\n <bindings>\n <basicHttpBinding>\n <binding name=\"YourServiceSoap\" />\n </basicHttpBinding>\n </bindings>\n <client>\n **** CHANGE THE LINE BELOW TO CHANGE THE URL **** \n <endpoint address=\"http://10.10.10.100:8080/services/YourService.asmx\"\n binding=\"basicHttpBinding\" bindingConfiguration=\"YourServiceSoap\"\n contract=\"YourServiceRef.YourServiceSoap\" name=\"YourServiceSoap\" />\n </client>\n" }, { "answer_id": 40891456, "author": "rwg", "author_id": 899449, "author_profile": "https://Stackoverflow.com/users/899449", "pm_score": 5, "selected": false, "text": "private void CallTheService( string url )\n{\n TheService.TheServiceClient client = new TheService.TheServiceClient();\n client.Endpoint.Address = new System.ServiceModel.EndpointAddress(url);\n var results = client.AMethodFromTheService();\n}\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7623/" ]
125,400
<p>Not sure if this is possible or if I'm expressing correctly what I'm looking for, but I have the following piece of code in my library repeatedly and would like to practice some DRY. I have set of SQL Server tables that I'm querying based on a simple user-supplied search field ala Google. I'm using LINQ to compose the final query based on what's in the search string. I'm looking for a way to use generics and passed in lambda functions to create a reusable routine out of this: </p> <pre><code>string[] arrayOfQueryTerms = getsTheArray(); var somequery = from q in dataContext.MyTable select q; if (arrayOfQueryTerms.Length == 1) { somequery = somequery.Where&lt;MyTableEntity&gt;( e =&gt; e.FieldName.StartsWith(arrayOfQueryTerms[0])); } else { foreach(string queryTerm in arrayOfQueryTerms) { if (!String.IsNullOrEmpty(queryTerm)) { somequery = somequery .Where&lt;MyTableEntity&gt;( e =&gt; e.FieldName.Contains(queryTerm)); } } } </code></pre> <p>I was hoping to create a generic method with signature that looks something like:</p> <pre><code>private IQueryable&lt;T&gt; getQuery( T MyTableEntity, string[] arrayOfQueryTerms, Func&lt;T, bool&gt; predicate) </code></pre> <p>I'm using the same search strategy across all my tables, so the only thing that really differs from usage to usage is the MyTable &amp; MyTableEntity searched and the FieldName searched. Does this make sense? Is there a way with LINQ to dynamically pass in the name of the field to query in the where clause? Or can I pass in this as a predicate lambda?</p> <pre><code>e =&gt; e.FieldName.Contains(queryTerm) </code></pre> <p>I realize there a million and a half ways to do this in SQL, probably easier, but I'd love to keep everything in the LINQ family for this one. Also, I feel that generics should be handy for a problem like this. Any ideas?</p>
[ { "answer_id": 125418, "author": "Erik Forbes", "author_id": 16942, "author_profile": "https://Stackoverflow.com/users/16942", "pm_score": 5, "selected": true, "text": "var query = dataSource.Where(\"CategoryID == 2 && UnitPrice > 3\")\n .OrderBy(\"SupplierID\");\n" }, { "answer_id": 125429, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": false, "text": "IQueryable<T> getQuery<T>(T myTableEntity, string[] arrayOfQueryTerms, Expression<Func<T, bool>> predicate)\n { var fieldOrProperty = getMemberInfo(predicate);\n /* ... */\n }\n\nMemberInfo getmemberInfo<T>(Expression<Func<T,bool> expr)\n { var memberExpr = expr as MemberExpression;\n if (memberExpr != null) return memberExpr.Member;\n throw new ArgumentException();\n }\n\nvar q = getQuery<FooTable>(foo, new[]{\"Bar\",\"Baz\"}, x=>x.FieldName);\n" }, { "answer_id": 69234899, "author": "AliReza Sabouri", "author_id": 786376, "author_profile": "https://Stackoverflow.com/users/786376", "pm_score": 0, "selected": false, "text": "query = dataSource.ApplyFiltering(\"FiledName=John\");\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17729/" ]
125,449
<p>I am using Excel where certain fields are allowed for user input and other cells are to be protected. I have used Tools Protect sheet, however after doing this I am not able to change the values in the VBA script. I need to restrict the sheet to stop user input, at the same time allow the VBA code to change the cell values based on certain computations.</p>
[ { "answer_id": 125505, "author": "Kevin Crumley", "author_id": 1818, "author_profile": "https://Stackoverflow.com/users/1818", "pm_score": 2, "selected": false, "text": "wksht.Unprotect()\n wksht.Protect()\n" }, { "answer_id": 126032, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 8, "selected": true, "text": "Worksheet.Protect \"Password\", UserInterfaceOnly := True\n" }, { "answer_id": 126748, "author": "Robert Mearns", "author_id": 5050, "author_profile": "https://Stackoverflow.com/users/5050", "pm_score": 4, "selected": false, "text": "Sub UnProtect_Modify_Protect()\n\n ThisWorkbook.Worksheets(\"Sheet1\").Unprotect Password:=\"Password\"\n'Unprotect\n\n ThisWorkbook.ActiveSheet.Range(\"A1\").FormulaR1C1 = \"Changed\"\n'Modify\n\n ThisWorkbook.Worksheets(\"Sheet1\").Protect Password:=\"Password\"\n'Protect\n\nEnd Sub\n Sub Re-Protect_Modify()\n\nThisWorkbook.Worksheets(\"Sheet1\").Protect Password:=\"Password\", _\n UserInterfaceOnly:=True\n'Protect, even if already protected\n\n ThisWorkbook.ActiveSheet.Range(\"A1\").FormulaR1C1 = \"Changed\"\n'Modify\n\nEnd Sub\n" }, { "answer_id": 21682830, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "Sub Example()\n ActiveSheet.Unprotect\n Program logic...\n ActiveSheet.Protect\nEnd Sub\n" }, { "answer_id": 43930958, "author": "Alan", "author_id": 8001267, "author_profile": "https://Stackoverflow.com/users/8001267", "pm_score": 0, "selected": false, "text": "ThisWorkbook.Worksheets(\"Sheet1\").Protect Password:=\"Password\", _\nUserInterfaceOnly:=True\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17266/" ]
125,457
<p>If I need to copy a stored procedure (SP) from one SQL Server to another I right click on the SP in SSMS and select Script Stored Procedure as > CREATE to > New Query Editor Window. I then change the connection by right clicking on that window and selecting Connection > Change Connection... and then selecting the new server and F5 to run the create on the new server.</p> <p>So my question is "What is the T-SQL syntax to connect to another SQL Server?" so that I can just paste that in the top of the create script and F5 to run it and it would switch to the new server and run the create script.</p> <p>While typing the question I realized that if I gave you the back ground to what I'm trying to do that you might come up with a faster and better way from me to accomplish this.</p>
[ { "answer_id": 125472, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 5, "selected": false, "text": "USE master\nGO\nEXEC sp_addlinkedserver \n 'SEATTLESales',\n N'SQL Server'\nGO\n" }, { "answer_id": 125499, "author": "Codewerks", "author_id": 17729, "author_profile": "https://Stackoverflow.com/users/17729", "pm_score": 7, "selected": true, "text": "SELECT * FROM [LinkedServer].[RemoteDatabase].[User].[Table]\n" }, { "answer_id": 3153405, "author": "mwg2002", "author_id": 380525, "author_profile": "https://Stackoverflow.com/users/380525", "pm_score": 7, "selected": false, "text": ":Connect server_name[\\instance_name] [-l timeout] [-U user_name [-P password]\n GO" }, { "answer_id": 8182097, "author": "SASMITA MOHAPATRA", "author_id": 1053749, "author_profile": "https://Stackoverflow.com/users/1053749", "pm_score": 3, "selected": false, "text": "-- Server one scalar variable\nDECLARE @SERVER VARCHAR(MAX)\n--Oracle is the server to which we want to connect\nEXEC SP_ADDLINKEDSERVER @SERVER='ORACLE'\n --DBO is the owner name to know table owner name execute (SP_HELP TABLENAME) \nSELECT * INTO DESTINATION_TABLE_NAME \nFROM ORACLE.SOURCE_DATABASENAME.DBO.SOURCE_TABLE\n" }, { "answer_id": 22917476, "author": "Oscar Fraxedas", "author_id": 1074245, "author_profile": "https://Stackoverflow.com/users/1074245", "pm_score": 2, "selected": false, "text": ":CONNECT SERVER1\nSelect * from Table\nGO\nenter code here\n:CONNECT SERVER1\nSelect * from Table\nGO\n" }, { "answer_id": 30951573, "author": "frans eilering", "author_id": 4962958, "author_profile": "https://Stackoverflow.com/users/4962958", "pm_score": 2, "selected": false, "text": "Print 'START(A) create table'\n\nGO 1\n\nIf not EXISTS\n(\n SELECT *\n FROM INFORMATION_SCHEMA.TABLES\n WHERE TABLE_NAME = 'Bedrijf'\n)\nBEGIN\nCREATE TABLE [dbo].[Bedrijf] (\n[IDBedrijf] [varchar] (38) NOT NULL ,\n[logo] [varbinary] (max) NULL ,\n[VolledigeHandelsnaam] [varchar] (100) NULL \n) ON [PRIMARY]\n OSQL.EXE -U Username -P Password -S IPaddress -i C:Bedrijf.txt -o C:Bedrijf.out -d myDatabaseName\n 1> 2> 3> START(A) create table\n" }, { "answer_id": 54652341, "author": "Igor Krupitsky", "author_id": 1781849, "author_profile": "https://Stackoverflow.com/users/1781849", "pm_score": 0, "selected": false, "text": "$cn = new-object system.data.SqlClient.SQLConnection(\"Data Source=server1;Initial Catalog=db1;User ID=user1;Password=password1\");\n$cmd = new-object system.data.sqlclient.sqlcommand(\"exec Proc1\", $cn);\n$cn.Open();\n$cmd.CommandTimeout = 0\n$cmd.ExecuteNonQuery()\n$cn.Close();\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
125,463
<p>I'm developping a small UML Class editor in Java, mainly a personal project, it might end up on SourceForge if I find the time to create a project on it.</p> <p>The project is quite advanced : I can create classes, move them around, create interfaces, create links, etc.</p> <p>What I'm working on is the dialog box for setting class/interface properties and creating new classes/interfaces.</p> <p>For example, I have a class that extends JDialog. This is the main "window" for editing classes and interfaces (well, there a class for each). It contains a JTabbedPane which in turn contain JPanels.</p> <p>This JPanel are actually custom ones. I created an abstract class that extends JPanel. This class uses components (defined by its subclasses) and add their values to a JTable (also contained in the JPanel).</p> <p>For example, if I want to edit a class' attributes, the JPanel will contain a JTextField for entering the name of the attribute as well as another one for entering its type. There is also a set of button for processing the data entered in these fields. When I click "Save", the data I entered in the JTextFields are added into the JTable (à la Enterprise Architect). The concreted class that extends the abstract one are responsible for defining control and deciding what do to with the data when a line is added or deleted from the JTable. The JTable management is, however, the responsability of the abstract class.</p> <p>Here is my problem : in OO, a class has methods, and an interface has methods too. I told myself : I could use the same concrete custom JPanel (AttributesPanel (which extends the abstract JPanel class I created)) to store the methods for a class or and interface.</p> <p>However, the class needs to keep a copy (as an attribute) of the class or interface I am working on. That way, when a method is added to it, I can call editedClass.addMethod() (or editedInterface.addMethod()). The problem is that I have no way of telling whether I work on a Class or and Interface.</p> <p>The solution I found is ugly : keep an attribute editedClass and an attribute editedInterface in the AttributesPanel class. According to whether I am editing a class or interface, one of these attributes will be null while to other will not.</p> <p>It is quite ugly if you ask me. In fact, I can hear my software engineering teachers in my head screaming in agony while burning (well, actually, freezing) in the ninth circle of Hell.</p> <p>The quick way to fix this design problem would be to create an interface called "ObjectWithMethods", which my Class and Interface classes will implement. That way, I will only have to put an ObjectWithMethods parameter in my AttributesPanel class.</p> <p>But does that mean that I should create a class named "ObjectWithAttributes", or "ObjectWithBlahBlah" ? I see some good "TheDailyWTF" potential here... Besides, I don't think I should modify my domain objects (a Class, Interface, Note, Relationship (for my UML editor)) or create an new Interface just for the sake of some UI consideration....</p> <p>What do you think?</p> <p>I you need more clarifications (because I am very tired right now and I tend to right quite badly (especially in English - my mother tongue is French) while in this state of mind...), just ask and I'll edit this question.</p> <p>Cheers,</p> <p>Guillaume.</p>
[ { "answer_id": 6549048, "author": "Tair", "author_id": 808237, "author_profile": "https://Stackoverflow.com/users/808237", "pm_score": 0, "selected": false, "text": "if( .. instanceof ..)" }, { "answer_id": 6551031, "author": "umlcat", "author_id": 535724, "author_profile": "https://Stackoverflow.com/users/535724", "pm_score": 0, "selected": false, "text": "// all code, classes, mixed up\npublic class JCustomPanel: {\n\n protected ChartClass Charts;\n protected ArrayList<String> MyClassAttributes;\n protected ArrayList<String> MyClassMethods;\n\n void PanelDoSomeThing();\n void ClassDoSomeThing();\n void InterfaceDoSomeThing();\n\n // ...\n} // class JCustomPanel\n // things related to a single class or interface,\n// nothing to do with the chart\n\npublic class JClassRepresentation: {\n\n ArrayList<String> Attributes;\n ArrayList<String> Methods;\n\n bool IsInterface;\n\n void ClassDoSomeThing();\n void InterfaceDoSomeThing();\n\n // ...\n} // class JCustomPanel\n\n// things related to the editor,\n// contains the classes and interfaces,\n// but, as separate stuff\npublic class JCustomPanel: {\n\n ArrayList<JClassRepresentation> Classes;\n\n int PagesCount;\n\n void InterfaceDoSomeThing();\n\n // ...\n} // class JCustomPanel\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10687/" ]
125,467
<p>Using Rails v2.1, lets say you have an action for a controller that is accessible from more than one location. For example, within the Rails app, you have a link to edit a user from two different views, one on the users index view, and another from another view (lets say from the nav bar on every page).</p> <p>I'm wondering what is the best way to redirect the user back to the right spot depending on what link they clicked on. For example:</p> <p>Example 1:</p> <ol> <li>List all users</li> <li>Click "edit" on a user in the list</li> <li>User clicks "save" on the form, the controller redirects back to 1.</li> </ol> <p>Example 2:</p> <ol> <li>The user could be on any page within the application, the nav bar shows a link to edit the current user</li> <li>The user clicks on the link to edit</li> <li>The user clicks "save" on the form, controller redirects back to whatever page they were on when the user clicked the "edit" link in the nav bar.</li> </ol> <p>I've seen it done in the past by:</p> <ol> <li>Placing a parameter on the original edit link with the original controller/action in which the link appeared. To make this more DRY, you could use @controller.controller_name and @controller.action_name in a helper.</li> <li>The controller saves the parameters to a session variable.</li> <li>Once the controller has saved the record, it redirects to the session variable.</li> </ol> <p>What I don't particularly like about this solution is the need to add the parameter to every applicable link in the views. I'm wondering if there's a way to build this all into the controller.</p> <p>One better way I was thinking was to:</p> <ol> <li>Place a before_filter on the "edit" action to save the referrer (is this reliable enough?) into the session.</li> <li>When "update" is hit, the controller will redirect to the session variable and then delete the session variable.</li> </ol> <p>Any thoughts on the best way to do this?</p>
[ { "answer_id": 125988, "author": "Patrick McKenzie", "author_id": 15046, "author_profile": "https://Stackoverflow.com/users/15046", "pm_score": 2, "selected": false, "text": "#in edit controller\n...\nflash[:page_to_redirect_to] = request.referer || \"/my/default/path\"\n...\n\n#in save controller\nredirect_to flash[:page_to_redirect_to] || \"/my/default/path\"\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14530/" ]
125,468
<p>I have a repository of files which are unrelated to each other but are common to multiple projects. Each project might only need a subset of these files. For example:</p> <pre><code>/myRepo: /jquery.js /jquery.form.js /jquery.ui.js </code></pre> <p>Project A requires <code>jquery.js</code> and <code>jquery.form.js</code>, whereas Project B requires <code>jquery.js</code> and <code>jquery.ui.js</code></p> <p>I could just do a checkout of <code>myRepo</code> into both projects, but that'd add a lot of unnecessary files into both. What I'd like is some sort of way for each Project to only get the files it needs. One way I thought it might be possible is if I put just the required files into each project and then run an <code>svn update</code> on it, but somehow stop SVN from adding new files to each directory. They'd still get the modifications to the existing files, but no unnecessary files would be added.</p> <p>Is this possible at all?</p>
[ { "answer_id": 125525, "author": "Jonathan Arkell", "author_id": 11052, "author_profile": "https://Stackoverflow.com/users/11052", "pm_score": 1, "selected": false, "text": "find . -print | grep -v '\\.svn' | xargs svn update\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
125,470
<p>I need to create a configuration section, that is able to store key-value pairs in an app.config file and the key-value pairs can be added runtime regardless of their type. It is also important that the value keeps its original type. I need to extend the following interface </p> <pre><code>public interface IPreferencesBackend { bool TryGet&lt;T&gt;(string key, out T value); bool TrySet&lt;T&gt;(string key, T value); } </code></pre> <p>At runtime, I can say something like: </p> <pre><code>My.Foo.Data data = new My.Foo.Data("blabla"); Pref pref = new Preferences(); pref.TrySet("foo.data", data); pref.Save(); My.Foo.Data date = new My.Foo.Data(); pref.TryGet("foo.data", out data); </code></pre> <p>I tried with System.Configuration.Configuration.AppSettings, but the problem with that that it is storing the key-value pairs in a string array. </p> <p>What I need is to have an implementation of System.Configuration.ConfigurationSection, where I can control the how the individual setting is serialized. I noticed that the settings generated by Visual Studio kind of do this. It is using reflection to create all the setting keys. what I need is to do this runtime and dynamically. </p> <pre><code>[System.Configuration.UserScopedSettingAttribute()] [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.Configuration.DefaultSettingValueAttribute("2008-09-24")] public global::System.DateTime DateTime { get { return ((global::System.DateTime)(this["DateTime"])); } set { this["DateTime"] = value; } } </code></pre>
[ { "answer_id": 125490, "author": "Ron Savage", "author_id": 12476, "author_profile": "https://Stackoverflow.com/users/12476", "pm_score": 1, "selected": false, "text": "<key=\"myParam\" value=\"type, value\" />\n <key=\"payRate\" value=\"money,85.79\"/>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260/" ]
125,496
<p>On my rails app I have a list of items (like a task list) and for each item there is a couple of check box to set parameters.</p> <p>When I submit the form, the checked box are stored as zero and the unchecked as null on DB. </p> <p>the question is: Is there a way to configure it? To store the data on a more traditional 0 or 1, because I think that storing null as false and 0 as true is a bit confusing, specially if another app (like a C app) needs to read the data.</p>
[ { "answer_id": 127702, "author": "Yardboy", "author_id": 9550, "author_profile": "https://Stackoverflow.com/users/9550", "pm_score": 3, "selected": true, "text": "club_member if model.club_member value=\"1\"\n" }, { "answer_id": 2599922, "author": "Fabian ", "author_id": 311894, "author_profile": "https://Stackoverflow.com/users/311894", "pm_score": 1, "selected": false, "text": "value.to_i.zero? >> a=nil\n=> nil\n>> a.to_i.zero?\n=> true\n>> a=0\n=> 0\n>> a.to_i.zero?\n=> true\n>> a=3\n=> 3\n>> a.to_i.zero?\n=> false\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/440867/" ]
125,512
<p>In my rails app I use the validation helpers in my active record objects and they are great. When there is a problem I see the standard "3 errors prohibited this foobar from being saved" on my web page along with the individual problems. </p> <p>Is there any way I can override this default message with my own?</p>
[ { "answer_id": 125563, "author": "Toby Hede", "author_id": 14971, "author_profile": "https://Stackoverflow.com/users/14971", "pm_score": 1, "selected": false, "text": "<% if(!@model.errors.empty?) %>\n<div id=\"error_message\"> \n <h2>\n <%= image_tag(\"error.png\", :align => \"top\", :alt => \"Error\") -%>\n Oops, there was a problem editing your information.\n </h2>\n <%= short_error_messages_for(:model) %>\n</div>\n<% end %> \n def short_error_messages_for(object_name)\n object = instance_variable_get(\"@#{object_name}\")\n if object && !object.errors.empty?\n content_tag(\"ul\", object.errors.full_messages.collect { |msg| content_tag(\"li\", msg) } ) \n else\n \"\"\n end\n end \n" }, { "answer_id": 127613, "author": "Yardboy", "author_id": 9550, "author_profile": "https://Stackoverflow.com/users/9550", "pm_score": 5, "selected": true, "text": "error_messages_for :header_message error_messages_for 'model', :header_message => \"You have some errors that prevented saving this model\"" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16779/" ]
125,523
<p>Is it possible to use an attribute of a child to group a query?</p> <pre><code>Post.find(:all, :include =&gt; [ :authors, :comments ], :group=&gt;'authors.city') </code></pre> <p>does not work. </p> <p>However, I am able to use <code>author.city</code> as part of the conditions.</p>
[ { "answer_id": 125537, "author": "Terry G Lorber", "author_id": 809, "author_profile": "https://Stackoverflow.com/users/809", "pm_score": 1, "selected": false, "text": "Post.find(:all, :include => [ :author, :comments ], :group=>'authors.city')\n class Post < AR:Base\n belongs_to :author\n has_many :comments\n end\n\n class Author < AR:Base\n has_many :posts\n end\n\n class Comment < AR:Base\n belongs_to :post\n end\n posts\n id\n author_id\n authors\n id\n comments\n id\n post_id\n" }, { "answer_id": 126677, "author": "Codebeef", "author_id": 12037, "author_profile": "https://Stackoverflow.com/users/12037", "pm_score": 0, "selected": false, "text": "Post.find(:all, :include => [ :authors, :comments ], :group=>'authors.city')\n" }, { "answer_id": 137698, "author": "sutee", "author_id": 1227001, "author_profile": "https://Stackoverflow.com/users/1227001", "pm_score": 2, "selected": false, "text": "Post.find(:all, :include => [ :author, :comments ], :joins=>\"INNER JOIN authors ON posts.author_id=authors.id\", :group=>'authors.city')\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1227001/" ]
125,536
<p>I want to add a constant value onto an incoming bound integer. In fact I have several places where I want to bind to the same source value but add different constants. So the ideal solution would be something like this...</p> <pre><code>&lt;TextBox Canvas.Top="{Binding ElementName=mySource, Path=myInt, Constant=5}"/&gt; &lt;TextBox Canvas.Top="{Binding ElementName=mySource, Path=myInt, Constant=8}"/&gt; &lt;TextBox Canvas.Top="{Binding ElementName=mySource, Path=myInt, Constant=24}"/&gt; </code></pre> <p>(NOTE: This is an example to show the idea, my actual binding scenario is not to the canvas property of a TextBox. But this shows the idea more clearly) </p> <p>At the moment the only solution I can think of is to expose many different source properties each of which adds on a different constant to the same internal value. So I could do something like this...</p> <pre><code>&lt;TextBox Canvas.Top="{Binding ElementName=mySource, Path=myIntPlus5}"/&gt; &lt;TextBox Canvas.Top="{Binding ElementName=mySource, Path=myIntPlus8}"/&gt; &lt;TextBox Canvas.Top="{Binding ElementName=mySource, Path=myIntPlus24}"/&gt; </code></pre> <p>But this is pretty grim because in the future I might need to keep adding new properties for new constants. Also if I need to change the value added I need to go an alter the source object which is pretty naff. </p> <p>There must be a more generic way than this? Any WPF experts got any ideas?</p>
[ { "answer_id": 125592, "author": "billjamesdev", "author_id": 13824, "author_profile": "https://Stackoverflow.com/users/13824", "pm_score": 0, "selected": false, "text": "public Integer get( Integer key ) { return baseInt + key; } // or some such\n" }, { "answer_id": 126483, "author": "Ian Oakes", "author_id": 21606, "author_profile": "https://Stackoverflow.com/users/21606", "pm_score": 3, "selected": false, "text": "public class AddValueConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n object result = value;\n int parameterValue;\n\n if (value != null && targetType == typeof(Int32) && \n int.TryParse((string)parameter, \n NumberStyles.Integer, culture, out parameterValue))\n {\n result = (int)value + (int)parameterValue;\n }\n\n return result;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n <Setter Property=\"Grid.ColumnSpan\"\n Value=\"{Binding \n Path=ColumnDefinitions.Count,\n RelativeSource={RelativeSource AncestorType=Grid},\n Converter={StaticResource addValueConverter},\n ConverterParameter=1}\"\n />\n" }, { "answer_id": 7133443, "author": "Rachel", "author_id": 302677, "author_profile": "https://Stackoverflow.com/users/302677", "pm_score": 5, "selected": false, "text": "MathConverter <TextBox Canvas.Top=\"{Binding SomeValue, \n Converter={StaticResource MathConverter},\n ConverterParameter=@VALUE+5}\" />\n Width=\"{Binding ElementName=RootWindow, Path=ActualWidth,\n Converter={StaticResource MathConverter},\n ConverterParameter=((@VALUE-200)*.3)}\"\n" }, { "answer_id": 61399582, "author": "Péter Hidvégi", "author_id": 4994278, "author_profile": "https://Stackoverflow.com/users/4994278", "pm_score": 0, "selected": false, "text": "namespace Example.Converters\n{\n public class ArithmeticConverter : IMultiValueConverter\n { \n public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n {\n double result = 0;\n\n for (int i = 0; i < values.Length; i++)\n {\n if (!double.TryParse(values[i]?.ToString(), out var parsedNumber)) continue;\n\n if (TryGetOperations(parameter, i, out var operation))\n {\n result = operation(result, parsedNumber);\n }\n }\n\n return result;\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)\n {\n return new[] { Binding.DoNothing, false };\n }\n\n\n private static bool TryGetOperations(object parameter, int operationIndex, out Func<double, double, double> operation)\n {\n operation = null;\n var operations = parameter?.ToString().Split(',');\n\n if (operations == null || operations.Length == 0) return false;\n\n if (operations.Length <= operationIndex)\n {\n operationIndex = operations.Length - 1;\n }\n\n return Operations.TryGetValue(operations[operationIndex]?.ToString(), out operation);\n }\n\n public const string Add = \"+\";\n public const string Subtract = \"-\";\n public const string Multiply = \"*\";\n public const string Divide = \"/\";\n\n private static IDictionary<string, Func<double, double, double>> Operations = new Dictionary<string, Func<double, double, double>>\n {\n { Add, (x, y) => x + y },\n { Subtract, (x, y) => x - y },\n { Multiply, (x, y) => x * y },\n { Divide, (x, y) => x / y }\n };\n }\n}\n <UserControl \n xmlns:converters=\"clr-namespace:Example.Converters\">\n <UserControl.Resources>\n <converters:ArithmeticConverter x:Key=\"ArithmeticConverter\" />\n </UserControl.Resources>\n <MultiBinding Converter=\"{StaticResource ArithmeticConverter}\" ConverterParameter=\"+,-\">\n <Binding Path=\"NumberToAdd\" />\n <Binding Path=\"NumberToSubtract\" />\n</MultiBinding>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6276/" ]
125,541
<p><a href="https://stackoverflow.com/questions/63938/how-do-i-show-data-in-the-header-of-a-sql-2005-reporting-services-report">This question</a> was very helpful, however I have a list control in my report, and when the report grows over 1 page, data in the header only shows up on the last page of the report.</p> <p>Apparently, hidden textboxes have to be on every page of the report for header to function properly. How do I do that? The only control I have in the list is a textbox with bunch of text that grows way over 1 page.</p>
[ { "answer_id": 1123865, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "=Parameters!Footer.Value Footer" }, { "answer_id": 6177284, "author": "mon", "author_id": 776379, "author_profile": "https://Stackoverflow.com/users/776379", "pm_score": 3, "selected": false, "text": "Hidden =ReportItems!TextBox1.Value" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3661/" ]
125,557
<p>In a tic-tac-toe implementation I guess that the challenging part is to determine the best move to be played by the machine.</p> <p>What are the algorithms that can pursued? I'm looking into implementations from simple to complex. How would I go about tackling this part of the problem?</p>
[ { "answer_id": 11476076, "author": "Kaushik", "author_id": 1524317, "author_profile": "https://Stackoverflow.com/users/1524317", "pm_score": 3, "selected": false, "text": "board[5]=2 (2, 4, 6 or 8) Posswin(p) p 18 3 x 3 x 2 X 50 5 x 5 x 2 Go (n) [n] X Turn = 1 Go(1) (upper left corner).\nTurn = 2 If Board[5] is blank, Go(5), else Go(1).\nTurn = 3 If Board[9] is blank, Go(9), else Go(3).\nTurn = 4 If Posswin(X) is not 0, then Go(Posswin(X)) i.e. [ block opponent’s win], else Go(Make2).\nTurn = 5 if Posswin(X) is not 0 then Go(Posswin(X)) [i.e. win], else if Posswin(O) is not 0, then Go(Posswin(O)) [i.e. block win], else if Board[7] is blank, then Go(7), else Go(3). [to explore other possibility if there be any ].\nTurn = 6 If Posswin(O) is not 0 then Go(Posswin(O)), else if Posswin(X) is not 0, then Go(Posswin(X)), else Go(Make2).\nTurn = 7 If Posswin(X) is not 0 then Go(Posswin(X)), else if Posswin(X) is not 0, then Go(Posswin(O)) else go anywhere that is blank.\nTurn = 8 if Posswin(O) is not 0 then Go(Posswin(O)), else if Posswin(X) is not 0, then Go(Posswin(X)), else go anywhere that is blank.\nTurn = 9 Same as Turn=7.\n" }, { "answer_id": 48128230, "author": "Ben Carp", "author_id": 7224430, "author_profile": "https://Stackoverflow.com/users/7224430", "pm_score": 0, "selected": false, "text": "let gameBoard: [\n [null, null, null],\n [null, null, null],\n [null, null, null]\n]\n\nconst SYMBOLS = {\n X:'X',\n O:'O'\n}\n\nconst RESULT = {\n INCOMPLETE: \"incomplete\",\n PLAYER_X_WON: SYMBOLS.x,\n PLAYER_O_WON: SYMBOLS.o,\n tie: \"tie\"\n}\n\n function checkSuccession (line){\n if (line === SYMBOLS.X.repeat(3)) return SYMBOLS.X\n if (line === SYMBOLS.O.repeat(3)) return SYMBOLS.O\n return false \n}\n\nfunction getResult(board){\n\n let result = RESULT.incomplete\n if (moveCount(board)<5){\n return result\n }\n\n let lines\n\n //first we check row, then column, then diagonal\n for (var i = 0 ; i<3 ; i++){\n lines.push(board[i].join(''))\n }\n\n for (var j=0 ; j<3; j++){\n const column = [board[0][j],board[1][j],board[2][j]]\n lines.push(column.join(''))\n }\n\n const diag1 = [board[0][0],board[1][1],board[2][2]]\n lines.push(diag1.join(''))\n const diag2 = [board[0][2],board[1][1],board[2][0]]\n lines.push(diag2.join(''))\n \n for (i=0 ; i<lines.length ; i++){\n const succession = checkSuccesion(lines[i])\n if(succession){\n return succession\n }\n }\n\n //Check for tie\n if (moveCount(board)==9){\n return RESULT.tie\n }\n\n return result\n} const copyBoard = (board) => board.map( \n row => row.map( square => square ) \n)\n\nfunction getAvailableMoves (board) {\n let availableMoves = []\n for (let row = 0 ; row<3 ; row++){\n for (let column = 0 ; column<3 ; column++){\n if (board[row][column]===null){\n availableMoves.push({row, column})\n }\n }\n }\n return availableMoves\n}\n\nfunction applyMove(board,move, symbol) {\n board[move.row][move.column]= symbol\n return board\n}\n \nfunction getBestMove (board, symbol){\n\n let availableMoves = getAvailableMoves(board)\n\n let availableMovesAndScores = []\n\n for (var i=0 ; i<availableMoves.length ; i++){\n let move = availableMoves[i]\n let newBoard = copyBoard(board)\n newBoard = applyMove(newBoard,move, symbol)\n result = getResult(newBoard,symbol).result\n let score\n if (result == RESULT.tie) {score = 0}\n else if (result == symbol) {\n score = 1\n }\n else {\n let otherSymbol = (symbol==SYMBOLS.x)? SYMBOLS.o : SYMBOLS.x\n nextMove = getBestMove(newBoard, otherSymbol)\n score = - (nextMove.score)\n }\n if(score === 1) // Performance optimization\n return {move, score}\n availableMovesAndScores.push({move, score})\n }\n\n availableMovesAndScores.sort((moveA, moveB )=>{\n return moveB.score - moveA.score\n })\n return availableMovesAndScores[0]\n }" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19790/" ]
125,570
<p>I am actually working on SP in SQL 2005. Using SP i am creating a job and am scheduling it for a particular time. These jobs take atleast 5 to 10 min to complete as the database is very huge. But I am not aware of how to check the status of the Job. I want to know if it has got completed successfully or was there any error in execution. On exception i also return proper error code. But i am not aware of where i can check for this error code.</p>
[ { "answer_id": 125738, "author": "Philip Fourie", "author_id": 11123, "author_profile": "https://Stackoverflow.com/users/11123", "pm_score": 3, "selected": true, "text": " exec msdb.dbo.sp_help_jobactivity @job_id = (your job_id here)\n" }, { "answer_id": 1497976, "author": "Faiz", "author_id": 82961, "author_profile": "https://Stackoverflow.com/users/82961", "pm_score": 0, "selected": false, "text": "Use msdb\ngo\n\nselect distinct j.Name as \"Job Name\", j.description as \"Job Description\", h.run_date as LastStatusDate, \ncase h.run_status \nwhen 0 then 'Failed' \nwhen 1 then 'Successful' \nwhen 3 then 'Cancelled' \n--when 4 then 'In Progress' \nend as JobStatus\nfrom sysJobHistory h, sysJobs j\nwhere j.job_id = h.job_id and h.run_date = \n(select max(hi.run_date) from sysJobHistory hi where h.job_id = hi.job_id)\norder by 1\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20951/" ]
125,577
<p>I open a connection like this:</p> <pre><code>Using conn as New OdbcConnection(connectionString) conn.Open() //do stuff End Using </code></pre> <p>If connection pooling is enabled, the connection is not physically closed but released to the pool and will get reused. If it is disabled, it will be physically closed.</p> <p>Is there any way of knowing <strong>programmatically</strong> <em>if</em> connection pooling is enabled or not? and the number of used and unused connections currently open in the pool?</p> <p><strong>EDIT:</strong> I need to get this information from within the program, I can't go and check it manually on every single PC where the program will be deployed.</p>
[ { "answer_id": 838566, "author": "Anand", "author_id": 57817, "author_profile": "https://Stackoverflow.com/users/57817", "pm_score": 0, "selected": false, "text": "select db_name(dbid) , count(*) 'connections count'\n from master..sysprocesses\n where spid > 50 and spid @@spid\n group by db_name(dbid)\n order by count(*) desc\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10786/" ]
125,606
<p>I'm working on a C#/ASP.NET web application, and I have a number of situations where I need to do locking. Ideally, I want the locks to act independently, since they have nothing to do with each other. I've been considering <code>[MethodImpl(MethodImplOptions.Synchronized)]</code> and a few ways of using <code>lock()</code>, but I have a few questions/concerns. </p> <p>It seems like MethodImplOptions.Synchronized<code>will essentially do</code>lock(this)`. If that's the case, it seems like a thread entering any synchronized method would block <em>all other</em> threads from entering <em>any</em> synchronized method. Is that right? If so, this isn't granular enough. At that point, it seems like I may as well use Application.Lock. (But please correct me if I'm wrong.)</p> <p>Concerning <code>lock()</code>, I'm trying to figure out what I should pass in. Should I create a set of objects solely for this purpose, and use each one for a different lock? Is there a better way?</p> <p>Thanks in advance!</p>
[ { "answer_id": 125622, "author": "Hamish Smith", "author_id": 15572, "author_profile": "https://Stackoverflow.com/users/15572", "pm_score": 2, "selected": false, "text": "private object lockForSomeResource = new object();\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13348/" ]
125,610
<p>Ok, my web application is at <strong>C:\inetpub\wwwroot\website</strong></p> <p>The files I want to link to are in <strong>S:\someFolder</strong></p> <p>Can I make a link in the webapp that will direct to the file in <strong>someFolder</strong>?</p>
[ { "answer_id": 125611, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 4, "selected": true, "text": "/virtdirect/somefolder/" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14777/" ]
125,612
<p>I have a menu running off of a sitemap which one of the SiteMapNode looks like this: </p> <pre><code>&lt;siteMapNode title="Gear" description="" url=""&gt; &lt;siteMapNode title="Armor" description="" url="~/Armor.aspx" /&gt; &lt;siteMapNode title="Weapons" description="" url="~/Weapons.aspx" /&gt; &lt;/siteMapNode&gt; </code></pre> <p>I also have a Skin applied to the asp:menu which uses the following css definition:</p> <pre><code>.nav-bar { z-index: 2; margin-top: -5%; position: absolute; top: 281px; font-family: Jokewood; font-style: italic; } </code></pre> <p>When I run the website and mouseOver the Gear link, the Jokewood font is not applied to those items, how can I apply the css to the Armor and Weapons titles?</p> <p><strong>Update</strong><br> I should of mentioned that the font is displayed correctly on all non-nested siteMapNodes.</p>
[ { "answer_id": 125706, "author": "Alexander Prokofyev", "author_id": 11256, "author_profile": "https://Stackoverflow.com/users/11256", "pm_score": 1, "selected": true, "text": "<asp:Menu ID=\"Menu1\" runat=\"server\" >\n <StaticMenuStyle CssClass=\"nav-bar\" />\n <DynamicMenuStyle CssClass=\"nav-bar\" />\n</asp:Menu>\n" }, { "answer_id": 125742, "author": "Matt R", "author_id": 4298, "author_profile": "https://Stackoverflow.com/users/4298", "pm_score": 0, "selected": false, "text": "<asp:Menu runat=\"server\" CssClass=\"nav-bar\" />\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4298/" ]
125,619
<p>I'm working on an app that requires no user input, but I don't want the iPhone to enter the power saving mode.</p> <p>Is it possible to disable power saving from an app?</p>
[ { "answer_id": 125645, "author": "lajos", "author_id": 3740, "author_profile": "https://Stackoverflow.com/users/3740", "pm_score": 9, "selected": true, "text": "[[UIApplication sharedApplication] setIdleTimerDisabled:YES];\n UIApplication.shared.isIdleTimerDisabled = true\n" }, { "answer_id": 29295059, "author": "Vettiyanakan", "author_id": 2082723, "author_profile": "https://Stackoverflow.com/users/2082723", "pm_score": 5, "selected": false, "text": "UIApplication.sharedApplication().idleTimerDisabled = true\n" }, { "answer_id": 36068248, "author": "JMStudios.jrichardson", "author_id": 2232919, "author_profile": "https://Stackoverflow.com/users/2232919", "pm_score": 2, "selected": false, "text": "UIApplication.sharedApplication().idleTimerDisabled = true \n UIApplication.sharedApplication().idleTimerDisabled = false\nUIApplication.sharedApplication().idleTimerDisabled = true\n" }, { "answer_id": 40866960, "author": "Charlie Seligman", "author_id": 646818, "author_profile": "https://Stackoverflow.com/users/646818", "pm_score": 4, "selected": false, "text": "UIApplication.shared.isIdleTimerDisabled = true\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3740/" ]
125,620
<p>I'm trying to put several images together into one big image, and am looking for an algorithm which determines the placing most optimally. The images can't be rotated or resized, but the position in the resulting image is not important.</p> <p>edit: added no resize constraint</p>
[ { "answer_id": 125952, "author": "Davy Landman", "author_id": 11098, "author_profile": "https://Stackoverflow.com/users/11098", "pm_score": 1, "selected": false, "text": "Images: array of the input images\nResultMap: 2d array of Booleans\nFinalImage: large image\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3197/" ]
125,627
<p>I want to call a web service, but I won't know the url till runtime.</p> <p>Whats the best way to get the web reference in, without actually committing to a url.</p> <p>What about having 1 client hit the same web service on say 10 different domains?</p>
[ { "answer_id": 125637, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "service = new MyWebService.MyWebService();\nservice.Url = myWebServiceUrl;\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1220/" ]
125,632
<p>When providing a link to a PDF file on a website, is it possible to include information in the URL (request parameters) which will make the PDF browser plugin (if used) jump to a particular bookmark instead of just opening at the beginning?</p> <p>Something like: <a href="http://www.somehost.com/user-guide.pdf?bookmark=chapter3" rel="noreferrer">http://www.somehost.com/user-guide.pdf?bookmark=chapter3</a> ?</p> <p>If not a bookmark, would it be possible to go to a particular page?</p> <p>I'm assuming that if there is an answer it may be specific to Adobe's PDF reader plugin or something, and may have version limitations, but I'm mostly interested in whether the technique exists at all.</p>
[ { "answer_id": 125650, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 7, "selected": true, "text": "<a href=\"http://www.domain.com/file.pdf#page=3\">Link text</a>\n <a href=\"http://www.domain.com/file.pdf#nameddest=TOC\">Link text</a>\n" }, { "answer_id": 38049428, "author": "Matas Vaitkevicius", "author_id": 1509764, "author_profile": "https://Stackoverflow.com/users/1509764", "pm_score": 4, "selected": false, "text": "+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| Syntax | Description | Example |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| nameddest=destination | Specifies a named destination in the PDF document | http://example.org/doc.pdf#Chapter6 |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| page=pagenum | Specifies a numbered page in the document, using an integer | http://example.org/doc.pdf#page=3 |\n| | value. The document’s first page has a pagenum value of 1. | |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| comment=commentID | Specifies a comment on a given page in the PDF document. Use | #page=1&comment=452fde0e-fd22-457c-84aa- |\n| | the page command before this command. | 2cf5bed5a349 |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| collab=setting | Sets the comment repository to be used to supply and store | #collab=DAVFDF@http://review_server/Collab |\n| | comments for the document. This overrides the default comment | /user1 |\n| | server for the review or the default preference. The setting is of the | |\n| | form store_type@location, where valid values for store_type are: | |\n| | ● DAVFDF (WebDAV) | |\n| | ● FSFDF (Network folder) | |\n| | ● DB (ADBC) | |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| zoom=scale | Sets the zoom and scroll factors, using float or integer values. For | http://example.org/doc.pdf#page=3&zoom=200,250,100 |\n| zoom=scale,left,top | example, a scale value of 100 indicates a zoom value of 100%. | |\n| | Scroll values left and top are in a coordinate system where 0,0 | |\n| | represents the top left corner of the visible page, regardless of | |\n| | document rotation | |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| view=Fit | Set the view of the displayed page, using the keyword values | http://example.org/doc.pdf#page=72&view=fitH,100 |\n| view=FitH | defined in the PDF language specification. For more information, | |\n| view=FitH,top | see the PDF Reference. | |\n| view=FitV | Scroll values left and top are floats or integers in a coordinate | |\n| view=FitV,left | system where 0,0 represents the top left corner of the visible | |\n| view=FitB | page, regardless of document rotation. | |\n| view=FitBH | Use the page command before this command. | |\n| view=FitBH,top | | |\n| view=FitBV | | |\n| view=FitBV,left | | |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| viewrect=left,top,wd,ht | Sets the view rectangle using float or integer values in a | |\n| | coordinate system where 0,0 represents the top left corner of the | |\n| | visible page, regardless of document rotation. | |\n| | Use the page command before this command. | |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| pagemode=bookmarks | Displays bookmarks or thumbnails. | http://example.org/doc.pdf#pagemode=bookmarks&page=2 |\n| pagemode=thumbs | | |\n| pagemode=none | | |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| scrollbar=1|0 | Turns scrollbars on or off | |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| search=wordList | Opens the Search panel and performs a search for any of thewords in the specified word list. | #search=\"word1 word2\" |\n| | The first matching word ishighlighted in the document. | |\n| | The words must be enclosed in quotation marks and separated byspaces. | |\n| | You can search only for single words. You cannot search for a string of words. | |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| toolbar=1|0 | Turns the toolbar on or off. | |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| statusbar=1|0 | Turns the status bar on or off. | |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| messages=1|0 | Turns the document message bar on or off. | |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| navpanes=1|0 | Turns the navigation panes and tabs on or off. | |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| highlight=lt,rt,top,btm | Highlights a specified rectangle on the displayed page. Use the | |\n| | page command before this command. | |\n| | The rectangle values are integers in a coordinate system where | |\n| | 0,0 represents the top left corner of the visible page, regardless of | |\n| | document rotation | |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n| fdf=URL | Specifies an FDF file to populate form fields in the PDF file beingopened. | #fdf=http://example.org/doc.fdf |\n| | Note: The fdf parameter should be specified last in a URL. | |\n+-------------------------+----------------------------------------------------------------------------------------------+------------------------------------------------------+\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1119/" ]
125,638
<p>At run time I want to dynamically build grid columns (or another display layout) in a WPF ListView. I do not know the number and names of the columns before hand.</p> <p>I want to be able to do:<br/> MyListView.ItemSource = MyDataset;<br/> MyListView.CreateColumns();</p>
[ { "answer_id": 128093, "author": "Greg", "author_id": 11013, "author_profile": "https://Stackoverflow.com/users/11013", "pm_score": 2, "selected": true, "text": " <Style TargetType=\"{x:Type GridViewColumnHeader}\" x:Key=\"gridViewColumnStyle\">\n <EventSetter Event=\"Click\" Handler=\"OnHeaderClicked\"/>\n <EventSetter Event=\"Loaded\" Handler=\"OnHeaderLoaded\"/>\n </Style>\n public MyListView()\n {\n InitializeComponent();\n GridView gridViewHeader = this.listView.View as GridView;\n System.Diagnostics.Debug.Assert(gridViewHeader != null, \"Expected ListView.View should be GridView\");\n if (null != gridViewHeader)\n {\n gridViewHeader.ColumnHeaderContainerStyle = (Style)this.FindResource(\"gridViewColumnStyle\");\n }\n }\n void OnHeaderLoaded(object sender, RoutedEventArgs e)\n {\n GridViewColumnHeader header = (GridViewColumnHeader)sender;\n GridViewColumn column = header.Column;\n e.Handled = true;\n }\n ListView.ItemsSourceProperty.AddOwner(typeof(MyListView), new PropertyMetadata(OnItemsSourceChanged));\n\n static void OnItemsSourceChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)\n {\n MyListView view = (MyListView)sender;\n //do reflection to get column names and types\n //and for each column, add it to your grid view:\n GridViewColumn column = new GridViewColumn();\n //set column properties here...\n view.Columns.Add(column);\n }\n" }, { "answer_id": 872322, "author": "treehouse", "author_id": 106402, "author_profile": "https://Stackoverflow.com/users/106402", "pm_score": 2, "selected": false, "text": " MyListBox.ItemsSource = view;\n ListView myListView = new ListView();\n\n GridView myGridView = new GridView();\n myGridView.AllowsColumnReorder = true;\n myGridView.ColumnHeaderToolTip = \"Employee Information\";\n\n GridViewColumn gvc1 = new GridViewColumn();\n gvc1.DisplayMemberBinding = new Binding(\"FirstName\");\n gvc1.Header = \"FirstName\";\n gvc1.Width = 100;\n myGridView.Columns.Add(gvc1);\n GridViewColumn gvc2 = new GridViewColumn();\n gvc2.DisplayMemberBinding = new Binding(\"LastName\");\n gvc2.Header = \"Last Name\";\n gvc2.Width = 100;\n myGridView.Columns.Add(gvc2);\n GridViewColumn gvc3 = new GridViewColumn();\n gvc3.DisplayMemberBinding = new Binding(\"EmployeeNumber\");\n gvc3.Header = \"Employee No.\";\n gvc3.Width = 100;\n myGridView.Columns.Add(gvc3);\n\n //ItemsSource is ObservableCollection of EmployeeInfo objects\n myListView.ItemsSource = new myEmployees();\n myListView.View = myGridView;\n myStackPanel.Children.Add(myListView);\n" }, { "answer_id": 74018748, "author": "Ali Nehme", "author_id": 7932581, "author_profile": "https://Stackoverflow.com/users/7932581", "pm_score": 0, "selected": false, "text": "private void AddListViewColumns<T>(GridView GvFOO)\n {\n foreach (System.Reflection.PropertyInfo property in typeof(T).GetProperties().Where(p => p.CanWrite)) //loop through the fields of the object\n {\n if (property.Name != \"Id\") //if you don't want to add the id in the list view\n {\n GridViewColumn gvc = new GridViewColumn(); //initialize the new column\n gvc.DisplayMemberBinding = new Binding(property.Name); // bind the column to the field\n if (property.PropertyType == typeof(DateTime)) { gvc.DisplayMemberBinding.StringFormat = \"yyyy-MM-dd\"; } //[optional] if you want to display dates only for DateTime data\n gvc.Header = property.Name; //set header name like the field name\n gvc.Width = (property.Name == \"Description\") ? 200 : 100; //set width dynamically\n GvFOO.Columns.Add(gvc); //add new column to the Gridview\n }\n }\n }\n AddLvTodoColumns<FOO>(GvFoo);\n <ListView x:Name=\"LvFOO\">\n <ListView.View>\n <GridView x:Name=\"GvTodos\"/>\n </ListView.View>\n </ListView>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5189/" ]
125,663
<p>I've been reading the legacy code,which invloves in the customized memory pooling system, then I found that the code uses _aligned_malloc. I wonder what is this function and when do I have to use it. </p> <hr> <p>Thanks all of you. </p> <p>I did read MSDN but what I wanted was the answer like "An example of a reason for wanting a certain alignment is to use the data with the SSE instruction set on x86 where the data must be aligned to a multiple 16".</p> <p>I finally understood what those code means. thanks again.</p>
[ { "answer_id": 125705, "author": "Viktor", "author_id": 17424, "author_profile": "https://Stackoverflow.com/users/17424", "pm_score": 4, "selected": false, "text": "((unsigned int)ptr) % alignment" }, { "answer_id": 14069095, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "_aligned_malloc() memalign openfile() FILE_FLAG_NO_BUFFERING _aligned_malloc(1234, 512);\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15189/" ]
125,664
<p>How do I write a program that tells when my other program ends?</p>
[ { "answer_id": 125698, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 4, "selected": false, "text": "#include <sys/ptrace.h>\n#include <errno.h>\n#include <stdio.h>\n#include <signal.h>\n#include <unistd.h>\n#include <sys/wait.h>\n\nint main(int argc, char** argv) {\n\n int pid = atoi(argv[1]);\n int status;\n siginfo_t si;\n\n switch (ptrace(PTRACE_ATTACH, pid, NULL)) {\n case 0:\n break;\n case -ESRCH:\n case -EPERM:\n return 0;\n default:\n fprintf(stderr, \"Failed to attach child\\n\");\n return 1;\n }\n if (pid != wait(&status)) {\n fprintf(stderr, \"wrong wait signal\\n\");\n return 1;\n }\n if (!WIFSTOPPED(status) || (WSTOPSIG(status) != SIGSTOP)) {\n /* The pid might not be running */\n if (!kill(pid, 0)) {\n fprintf(stderr, \"SIGSTOP didn't stop child\\n\");\n return 1;\n } else {\n return 0;\n }\n }\n if (ptrace(PTRACE_CONT, pid, 0, 0)) {\n fprintf(stderr, \"Failed to restart child\\n\");\n return 1;\n }\n\n while (1) {\n if (waitid(P_PID, pid, &si, WSTOPPED | WEXITED)) {\n // an error occurred.\n if (errno == ECHILD)\n return 0;\n return 1;\n }\n errno = 0;\n\n if (si.si_code & (CLD_STOPPED | CLD_TRAPPED)) {\n /* If the child gets stopped, we have to PTRACE_CONT it\n * this will happen when the child has a child that exits.\n **/\n if (ptrace(PTRACE_CONT, pid, 1, si.si_status)) {\n if (errno == ENOSYS) {\n /* Wow, we're stuffed. Stop and return */\n return 0;\n }\n }\n continue;\n }\n\n if (si.si_code & (CLD_EXITED | CLD_KILLED | CLD_DUMPED)) {\n return si.si_status;\n }\n // Fall through to exiting.\n return 1;\n }\n}\n" }, { "answer_id": 125699, "author": "Justin Yost", "author_id": 657, "author_profile": "https://Stackoverflow.com/users/657", "pm_score": -1, "selected": false, "text": "Foo {\n func Stops(foo_sub) { run foo_sub; return 1; }\n}\n" }, { "answer_id": 125723, "author": "pjf", "author_id": 19422, "author_profile": "https://Stackoverflow.com/users/19422", "pm_score": 2, "selected": false, "text": "system use POSIX qw(:sys_wait_h);\n\nsub child_handler {\n\n while ((my $child = waitpid(-1, WNOHANG)) > 0) {\n # We've caught a process dying, its PID is now in $child.\n # The exit value and other information is in $?\n }\n\n $SIG{CHLD} \\&child_handler; # SysV systems clear handlers when called,\n # so we need to re-instate it.\n}\n\n# This establishes our handler.\n$SIG{CHLD} = \\&child_handler;\n waitpid WNOHANG ->Wait Win32::Process 0 1" }, { "answer_id": 125928, "author": "RichS", "author_id": 6247, "author_profile": "https://Stackoverflow.com/users/6247", "pm_score": 2, "selected": false, "text": " bool WaitForProcessExit( DWORD _dwPID )\n { \n HANDLE hProc = NULL;\n bool bReturn = false;\n\n hProc = OpenProcess(SYNCHRONIZE, FALSE, _dwPID);\n\n if(hProc != NULL)\n {\n if ( WAIT_OBJECT_0 == WaitForSingleObject(hProc, INFINITE) )\n {\n bReturn = true;\n }\n }\n\n CloseHandle(hProc) ;\n }\n\n return bReturn;\n}\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
125,677
<p>So I'm writing a framework on which I want to base a few apps that I'm working on (the framework is there so I have an environment to work with, and a system that will let me, for example, use a single sign-on)</p> <p>I want to make this framework, and the apps it has use a Resource Oriented Architecture.</p> <p>Now, I want to create a URL routing class that is expandable by APP writers (and possibly also by CMS App users, but that's WAYYYY ahead in the future) and I'm trying to figure out the best way to do it by looking at how other apps do it.</p>
[ { "answer_id": 125799, "author": "Mez", "author_id": 20010, "author_profile": "https://Stackoverflow.com/users/20010", "pm_score": 1, "selected": false, "text": "^/users/[\\w-]+/bookmarks/(.+)/$\n^/users/[\\w-]+/bookmarks/$\n^/users/[\\w-]+/$\n" }, { "answer_id": 127196, "author": "Michael Johnson", "author_id": 17688, "author_profile": "https://Stackoverflow.com/users/17688", "pm_score": -1, "selected": false, "text": "/router/controller/action/key1/value1/key2/value2\n router mod_rewrite controller Zend_Controller_Action action actionAction" }, { "answer_id": 128619, "author": "gradbot", "author_id": 17919, "author_profile": "https://Stackoverflow.com/users/17919", "pm_score": 5, "selected": true, "text": "/api/related/joe ApiController relatedDocuments(array('tags' => 'joe')); // the 12 strips the subdirectory my app is running in\n$index = urldecode(substr($_SERVER[\"REQUEST_URI\"], 12)); \n\nRoute::process($index, array(\n \"#^api/related/(.*)$#Di\" => \"ApiController/relatedDocuments/tags\",\n\n \"#^thread/(.*)/post$#Di\" => \"ThreadController/post/title\",\n \"#^thread/(.*)/reply$#Di\" => \"ThreadController/reply/title\",\n \"#^thread/(.*)$#Di\" => \"ThreadController/thread/title\",\n\n \"#^ajax/tag/(.*)/(.*)$#Di\" => \"TagController/add/id/tags\",\n \"#^ajax/reply/(.*)/post$#Di\"=> \"ThreadController/ajaxPost/id\",\n \"#^ajax/reply/(.*)$#Di\" => \"ArticleController/newReply/id\",\n \"#^ajax/toggle/(.*)$#Di\" => \"ApiController/toggle/toggle\",\n\n \"#^$#Di\" => \"HomeController\",\n));\n Route::process($index, array(\n \"#^api/related/(.*)$#Di\" => \"ApiController/relatedDocuments/tags\",\n\n \"#^thread/(.*)$#Di\" => \"ThreadController/route/uri\",\n\n \"#^ajax/tag/(.*)/(.*)$#Di\" => \"TagController/add/id/tags\",\n \"#^ajax/reply/(.*)/post$#Di\"=> \"ThreadController/ajaxPost/id\",\n \"#^ajax/reply/(.*)$#Di\" => \"ArticleController/newReply/id\",\n \"#^ajax/toggle/(.*)$#Di\" => \"ApiController/toggle/toggle\",\n\n \"#^$#Di\" => \"HomeController\",\n));\n function route($args) {\n Route::process($args['uri'], array(\n \"#^(.*)/post$#Di\" => \"ThreadController/post/title\",\n \"#^(.*)/reply$#Di\" => \"ThreadController/reply/title\",\n \"#^(.*)$#Di\" => \"ThreadController/thread/title\",\n ));\n}\n" }, { "answer_id": 11280912, "author": "Gindi Bar Yahav", "author_id": 568867, "author_profile": "https://Stackoverflow.com/users/568867", "pm_score": 0, "selected": false, "text": "${OBJECT}->${REQUEST METHOD}(${PATTERM}, ${CALLBACK}) $app->get(\"/Home\", function() {\n print('Welcome to the home page');\n}\n\n$app->get('/Profile/:memberName', function($memberName) {\n print( 'I\\'m viewing ' . $memberName . '\\'s profile.' );\n}\n\n$app->post('/ContactUs', function() {\n print( 'This action will be fired only if a POST request will occure');\n}\n $app $_FURLTEMPLATES['login'] = array(\n 'i' => array( // Input - how the router parse an incomming path into query string params\n 'pattern' => '@Members/Login/?@i',\n 'matches' => array( 'Application' => 'Members', 'Module' => 'Login' ),\n ),\n 'o' => array( // Output - how the router parse a query string into a route\n '@Application=Members(&|&amp;)Module=Login/?@' => 'Members/Login/'\n )\n);\n $_FURLTEMPLATES['article'] = array(\n 'i' => array(\n 'pattern' => '@CMS/Articles/([\\d]+)/?@i',\n 'matches' => array( 'Application' => \"CMS\",\n 'Module' => 'Articles',\n 'Sector' => 'showArticle',\n 'ArticleID' => '$1' ),\n ),\n 'o' => array(\n '@Application=CMS(&|&amp;)Module=Articles(&|&amp;)Sector=showArticle(&|&amp;)ArticleID=([\\d]+)@' => 'CMS/Articles/$4'\n )\n);\n" }, { "answer_id": 21405881, "author": "c9s", "author_id": 780629, "author_profile": "https://Stackoverflow.com/users/780629", "pm_score": 0, "selected": false, "text": "<?php\nrequire 'vendor/autoload.php'; // use PCRE patterns you need Pux\\PatternCompiler class.\nuse Pux\\Executor;\n\nclass ProductController {\n public function listAction() {\n return 'product list';\n }\n public function itemAction($id) { \n return \"product $id\";\n }\n}\n$mux = new Pux\\Mux;\n$mux->any('/product', ['ProductController','listAction']);\n$mux->get('/product/:id', ['ProductController','itemAction'] , [\n 'require' => [ 'id' => '\\d+', ],\n 'default' => [ 'id' => '1', ]\n]);\n$mux->post('/product/:id', ['ProductController','updateAction'] , [\n 'require' => [ 'id' => '\\d+', ],\n 'default' => [ 'id' => '1', ]\n]);\n$mux->delete('/product/:id', ['ProductController','deleteAction'] , [\n 'require' => [ 'id' => '\\d+', ],\n 'default' => [ 'id' => '1', ]\n]);\n$route = $mux->dispatch('/product/1');\nExecutor::execute($route);\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20010/" ]
125,703
<p>I'm using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that?</p>
[ { "answer_id": 125713, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 7, "selected": false, "text": " with open(\"foo.txt\", \"a\") as f:\n f.write(\"new line\\n\")\n with open(\"foo.txt\", \"r+\") as f:\n old = f.read() # read everything in the file\n f.seek(0) # rewind\n f.write(\"new line\\n\" + old) # write the new line before\n" }, { "answer_id": 126389, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 5, "selected": false, "text": "~ import shutil\nshutil.move(afile, afile + \"~\")\n\ndestination= open(aFile, \"w\")\nsource= open(aFile + \"~\", \"r\")\nfor line in source:\n destination.write(line)\n if <some condition>:\n destination.write(<some additional line> + \"\\n\")\n\nsource.close()\ndestination.close()\n shutil import os\nos.rename(aFile, aFile + \"~\")\n" }, { "answer_id": 130844, "author": "mhawke", "author_id": 21945, "author_profile": "https://Stackoverflow.com/users/21945", "pm_score": 4, "selected": false, "text": "import os\nfrom mmap import mmap\n\ndef insert(filename, str, pos):\n if len(str) < 1:\n # nothing to insert\n return\n\n f = open(filename, 'r+')\n m = mmap(f.fileno(), os.path.getsize(filename))\n origSize = m.size()\n\n # or this could be an error\n if pos > origSize:\n pos = origSize\n elif pos < 0:\n pos = 0\n\n m.resize(origSize + len(str))\n m[pos+len(str):] = m[pos:origSize]\n m[pos:pos+len(str)] = str\n m.close()\n f.close()\n" }, { "answer_id": 1811866, "author": "Dave", "author_id": 220371, "author_profile": "https://Stackoverflow.com/users/220371", "pm_score": 6, "selected": false, "text": "fileinput import sys\nimport fileinput\n\n# replace all occurrences of 'sit' with 'SIT' and insert a line after the 5th\nfor i, line in enumerate(fileinput.input('lorem_ipsum.txt', inplace=1)):\n sys.stdout.write(line.replace('sit', 'SIT')) # replace 'sit' and write\n if i == 4: sys.stdout.write('\\n') # write a blank line after the 5th line\n" }, { "answer_id": 13464228, "author": "Maxime R.", "author_id": 1792823, "author_profile": "https://Stackoverflow.com/users/1792823", "pm_score": 4, "selected": false, "text": "# open file with r+b (allow write and binary mode)\nf = open(\"file.log\", 'r+b') \n# read entire content of file into memory\nf_content = f.read()\n# basically match middle line and replace it with itself and the extra line\nf_content = re.sub(r'(middle line)', r'\\1\\nnew line', f_content)\n# return pointer to top of file so we can re-write the content with replaced string\nf.seek(0)\n# clear file content \nf.truncate()\n# re-write the content with the updated content\nf.write(f_content)\n# close file\nf.close()\n # open file with r+b (allow write and binary mode)\nf = open(\"file.log\" , 'r+b') \n# get array of lines\nf_content = f.readlines()\n# get middle line\nmiddle_line = len(f_content)/2\n# overwrite middle line\nf_content[middle_line] += \"\\nnew line\"\n# return pointer to top of file so we can re-write the content with replaced string\nf.seek(0)\n# clear file content \nf.truncate()\n# re-write the content with the updated content\nf.write(''.join(f_content))\n# close file\nf.close()\n" }, { "answer_id": 35149780, "author": "ananth krishnan", "author_id": 5871801, "author_profile": "https://Stackoverflow.com/users/5871801", "pm_score": 1, "selected": false, "text": "import tempfile\n\nclass FileModifierError(Exception):\n pass\n\nclass FileModifier(object):\n\n def __init__(self, fname):\n self.__write_dict = {}\n self.__filename = fname\n self.__tempfile = tempfile.TemporaryFile()\n with open(fname, 'rb') as fp:\n for line in fp:\n self.__tempfile.write(line)\n self.__tempfile.seek(0)\n\n def write(self, s, line_number = 'END'):\n if line_number != 'END' and not isinstance(line_number, (int, float)):\n raise FileModifierError(\"Line number %s is not a valid number\" % line_number)\n try:\n self.__write_dict[line_number].append(s)\n except KeyError:\n self.__write_dict[line_number] = [s]\n\n def writeline(self, s, line_number = 'END'):\n self.write('%s\\n' % s, line_number)\n\n def writelines(self, s, line_number = 'END'):\n for ln in s:\n self.writeline(s, line_number)\n\n def __popline(self, index, fp):\n try:\n ilines = self.__write_dict.pop(index)\n for line in ilines:\n fp.write(line)\n except KeyError:\n pass\n\n def close(self):\n self.__exit__(None, None, None)\n\n def __enter__(self):\n return self\n\n def __exit__(self, type, value, traceback):\n with open(self.__filename,'w') as fp:\n for index, line in enumerate(self.__tempfile.readlines()):\n self.__popline(index, fp)\n fp.write(line)\n for index in sorted(self.__write_dict):\n for line in self.__write_dict[index]:\n fp.write(line)\n self.__tempfile.close()\n with FileModifier(filename) as fp:\n fp.writeline(\"String 1\", 0)\n fp.writeline(\"String 2\", 20)\n fp.writeline(\"String 3\") # To write at the end of the file\n" }, { "answer_id": 53124215, "author": "G. LC", "author_id": 9877204, "author_profile": "https://Stackoverflow.com/users/9877204", "pm_score": -1, "selected": false, "text": "$ cat my_data.txt\nThis is a data file\nwith all of my data in it.\n os sed import os\n\n# Identifiers used are:\nmy_data_file = \"my_data.txt\"\ncommand = \"sed -i 's/all/none/' my_data.txt\"\n\n# Execute the command\nos.system(command)\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
125,711
<p>I would like to know your experience when you need to take over somebody else's software project - more so when the original software developer has already resigned.</p>
[ { "answer_id": 126414, "author": "Manrico Corazzi", "author_id": 4690, "author_profile": "https://Stackoverflow.com/users/4690", "pm_score": 2, "selected": false, "text": "List<Stuff> stuff = null; \nif (LOG.isDebugEnabled())\n{\n stuff = findStuff();\n LOG.debug(\"Yeah, I'm a smart guy!\");\n for (Stuff stu : stuff)\n {\n LOG.debug(\"I've got this stuff: \" + stu);\n }\n} \nmethodThatUsesStuff(stuff);\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10923/" ]
125,719
<p>Is there any way to edit column names in a DataGridView?</p>
[ { "answer_id": 125731, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 2, "selected": false, "text": "myDataGrid.TableStyles[0].GridColumnStyles[0].HeaderText = \"My Header\"\n" }, { "answer_id": 125758, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 2, "selected": false, "text": "protected void gvCSMeasureCompare_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n if (e.Row.RowType == DataControlRowType.Header)\n e.Row.Cells[0].Text = \"New Header for Column 1\";\n}\n" }, { "answer_id": 125765, "author": "Ryan Spears", "author_id": 11948, "author_profile": "https://Stackoverflow.com/users/11948", "pm_score": 5, "selected": false, "text": "myDataGrid.Columns[0].HeaderText = \"My Header\"\n myDataGrid DataSource" }, { "answer_id": 7487601, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "select ID as \"Customer ID\", CstNm as \"First Name\", CstLstNm as \"Last Name\"\nfrom Customers\n" }, { "answer_id": 15113223, "author": "Bjørn Otto Vasbotten", "author_id": 29397, "author_profile": "https://Stackoverflow.com/users/29397", "pm_score": 4, "selected": false, "text": "dataGridView1.Columns[0].HeaderCell.Value = \"Created\";\ndataGridView1.Columns[1].HeaderCell.Value = \"Name\";\n" }, { "answer_id": 23987540, "author": "user3698169", "author_id": 3698169, "author_profile": "https://Stackoverflow.com/users/3698169", "pm_score": -1, "selected": false, "text": "myDataGrid.Columns[0].HeaderText = \"My Header\"\nmyDataGrid.Bind() ;\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11137/" ]
125,726
<p>Has anyone any reources for learning how to implement SVG with php/mysql (and possibly with php-gtk)? I am thinking of making a top-down garden designer, with drag and drop predefined elements (such as trees/bushes) and definable areas of planting (circles/squares). Gardeners could then track over time how well planting did in a certain area.</p> <p>I don´t really want to get into flash... </p>
[ { "answer_id": 125731, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 2, "selected": false, "text": "myDataGrid.TableStyles[0].GridColumnStyles[0].HeaderText = \"My Header\"\n" }, { "answer_id": 125758, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 2, "selected": false, "text": "protected void gvCSMeasureCompare_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n if (e.Row.RowType == DataControlRowType.Header)\n e.Row.Cells[0].Text = \"New Header for Column 1\";\n}\n" }, { "answer_id": 125765, "author": "Ryan Spears", "author_id": 11948, "author_profile": "https://Stackoverflow.com/users/11948", "pm_score": 5, "selected": false, "text": "myDataGrid.Columns[0].HeaderText = \"My Header\"\n myDataGrid DataSource" }, { "answer_id": 7487601, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "select ID as \"Customer ID\", CstNm as \"First Name\", CstLstNm as \"Last Name\"\nfrom Customers\n" }, { "answer_id": 15113223, "author": "Bjørn Otto Vasbotten", "author_id": 29397, "author_profile": "https://Stackoverflow.com/users/29397", "pm_score": 4, "selected": false, "text": "dataGridView1.Columns[0].HeaderCell.Value = \"Created\";\ndataGridView1.Columns[1].HeaderCell.Value = \"Name\";\n" }, { "answer_id": 23987540, "author": "user3698169", "author_id": 3698169, "author_profile": "https://Stackoverflow.com/users/3698169", "pm_score": -1, "selected": false, "text": "myDataGrid.Columns[0].HeaderText = \"My Header\"\nmyDataGrid.Bind() ;\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
125,730
<p>Why do I get following error when trying to start a ruby on rails application with <pre>mongrel_rails start</pre>?</p> <pre> C:\RailsTest\cookbook2>mongrel_rails start ** WARNING: Win32 does not support daemon mode. ** Daemonized, any open files are closed. Look at log/mongrel.pid and log/mongr el.log for info. ** Starting Mongrel listening at 0.0.0.0:3000 c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../lib/mongrel/t cphack.rb:12:in `initialize_without_backlog': Only one usage of each socket addr ess (protocol/network address/port) is normally permitted. - bind(2) (Errno::EAD DRINUSE) from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/tcphack.rb:12:in `initialize' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel.rb:93:in `new' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel.rb:93:in `initialize' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/configurator.rb:139:in `new' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/configurator.rb:139:in `listener' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/mon grel_rails:99:in `cloaker_' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/configurator.rb:50:in `call' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/configurator.rb:50:in `initialize' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/mon grel_rails:84:in `new' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/mon grel_rails:84:in `run' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/command.rb:212:in `run' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/mon grel_rails:281 from c:/ruby/bin/mongrel_rails:19:in `load' from c:/ruby/bin/mongrel_rails:19 </pre>
[ { "answer_id": 126769, "author": "Dave Nolan", "author_id": 9474, "author_profile": "https://Stackoverflow.com/users/9474", "pm_score": 3, "selected": true, "text": "mongrel_rails start -p 3001\n mongrel_rails install::service ...\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14027/" ]
125,735
<p>I'm using the following code for setting/getting deleting cookies:</p> <pre><code>function get_cookie(cookie_name) { var results = document.cookie.match('(^|;) ?' + cookie_name + '=([^;]*)(;|$)'); if (results) return ( decodeURI(results[2]) ); else return null; } function set_cookie(name, value, exp_y, exp_m, exp_d, path, domain, secure) { var cookie_string = name + "=" + encodeURI(value); if (exp_y) { var expires = new Date(exp_y, exp_m, exp_d); cookie_string += "; expires=" + expires.toGMTString(); } if (path) cookie_string += "; path=" + encodeURI(path); if (domain) cookie_string += "; domain=" + encodeURI(domain); if (secure) cookie_string += "; secure"; document.cookie = cookie_string; } function delete_cookie(cookie_name) { var cookie_date = new Date(); // current date &amp; time cookie_date.setTime(cookie_date.getTime() - 1); document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString(); } </code></pre> <p>but i am getting inconsistent results. for example, a cookie set on the startpage (www.example.com/start) , will not always show up on a subsequent page (www.example.com/foo/thing.jsp). i am setting a cookie "onUnload" of the page using </p> <pre><code>set_cookie("beginrequest", (new Date()).getTime(), null, null, null, "/"); </code></pre> <p>and retrieving + deleting it "onLoad" via </p> <pre><code>loadDur = (new Date()).getTime() - get_cookie("beginrequest"); delete_cookie("beginrequest"); </code></pre> <p>to measure the total amount of time the page took to load.</p> <p>when using firebug, i often see "leftover" beginrequest-cookies and multiple instances of beginrequest with past timestamps.</p> <p>how can i achieve to see just one beginrequest-cookie on every page?</p>
[ { "answer_id": 126265, "author": "Daniel James", "author_id": 2434, "author_profile": "https://Stackoverflow.com/users/2434", "pm_score": 1, "selected": false, "text": "var deleted_cookie = false;\nfunction delete_timestamp() {\n if(!deleted_cookie) delete_cookie(\"beginrequest\");\n deleted_cookie = true;\n}\n var results = document.cookie.match('(^|;) ?' + cookie_name + '=([^;]+)(;|$)');\n" }, { "answer_id": 204337, "author": "Remy Sharp", "author_id": 22617, "author_profile": "https://Stackoverflow.com/users/22617", "pm_score": 1, "selected": false, "text": "<script type=\"text/javascript\"> var start = 1224068624230;</script>\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16542/" ]
125,756
<p>I'm looking for a way to set the default language for visitors comming to a site built in EPiServer for the first time. Not just administrators/editors in the backend, people comming to the public site.</p>
[ { "answer_id": 126318, "author": "user19264", "author_id": 19264, "author_profile": "https://Stackoverflow.com/users/19264", "pm_score": 3, "selected": true, "text": "<sectionGroup name=\"episerver\">\n <section name=\"domainLanguageMappings\" allowDefinition=\"MachineToApplication\" allowLocation=\"false\" type=\"EPiServer.Util.DomainLanguageConfigurationHandler,EPiServer\" />\n <domainLanguageMappings>\n <map domain=\"site.com\" language=\"EN\" />\n <map domain=\"site.se\" language=\"SV\" />\n </domainLanguageMappings>\n <add name=\"EPsDefaultLanguageBranch\" key=\"EN\"/>\n" }, { "answer_id": 126342, "author": "mannu", "author_id": 15858, "author_profile": "https://Stackoverflow.com/users/15858", "pm_score": 0, "selected": false, "text": "<globalization culture=\"sv-SE\" uiCulture=\"sv\" requestEncoding=\"utf-8\" responseEncoding=\"utf-8\" resourceProviderFactoryType=\"EPiServer.Resources.XmlResourceProviderFactory, EPiServer\" />\n" }, { "answer_id": 559007, "author": "Fredrik Haglund", "author_id": 67593, "author_profile": "https://Stackoverflow.com/users/67593", "pm_score": 0, "selected": false, "text": "<site description=\"Example Site\">\n <siteHosts>\n <add name=\"www.site.se\" language=\"sv\" />\n <add name=\"www.site.no\" language=\"no\" />\n <add name=\"www.site.co.uk\" language=\"en-GB\" />\n <add name=\"*\" />\n </siteHosts>\n pageUseBrowserLanguagePreferences=\"true\"" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/452521/" ]
125,785
<p>I need a function written in Excel VBA that will hash passwords using a standard algorithm such as SHA-1. Something with a simple interface like:</p> <pre><code>Public Function CreateHash(Value As String) As String ... End Function </code></pre> <p>The function needs to work on an XP workstation with Excel 2003 installed, but otherwise must use no third party components. It can reference and use DLLs that are available with XP, such as CryptoAPI. </p> <p>Does anyone know of a sample to achieve this hashing functionality?</p>
[ { "answer_id": 482150, "author": "Chris", "author_id": 59198, "author_profile": "https://Stackoverflow.com/users/59198", "pm_score": 6, "selected": false, "text": "' Based on: http://vb.wikia.com/wiki/SHA-1.bas\nOption Explicit\n\nPrivate Type FourBytes\n A As Byte\n B As Byte\n C As Byte\n D As Byte\nEnd Type\nPrivate Type OneLong\n L As Long\nEnd Type\n\nFunction HexDefaultSHA1(Message() As Byte) As String\n Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long\n DefaultSHA1 Message, H1, H2, H3, H4, H5\n HexDefaultSHA1 = DecToHex5(H1, H2, H3, H4, H5)\nEnd Function\n\nFunction HexSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long) As String\n Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long\n xSHA1 Message, Key1, Key2, Key3, Key4, H1, H2, H3, H4, H5\n HexSHA1 = DecToHex5(H1, H2, H3, H4, H5)\nEnd Function\n\nSub DefaultSHA1(Message() As Byte, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)\n xSHA1 Message, &H5A827999, &H6ED9EBA1, &H8F1BBCDC, &HCA62C1D6, H1, H2, H3, H4, H5\nEnd Sub\n\nSub xSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)\n 'CA62C1D68F1BBCDC6ED9EBA15A827999 + \"abc\" = \"A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D\"\n '\"abc\" = \"A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D\"\n\n Dim U As Long, P As Long\n Dim FB As FourBytes, OL As OneLong\n Dim i As Integer\n Dim W(80) As Long\n Dim A As Long, B As Long, C As Long, D As Long, E As Long\n Dim T As Long\n\n H1 = &H67452301: H2 = &HEFCDAB89: H3 = &H98BADCFE: H4 = &H10325476: H5 = &HC3D2E1F0\n\n U = UBound(Message) + 1: OL.L = U32ShiftLeft3(U): A = U \\ &H20000000: LSet FB = OL 'U32ShiftRight29(U)\n\n ReDim Preserve Message(0 To (U + 8 And -64) + 63)\n Message(U) = 128\n\n U = UBound(Message)\n Message(U - 4) = A\n Message(U - 3) = FB.D\n Message(U - 2) = FB.C\n Message(U - 1) = FB.B\n Message(U) = FB.A\n\n While P < U\n For i = 0 To 15\n FB.D = Message(P)\n FB.C = Message(P + 1)\n FB.B = Message(P + 2)\n FB.A = Message(P + 3)\n LSet OL = FB\n W(i) = OL.L\n P = P + 4\n Next i\n\n For i = 16 To 79\n W(i) = U32RotateLeft1(W(i - 3) Xor W(i - 8) Xor W(i - 14) Xor W(i - 16))\n Next i\n\n A = H1: B = H2: C = H3: D = H4: E = H5\n\n For i = 0 To 19\n T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key1), ((B And C) Or ((Not B) And D)))\n E = D: D = C: C = U32RotateLeft30(B): B = A: A = T\n Next i\n For i = 20 To 39\n T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key2), (B Xor C Xor D))\n E = D: D = C: C = U32RotateLeft30(B): B = A: A = T\n Next i\n For i = 40 To 59\n T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key3), ((B And C) Or (B And D) Or (C And D)))\n E = D: D = C: C = U32RotateLeft30(B): B = A: A = T\n Next i\n For i = 60 To 79\n T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key4), (B Xor C Xor D))\n E = D: D = C: C = U32RotateLeft30(B): B = A: A = T\n Next i\n\n H1 = U32Add(H1, A): H2 = U32Add(H2, B): H3 = U32Add(H3, C): H4 = U32Add(H4, D): H5 = U32Add(H5, E)\n Wend\nEnd Sub\n\nFunction U32Add(ByVal A As Long, ByVal B As Long) As Long\n If (A Xor B) < 0 Then\n U32Add = A + B\n Else\n U32Add = (A Xor &H80000000) + B Xor &H80000000\n End If\nEnd Function\n\nFunction U32ShiftLeft3(ByVal A As Long) As Long\n U32ShiftLeft3 = (A And &HFFFFFFF) * 8\n If A And &H10000000 Then U32ShiftLeft3 = U32ShiftLeft3 Or &H80000000\nEnd Function\n\nFunction U32ShiftRight29(ByVal A As Long) As Long\n U32ShiftRight29 = (A And &HE0000000) \\ &H20000000 And 7\nEnd Function\n\nFunction U32RotateLeft1(ByVal A As Long) As Long\n U32RotateLeft1 = (A And &H3FFFFFFF) * 2\n If A And &H40000000 Then U32RotateLeft1 = U32RotateLeft1 Or &H80000000\n If A And &H80000000 Then U32RotateLeft1 = U32RotateLeft1 Or 1\nEnd Function\nFunction U32RotateLeft5(ByVal A As Long) As Long\n U32RotateLeft5 = (A And &H3FFFFFF) * 32 Or (A And &HF8000000) \\ &H8000000 And 31\n If A And &H4000000 Then U32RotateLeft5 = U32RotateLeft5 Or &H80000000\nEnd Function\nFunction U32RotateLeft30(ByVal A As Long) As Long\n U32RotateLeft30 = (A And 1) * &H40000000 Or (A And &HFFFC) \\ 4 And &H3FFFFFFF\n If A And 2 Then U32RotateLeft30 = U32RotateLeft30 Or &H80000000\nEnd Function\n\nFunction DecToHex5(ByVal H1 As Long, ByVal H2 As Long, ByVal H3 As Long, ByVal H4 As Long, ByVal H5 As Long) As String\n Dim H As String, L As Long\n DecToHex5 = \"00000000 00000000 00000000 00000000 00000000\"\n H = Hex(H1): L = Len(H): Mid(DecToHex5, 9 - L, L) = H\n H = Hex(H2): L = Len(H): Mid(DecToHex5, 18 - L, L) = H\n H = Hex(H3): L = Len(H): Mid(DecToHex5, 27 - L, L) = H\n H = Hex(H4): L = Len(H): Mid(DecToHex5, 36 - L, L) = H\n H = Hex(H5): L = Len(H): Mid(DecToHex5, 45 - L, L) = H\nEnd Function\n\n' Convert the string into bytes so we can use the above functions\n' From Chris Hulbert: http://splinter.com.au/blog\n\nPublic Function SHA1HASH(str)\n Dim i As Integer\n Dim arr() As Byte\n ReDim arr(0 To Len(str) - 1) As Byte\n For i = 0 To Len(str) - 1\n arr(i) = Asc(Mid(str, i + 1, 1))\n Next i\n SHA1HASH = Replace(LCase(HexDefaultSHA1(arr)), \" \", \"\")\nEnd Function\n" }, { "answer_id": 29271611, "author": "Leiver Espinoza", "author_id": 4715077, "author_profile": "https://Stackoverflow.com/users/4715077", "pm_score": 3, "selected": false, "text": " Private Const BITS_TO_A_BYTE = 8\n Private Const BYTES_TO_A_WORD = 4\n Private Const BITS_TO_A_WORD = 32\n\n Private m_lOnBits(30)\n Private m_l2Power(30)\n\n Sub SetUpArrays()\n m_lOnBits(0) = CLng(1)\n m_lOnBits(1) = CLng(3)\n m_lOnBits(2) = CLng(7)\n m_lOnBits(3) = CLng(15)\n m_lOnBits(4) = CLng(31)\n m_lOnBits(5) = CLng(63)\n m_lOnBits(6) = CLng(127)\n m_lOnBits(7) = CLng(255)\n m_lOnBits(8) = CLng(511)\n m_lOnBits(9) = CLng(1023)\n m_lOnBits(10) = CLng(2047)\n m_lOnBits(11) = CLng(4095)\n m_lOnBits(12) = CLng(8191)\n m_lOnBits(13) = CLng(16383)\n m_lOnBits(14) = CLng(32767)\n m_lOnBits(15) = CLng(65535)\n m_lOnBits(16) = CLng(131071)\n m_lOnBits(17) = CLng(262143)\n m_lOnBits(18) = CLng(524287)\n m_lOnBits(19) = CLng(1048575)\n m_lOnBits(20) = CLng(2097151)\n m_lOnBits(21) = CLng(4194303)\n m_lOnBits(22) = CLng(8388607)\n m_lOnBits(23) = CLng(16777215)\n m_lOnBits(24) = CLng(33554431)\n m_lOnBits(25) = CLng(67108863)\n m_lOnBits(26) = CLng(134217727)\n m_lOnBits(27) = CLng(268435455)\n m_lOnBits(28) = CLng(536870911)\n m_lOnBits(29) = CLng(1073741823)\n m_lOnBits(30) = CLng(2147483647)\n\n m_l2Power(0) = CLng(1)\n m_l2Power(1) = CLng(2)\n m_l2Power(2) = CLng(4)\n m_l2Power(3) = CLng(8)\n m_l2Power(4) = CLng(16)\n m_l2Power(5) = CLng(32)\n m_l2Power(6) = CLng(64)\n m_l2Power(7) = CLng(128)\n m_l2Power(8) = CLng(256)\n m_l2Power(9) = CLng(512)\n m_l2Power(10) = CLng(1024)\n m_l2Power(11) = CLng(2048)\n m_l2Power(12) = CLng(4096)\n m_l2Power(13) = CLng(8192)\n m_l2Power(14) = CLng(16384)\n m_l2Power(15) = CLng(32768)\n m_l2Power(16) = CLng(65536)\n m_l2Power(17) = CLng(131072)\n m_l2Power(18) = CLng(262144)\n m_l2Power(19) = CLng(524288)\n m_l2Power(20) = CLng(1048576)\n m_l2Power(21) = CLng(2097152)\n m_l2Power(22) = CLng(4194304)\n m_l2Power(23) = CLng(8388608)\n m_l2Power(24) = CLng(16777216)\n m_l2Power(25) = CLng(33554432)\n m_l2Power(26) = CLng(67108864)\n m_l2Power(27) = CLng(134217728)\n m_l2Power(28) = CLng(268435456)\n m_l2Power(29) = CLng(536870912)\n m_l2Power(30) = CLng(1073741824)\n End Sub\n\n Private Function LShift(lValue, iShiftBits)\n If iShiftBits = 0 Then\n LShift = lValue\n Exit Function\n ElseIf iShiftBits = 31 Then\n If lValue And 1 Then\n LShift = &H80000000\n Else\n LShift = 0\n End If\n Exit Function\n ElseIf iShiftBits < 0 Or iShiftBits > 31 Then\n Err.Raise 6\n End If\n\n If (lValue And m_l2Power(31 - iShiftBits)) Then\n LShift = ((lValue And m_lOnBits(31 - (iShiftBits + 1))) * m_l2Power(iShiftBits)) Or &H80000000\n Else\n LShift = ((lValue And m_lOnBits(31 - iShiftBits)) * m_l2Power(iShiftBits))\n End If\n End Function\n\n Private Function RShift(lValue, iShiftBits)\n If iShiftBits = 0 Then\n RShift = lValue\n Exit Function\n ElseIf iShiftBits = 31 Then\n If lValue And &H80000000 Then\n RShift = 1\n Else\n RShift = 0\n End If\n Exit Function\n ElseIf iShiftBits < 0 Or iShiftBits > 31 Then\n Err.Raise 6\n End If\n\n RShift = (lValue And &H7FFFFFFE) \\ m_l2Power(iShiftBits)\n\n If (lValue And &H80000000) Then\n RShift = (RShift Or (&H40000000 \\ m_l2Power(iShiftBits - 1)))\n End If\n End Function\n\n Private Function RotateLeft(lValue, iShiftBits)\n RotateLeft = LShift(lValue, iShiftBits) Or RShift(lValue, (32 - iShiftBits))\n End Function\n\n Private Function AddUnsigned(lX, lY)\n Dim lX4\n Dim lY4\n Dim lX8\n Dim lY8\n Dim lResult\n\n lX8 = lX And &H80000000\n lY8 = lY And &H80000000\n lX4 = lX And &H40000000\n lY4 = lY And &H40000000\n\n lResult = (lX And &H3FFFFFFF) + (lY And &H3FFFFFFF)\n\n If lX4 And lY4 Then\n lResult = lResult Xor &H80000000 Xor lX8 Xor lY8\n ElseIf lX4 Or lY4 Then\n If lResult And &H40000000 Then\n lResult = lResult Xor &HC0000000 Xor lX8 Xor lY8\n Else\n lResult = lResult Xor &H40000000 Xor lX8 Xor lY8\n End If\n Else\n lResult = lResult Xor lX8 Xor lY8\n End If\n\n AddUnsigned = lResult\n End Function\n\n Private Function F(x, y, z)\n F = (x And y) Or ((Not x) And z)\n End Function\n\n Private Function G(x, y, z)\n G = (x And z) Or (y And (Not z))\n End Function\n\n Private Function H(x, y, z)\n H = (x Xor y Xor z)\n End Function\n\n Private Function I(x, y, z)\n I = (y Xor (x Or (Not z)))\n End Function\n\n Private Sub FF(a, b, c, d, x, s, ac)\n a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac))\n a = RotateLeft(a, s)\n a = AddUnsigned(a, b)\n End Sub\n\n Private Sub GG(a, b, c, d, x, s, ac)\n a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac))\n a = RotateLeft(a, s)\n a = AddUnsigned(a, b)\n End Sub\n\n Private Sub HH(a, b, c, d, x, s, ac)\n a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac))\n a = RotateLeft(a, s)\n a = AddUnsigned(a, b)\n End Sub\n\n Private Sub II(a, b, c, d, x, s, ac)\n a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac))\n a = RotateLeft(a, s)\n a = AddUnsigned(a, b)\n End Sub\n\n Private Function ConvertToWordArray(sMessage)\n Dim lMessageLength\n Dim lNumberOfWords\n Dim lWordArray()\n Dim lBytePosition\n Dim lByteCount\n Dim lWordCount\n\n Const MODULUS_BITS = 512\n Const CONGRUENT_BITS = 448\n\n lMessageLength = Len(sMessage)\n\n lNumberOfWords = (((lMessageLength + ((MODULUS_BITS - CONGRUENT_BITS) \\ BITS_TO_A_BYTE)) \\ (MODULUS_BITS \\ BITS_TO_A_BYTE)) + 1) * (MODULUS_BITS \\ BITS_TO_A_WORD)\n ReDim lWordArray(lNumberOfWords - 1)\n\n lBytePosition = 0\n lByteCount = 0\n Do Until lByteCount >= lMessageLength\n lWordCount = lByteCount \\ BYTES_TO_A_WORD\n lBytePosition = (lByteCount Mod BYTES_TO_A_WORD) * BITS_TO_A_BYTE\n lWordArray(lWordCount) = lWordArray(lWordCount) Or LShift(Asc(Mid(sMessage, lByteCount + 1, 1)), lBytePosition)\n lByteCount = lByteCount + 1\n Loop\n\n lWordCount = lByteCount \\ BYTES_TO_A_WORD\n lBytePosition = (lByteCount Mod BYTES_TO_A_WORD) * BITS_TO_A_BYTE\n\n lWordArray(lWordCount) = lWordArray(lWordCount) Or LShift(&H80, lBytePosition)\n\n lWordArray(lNumberOfWords - 2) = LShift(lMessageLength, 3)\n lWordArray(lNumberOfWords - 1) = RShift(lMessageLength, 29)\n\n ConvertToWordArray = lWordArray\n End Function\n\n Private Function WordToHex(lValue)\n Dim lByte\n Dim lCount\n\n For lCount = 0 To 3\n lByte = RShift(lValue, lCount * BITS_TO_A_BYTE) And m_lOnBits(BITS_TO_A_BYTE - 1)\n WordToHex = WordToHex & Right(\"0\" & Hex(lByte), 2)\n Next\n End Function\n\n Public Function MD5(sMessage)\n\n module_md5.SetUpArrays\n\n Dim x\n Dim k\n Dim AA\n Dim BB\n Dim CC\n Dim DD\n Dim a\n Dim b\n Dim c\n Dim d\n\n Const S11 = 7\n Const S12 = 12\n Const S13 = 17\n Const S14 = 22\n Const S21 = 5\n Const S22 = 9\n Const S23 = 14\n Const S24 = 20\n Const S31 = 4\n Const S32 = 11\n Const S33 = 16\n Const S34 = 23\n Const S41 = 6\n Const S42 = 10\n Const S43 = 15\n Const S44 = 21\n\n x = ConvertToWordArray(sMessage)\n\n a = &H67452301\n b = &HEFCDAB89\n c = &H98BADCFE\n d = &H10325476\n\n For k = 0 To UBound(x) Step 16\n AA = a\n BB = b\n CC = c\n DD = d\n\n FF a, b, c, d, x(k + 0), S11, &HD76AA478\n FF d, a, b, c, x(k + 1), S12, &HE8C7B756\n FF c, d, a, b, x(k + 2), S13, &H242070DB\n FF b, c, d, a, x(k + 3), S14, &HC1BDCEEE\n FF a, b, c, d, x(k + 4), S11, &HF57C0FAF\n FF d, a, b, c, x(k + 5), S12, &H4787C62A\n FF c, d, a, b, x(k + 6), S13, &HA8304613\n FF b, c, d, a, x(k + 7), S14, &HFD469501\n FF a, b, c, d, x(k + 8), S11, &H698098D8\n FF d, a, b, c, x(k + 9), S12, &H8B44F7AF\n FF c, d, a, b, x(k + 10), S13, &HFFFF5BB1\n FF b, c, d, a, x(k + 11), S14, &H895CD7BE\n FF a, b, c, d, x(k + 12), S11, &H6B901122\n FF d, a, b, c, x(k + 13), S12, &HFD987193\n FF c, d, a, b, x(k + 14), S13, &HA679438E\n FF b, c, d, a, x(k + 15), S14, &H49B40821\n\n GG a, b, c, d, x(k + 1), S21, &HF61E2562\n GG d, a, b, c, x(k + 6), S22, &HC040B340\n GG c, d, a, b, x(k + 11), S23, &H265E5A51\n GG b, c, d, a, x(k + 0), S24, &HE9B6C7AA\n GG a, b, c, d, x(k + 5), S21, &HD62F105D\n GG d, a, b, c, x(k + 10), S22, &H2441453\n GG c, d, a, b, x(k + 15), S23, &HD8A1E681\n GG b, c, d, a, x(k + 4), S24, &HE7D3FBC8\n GG a, b, c, d, x(k + 9), S21, &H21E1CDE6\n GG d, a, b, c, x(k + 14), S22, &HC33707D6\n GG c, d, a, b, x(k + 3), S23, &HF4D50D87\n GG b, c, d, a, x(k + 8), S24, &H455A14ED\n GG a, b, c, d, x(k + 13), S21, &HA9E3E905\n GG d, a, b, c, x(k + 2), S22, &HFCEFA3F8\n GG c, d, a, b, x(k + 7), S23, &H676F02D9\n GG b, c, d, a, x(k + 12), S24, &H8D2A4C8A\n\n HH a, b, c, d, x(k + 5), S31, &HFFFA3942\n HH d, a, b, c, x(k + 8), S32, &H8771F681\n HH c, d, a, b, x(k + 11), S33, &H6D9D6122\n HH b, c, d, a, x(k + 14), S34, &HFDE5380C\n HH a, b, c, d, x(k + 1), S31, &HA4BEEA44\n HH d, a, b, c, x(k + 4), S32, &H4BDECFA9\n HH c, d, a, b, x(k + 7), S33, &HF6BB4B60\n HH b, c, d, a, x(k + 10), S34, &HBEBFBC70\n HH a, b, c, d, x(k + 13), S31, &H289B7EC6\n HH d, a, b, c, x(k + 0), S32, &HEAA127FA\n HH c, d, a, b, x(k + 3), S33, &HD4EF3085\n HH b, c, d, a, x(k + 6), S34, &H4881D05\n HH a, b, c, d, x(k + 9), S31, &HD9D4D039\n HH d, a, b, c, x(k + 12), S32, &HE6DB99E5\n HH c, d, a, b, x(k + 15), S33, &H1FA27CF8\n HH b, c, d, a, x(k + 2), S34, &HC4AC5665\n\n II a, b, c, d, x(k + 0), S41, &HF4292244\n II d, a, b, c, x(k + 7), S42, &H432AFF97\n II c, d, a, b, x(k + 14), S43, &HAB9423A7\n II b, c, d, a, x(k + 5), S44, &HFC93A039\n II a, b, c, d, x(k + 12), S41, &H655B59C3\n II d, a, b, c, x(k + 3), S42, &H8F0CCC92\n II c, d, a, b, x(k + 10), S43, &HFFEFF47D\n II b, c, d, a, x(k + 1), S44, &H85845DD1\n II a, b, c, d, x(k + 8), S41, &H6FA87E4F\n II d, a, b, c, x(k + 15), S42, &HFE2CE6E0\n II c, d, a, b, x(k + 6), S43, &HA3014314\n II b, c, d, a, x(k + 13), S44, &H4E0811A1\n II a, b, c, d, x(k + 4), S41, &HF7537E82\n II d, a, b, c, x(k + 11), S42, &HBD3AF235\n II c, d, a, b, x(k + 2), S43, &H2AD7D2BB\n II b, c, d, a, x(k + 9), S44, &HEB86D391\n\n a = AddUnsigned(a, AA)\n b = AddUnsigned(b, BB)\n c = AddUnsigned(c, CC)\n d = AddUnsigned(d, DD)\n Next\n\n MD5 = LCase(WordToHex(a) & WordToHex(b) & WordToHex(c) & WordToHex(d))\n End Function\n" }, { "answer_id": 51087561, "author": "Seva Alekseyev", "author_id": 219159, "author_profile": "https://Stackoverflow.com/users/219159", "pm_score": 4, "selected": false, "text": "Public Function SHA1(ByVal s As String) As String\n Dim Enc As Object, Prov As Object\n Dim Hash() As Byte, i As Integer\n\n Set Enc = CreateObject(\"System.Text.UTF8Encoding\")\n Set Prov = CreateObject(\"System.Security.Cryptography.SHA1CryptoServiceProvider\")\n\n Hash = Prov.ComputeHash_2(Enc.GetBytes_4(s))\n\n SHA1 = \"\"\n For i = LBound(Hash) To UBound(Hash)\n SHA1 = SHA1 & Hex(Hash(i) \\ 16) & Hex(Hash(i) Mod 16)\n Next\nEnd Function\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13087/" ]
125,806
<p>First, yes I know about <a href="https://stackoverflow.com/questions/50182/linuxx11-input-library-without-creating-a-window">this question</a>, but I'm looking for a bit more information that that. I have actually, a fairly similar problem, in that I need to be able to capture input for mouse/keyboard/joystick, and I'd also like to avoid SDL if at all possible. I was more or less wondering if anyone knows where I can get some decent primers on handling input from devices in Linux, perhaps even some tutorials. SDL works great for cross-platform input handling, but I'm not going to be using anything else at all from SDL, so I'd like to cut it out altogether. Suggestion, comments, and help are all appreciated. Thanks!</p> <p>Edit for clarity:</p> <p>The point is to capture mouse motion, keyboard press/release, mouse clicks, and potentially joystick handling for a game.</p>
[ { "answer_id": 125935, "author": "skymt", "author_id": 18370, "author_profile": "https://Stackoverflow.com/users/18370", "pm_score": 2, "selected": false, "text": "Documentation/input/input.txt evdev" }, { "answer_id": 128327, "author": "KPexEA", "author_id": 13676, "author_profile": "https://Stackoverflow.com/users/13676", "pm_score": 4, "selected": true, "text": " if(XPending(m_display))\n {\n XNextEvent(m_display, &m_e);\n switch(m_e.type)\n {\n case MotionNotify:\n m_mousex=m_e.xmotion.x;\n m_mousey=m_e.xmotion.y;\n break;\n case ButtonPress:\n switch(m_e.xbutton.button)\n {\n case Button1:\n m_mouseleft=true;\n break;\n case Button3:\n m_mouseright=true;\n break;\n case Button4:/* middle mouse wheel moved */\n m_mousewheel=1;\n break;\n case Button5:/* middle mouse wheel moved */\n m_mousewheel=-1;\n break;\n }\n break;\n case ButtonRelease:\n switch(m_e.xbutton.button)\n {\n case Button1:\n m_mouseleft=false;\n break;\n case Button3:\n m_mouseright=false;\n break;\n }\n break;\n case KeyPress:\n {\n XKeyEvent *ke;\n int ks;\n int key;\n\n ke=&m_e.xkey;\n kGUI::SetKeyShift((ke->state&ShiftMask)!=0);\n kGUI::SetKeyControl((ke->state&ControlMask)!=0);\n ks=XLookupKeysym(ke,(ke->state&ShiftMask)?1:0);\n......\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14838/" ]
125,812
<p>I am investigating the design of a work queue processor where the QueueProcessor retrieves a Command Pattern object from the Queue and executes it in a new thread.</p> <p>I am trying to get my head around a potential Queue lockup scenario where nested Commands may result in a deadlock.</p> <p>E.G.</p> <p>A FooCommand object is placed onto the queue which the QueueProcessor then executes in its own thread.</p> <p>The executing FooCommand places a BarCommand onto the queue.</p> <p>Assuming that the maximum allowed threads was only 1 thread, the QueueProcessor would be in a deadlocked state since the FooCommand is infinitely waiting for the BarCommand to complete.</p> <p>How can this situation be managed? Is a queue object the right object for the job? Are there any checks and balances that can be put into place to resolve this issue?</p> <p>Many thanks. ( application uses C# .NET 3.0 )</p>
[ { "answer_id": 125940, "author": "mancaus", "author_id": 13797, "author_profile": "https://Stackoverflow.com/users/13797", "pm_score": 1, "selected": false, "text": "\npublic void FooCommand()\n{\n Future<int> BarFuture = new Future<int>( () => BarCommand() );\n\n // Do Foo's Processing - Bar will (may) be running in parallel\n\n int barResult = BarFuture.Value;\n\n // More processing that needs barResult\n}\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14515/" ]
125,813
<p>How can I tell in JavaScript what path separator is used in the OS where the script is running?</p>
[ { "answer_id": 15035489, "author": "t98907", "author_id": 1906218, "author_profile": "https://Stackoverflow.com/users/1906218", "pm_score": 8, "selected": false, "text": "path node.js path.sep // on *nix evaluates to a string equal to \"/\"\n const path = require('path')\n" }, { "answer_id": 35246221, "author": "Decoded", "author_id": 2030601, "author_profile": "https://Stackoverflow.com/users/2030601", "pm_score": 4, "selected": false, "text": "' ' \\ %PROGRAM_FILES% (x86)\\Notepad++ var fs = require('fs'); // file system module\nvar targetDir = 'C:\\Program Files (x86)\\Notepad++'; // target installer dir\n\n// read all files in the directory\nfs.readdir(targetDir, function(err, files) {\n\n if(!err){\n for(var i = 0; i < files.length; ++i){\n var currFile = files[i];\n\n console.log(currFile); \n // ex output: 'C:\\Program Files (x86)\\Notepad++\\notepad++.exe'\n\n // attempt to print the parent directory of currFile\n var fileDir = getDir(currFile);\n\n console.log(fileDir); \n // output is empty string, ''...what!?\n }\n }\n});\n\nfunction getDir(filePath){\n if(filePath !== '' && filePath != null){\n\n // this will fail on Windows, and work on Others\n return filePath.substring(0, filePath.lastIndexOf('/') + 1);\n }\n}\n targetDir 0 0 indexOf('/') -1 C:\\Program Files\\Notepad\\Notepad++.exe myGlobals = { isWin: false, isOsX:false, isNix:false };\n // this var could likely a global or available to all parts of your app\nif(/^win/.test(process.platform)) { myGlobals.isWin=true; }\nelse if(process.platform === 'darwin'){ myGlobals.isOsX=true; }\nelse if(process.platform === 'linux') { myGlobals.isNix=true; }\n var appVer = navigator.appVersion;\nif (appVer.indexOf(\"Win\")!=-1) myGlobals.isWin = true;\nelse if (appVer.indexOf(\"Mac\")!=-1) myGlobals.isOsX = true;\nelse if (appVer.indexOf(\"X11\")!=-1) myGlobals.isNix = true;\nelse if (appVer.indexOf(\"Linux\")!=-1) myGlobals.isNix = true;\n function getPathSeparator(){\n if(myGlobals.isWin){\n return '\\\\';\n }\n else if(myGlobals.isOsx || myGlobals.isNix){\n return '/';\n }\n\n // default to *nix system.\n return '/';\n}\n\n// modifying our getDir method from above...\n function getDir(filePath){\n if(filePath !== '' && filePath != null){\n // this will fail on Windows, and work on Others\n return filePath.substring(0, filePath.lastIndexOf(getPathSeparator()) + 1);\n }\n}\n getDir() // in the body of getDir() ...\nvar sepIndex = filePath.lastIndexOf('/');\nif(sepIndex == -1){\n sepIndex = filePath.lastIndexOf('\\\\');\n}\n\n// include the trailing separator\nreturn filePath.substring(0, sepIndex+1);\n var path = require('path');\nvar fileSep = path.sep; // returns '\\\\' on windows, '/' on *nix\n" }, { "answer_id": 65238189, "author": "Benny Neugebauer", "author_id": 451634, "author_profile": "https://Stackoverflow.com/users/451634", "pm_score": 3, "selected": false, "text": "path.sep path.join const path = require('path');\n\nconst directory = 'logs';\nconst file = 'data.json';\n\nconst path1 = `${directory}${path.sep}${file}`;\nconst path2 = path.join(directory, file);\n\nconsole.log(path1); // Shows \"logs\\data.json\" on Windows\nconsole.log(path2); // Also shows \"logs\\data.json\" on Windows\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
125,828
<p>I'm trying to start an external application through <code>system()</code> - for example, <code>system("ls")</code>. I would like to capture its output as it happens so I can send it to another function for further processing. What's the best way to do that in C/C++?</p>
[ { "answer_id": 125856, "author": "wnoise", "author_id": 15464, "author_profile": "https://Stackoverflow.com/users/15464", "pm_score": 3, "selected": false, "text": "FILE *output = popen(\"ls\", \"r\");\n" }, { "answer_id": 125859, "author": "jkramer", "author_id": 12523, "author_profile": "https://Stackoverflow.com/users/12523", "pm_score": 5, "selected": false, "text": "#include <stdio.h>\n\nFILE *popen(const char *command, const char *type);\n\nint pclose(FILE *stream);\n" }, { "answer_id": 125866, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": " FILE *lsofFile_p = popen(\"lsof\", \"r\");\n\n if (!lsofFile_p)\n {\n return -1;\n }\n\n char buffer[1024];\n char *line_p = fgets(buffer, sizeof(buffer), lsofFile_p);\n pclose(lsofFile_p);\n" }, { "answer_id": 125876, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 1, "selected": false, "text": "popen() pclose()" }, { "answer_id": 5224650, "author": "Will", "author_id": 15721, "author_profile": "https://Stackoverflow.com/users/15721", "pm_score": 2, "selected": false, "text": "popen() popen3() int popen3(int fd[3],const char **const cmd) {\n int i, e;\n int p[3][2];\n pid_t pid;\n // set all the FDs to invalid\n for(i=0; i<3; i++)\n p[i][0] = p[i][1] = -1;\n // create the pipes\n for(int i=0; i<3; i++)\n if(pipe(p[i]))\n goto error;\n // and fork\n pid = fork();\n if(-1 == pid)\n goto error;\n // in the parent?\n if(pid) {\n // parent\n fd[STDIN_FILENO] = p[STDIN_FILENO][1];\n close(p[STDIN_FILENO][0]);\n fd[STDOUT_FILENO] = p[STDOUT_FILENO][0];\n close(p[STDOUT_FILENO][1]);\n fd[STDERR_FILENO] = p[STDERR_FILENO][0];\n close(p[STDERR_FILENO][1]);\n // success\n return 0;\n } else {\n // child\n dup2(p[STDIN_FILENO][0],STDIN_FILENO);\n close(p[STDIN_FILENO][1]);\n dup2(p[STDOUT_FILENO][1],STDOUT_FILENO);\n close(p[STDOUT_FILENO][0]);\n dup2(p[STDERR_FILENO][1],STDERR_FILENO);\n close(p[STDERR_FILENO][0]);\n // here we try and run it\n execv(*cmd,const_cast<char*const*>(cmd));\n // if we are there, then we failed to launch our program\n perror(\"Could not launch\");\n fprintf(stderr,\" \\\"%s\\\"\\n\",*cmd);\n _exit(EXIT_FAILURE);\n }\n\n // preserve original error\n e = errno;\n for(i=0; i<3; i++) {\n close(p[i][0]);\n close(p[i][1]);\n }\n errno = e;\n return -1;\n}\n" }, { "answer_id": 26178074, "author": "GreenScape", "author_id": 966376, "author_profile": "https://Stackoverflow.com/users/966376", "pm_score": 2, "selected": false, "text": "stdout FILE pid_t popen2(const char *command, int * infp, int * outfp)\n{\n int p_stdin[2], p_stdout[2];\n pid_t pid;\n\n if (pipe(p_stdin) == -1)\n return -1;\n\n if (pipe(p_stdout) == -1) {\n close(p_stdin[0]);\n close(p_stdin[1]);\n return -1;\n }\n\n pid = fork();\n\n if (pid < 0) {\n close(p_stdin[0]);\n close(p_stdin[1]);\n close(p_stdout[0]);\n close(p_stdout[1]);\n return pid;\n } else if (pid == 0) {\n close(p_stdin[1]);\n dup2(p_stdin[0], 0);\n close(p_stdout[0]);\n dup2(p_stdout[1], 1);\n dup2(::open(\"/dev/null\", O_WRONLY), 2);\n\n /// Close all other descriptors for the safety sake.\n for (int i = 3; i < 4096; ++i) {\n ::close(i);\n }\n\n setsid();\n execl(\"/bin/sh\", \"sh\", \"-c\", command, NULL);\n _exit(1);\n }\n\n close(p_stdin[0]);\n close(p_stdout[1]);\n\n if (infp == NULL) {\n close(p_stdin[1]);\n } else {\n *infp = p_stdin[1];\n }\n\n if (outfp == NULL) {\n close(p_stdout[0]);\n } else {\n *outfp = p_stdout[0];\n }\n\n return pid;\n}\n popen2() int child_stdout = -1;\npid_t child_pid = popen2(\"ls\", 0, &child_stdout);\n\nif (!child_pid) {\n handle_error();\n}\n\nchar buff[128];\nssize_t bytes_read = read(child_stdout, buff, sizeof(buff));\n int child_stdin = -1;\nint child_stdout = -1;\npid_t child_pid = popen2(\"grep 123\", &child_stdin, &child_stdout);\n\nif (!child_pid) {\n handle_error();\n}\n\nconst char text = \"1\\n2\\n123\\n3\";\nssize_t bytes_written = write(child_stdin, text, sizeof(text) - 1);\n\nchar buff[128];\nssize_t bytes_read = read(child_stdout, buff, sizeof(buff));\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10010/" ]
125,850
<p>I have this RewriteRule that works too well :-)</p> <pre><code>RewriteRule ^([^/]*)/$ /script.html?id=$1 [L] </code></pre> <p>The bad thing about this rule is that it also matches physical directories which I don't want.</p> <p>How can I tell the <code>mod_rewrite</code> to ignore physical directories and apply the above rule only when the directory matched does not exist?</p>
[ { "answer_id": 125864, "author": "ctcherry", "author_id": 10322, "author_profile": "https://Stackoverflow.com/users/10322", "pm_score": 3, "selected": true, "text": "RewriteCond %{REQUEST_FILENAME} !-d\nRewriteCond %{REQUEST_FILENAME} !-f\n" }, { "answer_id": 125886, "author": "daniels", "author_id": 9789, "author_profile": "https://Stackoverflow.com/users/9789", "pm_score": 0, "selected": false, "text": "RewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule ^([^/]*)/$ /script.html?id=$1 [L]\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
125,857
<p>Having a problem getting a TreeView control to display node images. The code below works sometimes but fails to show any image at other times.</p> <pre><code> private TreeNode AddNodeForCore(TreeNode root, Core c) { string key = GetImageKey(c); TreeNode t = root.Nodes.Add(c.Name, c.Name, key, key); t.Tag = c; return t; } </code></pre> <p>Note that when it fails, the TreeView fails to show any images for any node. The TreeView does have an ImageList assigned to it, and the image key is definitely in the images collection.</p> <p>Edit:<br> My google-fu is weak. Can't believe I didn't find that answer myself.</p>
[ { "answer_id": 125871, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 2, "selected": false, "text": "public partial class ThisApplication\n{\n Form1 frm;\n\n private void ThisApplication_Startup(object sender, System.EventArgs e)\n {\n frm = new Form1();\n frm.Show();\n\n }\n public partial class ThisApplication\n{\n Form1 frm = new Form1();\n\n\n private void ThisApplication_Startup(object sender, System.EventArgs e)\n {\n frm.Show();\n\n }\n" }, { "answer_id": 125933, "author": "Johan Buret", "author_id": 15366, "author_profile": "https://Stackoverflow.com/users/15366", "pm_score": 1, "selected": false, "text": "TreeView.ImageList TreeView.SelectedImageList" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1389021/" ]
125,875
<p>I need to change the credentials of an already existing Windows service using C#. I am aware of two different ways of doing this.</p> <ol> <li>ChangeServiceConfig, see <a href="http://www.pinvoke.net/default.aspx/advapi32.ChangeServiceConfig" rel="nofollow noreferrer">ChangeServiceConfig on pinvoke.net</a></li> <li>ManagementObject.InvokeMethod using Change as the method name.</li> </ol> <p>Neither seems a very "friendly" way of doing this and I was wondering if I am missing another and better way to do this.</p>
[ { "answer_id": 126549, "author": "Magnus Johansson", "author_id": 3584, "author_profile": "https://Stackoverflow.com/users/3584", "pm_score": 3, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Management;\n\nnamespace ServiceTest\n{\n class Program\n {\n static void Main(string[] args)\n {\n string theServiceName = \"My Windows Service\";\n string objectPath = string.Format(\"Win32_Service.Name='{0}'\", theServiceName);\n using (ManagementObject mngService = new ManagementObject(new ManagementPath(objectPath)))\n {\n object[] wmiParameters = new object[11];\n wmiParameters[6] = @\"domain\\username\";\n wmiParameters[7] = \"password\";\n mngService.InvokeMethod(\"Change\", wmiParameters);\n }\n }\n }\n}\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19676/" ]
125,877
<p>(Not related to versioning the database schema)</p> <p>Applications that interfaces with databases often have domain objects that are composed with data from many tables. Suppose the application were to support versioning, in the sense of CVS, for these domain objects.</p> <p>For some arbitry domain object, how would you design a database schema to handle this requirement? Any experience to share?</p>
[ { "answer_id": 125900, "author": "Jim T", "author_id": 7298, "author_profile": "https://Stackoverflow.com/users/7298", "pm_score": 4, "selected": false, "text": "|Name|D.O.B |Telephone|From|To |\n|Fred|1 april|555-29384|1 |NULL|\n |Name|D.O.B |Telephone|From|To |\n|Fred|1 april|555-29384|1 |1 |\n|Fred|1 april|555-43534|2 |NULL|\n |Name|D.O.B |Telephone|From|To |\n|Fred|1 april|555-29384|1 |1 |\n|Fred|1 april|555-43534|2 |2 |\n" }, { "answer_id": 3465824, "author": "deamon", "author_id": 238134, "author_profile": "https://Stackoverflow.com/users/238134", "pm_score": 2, "selected": false, "text": "@Audited" }, { "answer_id": 30617521, "author": "Thadeuse", "author_id": 1733575, "author_profile": "https://Stackoverflow.com/users/1733575", "pm_score": 0, "selected": false, "text": "Add one property of type int in our pojo class.\n\nIn hibernate mapping file, add an element called version soon after id element\n" }, { "answer_id": 53422161, "author": "Ben", "author_id": 5425063, "author_profile": "https://Stackoverflow.com/users/5425063", "pm_score": 0, "selected": false, "text": "SELECT * FROM table WHERE (CHANGE_ID IN :ChangeId OR (EFFECTIVE_FROM <= :Now AND (EFFECTIVE_TO IS NULL OR EFFECTIVE_TO > :Now) AND ROOT_ID NOT IN (SELECT ROOT_ID FROM table WHERE CHANGE_ID IN :ChangeId)))\n SELECT * FROM table WHERE EFFECTIVE_FROM <= :Now AND (EFFECTIVE_TO IS NULL OR EFFECTIVE_TO > :Now)\n" } ]
2008/09/24
[ "https://Stackoverflow.com/questions/125877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13251/" ]