qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
249,775
<p>Say I have an input file, and a target directory. How do I determine if the input file is on the same hard-drive (or partition) as the target directory?</p> <p>What I want to do is the copy a file if it's on a different, but move it if it's the same. For example:</p> <pre><code>target_directory = "/Volumes/externalDrive/something/" input_foldername, input_filename = os.path.split(input_file) if same_partition(input_foldername, target_directory): copy(input_file, target_directory) else: move(input_file, target_directory) </code></pre>
[ { "answer_id": 249796, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 5, "selected": true, "text": "<p>In C, you would use <code>stat()</code> and compare the <code>st_dev</code> field. In python, <code>os.stat</code> should do the same.</p>\n\n<pre><code>import os\ndef same_partition(f1, f2):\n return os.stat(f1).st_dev == os.stat(f2).st_dev\n</code></pre>\n" }, { "answer_id": 250149, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 2, "selected": false, "text": "<p>Another way is the “better to ask forgiveness than permission” approach—just try to rename it, and if that fails, catch the appropriate <code>OSError</code> and try the copy approach. ie:</p>\n\n<pre><code>import errno\ntry:\n os.rename(source, dest):\nexcept IOError, ex:\n if ex.errno == errno.EXDEV:\n # perform the copy instead.\n</code></pre>\n\n<p>This has the advantage that it will also work on Windows, where st_dev is always 0 for all partitions.</p>\n\n<p>Note that if you actually want to copy and then delete the source file (ie. perform a move), rather than just copy, then shutil.move will already do what you want:</p>\n\n<pre>\nHelp on function move in module shutil:\n\nmove(src, dst)\n Recursively move a file or directory to another location.\n\n If the destination is on our current filesystem, then simply use\n rename. Otherwise, copy src to the dst and then remove src.\n</pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745/" ]
Say I have an input file, and a target directory. How do I determine if the input file is on the same hard-drive (or partition) as the target directory? What I want to do is the copy a file if it's on a different, but move it if it's the same. For example: ``` target_directory = "/Volumes/externalDrive/something/" input_foldername, input_filename = os.path.split(input_file) if same_partition(input_foldername, target_directory): copy(input_file, target_directory) else: move(input_file, target_directory) ```
In C, you would use `stat()` and compare the `st_dev` field. In python, `os.stat` should do the same. ``` import os def same_partition(f1, f2): return os.stat(f1).st_dev == os.stat(f2).st_dev ```
249,779
<p>I'm using a <code>BindingList&lt;T&gt;</code> in my Windows Forms that contains a list of "<code>IComparable&lt;Contact&gt;</code>" Contact-objects. Now I'd like the user to be able to sort by any column displayed in the grid.</p> <p>There is a way described on MSDN online which shows how to implement a custom collection based on <code>BindingList&lt;T&gt;</code> which allows sorting. But isn't there a Sort-event or something that could be caught in the DataGridView (or, even nicer, on the BindingSource) to sort the underlying collection using custom code?</p> <p>I don't really like the way described by MSDN. The other way I could easily apply a LINQ query to the collection.</p>
[ { "answer_id": 249816, "author": "Darren C", "author_id": 32339, "author_profile": "https://Stackoverflow.com/users/32339", "pm_score": 0, "selected": false, "text": "<p>Not for custom objects. In .Net 2.0, I had to roll my on sorting using BindingList. There may be something new in .Net 3.5 but I have not looked into that yet. Now that there is LINQ and the sorting options that come with if this now may be easier to implement.</p>\n" }, { "answer_id": 281324, "author": "Matthias Meid", "author_id": 17713, "author_profile": "https://Stackoverflow.com/users/17713", "pm_score": 5, "selected": false, "text": "<p>I googled and tried on my own some more time...</p>\n\n<p>There is no built-in way in .NET so far. You have to implement a custom class based on <code>BindingList&lt;T&gt;</code>. One way is described in <a href=\"http://msdn.microsoft.com/en-us/library/ms993236.aspx\" rel=\"noreferrer\">Custom Data Binding, Part 2 (MSDN)</a>. I finally produces a different implementation of the <code>ApplySortCore</code>-method to provide an implementation which is not project-dependent.</p>\n\n<pre><code>protected override void ApplySortCore(PropertyDescriptor property, ListSortDirection direction)\n{\n List&lt;T&gt; itemsList = (List&lt;T&gt;)this.Items;\n if(property.PropertyType.GetInterface(\"IComparable\") != null)\n {\n itemsList.Sort(new Comparison&lt;T&gt;(delegate(T x, T y)\n {\n // Compare x to y if x is not null. If x is, but y isn't, we compare y\n // to x and reverse the result. If both are null, they're equal.\n if(property.GetValue(x) != null)\n return ((IComparable)property.GetValue(x)).CompareTo(property.GetValue(y)) * (direction == ListSortDirection.Descending ? -1 : 1);\n else if(property.GetValue(y) != null)\n return ((IComparable)property.GetValue(y)).CompareTo(property.GetValue(x)) * (direction == ListSortDirection.Descending ? 1 : -1);\n else\n return 0;\n }));\n }\n\n isSorted = true;\n sortProperty = property;\n sortDirection = direction;\n}\n</code></pre>\n\n<p>Using this one, you can sort by any member that implements <code>IComparable</code>.</p>\n" }, { "answer_id": 1178144, "author": "Sorin Comanescu", "author_id": 117290, "author_profile": "https://Stackoverflow.com/users/117290", "pm_score": 6, "selected": true, "text": "<p>I higly appreciate <a href=\"https://stackoverflow.com/a/281324/3834\">Matthias' solution</a> for its simplicity and beauty.</p>\n\n<p>However, while this gives excellent results for low data volumes, when working with large data volumes the performance is not so good, due to reflection.</p>\n\n<p>I ran a test with a collection of simple data objects, counting 100000 elements. Sorting by an integer type property took around 1 min. The implementation I'm going to further detail changed this to ~200ms.</p>\n\n<p>The basic idea is to benefit strongly typed comparison, while keeping the ApplySortCore method generic. The following replaces the generic comparison delegate with a call to a specific comparer, implemented in a derived class:</p>\n\n<p>New in SortableBindingList&lt;T&gt;:</p>\n\n<pre><code>protected abstract Comparison&lt;T&gt; GetComparer(PropertyDescriptor prop);\n</code></pre>\n\n<p>ApplySortCore changes to:</p>\n\n<pre><code>protected override void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction)\n{\n List&lt;T&gt; itemsList = (List&lt;T&gt;)this.Items;\n if (prop.PropertyType.GetInterface(\"IComparable\") != null)\n {\n Comparison&lt;T&gt; comparer = GetComparer(prop);\n itemsList.Sort(comparer);\n if (direction == ListSortDirection.Descending)\n {\n itemsList.Reverse();\n }\n }\n\n isSortedValue = true;\n sortPropertyValue = prop;\n sortDirectionValue = direction;\n}\n</code></pre>\n\n<p>Now, in the derived class one have to implement comparers for each sortable property:</p>\n\n<pre><code>class MyBindingList:SortableBindingList&lt;DataObject&gt;\n{\n protected override Comparison&lt;DataObject&gt; GetComparer(PropertyDescriptor prop)\n {\n Comparison&lt;DataObject&gt; comparer;\n switch (prop.Name)\n {\n case \"MyIntProperty\":\n comparer = new Comparison&lt;DataObject&gt;(delegate(DataObject x, DataObject y)\n {\n if (x != null)\n if (y != null)\n return (x.MyIntProperty.CompareTo(y.MyIntProperty));\n else\n return 1;\n else if (y != null)\n return -1;\n else\n return 0;\n });\n break;\n\n // Implement comparers for other sortable properties here.\n }\n return comparer;\n }\n }\n}\n</code></pre>\n\n<p>This variant requires a little bit more code but, if performance is an issue, I think it worths the effort.</p>\n" }, { "answer_id": 3687781, "author": "Dan Koster", "author_id": 444685, "author_profile": "https://Stackoverflow.com/users/444685", "pm_score": 2, "selected": false, "text": "<p>Here is an alternative that is very clean and works just fine in my case. I already had specific comparison functions set up for use with List.Sort(Comparison) so I just adapted this from parts of the other StackOverflow examples.</p>\n\n<pre><code>class SortableBindingList&lt;T&gt; : BindingList&lt;T&gt;\n{\n public SortableBindingList(IList&lt;T&gt; list) : base(list) { }\n\n public void Sort() { sort(null, null); }\n public void Sort(IComparer&lt;T&gt; p_Comparer) { sort(p_Comparer, null); }\n public void Sort(Comparison&lt;T&gt; p_Comparison) { sort(null, p_Comparison); }\n\n private void sort(IComparer&lt;T&gt; p_Comparer, Comparison&lt;T&gt; p_Comparison)\n {\n if(typeof(T).GetInterface(typeof(IComparable).Name) != null)\n {\n bool originalValue = this.RaiseListChangedEvents;\n this.RaiseListChangedEvents = false;\n try\n {\n List&lt;T&gt; items = (List&lt;T&gt;)this.Items;\n if(p_Comparison != null) items.Sort(p_Comparison);\n else items.Sort(p_Comparer);\n }\n finally\n {\n this.RaiseListChangedEvents = originalValue;\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 20406268, "author": "Scott Chamberlain", "author_id": 80274, "author_profile": "https://Stackoverflow.com/users/80274", "pm_score": 2, "selected": false, "text": "<p>Here is a new implmentation using a few new tricks.</p>\n\n<p>The underlying type of the <code>IList&lt;T&gt;</code> must implement <code>void Sort(Comparison&lt;T&gt;)</code> or you must pass in a delegate to call the sort function for you. (<code>IList&lt;T&gt;</code> does not have a <code>void Sort(Comparison&lt;T&gt;)</code> function) </p>\n\n<p>During the static constructor the class will go through the type <code>T</code> finding all public instanced properties that implements <code>ICompareable</code> or <code>ICompareable&lt;T&gt;</code> and caches the delegates it creates for later use. This is done in a static constructor because we only need to do it once per type of <code>T</code> and <code>Dictionary&lt;TKey,TValue&gt;</code> is thread safe on reads.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Linq;\nusing System.Linq.Expressions;\nusing System.Reflection;\n\nnamespace ExampleCode\n{\n public class SortableBindingList&lt;T&gt; : BindingList&lt;T&gt;\n {\n private static readonly Dictionary&lt;string, Comparison&lt;T&gt;&gt; PropertyLookup;\n private readonly Action&lt;IList&lt;T&gt;, Comparison&lt;T&gt;&gt; _sortDelegate;\n\n private bool _isSorted;\n private ListSortDirection _sortDirection;\n private PropertyDescriptor _sortProperty;\n\n //A Dictionary&lt;TKey, TValue&gt; is thread safe on reads so we only need to make the dictionary once per type.\n static SortableBindingList()\n {\n PropertyLookup = new Dictionary&lt;string, Comparison&lt;T&gt;&gt;();\n foreach (PropertyInfo property in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance))\n {\n Type propertyType = property.PropertyType;\n bool usingNonGenericInterface = false;\n\n //First check to see if it implments the generic interface.\n Type compareableInterface = propertyType.GetInterfaces()\n .FirstOrDefault(a =&gt; a.Name == \"IComparable`1\" &amp;&amp;\n a.GenericTypeArguments[0] == propertyType);\n\n //If we did not find a generic interface then use the non-generic interface.\n if (compareableInterface == null)\n {\n compareableInterface = propertyType.GetInterface(\"IComparable\");\n usingNonGenericInterface = true;\n }\n\n if (compareableInterface != null)\n {\n ParameterExpression x = Expression.Parameter(typeof(T), \"x\");\n ParameterExpression y = Expression.Parameter(typeof(T), \"y\");\n\n MemberExpression xProp = Expression.Property(x, property.Name);\n Expression yProp = Expression.Property(y, property.Name);\n\n MethodInfo compareToMethodInfo = compareableInterface.GetMethod(\"CompareTo\");\n\n //If we are not using the generic version of the interface we need to \n // cast to object or we will fail when using structs.\n if (usingNonGenericInterface)\n {\n yProp = Expression.TypeAs(yProp, typeof(object));\n }\n\n MethodCallExpression call = Expression.Call(xProp, compareToMethodInfo, yProp);\n\n Expression&lt;Comparison&lt;T&gt;&gt; lambada = Expression.Lambda&lt;Comparison&lt;T&gt;&gt;(call, x, y);\n PropertyLookup.Add(property.Name, lambada.Compile());\n }\n }\n }\n\n public SortableBindingList() : base(new List&lt;T&gt;())\n {\n _sortDelegate = (list, comparison) =&gt; ((List&lt;T&gt;)list).Sort(comparison);\n }\n\n public SortableBindingList(IList&lt;T&gt; list) : base(list)\n {\n MethodInfo sortMethod = list.GetType().GetMethod(\"Sort\", new[] {typeof(Comparison&lt;T&gt;)});\n if (sortMethod == null || sortMethod.ReturnType != typeof(void))\n {\n throw new ArgumentException(\n \"The passed in IList&lt;T&gt; must support a \\\"void Sort(Comparision&lt;T&gt;)\\\" call or you must provide one using the other constructor.\",\n \"list\");\n }\n\n _sortDelegate = CreateSortDelegate(list, sortMethod);\n }\n\n public SortableBindingList(IList&lt;T&gt; list, Action&lt;IList&lt;T&gt;, Comparison&lt;T&gt;&gt; sortDelegate)\n : base(list)\n {\n _sortDelegate = sortDelegate;\n }\n\n protected override bool IsSortedCore\n {\n get { return _isSorted; }\n }\n\n protected override ListSortDirection SortDirectionCore\n {\n get { return _sortDirection; }\n }\n\n protected override PropertyDescriptor SortPropertyCore\n {\n get { return _sortProperty; }\n }\n\n protected override bool SupportsSortingCore\n {\n get { return true; }\n }\n\n private static Action&lt;IList&lt;T&gt;, Comparison&lt;T&gt;&gt; CreateSortDelegate(IList&lt;T&gt; list, MethodInfo sortMethod)\n {\n ParameterExpression sourceList = Expression.Parameter(typeof(IList&lt;T&gt;));\n ParameterExpression comparer = Expression.Parameter(typeof(Comparison&lt;T&gt;));\n UnaryExpression castList = Expression.TypeAs(sourceList, list.GetType());\n MethodCallExpression call = Expression.Call(castList, sortMethod, comparer);\n Expression&lt;Action&lt;IList&lt;T&gt;, Comparison&lt;T&gt;&gt;&gt; lambada =\n Expression.Lambda&lt;Action&lt;IList&lt;T&gt;, Comparison&lt;T&gt;&gt;&gt;(call,\n sourceList, comparer);\n Action&lt;IList&lt;T&gt;, Comparison&lt;T&gt;&gt; sortDelegate = lambada.Compile();\n return sortDelegate;\n }\n\n protected override void ApplySortCore(PropertyDescriptor property, ListSortDirection direction)\n {\n Comparison&lt;T&gt; comparison;\n\n if (PropertyLookup.TryGetValue(property.Name, out comparison))\n {\n if (direction == ListSortDirection.Descending)\n {\n _sortDelegate(Items, (x, y) =&gt; comparison(y, x));\n }\n else\n {\n _sortDelegate(Items, comparison);\n }\n\n _isSorted = true;\n _sortProperty = property;\n _sortDirection = direction;\n\n OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, property));\n }\n }\n\n protected override void RemoveSortCore()\n {\n _isSorted = false;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 28520948, "author": "Ravi M Patel", "author_id": 3317709, "author_profile": "https://Stackoverflow.com/users/3317709", "pm_score": 3, "selected": false, "text": "<p>I understand all these answers were good at the time they were written. Probably they still are. I was looking for something similar and found an alternative solution to convert <strong>any</strong> list or collection to sortable <code>BindingList&lt;T&gt;</code>.</p>\n\n<p>Here is the important snippet (link to the full sample is shared below):</p>\n\n<pre><code>void Main()\n{\n DataGridView dgv = new DataGridView();\n dgv.DataSource = new ObservableCollection&lt;Person&gt;(Person.GetAll()).ToBindingList();\n} \n</code></pre>\n\n<p>This solution uses an extension method available in <a href=\"https://entityframework.codeplex.com/SourceControl/latest#src/EntityFramework/ObservableCollectionExtensions.cs\" rel=\"noreferrer\">Entity Framework</a> library. So please consider the following before you proceed further:</p>\n\n<ol>\n<li>If you don't want to use Entity Framework, its fine, this solution is not using it either. We are just using an extension method they have developed. The size of the EntityFramework.dll is 5 MB. If it's too big for you in the era of Petabytes, feel free to extract the method and its dependencies from the above link.</li>\n<li>If you are using (or would like to use) Entity Framework (>=v6.0), you've nothing to worry about. Just install the <strong>Entity Framework</strong> Nuget package and get going.</li>\n</ol>\n\n<p>I have uploaded the <a href=\"http://www.linqpad.net/\" rel=\"noreferrer\">LINQPad</a> code sample <a href=\"http://share.linqpad.net/5qsxxa.linq\" rel=\"noreferrer\">here</a>.</p>\n\n<ol>\n<li>Download the sample, open it using LINQPad and hit F4.</li>\n<li>You should see EntityFramework.dll in red. Download the dll from this <a href=\"https://entityframework.codeplex.com/\" rel=\"noreferrer\">location</a>. Browse and add the reference.</li>\n<li>Click OK. Hit F5.</li>\n</ol>\n\n<p>As you can see, you can sort on all four columns of different data types by clicking their column headers on the DataGridView control.</p>\n\n<p>Those who don't have LINQPad, can still download the query and open it with notepad, to see the full sample.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17713/" ]
I'm using a `BindingList<T>` in my Windows Forms that contains a list of "`IComparable<Contact>`" Contact-objects. Now I'd like the user to be able to sort by any column displayed in the grid. There is a way described on MSDN online which shows how to implement a custom collection based on `BindingList<T>` which allows sorting. But isn't there a Sort-event or something that could be caught in the DataGridView (or, even nicer, on the BindingSource) to sort the underlying collection using custom code? I don't really like the way described by MSDN. The other way I could easily apply a LINQ query to the collection.
I higly appreciate [Matthias' solution](https://stackoverflow.com/a/281324/3834) for its simplicity and beauty. However, while this gives excellent results for low data volumes, when working with large data volumes the performance is not so good, due to reflection. I ran a test with a collection of simple data objects, counting 100000 elements. Sorting by an integer type property took around 1 min. The implementation I'm going to further detail changed this to ~200ms. The basic idea is to benefit strongly typed comparison, while keeping the ApplySortCore method generic. The following replaces the generic comparison delegate with a call to a specific comparer, implemented in a derived class: New in SortableBindingList<T>: ``` protected abstract Comparison<T> GetComparer(PropertyDescriptor prop); ``` ApplySortCore changes to: ``` protected override void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction) { List<T> itemsList = (List<T>)this.Items; if (prop.PropertyType.GetInterface("IComparable") != null) { Comparison<T> comparer = GetComparer(prop); itemsList.Sort(comparer); if (direction == ListSortDirection.Descending) { itemsList.Reverse(); } } isSortedValue = true; sortPropertyValue = prop; sortDirectionValue = direction; } ``` Now, in the derived class one have to implement comparers for each sortable property: ``` class MyBindingList:SortableBindingList<DataObject> { protected override Comparison<DataObject> GetComparer(PropertyDescriptor prop) { Comparison<DataObject> comparer; switch (prop.Name) { case "MyIntProperty": comparer = new Comparison<DataObject>(delegate(DataObject x, DataObject y) { if (x != null) if (y != null) return (x.MyIntProperty.CompareTo(y.MyIntProperty)); else return 1; else if (y != null) return -1; else return 0; }); break; // Implement comparers for other sortable properties here. } return comparer; } } } ``` This variant requires a little bit more code but, if performance is an issue, I think it worths the effort.
249,780
<p>I have a really simple search form with the following</p> <ul> <li>Label ("Search")</li> <li>Textbox (fixed width)</li> <li>Submit button</li> <li>"Advanced" link</li> </ul> <p>Label, textbox and submit are all on one horizontal line and centered. Now I would like my advanced link to be under the submit button.</p> <p>Any ideas?</p>
[ { "answer_id": 249790, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 3, "selected": true, "text": "<p>If I understand the question you want:</p>\n\n<pre><code> Search [xxxxxxxxxxxxxxxx] [Submit]\n Advanced\n</code></pre>\n\n<p>You'll have to add some more elements in to do that:</p>\n\n<pre><code>&lt;div style=\"width: 300px; margin: auto; text-align: center;\"&gt;\n Search [xxxxxxxxxxxxxxx] [Submit]\n &lt;div style=\"text-align: right\"&gt;Advanced&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 249812, "author": "Norbert B.", "author_id": 2605840, "author_profile": "https://Stackoverflow.com/users/2605840", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;style type=\"text/css\"&gt;\n #searchpanel\n {\n width: &lt;displaywidth of controls&gt;px;\n text-align: center;\n }\n\n #button\n {\n text-align: right;\n }\n&lt;/style&gt;\n&lt;div =\"searchpanel\"&gt;\n &lt;label for=\"textbox\"&gt;Search&lt;/label&gt;&lt;input type=\"text\" id=\"textbox\" /&gt;\n &lt;input type=\"submit\" value=\"Search\" /&gt;\n&lt;/div&gt;\n&lt;div id=\"button\"&gt;\n &lt;a href=\"#\"&gt;Advanced&lt;/a&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Hope this helps.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]
I have a really simple search form with the following * Label ("Search") * Textbox (fixed width) * Submit button * "Advanced" link Label, textbox and submit are all on one horizontal line and centered. Now I would like my advanced link to be under the submit button. Any ideas?
If I understand the question you want: ``` Search [xxxxxxxxxxxxxxxx] [Submit] Advanced ``` You'll have to add some more elements in to do that: ``` <div style="width: 300px; margin: auto; text-align: center;"> Search [xxxxxxxxxxxxxxx] [Submit] <div style="text-align: right">Advanced</div> </div> ```
249,785
<p>Simply moving the file to <code>~/.Trash/</code> will not work, as if the file os on an external drive, it will move the file to the main system drive..</p> <p>Also, there are other conditions, like files on external drives get moved to <code>/Volumes/.Trash/501/</code> (or whatever the current user's ID is)</p> <p>Given a file or folder path, what is the correct way to determine the trash folder? I imagine the language is pretty irrelevant, but I intend to use Python</p>
[ { "answer_id": 249800, "author": "Matthew Schinckel", "author_id": 188, "author_profile": "https://Stackoverflow.com/users/188", "pm_score": 2, "selected": false, "text": "<p>The File Manager API has a pair of functions called FSMoveObjectToTrashAsync and FSPathMoveObjectToTrashSync.</p>\n\n<p>Not sure if that is exposed to Python or not.</p>\n" }, { "answer_id": 251566, "author": "Dave Dribin", "author_id": 26825, "author_profile": "https://Stackoverflow.com/users/26825", "pm_score": 4, "selected": true, "text": "<p>Alternatively, if you're on OS X 10.5, you could use Scripting Bridge to delete files via the Finder. I've done this in Ruby code <a href=\"http://osx-trash.rubyforge.org/git?p=osx-trash.git;a=blob;f=bin/trash;h=26911131eacafd659b4d760bda1bd4c99dc2f918;hb=HEAD\" rel=\"noreferrer\">here</a> via RubyCocoa. The the gist of it is:</p>\n\n<pre><code>url = NSURL.fileURLWithPath(path)\nfinder = SBApplication.applicationWithBundleIdentifier(\"com.apple.Finder\")\nitem = finder.items.objectAtLocation(url)\nitem.delete\n</code></pre>\n\n<p>You could easily do something similar with PyObjC.</p>\n" }, { "answer_id": 252920, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 3, "selected": false, "text": "<p>Based upon code from <a href=\"http://www.cocoadev.com/index.pl?MoveToTrash\" rel=\"noreferrer\">http://www.cocoadev.com/index.pl?MoveToTrash</a> I have came up with the following:</p>\n\n<pre><code>def get_trash_path(input_file):\n path, file = os.path.split(input_file)\n if path.startswith(\"/Volumes/\"):\n # /Volumes/driveName/.Trashes/&lt;uid&gt;\n s = path.split(os.path.sep)\n # s[2] is drive name ([0] is empty, [1] is Volumes)\n trash_path = os.path.join(\"/Volumes\", s[2], \".Trashes\", str(os.getuid()))\n if not os.path.isdir(trash_path):\n raise IOError(\"Volume appears to be a network drive (%s could not be found)\" % (trash_path))\n else:\n trash_path = os.path.join(os.getenv(\"HOME\"), \".Trash\")\n return trash_path\n</code></pre>\n\n<p>Fairly basic, and there's a few things that have to be done seperatly, particularly checking if the filename already exist in trash (to avoid overwriting) and the actual moving to trash, but it seems to cover most things (internal, external and network drives)</p>\n\n<p><strong>Update:</strong> I wanted to trash a file in a Python script, so I re-implemented Dave Dribin's solution in Python:</p>\n\n<pre><code>from AppKit import NSURL\nfrom ScriptingBridge import SBApplication\n\ndef trashPath(path):\n \"\"\"Trashes a path using the Finder, via OS X's Scripting Bridge.\n \"\"\"\n targetfile = NSURL.fileURLWithPath_(path)\n finder = SBApplication.applicationWithBundleIdentifier_(\"com.apple.Finder\")\n items = finder.items().objectAtLocation_(targetfile)\n items.delete()\n</code></pre>\n\n<p>Usage is simple:</p>\n\n<pre><code>trashPath(\"/tmp/examplefile\")\n</code></pre>\n" }, { "answer_id": 621219, "author": "Peter Hosey", "author_id": 30461, "author_profile": "https://Stackoverflow.com/users/30461", "pm_score": 2, "selected": false, "text": "<p>A better way is <a href=\"http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSWorkspace_Class/Reference/Reference.html#//apple_ref/doc/c_ref/NSWorkspaceRecycleOperation\" rel=\"nofollow noreferrer\">NSWorkspaceRecycleOperation</a>, which is one of the operations you can use with <a href=\"http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSWorkspace_Class/Reference/Reference.html#//apple_ref/occ/instm/NSWorkspace/performFileOperation:source:destination:files:tag:\" rel=\"nofollow noreferrer\">-[NSWorkspace performFileOperation:source:destination:files:tag:]</a>. The constant's name is another artifact of Cocoa's NeXT heritage; its function is to move the item to the Trash.</p>\n\n<p>Since it's part of Cocoa, it should be available to both Python and Ruby.</p>\n" }, { "answer_id": 3654566, "author": "tig", "author_id": 96823, "author_profile": "https://Stackoverflow.com/users/96823", "pm_score": 1, "selected": false, "text": "<p>Another one in ruby:</p>\n\n<pre><code>Appscript.app('Finder').items[MacTypes::Alias.path(path)].delete\n</code></pre>\n\n<p>You will need <a href=\"http://rubygems.org/gems/rb-appscript\" rel=\"nofollow noreferrer\">rb-appscript</a> gem, you can read about it <a href=\"http://appscript.sourceforge.net/rb-appscript/index.html\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 5012645, "author": "Ashley Clark", "author_id": 4556, "author_profile": "https://Stackoverflow.com/users/4556", "pm_score": 2, "selected": false, "text": "<p>In Python, without using the scripting bridge, you can do this:</p>\n\n<pre><code>from AppKit import NSWorkspace, NSWorkspaceRecycleOperation\n\nsource = \"path holding files\"\nfiles = [\"file1\", \"file2\"]\n\nws = NSWorkspace.sharedWorkspace()\nws.performFileOperation_source_destination_files_tag_(NSWorkspaceRecycleOperation, source, \"\", files, None)\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745/" ]
Simply moving the file to `~/.Trash/` will not work, as if the file os on an external drive, it will move the file to the main system drive.. Also, there are other conditions, like files on external drives get moved to `/Volumes/.Trash/501/` (or whatever the current user's ID is) Given a file or folder path, what is the correct way to determine the trash folder? I imagine the language is pretty irrelevant, but I intend to use Python
Alternatively, if you're on OS X 10.5, you could use Scripting Bridge to delete files via the Finder. I've done this in Ruby code [here](http://osx-trash.rubyforge.org/git?p=osx-trash.git;a=blob;f=bin/trash;h=26911131eacafd659b4d760bda1bd4c99dc2f918;hb=HEAD) via RubyCocoa. The the gist of it is: ``` url = NSURL.fileURLWithPath(path) finder = SBApplication.applicationWithBundleIdentifier("com.apple.Finder") item = finder.items.objectAtLocation(url) item.delete ``` You could easily do something similar with PyObjC.
249,787
<p>I am in the process of moving from VSS to SVN and I'm not sure how to share files in SVN.</p> <p>Basically we have the following structure in VSS</p> <pre><code>$MOSS - Components - ComponentA - bin - ComponentB - bin - GAC Mirror </code></pre> <p>GAC Mirror holds a shared copy of all the Dlls from the bin folders of the components to allow for easy copying to the GAC.</p> <p>In VSS all you do is drag the Dll from the bin folder to the GAC Mirror folder and it works it's life out.</p> <p>How would I do this in SVN?</p> <p>Thanks in advance.</p>
[ { "answer_id": 249808, "author": "RickL", "author_id": 7261, "author_profile": "https://Stackoverflow.com/users/7261", "pm_score": 1, "selected": false, "text": "<p>We had the same problem. The simple answer is that you can't share files in SVN - in the end we had to restructure our directories and use batch files.</p>\n\n<p>e.g. for source code files that were shared, we moved them to an Include folder, and have all the projects reference that folder.</p>\n\n<p>For binary files that need to be copied to more than one location we store them just once in SVN, and then use batch files to copy them across to the target locations on each developers machine (or also on the build machine).</p>\n" }, { "answer_id": 249826, "author": "tunaranch", "author_id": 27708, "author_profile": "https://Stackoverflow.com/users/27708", "pm_score": 4, "selected": true, "text": "<p>Is svn:externals what you're after? <a href=\"http://svnbook.red-bean.com/en/1.0/ch07s03.html\" rel=\"nofollow noreferrer\">http://svnbook.red-bean.com/en/1.0/ch07s03.html</a></p>\n" }, { "answer_id": 249857, "author": "akauppi", "author_id": 14455, "author_profile": "https://Stackoverflow.com/users/14455", "pm_score": 2, "selected": false, "text": "<p>I second Rick on this. To me, the whole concept of \"sharing\" (= having the same file occur in two places at checkouts) is weird.</p>\n\n<p>I guess each versioning system has its own mindset implicitly attached to it. I've tried Perforce and I've stayed with Subversion. Bringing your projects to it without changing the mindset and maybe workflow may be flawed, though.</p>\n\n<p>The <a href=\"http://svnbook.red-bean.com/\" rel=\"nofollow noreferrer\">Book</a> on svn is a worthy read, to get some of the mindset submerged before doing the plunge. You can select some sections only, you don't have to read all at once.</p>\n" }, { "answer_id": 4733535, "author": "Eric Liu", "author_id": 127526, "author_profile": "https://Stackoverflow.com/users/127526", "pm_score": 0, "selected": false, "text": "<p>Use SVN 1.6+, it supports files also, see:\n<a href=\"http://svnbook.red-bean.com/nightly/en/svn-book.html#svn.advanced.externals\" rel=\"nofollow\">http://svnbook.red-bean.com/nightly/en/svn-book.html#svn.advanced.externals</a></p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26792/" ]
I am in the process of moving from VSS to SVN and I'm not sure how to share files in SVN. Basically we have the following structure in VSS ``` $MOSS - Components - ComponentA - bin - ComponentB - bin - GAC Mirror ``` GAC Mirror holds a shared copy of all the Dlls from the bin folders of the components to allow for easy copying to the GAC. In VSS all you do is drag the Dll from the bin folder to the GAC Mirror folder and it works it's life out. How would I do this in SVN? Thanks in advance.
Is svn:externals what you're after? <http://svnbook.red-bean.com/en/1.0/ch07s03.html>
249,791
<p>How do I get the substring <code>" It's big \"problem "</code> using a regular expression?</p> <pre><code>s = ' function(){ return " It\'s big \"problem "; }'; </code></pre>
[ { "answer_id": 249804, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code>/([\"\\']).*?(?&lt;!\\\\)(\\\\\\\\)*\\1/is\n</code></pre>\n\n<p>should work with any quoted string</p>\n" }, { "answer_id": 249844, "author": "Henrik Paul", "author_id": 2238, "author_profile": "https://Stackoverflow.com/users/2238", "pm_score": 0, "selected": false, "text": "<p>One has to remember that regexps aren't a silver bullet for everything string-y. Some stuff are simpler to do with a cursor and linear, manual, seeking. A <a href=\"http://en.wikipedia.org/wiki/Context-free_language\" rel=\"nofollow noreferrer\">CFL</a> would do the trick pretty trivially, but there aren't many CFL implementations (afaik).</p>\n" }, { "answer_id": 249937, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 8, "selected": false, "text": "<pre><code>/\"(?:[^\"\\\\]|\\\\.)*\"/\n</code></pre>\n\n<p>Works in The Regex Coach and PCRE Workbench.</p>\n\n<p>Example of test in JavaScript:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> var s = ' function(){ return \" Is big \\\\\"problem\\\\\", \\\\no? \"; }';\r\n var m = s.match(/\"(?:[^\"\\\\]|\\\\.)*\"/);\r\n if (m != null)\r\n alert(m);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 1016356, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>This one comes from nanorc.sample available in many linux distros. It is used for syntax highlighting of C style strings</p>\n\n<pre><code>\\\"(\\\\.|[^\\\"])*\\\"\n</code></pre>\n" }, { "answer_id": 4448207, "author": "Tosh Afanasiev", "author_id": 543106, "author_profile": "https://Stackoverflow.com/users/543106", "pm_score": 3, "selected": false, "text": "<pre><code>\"(?:\\\\\"|.)*?\"\n</code></pre>\n\n<p>Alternating the <code>\\\"</code> and the <code>.</code> passes over escaped quotes while the lazy quantifier <code>*?</code> ensures that you don't go past the end of the quoted string. Works with .NET Framework RE classes</p>\n" }, { "answer_id": 10786066, "author": "Guy Bedford", "author_id": 1292590, "author_profile": "https://Stackoverflow.com/users/1292590", "pm_score": 5, "selected": false, "text": "<p>As provided by ePharaoh, the answer is</p>\n\n<pre><code>/\"([^\"\\\\]*(\\\\.[^\"\\\\]*)*)\"/\n</code></pre>\n\n<p>To have the above apply to either single quoted or double quoted strings, use</p>\n\n<pre><code>/\"([^\"\\\\]*(\\\\.[^\"\\\\]*)*)\"|\\'([^\\'\\\\]*(\\\\.[^\\'\\\\]*)*)\\'/\n</code></pre>\n" }, { "answer_id": 15936558, "author": "user2267983", "author_id": 2267983, "author_profile": "https://Stackoverflow.com/users/2267983", "pm_score": 0, "selected": false, "text": "<p>If it is searched from the beginning, maybe this can work?</p>\n\n<pre><code>\\\"((\\\\\\\")|[^\\\\])*\\\"\n</code></pre>\n" }, { "answer_id": 20352652, "author": "Rvanlaak", "author_id": 1794894, "author_profile": "https://Stackoverflow.com/users/1794894", "pm_score": 0, "selected": false, "text": "<p>A more extensive version of <a href=\"https://stackoverflow.com/a/10786066/1794894\">https://stackoverflow.com/a/10786066/1794894</a></p>\n\n<pre><code>/\"([^\"\\\\]{50,}(\\\\.[^\"\\\\]*)*)\"|\\'[^\\'\\\\]{50,}(\\\\.[^\\'\\\\]*)*\\'|“[^”\\\\]{50,}(\\\\.[^“\\\\]*)*”/ \n</code></pre>\n\n<p>This version also contains</p>\n\n<ol>\n<li>Minimum quote length of 50</li>\n<li>Extra type of quotes (open <code>“</code> and close <code>”</code>)</li>\n</ol>\n" }, { "answer_id": 25954054, "author": "Petter Thowsen", "author_id": 1303805, "author_profile": "https://Stackoverflow.com/users/1303805", "pm_score": -1, "selected": false, "text": "<p>Messed around at <a href=\"http://regexpal.com\" rel=\"nofollow\">regexpal</a> and ended up with this regex: (Don't ask me how it works, I barely understand even tho I wrote it lol)</p>\n\n<pre><code>\"(([^\"\\\\]?(\\\\\\\\)?)|(\\\\\")+)+\"\n</code></pre>\n" }, { "answer_id": 30737232, "author": "Marc-André Poulin", "author_id": 3208143, "author_profile": "https://Stackoverflow.com/users/3208143", "pm_score": 4, "selected": false, "text": "<p>Most of the solutions provided here use alternative repetition paths i.e. (A|B)*.</p>\n\n<p>You may encounter stack overflows on large inputs since some pattern compiler implements this using recursion.</p>\n\n<p>Java for instance: <a href=\"http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6337993\" rel=\"noreferrer\">http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6337993</a></p>\n\n<p>Something like this:\n<code>\"(?:[^\"\\\\]*(?:\\\\.)?)*\"</code>, or the one provided by Guy Bedford will reduce the amount of parsing steps avoiding most stack overflows.</p>\n" }, { "answer_id": 33617839, "author": "ack", "author_id": 588561, "author_profile": "https://Stackoverflow.com/users/588561", "pm_score": 3, "selected": false, "text": "<pre><code>/\"(?:[^\"\\\\]++|\\\\.)*+\"/\n</code></pre>\n\n<p>Taken straight from <code>man perlre</code> on a Linux system with Perl 5.22.0 installed.\nAs an optimization, this regex uses the 'posessive' form of both <code>+</code> and <code>*</code> to prevent backtracking, for it is known beforehand that a string without a closing quote wouldn't match in any case.</p>\n" }, { "answer_id": 43597014, "author": "Vadim Sayfi", "author_id": 7915886, "author_profile": "https://Stackoverflow.com/users/7915886", "pm_score": 3, "selected": false, "text": "<p>This one works perfect on PCRE and does not fall with StackOverflow.</p>\n\n<pre><code>\"(.*?[^\\\\])??((\\\\\\\\)+)?+\"\n</code></pre>\n\n<p>Explanation:</p>\n\n<ol>\n<li>Every quoted string starts with Char: <code>\"</code> ;</li>\n<li>It may contain any number of any characters: <code>.*?</code> {Lazy match}; ending with non escape character <code>[^\\\\]</code>;</li>\n<li>Statement (2) is Lazy(!) optional because string can be empty(\"\"). So: <code>(.*?[^\\\\])??</code></li>\n<li>Finally, every quoted string ends with Char(<code>\"</code>), but it can be preceded with even number of escape sign pairs <code>(\\\\\\\\)+</code>; and it is Greedy(!) optional: <code>((\\\\\\\\)+)?+</code> {Greedy matching}, bacause string can be empty or without ending pairs!</li>\n</ol>\n" }, { "answer_id": 45526948, "author": "mathias hansen", "author_id": 8010265, "author_profile": "https://Stackoverflow.com/users/8010265", "pm_score": 2, "selected": false, "text": "<p>here is one that work with both \" and ' and you easily add others at the start.</p>\n\n<pre>(\"|')(?:\\\\\\1|[^\\1])*?\\1</pre>\n\n<p>it uses the backreference (\\1) match exactley what is in the first group (\" or '). </p>\n\n<p><a href=\"http://www.regular-expressions.info/backref.html\" rel=\"nofollow noreferrer\">http://www.regular-expressions.info/backref.html</a></p>\n" }, { "answer_id": 48165319, "author": "scagood", "author_id": 3533202, "author_profile": "https://Stackoverflow.com/users/3533202", "pm_score": 2, "selected": false, "text": "<p>An option that has not been touched on before is:</p>\n\n<ol>\n<li>Reverse the string.</li>\n<li>Perform the matching on the reversed string.</li>\n<li>Re-reverse the matched strings.</li>\n</ol>\n\n<p>This has the added bonus of being able to correctly match escaped open tags.</p>\n\n<p>Lets say you had the following string; <code>String \\\"this \"should\" NOT match\\\" and \"this \\\"should\\\" match\"</code>\nHere, <code>\\\"this \"should\" NOT match\\\"</code> should not be matched and <code>\"should\"</code> should be.\nOn top of that <code>this \\\"should\\\" match</code> should be matched and <code>\\\"should\\\"</code> should not.</p>\n\n<p>First an example.\n</p>\n\n<pre><code>// The input string.\nconst myString = 'String \\\\\"this \"should\" NOT match\\\\\" and \"this \\\\\"should\\\\\" match\"';\n\n// The RegExp.\nconst regExp = new RegExp(\n // Match close\n '([\\'\"])(?!(?:[\\\\\\\\]{2})*[\\\\\\\\](?![\\\\\\\\]))' +\n '((?:' +\n // Match escaped close quote\n '(?:\\\\1(?=(?:[\\\\\\\\]{2})*[\\\\\\\\](?![\\\\\\\\])))|' +\n // Match everything thats not the close quote\n '(?:(?!\\\\1).)' +\n '){0,})' +\n // Match open\n '(\\\\1)(?!(?:[\\\\\\\\]{2})*[\\\\\\\\](?![\\\\\\\\]))',\n 'g'\n);\n\n// Reverse the matched strings.\nmatches = myString\n // Reverse the string.\n .split('').reverse().join('')\n // '\"hctam \"\\dluohs\"\\ siht\" dna \"\\hctam TON \"dluohs\" siht\"\\ gnirtS'\n\n // Match the quoted\n .match(regExp)\n // ['\"hctam \"\\dluohs\"\\ siht\"', '\"dluohs\"']\n\n // Reverse the matches\n .map(x =&gt; x.split('').reverse().join(''))\n // ['\"this \\\"should\\\" match\"', '\"should\"']\n\n // Re order the matches\n .reverse();\n // ['\"should\"', '\"this \\\"should\\\" match\"']\n</code></pre>\n\n<p>Okay, now to explain the RegExp.\nThis is the regexp can be easily broken into three pieces. As follows:\n</p>\n\n<pre><code># Part 1\n(['\"]) # Match a closing quotation mark \" or '\n(?! # As long as it's not followed by\n (?:[\\\\]{2})* # A pair of escape characters\n [\\\\] # and a single escape\n (?![\\\\]) # As long as that's not followed by an escape\n)\n# Part 2\n((?: # Match inside the quotes\n(?: # Match option 1:\n \\1 # Match the closing quote\n (?= # As long as it's followed by\n (?:\\\\\\\\)* # A pair of escape characters\n \\\\ # \n (?![\\\\]) # As long as that's not followed by an escape\n ) # and a single escape\n)| # OR\n(?: # Match option 2:\n (?!\\1). # Any character that isn't the closing quote\n)\n)*) # Match the group 0 or more times\n# Part 3\n(\\1) # Match an open quotation mark that is the same as the closing one\n(?! # As long as it's not followed by\n (?:[\\\\]{2})* # A pair of escape characters\n [\\\\] # and a single escape\n (?![\\\\]) # As long as that's not followed by an escape\n)\n</code></pre>\n\n<p>This is probably a lot clearer in image form: generated using <a href=\"https://jex.im/regulex/\" rel=\"nofollow noreferrer\">Jex's Regulex</a></p>\n\n<p><a href=\"https://user-images.githubusercontent.com/2230835/34616812-3cc9c220-f231-11e7-948b-2429f1551844.png\" rel=\"nofollow noreferrer\">Image on github (JavaScript Regular Expression Visualizer.)</a>\nSorry, I don't have a high enough reputation to include images, so, it's just a link for now.</p>\n\n<p>Here is a gist of an example function using this concept that's a little more advanced: <a href=\"https://gist.github.com/scagood/bd99371c072d49a4fee29d193252f5fc#file-matchquotes-js\" rel=\"nofollow noreferrer\">https://gist.github.com/scagood/bd99371c072d49a4fee29d193252f5fc#file-matchquotes-js</a></p>\n" }, { "answer_id": 49291272, "author": "Bigger", "author_id": 1447087, "author_profile": "https://Stackoverflow.com/users/1447087", "pm_score": 0, "selected": false, "text": "<p>I faced a similar problem trying to remove quoted strings that may interfere with parsing of some files.</p>\n\n<p>I ended up with a two-step solution that beats any convoluted regex you can come up with:</p>\n\n<pre><code> line = line.replace(\"\\\\\\\"\",\"\\'\"); // Replace escaped quotes with something easier to handle\n line = line.replaceAll(\"\\\"([^\\\"]*)\\\"\",\"\\\"x\\\"\"); // Simple is beautiful\n</code></pre>\n\n<p>Easier to read and probably more efficient.</p>\n" }, { "answer_id": 62857781, "author": "Aramis NSR", "author_id": 10499624, "author_profile": "https://Stackoverflow.com/users/10499624", "pm_score": 0, "selected": false, "text": "<p>If your IDE is IntelliJ Idea, you can forget all these headaches and store your regex into a String variable and as you copy-paste it inside the double-quote it will automatically change to a regex acceptable format.</p>\n<p>example in Java:</p>\n<pre><code>String s = &quot;\\&quot;en_usa\\&quot;:[^\\\\,\\\\}]+&quot;;\n</code></pre>\n<p>now you can use this variable in your regexp or anywhere.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do I get the substring `" It's big \"problem "` using a regular expression? ``` s = ' function(){ return " It\'s big \"problem "; }'; ```
``` /"(?:[^"\\]|\\.)*"/ ``` Works in The Regex Coach and PCRE Workbench. Example of test in JavaScript: ```js var s = ' function(){ return " Is big \\"problem\\", \\no? "; }'; var m = s.match(/"(?:[^"\\]|\\.)*"/); if (m != null) alert(m); ```
249,794
<p>I'me looking for a function that would receive a time and would round it to the next/previous hour / half-hour / quarter / minute.</p>
[ { "answer_id": 249828, "author": "IAdapter", "author_id": 30453, "author_profile": "https://Stackoverflow.com/users/30453", "pm_score": 6, "selected": true, "text": "<p>Try this function</p>\n\n<pre><code>CREATE FUNCTION [dbo].[RoundTime] (@Time datetime, @RoundTo float)\nRETURNS datetime\nAS\nBEGIN\n DECLARE @RoundedTime smalldatetime\n DECLARE @Multiplier float\n\n SET @Multiplier= 24.0/@RoundTo\n\n SET @RoundedTime= ROUND(CAST(CAST(CONVERT(varchar,@Time,121) AS datetime) AS float) * @Multiplier,0)/@Multiplier\n\n RETURN @RoundedTime\nEND\n\n\n\nselect dbo.roundtime('13:15',0.5)\n</code></pre>\n\n<p>The 1st param is the time to be rounded and the 2nd will be base on your list (0.5-half hour, 1-one hour, ...)</p>\n" }, { "answer_id": 3176740, "author": "Kevin", "author_id": 383318, "author_profile": "https://Stackoverflow.com/users/383318", "pm_score": 3, "selected": false, "text": "<p>Very nice thanks. I used it in-line to round to 15 minutes</p>\n\n<pre><code>convert(smalldatetime,ROUND(cast(TDatalog.Time as float) * (24/.25),0)/(24/.25)) AS RoundedTime\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1842864/" ]
I'me looking for a function that would receive a time and would round it to the next/previous hour / half-hour / quarter / minute.
Try this function ``` CREATE FUNCTION [dbo].[RoundTime] (@Time datetime, @RoundTo float) RETURNS datetime AS BEGIN DECLARE @RoundedTime smalldatetime DECLARE @Multiplier float SET @Multiplier= 24.0/@RoundTo SET @RoundedTime= ROUND(CAST(CAST(CONVERT(varchar,@Time,121) AS datetime) AS float) * @Multiplier,0)/@Multiplier RETURN @RoundedTime END select dbo.roundtime('13:15',0.5) ``` The 1st param is the time to be rounded and the 2nd will be base on your list (0.5-half hour, 1-one hour, ...)
249,797
<p>I'm currently using the ActiveRecord-based session store for my Rails app and I have a background process which clears out inactive sessions every 30 minutes.</p> <p>I'd like to switch to Rails' new cookie-based session store but how do I set the expiry time of the session to 30 minutes, as opposed to the default 'at end of session' value?</p>
[ { "answer_id": 249830, "author": "Gareth", "author_id": 31582, "author_profile": "https://Stackoverflow.com/users/31582", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"http://wiki.rubyonrails.org/rails/pages/HowtoChangeSessionOptions\" rel=\"nofollow noreferrer\">session options</a> page on the Rails wiki hints that this is only possible through a plugin:</p>\n\n<hr>\n\n<h2>Set the session cookie expire time</h2>\n\n<p>Unfortunately Rails has no way to dynamically set the expiry time of the session cookie. So it is recommended that you use the following plugin, which allows you to accomplish it: <a href=\"http://blog.codahale.com/2006/04/08/dynamic-session-expiration-times-with-rails/\" rel=\"nofollow noreferrer\">http://blog.codahale.com/2006/04/08/dynamic-session-expiration-times-with-rails/</a></p>\n\n<hr>\n\n<p>Of course take into account that the plugin is old, and may not work with your current version of Rails (I haven't looked at the specifics)</p>\n" }, { "answer_id": 249966, "author": "Codebeef", "author_id": 12037, "author_profile": "https://Stackoverflow.com/users/12037", "pm_score": -1, "selected": false, "text": "<p>You could try adding the following line to your environment.rb file:</p>\n\n<pre><code>session :session_key =&gt; 'my_session_key'\nsession :session_expires =&gt; 1.day.from_now\n</code></pre>\n\n<p>Alternatively, you can set the session options as follows:</p>\n\n<pre><code>ActionController::Base.session_options[:session_expires] = 1.day.from_now\n</code></pre>\n\n<p>I've not tested this thouroughly, so YMMV.</p>\n" }, { "answer_id": 251123, "author": "Daniel Beardsley", "author_id": 13216, "author_profile": "https://Stackoverflow.com/users/13216", "pm_score": 3, "selected": false, "text": "<p>Ideally, you'd want to add something like this to environment.rb:</p>\n\n<pre><code>session :session_expires =&gt; 1.day.from_now\n</code></pre>\n\n<p>But that won't work because the code is only run once when the APP is started and thus the next day all your sessions are being created with an expiration in the past.</p>\n\n<p>I usually set the <code>session_expires</code> to some time far in the future (6 months). Then manually set and check a <code>session[:expires]</code> date in a <code>before_filter</code> on my application controller and reset the session when that date has passed.</p>\n\n<p>This makes it VERY easy to add a 'Keep me logged in for ___' option when signing in, you just set <code>session[:expires] = Time.now + ___</code></p>\n" }, { "answer_id": 251462, "author": "Allan L.", "author_id": 19527, "author_profile": "https://Stackoverflow.com/users/19527", "pm_score": 0, "selected": false, "text": "<p>Use this, it's working for me in rails 2.1.x:</p>\n\n<p><a href=\"http://squarewheel.wordpress.com/2007/11/03/session-cookie-expiration-time-in-rails/\" rel=\"nofollow noreferrer\">SlidingSessions</a></p>\n\n<p>I currently have cookies set to expire exactly 2 weeks after a user logs in, and setting it to 30 minutes is simple.</p>\n" }, { "answer_id": 3351506, "author": "Graeme Mathieson", "author_id": 341874, "author_profile": "https://Stackoverflow.com/users/341874", "pm_score": 5, "selected": true, "text": "<p>I stumbled across this question after a conversation in the office. Just for the sake of completeness, I've discovered that it is possible to expire sessions after a period of inactivity and it's built into Rails. In config/environment.rb, do something along the lines of:</p>\n\n<pre><code>config.action_controller.session = {\n :key =&gt; 'whatever',\n :secret =&gt; 'nottellingyou',\n :expire_after =&gt; 30.minutes\n}\n</code></pre>\n\n<p>Check out <a href=\"http://github.com/rails/rails/blob/2-3-stable/actionpack/lib/action_controller/session/cookie_store.rb#L114\" rel=\"noreferrer\">lib/action_controller/session/cookie_store.rb#114</a> for the (apparently undocumented) option in action. Looks like it's been around since the move to Rack sessions back in December 2008.</p>\n" }, { "answer_id": 14544511, "author": "n8vision", "author_id": 1701350, "author_profile": "https://Stackoverflow.com/users/1701350", "pm_score": 2, "selected": false, "text": "<p>After a lot of pain &amp; experimenting, found in Rails 3.x, you need to set your custom session parameters in an after filter in every request</p>\n\n<pre><code> class ApplicationController &lt; ActionController::Base\n\n after_filter :short_session\n\n ...\n\n def short_session\n request.session_options = request.session_options.dup\n request.session_options[:expire_after] = 1.minute\n request.session_options.freeze\n end\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1174/" ]
I'm currently using the ActiveRecord-based session store for my Rails app and I have a background process which clears out inactive sessions every 30 minutes. I'd like to switch to Rails' new cookie-based session store but how do I set the expiry time of the session to 30 minutes, as opposed to the default 'at end of session' value?
I stumbled across this question after a conversation in the office. Just for the sake of completeness, I've discovered that it is possible to expire sessions after a period of inactivity and it's built into Rails. In config/environment.rb, do something along the lines of: ``` config.action_controller.session = { :key => 'whatever', :secret => 'nottellingyou', :expire_after => 30.minutes } ``` Check out [lib/action\_controller/session/cookie\_store.rb#114](http://github.com/rails/rails/blob/2-3-stable/actionpack/lib/action_controller/session/cookie_store.rb#L114) for the (apparently undocumented) option in action. Looks like it's been around since the move to Rack sessions back in December 2008.
249,819
<p>I have the following sql query for transforming data but is it possible to save the value of the int in some variable to avoid casting multiple times?</p> <pre><code>update prospekts set sni_kod = case when cast(sni_kod as int) &gt;= 1000 and cast(sni_kod as int) &lt;= 1499 or cast(sni_kod as int) &gt;= 1600 and cast(sni_kod as int) &lt;= 2439 then '1' when cast(sni_kod as int) &gt;= 7000 and cast(sni_kod as int) &lt;= 7499 then 'W' else sni_kod end </code></pre> <p>There are a lot more when-cases in the script, just showing the first one. I cannot use anything other than a simple text-script.</p> <p><strong>Update</strong> Using SQL Server 2000</p> <p>Thanks</p> <p>Anders</p>
[ { "answer_id": 249836, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 1, "selected": false, "text": "<p>you can use a subquery or CTE:</p>\n\n<pre><code>With xxx AS (\n i_sni_kod = cast(sni_kod as int)\n ...)\nUPDATE prospekts set sni_kod = case \n when i_sni_kod &gt;= 100 ...\n</code></pre>\n" }, { "answer_id": 249841, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 0, "selected": false, "text": "<p>Does this work in your DBMS?</p>\n\n<pre><code>update (select prospekts.*, cast(sni_kod as int) sni_kod_int from prospekts)\nset sni_kod = case\nwhen \n sni_kod_int &gt;= 1000 and sni_kod_int &lt;= 1499 \n or sni_kod_int &gt;= 1600 and sni_kod_int &lt;= 2439\nthen 1\nelse\n sni_kod\nend\n</code></pre>\n" }, { "answer_id": 249912, "author": "Jason Kester", "author_id": 27214, "author_profile": "https://Stackoverflow.com/users/27214", "pm_score": 0, "selected": false, "text": "<p>This seems like a problem with your model, not your query. Why is that column not simply an int?</p>\n\n<p>This seems like a <a href=\"http://weblogs.asp.net/alex_papadimoulis/archive/2005/05/25/408925.aspx\" rel=\"nofollow noreferrer\">shoe or glass bottle</a> question. The multiple casting issue you see is simply a result of earlier bad practices. Fix those and your problem will go away.</p>\n" }, { "answer_id": 249965, "author": "Chris Shaffer", "author_id": 6744, "author_profile": "https://Stackoverflow.com/users/6744", "pm_score": 0, "selected": false, "text": "<p>Something like this might works:</p>\n\n<pre><code>update prospekts set sni_kod = 1\nfrom prospekts\n join (select prospekts.primarykey, cast(prospekts.sni_kod as int) as sni_kod_int from prospekts) p2 on prospekts.primarykey = p2.primarykey\nWHERE (p2.sni_kod_int &gt;=1000 and p2.sni_kod_int &lt;= 1499)\n or (p2.sni_kod_int &gt;=1600 and p2.sni_kod_int &lt;= 2439)\n</code></pre>\n" }, { "answer_id": 250015, "author": "pipTheGeek", "author_id": 28552, "author_profile": "https://Stackoverflow.com/users/28552", "pm_score": 0, "selected": false, "text": "<p>The UPDATE statement that you show; I assume it will only be run once? If it is run a second time then the cast to int will fail when it finds the 'W' that was added in the previous run.\nThe best option here is to change the data type of the sni_kod column. Maybe you could explain what this column is holding, why it needs to hold both int and varchar data?\nLastly, SQL server is almost certainly only doing the cast once. It is pretty good at finding repeated expressions and sub-queries in a query and only running them once. If you are not sure then take a look at the execution plan.</p>\n" }, { "answer_id": 250017, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 2, "selected": false, "text": "<p>Is this just a one-off script, as it appears? If so, and you are just trying to save on typing then write as:</p>\n\n<pre><code>update prospekts set sni_kod = case\nwhen \n xxx &gt;= 1000 and xxx &lt;= 1499 \n or xxx &gt;= 1600 and xxx &lt;= 2439\nthen '1'\nwhen \n xxx &gt;= 7000 and xxx &lt;= 7499 \nthen 'W'\nelse\n sni_kod\nend\n</code></pre>\n\n<p>... and then do a global search and replace with a text editor.</p>\n\n<p>Or perhaps you are concerned about the performance of casting several times per row when once might do? But again, if this script is a one off, does it really matter?</p>\n" }, { "answer_id": 250099, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 2, "selected": false, "text": "<p>In you question, you mentioned that you want to \"avoid casting multiple times\". If you are concerned about performance issues, then don't be. SQL is not converting that field more than once (even though you have it in your script more than once).</p>\n\n<p>Example:</p>\n\n<pre><code>SELECT CONVERT(INT, '123'), CONVERT(INT, '123')\n</code></pre>\n\n<p>T-SQL is only going to run that method once (no performance loss).</p>\n\n<p>With that said, then the only other concern you could have is typing a bunch... and if that's the case, then the \"xxx / find and replace\" comment mentioned by Tony Andrews is good enough.</p>\n" }, { "answer_id": 250102, "author": "Kevin Fairchild", "author_id": 3743, "author_profile": "https://Stackoverflow.com/users/3743", "pm_score": 3, "selected": true, "text": "<p>Ok... here's my rewrite of your code...</p>\n\n<pre><code>UPDATE prospekts SET sni_kod = \n CASE\n WHEN ISNUMERIC(@sni_kod)=1 THEN\n CASE \n WHEN cast(@sni_kod as int) BETWEEN 1000 AND 1499 OR cast(@sni_kod as int) BETWEEN 1600 AND 2439 THEN '1'\n WHEN cast(@sni_kod as int) BETWEEN 7000 AND 7499 THEN 'W'\n ELSE @sni_kod\n END\n ELSE @sni_kod\n END\n</code></pre>\n\n<p>This way, it'll only attempt to do a CAST if it's a numeric value, so you won't get cast exceptions, like other people have mentioned in comments.</p>\n\n<p>Since you said there are a lot more statements involved, I'm guessing you have a lot more number ranges that get different values... If that's the case, you might be able to use a second table (can be a temporary one if, like your question says, you're limited to just SQL code) to join on which have min value, max value, and what you want to display based on that. Gets more tricky when you need to evaluate non-numeric values, but it isn't impossible.</p>\n\n<p>Without seeing the full statement, though, this is the best I can offer.</p>\n" }, { "answer_id": 251272, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "<p>I see someone posted a solution which joins a subquery in the from clause. Here's a solution with -just- a subquery in the from clause.</p>\n\n<pre><code>DECLARE @MyTable TABLE\n(\n theKey int identity(1,1) PRIMARY KEY,\n theValue varchar(30)\n)\n------ \nINSERT INTO @MyTable SELECT '1'\nINSERT INTO @MyTable SELECT '2'\nINSERT INTO @MyTable SELECT '3'\n------\n\nUPDATE sub\nSET theValue =\n CASE\n WHEN convertedvalue % 2 = 0 THEN 'even'\n ELSE theValue\n END\nFROM\n(\n SELECT\n CASE\n WHEN Isnumeric(theValue) = 1\n THEN convert(int, theValue)\n ELSE null\n END as convertedValue, *\n FROM @MyTable mt\n) as sub\n------\nSELECT *\nFROM @MyTable\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22092/" ]
I have the following sql query for transforming data but is it possible to save the value of the int in some variable to avoid casting multiple times? ``` update prospekts set sni_kod = case when cast(sni_kod as int) >= 1000 and cast(sni_kod as int) <= 1499 or cast(sni_kod as int) >= 1600 and cast(sni_kod as int) <= 2439 then '1' when cast(sni_kod as int) >= 7000 and cast(sni_kod as int) <= 7499 then 'W' else sni_kod end ``` There are a lot more when-cases in the script, just showing the first one. I cannot use anything other than a simple text-script. **Update** Using SQL Server 2000 Thanks Anders
Ok... here's my rewrite of your code... ``` UPDATE prospekts SET sni_kod = CASE WHEN ISNUMERIC(@sni_kod)=1 THEN CASE WHEN cast(@sni_kod as int) BETWEEN 1000 AND 1499 OR cast(@sni_kod as int) BETWEEN 1600 AND 2439 THEN '1' WHEN cast(@sni_kod as int) BETWEEN 7000 AND 7499 THEN 'W' ELSE @sni_kod END ELSE @sni_kod END ``` This way, it'll only attempt to do a CAST if it's a numeric value, so you won't get cast exceptions, like other people have mentioned in comments. Since you said there are a lot more statements involved, I'm guessing you have a lot more number ranges that get different values... If that's the case, you might be able to use a second table (can be a temporary one if, like your question says, you're limited to just SQL code) to join on which have min value, max value, and what you want to display based on that. Gets more tricky when you need to evaluate non-numeric values, but it isn't impossible. Without seeing the full statement, though, this is the best I can offer.
249,860
<p>How can i restrict adding controls in Panel in C# window controls? I have to restrict user to add controls in a panel at design time.</p>
[ { "answer_id": 249890, "author": "Echostorm", "author_id": 12862, "author_profile": "https://Stackoverflow.com/users/12862", "pm_score": -1, "selected": false, "text": "<p>Set AllowDrop to false.</p>\n" }, { "answer_id": 249934, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 1, "selected": false, "text": "<p>If you want to limit the types of controls or number of controls one can add to the panel you can make your own subclass of the panel and check the Control type or Control count in an overload of the Controls.Add method. </p>\n\n<p>Edit: Overloading the Controls.Add method was not as easy as I thought, but you can make a new class that extends the Panel class and override the OnControlAdded method to check the type of control that was added. Something like this should work:</p>\n\n<pre><code>class MyPanel : Panel\n{\n\n public MyPanel()\n { }\n\n protected override void OnControlAdded(ControlEventArgs e)\n {\n base.OnControlAdded(e);\n\n if (!(e.Control is Label))\n {\n MessageBox.Show(\"control \" + e.Control.Name + \" is not a label but a \" + e.Control.GetType().ToString());\n Controls.Remove(e.Control);\n }\n\n }\n\n}\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31159/" ]
How can i restrict adding controls in Panel in C# window controls? I have to restrict user to add controls in a panel at design time.
If you want to limit the types of controls or number of controls one can add to the panel you can make your own subclass of the panel and check the Control type or Control count in an overload of the Controls.Add method. Edit: Overloading the Controls.Add method was not as easy as I thought, but you can make a new class that extends the Panel class and override the OnControlAdded method to check the type of control that was added. Something like this should work: ``` class MyPanel : Panel { public MyPanel() { } protected override void OnControlAdded(ControlEventArgs e) { base.OnControlAdded(e); if (!(e.Control is Label)) { MessageBox.Show("control " + e.Control.Name + " is not a label but a " + e.Control.GetType().ToString()); Controls.Remove(e.Control); } } } ```
249,865
<p>We're seeing the error message ORA-00936 Missing Expression for the following SQL:</p> <p>Note that this is just a cut-down version of a much bigger SQL so rewriting it to a inner join or similar is not really in the scope of this:</p> <p>This is the SQL that fails:</p> <pre><code>select (select count(*) from gt_roster where ROS_ROSTERPLAN_ID = RPL_ID) from gt_rosterplan where RPL_ID = 432065061 </code></pre> <p>What I've tried: * Extracting the innermost SQL and substituting the ID from the outer SQL gives me the number 12. * Aliasing both the sub-query, and the count(*) individually and both at the same time does not change the outcome (ie. still an error)</p> <p>What else do I need to look at?</p> <p>The above are only tables, no views, RPL_ID is primary key of gt_rosterplan, and ROS_ROSTERPLAN_ID is a foreign key to this column, there is basically no magic or hidden information here.</p> <hr> <p><strong>Edit:</strong> In response to answer, no, you do not need the aliases here as the columns are uniquely named across the tables.</p> <hr> <p><strong>Solved:</strong> The problem was that the client was running the wrong client driver version, 9.2.0.1, and there are known problems with that version.</p>
[ { "answer_id": 249915, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 2, "selected": true, "text": "<p>That should work, assuming the column names are not ambiguous (and even if they were that would lead to a different error). I ran an equivalent statement and got a result without error:</p>\n\n<pre><code>SQL&gt; select (select count(*) from emp2 where empdeptno = deptno)\n 2 from dept\n 3 where deptno=10\n 4 /\n\n(SELECTCOUNT(*)FROMEMP2WHEREEMPDEPTNO=DEPTNO)\n---------------------------------------------\n 3\n</code></pre>\n\n<p>Googling it appears that there are or have been Oracle bugs leading to ORA-00936 errors - see <a href=\"http://oracle-error.blogspot.com/2008/04/ora-00936missing-expression.html\" rel=\"nofollow noreferrer\">this for example</a>.</p>\n" }, { "answer_id": 482715, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 2, "selected": false, "text": "<p>The problem was that the client was running the wrong client driver version, 9.2.0.1, and there are known problems with that version.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267/" ]
We're seeing the error message ORA-00936 Missing Expression for the following SQL: Note that this is just a cut-down version of a much bigger SQL so rewriting it to a inner join or similar is not really in the scope of this: This is the SQL that fails: ``` select (select count(*) from gt_roster where ROS_ROSTERPLAN_ID = RPL_ID) from gt_rosterplan where RPL_ID = 432065061 ``` What I've tried: \* Extracting the innermost SQL and substituting the ID from the outer SQL gives me the number 12. \* Aliasing both the sub-query, and the count(\*) individually and both at the same time does not change the outcome (ie. still an error) What else do I need to look at? The above are only tables, no views, RPL\_ID is primary key of gt\_rosterplan, and ROS\_ROSTERPLAN\_ID is a foreign key to this column, there is basically no magic or hidden information here. --- **Edit:** In response to answer, no, you do not need the aliases here as the columns are uniquely named across the tables. --- **Solved:** The problem was that the client was running the wrong client driver version, 9.2.0.1, and there are known problems with that version.
That should work, assuming the column names are not ambiguous (and even if they were that would lead to a different error). I ran an equivalent statement and got a result without error: ``` SQL> select (select count(*) from emp2 where empdeptno = deptno) 2 from dept 3 where deptno=10 4 / (SELECTCOUNT(*)FROMEMP2WHEREEMPDEPTNO=DEPTNO) --------------------------------------------- 3 ``` Googling it appears that there are or have been Oracle bugs leading to ORA-00936 errors - see [this for example](http://oracle-error.blogspot.com/2008/04/ora-00936missing-expression.html).
249,866
<p>I'm creating a <code>Path</code> in <em>Silverlight</em>, and adding elements to it on mouse events. But, although the elements are there in memory, the screen doesn't get updated until something else causes a screen repaint to happen.</p> <p>Here's the relevant code - I'm responding to a mouse event, and I keep a class member of the path I'm editing.</p> <pre><code>Path path = null; private void LayoutRoot_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { Point thisPoint = e.GetPosition(LayoutRoot); if (path == null) { CreateNewPath(thisPoint); path.LayoutUpdated += new EventHandler(path_LayoutUpdated); } else { path.AddLineElement(thisPoint); } } private void CreateNewPath(Point startPoint) { path = new Path(); PathGeometry geometry = new PathGeometry(); path.Data = geometry; PathFigureCollection figures = new PathFigureCollection(); geometry.Figures = figures; PathFigure figure = new PathFigure(); figures.Add(figure); figure.StartPoint = startPoint; figure.Segments = new PathSegmentCollection(); path.Stroke = new SolidColorBrush(Colors.Red); path.StrokeThickness = 2; path.Stretch = Stretch.None; LayoutRoot.Children.Add(path); } </code></pre> <p><code>AddLineElement</code> is an extension method for the path class just to simplify:</p> <pre><code>public static class PathHelper { public static void AddLineElement(this Path thePath, Point newPoint) { PathGeometry geometry = thePath.Data as PathGeometry; geometry.Figures[0].Segments.Add(new LineSegment { Point = newPoint }); } } </code></pre> <p>This is the minimum needed to reproduce the problem. If you run this code in a full WPF app it all works as expected. Mouse clicks add line elements which appear immediately. However, in <em>Silverlight</em> it's a different matter. The clicks appear to do nothing, even though stepping through the code shows that the data is getting added. But if you click a few times, then resize the browser, for example, the path elements appear. If you happen to have a button on the page as well, and move the mouse over, the path will appear.</p> <p>I've tried all the obvious things, like calling <code>InvalidateMeasure</code> and <code>InvalidateArrange</code> on the <code>Path</code> (and on the parent grid) to no avail. </p> <p>The only workaround I've got is to change a property on the path then change it back, which seems to be enough to get the rendering engine to draw the new path elements. I use <code>Opacity</code>. You have to set it to a different value, otherwise (I presume) the <code>PropertyChanged</code> event won't fire. It's a kludge, though.</p> <p>Has anyone else played with paths in this way? I guess if I were putting other graphical elements on screen at the same time this wouldn't be an issue, so it's probably not something which will affect may people, but it would be good to know if there's a more correct way to do it.</p>
[ { "answer_id": 250873, "author": "Bryant", "author_id": 10893, "author_profile": "https://Stackoverflow.com/users/10893", "pm_score": 0, "selected": false, "text": "<p>What kind of element is your layout root? I copied your code and used a Canvas as the layout root and it works great in both IE and Firefox. </p>\n\n<pre><code>&lt;UserControl x:Class=\"SilverlightTesting.Page\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" \n Width=\"400\" Height=\"300\"&gt;\n &lt;Canvas x:Name=\"LayoutRoot\" Background=\"White\" Width=\"400\" Height=\"300\" MouseLeftButtonDown=\"LayoutRoot_MouseLeftButtonDown\"/&gt;\n&lt;/UserControl&gt;\n</code></pre>\n\n<p>I copied all your code and created a new path_LayoutUpdated method which does nothing. When I click on the screen I get new lines draw to the point that I clicked.</p>\n" }, { "answer_id": 852122, "author": "Conceptdev", "author_id": 25673, "author_profile": "https://Stackoverflow.com/users/25673", "pm_score": 1, "selected": false, "text": "<p>I needed something very similar but drawing on the new Silverlight VE Map Control. Your code above worked fine without any fiddling other properties to 'force a redraw'. Code here for your reference:</p>\n\n<pre><code>using System.Windows.Controls;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing Microsoft.VirtualEarth.MapControl;\n\nnamespace MapInfo\n{\n public partial class Page : UserControl\n {\n /// &lt;summary&gt;\n /// Sample drawing a polyline on a Virtual Earth map\n /// &lt;/summary&gt;\n public Page()\n {\n InitializeComponent();\n VEMap.MouseLeftButtonUp += new MouseButtonEventHandler(VEMap_MouseLeftButtonDown);\n VEMap.MouseLeave += new MouseEventHandler(VEMap_MouseLeave);\n }\n\n MapPolyline polyline = null;\n\n /// &lt;summary&gt;\n /// Ends drawing the current polyline\n /// &lt;/summary&gt;\n void VEMap_MouseLeave(object sender, MouseEventArgs e)\n {\n polyline = null;\n }\n /// &lt;summary&gt;\n /// Start or add-to a polyline\n /// &lt;/summary&gt;\n private void VEMap_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n {\n Map m = (Map)sender;\n\n Location l = m.ViewportPointToLocation(e.GetPosition(m));\n\n if (polyline == null)\n {\n CreateNewPolyline(l);\n }\n else\n {\n polyline.Locations.Add(l);\n }\n }\n /// &lt;summary&gt;\n /// Create a new MapPolyline\n /// &lt;/summary&gt;\n /// &lt;param name=\"startPoint\"&gt;starting Location&lt;/param&gt;\n private void CreateNewPolyline(Location startPoint)\n {\n polyline = new MapPolyline();\n polyline.Stroke = new SolidColorBrush(Colors.Red);\n polyline.StrokeThickness = 2;\n var lc = new LocationCollection();\n lc.Add(startPoint);\n polyline.Locations = lc;\n VEMap.Children.Add(polyline);\n }\n }\n}\n</code></pre>\n\n<p>Doesn't help your immediate scenario but shows that other Silverlight stuff works as you'd expect. Might help someone else I hope...</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6483/" ]
I'm creating a `Path` in *Silverlight*, and adding elements to it on mouse events. But, although the elements are there in memory, the screen doesn't get updated until something else causes a screen repaint to happen. Here's the relevant code - I'm responding to a mouse event, and I keep a class member of the path I'm editing. ``` Path path = null; private void LayoutRoot_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { Point thisPoint = e.GetPosition(LayoutRoot); if (path == null) { CreateNewPath(thisPoint); path.LayoutUpdated += new EventHandler(path_LayoutUpdated); } else { path.AddLineElement(thisPoint); } } private void CreateNewPath(Point startPoint) { path = new Path(); PathGeometry geometry = new PathGeometry(); path.Data = geometry; PathFigureCollection figures = new PathFigureCollection(); geometry.Figures = figures; PathFigure figure = new PathFigure(); figures.Add(figure); figure.StartPoint = startPoint; figure.Segments = new PathSegmentCollection(); path.Stroke = new SolidColorBrush(Colors.Red); path.StrokeThickness = 2; path.Stretch = Stretch.None; LayoutRoot.Children.Add(path); } ``` `AddLineElement` is an extension method for the path class just to simplify: ``` public static class PathHelper { public static void AddLineElement(this Path thePath, Point newPoint) { PathGeometry geometry = thePath.Data as PathGeometry; geometry.Figures[0].Segments.Add(new LineSegment { Point = newPoint }); } } ``` This is the minimum needed to reproduce the problem. If you run this code in a full WPF app it all works as expected. Mouse clicks add line elements which appear immediately. However, in *Silverlight* it's a different matter. The clicks appear to do nothing, even though stepping through the code shows that the data is getting added. But if you click a few times, then resize the browser, for example, the path elements appear. If you happen to have a button on the page as well, and move the mouse over, the path will appear. I've tried all the obvious things, like calling `InvalidateMeasure` and `InvalidateArrange` on the `Path` (and on the parent grid) to no avail. The only workaround I've got is to change a property on the path then change it back, which seems to be enough to get the rendering engine to draw the new path elements. I use `Opacity`. You have to set it to a different value, otherwise (I presume) the `PropertyChanged` event won't fire. It's a kludge, though. Has anyone else played with paths in this way? I guess if I were putting other graphical elements on screen at the same time this wouldn't be an issue, so it's probably not something which will affect may people, but it would be good to know if there's a more correct way to do it.
I needed something very similar but drawing on the new Silverlight VE Map Control. Your code above worked fine without any fiddling other properties to 'force a redraw'. Code here for your reference: ``` using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using Microsoft.VirtualEarth.MapControl; namespace MapInfo { public partial class Page : UserControl { /// <summary> /// Sample drawing a polyline on a Virtual Earth map /// </summary> public Page() { InitializeComponent(); VEMap.MouseLeftButtonUp += new MouseButtonEventHandler(VEMap_MouseLeftButtonDown); VEMap.MouseLeave += new MouseEventHandler(VEMap_MouseLeave); } MapPolyline polyline = null; /// <summary> /// Ends drawing the current polyline /// </summary> void VEMap_MouseLeave(object sender, MouseEventArgs e) { polyline = null; } /// <summary> /// Start or add-to a polyline /// </summary> private void VEMap_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { Map m = (Map)sender; Location l = m.ViewportPointToLocation(e.GetPosition(m)); if (polyline == null) { CreateNewPolyline(l); } else { polyline.Locations.Add(l); } } /// <summary> /// Create a new MapPolyline /// </summary> /// <param name="startPoint">starting Location</param> private void CreateNewPolyline(Location startPoint) { polyline = new MapPolyline(); polyline.Stroke = new SolidColorBrush(Colors.Red); polyline.StrokeThickness = 2; var lc = new LocationCollection(); lc.Add(startPoint); polyline.Locations = lc; VEMap.Children.Add(polyline); } } } ``` Doesn't help your immediate scenario but shows that other Silverlight stuff works as you'd expect. Might help someone else I hope...
249,867
<p>I was wondering if in Java I would get any odd behaviour if I synchronise twice on the same object?</p> <p>The scenario is as follows</p> <pre><code>pulbic class SillyClassName { object moo; ... public void method1(){ synchronized(moo) { .... method2(); .... } } public void method2(){ synchronized(moo) { doStuff(); } } } </code></pre> <p>Both methods use the object and are synchronised on it. Will the second method when called by the first method stop because it's locked?</p> <p>I don't think so because it's the same thread but I'm unsure of any other odd results that might occur.</p>
[ { "answer_id": 249888, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>In java, the <code>synchronized</code> keyword on a method basically synchronizes on the current object, so in effect it's doing what you suggest above implicitly.</p>\n\n<p>You won't experience problems with synchronizing on one object in one method and then synchronizing on the same object in another method because, as you say, the current thread already holds the lock on that object.</p>\n" }, { "answer_id": 249896, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 1, "selected": false, "text": "<p>No problems. In your example, (once you fix your code to get rid of the compile warnings that you'll get ;) ), the synchronization ensures that the blocks in method1 and method2 will not execute simultaneously.</p>\n\n<p>That's kind of the point of synchronization. :)</p>\n\n<hr>\n\n<p>Edit: Sorry, missed parts of your question, but Phill answered it. To summarize, a single thread cannot deadlock itself.</p>\n" }, { "answer_id": 249907, "author": "Leigh", "author_id": 26061, "author_profile": "https://Stackoverflow.com/users/26061", "pm_score": 7, "selected": true, "text": "<h1>Reentrant</h1>\n<p>Synchronized blocks use <em>reentrant</em> locks, which means if the thread already holds the lock, it can re-aquire it without problems. Therefore your code will work as you expect.</p>\n<p>See the bottom of the <a href=\"https://docs.oracle.com/javase/tutorial/index.html\" rel=\"noreferrer\">Java Tutorial</a> page <a href=\"https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html\" rel=\"noreferrer\">Intrinsic Locks and Synchronization</a>.</p>\n<p>To quote as of 2015-01…</p>\n<blockquote>\n<p><strong>Reentrant Synchronization</strong></p>\n<p>Recall that a thread cannot acquire a lock owned by another thread. But a thread can acquire a lock that it already owns. Allowing a thread to acquire the same lock more than once enables <em>reentrant synchronization</em>. This describes a situation where synchronized code, directly or indirectly, invokes a method that also contains synchronized code, and both sets of code use the same lock. Without reentrant synchronization, synchronized code would have to take many additional precautions to avoid having a thread cause itself to block.</p>\n</blockquote>\n" }, { "answer_id": 250680, "author": "RuntimeException", "author_id": 15789, "author_profile": "https://Stackoverflow.com/users/15789", "pm_score": 0, "selected": false, "text": "<p>No, the second method will not stop if called by the first. No odd results will occur (Except a slight overhead for checking the lock. This won't matter much. From Java 6 onwards, you have lock coarsening in the JVM - <a href=\"https://www.oracle.com/java/technologies/javase/6performance.html\" rel=\"nofollow noreferrer\">Java SE 6 Performance White Paper</a>.)</p>\n<p>For example, take a look at source code of java.util.Vector. There are a lot of calls to other synchronized methods from within synchronized methods.</p>\n" }, { "answer_id": 8085809, "author": "Odell Damon", "author_id": 1040522, "author_profile": "https://Stackoverflow.com/users/1040522", "pm_score": 2, "selected": false, "text": "<p>Java appears to fully support nested locks on one object by the same thread. This means that if a thread has an outer and an inner lock on an object, and another thread tries to lock on the same object, the second thread will be suspended until <b>both</b> locks have been released by the first thread.<p>\nMy testing was done under Java 6 SE.</p>\n" }, { "answer_id": 10018786, "author": "Praveen Mookoni", "author_id": 1313824, "author_profile": "https://Stackoverflow.com/users/1313824", "pm_score": 2, "selected": false, "text": "<p>I think we have to use reentrant lock for what you are trying to do. Here's a snippet from <a href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/ReentrantLock.html\" rel=\"nofollow noreferrer\">http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/ReentrantLock.html</a>.</p>\n\n<blockquote>\n <p>What do we mean by a reentrant lock? Simply that there is an acquisition count associated with the lock, and if a thread that holds the lock acquires it again, the acquisition count is incremented and the lock then needs to be released twice to truly release the lock. This parallels the semantics of synchronized; if a thread enters a synchronized block protected by a monitor that the thread already owns, the thread will be allowed to proceed, and the lock will not be released when the thread exits the second (or subsequent) synchronized block, but only will be released when it exits the first synchronized block it entered protected by that monitor.</p>\n</blockquote>\n\n<p>Though I have not tried it, I guess if you want to do what you have above, you have to use a re-entrant lock. </p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ]
I was wondering if in Java I would get any odd behaviour if I synchronise twice on the same object? The scenario is as follows ``` pulbic class SillyClassName { object moo; ... public void method1(){ synchronized(moo) { .... method2(); .... } } public void method2(){ synchronized(moo) { doStuff(); } } } ``` Both methods use the object and are synchronised on it. Will the second method when called by the first method stop because it's locked? I don't think so because it's the same thread but I'm unsure of any other odd results that might occur.
Reentrant ========= Synchronized blocks use *reentrant* locks, which means if the thread already holds the lock, it can re-aquire it without problems. Therefore your code will work as you expect. See the bottom of the [Java Tutorial](https://docs.oracle.com/javase/tutorial/index.html) page [Intrinsic Locks and Synchronization](https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html). To quote as of 2015-01… > > **Reentrant Synchronization** > > > Recall that a thread cannot acquire a lock owned by another thread. But a thread can acquire a lock that it already owns. Allowing a thread to acquire the same lock more than once enables *reentrant synchronization*. This describes a situation where synchronized code, directly or indirectly, invokes a method that also contains synchronized code, and both sets of code use the same lock. Without reentrant synchronization, synchronized code would have to take many additional precautions to avoid having a thread cause itself to block. > > >
249,883
<p>I have two XML files with two different XSD schemas and different namespaces. They have both an identical substructure. And now i need to copy that node (and all childs) from one XML document to the other one. </p> <p>Clone would do, if the namespaces were the same. Is there a nice way to do it? (The substructure will change later on - but will be kept identical.)</p>
[ { "answer_id": 250057, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 3, "selected": true, "text": "<p>Basically, you need an XSL transformation that creates new elements with equal names, but a different namespace.</p>\n\n<p>Consider the following input XML:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;test xmlns=\"http://tempuri.org/ns_old\"&gt;\n &lt;child attrib=\"value\"&gt;text&lt;/child&gt;\n&lt;/test&gt;\n</code></pre>\n\n<p>Now you need a template that says \"copy structure and name of everything you see, but declare a new namespace while you're at it\":</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;xsl:stylesheet\n version=\"1.0\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:old=\"http://tempuri.org/ns_old\"\n&gt;\n &lt;xsl:output method=\"xml\" version=\"1.0\" \n encoding=\"UTF-8\" indent=\"yes\" omit-xml-declaration=\"no\" \n /&gt;\n\n &lt;xsl:template match=\"node()|@*\"&gt;\n &lt;xsl:copy&gt;\n &lt;xsl:apply-templates select=\"node()|@*\"/&gt;\n &lt;/xsl:copy&gt;\n &lt;/xsl:template&gt;\n\n &lt;xsl:template match=\"old:*\"&gt;\n &lt;xsl:element name=\"{local-name()}\" namespace=\"http://tempuri.org/ns_new\"&gt;\n &lt;xsl:apply-templates select=\"node()|@*\"/&gt;\n &lt;/xsl:element&gt;\n &lt;/xsl:template&gt;\n\n&lt;/xsl:stylesheet&gt;\n</code></pre>\n\n<p>When you run the above XML through it, this produces:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;test xmlns=\"http://tempuri.org/ns_new\"&gt;\n &lt;child attrib=\"value\"&gt;text&lt;/child&gt;\n&lt;/test&gt;\n</code></pre>\n\n<p>All your <code>http://tempuri.org/ns_old</code> elements have effectively changed their namespace. When your input XML has more than one namespace at the same time, the XSL must most likely be extended a bit.</p>\n" }, { "answer_id": 251661, "author": "steve", "author_id": 32103, "author_profile": "https://Stackoverflow.com/users/32103", "pm_score": 0, "selected": false, "text": "<p>Not sure if this applies, but I've done something similar working with two xml docs in vb.net:</p>\n\n<pre><code>Private Shared Sub CopyElement(ByVal FromE As Xml.XmlElement, ByVal ToE As Xml.XmlElement)\n CopyElement(FromE, ToE, Nothing)\nEnd Sub\nPrivate Shared Sub CopyElement(ByVal FromE As Xml.XmlElement, ByVal ToE As Xml.XmlElement, ByVal overAttr As Xml.XmlAttributeCollection)\n Dim NewE As Xml.XmlElement\n Dim e As Xml.XmlElement\n NewE = ToE.OwnerDocument.CreateElement(FromE.Name)\n\n CopyAttributes(FromE, NewE)\n If Not overAttr Is Nothing Then\n OverrideAttributes(overAttr, NewE)\n End If\n For Each e In FromE\n CopyElement(e, NewE, overAttr)\n Next\n ToE.AppendChild(NewE)\n\n\nEnd Sub\nPrivate Shared Sub CopyAttributes(ByVal FromE As Xml.XmlElement, ByVal ToE As Xml.XmlElement)\n Dim a As Xml.XmlAttribute\n For Each a In FromE.Attributes\n ToE.SetAttribute(a.Name, a.Value)\n Next\nEnd Sub\nPrivate Shared Sub OverrideAttributes(ByVal AC As Xml.XmlAttributeCollection, ByVal E As Xml.XmlElement)\n Dim a As Xml.XmlAttribute\n For Each a In AC\n If Not E.Attributes.ItemOf(a.Name) Is Nothing Then\n E.SetAttribute(a.Name, a.Value)\n End If\n Next\nEnd Sub\n</code></pre>\n" }, { "answer_id": 531434, "author": "zhaorufei", "author_id": 64469, "author_profile": "https://Stackoverflow.com/users/64469", "pm_score": 0, "selected": false, "text": "<p>Following Tomalak's example(with a little fix), but use SetAttribute + OuterXml + InnerXml is much more simple\nconst string xml_str = @\"</p>\n\n<pre>\n&lt;?xml version='1.0' encoding='UTF-8'?>\n&lt;root>\n &lt;test xmlns='http://tempuri.org/ns_old'>\n &lt;child attrib='value'>text&lt;/child>\n &lt;/test>\n&lt;/root>\";\n</pre>\n\n<p>\";</p>\n\n<pre><code>public static void RunSnippet()\n</code></pre>\n\n<p>{</p>\n\n<pre><code> XmlDocument doc = new XmlDocument();\n doc.LoadXml(xml_str);\n\n XmlElement elem = doc.DocumentElement[\"test\"];\n WL( string.Format(\"[{0}]\", elem ) );\n elem.SetAttribute(\"xmlns\", \"http://another.namespace.org/\");\n WL( elem.OuterXml );\n\n XmlDocument another_doc = new XmlDocument();\n another_doc.LoadXml(\"&lt;root/&gt;\");\n another_doc.DocumentElement.InnerXml = elem.OuterXml;\n WL( another_doc.DocumentElement.OuterXml );\n</code></pre>\n\n<p>}</p>\n" }, { "answer_id": 11391690, "author": "Kanika", "author_id": 1511452, "author_profile": "https://Stackoverflow.com/users/1511452", "pm_score": 0, "selected": false, "text": "<p>In case you wish to copy all the sub elements of a node on matching of some attribute. You can just copy the <code>InnerXML</code> of referenced node and set it equal to new node.</p>\n\n<p>Something like this, below, I have a XML block with <em>Document Element</em> or <em>Root</em> element as <code>Tablist</code>, I need to add new node under <code>Tablist</code> with <code>Role=\"Ka\"</code> and all the sub nodes of <code>Ka</code> should be same as XXX:</p>\n\n<pre><code>&lt;Tablist&gt;\n &lt;Designation Role=\"XXX\"&gt;\n &lt;!--&lt;Tab name=\"x\" default=\"x\"/&gt;--&gt;\n &lt;!--&lt;Tab name=\"y\" default=\"y\"/&gt;--&gt;\n &lt;Tab name=\"r\" default=\"r\" /&gt;\n &lt;Tab name=\"rd\" default=\"rd\" /&gt;\n &lt;Tab name=\"qq\" default=\"qq\" /&gt;\n &lt;Tab name=\"ddd\" default=\"ddd\" /&gt;\n &lt;/Designation&gt;\n &lt;Designation Role=\"YYY\"&gt;\n &lt;!--&lt;Tab name=\"a\" default=\"a\"/&gt;--&gt;\n &lt;!--&lt;Tab name=\"b\" default=\"b\"/&gt;--&gt;\n &lt;Tab name=\"c\" default=\"c\" /&gt;\n &lt;Tab name=\"dd\" default=\"dd\" /&gt;\n &lt;Tab name=\"ee\" default=\"ee\" /&gt;\n &lt;Tab name=\"f\" default=\"f\" /&gt;\n &lt;/Designation&gt;\n &lt;/Tablist&gt;\n</code></pre>\n\n<p>So I just write following code:</p>\n\n<pre><code>XmlDocument objXmlDocument1 = null;\nobjXmlDocument1 = new XmlDocument();\nobjXmlDocument1.Load(\n System.Web.HttpContext.Current.Server.MapPath(\"\") + \n \"\\\\XMLSchema\\\\\" + \n \"ABC.xml\");\n\nXMLNodesList nodes1 = objXmlDocument1.GetElementsByTagName(\"Designation\");\nforeach (XmlNode n in nodes1) {\n if (n.Attributes[\"Role\"].Value.Trim().Equals(\"XXX\"){ \n objnode1 = n;\n break;\n }\n}\nif (objnode1 != null){\n XmlNodeList innerNodes1 = objnode1.ChildNodes;\n XmlNode newNode1 = objXmlDocument1.CreateElement(\"Designation\");\n XmlAttribute newAtt1 = objXmlDocument1.CreateAttribute(\"Role\");\n newAtt1.Value = \"Ka\";\n newNode1.Attributes.Append(newAtt1);\n newNode1.InnerXml=objnode1.InnerXml;\n objXmlDocument1.DocumentElement.AppendChild(newNode1);\n}\nobjXmlDocument1.Save(\n System.Web.HttpContext.Current.Server.MapPath(\"\") + \n \"\\\\XMLSchema\\\\\" + \n \"ABC.xml\");\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32726/" ]
I have two XML files with two different XSD schemas and different namespaces. They have both an identical substructure. And now i need to copy that node (and all childs) from one XML document to the other one. Clone would do, if the namespaces were the same. Is there a nice way to do it? (The substructure will change later on - but will be kept identical.)
Basically, you need an XSL transformation that creates new elements with equal names, but a different namespace. Consider the following input XML: ``` <?xml version="1.0" encoding="UTF-8"?> <test xmlns="http://tempuri.org/ns_old"> <child attrib="value">text</child> </test> ``` Now you need a template that says "copy structure and name of everything you see, but declare a new namespace while you're at it": ``` <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:old="http://tempuri.org/ns_old" > <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" omit-xml-declaration="no" /> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <xsl:template match="old:*"> <xsl:element name="{local-name()}" namespace="http://tempuri.org/ns_new"> <xsl:apply-templates select="node()|@*"/> </xsl:element> </xsl:template> </xsl:stylesheet> ``` When you run the above XML through it, this produces: ``` <?xml version="1.0" encoding="UTF-8"?> <test xmlns="http://tempuri.org/ns_new"> <child attrib="value">text</child> </test> ``` All your `http://tempuri.org/ns_old` elements have effectively changed their namespace. When your input XML has more than one namespace at the same time, the XSL must most likely be extended a bit.
249,926
<pre><code>&lt;a id="lblShowTimings" runat="server" title='&lt;%# Eval("SHOW_Name") %&gt;' onclick='PopulateTicketDiv(&lt;%#Eval("SHOW_ID") %&gt;)'&gt; &lt;-- this is the problem %#Eval("SHOW_Time") %&gt; &lt;/a&gt; </code></pre> <p>Can Eval be passed as an argument to a javascript function? If so whats the syntax?</p>
[ { "answer_id": 249986, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 6, "selected": true, "text": "<p>Yes. What you want to do is this, though:</p>\n\n<pre><code>onclick='&lt;%# \"PopulateTicketDiv(\" +Eval(\"SHOW_ID\") + \" );\" %&gt;'\n</code></pre>\n" }, { "answer_id": 250004, "author": "Rob Stevenson-Leggett", "author_id": 4950, "author_profile": "https://Stackoverflow.com/users/4950", "pm_score": 2, "selected": false, "text": "<p>Try</p>\n\n<pre><code>&lt;script type=\"javascript\"&gt;\n //Pollute the global namespace\n var ticketDivID = &lt;%= SHOW_ID %&gt;\n&lt;/script&gt;\n\n&lt;a id=\"lblShowTimings\" runat=\"server\" title='&lt;%# Eval(\"SHOW_Name\") %&gt;' onclick='PopulateTicketDiv(ticketDivID)'&gt; &lt;%#Eval(\"SHOW_Time\") %&gt;&lt;/a&gt;\n</code></pre>\n\n<p>On a side note because you've got runat=\"server\" you can set the onclick from the backend in OnRowDataBound if this is in a grid/repeater or on page_load if not.</p>\n" }, { "answer_id": 5893726, "author": "Rohan ", "author_id": 739340, "author_profile": "https://Stackoverflow.com/users/739340", "pm_score": 5, "selected": false, "text": "<p>The above solution creates problem when you want to pass the string as parameter,\nyou can use following syntax to get through:</p>\n\n<pre><code>OnClientClick='&lt;%# String.Format(\"javascript:return displayDeleteWarning(\\\"{0}\\\")\", Eval(\"ItemName\").ToString()) %&gt;' \n</code></pre>\n\n<p>Above line should work irrespective of parameter data type</p>\n" }, { "answer_id": 14872753, "author": "Sajishanoop", "author_id": 1911897, "author_profile": "https://Stackoverflow.com/users/1911897", "pm_score": 1, "selected": false, "text": "<p>Pls Check this code</p>\n\n<p>onclick='&lt;%#Eval(\"DocumentPath\",\"Chk(\\\"{0}\\\")\") %>'</p>\n" }, { "answer_id": 20137061, "author": "Aruna", "author_id": 2047527, "author_profile": "https://Stackoverflow.com/users/2047527", "pm_score": 2, "selected": false, "text": "<p>You can use this syntax within a gridview, repeater or..etc.</p>\n\n<pre><code>&lt;asp:ImageButton \n ID=\"Imagebutton1\" runat=\"server\"\n ImageUrl=\"../../common/images/pencil.gif\" \n OnClientClick='&lt;%# String.Format(\"EditBankAccount(\\\"{0}\\\");\", Eval(\"BankAccountID\")) %&gt;'\n OnClick=\"ImgBankAccountsDGEdit_Click\"/&gt;\n</code></pre>\n\n<p>Your JavaScript function would be:</p>\n\n<pre><code> function EditBankAccount(bankaccountid) {\n // Your code goes here\n // return true OR false based on your requirement\n }\n</code></pre>\n" }, { "answer_id": 64317023, "author": "sushil suthar", "author_id": 4195533, "author_profile": "https://Stackoverflow.com/users/4195533", "pm_score": 0, "selected": false, "text": "<p>Basically you need to escape the quote</p>\n<pre><code>&lt;asp:CheckBox onclick='&lt;%# &quot;ToggleByPassValidationRules(&quot; + &quot;\\&quot;&quot; + Eval(&quot;Name&quot;) + &quot;\\&quot;&quot; + &quot;);&quot; %&gt;' ID=&quot;chkIsRuleActive&quot; runat=&quot;server&quot; Enabled=&quot;false&quot; /&gt;\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17447/" ]
``` <a id="lblShowTimings" runat="server" title='<%# Eval("SHOW_Name") %>' onclick='PopulateTicketDiv(<%#Eval("SHOW_ID") %>)'> <-- this is the problem %#Eval("SHOW_Time") %> </a> ``` Can Eval be passed as an argument to a javascript function? If so whats the syntax?
Yes. What you want to do is this, though: ``` onclick='<%# "PopulateTicketDiv(" +Eval("SHOW_ID") + " );" %>' ```
249,927
<p>How can I restart(recycle) IIS Application Pool from C# (.net 2)?</p> <p>Appreciate if you post sample code?</p>
[ { "answer_id": 249942, "author": "dove", "author_id": 30913, "author_profile": "https://Stackoverflow.com/users/30913", "pm_score": 7, "selected": true, "text": "<p>If you're on <strong>IIS7</strong> then this will do it if it is stopped. I assume you can adjust for restarting without having to be shown.</p>\n\n<pre><code>// Gets the application pool collection from the server.\n[ModuleServiceMethod(PassThrough = true)]\npublic ArrayList GetApplicationPoolCollection()\n{\n // Use an ArrayList to transfer objects to the client.\n ArrayList arrayOfApplicationBags = new ArrayList();\n\n ServerManager serverManager = new ServerManager();\n ApplicationPoolCollection applicationPoolCollection = serverManager.ApplicationPools;\n foreach (ApplicationPool applicationPool in applicationPoolCollection)\n {\n PropertyBag applicationPoolBag = new PropertyBag();\n applicationPoolBag[ServerManagerDemoGlobals.ApplicationPoolArray] = applicationPool;\n arrayOfApplicationBags.Add(applicationPoolBag);\n // If the applicationPool is stopped, restart it.\n if (applicationPool.State == ObjectState.Stopped)\n {\n applicationPool.Start();\n }\n\n }\n\n // CommitChanges to persist the changes to the ApplicationHost.config.\n serverManager.CommitChanges();\n return arrayOfApplicationBags;\n}\n</code></pre>\n\n<p>If you're on <strong>IIS6</strong> I'm not so sure, but you could try getting the web.config and editing the modified date or something. Once an edit is made to the web.config then the application will restart.</p>\n" }, { "answer_id": 250043, "author": "alexandrul", "author_id": 19756, "author_profile": "https://Stackoverflow.com/users/19756", "pm_score": 3, "selected": false, "text": "<p>Maybe this articles will help:</p>\n\n<ul>\n<li><a href=\"http://web.archive.org/web/20140705173452/http://www.logue.com.ar/blog/2008/02/find-and-recycle-current-application-pool-programmatically-for-iis-6\" rel=\"nofollow noreferrer\">Recycle current Application Pool programmatically (for IIS 6+)</a></li>\n<li><a href=\"http://blogs.iis.net/chrisad/archive/2006/08/30/Recycling-Application-Pools-using-WMI-in-IIS-6.0.aspx\" rel=\"nofollow noreferrer\">Recycling Application Pools using WMI in IIS 6.0</a></li>\n<li><a href=\"http://www.codeproject.com/KB/aspnet/AppPoolRecycle.aspx\" rel=\"nofollow noreferrer\">Recycling IIS 6.0 application pools programmatically</a></li>\n<li><a href=\"http://web.archive.org/web/20130405055048/http://blog.developers.ie/cgreen/archive/2006/10/20/2341.aspx\" rel=\"nofollow noreferrer\">Programatically recycle an IIS application pool</a></li>\n</ul>\n" }, { "answer_id": 333380, "author": "Wolf5", "author_id": 37643, "author_profile": "https://Stackoverflow.com/users/37643", "pm_score": 3, "selected": false, "text": "<p>Recycle code working on IIS6:</p>\n\n<pre><code> /// &lt;summary&gt;\n /// Get a list of available Application Pools\n /// &lt;/summary&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public static List&lt;string&gt; HentAppPools() {\n\n List&lt;string&gt; list = new List&lt;string&gt;();\n DirectoryEntry W3SVC = new DirectoryEntry(\"IIS://LocalHost/w3svc\", \"\", \"\");\n\n foreach (DirectoryEntry Site in W3SVC.Children) {\n if (Site.Name == \"AppPools\") {\n foreach (DirectoryEntry child in Site.Children) {\n list.Add(child.Name);\n }\n }\n }\n return list;\n }\n\n /// &lt;summary&gt;\n /// Recycle an application pool\n /// &lt;/summary&gt;\n /// &lt;param name=\"IIsApplicationPool\"&gt;&lt;/param&gt;\n public static void RecycleAppPool(string IIsApplicationPool) {\n ManagementScope scope = new ManagementScope(@\"\\\\localhost\\root\\MicrosoftIISv2\");\n scope.Connect();\n ManagementObject appPool = new ManagementObject(scope, new ManagementPath(\"IIsApplicationPool.Name='W3SVC/AppPools/\" + IIsApplicationPool + \"'\"), null);\n\n appPool.InvokeMethod(\"Recycle\", null, null);\n }\n</code></pre>\n" }, { "answer_id": 496357, "author": "Ricardo Nolde", "author_id": 36272, "author_profile": "https://Stackoverflow.com/users/36272", "pm_score": 3, "selected": false, "text": "<p>The code below works on IIS6. Not tested in IIS7.</p>\n\n<pre><code>using System.DirectoryServices;\n\n...\n\nvoid Recycle(string appPool)\n{\n string appPoolPath = \"IIS://localhost/W3SVC/AppPools/\" + appPool;\n\n using (DirectoryEntry appPoolEntry = new DirectoryEntry(appPoolPath))\n {\n appPoolEntry.Invoke(\"Recycle\", null);\n appPoolEntry.Close();\n }\n}\n</code></pre>\n\n<p>You can change \"Recycle\" for \"Start\" or \"Stop\" also.</p>\n" }, { "answer_id": 1081902, "author": "Nathan Ridley", "author_id": 98389, "author_profile": "https://Stackoverflow.com/users/98389", "pm_score": 6, "selected": false, "text": "<p>Here we go:</p>\n\n<pre><code>HttpRuntime.UnloadAppDomain();\n</code></pre>\n" }, { "answer_id": 18585661, "author": "Simply G.", "author_id": 381122, "author_profile": "https://Stackoverflow.com/users/381122", "pm_score": 2, "selected": false, "text": "<p>Sometimes I feel that simple is best. And while I suggest that one adapts the actual path in some clever way to work on a wider way on other enviorments - my solution looks something like:</p>\n\n<pre><code>ExecuteDosCommand(@\"c:\\Windows\\System32\\inetsrv\\appcmd recycle apppool \" + appPool);\n</code></pre>\n\n<p>From C#, run a DOS command that does the trick. Many of the solutions above does not work on various settings and/or require features on Windows to be turned on (depending on setting).</p>\n" }, { "answer_id": 28553422, "author": "Spazmoose", "author_id": 312147, "author_profile": "https://Stackoverflow.com/users/312147", "pm_score": 3, "selected": false, "text": "<p>I went a slightly different route with my code to recycle the application pool. A few things to note that are different than what others have provided:</p>\n\n<p>1) I used a using statement to ensure proper disposal of the ServerManager object.</p>\n\n<p>2) I am waiting for the application pool to finish starting before stopping it, so that we don't run into any issues with trying to stop the application. Similarly, I am waiting for the app pool to finish stopping before trying to start it.</p>\n\n<p>3) I am forcing the method to accept an actual server name instead of falling back to the local server, because I figured you should probably know what server you are running this against.</p>\n\n<p>4) I decided to start/stop the application as opposed to recycling it, so that I could make sure that we didn't accidentally start an application pool that was stopped for another reason, and to avoid issues with trying to recycle an already stopped application pool.</p>\n\n<pre><code>public static void RecycleApplicationPool(string serverName, string appPoolName)\n{\n if (!string.IsNullOrEmpty(serverName) &amp;&amp; !string.IsNullOrEmpty(appPoolName))\n {\n try\n {\n using (ServerManager manager = ServerManager.OpenRemote(serverName))\n {\n ApplicationPool appPool = manager.ApplicationPools.FirstOrDefault(ap =&gt; ap.Name == appPoolName);\n\n //Don't bother trying to recycle if we don't have an app pool\n if (appPool != null)\n {\n //Get the current state of the app pool\n bool appPoolRunning = appPool.State == ObjectState.Started || appPool.State == ObjectState.Starting;\n bool appPoolStopped = appPool.State == ObjectState.Stopped || appPool.State == ObjectState.Stopping;\n\n //The app pool is running, so stop it first.\n if (appPoolRunning)\n {\n //Wait for the app to finish before trying to stop\n while (appPool.State == ObjectState.Starting) { System.Threading.Thread.Sleep(1000); }\n\n //Stop the app if it isn't already stopped\n if (appPool.State != ObjectState.Stopped)\n {\n appPool.Stop();\n }\n appPoolStopped = true;\n }\n\n //Only try restart the app pool if it was running in the first place, because there may be a reason it was not started.\n if (appPoolStopped &amp;&amp; appPoolRunning)\n {\n //Wait for the app to finish before trying to start\n while (appPool.State == ObjectState.Stopping) { System.Threading.Thread.Sleep(1000); }\n\n //Start the app\n appPool.Start();\n }\n }\n else\n {\n throw new Exception(string.Format(\"An Application Pool does not exist with the name {0}.{1}\", serverName, appPoolName));\n }\n }\n }\n catch (Exception ex)\n {\n throw new Exception(string.Format(\"Unable to restart the application pools for {0}.{1}\", serverName, appPoolName), ex.InnerException);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 34154221, "author": "Fred", "author_id": 1442180, "author_profile": "https://Stackoverflow.com/users/1442180", "pm_score": 2, "selected": false, "text": "<p>this code work for me. just call it to reload application.</p>\n\n<pre><code>System.Web.HttpRuntime.UnloadAppDomain()\n</code></pre>\n" }, { "answer_id": 53431386, "author": "Kaarthikeyan", "author_id": 2092251, "author_profile": "https://Stackoverflow.com/users/2092251", "pm_score": 3, "selected": false, "text": "<p>Below method is tested to be working for both IIS7 and IIS8</p>\n\n<p>Step 1 : Add reference to <strong>Microsoft.Web.Administration.dll</strong>. The file can be found in the path C:\\Windows\\System32\\inetsrv\\, or install it as NuGet Package <a href=\"https://www.nuget.org/packages/Microsoft.Web.Administration/\" rel=\"noreferrer\">https://www.nuget.org/packages/Microsoft.Web.Administration/</a></p>\n\n<p>Step 2 : Add the below code</p>\n\n<pre><code>using Microsoft.Web.Administration;\n</code></pre>\n\n<p><strong>Using Null-Conditional Operator</strong></p>\n\n<pre><code>new ServerManager().ApplicationPools[\"Your_App_Pool_Name\"]?.Recycle();\n</code></pre>\n\n<p><strong><em>OR</em></strong></p>\n\n<p><strong>Using if condition to check for null</strong></p>\n\n<pre><code>var yourAppPool=new ServerManager().ApplicationPools[\"Your_App_Pool_Name\"];\nif(yourAppPool!=null)\n yourAppPool.Recycle();\n</code></pre>\n" }, { "answer_id": 57077950, "author": "Alex from Jitbit", "author_id": 56621, "author_profile": "https://Stackoverflow.com/users/56621", "pm_score": 0, "selected": false, "text": "<p>Another option:</p>\n\n<pre><code>System.Web.Hosting.HostingEnvironment.InitiateShutdown();\n</code></pre>\n\n<p>Seems better than <code>UploadAppDomain</code> which \"terminates\" the app while the former waits for stuff to finish its work.</p>\n" }, { "answer_id": 72033862, "author": "phillhutt", "author_id": 2585195, "author_profile": "https://Stackoverflow.com/users/2585195", "pm_score": 0, "selected": false, "text": "<p>Here is a simple solution if you just want to recycle all the app pools on the current machine. I had to &quot;run as administrator&quot; for this to work.</p>\n<pre><code>using (var serverManager = new ServerManager())\n{\n foreach (var appPool in serverManager.ApplicationPools)\n {\n appPool.Recycle();\n }\n}\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How can I restart(recycle) IIS Application Pool from C# (.net 2)? Appreciate if you post sample code?
If you're on **IIS7** then this will do it if it is stopped. I assume you can adjust for restarting without having to be shown. ``` // Gets the application pool collection from the server. [ModuleServiceMethod(PassThrough = true)] public ArrayList GetApplicationPoolCollection() { // Use an ArrayList to transfer objects to the client. ArrayList arrayOfApplicationBags = new ArrayList(); ServerManager serverManager = new ServerManager(); ApplicationPoolCollection applicationPoolCollection = serverManager.ApplicationPools; foreach (ApplicationPool applicationPool in applicationPoolCollection) { PropertyBag applicationPoolBag = new PropertyBag(); applicationPoolBag[ServerManagerDemoGlobals.ApplicationPoolArray] = applicationPool; arrayOfApplicationBags.Add(applicationPoolBag); // If the applicationPool is stopped, restart it. if (applicationPool.State == ObjectState.Stopped) { applicationPool.Start(); } } // CommitChanges to persist the changes to the ApplicationHost.config. serverManager.CommitChanges(); return arrayOfApplicationBags; } ``` If you're on **IIS6** I'm not so sure, but you could try getting the web.config and editing the modified date or something. Once an edit is made to the web.config then the application will restart.
249,968
<p>I have written a web app in PHP which makes use of Ajax requests (made using YUI.util.Connect.asyncRequest).</p> <p>Most of the time, this works fine. The request is sent with an <strong>X-Requested-With</strong> value of <strong>XMLHttpRequest</strong>. My PHP controller code uses apache_request_headers() to check whether an incoming request is Ajax or not and all works well.</p> <p>But not always. Intermittently, I'm getting a situation where the Ajax request is sent (and Firebug confirms for me that the headers on the request include an X-Requested-With of XMLHttpRequest) but apache_request_headers() is not returning that header in its list.</p> <p>The output from when I var_dump the apache_request_headers() is as follows (note the lack of X-</p> <pre><code>'Host' =&gt; string 'peterh.labs.example.com' (length=26) 'User-Agent' =&gt; string 'Mozilla/5.0 (X11; U; Linux i686; en-GB; rv:1.9.0.3) Gecko/2008101315 Ubuntu/8.10 (intrepid) Firefox/3.0.3' (length=105) 'Accept' =&gt; string 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' (length=63) 'Accept-Language' =&gt; string 'en-gb,en;q=0.5' (length=14) 'Accept-Encoding' =&gt; string 'gzip,deflate' (length=12) 'Accept-Charset' =&gt; string 'ISO-8859-1,utf-8;q=0.7,*;q=0.7' (length=30) 'Keep-Alive' =&gt; string '300' (length=3) 'Connection' =&gt; string 'keep-alive' (length=10) 'Referer' =&gt; string 'http://peterh.labs.example.com/qmail/' (length=40) 'Cookie' =&gt; string 'WORKFLOW_SESSION=55f9aff2051746851de453c1f776ad10745354f6' (length=57) 'Pragma' =&gt; string 'no-cache' (length=8) 'Cache-Control' =&gt; string 'no-cache' (length=8) </code></pre> <p>But Firebug tells me:</p> <pre><code>Request Headers: Host peterh.labs.example.com User-Agent Mozilla/5.0 (X11; U; Linux i686; en-GB; rv:1.9.0.3) Gecko/2008101315 Ubuntu/8.10 (intrepid) Firefox/3.0.3 Accept text/html,application/xhtml+xml,application/xml;q=0.9,**;q=0.8 Accept-Language en-gb,en;q=0.5 Accept-Encoding gzip,deflate Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive 300 Connection keep-alive X-Requested-With XMLHttpRequest Referer http://peterh.labs.example.com/qmail/ Cookie WORKFLOW_SESSION=55f9aff2051746851de453c1f776ad10745354f6 </code></pre> <p>This mismatch is (apparently) intermittent when executing the same code. But I don't believe in "intermittent" when it comes to software! Help!</p>
[ { "answer_id": 250242, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 0, "selected": false, "text": "<p>Double-check that the missing header is not in the superglobal <code>$_SERVER</code>. In general, I wouldn't rely on apache_* if I really had to.</p>\n\n<p>On a side-note, is X-Requested-With the standard yet? I've read about various libraries adding it, but I didn't know that it became the standard yet.</p>\n" }, { "answer_id": 250246, "author": "user27987", "author_id": 27987, "author_profile": "https://Stackoverflow.com/users/27987", "pm_score": 4, "selected": true, "text": "<p>I'm not sure why the apache_request_headers() and firebug mismatching, but in order to read request headers you can use the $_SERVER super global</p>\n\n<p>each header that is being sent by a client (and it doesn't matter how is the client) will arrive to the $<em>SERVER array.\nThe key of that header will be with HTTP</em> prefix, all letters capital and dash is converted to underscore (_)</p>\n\n<p>in your case you can find your necessary value in:</p>\n\n<p>$_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'</p>\n" }, { "answer_id": 250287, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 0, "selected": false, "text": "<p>I can't specifically answer this case, but in general I'd recommend using a (query) parameter to signal xmlhttp requests, instead of a header. You never know what funny security or proxy server might take it upon itself to fiddle with HTTP headers, or to cache an AJAX response that should have been a plain browser HTML response (or vice-versa).</p>\n" }, { "answer_id": 2509887, "author": "pnomolos", "author_id": 262092, "author_profile": "https://Stackoverflow.com/users/262092", "pm_score": 1, "selected": false, "text": "<p>For future reference of those coming across this question, the \"intermittent\" may be due to a redirect happening server-side. If a 302 redirect occurs the X-Requested-With header isn't passed along even though it's been sent in the original request. This may have been the original cause of the problem.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24106/" ]
I have written a web app in PHP which makes use of Ajax requests (made using YUI.util.Connect.asyncRequest). Most of the time, this works fine. The request is sent with an **X-Requested-With** value of **XMLHttpRequest**. My PHP controller code uses apache\_request\_headers() to check whether an incoming request is Ajax or not and all works well. But not always. Intermittently, I'm getting a situation where the Ajax request is sent (and Firebug confirms for me that the headers on the request include an X-Requested-With of XMLHttpRequest) but apache\_request\_headers() is not returning that header in its list. The output from when I var\_dump the apache\_request\_headers() is as follows (note the lack of X- ``` 'Host' => string 'peterh.labs.example.com' (length=26) 'User-Agent' => string 'Mozilla/5.0 (X11; U; Linux i686; en-GB; rv:1.9.0.3) Gecko/2008101315 Ubuntu/8.10 (intrepid) Firefox/3.0.3' (length=105) 'Accept' => string 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' (length=63) 'Accept-Language' => string 'en-gb,en;q=0.5' (length=14) 'Accept-Encoding' => string 'gzip,deflate' (length=12) 'Accept-Charset' => string 'ISO-8859-1,utf-8;q=0.7,*;q=0.7' (length=30) 'Keep-Alive' => string '300' (length=3) 'Connection' => string 'keep-alive' (length=10) 'Referer' => string 'http://peterh.labs.example.com/qmail/' (length=40) 'Cookie' => string 'WORKFLOW_SESSION=55f9aff2051746851de453c1f776ad10745354f6' (length=57) 'Pragma' => string 'no-cache' (length=8) 'Cache-Control' => string 'no-cache' (length=8) ``` But Firebug tells me: ``` Request Headers: Host peterh.labs.example.com User-Agent Mozilla/5.0 (X11; U; Linux i686; en-GB; rv:1.9.0.3) Gecko/2008101315 Ubuntu/8.10 (intrepid) Firefox/3.0.3 Accept text/html,application/xhtml+xml,application/xml;q=0.9,**;q=0.8 Accept-Language en-gb,en;q=0.5 Accept-Encoding gzip,deflate Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive 300 Connection keep-alive X-Requested-With XMLHttpRequest Referer http://peterh.labs.example.com/qmail/ Cookie WORKFLOW_SESSION=55f9aff2051746851de453c1f776ad10745354f6 ``` This mismatch is (apparently) intermittent when executing the same code. But I don't believe in "intermittent" when it comes to software! Help!
I'm not sure why the apache\_request\_headers() and firebug mismatching, but in order to read request headers you can use the $\_SERVER super global each header that is being sent by a client (and it doesn't matter how is the client) will arrive to the $*SERVER array. The key of that header will be with HTTP* prefix, all letters capital and dash is converted to underscore (\_) in your case you can find your necessary value in: $\_SERVER['HTTP\_X\_REQUESTED\_WITH'] = 'XMLHttpRequest'
249,971
<p>Having some Geometry data and a Transform how can the transform be applied to the Geometry to get a new Geometry with it's data transformed ?</p> <p>Ex: I Have a Path object that has it's Path.Data set to a PathGeometry object, I want to tranform <strong>the points</strong> of the PathGeometry object <strong>in place</strong> using a transform, and not apply a transform to the PathGeometry that will be used at render time.</p> <p>P.S. I know that the Transform class has a method <code>Point Transform.Transform(Point p)</code> that can be used to transform a Point but...is there a way to transform a arbitrary geometry at once?</p> <p>Edit: See my repply for a currently found <a href="https://stackoverflow.com/questions/249971/wpf-how-to-apply-a-generaltransform-to-a-geometry-data-and-return-the-new-geome#250913">solution</a></p>
[ { "answer_id": 250028, "author": "Nir", "author_id": 3509, "author_profile": "https://Stackoverflow.com/users/3509", "pm_score": -1, "selected": false, "text": "<p>There are two things you have to consider:</p>\n\n<ol>\n<li>Geometry inherits from Freezable, you can't modify the geometry object in-place if it's frozen.</li>\n<li>You can scan the PathGeometry list of figures and segments and transform all the points in them but some types, like ArcSegment includes sizes and angles, you can't transform them.</li>\n</ol>\n" }, { "answer_id": 250253, "author": "cplotts", "author_id": 22294, "author_profile": "https://Stackoverflow.com/users/22294", "pm_score": 0, "selected": false, "text": "<p>Unfortunately, I don't think there is a method or property to do what you are asking. At least, I can't find one. (Great question!)</p>\n\n<p>It seems like you would have to do it manually (as you suggest yourself) ... that is call <strong>Point Transform.Transform(Point p)</strong> for every point in your PathGeometry ... creating a new PathGeometry in the process.</p>\n\n<p>Probably isn't the answer you want. <em>(Rueful Grin)</em></p>\n" }, { "answer_id": 250587, "author": "Todd White", "author_id": 30833, "author_profile": "https://Stackoverflow.com/users/30833", "pm_score": 5, "selected": true, "text": "<p>You could try and use Geometry.Combine. It applies a transform during the combine. One catch is that Combine only works if your Geometry has area, so single lines will not work.</p>\n\n<p>Here is a sample that worked for me.</p>\n\n<pre><code>PathGeometry geometry = new PathGeometry();\ngeometry.Figures.Add(new PathFigure(new Point(10, 10), new PathSegment[] { new LineSegment(new Point(10, 20), true), new LineSegment(new Point(20, 20), true) }, true));\nScaleTransform transform = new ScaleTransform(2, 2);\nPathGeometry geometryTransformed = Geometry.Combine(geometry, geometry, GeometryCombineMode.Intersect, transform);\n</code></pre>\n" }, { "answer_id": 250913, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 4, "selected": false, "text": "<p>I've found a solution with which arbitrary tranform can be applied to a path geometry, thanks to <a href=\"https://stackoverflow.com/questions/249971/wpf-how-to-apply-a-generaltransform-to-a-geometry-data-and-return-the-new-geome#250587\">Todd White</a>'s answer: </p>\n\n<p>Basically Geometry.Combine is used to combine the desired geometry with Geometry.Empty using Union, and the desired transform is given. The resulting geometry is transformed with the given transform. </p>\n\n<pre><code>PathGeometry geometryTransformed = Geometry.Combine(Geometry.Empty, geometry, GeometryCombineMode.Union, transform);\n</code></pre>\n" }, { "answer_id": 1504510, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I've had the same problem AND need lines as well (not only geometries with area).</p>\n\n<p>I'm only using PathGeometry, so this may not be the general solution you are looking for, but this worked for me:</p>\n\n<pre><code>pathgeometry.Transform = transform;\nPathGeometry transformed = PathGeometry.CreateFromGeometry(pathgeometry);\n</code></pre>\n" }, { "answer_id": 7515015, "author": "Snowbear", "author_id": 570357, "author_profile": "https://Stackoverflow.com/users/570357", "pm_score": 2, "selected": false, "text": "<p>I didn't use accepted answer since it was returning geometry in format different from the original one, so I used this: </p>\n\n<pre><code>Geometry inputGeometry = new PathGeometry();\nvar inputGeometryClone = inputGeometry.Clone(); // we need a clone since in order to\n // apply a Transform and geometry might be readonly\ninputGeometryClone.Transform = new TranslateTransform(); // applying some transform to it\nvar result = inputGeometryClone.GetFlattenedPathGeometry();\n</code></pre>\n" }, { "answer_id": 13960034, "author": "Curtis", "author_id": 981187, "author_profile": "https://Stackoverflow.com/users/981187", "pm_score": 3, "selected": false, "text": "<p>This is what I found you can do to get a transformed geometry with all of the figure information intact:</p>\n\n<pre><code>var geometry = new PathGeometry();\ngeometry.Figures.Add(new PathFigure(new Point(10, 10), new PathSegment[] { new LineSegment(new Point(10, 20), true), new LineSegment(new Point(20, 20), true) }, true));\ngeometry.Transform = new ScaleTransform(2, 2);\n\nvar transformedGeometry = new PathGeometry ();\n// this copies the transformed figures one by one into the new geometry\ntransformedGeometry.AddGeometry (geometry); \n</code></pre>\n" }, { "answer_id": 27507885, "author": "rpaulin56", "author_id": 2794352, "author_profile": "https://Stackoverflow.com/users/2794352", "pm_score": 2, "selected": false, "text": "<p>None of the quick solutions based on Geometry.Combine works in the case of path made of a single LineElement.\nSo I solved the problem the hard way, like this (But I am also limited to PathGeometry):</p>\n\n<pre><code>public static class GeometryHelper\n{\npublic static PointCollection TransformPoints(PointCollection pc, Transform t)\n{\n PointCollection tp = new PointCollection(pc.Count);\n foreach (Point p in pc)\n tp.Add(t.Transform(p));\n return tp;\n}\npublic static PathGeometry TransformedGeometry(PathGeometry g, Transform t)\n{\n Matrix m = t.Value;\n double scaleX = Math.Sqrt(m.M11 * m.M11 + m.M21 * m.M21);\n double scaleY = (m.M11 * m.M22 - m.M12 * m.M21) / scaleX;\n PathGeometry ng = g.Clone();\n foreach (PathFigure f in ng.Figures)\n {\n f.StartPoint = t.Transform(f.StartPoint);\n foreach (PathSegment s in f.Segments)\n {\n if (s is LineSegment)\n (s as LineSegment).Point = t.Transform((s as LineSegment).Point);\n else if (s is PolyLineSegment)\n (s as PolyLineSegment).Points = TransformPoints((s as PolyLineSegment).Points, t);\n else if (s is BezierSegment)\n {\n (s as BezierSegment).Point1 = t.Transform((s as BezierSegment).Point1);\n (s as BezierSegment).Point2 = t.Transform((s as BezierSegment).Point2);\n (s as BezierSegment).Point3 = t.Transform((s as BezierSegment).Point3);\n }\n else if (s is PolyBezierSegment)\n (s as PolyBezierSegment).Points = TransformPoints((s as PolyBezierSegment).Points, t);\n else if (s is QuadraticBezierSegment)\n {\n (s as QuadraticBezierSegment).Point1 = t.Transform((s as QuadraticBezierSegment).Point1);\n (s as QuadraticBezierSegment).Point2 = t.Transform((s as QuadraticBezierSegment).Point2);\n }\n else if (s is PolyQuadraticBezierSegment)\n (s as PolyQuadraticBezierSegment).Points = TransformPoints((s as PolyQuadraticBezierSegment).Points, t);\n else if (s is ArcSegment)\n {\n ArcSegment a = s as ArcSegment;\n a.Point = t.Transform(a.Point);\n a.Size = new Size(a.Size.Width * scaleX, a.Size.Height * scaleY); // NEVER TRIED\n }\n }\n }\n return ng;\n}\n}\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4685/" ]
Having some Geometry data and a Transform how can the transform be applied to the Geometry to get a new Geometry with it's data transformed ? Ex: I Have a Path object that has it's Path.Data set to a PathGeometry object, I want to tranform **the points** of the PathGeometry object **in place** using a transform, and not apply a transform to the PathGeometry that will be used at render time. P.S. I know that the Transform class has a method `Point Transform.Transform(Point p)` that can be used to transform a Point but...is there a way to transform a arbitrary geometry at once? Edit: See my repply for a currently found [solution](https://stackoverflow.com/questions/249971/wpf-how-to-apply-a-generaltransform-to-a-geometry-data-and-return-the-new-geome#250913)
You could try and use Geometry.Combine. It applies a transform during the combine. One catch is that Combine only works if your Geometry has area, so single lines will not work. Here is a sample that worked for me. ``` PathGeometry geometry = new PathGeometry(); geometry.Figures.Add(new PathFigure(new Point(10, 10), new PathSegment[] { new LineSegment(new Point(10, 20), true), new LineSegment(new Point(20, 20), true) }, true)); ScaleTransform transform = new ScaleTransform(2, 2); PathGeometry geometryTransformed = Geometry.Combine(geometry, geometry, GeometryCombineMode.Intersect, transform); ```
249,979
<p>In the below code snippet can i replace char * to const char * and remove the strdup() function call and directly take the optarg value set by getopt()? I am advised to use const char * to skip the strdup function usage. Appreciate the help in advance.</p> <pre><code>/* Code Snippet */ char *dir = NULL; char *bld = NULL; int chr; while ( ( chr = getopt( argc, argv, "d:a:b:f:" ) ) != -1 ) { switch ( chr ) { case 'd': //Directory parameter dir = strdup( optarg ); if (dir == NULL) { /*Error*/ } case 'b': //Build parameter bld = strdup( optarg ); if (bld == NULL) { /*Error*/ } ...other code... } } </code></pre> <p>I really don't understand the need for doing so.</p> <p>Edit: Thanks for the answers. It was really helpful. I modified the code to const char * and skipped the strdup call.</p> <p>Thanks, Liju</p>
[ { "answer_id": 250028, "author": "Nir", "author_id": 3509, "author_profile": "https://Stackoverflow.com/users/3509", "pm_score": -1, "selected": false, "text": "<p>There are two things you have to consider:</p>\n\n<ol>\n<li>Geometry inherits from Freezable, you can't modify the geometry object in-place if it's frozen.</li>\n<li>You can scan the PathGeometry list of figures and segments and transform all the points in them but some types, like ArcSegment includes sizes and angles, you can't transform them.</li>\n</ol>\n" }, { "answer_id": 250253, "author": "cplotts", "author_id": 22294, "author_profile": "https://Stackoverflow.com/users/22294", "pm_score": 0, "selected": false, "text": "<p>Unfortunately, I don't think there is a method or property to do what you are asking. At least, I can't find one. (Great question!)</p>\n\n<p>It seems like you would have to do it manually (as you suggest yourself) ... that is call <strong>Point Transform.Transform(Point p)</strong> for every point in your PathGeometry ... creating a new PathGeometry in the process.</p>\n\n<p>Probably isn't the answer you want. <em>(Rueful Grin)</em></p>\n" }, { "answer_id": 250587, "author": "Todd White", "author_id": 30833, "author_profile": "https://Stackoverflow.com/users/30833", "pm_score": 5, "selected": true, "text": "<p>You could try and use Geometry.Combine. It applies a transform during the combine. One catch is that Combine only works if your Geometry has area, so single lines will not work.</p>\n\n<p>Here is a sample that worked for me.</p>\n\n<pre><code>PathGeometry geometry = new PathGeometry();\ngeometry.Figures.Add(new PathFigure(new Point(10, 10), new PathSegment[] { new LineSegment(new Point(10, 20), true), new LineSegment(new Point(20, 20), true) }, true));\nScaleTransform transform = new ScaleTransform(2, 2);\nPathGeometry geometryTransformed = Geometry.Combine(geometry, geometry, GeometryCombineMode.Intersect, transform);\n</code></pre>\n" }, { "answer_id": 250913, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 4, "selected": false, "text": "<p>I've found a solution with which arbitrary tranform can be applied to a path geometry, thanks to <a href=\"https://stackoverflow.com/questions/249971/wpf-how-to-apply-a-generaltransform-to-a-geometry-data-and-return-the-new-geome#250587\">Todd White</a>'s answer: </p>\n\n<p>Basically Geometry.Combine is used to combine the desired geometry with Geometry.Empty using Union, and the desired transform is given. The resulting geometry is transformed with the given transform. </p>\n\n<pre><code>PathGeometry geometryTransformed = Geometry.Combine(Geometry.Empty, geometry, GeometryCombineMode.Union, transform);\n</code></pre>\n" }, { "answer_id": 1504510, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I've had the same problem AND need lines as well (not only geometries with area).</p>\n\n<p>I'm only using PathGeometry, so this may not be the general solution you are looking for, but this worked for me:</p>\n\n<pre><code>pathgeometry.Transform = transform;\nPathGeometry transformed = PathGeometry.CreateFromGeometry(pathgeometry);\n</code></pre>\n" }, { "answer_id": 7515015, "author": "Snowbear", "author_id": 570357, "author_profile": "https://Stackoverflow.com/users/570357", "pm_score": 2, "selected": false, "text": "<p>I didn't use accepted answer since it was returning geometry in format different from the original one, so I used this: </p>\n\n<pre><code>Geometry inputGeometry = new PathGeometry();\nvar inputGeometryClone = inputGeometry.Clone(); // we need a clone since in order to\n // apply a Transform and geometry might be readonly\ninputGeometryClone.Transform = new TranslateTransform(); // applying some transform to it\nvar result = inputGeometryClone.GetFlattenedPathGeometry();\n</code></pre>\n" }, { "answer_id": 13960034, "author": "Curtis", "author_id": 981187, "author_profile": "https://Stackoverflow.com/users/981187", "pm_score": 3, "selected": false, "text": "<p>This is what I found you can do to get a transformed geometry with all of the figure information intact:</p>\n\n<pre><code>var geometry = new PathGeometry();\ngeometry.Figures.Add(new PathFigure(new Point(10, 10), new PathSegment[] { new LineSegment(new Point(10, 20), true), new LineSegment(new Point(20, 20), true) }, true));\ngeometry.Transform = new ScaleTransform(2, 2);\n\nvar transformedGeometry = new PathGeometry ();\n// this copies the transformed figures one by one into the new geometry\ntransformedGeometry.AddGeometry (geometry); \n</code></pre>\n" }, { "answer_id": 27507885, "author": "rpaulin56", "author_id": 2794352, "author_profile": "https://Stackoverflow.com/users/2794352", "pm_score": 2, "selected": false, "text": "<p>None of the quick solutions based on Geometry.Combine works in the case of path made of a single LineElement.\nSo I solved the problem the hard way, like this (But I am also limited to PathGeometry):</p>\n\n<pre><code>public static class GeometryHelper\n{\npublic static PointCollection TransformPoints(PointCollection pc, Transform t)\n{\n PointCollection tp = new PointCollection(pc.Count);\n foreach (Point p in pc)\n tp.Add(t.Transform(p));\n return tp;\n}\npublic static PathGeometry TransformedGeometry(PathGeometry g, Transform t)\n{\n Matrix m = t.Value;\n double scaleX = Math.Sqrt(m.M11 * m.M11 + m.M21 * m.M21);\n double scaleY = (m.M11 * m.M22 - m.M12 * m.M21) / scaleX;\n PathGeometry ng = g.Clone();\n foreach (PathFigure f in ng.Figures)\n {\n f.StartPoint = t.Transform(f.StartPoint);\n foreach (PathSegment s in f.Segments)\n {\n if (s is LineSegment)\n (s as LineSegment).Point = t.Transform((s as LineSegment).Point);\n else if (s is PolyLineSegment)\n (s as PolyLineSegment).Points = TransformPoints((s as PolyLineSegment).Points, t);\n else if (s is BezierSegment)\n {\n (s as BezierSegment).Point1 = t.Transform((s as BezierSegment).Point1);\n (s as BezierSegment).Point2 = t.Transform((s as BezierSegment).Point2);\n (s as BezierSegment).Point3 = t.Transform((s as BezierSegment).Point3);\n }\n else if (s is PolyBezierSegment)\n (s as PolyBezierSegment).Points = TransformPoints((s as PolyBezierSegment).Points, t);\n else if (s is QuadraticBezierSegment)\n {\n (s as QuadraticBezierSegment).Point1 = t.Transform((s as QuadraticBezierSegment).Point1);\n (s as QuadraticBezierSegment).Point2 = t.Transform((s as QuadraticBezierSegment).Point2);\n }\n else if (s is PolyQuadraticBezierSegment)\n (s as PolyQuadraticBezierSegment).Points = TransformPoints((s as PolyQuadraticBezierSegment).Points, t);\n else if (s is ArcSegment)\n {\n ArcSegment a = s as ArcSegment;\n a.Point = t.Transform(a.Point);\n a.Size = new Size(a.Size.Width * scaleX, a.Size.Height * scaleY); // NEVER TRIED\n }\n }\n }\n return ng;\n}\n}\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18657/" ]
In the below code snippet can i replace char \* to const char \* and remove the strdup() function call and directly take the optarg value set by getopt()? I am advised to use const char \* to skip the strdup function usage. Appreciate the help in advance. ``` /* Code Snippet */ char *dir = NULL; char *bld = NULL; int chr; while ( ( chr = getopt( argc, argv, "d:a:b:f:" ) ) != -1 ) { switch ( chr ) { case 'd': //Directory parameter dir = strdup( optarg ); if (dir == NULL) { /*Error*/ } case 'b': //Build parameter bld = strdup( optarg ); if (bld == NULL) { /*Error*/ } ...other code... } } ``` I really don't understand the need for doing so. Edit: Thanks for the answers. It was really helpful. I modified the code to const char \* and skipped the strdup call. Thanks, Liju
You could try and use Geometry.Combine. It applies a transform during the combine. One catch is that Combine only works if your Geometry has area, so single lines will not work. Here is a sample that worked for me. ``` PathGeometry geometry = new PathGeometry(); geometry.Figures.Add(new PathFigure(new Point(10, 10), new PathSegment[] { new LineSegment(new Point(10, 20), true), new LineSegment(new Point(20, 20), true) }, true)); ScaleTransform transform = new ScaleTransform(2, 2); PathGeometry geometryTransformed = Geometry.Combine(geometry, geometry, GeometryCombineMode.Intersect, transform); ```
249,991
<p>I am trying to read a custom (non-standard) CSS property, set in a stylesheet (not the inline style attribute) and get its value. Take this CSS for example:</p> <pre><code>#someElement { foo: 'bar'; } </code></pre> <p>I have managed to get its value with the currentStyle property in IE7:</p> <pre><code>var element = document.getElementById('someElement'); var val = element.currentStyle.foo; </code></pre> <p>But currentStyle is MS-specific. So I tried getComputedStyle() in Firefox 3 and Safari 3:</p> <pre><code>var val = getComputedStyle(element,null).foo; </code></pre> <p>...and it returns undefined. <strong>Does anyone know a cross-browser way of retreiving a custom CSS property value?</strong></p> <p><em>(As you might have noticed, this isn't valid CSS. But it should work as long as the value follows the correct syntax. A better property name would be "-myNameSpace-foo" or something.)</em></p>
[ { "answer_id": 250140, "author": "Chase Seibert", "author_id": 7679, "author_profile": "https://Stackoverflow.com/users/7679", "pm_score": 4, "selected": true, "text": "<p>Firefox does not carry over tags, attributes or CSS styles it does not understand from the code to the DOM. That is by design. Javascript only has access to the DOM, not the code. So no, there is no way to access a property from javascript that the browser itself does not support.</p>\n" }, { "answer_id": 265566, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 2, "selected": false, "text": "<p>By reading in the Stylesheet info in IE, you CAN get these \"bogus\" properties, but only in IE that I'm aware of.</p>\n\n<pre><code>var firstSS = document.styleSheets[0];\nvar firstSSRule = firstSS.rules[0];\nif(typeof(firstSSRule.style.bar) != 'undefined'){\n alert('value of [foo] is: ' + firstSSRule.style.bar);\n} else {\n alert('does not have [foo] property');\n}\n</code></pre>\n\n<p>Its ugly code, but you get the picture.</p>\n" }, { "answer_id": 330507, "author": "joolss", "author_id": 27741, "author_profile": "https://Stackoverflow.com/users/27741", "pm_score": 2, "selected": false, "text": "<p>One way would of course be to write your own CSS-parser in Javascript. But I believe that is <em>really</em> over the top.</p>\n" }, { "answer_id": 545471, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I too have some pages that work wonderfully in MSIE, but have lots of info in styles and style sheets. So I'm thinking about workarounds. One thing Firefox does allow, mercifully, is putting inline attributes into the DOM. So here's a partial strategy: </p>\n\n<ol>\n<li><p>Replace each inline style in the html document with a corresponding \"nStyle\", e.g., \n&lt;span class=\"cls1\" nStyle=\"color:red; nref:#myid; foo:bar\"> ... &lt;/span></p></li>\n<li><p>When the page is loaded, do the following with each element node: (a) copy the value of the nStyle attribute into the tag's cssText, and at the same time (b) convert the nonstandard attributes into an easier format, so that, e.g., node.getAttribute('nStyle') becomes the object {\"nref\":\"#myid\", \"foo\":\"bar\"}.</p></li>\n<li><p>Write a \"calculatedStyle\" function that gets either the style or the nStyle, depending on what's available.</p></li>\n</ol>\n\n<p>Writing a rough parser for style sheets might enable a similar strategy for them, but I have a question: How do I get over the hurdle of reading the style sheet without censorship from Firefox?</p>\n" }, { "answer_id": 11599944, "author": "Esailija", "author_id": 995876, "author_profile": "https://Stackoverflow.com/users/995876", "pm_score": 4, "selected": false, "text": "<p>Modern browsers will just throw away any invalid css. However, you can use the content property since it only has effect with\n<code>:after</code>, <code>:before</code> etc. You can store JSON inside it:</p>\n\n<pre><code>#someElement {\n content: '{\"foo\": \"bar\"}';\n}\n</code></pre>\n\n<p>Then use code like this to retrieve it:</p>\n\n<pre><code>var CSSMetaData = function() {\n\n function trimQuotes( str ) {\n return str.replace( /^['\"]/, \"\" ).replace( /[\"']$/, \"\" ); \n }\n\n function fixFirefoxEscape( str ) {\n return str.replace( /\\\\\"/g, '\"' );\n }\n\n var forEach = [].forEach,\n div = document.createElement(\"div\"),\n matchesSelector = div.webkitMatchesSelector ||\n div.mozMatchesSelector ||\n div.msMatchesSelector ||\n div.oMatchesSelector ||\n div.matchesSelector,\n data = {};\n\n forEach.call( document.styleSheets, function( styleSheet ) {\n forEach.call( styleSheet.cssRules, function( rule ) {\n var content = rule.style.getPropertyValue( \"content\" ),\n obj;\n\n if( content ) {\n content = trimQuotes(content);\n try {\n obj = JSON.parse( content );\n }\n catch(e) {\n try {\n\n obj = JSON.parse( fixFirefoxEscape( content ) );\n }\n catch(e2) {\n return ;\n }\n\n }\n data[rule.selectorText] = obj;\n }\n });\n\n });\n\n\n return {\n\n getDataByElement: function( elem ) {\n var storedData;\n for( var selector in data ) {\n if( matchesSelector.call( elem, selector ) ) {\n storedData = data[selector];\n if( storedData ) return storedData;\n\n }\n }\n\n return null;\n }\n };\n\n}();\nvar obj = CSSMetaData.getDataByElement( document.getElementById(\"someElement\"));\nconsole.log( obj.foo ); //bar\n</code></pre>\n\n<p>Note, this is only for modern browsers. Demo: <a href=\"http://jsfiddle.net/xFjZp/3/\">http://jsfiddle.net/xFjZp/3/</a></p>\n" }, { "answer_id": 11654894, "author": "Miljan Puzović", "author_id": 1550040, "author_profile": "https://Stackoverflow.com/users/1550040", "pm_score": -1, "selected": false, "text": "<p>Maybe you can try with <a href=\"http://lesscss.org/\" rel=\"nofollow\">LESS</a>. It's The Dynamic Stylesheet language and you can create non-standard css attributes, commands that will compile later.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27741/" ]
I am trying to read a custom (non-standard) CSS property, set in a stylesheet (not the inline style attribute) and get its value. Take this CSS for example: ``` #someElement { foo: 'bar'; } ``` I have managed to get its value with the currentStyle property in IE7: ``` var element = document.getElementById('someElement'); var val = element.currentStyle.foo; ``` But currentStyle is MS-specific. So I tried getComputedStyle() in Firefox 3 and Safari 3: ``` var val = getComputedStyle(element,null).foo; ``` ...and it returns undefined. **Does anyone know a cross-browser way of retreiving a custom CSS property value?** *(As you might have noticed, this isn't valid CSS. But it should work as long as the value follows the correct syntax. A better property name would be "-myNameSpace-foo" or something.)*
Firefox does not carry over tags, attributes or CSS styles it does not understand from the code to the DOM. That is by design. Javascript only has access to the DOM, not the code. So no, there is no way to access a property from javascript that the browser itself does not support.
249,994
<p>I have a dump of a windows service i made. The exception is that my code can't move a file (for some reason). Now, in my code there's a number of places where i move files around the filesystem. So, using Windbg, i'm trying to see the code where the exception occurs.</p> <p>here's my !clrstack dump..</p> <pre><code>0:016&gt; !clrstack -p OS Thread Id: 0xdf8 (16) Child-SP RetAddr Call Site 0000000019edea70 0000064278a15e4f System.IO.__Error.WinIOError(Int32, System.String) PARAMETERS: errorCode = &lt;no data&gt; maybeFullPath = &lt;no data&gt; 0000000019edead0 0000064280181ce5 System.IO.File.Move(System.String, System.String) PARAMETERS: sourceFileName = &lt;no data&gt; destFileName = &lt;no data&gt; 0000000019edeb50 0000064280196532 MyClass.Foo.DoSomeStuffInHere(System.String) PARAMETERS: this = 0x0000000000c30aa8 filePathAndName = 0x0000000000d1aad0 </code></pre> <p>now, this helps a lot...</p> <pre><code>0:016&gt; !do 0x0000000000d1aad0 Name: System.String MethodTable: 00000642784365e8 EEClass: 000006427803e4f0 Size: 88(0x58) bytes (C:\WINDOWS\assembly\GAC_64\mscorlib\2.0.0.0__b77a5c561934e089\mscorlib.dll) String: C:\BlahBlahFolder\FooFolder\4469.jpg Fields: -snipped- </code></pre> <p>So i've figured out the file which failed to be moved. kewl. But i just want to see the code in this method MyClass.Foo.DoSomeStuffInHere(System.String) which calls File.Move(..). That method has lots of File.Move .. so i could put try / catches / debug / trace information .. but i'm hoping to be more efficient by using Windbg to help find this problem.</p> <p>Any thoughts?</p>
[ { "answer_id": 250140, "author": "Chase Seibert", "author_id": 7679, "author_profile": "https://Stackoverflow.com/users/7679", "pm_score": 4, "selected": true, "text": "<p>Firefox does not carry over tags, attributes or CSS styles it does not understand from the code to the DOM. That is by design. Javascript only has access to the DOM, not the code. So no, there is no way to access a property from javascript that the browser itself does not support.</p>\n" }, { "answer_id": 265566, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 2, "selected": false, "text": "<p>By reading in the Stylesheet info in IE, you CAN get these \"bogus\" properties, but only in IE that I'm aware of.</p>\n\n<pre><code>var firstSS = document.styleSheets[0];\nvar firstSSRule = firstSS.rules[0];\nif(typeof(firstSSRule.style.bar) != 'undefined'){\n alert('value of [foo] is: ' + firstSSRule.style.bar);\n} else {\n alert('does not have [foo] property');\n}\n</code></pre>\n\n<p>Its ugly code, but you get the picture.</p>\n" }, { "answer_id": 330507, "author": "joolss", "author_id": 27741, "author_profile": "https://Stackoverflow.com/users/27741", "pm_score": 2, "selected": false, "text": "<p>One way would of course be to write your own CSS-parser in Javascript. But I believe that is <em>really</em> over the top.</p>\n" }, { "answer_id": 545471, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I too have some pages that work wonderfully in MSIE, but have lots of info in styles and style sheets. So I'm thinking about workarounds. One thing Firefox does allow, mercifully, is putting inline attributes into the DOM. So here's a partial strategy: </p>\n\n<ol>\n<li><p>Replace each inline style in the html document with a corresponding \"nStyle\", e.g., \n&lt;span class=\"cls1\" nStyle=\"color:red; nref:#myid; foo:bar\"> ... &lt;/span></p></li>\n<li><p>When the page is loaded, do the following with each element node: (a) copy the value of the nStyle attribute into the tag's cssText, and at the same time (b) convert the nonstandard attributes into an easier format, so that, e.g., node.getAttribute('nStyle') becomes the object {\"nref\":\"#myid\", \"foo\":\"bar\"}.</p></li>\n<li><p>Write a \"calculatedStyle\" function that gets either the style or the nStyle, depending on what's available.</p></li>\n</ol>\n\n<p>Writing a rough parser for style sheets might enable a similar strategy for them, but I have a question: How do I get over the hurdle of reading the style sheet without censorship from Firefox?</p>\n" }, { "answer_id": 11599944, "author": "Esailija", "author_id": 995876, "author_profile": "https://Stackoverflow.com/users/995876", "pm_score": 4, "selected": false, "text": "<p>Modern browsers will just throw away any invalid css. However, you can use the content property since it only has effect with\n<code>:after</code>, <code>:before</code> etc. You can store JSON inside it:</p>\n\n<pre><code>#someElement {\n content: '{\"foo\": \"bar\"}';\n}\n</code></pre>\n\n<p>Then use code like this to retrieve it:</p>\n\n<pre><code>var CSSMetaData = function() {\n\n function trimQuotes( str ) {\n return str.replace( /^['\"]/, \"\" ).replace( /[\"']$/, \"\" ); \n }\n\n function fixFirefoxEscape( str ) {\n return str.replace( /\\\\\"/g, '\"' );\n }\n\n var forEach = [].forEach,\n div = document.createElement(\"div\"),\n matchesSelector = div.webkitMatchesSelector ||\n div.mozMatchesSelector ||\n div.msMatchesSelector ||\n div.oMatchesSelector ||\n div.matchesSelector,\n data = {};\n\n forEach.call( document.styleSheets, function( styleSheet ) {\n forEach.call( styleSheet.cssRules, function( rule ) {\n var content = rule.style.getPropertyValue( \"content\" ),\n obj;\n\n if( content ) {\n content = trimQuotes(content);\n try {\n obj = JSON.parse( content );\n }\n catch(e) {\n try {\n\n obj = JSON.parse( fixFirefoxEscape( content ) );\n }\n catch(e2) {\n return ;\n }\n\n }\n data[rule.selectorText] = obj;\n }\n });\n\n });\n\n\n return {\n\n getDataByElement: function( elem ) {\n var storedData;\n for( var selector in data ) {\n if( matchesSelector.call( elem, selector ) ) {\n storedData = data[selector];\n if( storedData ) return storedData;\n\n }\n }\n\n return null;\n }\n };\n\n}();\nvar obj = CSSMetaData.getDataByElement( document.getElementById(\"someElement\"));\nconsole.log( obj.foo ); //bar\n</code></pre>\n\n<p>Note, this is only for modern browsers. Demo: <a href=\"http://jsfiddle.net/xFjZp/3/\">http://jsfiddle.net/xFjZp/3/</a></p>\n" }, { "answer_id": 11654894, "author": "Miljan Puzović", "author_id": 1550040, "author_profile": "https://Stackoverflow.com/users/1550040", "pm_score": -1, "selected": false, "text": "<p>Maybe you can try with <a href=\"http://lesscss.org/\" rel=\"nofollow\">LESS</a>. It's The Dynamic Stylesheet language and you can create non-standard css attributes, commands that will compile later.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30674/" ]
I have a dump of a windows service i made. The exception is that my code can't move a file (for some reason). Now, in my code there's a number of places where i move files around the filesystem. So, using Windbg, i'm trying to see the code where the exception occurs. here's my !clrstack dump.. ``` 0:016> !clrstack -p OS Thread Id: 0xdf8 (16) Child-SP RetAddr Call Site 0000000019edea70 0000064278a15e4f System.IO.__Error.WinIOError(Int32, System.String) PARAMETERS: errorCode = <no data> maybeFullPath = <no data> 0000000019edead0 0000064280181ce5 System.IO.File.Move(System.String, System.String) PARAMETERS: sourceFileName = <no data> destFileName = <no data> 0000000019edeb50 0000064280196532 MyClass.Foo.DoSomeStuffInHere(System.String) PARAMETERS: this = 0x0000000000c30aa8 filePathAndName = 0x0000000000d1aad0 ``` now, this helps a lot... ``` 0:016> !do 0x0000000000d1aad0 Name: System.String MethodTable: 00000642784365e8 EEClass: 000006427803e4f0 Size: 88(0x58) bytes (C:\WINDOWS\assembly\GAC_64\mscorlib\2.0.0.0__b77a5c561934e089\mscorlib.dll) String: C:\BlahBlahFolder\FooFolder\4469.jpg Fields: -snipped- ``` So i've figured out the file which failed to be moved. kewl. But i just want to see the code in this method MyClass.Foo.DoSomeStuffInHere(System.String) which calls File.Move(..). That method has lots of File.Move .. so i could put try / catches / debug / trace information .. but i'm hoping to be more efficient by using Windbg to help find this problem. Any thoughts?
Firefox does not carry over tags, attributes or CSS styles it does not understand from the code to the DOM. That is by design. Javascript only has access to the DOM, not the code. So no, there is no way to access a property from javascript that the browser itself does not support.
250,001
<p>Can someone define what exactly 'POCO' means? I am encountering the term more and more often, and I'm wondering if it is only about plain classes or it means something more?</p>
[ { "answer_id": 250006, "author": "David Mohundro", "author_id": 4570, "author_profile": "https://Stackoverflow.com/users/4570", "pm_score": 9, "selected": true, "text": "<p>\"Plain Old C# Object\"</p>\n\n<p>Just a normal class, no attributes describing infrastructure concerns or other responsibilities that your domain objects shouldn't have.</p>\n\n<p>EDIT - as other answers have stated, it is technically \"Plain Old CLR Object\" but I, like David Arno comments, prefer \"Plain Old Class Object\" to avoid ties to specific languages or technologies.</p>\n\n<p>TO CLARIFY: In other words, they don’t derive from \nsome special base class, nor do they return any special types for their properties.</p>\n\n<p>See below for an example of each.</p>\n\n<p>Example of a POCO:</p>\n\n<pre><code>public class Person\n{\n public string Name { get; set; }\n\n public int Age { get; set; }\n}\n</code></pre>\n\n<p>Example of something that isn’t a POCO:</p>\n\n<pre><code>public class PersonComponent : System.ComponentModel.Component\n{\n [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\n public string Name { get; set; }\n\n public int Age { get; set; }\n}\n</code></pre>\n\n<p>The example above both inherits from a special class to give it additional behavior as well as uses a custom attribute to change behavior… the same properties exist on both classes, but one is <em>not</em> just a plain old object anymore.</p>\n" }, { "answer_id": 250011, "author": "basszero", "author_id": 287, "author_profile": "https://Stackoverflow.com/users/287", "pm_score": 3, "selected": false, "text": "<p>In Java land typically \"PO\" means \"plain old\". The rest can be tricky, so I'm guessing that your example (in the context of Java) is \"plain old class object\".</p>\n\n<p>some other examples</p>\n\n<ul>\n<li>POJO (plain old java object)</li>\n<li>POJI (plain old java interface)</li>\n</ul>\n" }, { "answer_id": 250014, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 3, "selected": false, "text": "<p>POCO stands for \"Plain Old CLR Object\".</p>\n" }, { "answer_id": 250027, "author": "David Arno", "author_id": 7122, "author_profile": "https://Stackoverflow.com/users/7122", "pm_score": 3, "selected": false, "text": "<p>To add the the other answers, the POxx terms all appear to stem from POTS (<a href=\"http://en.wikipedia.org/wiki/Plain_old_telephone_service\" rel=\"noreferrer\">Plain old telephone services</a>).</p>\n\n<p>The POX, used to define simple (plain old) XML, rather than the complex multi-layered stuff associated with REST, SOAP etc, was a useful, and vaguely amusing, term. PO(insert language of choice)O terms have rather worn the joke thin.</p>\n" }, { "answer_id": 250136, "author": "Nic Wise", "author_id": 2947, "author_profile": "https://Stackoverflow.com/users/2947", "pm_score": 6, "selected": false, "text": "<p>Most people have said it - Plain Old CLR Object (as opposed to the earlier POJO - Plain Old Java Object)</p>\n\n<p>The POJO one came out of EJB, which required you to inherit from a specific parent class for things like value objects (what you get back from a query in an ORM or similar), so if you ever wanted to move from EJB (eg to Spring), you were stuffed. </p>\n\n<p>POJO's are just classes which dont force inheritance or any attribute markup to make them \"work\" in whatever framework you are using.</p>\n\n<p>POCO's are the same, except in .NET.</p>\n\n<p>Generally it'll be used around ORM's - older (and some current ones) require you to inherit from a specific base class, which ties you to that product. Newer ones dont (nhibernate being the variant I know) - you just make a class, register it with the ORM, and you are off. Much easier.</p>\n" }, { "answer_id": 293585, "author": "ayaz", "author_id": 23191, "author_profile": "https://Stackoverflow.com/users/23191", "pm_score": 2, "selected": false, "text": "<p>Interesting. The only thing I knew that had to do with programming and had POCO in it is the <a href=\"http://pocoproject.org/\" rel=\"nofollow noreferrer\">POCO C++ framework</a>. </p>\n" }, { "answer_id": 20866829, "author": "Naila Akbar", "author_id": 2660342, "author_profile": "https://Stackoverflow.com/users/2660342", "pm_score": 2, "selected": false, "text": "<p>In WPF MVVM terms, a POCO class is one that does not Fire PropertyChanged events</p>\n" }, { "answer_id": 28504028, "author": "Hardgraf", "author_id": 1860030, "author_profile": "https://Stackoverflow.com/users/1860030", "pm_score": 3, "selected": false, "text": "<p>In .NET a POCO is a 'Plain old CLR Object'. It is not a 'Plain old C# object'...</p>\n" }, { "answer_id": 38254006, "author": "Viking jonsson", "author_id": 4038542, "author_profile": "https://Stackoverflow.com/users/4038542", "pm_score": 5, "selected": false, "text": "<p>I may be wrong about this.. but anyways, I think POCO is Plain Old <strike>Class</strike> CLR Object and it comes from POJO plain old Java Object. A POCO is a class that holds data and has no behaviours.</p>\n\n<p>Here is an example written in C#:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>class Fruit \n{\n public Fruit() { }\n\n public Fruit(string name, double weight, int quantity) \n {\n Name = name;\n Weight = weight;\n Quantity = quantity;\n }\n\n public string Name { get; set; }\n public double Weight { get; set; }\n public int Quantity { get; set; }\n\n public override string ToString() \n {\n return $\"{Name.ToUpper()} ({Weight}oz): {Quantity}\";\n }\n}\n</code></pre>\n" }, { "answer_id": 38439474, "author": "Mr Mystery Guest", "author_id": 5371841, "author_profile": "https://Stackoverflow.com/users/5371841", "pm_score": 2, "selected": false, "text": "<p>Whilst I'm sure POCO means Plain Old Class Object or Plain Old C Object to 99.9% of people here, POCO is also Animator Pro's (Autodesk) built in scripting language.</p>\n" }, { "answer_id": 59906232, "author": "Mohammad Kamel", "author_id": 3227593, "author_profile": "https://Stackoverflow.com/users/3227593", "pm_score": 0, "selected": false, "text": "<p>POCO is a plain old CLR object, which represent the state and behavior of the application in terms of its problem domain.\nit is a pure class, without inheritance, without any attributes.\nExample: </p>\n\n<pre><code>public class Customer\n{\n public int Id { get; set; }\n\n public string Name { get; set; }\n}\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30726/" ]
Can someone define what exactly 'POCO' means? I am encountering the term more and more often, and I'm wondering if it is only about plain classes or it means something more?
"Plain Old C# Object" Just a normal class, no attributes describing infrastructure concerns or other responsibilities that your domain objects shouldn't have. EDIT - as other answers have stated, it is technically "Plain Old CLR Object" but I, like David Arno comments, prefer "Plain Old Class Object" to avoid ties to specific languages or technologies. TO CLARIFY: In other words, they don’t derive from some special base class, nor do they return any special types for their properties. See below for an example of each. Example of a POCO: ``` public class Person { public string Name { get; set; } public int Age { get; set; } } ``` Example of something that isn’t a POCO: ``` public class PersonComponent : System.ComponentModel.Component { [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string Name { get; set; } public int Age { get; set; } } ``` The example above both inherits from a special class to give it additional behavior as well as uses a custom attribute to change behavior… the same properties exist on both classes, but one is *not* just a plain old object anymore.
250,037
<p>I have a gridview and I need to sort its elements when the user clicks on the header.<br> Its datasource is a List object.</p> <p>The aspx is defined this way :</p> <pre><code>&lt;asp:GridView ID="grdHeader" AllowSorting="true" AllowPaging="false" AutoGenerateColumns="false" Width="780" runat="server" OnSorting="grdHeader_OnSorting" EnableViewState="true"&gt; &lt;Columns&gt; &lt;asp:BoundField DataField="Entitycode" HeaderText="Entity" SortExpression="Entitycode" /&gt; &lt;asp:BoundField DataField="Statusname" HeaderText="Status" SortExpression="Statusname" /&gt; &lt;asp:BoundField DataField="Username" HeaderText="User" SortExpression="Username" /&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; </code></pre> <p>The code behind is defined this way :<br> First load :</p> <pre><code>protected void btnSearch_Click(object sender, EventArgs e) { List&lt;V_ReportPeriodStatusEntity&gt; items = GetPeriodStatusesForScreenSelection(); this.grdHeader.DataSource = items; this.grdHeader.DataBind(); } </code></pre> <p>when the user clicks on headers :</p> <pre><code>protected void grdHeader_OnSorting(object sender, GridViewSortEventArgs e) { List&lt;V_ReportPeriodStatusEntity&gt; items = GetPeriodStatusesForScreenSelection(); items.Sort(new Helpers.GenericComparer&lt;V_ReportPeriodStatusEntity&gt;(e.SortExpression, e.SortDirection)); grdHeader.DataSource = items; grdHeader.DataBind(); } </code></pre> <p>My problem is that e.SortDirection is always set to Ascending.<br> I have webpage with a similar code and it works well, e.SortDirection alternates between Ascending and Descending.</p> <p>What did I do wrong ?</p>
[ { "answer_id": 250571, "author": "Michael DeLorenzo", "author_id": 1383003, "author_profile": "https://Stackoverflow.com/users/1383003", "pm_score": 1, "selected": false, "text": "<p>It's been awhile since I used a GridView, but I think you need to set the grid's SortDirection property to whatever it currently is before leaving the OnSorting method.</p>\n\n<p>So....</p>\n\n<p><code>List&lt;V_ReportPeriodStatusEntity&gt; items = GetPeriodStatusesForScreenSelection();</code><br>\n<code>items.Sort(new Helpers.GenericComparer&lt;V_ReportPeriodStatusEntity&gt;(e.SortExpression, e.SortDirection));</code><br>\n<strong><code>grdHeader.SortDirection = e.SortDirection.Equals(SortDirection.Ascending) ? SortDirection.Descending : SortDirection.Ascending;</code></strong><br>\n<code>grdHeader.DataSource = items;</code><br>\n<code>grdHeader.DataBind();</code></p>\n" }, { "answer_id": 261905, "author": "DiningPhilanderer", "author_id": 30934, "author_profile": "https://Stackoverflow.com/users/30934", "pm_score": 1, "selected": false, "text": "<p>I got tired of dealing with this issue and put the sort direction and sort column in the ViewState....</p>\n" }, { "answer_id": 300872, "author": "djuth", "author_id": 38787, "author_profile": "https://Stackoverflow.com/users/38787", "pm_score": 1, "selected": false, "text": "<p>To toggle ascending and descending, I use a method in my app's BasePage to cache the sort expression and sort direction:</p>\n\n<pre><code>protected void SetPageSort(GridViewSortEventArgs e)\n{\n if (e.SortExpression == SortExpression)\n {\n if (SortDirection == \"ASC\")\n {\n SortDirection = \"DESC\";\n }\n else\n {\n SortDirection = \"ASC\";\n }\n }\n else\n {\n SortDirection = \"ASC\";\n SortExpression = e.SortExpression;\n }\n}\n</code></pre>\n\n<p>SortExpression and SortDirection are both properties in BasePage that store and retrieve their values from ViewState.</p>\n\n<p>So all of my derived pages just call SetPageSort from the GridView's Sorting method, and bind the GridView:</p>\n\n<pre><code>protected void gv_Sorting(object sender, GridViewSortEventArgs e)\n{\n SetPageSort(e);\n BindGrid();\n}\n</code></pre>\n\n<p>BindGrid checks the SortExpression and uses it and SortDirection to do an ORDERY BY on the grid's data source, something like this:</p>\n\n<pre><code>if (SortExpression.Length &gt; 0)\n{\n qry.ORDER_BY(SortExpression + \" \" + SortDirection);\n}\n\ngv.DataSource = qry.ExecuteReader();\ngv.DataBind();\n</code></pre>\n\n<p>So, the base class' SetPageSort removes much of the drudgery of GridView sorting. I feel like I'm forgetting something, but that's the general idea.</p>\n" }, { "answer_id": 399880, "author": "Sander", "author_id": 2928, "author_profile": "https://Stackoverflow.com/users/2928", "pm_score": 4, "selected": false, "text": "<p>Automatic bidirectional sorting only works with the SQL data source. Unfortunately, all the documentation in MSDN assumes you are using that, so GridView can get a bit frustrating.</p>\n\n<p>The way I do it is by keeping track of the order on my own. For example:</p>\n\n<pre><code> protected void OnSortingResults(object sender, GridViewSortEventArgs e)\n {\n // If we're toggling sort on the same column, we simply toggle the direction. Otherwise, ASC it is.\n // e.SortDirection is useless and unreliable (only works with SQL data source).\n if (_sortBy == e.SortExpression)\n _sortDirection = _sortDirection == SortDirection.Descending ? SortDirection.Ascending : SortDirection.Descending;\n else\n _sortDirection = SortDirection.Ascending;\n\n _sortBy = e.SortExpression;\n\n BindResults();\n }\n</code></pre>\n" }, { "answer_id": 415759, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": true, "text": "<p>You can use a session variable to store the latest Sort Expression and when you sort the grid next time compare the sort expression of the grid with the Session variable which stores last sort expression. If the columns are equal then check the direction of the previous sort and sort in the opposite direction. </p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>DataTable sourceTable = GridAttendence.DataSource as DataTable;\nDataView view = new DataView(sourceTable);\nstring[] sortData = ViewState[\"sortExpression\"].ToString().Trim().Split(' ');\nif (e.SortExpression == sortData[0])\n{\n if (sortData[1] == \"ASC\")\n {\n view.Sort = e.SortExpression + \" \" + \"DESC\";\n this.ViewState[\"sortExpression\"] = e.SortExpression + \" \" + \"DESC\";\n }\n else\n {\n view.Sort = e.SortExpression + \" \" + \"ASC\";\n this.ViewState[\"sortExpression\"] = e.SortExpression + \" \" + \"ASC\";\n }\n}\nelse\n{\n view.Sort = e.SortExpression + \" \" + \"ASC\";\n this.ViewState[\"sortExpression\"] = e.SortExpression + \" \" + \"ASC\";\n}\n</code></pre>\n" }, { "answer_id": 536639, "author": "George", "author_id": 64187, "author_profile": "https://Stackoverflow.com/users/64187", "pm_score": 4, "selected": false, "text": "<p>This problem is absent not only with SQL data sources but with Object Data Sources as well. However, when setting the DataSource dynamically in code, that's when this goes bad. Unfortunately, MSDN sometimes is really very poor on information. A simple mentioning of this behavior(this is not a bug but a design issue) would save a lot of time. Anyhow, I'm not very inclined to use Session variables for this. I usually store the sorting direction in a ViewState.</p>\n" }, { "answer_id": 590830, "author": "rjzii", "author_id": 1185, "author_profile": "https://Stackoverflow.com/users/1185", "pm_score": 3, "selected": false, "text": "<p>The way I did this is similar to the code that the <a href=\"https://stackoverflow.com/questions/250037/gridview-sorting-sortdirection-always-ascending/415759#415759\">accepted answer</a> provided, bit is a bit different so I thought I would put it out there as well. Note that this sorting is being done to a <a href=\"http://msdn.microsoft.com/en-us/library/system.data.datatable.aspx\" rel=\"nofollow noreferrer\">DataTable</a> before it is being bound to the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.aspx\" rel=\"nofollow noreferrer\">GridView</a>.DataSource.</p>\n\n<p><strong>Option One: Using ViewState</strong></p>\n\n<pre><code>void DataGrid_Sorting(object sender, GridViewSortEventArgs e)\n{\n if (e.SortExpression == (string)ViewState[\"SortColumn\"])\n {\n // We are resorting the same column, so flip the sort direction\n e.SortDirection = \n ((SortDirection)ViewState[\"SortColumnDirection\"] == SortDirection.Ascending) ? \n SortDirection.Descending : SortDirection.Ascending;\n }\n // Apply the sort\n this._data.DefaultView.Sort = e.SortExpression +\n (string)((e.SortDirection == SortDirection.Ascending) ? \" ASC\" : \" DESC\");\n ViewState[\"SortColumn\"] = e.SortExpression;\n ViewState[\"SortColumnDirection\"] = e.SortDirection;\n}\n</code></pre>\n\n<p><strong>Option Two: Using Session</strong> </p>\n\n<p>Note that the following is being provided for legacy purposes in the event that you see it in the field, or that you are still supporting company systems that are targeting older browsers.</p>\n\n<pre><code>void DataGrid_Sorting(object sender, GridViewSortEventArgs e)\n{\n if (e.SortExpression == (string)HttpContext.Current.Session[\"SortColumn\"])\n {\n // We are resorting the same column, so flip the sort direction\n e.SortDirection = \n ((SortDirection)HttpContext.Current.Session[\"SortColumnDirection\"] == SortDirection.Ascending) ? \n SortDirection.Descending : SortDirection.Ascending;\n }\n // Apply the sort\n this._data.DefaultView.Sort = e.SortExpression +\n (string)((e.SortDirection == SortDirection.Ascending) ? \" ASC\" : \" DESC\");\n HttpContext.Current.Session[\"SortColumn\"] = e.SortExpression;\n HttpContext.Current.Session[\"SortColumnDirection\"] = e.SortDirection;\n}\n</code></pre>\n" }, { "answer_id": 812389, "author": "maxbeaudoin", "author_id": 79152, "author_profile": "https://Stackoverflow.com/users/79152", "pm_score": 4, "selected": false, "text": "<p>A simple solution:</p>\n\n<pre><code>protected SortDirection GetSortDirection(string column)\n{\n SortDirection nextDir = SortDirection.Ascending; // Default next sort expression behaviour.\n if (ViewState[\"sort\"] != null &amp;&amp; ViewState[\"sort\"].ToString() == column)\n { // Exists... DESC.\n nextDir = SortDirection.Descending;\n ViewState[\"sort\"] = null;\n }\n else\n { // Doesn't exists, set ViewState.\n ViewState[\"sort\"] = column;\n }\n return nextDir;\n}\n</code></pre>\n\n<p>Much like the default GridView sorting and lightweight on the ViewState.</p>\n\n<p><strong>USAGE:</strong></p>\n\n<pre><code>protected void grdHeader_OnSorting(object sender, GridViewSortEventArgs e)\n{\n List&lt;V_ReportPeriodStatusEntity&gt; items = GetPeriodStatusesForScreenSelection();\n\n items.Sort(new Helpers.GenericComparer&lt;V_ReportPeriodStatusEntity&gt;(e.SortExpression, GetSortDirection(e.SortExpression));\n grdHeader.DataSource = items;\n grdHeader.DataBind();\n}\n</code></pre>\n" }, { "answer_id": 1298329, "author": "rwo", "author_id": 154001, "author_profile": "https://Stackoverflow.com/users/154001", "pm_score": 6, "selected": false, "text": "<p>The problem with Session and Viewstate is that you also have to keep track of the gridview control for which SortColumn and Direction is stored if there is more than one gridview on the page.</p>\n\n<p>An alternative to Session and Viewstate is to add 2 attributes to the Gridview and keep track of Column and Direction that way.</p>\n\n<p>Here is an example:</p>\n\n<pre><code>private void GridViewSortDirection(GridView g, GridViewSortEventArgs e, out SortDirection d, out string f)\n{\n f = e.SortExpression;\n d = e.SortDirection;\n\n //Check if GridView control has required Attributes\n if (g.Attributes[\"CurrentSortField\"] != null &amp;&amp; g.Attributes[\"CurrentSortDir\"] != null)\n {\n if (f == g.Attributes[\"CurrentSortField\"])\n {\n d = SortDirection.Descending;\n if (g.Attributes[\"CurrentSortDir\"] == \"ASC\")\n {\n d = SortDirection.Ascending;\n }\n }\n\n g.Attributes[\"CurrentSortField\"] = f;\n g.Attributes[\"CurrentSortDir\"] = (d == SortDirection.Ascending ? \"DESC\" : \"ASC\");\n }\n\n}\n</code></pre>\n" }, { "answer_id": 1684595, "author": "Daver", "author_id": 68095, "author_profile": "https://Stackoverflow.com/users/68095", "pm_score": 0, "selected": false, "text": "<p>I had a horrible problem with this so I finally resorted to using LINQ to order the DataTable before assigning it to the view:</p>\n\n<pre><code>Dim lquery = From s In listToMap\n Select s\n Order By s.ACCT_Active Descending, s.ACCT_Name\n</code></pre>\n\n<p>In particular I really found the DataView.Sort and DataGrid.Sort methods unreliable when sorting a boolean field. </p>\n\n<p>I hope this helps someone out there.</p>\n" }, { "answer_id": 6477999, "author": "in4man_1", "author_id": 812365, "author_profile": "https://Stackoverflow.com/users/812365", "pm_score": 2, "selected": false, "text": "<p>All that answer not fully correct. I use That:</p>\n\n<pre><code>protected void SetPageSort(GridViewSortEventArgs e) \n { \n if (e.SortExpression == SortExpression) \n { \n if (SortDirection == \"ASC\") \n { \n SortDirection = \"DESC\"; \n } \n else \n { \n SortDirection = \"ASC\"; \n } \n } \n else \n {\n if (SortDirection == \"ASC\")\n {\n SortDirection = \"DESC\";\n }\n else\n {\n SortDirection = \"ASC\";\n } \n SortExpression = e.SortExpression; \n } \n } \n protected void gridView_Sorting(object sender, GridViewSortEventArgs e)\n {\n SetPageSort(e); \n</code></pre>\n\n<p>in gridView_Sorting...</p>\n" }, { "answer_id": 8510356, "author": "Basil", "author_id": 1098540, "author_profile": "https://Stackoverflow.com/users/1098540", "pm_score": 0, "selected": false, "text": "<pre><code>void dg_SortCommand(object source, DataGridSortCommandEventArgs e)\n{\n DataGrid dg = (DataGrid) source;\n string sortField = dg.Attributes[\"sortField\"];\n List &lt; SubreportSummary &gt; data = (List &lt; SubreportSummary &gt; ) dg.DataSource;\n string field = e.SortExpression.Split(' ')[0];\n string sort = \"ASC\";\n if (sortField != null)\n {\n sort = sortField.Split(' ')[0] == field ? (sortField.Split(' ')[1] == \"DESC\" ? \"ASC\" : \"DESC\") : \"ASC\";\n }\n dg.Attributes[\"sortField\"] = field + \" \" + sort;\n data.Sort(new GenericComparer &lt; SubreportSummary &gt; (field, sort, null));\n dg.DataSource = data;\n dg.DataBind();\n}\n</code></pre>\n" }, { "answer_id": 10426852, "author": "AVIK GHOSH", "author_id": 1371819, "author_profile": "https://Stackoverflow.com/users/1371819", "pm_score": 2, "selected": false, "text": "<pre><code> &lt;asp:GridView ID=\"GridView1\" runat=\"server\" AutoGenerateColumns=\"false\" AllowSorting=\"True\" \n onsorting=\"GridView1_Sorting\" EnableViewState=\"true\"&gt;\n &lt;Columns&gt;&lt;asp:BoundField DataField=\"bookid\" HeaderText=\"BOOK ID\" SortExpression=\"bookid\" /&gt;\n &lt;asp:BoundField DataField=\"bookname\" HeaderText=\"BOOK NAME\" /&gt;\n &lt;asp:BoundField DataField=\"writer\" HeaderText=\"WRITER\" /&gt;\n &lt;asp:BoundField DataField=\"totalbook\" HeaderText=\"TOTAL BOOK\" SortExpression=\"totalbook\" /&gt;\n &lt;asp:BoundField DataField=\"availablebook\" HeaderText=\"AVAILABLE BOOK\" /&gt;\n//gridview code on page load under ispostback false//after that.\n\n\n\nprotected void Page_Load(object sender, EventArgs e)\n {\n if (!IsPostBack)\n {\n string query = \"SELECT * FROM book\";\n DataTable DT = new DataTable();\n SqlDataAdapter DA = new SqlDataAdapter(query, sqlCon);\n DA.Fill(DT);\n\n\n GridView1.DataSource = DT;\n GridView1.DataBind();\n }\n }\n\n protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)\n {\n\n string query = \"SELECT * FROM book\";\n DataTable DT = new DataTable();\n SqlDataAdapter DA = new SqlDataAdapter(query, sqlCon);\n DA.Fill(DT);\n\n GridView1.DataSource = DT;\n GridView1.DataBind();\n\n if (DT != null)\n {\n\n DataView dataView = new DataView(DT);\n dataView.Sort = e.SortExpression + \" \" + ConvertSortDirectionToSql(e.SortDirection);\n\n\n GridView1.DataSource = dataView;\n GridView1.DataBind();\n }\n }\n\n private string GridViewSortDirection\n {\n get { return ViewState[\"SortDirection\"] as string ?? \"DESC\"; }\n set { ViewState[\"SortDirection\"] = value; }\n }\n\n private string ConvertSortDirectionToSql(SortDirection sortDirection)\n {\n switch (GridViewSortDirection)\n {\n case \"ASC\":\n GridViewSortDirection = \"DESC\";\n break;\n\n case \"DESC\":\n GridViewSortDirection = \"ASC\";\n break;\n }\n\n return GridViewSortDirection;\n }\n}\n</code></pre>\n" }, { "answer_id": 13504318, "author": "Dave Lucre", "author_id": 1219999, "author_profile": "https://Stackoverflow.com/users/1219999", "pm_score": 2, "selected": false, "text": "<p>This is probably going to bet buried here but the solution I came up with which works great for my situation:</p>\n\n<p>Form Load Event looks like this:</p>\n\n<pre><code>private DataTable DataTable1;\nprotected void Page_Load(object sender, EventArgs e)\n{\n DataTable1 = GetDataFromDatabase();\n this.GridView1.DataSource = DataTable1.DefaultView;\n this.GridView1.DataBind();\n}\n</code></pre>\n\n<p>Add two hidden fields on to the page:</p>\n\n<pre><code>&lt;asp:HiddenField runat=\"server\" ID=\"lastSortDirection\" /&gt;\n&lt;asp:HiddenField runat=\"server\" ID=\"lastSortExpression\" /&gt;\n</code></pre>\n\n<p>Add the following to your asp:GridView object:</p>\n\n<pre><code>AllowSorting=\"True\" OnSorting=\"GridView1_Sorting\"\n</code></pre>\n\n<p>Use the following GridView Sorting Event</p>\n\n<pre><code>protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)\n{\n if (lastSortExpression.Value == e.SortExpression.ToString())\n {\n if (lastSortDirection.Value == SortDirection.Ascending.ToString())\n {\n e.SortDirection = SortDirection.Descending;\n }\n else\n {\n e.SortDirection = SortDirection.Ascending;\n }\n lastSortDirection.Value = e.SortDirection.ToString();\n lastSortExpression.Value = e.SortExpression;\n }\n else\n {\n lastSortExpression.Value = e.SortExpression;\n e.SortDirection = SortDirection.Ascending;\n lastSortDirection.Value = e.SortDirection.ToString();\n }\n\n DataView dv = DataTable1.DefaultView;\n if (e.SortDirection == SortDirection.Ascending)\n {\n dv.Sort = e.SortExpression;\n }\n else\n {\n dv.Sort = e.SortExpression + \" DESC\";\n }\n\n DataTable1 = dv.ToTable();\n GridView1.DataSource = DataTable1.DefaultView;\n GridView1.DataBind();\n}\n</code></pre>\n\n<p>Now every column in my gridview is sorted without needing any further changes if any of the columns change.</p>\n" }, { "answer_id": 15334800, "author": "Amrit Jain", "author_id": 2075104, "author_profile": "https://Stackoverflow.com/users/2075104", "pm_score": 1, "selected": false, "text": "<p>XML:</p>\n\n<pre><code>&lt;asp:BoundField DataField=\"DealCRMID\" HeaderText=\"Opportunity ID\"\n SortExpression=\"DealCRMID\"/&gt;\n&lt;asp:BoundField DataField=\"DealCustomerName\" HeaderText=\"Customer\" \n SortExpression=\"DealCustomerName\"/&gt;\n&lt;asp:BoundField DataField=\"SLCode\" HeaderText=\"Practice\" \n SortExpression=\"SLCode\"/&gt;\n</code></pre>\n\n<p>Code:</p>\n\n<pre><code>private string ConvertSortDirectionToSql(String sortExpression,SortDirection sortDireciton)\n{\n switch (sortExpression)\n {\n case \"DealCRMID\":\n ViewState[\"DealCRMID\"]=ChangeSortDirection(ViewState[\"DealCRMID\"].ToString());\n return ViewState[\"DealCRMID\"].ToString();\n\n case \"DealCustomerName\":\n ViewState[\"DealCustomerName\"] = ChangeSortDirection(ViewState[\"DealCustomerName\"].ToString());\n return ViewState[\"DealCustomerName\"].ToString();\n\n case \"SLCode\":\n ViewState[\"SLCode\"] = ChangeSortDirection(ViewState[\"SLCode\"].ToString());\n return ViewState[\"SLCode\"].ToString();\n\n default:\n return \"ASC\";\n } \n}\n\nprivate string ChangeSortDirection(string sortDireciton)\n{\n switch (sortDireciton)\n    {\n        case \"DESC\":\n            return \"ASC\";\n        case \"ASC\":\n        return \"DESC\";\n     default:\n            return \"ASC\";\n    }\n}\n\nprotected void gvPendingApprovals_Sorting(object sender, GridViewSortEventArgs e)\n{\n DataSet ds = (System.Data.DataSet)(gvPendingApprovals.DataSource);\n\n if(ds.Tables.Count&gt;0)\n {\n DataView m_DataView = new DataView(ds.Tables[0]);\n m_DataView.Sort = e.SortExpression + \" \" + ConvertSortDirectionToSql   (e.SortExpression.ToString(), e.SortDirection);\n\n gvPendingApprovals.DataSource = m_DataView;\n gvPendingApprovals.DataBind();\n }\n}\n</code></pre>\n" }, { "answer_id": 17226727, "author": "Ali", "author_id": 1634697, "author_profile": "https://Stackoverflow.com/users/1634697", "pm_score": 1, "selected": false, "text": "<p>This is another way of solving the issue:</p>\n\n<pre><code>protected void grdHeader_OnSorting(object sender, GridViewSortEventArgs e)\n{\n List&lt;V_ReportPeriodStatusEntity&gt; items = GetPeriodStatusesForScreenSelection();\n items.Sort = e.SortExpression + \" \" + ConvertSortDirectionToSql(e);\n grdHeader.DataSource = items;\n grdHeader.DataBind();\n}\n\nprivate string ConvertSortDirectionToSql(GridViewSortEventArgs e)\n{\n ViewState[e.SortExpression] = ViewState[e.SortExpression] ?? \"ASC\";\n ViewState[e.SortExpression] = (ViewState[e.SortExpression].ToString() == \"ASC\") ? \"DESC\" : \"ASC\";\n return ViewState[e.SortExpression].ToString();\n}\n</code></pre>\n" }, { "answer_id": 20188834, "author": "Arijus Gilbrantas", "author_id": 1110126, "author_profile": "https://Stackoverflow.com/users/1110126", "pm_score": 2, "selected": false, "text": "<p>Another one :) Don't need to hard code column names..</p>\n\n<pre><code>DataTable dt = GetData();\n\n SortDirection sd;\n string f;\n GridViewSortDirection(gvProductBreakdown, e, out sd, out f);\n dt.DefaultView.Sort = sd == SortDirection.Ascending ? f + \" asc\" : f + \" desc\";\n gvProductBreakdown.DataSource = dt;\n gvProductBreakdown.DataBind();\n</code></pre>\n\n<p>Ant then:</p>\n\n<pre><code> private void GridViewSortDirection(GridView g, GridViewSortEventArgs e, out SortDirection d, out string f)\n {\n f = e.SortExpression;\n d = e.SortDirection;\n if (g.Attributes[f] != null)\n {\n d = g.Attributes[f] == \"ASC\" ? SortDirection.Descending : SortDirection.Ascending;\n\n g.Attributes[f] = d == SortDirection.Ascending ? \"ASC\" : \"DESC\";\n }\n else\n {\n g.Attributes[f] = \"ASC\";\n d = SortDirection.Ascending;\n }\n</code></pre>\n" }, { "answer_id": 21892323, "author": "PrzemG", "author_id": 3195498, "author_profile": "https://Stackoverflow.com/users/3195498", "pm_score": 2, "selected": false, "text": "<p>It can be done without the use of View State or Session. Current order can be determined based on value in first and last row in the column we sort by:</p>\n\n<pre><code> protected void gvItems_Sorting(object sender, GridViewSortEventArgs e)\n {\n GridView grid = sender as GridView; // get reference to grid\n SortDirection currentSortDirection = SortDirection.Ascending; // default order\n\n // get column index by SortExpression\n int columnIndex = grid.Columns.IndexOf(grid.Columns.OfType&lt;DataControlField&gt;()\n .First(x =&gt; x.SortExpression == e.SortExpression));\n\n // sort only if grid has more than 1 row\n if (grid.Rows.Count &gt; 1)\n {\n // get cells\n TableCell firstCell = grid.Rows[0].Cells[columnIndex];\n TableCell lastCell = grid.Rows[grid.Rows.Count - 1].Cells[columnIndex];\n\n // if field type of the cell is 'TemplateField' Text property is always empty.\n // Below assumes that value is binded to Label control in 'TemplateField'.\n string firstCellValue = firstCell.Controls.Count == 0 ? firstCell.Text : ((Label)firstCell.Controls[1]).Text;\n string lastCellValue = lastCell.Controls.Count == 0 ? lastCell.Text : ((Label)lastCell.Controls[1]).Text;\n\n DateTime tmpDate;\n decimal tmpDecimal;\n\n // try to determinate cell type to ensure correct ordering\n // by date or number\n if (DateTime.TryParse(firstCellValue, out tmpDate)) // sort as DateTime\n {\n currentSortDirection = \n DateTime.Compare(Convert.ToDateTime(firstCellValue), \n Convert.ToDateTime(lastCellValue)) &lt; 0 ? \n SortDirection.Ascending : SortDirection.Descending;\n }\n else if (Decimal.TryParse(firstCellValue, out tmpDecimal)) // sort as any numeric type\n {\n currentSortDirection = Decimal.Compare(Convert.ToDecimal(firstCellValue), \n Convert.ToDecimal(lastCellValue)) &lt; 0 ? \n SortDirection.Ascending : SortDirection.Descending;\n }\n else // sort as string\n {\n currentSortDirection = string.CompareOrdinal(firstCellValue, lastCellValue) &lt; 0 ? \n SortDirection.Ascending : SortDirection.Descending;\n }\n }\n\n // then bind GridView using correct sorting direction (in this example I use Linq)\n if (currentSortDirection == SortDirection.Descending)\n {\n grid.DataSource = myItems.OrderBy(x =&gt; x.GetType().GetProperty(e.SortExpression).GetValue(x, null));\n }\n else\n {\n grid.DataSource = myItems.OrderByDescending(x =&gt; x.GetType().GetProperty(e.SortExpression).GetValue(x, null));\n }\n\n grid.DataBind();\n }\n</code></pre>\n" }, { "answer_id": 23375917, "author": "mcfea", "author_id": 984463, "author_profile": "https://Stackoverflow.com/users/984463", "pm_score": 1, "selected": false, "text": "<p>Old string, but maybe my answer will help somebody.</p>\n\n<p>First get your SqlDataSource as a DataView:</p>\n\n<pre><code>Private Sub DataGrid1_SortCommand(ByVal source As Object, ByVal e As DataGridSortCommandEventArgs) Handles grid1.SortCommand\n Dim dataView As DataView = CType(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)\n dataView.Sort = e.SortExpression + dataView.FieldSortDirection(Session, e.SortExpression)\n\n grid1.DataSourceID = Nothing\n grid1.DataSource = dataView\n grid1.DataBind()\n\nEnd Sub\n</code></pre>\n\n<p>Then use an extension method for the sort (kind of a cheep shot, but a good start):</p>\n\n<pre><code>public static class DataViewExtensions\n{\n public static string FieldSortDirection(this DataView dataView, HttpSessionState session, string sortExpression)\n {\n const string SORT_DIRECTION = \"SortDirection\";\n var identifier = SORT_DIRECTION + sortExpression;\n\n if (session[identifier] != null)\n {\n if ((string) session[identifier] == \" ASC\")\n session[identifier] = \" DESC\";\n else if ((string) session[identifier] == \" DESC\")\n session[identifier] = \" ASC\";\n }\n else\n session[identifier] = \" ASC\";\n\n return (string) session[identifier];\n }\n}\n</code></pre>\n" }, { "answer_id": 25312200, "author": "Barry McDermid", "author_id": 403198, "author_profile": "https://Stackoverflow.com/users/403198", "pm_score": 0, "selected": false, "text": "<p>Perhaps this will help someone. Not sure if it's because it's 2014 or I don't understand the problem this post trying to resolve but this is very simple with slickgrid as follows:</p>\n\n<p>The issue seems to be how to 'remember' what the current sort setting is so suggestions are around Asp.Net holding that value for you. However slickGrid can tell you what the current sort order is:</p>\n\n<p>To toggle sort asc desc you can use grid.getSortColumns() to find out what the column sort currently is. This is what I did but I am only sorting on 1 column at a time thus I can safely do this : 'if(grid.getSortColumns()[0].sortAsc)'</p>\n\n<p>... so my code which works is like this:</p>\n\n<pre><code> // Make sure you have sortable: true on the relevant column names or \n // nothing happens as I found!!\n var columns = [\n { name: \"FileName\", id: \"FileName\", field: \"FileName\", width: 95, selectable: true, sortable: true },\n { name: \"Type\", id: \"DocumentType\", field: \"DocumentType\", minWidth: 105, width: 120, maxWidth: 120, selectable: true, sortable: true },\n { name: \"ScanDate\", id: \"ScanDate\", field: \"ScanDate\", width: 90, selectable: true, sortable: true }, ];\n</code></pre>\n\n<p>.. load your data as usual then the sort part:</p>\n\n<pre><code> // Clicking on a column header fires this event. Here we toggle the sort direction\n grid.onHeaderClick.subscribe(function(e, args) {\n var columnID = args.column.id;\n\n if (grid.getSortColumns()[0].sortAsc) {\n grid.setSortColumn(args.column.id, true);\n }\n else {\n grid.setSortColumn(args.column.id, false);\n }\n });\n\n // The actual sort function is like this \n grid.onSort.subscribe(function (e, args) {\n sortdir = args.sortAsc ? 1 : -1;\n sortcol = args.sortCol.field;\n\n //alert('in sort');\n\n // using native sort with comparer\n // preferred method but can be very slow in IE with huge datasets\n dataView.sort(comparer, args.sortAsc);\n grid.invalidateAllRows();\n grid.render();\n });\n\n// Default comparer is enough for what I'm doing here ..\nfunction comparer(a, b) {\n var x = a[sortcol], y = b[sortcol];\n return (x == y ? 0 : (x &gt; y ? 1 : -1));\n}\n</code></pre>\n\n<p>Lastly make sure you have the SlickGrid image folder included in your site and you'll get the asc/desc arrows appearing on the column when you select it. If they are missing the text will go italics but no arrows will appear.</p>\n" }, { "answer_id": 25657044, "author": "AdamE", "author_id": 796858, "author_profile": "https://Stackoverflow.com/users/796858", "pm_score": 3, "selected": false, "text": "<p>I don't know why everyone forgets about using hidden fields! They are so much \"cheaper\" than ViewState (which I have turned off since 2005). If you don't want to use Session or ViewState, then here is my solution:</p>\n\n<p>Put these two hidden fields on your aspx page, and put the default sort you want for your data (I'm using LastName for example):</p>\n\n<pre><code>&lt;asp:HiddenField ID=\"hfSortExpression\" runat=\"server\" Value=\"LastName\" /&gt;\n&lt;asp:HiddenField ID=\"hfSortDirection\" runat=\"server\" Value=\"Ascending\" /&gt;\n</code></pre>\n\n<p>Then put this helper code in your Base page (you have a base page don't you? If not, put in your .cs code behind).</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Since native ASP.Net GridViews do not provide accurate SortDirections, \n/// we must save a hidden field with previous sort Direction and Expression.\n/// Put these two hidden fields on page and call this method in grid sorting event\n/// &lt;/summary&gt;\n/// &lt;param name=\"hfSortExpression\"&gt;The hidden field on page that has the PREVIOUS column that is sorted on&lt;/param&gt;\n/// &lt;param name=\"hfSortDirection\"&gt;The hidden field on page that has the PREVIOUS sort direction&lt;/param&gt;\nprotected SortDirection GetSortDirection(GridViewSortEventArgs e, HiddenField hfSortExpression, HiddenField hfSortDirection)\n{\n //assume Ascending always by default!!\n SortDirection sortDirection = SortDirection.Ascending;\n\n //see what previous column (if any) was sorted on\n string previousSortExpression = hfSortExpression.Value;\n //see what previous sort direction was used\n SortDirection previousSortDirection = !string.IsNullOrEmpty(hfSortDirection.Value) ? ((SortDirection)Enum.Parse(typeof(SortDirection), hfSortDirection.Value)) : SortDirection.Ascending;\n\n //check if we are now sorting on same column\n if (e.SortExpression == previousSortExpression)\n {\n //check if previous direction was ascending\n if (previousSortDirection == SortDirection.Ascending)\n {\n //since column name matches but direction doesn't, \n sortDirection = SortDirection.Descending;\n }\n }\n\n // save them back so you know for next time\n hfSortExpression.Value = e.SortExpression;\n hfSortDirection.Value = sortDirection.ToString();\n\n return sortDirection;\n}\n</code></pre>\n\n<p>Next, you need to handle the sorting in your grid sorting event handler. Call the method above from the sorting event handler, before calling your main method that gets your data</p>\n\n<pre><code>protected void gridContacts_Sorting(object sender, GridViewSortEventArgs e)\n{\n //get the sort direction (since GridView sortDirection is not implemented!)\n SortDirection sortDirection = GetSortDirection(e, hfSortExpression, hfSortDirection);\n\n //get data, sort and rebind (obviously, this is my own method... you must replace with your own)\n GetCases(_accountId, e.SortExpression, sortDirection);\n}\n</code></pre>\n\n<p>Since so many examples out there use DataTables or DataViews or other non LINQ friendly collections, I thought I'd include an example a call to a middle tier method that returns a generic list, and use LINQ to do the sorting in order to round out the example and make it more \"real world\":</p>\n\n<pre><code>private void GetCases(AccountID accountId, string sortExpression, SortDirection sortDirection)\n{\n //get some data from a middle tier method (database etc._)(\n List&lt;PendingCase&gt; pendingCases = MyMiddleTier.GetCasesPending(accountId.Value);\n //show a count to the users on page (this is just nice to have)\n lblCountPendingCases.Text = pendingCases.Count.ToString();\n //do the actual sorting of your generic list of custom objects\n pendingCases = Sort(sortExpression, sortDirection, pendingCases);\n //bind your grid\n grid.DataSource = pendingCases;\n grid.DataBind();\n}\n</code></pre>\n\n<p>Lastly, here is the down and dirty sorting using LINQ on a generic list of custom objects. I'm sure there is something fancier out there that will do the trick, but this illustrates the concept:</p>\n\n<p>private static List Sort(string sortExpression, SortDirection sortDirection, List pendingCases)\n {</p>\n\n<pre><code> switch (sortExpression)\n {\n case \"FirstName\":\n pendingCases = sortDirection == SortDirection.Ascending ? pendingCases.OrderBy(c =&gt; c.FirstName).ToList() : pendingCases.OrderByDescending(c =&gt; c.FirstName).ToList();\n break;\n case \"LastName\":\n pendingCases = sortDirection == SortDirection.Ascending ? pendingCases.OrderBy(c =&gt; c.LastName).ToList() : pendingCases.OrderByDescending(c =&gt; c.LastName).ToList();\n break;\n case \"Title\":\n pendingCases = sortDirection == SortDirection.Ascending ? pendingCases.OrderBy(c =&gt; c.Title).ToList() : pendingCases.OrderByDescending(c =&gt; c.Title).ToList();\n break;\n case \"AccountName\":\n pendingCases = sortDirection == SortDirection.Ascending ? pendingCases.OrderBy(c =&gt; c.AccountName).ToList() : pendingCases.OrderByDescending(c =&gt; c.AccountName).ToList();\n break;\n case \"CreatedByEmail\":\n pendingCases = sortDirection == SortDirection.Ascending ? pendingCases.OrderBy(c =&gt; c.CreatedByEmail).ToList() : pendingCases.OrderByDescending(c =&gt; c.CreatedByEmail).ToList();\n break;\n default:\n break;\n }\n return pendingCases;\n}\n</code></pre>\n\n<p>Last but not least (did I say that already?) you may want to put something like this in your Page_Load handler, so that the grid binds by default upon page load... Note that _accountId is a querystring parameter, converted to a custom type of AccountID of my own in this case...</p>\n\n<pre><code> if (!Page.IsPostBack)\n {\n //sort by LastName ascending by default\n GetCases(_accountId,hfSortExpression.Value,SortDirection.Ascending);\n }\n</code></pre>\n" }, { "answer_id": 26285465, "author": "PCPGMR", "author_id": 323650, "author_profile": "https://Stackoverflow.com/users/323650", "pm_score": 1, "selected": false, "text": "<p>Using SecretSquirrel's <a href=\"https://stackoverflow.com/a/590830/323650\">solution above</a></p>\n\n<p>here is my full working, production code. Just change dgvCoaches to your grid view name.</p>\n\n<p>... during the binding of the grid</p>\n\n<pre><code> dgvCoaches.DataSource = dsCoaches.Tables[0];\n ViewState[\"AllCoaches\"] = dsCoaches.Tables[0];\n dgvCoaches.DataBind();\n</code></pre>\n\n<p>and now the sorting</p>\n\n<pre><code>protected void gridView_Sorting(object sender, GridViewSortEventArgs e)\n{\n DataTable dt = ViewState[\"AllCoaches\"] as DataTable;\n\n if (dt != null)\n {\n if (e.SortExpression == (string)ViewState[\"SortColumn\"])\n {\n // We are resorting the same column, so flip the sort direction\n e.SortDirection =\n ((SortDirection)ViewState[\"SortColumnDirection\"] == SortDirection.Ascending) ?\n SortDirection.Descending : SortDirection.Ascending;\n }\n // Apply the sort\n dt.DefaultView.Sort = e.SortExpression +\n (string)((e.SortDirection == SortDirection.Ascending) ? \" ASC\" : \" DESC\");\n ViewState[\"SortColumn\"] = e.SortExpression;\n ViewState[\"SortColumnDirection\"] = e.SortDirection; \n\n dgvCoaches.DataSource = dt;\n dgvCoaches.DataBind();\n }\n}\n</code></pre>\n\n<p>and here is the aspx code:</p>\n\n<pre><code>&lt;asp:GridView ID=\"dgvCoaches\" runat=\"server\" \n CssClass=\"table table-hover table-striped\" GridLines=\"None\" DataKeyNames=\"HealthCoachID\" OnRowCommand=\"dgvCoaches_RowCommand\"\n AutoGenerateColumns=\"False\" OnSorting=\"gridView_Sorting\" AllowSorting=\"true\"&gt;\n &lt;Columns&gt;\n &lt;asp:BoundField DataField=\"HealthCoachID\" Visible=\"false\" /&gt;\n &lt;asp:BoundField DataField=\"LastName\" HeaderText=\"Last Name\" SortExpression=\"LastName\" /&gt;\n &lt;asp:BoundField DataField=\"FirstName\" HeaderText=\"First Name\" SortExpression=\"FirstName\" /&gt;\n &lt;asp:BoundField DataField=\"LoginName\" HeaderText=\"Login Name\" SortExpression=\"LoginName\" /&gt;\n &lt;asp:BoundField DataField=\"Email\" HeaderText=\"Email\" SortExpression=\"Email\" HtmlEncode=\"false\" DataFormatString=\"&lt;a href=mailto:{0}&gt;{0}&lt;/a&gt;\" /&gt;\n &lt;asp:TemplateField&gt;\n &lt;ItemTemplate&gt;\n &lt;asp:LinkButton runat=\"server\" BorderStyle=\"None\" CssClass=\"btn btn-default\" Text=\"&lt;i class='glyphicon glyphicon-edit'&gt;&lt;/i&gt;\" CommandName=\"Update\" CommandArgument=\"&lt;%# ((GridViewRow) Container).RowIndex %&gt;\" /&gt;\n &lt;/ItemTemplate&gt;\n &lt;/asp:TemplateField&gt;\n &lt;asp:TemplateField&gt;\n &lt;ItemTemplate&gt;\n &lt;asp:LinkButton runat=\"server\" OnClientClick=\"return ConfirmOnDelete();\" BorderStyle=\"None\" CssClass=\"btn btn-default\" Text=\"&lt;i class='glyphicon glyphicon-remove'&gt;&lt;/i&gt;\" CommandName=\"Delete\" CommandArgument=\"&lt;%# ((GridViewRow) Container).RowIndex %&gt;\" /&gt;\n &lt;/ItemTemplate&gt;\n &lt;/asp:TemplateField&gt;\n &lt;/Columns&gt;\n &lt;RowStyle CssClass=\"cursor-pointer\" /&gt;\n&lt;/asp:GridView&gt;\n</code></pre>\n" }, { "answer_id": 41749085, "author": "Bert", "author_id": 7442666, "author_profile": "https://Stackoverflow.com/users/7442666", "pm_score": -1, "selected": false, "text": "<p>In vb.net but very simple!</p>\n\n<pre><code>Protected Sub grTicketHistory_Sorting(sender As Object, e As GridViewSortEventArgs) Handles grTicketHistory.Sorting\n\n Dim dt As DataTable = Session(\"historytable\")\n If Session(\"SortDirection\" &amp; e.SortExpression) = \"ASC\" Then\n Session(\"SortDirection\" &amp; e.SortExpression) = \"DESC\"\n Else\n Session(\"SortDirection\" &amp; e.SortExpression) = \"ASC\"\n End If\n dt.DefaultView.Sort = e.SortExpression &amp; \" \" &amp; Session(\"SortDirection\" &amp; e.SortExpression)\n grTicketHistory.DataSource = dt\n grTicketHistory.DataBind()\n\nEnd Sub\n</code></pre>\n" }, { "answer_id": 42719613, "author": "Rasmus W", "author_id": 4243762, "author_profile": "https://Stackoverflow.com/users/4243762", "pm_score": 0, "selected": false, "text": "<p>Wrote this, it works for me: </p>\n\n<pre><code> protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)\n {\n if (ViewState[\"sortExpression\"] == null || ViewState[\"sortExpression\"].ToString() != e.SortExpression.ToString())\n MyDataTable.DefaultView.Sort = e.SortExpression + \" ASC\";\n else\n {\n if (ViewState[\"SortDirection\"].ToString() == \"Ascending\")\n MyDataTable.DefaultView.Sort = e.SortExpression = e.SortExpression + \" DESC\";\n else\n MyDataTable.DefaultView.Sort = e.SortExpression + \" ASC\";\n }\n\n GridView1.DataSource = MyDataTable;\n GridView1.DataBind();\n\n ViewState[\"sortExpression\"] = e.SortExpression;\n ViewState[\"SortDirection\"] = e.SortDirection;\n }\n</code></pre>\n" }, { "answer_id": 54828533, "author": "Isaac Byrne", "author_id": 5115866, "author_profile": "https://Stackoverflow.com/users/5115866", "pm_score": 1, "selected": false, "text": "<p>Here is how I do. Much easier than alot of the answers here IMO:</p>\n\n<p>Create this SortDirection class</p>\n\n<pre><code> // ==================================================\n // SortByDirection\n // ==================================================\n public SortDirection SortByDirection\n {\n get\n {\n if (ViewState[\"SortByDirection\"] == null)\n {\n ViewState[\"SortByDirection\"] = SortDirection.Ascending;\n }\n\n return (SortDirection)Enum.Parse(typeof(SortDirection), ViewState[\"SortByDirection\"].ToString());\n }\n set { ViewState[\"SortByDirection\"] = value; }\n }\n</code></pre>\n\n<p>And then use it in your sort function like this:</p>\n\n<pre><code> // Created Date\n if (sortBy == \"CreatedDate\")\n {\n if (SortByDirection == SortDirection.Ascending)\n {\n data = data.OrderBy(x =&gt; x.CreatedDate).ToList();\n SortByDirection = SortDirection.Descending;\n }\n else {\n data = data.OrderByDescending(x =&gt; x.CreatedDate).ToList();\n SortByDirection = SortDirection.Ascending;\n } \n }\n</code></pre>\n" }, { "answer_id": 58069201, "author": "Tomas", "author_id": 12109550, "author_profile": "https://Stackoverflow.com/users/12109550", "pm_score": 0, "selected": false, "text": "<pre><code>protected void gv_Sorting(object sender, GridViewSortEventArgs e)\n{\n DataTable dataTable = (DataTable)Cache[\"GridData\"];\n\n if (dataTable != null)\n {\n DataView dataView = new DataView(dataTable);\n string Field1 = e.SortExpression;\n string whichWay = \"ASC\";\n if (HttpContext.Current.Session[Field1] != null)\n {\n whichWay = HttpContext.Current.Session[Field1].ToString();\n if (whichWay == \"ASC\")\n whichWay = \"DESC\";\n else\n whichWay = \"ASC\"; \n }\n\n HttpContext.Current.Session[Field1] = whichWay;\n dataView.Sort = Field1 + \" \" + whichWay; \n gv.DataSource = dataView;\n gv.DataBind();\n }\n}\n</code></pre>\n\n<p>and you store the information that previously was retrieved</p>\n\n<pre><code> string SqlConn = ConfigurationManager.ConnectionStrings[\"Sql28\"].ConnectionString;\n SqlConnection sqlcon = new SqlConnection(SqlConn);\n sqlcon.Open();\n\n SqlCommand cmd = new SqlCommand();\n cmd.Connection = sqlcon;\n cmd.CommandType = System.Data.CommandType.Text;\n cmd.CommandText = HttpContext.Current.Session[\"sql\"].ToString();\n\n SqlDataAdapter adapter = new SqlDataAdapter(cmd);\n DataTable employees = new DataTable();\n adapter.Fill(employees);\n\n gv.DataSource = employees;\n gv.DataBind();\n\n Cache.Insert(\"GridData\", employees, null, System.Web.Caching.Cache.NoAbsoluteExpiration,new TimeSpan(0, 360000, 0));\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28544/" ]
I have a gridview and I need to sort its elements when the user clicks on the header. Its datasource is a List object. The aspx is defined this way : ``` <asp:GridView ID="grdHeader" AllowSorting="true" AllowPaging="false" AutoGenerateColumns="false" Width="780" runat="server" OnSorting="grdHeader_OnSorting" EnableViewState="true"> <Columns> <asp:BoundField DataField="Entitycode" HeaderText="Entity" SortExpression="Entitycode" /> <asp:BoundField DataField="Statusname" HeaderText="Status" SortExpression="Statusname" /> <asp:BoundField DataField="Username" HeaderText="User" SortExpression="Username" /> </Columns> </asp:GridView> ``` The code behind is defined this way : First load : ``` protected void btnSearch_Click(object sender, EventArgs e) { List<V_ReportPeriodStatusEntity> items = GetPeriodStatusesForScreenSelection(); this.grdHeader.DataSource = items; this.grdHeader.DataBind(); } ``` when the user clicks on headers : ``` protected void grdHeader_OnSorting(object sender, GridViewSortEventArgs e) { List<V_ReportPeriodStatusEntity> items = GetPeriodStatusesForScreenSelection(); items.Sort(new Helpers.GenericComparer<V_ReportPeriodStatusEntity>(e.SortExpression, e.SortDirection)); grdHeader.DataSource = items; grdHeader.DataBind(); } ``` My problem is that e.SortDirection is always set to Ascending. I have webpage with a similar code and it works well, e.SortDirection alternates between Ascending and Descending. What did I do wrong ?
You can use a session variable to store the latest Sort Expression and when you sort the grid next time compare the sort expression of the grid with the Session variable which stores last sort expression. If the columns are equal then check the direction of the previous sort and sort in the opposite direction. **Example:** ``` DataTable sourceTable = GridAttendence.DataSource as DataTable; DataView view = new DataView(sourceTable); string[] sortData = ViewState["sortExpression"].ToString().Trim().Split(' '); if (e.SortExpression == sortData[0]) { if (sortData[1] == "ASC") { view.Sort = e.SortExpression + " " + "DESC"; this.ViewState["sortExpression"] = e.SortExpression + " " + "DESC"; } else { view.Sort = e.SortExpression + " " + "ASC"; this.ViewState["sortExpression"] = e.SortExpression + " " + "ASC"; } } else { view.Sort = e.SortExpression + " " + "ASC"; this.ViewState["sortExpression"] = e.SortExpression + " " + "ASC"; } ```
250,038
<p>I would like to be able to add a hook to my setup.py that will be run post-install (either when easy_install'ing or when doing python setup.py install).</p> <p>In my project, <a href="http://code.google.com/p/pysmell" rel="noreferrer">PySmell</a>, I have some support files for Vim and Emacs. When a user installs PySmell the usual way, these files get copied in the actual egg, and the user has to fish them out and place them in his .vim or .emacs directories. What I want is either asking the user, post-installation, where would he like these files copied, or even just a message printing the location of the files and what should he do with them.</p> <p>What is the best way to do this?</p> <p>Thanks</p> <p>My setup.py looks like so:</p> <pre><code>#!/usr/bin/env python # -*- coding: UTF-8 -*- from setuptools import setup version = __import__('pysmell.pysmell').pysmell.__version__ setup( name='pysmell', version = version, description = 'An autocompletion library for Python', author = 'Orestis Markou', author_email = '[email protected]', packages = ['pysmell'], entry_points = { 'console_scripts': [ 'pysmell = pysmell.pysmell:main' ] }, data_files = [ ('vim', ['pysmell.vim']), ('emacs', ['pysmell.el']), ], include_package_data = True, keywords = 'vim autocomplete', url = 'http://code.google.com/p/pysmell', long_description = """\ PySmell is a python IDE completion helper. It tries to statically analyze Python source code, without executing it, and generates information about a project's structure that IDE tools can use. The first target is Vim, because that's what I'm using and because its completion mechanism is very straightforward, but it's not limited to it. """, classifiers = [ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development', 'Topic :: Utilities', 'Topic :: Text Editors', ] ) </code></pre> <p>EDIT:</p> <p>Here's a stub which demonstrates the <code>python setup.py install</code>:</p> <pre><code>from setuptools.command.install import install as _install class install(_install): def run(self): _install.run(self) print post_install_message setup( cmdclass={'install': install}, ... </code></pre> <p>No luck with the easy_install route yet.</p>
[ { "answer_id": 253103, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 4, "selected": true, "text": "<p>It depends on how the user installs your package. If the user actually runs \"setup.py install\", it's fairly easy: Just add another subcommand to the install command (say, install_vim), whose run() method will copy the files you want in the places where you want them. You can add your subcommand to install.sub_commands, and pass the command into setup().</p>\n\n<p>If you want a post-install script in a binary, it depends on the type of binary you are creating. For example, bdist_rpm, bdist_wininst, and bdist_msi have support for post-install scripts, because the underlying packing formats support post-install scripts.</p>\n\n<p>bdist_egg doesn't support a post-install mechanism by design:</p>\n\n<p><a href=\"http://bugs.python.org/setuptools/issue41\" rel=\"noreferrer\">http://bugs.python.org/setuptools/issue41</a></p>\n" }, { "answer_id": 7931715, "author": "merwok", "author_id": 821378, "author_profile": "https://Stackoverflow.com/users/821378", "pm_score": 0, "selected": false, "text": "<p>As a work-around, you could set the zip_ok option to false so that your project is installed as an unzipped directory, then it will be a little easier for your users to find the editor config file.</p>\n\n<p>In distutils2, it will be possible to install things to more directories, including custom directories, and to have pre/post-install/remove hooks.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32617/" ]
I would like to be able to add a hook to my setup.py that will be run post-install (either when easy\_install'ing or when doing python setup.py install). In my project, [PySmell](http://code.google.com/p/pysmell), I have some support files for Vim and Emacs. When a user installs PySmell the usual way, these files get copied in the actual egg, and the user has to fish them out and place them in his .vim or .emacs directories. What I want is either asking the user, post-installation, where would he like these files copied, or even just a message printing the location of the files and what should he do with them. What is the best way to do this? Thanks My setup.py looks like so: ``` #!/usr/bin/env python # -*- coding: UTF-8 -*- from setuptools import setup version = __import__('pysmell.pysmell').pysmell.__version__ setup( name='pysmell', version = version, description = 'An autocompletion library for Python', author = 'Orestis Markou', author_email = '[email protected]', packages = ['pysmell'], entry_points = { 'console_scripts': [ 'pysmell = pysmell.pysmell:main' ] }, data_files = [ ('vim', ['pysmell.vim']), ('emacs', ['pysmell.el']), ], include_package_data = True, keywords = 'vim autocomplete', url = 'http://code.google.com/p/pysmell', long_description = """\ PySmell is a python IDE completion helper. It tries to statically analyze Python source code, without executing it, and generates information about a project's structure that IDE tools can use. The first target is Vim, because that's what I'm using and because its completion mechanism is very straightforward, but it's not limited to it. """, classifiers = [ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development', 'Topic :: Utilities', 'Topic :: Text Editors', ] ) ``` EDIT: Here's a stub which demonstrates the `python setup.py install`: ``` from setuptools.command.install import install as _install class install(_install): def run(self): _install.run(self) print post_install_message setup( cmdclass={'install': install}, ... ``` No luck with the easy\_install route yet.
It depends on how the user installs your package. If the user actually runs "setup.py install", it's fairly easy: Just add another subcommand to the install command (say, install\_vim), whose run() method will copy the files you want in the places where you want them. You can add your subcommand to install.sub\_commands, and pass the command into setup(). If you want a post-install script in a binary, it depends on the type of binary you are creating. For example, bdist\_rpm, bdist\_wininst, and bdist\_msi have support for post-install scripts, because the underlying packing formats support post-install scripts. bdist\_egg doesn't support a post-install mechanism by design: <http://bugs.python.org/setuptools/issue41>
250,082
<p>I have a makefile template to compile a single DLL (for a plugin system). The makefile of the user looks like this:</p> <pre><code>EXTRA_SRCS=file1 file2 include makefile.in </code></pre> <p>In the <code>makefile.in</code> I have:</p> <pre><code>plugin.dll: plugin.os $(patsubst %,%.os,$(EXTRA_SRCS)) </code></pre> <p>Where <code>plugin.os</code> is the main C++ file to be compiled. Btw, the files ending is <code>.os</code> are the object files compiled for shared library (i.e. using the <code>-fpic</code> option with <code>gcc</code>)</p> <p>Now, the problem is that the extra sources will probably (but not necessarily) be header files. Ideally I would like to add them as dependencies for the target <code>plugin.os</code> and the <code>file.cpp</code>, but only if they exist.</p> <p>The method should work for both windows and linux, or at least be adaptable to each. However, I only use the GNU version of make.</p>
[ { "answer_id": 250163, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 5, "selected": true, "text": "<p>Use the \"wildcard\" function:</p>\n\n<pre><code>$(wildcard *.h)\n</code></pre>\n\n<p>EDIT: in order to match a specific list, do</p>\n\n<pre><code>$(wildcard $(HEADER_FILES))\n</code></pre>\n\n<p>There is no need to use $(filter ...), the wildcard function automatically filters files which don't exist.</p>\n" }, { "answer_id": 250795, "author": "m0j0", "author_id": 31319, "author_profile": "https://Stackoverflow.com/users/31319", "pm_score": 3, "selected": false, "text": "<p>You didn't specify what compiler(s) you are using, but if you have access to gcc/g++ you can use the -MM option. </p>\n\n<p>What I do is create a file with the extension of .d for every .c or .cpp file, and then \"include\" the .d files. I use something like this in my Makefile:</p>\n\n<pre><code>%.d: %.c\n gcc $(INCS) $(CFLAGS) -MM $&lt; -MF $@\n\n%.d: %.cpp\n g++ $(INCS) $(CXXFLAGS) -MM $&lt; -MF $@\n</code></pre>\n\n<p>I then create the dependencies like this:</p>\n\n<pre><code>C_DEPS=$(C_SRCS:.c=.d)\nCPP_DEPS=$(CPP_SRCS:.cpp=.d)\nDEPS=$(C_DEPS) $(CPP_DEPS)\n</code></pre>\n\n<p>and this at the bottom of the Makefile:</p>\n\n<pre><code>include $(DEPS)\n</code></pre>\n\n<p>Is this the kind of behavior you're going for? The beauty of this method is that even if you're using a non-GNU compiler for actual compiling, the GNU compilers do a good job of calculating the dependencies.</p>\n" }, { "answer_id": 250831, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 2, "selected": false, "text": "<p>Does the simple</p>\n\n<pre><code>$(filter $(wildcard *.h),$(HEADER_FILES))\n</code></pre>\n\n<p>do what you want?</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7136/" ]
I have a makefile template to compile a single DLL (for a plugin system). The makefile of the user looks like this: ``` EXTRA_SRCS=file1 file2 include makefile.in ``` In the `makefile.in` I have: ``` plugin.dll: plugin.os $(patsubst %,%.os,$(EXTRA_SRCS)) ``` Where `plugin.os` is the main C++ file to be compiled. Btw, the files ending is `.os` are the object files compiled for shared library (i.e. using the `-fpic` option with `gcc`) Now, the problem is that the extra sources will probably (but not necessarily) be header files. Ideally I would like to add them as dependencies for the target `plugin.os` and the `file.cpp`, but only if they exist. The method should work for both windows and linux, or at least be adaptable to each. However, I only use the GNU version of make.
Use the "wildcard" function: ``` $(wildcard *.h) ``` EDIT: in order to match a specific list, do ``` $(wildcard $(HEADER_FILES)) ``` There is no need to use $(filter ...), the wildcard function automatically filters files which don't exist.
250,096
<p>I'm trying to code opposite action to this:</p> <pre><code>std::ostream outs; // properly initialized of course std::set&lt;int&gt; my_set; // ditto outs &lt;&lt; my_set.size(); std::copy( my_set.begin(), my_set.end(), std::ostream_iterator&lt;int&gt;( outs ) ); </code></pre> <p>it should be something like this:</p> <pre><code>std::istream ins; std::set&lt;int&gt;::size_type size; ins &gt;&gt; size; std::copy( std::istream_iterator&lt;int&gt;( ins ), std::istream_iterator&lt;int&gt;( ins ) ???, std::inserter( my_set, my_set.end() ) ); </code></pre> <p>But I'm stuck with the 'end' iterator -- input interators can't use std::advance and neither I can use two streams with the same source...</p> <p>Is there any elegant way how to solve this? Of course I can use for loop, but maybe there's something nicer :)</p>
[ { "answer_id": 250160, "author": "sdg", "author_id": 3529, "author_profile": "https://Stackoverflow.com/users/3529", "pm_score": 0, "selected": false, "text": "<p>(Edited: I should have read the question closer...)</p>\n\n<p>While somewhat suspect, you can get approximately the right behavior by having an entry in the file that will \"fail\" the first loop, then clear the fail bit on the stream and start reading more.</p>\n\n<p>Data, without an explicit size, but like this</p>\n\n<pre>\n1 1 2 3 5 8 Fibb\n</pre>\n\n<p>Fed to the code below seems to do what I meant, at least on VS2005 with STLPort.</p>\n\n<pre>\ntypedef std::istream_iterator &lt; int, char, std::char_traits ,ptrdiff_t> is_iter;\nstd::copy( is_iter(cin), is_iter(), inserter(my_set,my_set.end()));\ncin.clear();\nstd::cin >> instr;\n</pre>\n" }, { "answer_id": 250169, "author": "Miro Kropacek", "author_id": 21009, "author_profile": "https://Stackoverflow.com/users/21009", "pm_score": 0, "selected": false, "text": "<p>Yes sdg but when I want to use another data structures in that file / stream? I should probably explicitly write here, I want to store another stuff after this set, this is the reason why I'm storing the size as well.</p>\n" }, { "answer_id": 250237, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Errr... <a href=\"http://www.sgi.com/tech/stl/copy_n.html\" rel=\"nofollow noreferrer\">copy_n()</a> algorithm?</p>\n" }, { "answer_id": 250380, "author": "Dominik Grabiec", "author_id": 3719, "author_profile": "https://Stackoverflow.com/users/3719", "pm_score": 2, "selected": false, "text": "<p>Looking into this a bit I don't think reading directly into a set will work, as you need to call insert on it to actually add the elements (I could be mistaken, it is rather early in the morning here). Though looking at the STL documentation in VS2005 briefly I think something using the generate_n function should work, for instance:</p>\n\n<pre><code>std::istream ins;\nstd::set&lt;int&gt; my_set;\nstd::vector&lt;int&gt; my_vec;\n\nstruct read_functor\n{\n read_functor(std::istream&amp; stream) :\n m_stream(stream)\n {\n }\n\n int operator()\n {\n int temp;\n m_stream &gt;&gt; temp;\n return temp;\n }\nprivate:\n std::istream&amp; m_stream;\n};\n\nstd::set&lt;int&gt;::size_type size;\nins &gt;&gt; size;\nmy_vec.reserve(size);\n\nstd::generate_n(my_vec.begin(), size, read_functor(ins));\nmy_set.insert(my_vec.begin(), my_vec.end());\n</code></pre>\n\n<p>Hopefully that's either solved your problem, or convinced you that the loop isn't that bad in the grand scheme of things.</p>\n" }, { "answer_id": 250745, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 3, "selected": true, "text": "<p>You could derive from the istream_iterator&lt;T&gt;.<br>\nThough using <a href=\"https://stackoverflow.com/questions/250096/how-to-read-arbitrary-number-of-bytes-using-stdcopy#250380\">Daemin generator method</a> is another option, though I would generate directly into the set rather than use an intermediate vector.</p>\n\n<pre><code>#include &lt;set&gt;\n#include &lt;iterator&gt;\n#include &lt;algorithm&gt;\n#include &lt;iostream&gt;\n\n\ntemplate&lt;typename T&gt;\nstruct CountIter: public std::istream_iterator&lt;T&gt;\n{\n CountIter(size_t c)\n :std::istream_iterator&lt;T&gt;()\n ,count(c)\n {}\n CountIter(std::istream&amp; str)\n :std::istream_iterator&lt;T&gt;(str)\n ,count(0)\n {}\n\n bool operator!=(CountIter const&amp; rhs) const\n {\n return (count != rhs.count) &amp;&amp; (dynamic_cast&lt;std::istream_iterator&lt;T&gt; const&amp;&gt;(*this) != rhs);\n }\n T operator*()\n {\n ++count;\n return std::istream_iterator&lt;T&gt;::operator*();\n }\n\n private:\n size_t count;\n};\n\nint main()\n{\n std::set&lt;int&gt; x;\n\n //std::copy(std::istream_iterator&lt;int&gt;(std::cin),std::istream_iterator&lt;int&gt;(),std::inserter(x,x.end()));\n std::copy(\n CountIter&lt;int&gt;(std::cin),\n CountIter&lt;int&gt;(5),\n std::inserter(x,x.end())\n );\n}\n</code></pre>\n" }, { "answer_id": 252834, "author": "Dean Michael", "author_id": 11274, "author_profile": "https://Stackoverflow.com/users/11274", "pm_score": 1, "selected": false, "text": "<p>How about using an alternate iterator to do the traversal and then use a function object (or lambda) to fill in the container?</p>\n\n<pre><code>istream ins;\nset&lt;int&gt;::size_type size;\nset&lt;int&gt; new_set;\nins &gt;&gt; size;\nostream_iterator&lt;int&gt; ins_iter(ins);\n\nfor_each(counting_iterator&lt;int&gt;(0), counting_iterator&lt;int&gt;(size),\n [&amp;new_set, &amp;ins_iter](int n) { new_set.insert(*ins_iter++); }\n);\n</code></pre>\n\n<p>Of course this assumes you have a C++0x compliant compiler.</p>\n\n<p>BTW, 'counting_iterator&lt;>' is part of <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/iterator/doc/counting_iterator.html\" rel=\"nofollow noreferrer\">Boost.Iterator</a>.</p>\n" }, { "answer_id": 360344, "author": "Jeffrey Martinez", "author_id": 29703, "author_profile": "https://Stackoverflow.com/users/29703", "pm_score": 2, "selected": false, "text": "<p>Use:</p>\n\n<pre><code>std::copy( std::istream_iterator&lt;int&gt;(ins),\n std::istream_iterator&lt;int&gt;(),\n std::inserter(my_set, my_set.end())\n );\n</code></pre>\n\n<p>Note the empty parameter:</p>\n\n<pre><code>std::istream_iterator&lt;int&gt;();\n</code></pre>\n" }, { "answer_id": 5569467, "author": "jnyanez", "author_id": 695213, "author_profile": "https://Stackoverflow.com/users/695213", "pm_score": 1, "selected": false, "text": "<p>Or you could do this:</p>\n\n<pre><code>my_set.insert(std::istream_iterator&lt;int&gt;(ins), std::istream_iterator&lt;int&gt;());\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21009/" ]
I'm trying to code opposite action to this: ``` std::ostream outs; // properly initialized of course std::set<int> my_set; // ditto outs << my_set.size(); std::copy( my_set.begin(), my_set.end(), std::ostream_iterator<int>( outs ) ); ``` it should be something like this: ``` std::istream ins; std::set<int>::size_type size; ins >> size; std::copy( std::istream_iterator<int>( ins ), std::istream_iterator<int>( ins ) ???, std::inserter( my_set, my_set.end() ) ); ``` But I'm stuck with the 'end' iterator -- input interators can't use std::advance and neither I can use two streams with the same source... Is there any elegant way how to solve this? Of course I can use for loop, but maybe there's something nicer :)
You could derive from the istream\_iterator<T>. Though using [Daemin generator method](https://stackoverflow.com/questions/250096/how-to-read-arbitrary-number-of-bytes-using-stdcopy#250380) is another option, though I would generate directly into the set rather than use an intermediate vector. ``` #include <set> #include <iterator> #include <algorithm> #include <iostream> template<typename T> struct CountIter: public std::istream_iterator<T> { CountIter(size_t c) :std::istream_iterator<T>() ,count(c) {} CountIter(std::istream& str) :std::istream_iterator<T>(str) ,count(0) {} bool operator!=(CountIter const& rhs) const { return (count != rhs.count) && (dynamic_cast<std::istream_iterator<T> const&>(*this) != rhs); } T operator*() { ++count; return std::istream_iterator<T>::operator*(); } private: size_t count; }; int main() { std::set<int> x; //std::copy(std::istream_iterator<int>(std::cin),std::istream_iterator<int>(),std::inserter(x,x.end())); std::copy( CountIter<int>(std::cin), CountIter<int>(5), std::inserter(x,x.end()) ); } ```
250,137
<p>I have the following legacy code:</p> <pre><code>public class MyLegacyClass { private static final String jndiName = "java:comp/env/jdbc/LegacyDataSource" public static SomeLegacyClass doSomeLegacyStuff(SomeOtherLegacyClass legacyObj) { // do stuff using jndiName } } </code></pre> <p>This class is working in a J2EE-Container.</p> <p>Now I would like to test the class outside of the container.</p> <p>What is the best strategy? Refactoring is basically allowed.</p> <p>Accessing the LegacyDataSource is allowed (the test does not have to be a "pure" unit-test).</p> <p>EDIT: Introducing additional runtime-frameworks is not allowed.</p>
[ { "answer_id": 250146, "author": "Robin", "author_id": 21925, "author_profile": "https://Stackoverflow.com/users/21925", "pm_score": 2, "selected": false, "text": "<p>Refactor the code to use dependency injection. Then use you preferred DI framework (Spring, Guice, ...) to inject your resources. That will make it easy to switch between resource objects and strategies at runtime.</p>\n\n<p>In this case, you can inject your datasource.</p>\n\n<p>EDIT: Based on your new restriction, you can accomplish the same thing by using a strategy pattern to set your datasource at runtime. You can probably just use a properties file to distinguish which strategy to create and supply the datasource. This would require no new framework, you would just be hand coding the same basic functionality. We used this exact idea with a ServiceLocator to supply a mock datasource when testing outside of the Java EE container.</p>\n" }, { "answer_id": 250272, "author": "David Santamaria", "author_id": 24097, "author_profile": "https://Stackoverflow.com/users/24097", "pm_score": 1, "selected": false, "text": "<p>I think that the best solution here is bind that JNDI to a local </p>\n\n<p>The legacy Code is using the jndiName like that:</p>\n\n<pre><code>DataSource datasource = (DataSource)initialContext.lookup(DATASOURCE_CONTEXT);\n</code></pre>\n\n<p>So, The solution here is bind a local (or whatever you have for you test data) into a JNDI like that:</p>\n\n<pre><code> BasicDataSource dataSource = new BasicDataSource();\n dataSource.setDriverClassName(System.getProperty(\"driverClassName\"));\n dataSource.setUser(\"username\");\n dataSource.setPassword(\"password\");\n dataSource.setServerName(\"localhost\");\n dataSource.setPort(3306);\n dataSource.setDatabaseName(\"databasename\");\n</code></pre>\n\n<p>And then the binding:</p>\n\n<pre><code>Context context = new InitialContext();\ncontext.bind(\"java:comp/env/jdbc/LegacyDataSource\",datasource); \n</code></pre>\n\n<p>Or something similar, hope that helps you.</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 250635, "author": "Scott Bale", "author_id": 2495576, "author_profile": "https://Stackoverflow.com/users/2495576", "pm_score": 4, "selected": true, "text": "<p>Just to make @Robin's suggestion of a strategy pattern more concrete: (Notice that the public API of your original question remains unchanged.)</p>\n\n<pre><code>public class MyLegacyClass {\n\n private static Strategy strategy = new JNDIStrategy();\n\n public static SomeLegacyClass doSomeLegacyStuff(SomeOtherLegacyClass legacyObj) {\n // legacy logic\n SomeLegacyClass result = strategy.doSomeStuff(legacyObj);\n // more legacy logic\n return result;\n }\n\n static void setStrategy(Strategy strategy){\n MyLegacyClass.strategy = strategy;\n }\n\n}\n\ninterface Strategy{\n public SomeLegacyClass doSomeStuff(SomeOtherLegacyClass legacyObj);\n}\n\nclass JNDIStrategy implements Strategy {\n private static final String jndiName = \"java:comp/env/jdbc/LegacyDataSource\";\n\n public SomeLegacyClass doSomeStuff(SomeOtherLegacyClass legacyObj) {\n // do stuff using jndiName\n }\n}\n</code></pre>\n\n<p>...and JUnit test. I'm not a big fan of having to do this setup/teardown maintenance, but that's an unfortunate side effect of having an API based on static methods (or Singletons for that matter). What I <em>do</em> like about this test is it does not use JNDI - that's good because (a) it'll run fast, and (b) the unit test should only be testing the business logic in doSomeLegacyStuff() method anyway, not testing the actual data source. (By the way, this assumes the test class is in the same package as MyLegacyClass.)</p>\n\n<pre><code>public class MyLegacyClassTest extends TestCase {\n\n private MockStrategy mockStrategy = new MockStrategy();\n\n protected void setUp() throws Exception {\n MyLegacyClass.setStrategy(mockStrategy);\n }\n\n protected void tearDown() throws Exception {\n // TODO, reset original strategy on MyLegacyClass...\n }\n\n public void testDoSomeLegacyStuff() {\n MyLegacyClass.doSomeLegacyStuff(..);\n assertTrue(..);\n }\n\n static class MockStrategy implements Strategy{\n\n public SomeLegacyClass doSomeStuff(SomeOtherLegacyClass legacyObj) {\n // mock behavior however you want, record state however\n // you'd like for test asserts. Good frameworks like Mockito exist\n // to help create mocks\n }\n }\n}\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32749/" ]
I have the following legacy code: ``` public class MyLegacyClass { private static final String jndiName = "java:comp/env/jdbc/LegacyDataSource" public static SomeLegacyClass doSomeLegacyStuff(SomeOtherLegacyClass legacyObj) { // do stuff using jndiName } } ``` This class is working in a J2EE-Container. Now I would like to test the class outside of the container. What is the best strategy? Refactoring is basically allowed. Accessing the LegacyDataSource is allowed (the test does not have to be a "pure" unit-test). EDIT: Introducing additional runtime-frameworks is not allowed.
Just to make @Robin's suggestion of a strategy pattern more concrete: (Notice that the public API of your original question remains unchanged.) ``` public class MyLegacyClass { private static Strategy strategy = new JNDIStrategy(); public static SomeLegacyClass doSomeLegacyStuff(SomeOtherLegacyClass legacyObj) { // legacy logic SomeLegacyClass result = strategy.doSomeStuff(legacyObj); // more legacy logic return result; } static void setStrategy(Strategy strategy){ MyLegacyClass.strategy = strategy; } } interface Strategy{ public SomeLegacyClass doSomeStuff(SomeOtherLegacyClass legacyObj); } class JNDIStrategy implements Strategy { private static final String jndiName = "java:comp/env/jdbc/LegacyDataSource"; public SomeLegacyClass doSomeStuff(SomeOtherLegacyClass legacyObj) { // do stuff using jndiName } } ``` ...and JUnit test. I'm not a big fan of having to do this setup/teardown maintenance, but that's an unfortunate side effect of having an API based on static methods (or Singletons for that matter). What I *do* like about this test is it does not use JNDI - that's good because (a) it'll run fast, and (b) the unit test should only be testing the business logic in doSomeLegacyStuff() method anyway, not testing the actual data source. (By the way, this assumes the test class is in the same package as MyLegacyClass.) ``` public class MyLegacyClassTest extends TestCase { private MockStrategy mockStrategy = new MockStrategy(); protected void setUp() throws Exception { MyLegacyClass.setStrategy(mockStrategy); } protected void tearDown() throws Exception { // TODO, reset original strategy on MyLegacyClass... } public void testDoSomeLegacyStuff() { MyLegacyClass.doSomeLegacyStuff(..); assertTrue(..); } static class MockStrategy implements Strategy{ public SomeLegacyClass doSomeStuff(SomeOtherLegacyClass legacyObj) { // mock behavior however you want, record state however // you'd like for test asserts. Good frameworks like Mockito exist // to help create mocks } } } ```
250,157
<p>When you have a complex property, should you instantiate it or leave it to the user to instantiate it?</p> <p>For example (C#)</p> <p>A)</p> <pre><code> class Xyz{ List&lt;String&gt; Names {get; set;} } </code></pre> <p>When I try to use, I have to set it.</p> <pre><code>... Xyz xyz = new Xyz(); xyz.Name = new List&lt;String&gt;(); xyz.Name.Add("foo"); ... </code></pre> <p>Where as if I modify the code</p> <p>B)</p> <pre><code> class Xyz{ public Xyz(){ Names = new List&lt;String&gt;(); } List&lt;String&gt; Names {get; } } </code></pre> <p>which in this case, I can make the List read-only.</p> <p>Another scenario might arise, I suppose where you would intentionally not want to set it. For example in</p> <p>C)</p> <pre><code> class Xyz{ String Name {get; set;} } </code></pre> <p>I would thing it bad practice to initialize.</p> <p>Are there some rules of thumb for such scenarios?</p>
[ { "answer_id": 250193, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 2, "selected": false, "text": "<p>This is my normal solution:</p>\n\n<pre><code>class XYZ \n{\n public XYZ () { Names = new List&lt;string&gt;(); }\n public List&lt;string&gt; Names { get; private set; }\n}\n</code></pre>\n\n<p><s>(Note that it doesn't work with XmlSerialization, as you need getters and setters on all XmlSerialized properties.) (You can override this, but it seems like too much work for little effort).</s></p>\n\n<p>As <a href=\"https://stackoverflow.com/users/20363/oregonghost\">OregonGhost</a> pointed out - you need to add <code>[XmlArray]</code> for this to work with XmlSerialization.</p>\n\n<p>This still breaks the rules of encapsulation, as if you wanted to be entirely correct, you would have:</p>\n\n<pre><code>class XYZ \n{\n public XYZ () { AllNames = new List&lt;string&gt;(); }\n private List&lt;string&gt; AllNames { get; set; }\n public void AddName ( string name ) { AllNames.Add(name); }\n public IEnumerable&lt;string&gt; Names { get { return AllNames.AsReadOnly(); } }\n}\n</code></pre>\n\n<p>As this goes against the design of almost all the rest of the .Net framework, I usually end up using the first solution.</p>\n\n<p>However, this does have the added benefit that XYZ can track the changes to it's collection of names, and that XYZ is the only place where the collection of names can be modified.</p>\n\n<p>I have implemented this for a few cases, but it causes too much friction with other programmers when I do it for everything.</p>\n" }, { "answer_id": 250199, "author": "Morgan Cheng", "author_id": 26349, "author_profile": "https://Stackoverflow.com/users/26349", "pm_score": 1, "selected": false, "text": "<p>It really depends.</p>\n\n<p>If the class is supposed to operate correctly with a null property, you can leave it as un-initialized. Otherwise, you'd better initialize it in constructor.</p>\n\n<p>And, if you don't want the property to be changed after construction, you can have it private</p>\n\n<pre><code>class Xyz\n{\n public Xyz(string name)\n {\n this.Name = name;\n }\n String Name \n {\n get; \n private set;\n }\n}\n</code></pre>\n" }, { "answer_id": 250200, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 2, "selected": false, "text": "<p>As a rule of thumb (meaning there will always be exceptions from that rule) set your member in the constructor. That's what the constructor is for.</p>\n\n<p>Remember one of the ideas beind OO is abstraction. Requiring the 'user' (i.e. the programmer who wants to instantiate your object in his source code) to do that is\na violation of the abstraction principle. It would be one more thing the user must think of before using your object, hence one more potential source for errors.</p>\n" }, { "answer_id": 250204, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Yes, there are rules of thumb. Code analysis tools are a good start for this.</p>\n\n<p>Some rules of thumb about your code in question:</p>\n\n<p>Its bad practice to allow setters on collection properties. This is because its simple to treat empty collections just like full ones in code. Forcing people to do null checks on collections will get you beaten. Consider the following code snippet:</p>\n\n<pre><code>public bool IsValid(object input){\n foreach(var validator in this.Validators)\n if(!validator.IsValid(input)\n return false;\n return true;\n}\n</code></pre>\n\n<p>This code works whether or not the collection of validators is empty or not. If you wish validation, add validators to the collection. If not, leave the collection empty. Simple. Allowing the collection property to be null results in this smelly code version of the above:</p>\n\n<pre><code>public bool IsValid(object input){\n if(this.Validators == null) \n return false;\n foreach(var validator in this.Validators)\n if(!validator.IsValid(input)\n return false;\n return true;\n}\n</code></pre>\n\n<p>More lines of code, less elegant. </p>\n\n<p>Secondly, for reference types OTHER than collections, you must consider how the object behaves when determining if you want to set property values. Is there a single, obvious, default value for the property? Or does a null value for the property have a valid meaning? </p>\n\n<p>In your example, you may wish to always check,in the setter, the Name value and set it to a default \"(No name given)\" when assigned a null. This may make it easier when binding this object against UI. Or, the name may be null because you REQUIRE a valid name, and you will be checking it and throwing an InvalidOperationException when the caller tries to perform an action on the object without first setting the name.</p>\n\n<p>Like most things in programming, there are a bunch of different ways to do something, half of which are bad, and each way in the other half are good only in certain circumstances.</p>\n" }, { "answer_id": 250339, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "<p>The purpose of a constructor is the <strong>construct</strong> the object. No further \"setup\" should be necessary. If there is some information which on the caller knows, then that should be passed to the constructor:</p>\n\n<p><strong>Wrong:</strong></p>\n\n<pre><code>MyClass myc = new MyClass();\nmyc.SomeProp = 5;\nmyc.DoSomething();\n</code></pre>\n\n<p><strong>Right:</strong></p>\n\n<pre><code>MyClass myc = new MyClass(5);\nmyc.DoSomething();\n</code></pre>\n\n<p>This is especially true if SomeProp needs to be set for myc to be in a valid state. </p>\n" }, { "answer_id": 3431143, "author": "Jerod Houghtelling", "author_id": 373521, "author_profile": "https://Stackoverflow.com/users/373521", "pm_score": 0, "selected": false, "text": "<p>If possible you should try to encapsulate your data. Exposing the object as a list requires the user to know a too many intimate details about the class. For example, they have to know whether or not they have to create the list from scratch to avoid a null reference exception. </p>\n\n<pre><code>public class Xyz\n{\n private List&lt;String&gt; _names = new List&lt;String&gt;(); // could also set in constructor\n\n public IEnumerable&lt;String&gt; Names\n {\n get\n {\n return _names;\n }\n }\n\n public void AddName( string name )\n {\n _names.Add( name );\n }\n}\n</code></pre>\n\n<p>Now it doesn't matter if you use a List, HashTable, Dictionary, etc.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2017/" ]
When you have a complex property, should you instantiate it or leave it to the user to instantiate it? For example (C#) A) ``` class Xyz{ List<String> Names {get; set;} } ``` When I try to use, I have to set it. ``` ... Xyz xyz = new Xyz(); xyz.Name = new List<String>(); xyz.Name.Add("foo"); ... ``` Where as if I modify the code B) ``` class Xyz{ public Xyz(){ Names = new List<String>(); } List<String> Names {get; } } ``` which in this case, I can make the List read-only. Another scenario might arise, I suppose where you would intentionally not want to set it. For example in C) ``` class Xyz{ String Name {get; set;} } ``` I would thing it bad practice to initialize. Are there some rules of thumb for such scenarios?
This is my normal solution: ``` class XYZ { public XYZ () { Names = new List<string>(); } public List<string> Names { get; private set; } } ``` ~~(Note that it doesn't work with XmlSerialization, as you need getters and setters on all XmlSerialized properties.) (You can override this, but it seems like too much work for little effort).~~ As [OregonGhost](https://stackoverflow.com/users/20363/oregonghost) pointed out - you need to add `[XmlArray]` for this to work with XmlSerialization. This still breaks the rules of encapsulation, as if you wanted to be entirely correct, you would have: ``` class XYZ { public XYZ () { AllNames = new List<string>(); } private List<string> AllNames { get; set; } public void AddName ( string name ) { AllNames.Add(name); } public IEnumerable<string> Names { get { return AllNames.AsReadOnly(); } } } ``` As this goes against the design of almost all the rest of the .Net framework, I usually end up using the first solution. However, this does have the added benefit that XYZ can track the changes to it's collection of names, and that XYZ is the only place where the collection of names can be modified. I have implemented this for a few cases, but it causes too much friction with other programmers when I do it for everything.
250,166
<p>I have an application that I'm trying to wrap into a jar for easier deployment. The application compiles and runs fine (in a Windows cmd window) when run as a set of classes reachable from the CLASSPATH. But when I jar up my classes and try to run it with java 1.6 in the same cmd window, I start getting exceptions:</p> <pre><code>C:\dev\myapp\src\common\datagen&gt;C:/apps/jdk1.6.0_07/bin/java.exe -classpath C:\myapp\libs\commons -logging-1.1.jar -server -jar DataGen.jar Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory at com.example.myapp.fomc.common.datagen.DataGenerationTest.&lt;clinit&gt;(Unknown Source) Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) ... 1 more </code></pre> <p>The funny thing is, the offending LogFactory seems to be in commons-logging-1.1.jar, which is in the class path specified. The jar file (yep, it's really there):</p> <pre><code>C:\dev\myapp\src\common\datagen&gt;dir C:\myapp\libs\commons-logging-1.1.jar Volume in drive C is Local Disk Volume Serial Number is ECCD-A6A7 Directory of C:\myapp\libs 12/11/2007 11:46 AM 52,915 commons-logging-1.1.jar 1 File(s) 52,915 bytes 0 Dir(s) 10,956,947,456 bytes free </code></pre> <p>The contents of the commons-logging-1.1.jar file:</p> <pre><code>C:\dev\myapp\src\common\datagen&gt;jar -tf C:\myapp\libs\commons-logging-1.1.jar META-INF/ META-INF/MANIFEST.MF org/ org/apache/ org/apache/commons/ org/apache/commons/logging/ org/apache/commons/logging/impl/ META-INF/LICENSE.txt META-INF/NOTICE.txt org/apache/commons/logging/Log.class org/apache/commons/logging/LogConfigurationException.class org/apache/commons/logging/LogFactory$1.class org/apache/commons/logging/LogFactory$2.class org/apache/commons/logging/LogFactory$3.class org/apache/commons/logging/LogFactory$4.class org/apache/commons/logging/LogFactory$5.class org/apache/commons/logging/LogFactory.class ... (more classes in commons-logging-1.1 ...) </code></pre> <p>Yep, commons-logging has the LogFactory class. And finally, the contents of my jar's manifest:</p> <pre><code>Manifest-Version: 1.0 Ant-Version: Apache Ant 1.6.5 Created-By: 10.0-b23 (Sun Microsystems Inc.) Main-Class: com.example.myapp.fomc.common.datagen.DataGenerationTest Class-Path: commons-logging-1.1.jar commons-lang.jar antlr.jar toplink .jar GroboTestingJUnit-1.2.1-core.jar junit.jar </code></pre> <p>This has stumped me, and any coworkers I've bugged for more than a day now. Just to cull the answers, for now at least, third party solutions to this are probably out due to licensing restrictions and company policies (e.g.: tools for creating exe's or packaging up jars). The ultimate goal is to create a jar that can be copied from my development Windows box to a Linux server (with any dependent jars) and used to populate a database (so classpaths may wind up being different between development and deployment environments). Any clues to this mystery would be greatly appreciated!</p>
[ { "answer_id": 250173, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 7, "selected": true, "text": "<p>The -jar option is mutually exclusive of -classpath. See an old description <a href=\"http://download.java.net/jdk8u20/docs/technotes/tools/windows/java.html\" rel=\"noreferrer\">here</a></p>\n<blockquote>\n<p>-jar</p>\n<p>Execute a program encapsulated in a JAR file. The first argument is the name of a JAR file instead of a startup class name. In order for this option to work, the manifest of the JAR file must contain a line of the form Main-Class: classname. Here, classname identifies the class having the public static void main(String[] args) method that serves as your application's starting point.</p>\n<p>See the Jar tool reference page and the Jar trail of the Java Tutorial for information about working with Jar files and Jar-file manifests.</p>\n<p><em><strong>When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.</strong></em></p>\n</blockquote>\n<p>A quick and dirty hack is to append your classpath to the bootstrap classpath:</p>\n<blockquote>\n<p>-Xbootclasspath/a:<em><strong>path</strong></em></p>\n<p>Specify a colon-separated path of directires, JAR archives, and ZIP archives to append to the default bootstrap class path.</p>\n</blockquote>\n<p>However, as <a href=\"https://stackoverflow.com/users/5171/dan-dyer\">@Dan</a> rightly says, the correct solution is to ensure your JARs Manifest contains the classpath for all JARs it will need.</p>\n" }, { "answer_id": 250288, "author": "flash", "author_id": 25909, "author_profile": "https://Stackoverflow.com/users/25909", "pm_score": 2, "selected": false, "text": "<p>if you use external libraries in your program and you try to pack all together in a jar file it's not that simple, because of classpath issues etc.</p>\n\n<p>I'd prefer to use <a href=\"http://one-jar.sourceforge.net/\" rel=\"nofollow noreferrer\">OneJar</a> for this issue.</p>\n" }, { "answer_id": 8838405, "author": "g_tom", "author_id": 1145934, "author_profile": "https://Stackoverflow.com/users/1145934", "pm_score": 5, "selected": false, "text": "<p>You can omit the <code>-jar</code> option and start the jar file like this:</p>\n\n<p><code>java -cp MyJar.jar;C:\\externalJars\\* mainpackage.MyMainClass</code></p>\n" }, { "answer_id": 8842917, "author": "Mary C", "author_id": 1146507, "author_profile": "https://Stackoverflow.com/users/1146507", "pm_score": 0, "selected": false, "text": "<p>I have found when I am using a manifest that the listing of jars for the classpath need to have a space after the listing of each jar e.g. \"required_lib/sun/pop3.jar required_lib/sun/smtp.jar \". Even if it is the last in the list. </p>\n" }, { "answer_id": 12282945, "author": "Gautam Mandsorwale", "author_id": 1275496, "author_profile": "https://Stackoverflow.com/users/1275496", "pm_score": 4, "selected": false, "text": "<p>This is the problem that is occurring,</p>\n\n<p>if the JAR file was loaded from \"C:\\java\\apps\\appli.jar\", and your manifest file has the Class-Path: reference \"lib/other.jar\", the class loader will look in \"C:\\java\\apps\\lib\\\" for \"other.jar\". It won't look at the JAR file entry \"lib/other.jar\".</p>\n\n<p><strong>Solution:-</strong></p>\n\n<ol>\n<li>Right click on project, Select Export.</li>\n<li>Select Java Folder and in it select Runnable JAR File instead of JAR file.</li>\n<li>Select the proper options and in the Library Handling section select the 3rd option i.e. (Copy required libraries into a sub-folder next to the generated JAR).</li>\n</ol>\n\n<p><em>[ <strong>EDIT</strong> = 3rd option generates a folder in addition to the jar, 2nd option (\"Package required libraries into generated JAR\") can also be used as you have the jar. ]</em></p>\n\n<ol start=\"4\">\n<li>Click finish and your JAR is created at the specified position along with a folder that contains the JARS mentioned in the manifest file.</li>\n<li><p>open the terminal,give the proper path to your jar and run it using this command java -jar abc.jar </p>\n\n<p>Now what will happen is the class loader will look in the correct folder for the referenced JARS since now they are present in the same folder that contains your app JAR..There is no \"java.lang.NoClassDefFoundError\" exception thrown now.</p></li>\n</ol>\n\n<p>This worked for me... Hope it works for you too!!!</p>\n" }, { "answer_id": 33800968, "author": "mouhcine", "author_id": 5580667, "author_profile": "https://Stackoverflow.com/users/5580667", "pm_score": 2, "selected": false, "text": "<p>i had the same problem with my jar\nthe solution</p>\n<ol>\n<li>Create the MANIFEST.MF file:</li>\n</ol>\n<blockquote>\n<p>Manifest-Version: 1.0</p>\n<p>Sealed: true</p>\n<p>Class-Path: . lib/jarX1.jar lib/jarX2.jar lib/jarX3.jar</p>\n<p>Main-Class: com.MainClass</p>\n</blockquote>\n<ol start=\"2\">\n<li>Right click on project, Select Export.</li>\n</ol>\n<blockquote>\n<p>select export all outpout folders for checked project</p>\n</blockquote>\n<ol start=\"3\">\n<li>select using existing manifest from workspace and select the MANIFEST.MF file</li>\n</ol>\n<p>This worked for me :)</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13140/" ]
I have an application that I'm trying to wrap into a jar for easier deployment. The application compiles and runs fine (in a Windows cmd window) when run as a set of classes reachable from the CLASSPATH. But when I jar up my classes and try to run it with java 1.6 in the same cmd window, I start getting exceptions: ``` C:\dev\myapp\src\common\datagen>C:/apps/jdk1.6.0_07/bin/java.exe -classpath C:\myapp\libs\commons -logging-1.1.jar -server -jar DataGen.jar Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory at com.example.myapp.fomc.common.datagen.DataGenerationTest.<clinit>(Unknown Source) Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) ... 1 more ``` The funny thing is, the offending LogFactory seems to be in commons-logging-1.1.jar, which is in the class path specified. The jar file (yep, it's really there): ``` C:\dev\myapp\src\common\datagen>dir C:\myapp\libs\commons-logging-1.1.jar Volume in drive C is Local Disk Volume Serial Number is ECCD-A6A7 Directory of C:\myapp\libs 12/11/2007 11:46 AM 52,915 commons-logging-1.1.jar 1 File(s) 52,915 bytes 0 Dir(s) 10,956,947,456 bytes free ``` The contents of the commons-logging-1.1.jar file: ``` C:\dev\myapp\src\common\datagen>jar -tf C:\myapp\libs\commons-logging-1.1.jar META-INF/ META-INF/MANIFEST.MF org/ org/apache/ org/apache/commons/ org/apache/commons/logging/ org/apache/commons/logging/impl/ META-INF/LICENSE.txt META-INF/NOTICE.txt org/apache/commons/logging/Log.class org/apache/commons/logging/LogConfigurationException.class org/apache/commons/logging/LogFactory$1.class org/apache/commons/logging/LogFactory$2.class org/apache/commons/logging/LogFactory$3.class org/apache/commons/logging/LogFactory$4.class org/apache/commons/logging/LogFactory$5.class org/apache/commons/logging/LogFactory.class ... (more classes in commons-logging-1.1 ...) ``` Yep, commons-logging has the LogFactory class. And finally, the contents of my jar's manifest: ``` Manifest-Version: 1.0 Ant-Version: Apache Ant 1.6.5 Created-By: 10.0-b23 (Sun Microsystems Inc.) Main-Class: com.example.myapp.fomc.common.datagen.DataGenerationTest Class-Path: commons-logging-1.1.jar commons-lang.jar antlr.jar toplink .jar GroboTestingJUnit-1.2.1-core.jar junit.jar ``` This has stumped me, and any coworkers I've bugged for more than a day now. Just to cull the answers, for now at least, third party solutions to this are probably out due to licensing restrictions and company policies (e.g.: tools for creating exe's or packaging up jars). The ultimate goal is to create a jar that can be copied from my development Windows box to a Linux server (with any dependent jars) and used to populate a database (so classpaths may wind up being different between development and deployment environments). Any clues to this mystery would be greatly appreciated!
The -jar option is mutually exclusive of -classpath. See an old description [here](http://download.java.net/jdk8u20/docs/technotes/tools/windows/java.html) > > -jar > > > Execute a program encapsulated in a JAR file. The first argument is the name of a JAR file instead of a startup class name. In order for this option to work, the manifest of the JAR file must contain a line of the form Main-Class: classname. Here, classname identifies the class having the public static void main(String[] args) method that serves as your application's starting point. > > > See the Jar tool reference page and the Jar trail of the Java Tutorial for information about working with Jar files and Jar-file manifests. > > > ***When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.*** > > > A quick and dirty hack is to append your classpath to the bootstrap classpath: > > -Xbootclasspath/a:***path*** > > > Specify a colon-separated path of directires, JAR archives, and ZIP archives to append to the default bootstrap class path. > > > However, as [@Dan](https://stackoverflow.com/users/5171/dan-dyer) rightly says, the correct solution is to ensure your JARs Manifest contains the classpath for all JARs it will need.
250,191
<p>I have a menu of product brands that I want to split over 4 columns. So if I have 39 brands, then I want the maximum item count for each column to be 10 (with a single gap in the last column. Here's how I'm calculating the item count for a column (using C#):</p> <pre><code>int ItemCount = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(BrandCount) / 4m)); </code></pre> <p>All that conversion seems really ugly to me. Is there a better way to do math on integers in C#?</p>
[ { "answer_id": 250205, "author": "GavinCattell", "author_id": 21644, "author_profile": "https://Stackoverflow.com/users/21644", "pm_score": 3, "selected": false, "text": "<p>A longer alternative with Mod.</p>\n\n<pre><code>ItemCount = BrandCount / 4;\nif (BrandCount%4 &gt; 0) ItemCount++;\n</code></pre>\n" }, { "answer_id": 250206, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 5, "selected": true, "text": "<p>You can cast:</p>\n\n<pre><code>int ItemCount = (int) Math.Ceiling( (decimal)BrandCount / 4m );\n</code></pre>\n\n<p>Also, because <code>int</code>/<code>decimal</code> results in a <code>decimal</code> you can remove one of the casts:</p>\n\n<pre><code>int ItemCount = (int) Math.Ceiling( BrandCount / 4m );\n</code></pre>\n" }, { "answer_id": 250211, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 2, "selected": false, "text": "<p>Perhaps try something like this ... Assuming <code>BrandCount</code> is an integer. You still have the same casts, but it might be clearer:</p>\n\n<pre><code>int ItemCount = (int)(Math.Ceiling(BrandCount / 4m));\n</code></pre>\n\n<p>I'm not a huge fan of the <code>Convert</code> class, and I avoid it whenever possible. It always seems to make my code illegible.</p>\n" }, { "answer_id": 250266, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 4, "selected": false, "text": "<p>Why are you even using a decimal? </p>\n\n<pre><code>int ItemCount = (BrandCount+3)/4;\n</code></pre>\n\n<p>The <code>+3</code> makes sure you round up rather than down:</p>\n\n<pre><code>(37+3)/4 == 40/4 == 10\n(38+3)/4 == 41/4 == 10\n(39+3)/4 == 42/4 == 10\n(40+3)/4 == 43/4 == 10\n</code></pre>\n\n<p>In general:</p>\n\n<pre><code>public uint DivUp(uint num, uint denom)\n{\n return (num + denom - 1) / denom;\n}\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/203/" ]
I have a menu of product brands that I want to split over 4 columns. So if I have 39 brands, then I want the maximum item count for each column to be 10 (with a single gap in the last column. Here's how I'm calculating the item count for a column (using C#): ``` int ItemCount = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(BrandCount) / 4m)); ``` All that conversion seems really ugly to me. Is there a better way to do math on integers in C#?
You can cast: ``` int ItemCount = (int) Math.Ceiling( (decimal)BrandCount / 4m ); ``` Also, because `int`/`decimal` results in a `decimal` you can remove one of the casts: ``` int ItemCount = (int) Math.Ceiling( BrandCount / 4m ); ```
250,197
<p>I am attempting to compose a style sheet that, given an XML input (obviously) and a parameter that specifies a "target", will produce a list of commands that match that target. Here is the style sheet as written:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"&gt; &lt;xsl:param name="target" select="cora_cmd"/&gt; &lt;xsl:output method="xml" indent="yes"/&gt; &lt;xsl:template match="command/program"&gt; &lt;xsl:if test="@name=$target"&gt; &lt;xsl:message terminate="no"&gt;found match &lt;xsl:value-of select="$target"/&gt; &lt;/xsl:message&gt; &lt;xi:include xmlns:xi="http://www.w3.org/2003/XInclude"&gt; &lt;xsl:attribute name="href"&gt;&lt;xsl:value-of select="../@help"/&gt;&lt;/xsl:attribute&gt; &lt;/xi:include&gt; &lt;/xsl:if&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p>I am invoking xsltproc to execute this style sheet as follows:</p> <pre><code>xsltproc --param target cora_cmd gen-commands.xsl commands.xml </code></pre> <p>The problem that I am encountering is that the parameter value for target does not seem to get set. At least the name that comes from the message appears to be an empty string and the test for xsl:if always fails. I am certain that this is due to some bone-headed mistake on my part but I've yet to recognise it. Does anybody know what I've done wrong?</p>
[ { "answer_id": 250337, "author": "Tim C", "author_id": 7585, "author_profile": "https://Stackoverflow.com/users/7585", "pm_score": 6, "selected": true, "text": "<p>If I have understood the question correctly, I think you need to use 'stringparam' as the option to call xsltproc, assuming you are passing a string value to match, and not an XPath expression.</p>\n\n<pre><code>xsltproc --stringparam target cora_cmd gen-commands.xsl commands.xml\n</code></pre>\n" }, { "answer_id": 259119, "author": "ChuckB", "author_id": 28605, "author_profile": "https://Stackoverflow.com/users/28605", "pm_score": 3, "selected": false, "text": "<p>In your declaration of the 'target' parameter in the stylesheet, you should quote the <code>@select</code> value if you want it to function as a default value when the parameter is not used on the command line:</p>\n\n<pre><code>&lt;xsl:param name=\"target\" select=\"'cora_cmd'\"/&gt;\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19674/" ]
I am attempting to compose a style sheet that, given an XML input (obviously) and a parameter that specifies a "target", will produce a list of commands that match that target. Here is the style sheet as written: ``` <?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:param name="target" select="cora_cmd"/> <xsl:output method="xml" indent="yes"/> <xsl:template match="command/program"> <xsl:if test="@name=$target"> <xsl:message terminate="no">found match <xsl:value-of select="$target"/> </xsl:message> <xi:include xmlns:xi="http://www.w3.org/2003/XInclude"> <xsl:attribute name="href"><xsl:value-of select="../@help"/></xsl:attribute> </xi:include> </xsl:if> </xsl:template> </xsl:stylesheet> ``` I am invoking xsltproc to execute this style sheet as follows: ``` xsltproc --param target cora_cmd gen-commands.xsl commands.xml ``` The problem that I am encountering is that the parameter value for target does not seem to get set. At least the name that comes from the message appears to be an empty string and the test for xsl:if always fails. I am certain that this is due to some bone-headed mistake on my part but I've yet to recognise it. Does anybody know what I've done wrong?
If I have understood the question correctly, I think you need to use 'stringparam' as the option to call xsltproc, assuming you are passing a string value to match, and not an XPath expression. ``` xsltproc --stringparam target cora_cmd gen-commands.xsl commands.xml ```
250,207
<p>How to host the WCF service in windows service?</p> <p>Thanks Sekar</p>
[ { "answer_id": 250229, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I just saw this today come across Channel 9:</p>\n\n<p><a href=\"http://channel9.msdn.com/shows/Endpoint/endpointtv-Screencast-Hosting-WCF-Services-in-Windows-Services/\" rel=\"nofollow noreferrer\">http://channel9.msdn.com/shows/Endpoint/endpointtv-Screencast-Hosting-WCF-Services-in-Windows-Services/</a></p>\n" }, { "answer_id": 250231, "author": "John Sibly", "author_id": 1078, "author_profile": "https://Stackoverflow.com/users/1078", "pm_score": 3, "selected": false, "text": "<p>I thought this article did a pretty good job of covering the steps required:\n<a href=\"http://msdn.microsoft.com/en-us/library/ms733069.aspx\" rel=\"nofollow noreferrer\">WCF Link</a></p>\n\n<p>To summarize:</p>\n\n<ul>\n<li>To start with you need to create a new visual studio project of the type \"Windows Service\". </li>\n<li>Next to be able to install the service, you also need to write an installer class of the form:</li>\n</ul>\n\n<p>.</p>\n\n<pre><code> [RunInstaller(true)]\n public class ProjectInstaller : Installer\n {\n }\n</code></pre>\n\n<ul>\n<li><p>Add your WCF classes to the project, and in the OnStart and OnStop events of the windows service you'll have to explicitly start your WCF services.</p></li>\n<li><p>From a visual studio command prompt you can install the service using the command</p></li>\n</ul>\n\n<p>.</p>\n\n<pre><code>installutil myservicename.exe\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How to host the WCF service in windows service? Thanks Sekar
I thought this article did a pretty good job of covering the steps required: [WCF Link](http://msdn.microsoft.com/en-us/library/ms733069.aspx) To summarize: * To start with you need to create a new visual studio project of the type "Windows Service". * Next to be able to install the service, you also need to write an installer class of the form: . ``` [RunInstaller(true)] public class ProjectInstaller : Installer { } ``` * Add your WCF classes to the project, and in the OnStart and OnStop events of the windows service you'll have to explicitly start your WCF services. * From a visual studio command prompt you can install the service using the command . ``` installutil myservicename.exe ```
250,209
<p>I'm relatively new to the Python world, but this seems very straight forward.</p> <p>Google is yelling at me that this code needs to be optimized:</p> <pre><code>class AddLinks(webapp.RequestHandler): def post(self): # Hash the textarea input to generate pseudo-unique value hash = md5.new(self.request.get('links')).hexdigest() # Seperate the input by line allLinks = self.request.get('links').splitlines() # For each line in the input, add to the database for x in allLinks: newGroup = LinkGrouping() newGroup.reference = hash newGroup.link = x newGroup.put() # testing vs live #baseURL = 'http://localhost:8080' baseURL = 'http://linkabyss.appspot.com' # Build template parameters template_values = { 'all_links': allLinks, 'base_url': baseURL, 'reference': hash, } # Output the template path = os.path.join(os.path.dirname(__file__), 'addLinks.html') self.response.out.write(template.render(path, template_values)) </code></pre> <p>The dashboard is telling me that this is using a ton of CPU.</p> <p>Where should I look for improvements?</p>
[ { "answer_id": 250294, "author": "monkut", "author_id": 24718, "author_profile": "https://Stackoverflow.com/users/24718", "pm_score": 2, "selected": false, "text": "<p>Looks pretty tight to me.</p>\n\n<p>I see one thing that may make a small improvement.\nYour calling, \"self.request.get('links')\" twice.</p>\n\n<p>So adding:</p>\n\n<pre><code>unsplitlinks = self.request.get('links')\n</code></pre>\n\n<p>And referencing, \"unsplitlinks\" could help.</p>\n\n<p>Other than that the loop is the only area I see that would be a target for optimization.\nIs it possible to prep the data and then add it to the db at once, instead of doing a db add per link? (I assume the .put() command adds the link to the database)</p>\n" }, { "answer_id": 250318, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 0, "selected": false, "text": "<p>How frequently is this getting called? This doesn't look that bad... especially after removing the duplicate request.</p>\n" }, { "answer_id": 250322, "author": "Andre Bossard", "author_id": 21027, "author_profile": "https://Stackoverflow.com/users/21027", "pm_score": 2, "selected": false, "text": "<p>You can dramatically reduce the interaction between your app and the database by just storing the complete <code>self.request.get('links')</code> in a text field in the database.</p>\n\n<ul>\n<li>only one <code>put()</code> per <code>post(self)</code></li>\n<li>the hash isn't stored n-times (for every link, which makes no sense and is really a waste of space)</li>\n</ul>\n\n<p>And you save yourself the parsing of the textfield when someone actually calls the page....</p>\n" }, { "answer_id": 250395, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 4, "selected": true, "text": "<p>The main overhead here is the multiple individual puts to the datastore. If you can, store the links as a single entity, as Andre suggests. You can always split the links into an array and store it in a ListProperty.</p>\n\n<p>If you do need an entity for each link, try this:</p>\n\n<pre><code># For each line in the input, add to the database\ngroups = []\nfor x in allLinks:\n newGroup = LinkGrouping()\n newGroup.reference = hash\n newGroup.link = x\n groups.append(newGroup)\ndb.put(groups)\n</code></pre>\n\n<p>It will reduce the datastore roundtrips to one, and it's the roundtrips that are really killing your high CPU cap.</p>\n" }, { "answer_id": 250465, "author": "databyss", "author_id": 9094, "author_profile": "https://Stackoverflow.com/users/9094", "pm_score": 0, "selected": false, "text": "<p>Can I query against the ListProperty?</p>\n\n<p>Something like </p>\n\n<pre><code>SELECT * FROM LinkGrouping WHERE links.contains('http://www.google.com')\n</code></pre>\n\n<p>I have future plans where I would need that functionality.</p>\n\n<p>I'll definitely implement the single db.put() to reduce usage.</p>\n" }, { "answer_id": 264785, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>no/ you can not use something like \"links.contains('<a href=\"http://www.google.com\" rel=\"nofollow noreferrer\">http://www.google.com</a>')\"\nGQL not support this</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9094/" ]
I'm relatively new to the Python world, but this seems very straight forward. Google is yelling at me that this code needs to be optimized: ``` class AddLinks(webapp.RequestHandler): def post(self): # Hash the textarea input to generate pseudo-unique value hash = md5.new(self.request.get('links')).hexdigest() # Seperate the input by line allLinks = self.request.get('links').splitlines() # For each line in the input, add to the database for x in allLinks: newGroup = LinkGrouping() newGroup.reference = hash newGroup.link = x newGroup.put() # testing vs live #baseURL = 'http://localhost:8080' baseURL = 'http://linkabyss.appspot.com' # Build template parameters template_values = { 'all_links': allLinks, 'base_url': baseURL, 'reference': hash, } # Output the template path = os.path.join(os.path.dirname(__file__), 'addLinks.html') self.response.out.write(template.render(path, template_values)) ``` The dashboard is telling me that this is using a ton of CPU. Where should I look for improvements?
The main overhead here is the multiple individual puts to the datastore. If you can, store the links as a single entity, as Andre suggests. You can always split the links into an array and store it in a ListProperty. If you do need an entity for each link, try this: ``` # For each line in the input, add to the database groups = [] for x in allLinks: newGroup = LinkGrouping() newGroup.reference = hash newGroup.link = x groups.append(newGroup) db.put(groups) ``` It will reduce the datastore roundtrips to one, and it's the roundtrips that are really killing your high CPU cap.
250,214
<p>I am updating a VBA program (excel). At startup the program checks if it can find a directory which is on the office file server using:</p> <pre><code>FileSystemObject.FolderExists("\\servername\path") </code></pre> <p>If this is not found the program switches to offline mode and saves its output to the local hard disk (for later transfer), instead of directly to the fileserver. </p> <p>This works OK, It's very quick if the computer can reach the path, however it can sometimes take a while (up to one minute) for the call to FolderExists to complete/time-out, especially if there is a network connection open but the required path does not exist (i.e. we are connected to some other LAN).</p> <p>My Question(s):</p> <ol> <li><p>is there a quicker/better way to check for the existence of a network path using VBA?</p></li> <li><p>is there a way to have the user cancel the search done by FolderExists() when (s)he knows it cannot succeed because they're not in the office. I.e. is there some way to prematurely exit FolderExists() (or any other function call for that matter)</p></li> </ol> <p>I want the solution to have as little user input as possible, which is why the check is done automatically, rather than just asking the user if (s)he's in the office or not in the first place.</p>
[ { "answer_id": 250224, "author": "Kevin Fairchild", "author_id": 3743, "author_profile": "https://Stackoverflow.com/users/3743", "pm_score": 3, "selected": true, "text": "<p><strong>If you're on a domain:</strong></p>\n\n<p>Check the LOGONSERVER environmental variable.</p>\n\n<p>If there are two '\\' symbols before the server name, it's connected to active directory and so you should do your check.</p>\n\n<p>Otherwise, it isn't logged into the office network, so you can bypass the check.</p>\n\n<p><strong>If you aren't on a domain:</strong></p>\n\n<p>Probably your best bet is to run a ping against the target server.</p>\n\n<p>If it can't get a ping response, it either isn't connected to the network, isn't connected to YOUR network, or the server is down. You don't want your code to run either way, in those cases.</p>\n\n<p><a href=\"http://vbnet.mvps.org/index.html?code/internet/ping.htm\" rel=\"nofollow noreferrer\">MVPS.ORG</a> and <a href=\"http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/9a509391-f4e2-4ea7-827a-3370aa203bfb/\" rel=\"nofollow noreferrer\">MSDN Forums</a> both have some code samples for that,</p>\n" }, { "answer_id": 11306581, "author": "Rob Gibson", "author_id": 1498067, "author_profile": "https://Stackoverflow.com/users/1498067", "pm_score": 0, "selected": false, "text": "<p>I use the <code>Dir</code> Command, targeting a shared folder on the server and trapping the error when not found.</p>\n\n<pre><code>Dir(\"\\\\Servername\\aFolder\\\", vbDirectory)\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32763/" ]
I am updating a VBA program (excel). At startup the program checks if it can find a directory which is on the office file server using: ``` FileSystemObject.FolderExists("\\servername\path") ``` If this is not found the program switches to offline mode and saves its output to the local hard disk (for later transfer), instead of directly to the fileserver. This works OK, It's very quick if the computer can reach the path, however it can sometimes take a while (up to one minute) for the call to FolderExists to complete/time-out, especially if there is a network connection open but the required path does not exist (i.e. we are connected to some other LAN). My Question(s): 1. is there a quicker/better way to check for the existence of a network path using VBA? 2. is there a way to have the user cancel the search done by FolderExists() when (s)he knows it cannot succeed because they're not in the office. I.e. is there some way to prematurely exit FolderExists() (or any other function call for that matter) I want the solution to have as little user input as possible, which is why the check is done automatically, rather than just asking the user if (s)he's in the office or not in the first place.
**If you're on a domain:** Check the LOGONSERVER environmental variable. If there are two '\' symbols before the server name, it's connected to active directory and so you should do your check. Otherwise, it isn't logged into the office network, so you can bypass the check. **If you aren't on a domain:** Probably your best bet is to run a ping against the target server. If it can't get a ping response, it either isn't connected to the network, isn't connected to YOUR network, or the server is down. You don't want your code to run either way, in those cases. [MVPS.ORG](http://vbnet.mvps.org/index.html?code/internet/ping.htm) and [MSDN Forums](http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/9a509391-f4e2-4ea7-827a-3370aa203bfb/) both have some code samples for that,
250,216
<p>Is there a good way to determine if a person has a popup blocker enabled? I need to maintain a web application that unfortunately has tons of popups throughout it and I need to check if the user has popup blockers enabled.</p> <p>The only way I've found to do this is to open a window from javascript, check to see if it's open to determine if a blocker is enabled and then close it right away.</p> <p>This is slightly annoying since users who do not have it enabled see a small flash on the screen as the window opens and closes right away.</p> <p>Are there any other non-obtrusive methods for accomplishing this?</p>
[ { "answer_id": 250247, "author": "Codebeef", "author_id": 12037, "author_profile": "https://Stackoverflow.com/users/12037", "pm_score": 1, "selected": false, "text": "<p>I don't think there is any way of detecting this without attempting to open a window, as popup blockers don't add anything that can be interrogated in JS.</p>\n" }, { "answer_id": 250267, "author": "Andre Bossard", "author_id": 21027, "author_profile": "https://Stackoverflow.com/users/21027", "pm_score": 4, "selected": true, "text": "<p>Read <a href=\"http://www.visitor-stats.com/articles/detect-popup-blocker.php\" rel=\"nofollow noreferrer\">Detect a popup blocker using Javascript</a>:</p>\n\n<p>Basically you check if the 'window.open' method returns a handle to a newly-opened window.</p>\n\n<p>Looks like this:</p>\n\n<pre><code>var mine = window.open('','','width=1,height=1,left=0,top=0,scrollbars=no');\nif(mine)\n var popUpsBlocked = false\nelse\n var popUpsBlocked = true\nmine.close()\n</code></pre>\n" }, { "answer_id": 250364, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 2, "selected": false, "text": "<p>As others have commented, the only way to find out for sure is to try it.</p>\n\n<p>However, a good approximate answer to the question “is a popup-blocker installed” is, these days, “yes”. All recent browsers will block your pop-ups by default, so you'd better design your app to cope gracefully with this. Namely, don't try to window.open except in reaction to a user interaction (typically onclick), and you'll be fine.</p>\n" }, { "answer_id": 250393, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 0, "selected": false, "text": "<p>Popups that are opened in response to an action by a user&mdash;such as clicking a link&mdash;shouldn't be blocked by popup blockers.</p>\n" }, { "answer_id": 250715, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 2, "selected": false, "text": "<p>As others have said, you'll have to try it and see, but checking for the resulting window object being non-\"falsy\" isn't sufficient for all browsers.</p>\n\n<p>Opera still returns a <code>Window</code> object when a popup is blocked, so you have to examine the object sufficiently to determine if it's a real window:</p>\n\n<pre><code>var popup = window.open(/* ... */);\nvar popupBlocked = (!popup || typeof popup.document.getElementById == \"undefined\");\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2849/" ]
Is there a good way to determine if a person has a popup blocker enabled? I need to maintain a web application that unfortunately has tons of popups throughout it and I need to check if the user has popup blockers enabled. The only way I've found to do this is to open a window from javascript, check to see if it's open to determine if a blocker is enabled and then close it right away. This is slightly annoying since users who do not have it enabled see a small flash on the screen as the window opens and closes right away. Are there any other non-obtrusive methods for accomplishing this?
Read [Detect a popup blocker using Javascript](http://www.visitor-stats.com/articles/detect-popup-blocker.php): Basically you check if the 'window.open' method returns a handle to a newly-opened window. Looks like this: ``` var mine = window.open('','','width=1,height=1,left=0,top=0,scrollbars=no'); if(mine) var popUpsBlocked = false else var popUpsBlocked = true mine.close() ```
250,228
<p>I have a page with many forms on it. could be 1..200. None of these forms have buttons and they are built programatically. I am using jquery to submit all the forms that are checked.</p> <pre><code> function FakeName() { $("input:checked").parent("form").submit(); } </code></pre> <p>My forms look like:</p> <pre><code> &lt;form name="FakeForm&lt;%=i%&gt;" action="javascript:void%200" onSubmit="processRow(&lt;%=i%&gt;)" method="post" style="margin:0px;"&gt; &lt;input type="checkbox" name="FakeNameCheck" value="FakeNameCheck"/&gt; &lt;input type="hidden" name="FakeNum" value="&lt;%= FakeNum%&gt;"/&gt; &lt;input type="hidden" name="FakeId" value="&lt;%=FakeIdr%&gt;"/&gt; &lt;input type="hidden" name="FakeAmt" value="&lt;%=FakeAmount%&gt;"/&gt; &lt;input type="hidden" name="FakeTrans" value="FakeTrans"/&gt; &lt;/form&gt; </code></pre> <p>Note: action is set to "javascript:void%200" so that it posts to a fake page. I want to handle my own posting in processRow.</p> <p>OnSubmit never gets called and therefore ProcessRow never gets called. </p> <p>Obviously all the names of the functions and variables have been changed to protect their identity :D</p> <p>How can I get a function in each form to fire when I call submit programmatically.</p>
[ { "answer_id": 250259, "author": "Gareth", "author_id": 31582, "author_profile": "https://Stackoverflow.com/users/31582", "pm_score": 3, "selected": true, "text": "<p>The <code>onsubmit</code> handler is deliberately not triggered when you programatically submit the form. This is to avoid infinite recursion if an event handler would cause the event to be triggered again (and therefore the event handler to be called again)</p>\n\n<p>However, of course you can call the <code>processRow()</code> function yourself in place of the <code>.submit()</code> call.</p>\n\n<p>You're allowed to have inputs outside of forms. One school of thought is that a <code>&lt;form&gt;</code> shouldn't be a <code>&lt;form&gt;</code> if it's not intended to be submitted to the server via HTML.</p>\n" }, { "answer_id": 250312, "author": "Rakesh Pai", "author_id": 20089, "author_profile": "https://Stackoverflow.com/users/20089", "pm_score": 0, "selected": false, "text": "<p>Look up <a href=\"https://developer.mozilla.org/index.php?title=En/DOM/Element.dispatchEvent\" rel=\"nofollow noreferrer\">dispatchEvent</a> and it's equivalent <a href=\"http://msdn.microsoft.com/en-us/library/ms536423(VS.85).aspx\" rel=\"nofollow noreferrer\">fireEvent</a>. It's not the easiest thing in the world to use, but I think that's what you are looking for.</p>\n\n<p>I'm surprised that there's no library that helps with this easily. Prototype (the one I've used the most) comes closest with a .fire() method on elements.</p>\n" }, { "answer_id": 250315, "author": "Brian G", "author_id": 3208, "author_profile": "https://Stackoverflow.com/users/3208", "pm_score": 0, "selected": false, "text": "<p>Looks like I may be able to do this:</p>\n\n<pre><code>&lt;form name=\"FakeForm&lt;%=i%&gt;\" action=\"javascript:processRow(&lt;%=i%&gt;)\" method=\"post\" style=\"margin:0px;\"&gt;\n &lt;input type=\"checkbox\" name=\"FakeNameCheck\" value=\"FakeNameCheck\"/&gt;\n &lt;input type=\"hidden\" name=\"FakeNum\" value=\"&lt;%= FakeNum%&gt;\"/&gt;\n &lt;input type=\"hidden\" name=\"FakeId\" value=\"&lt;%=FakeIdr%&gt;\"/&gt;\n &lt;input type=\"hidden\" name=\"FakeAmt\" value=\"&lt;%=FakeAmount%&gt;\"/&gt;\n &lt;input type=\"hidden\" name=\"FakeTrans\" value=\"FakeTrans\"/&gt;\n &lt;/form&gt;\n</code></pre>\n\n<p>Are there any drawbacks to this?</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ]
I have a page with many forms on it. could be 1..200. None of these forms have buttons and they are built programatically. I am using jquery to submit all the forms that are checked. ``` function FakeName() { $("input:checked").parent("form").submit(); } ``` My forms look like: ``` <form name="FakeForm<%=i%>" action="javascript:void%200" onSubmit="processRow(<%=i%>)" method="post" style="margin:0px;"> <input type="checkbox" name="FakeNameCheck" value="FakeNameCheck"/> <input type="hidden" name="FakeNum" value="<%= FakeNum%>"/> <input type="hidden" name="FakeId" value="<%=FakeIdr%>"/> <input type="hidden" name="FakeAmt" value="<%=FakeAmount%>"/> <input type="hidden" name="FakeTrans" value="FakeTrans"/> </form> ``` Note: action is set to "javascript:void%200" so that it posts to a fake page. I want to handle my own posting in processRow. OnSubmit never gets called and therefore ProcessRow never gets called. Obviously all the names of the functions and variables have been changed to protect their identity :D How can I get a function in each form to fire when I call submit programmatically.
The `onsubmit` handler is deliberately not triggered when you programatically submit the form. This is to avoid infinite recursion if an event handler would cause the event to be triggered again (and therefore the event handler to be called again) However, of course you can call the `processRow()` function yourself in place of the `.submit()` call. You're allowed to have inputs outside of forms. One school of thought is that a `<form>` shouldn't be a `<form>` if it's not intended to be submitted to the server via HTML.
250,234
<p>I have been trying to get PEAR::mail to successfully deliver emails to hotmail users without being flagged as SPAM and ending up in the junk folder, i have no problems with yahoo/gmail only with hotmail.</p> <p>google suggested that this is a common problem with hotmail and that possible causes can include</p> <ul> <li>incorrect reverse DNS for main IP of the server</li> <li>lack of SenderId/SPF records </li> <li>being blacklisted</li> </ul> <p>having checked all of the above i can only think of one other reason - incorrectly formatted headers ?</p> <p>to test this theory i set up outlook to send email via the same address that PEAR::mail uses and sent a quick test - it delivered straight to my inbox</p> <p>so i compared the headers from the email sent from PEAR::mail against the headers sent by Outlook and there are only a few differences - i have only listed the differences to save space (and peoples eyes)</p> <p>PEAR::mail headers (not in outlook headers)</p> <pre><code>X-PHP-Script: www.example.com/register.php for [users ip address] </code></pre> <p>Outlook headers (not in PEAR::mail headers)</p> <pre><code>X-Mailer: Microsoft Office Outlook 11 Thread-Index: Ack6CWSQlgV8s6+6SWyifka2NNpB7g== X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.3350 </code></pre> <p>the only other differences that i can see are</p> <ul> <li>the order of the From: and To: headers are reversed </li> <li>and in the Received: section of the headers</li> </ul> <p>Outlook</p> <pre><code>Received: from myhomehostname.com ([ip address] helo=simber) by mywebhostname.com with local (Exim 4.67) </code></pre> <p>PEAR::mail</p> <pre><code>Received: from apache by mywebhostname.com with local (Exim 4.67) </code></pre> <p>could these small differences in the headers be the cause or am i looking in the wrong place ? i knew this might be problematic hence why i chose to use the PEAR::mail class rather than rolling my own but now i really have no idea where to go with this, any help would be greatly appreciated.</p> <p><strong><em>Update:</em></strong> as per changelog's suggestion i have tried adding the MS headers to the PEAR::mail class and i have tried replacing PEAR::mail with PHPMailer (with &amp; without the extra headers) - they all end up in the junk folder.</p> <p>I am starting to believe that it may not be the headers afterall.</p> <p><strong><em>Update 2:</em></strong> i should have mentioned that the emails are just a registration confirmation to validate the email address the user signed up with - no mailshots etc so our volume is extremely low. </p> <p>I have considered warning users who provide a @hotmail/live email address to add us to their address book or check their junk folder - but this just seems unprofessional to me - it may be that i have to resort to this.</p> <p>As for becoming Sender Score Certified - its very unlikely that i can justify the cost of this when considering the low volume and purpose of these emails.</p>
[ { "answer_id": 250243, "author": "changelog", "author_id": 5646, "author_profile": "https://Stackoverflow.com/users/5646", "pm_score": 1, "selected": false, "text": "<p>I have always used <a href=\"http://phpmailer.codeworxtech.com/\" rel=\"nofollow noreferrer\">PHPMailer</a> in my projects, and what I did to avoid Hotmail's junk folder was to call a method they had that added MS Headers to the message.</p>\n\n<p><a href=\"http://www.koders.com/php/fid8B2BF59A0FE70060034616281BE9155A6532DE07.aspx?s=smtp+server#L1168\" rel=\"nofollow noreferrer\">Take a look at the source</a>, and add those headers yourself.</p>\n\n<p>Also, I recommend including a text-version if you're sending HTML e-mail.</p>\n" }, { "answer_id": 250446, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 0, "selected": false, "text": "<p>I'd suggest modifying the headers you send to match 100% what outlook sends, and see if that solves the problem. Really it's a tough one though, hotmail is known for having a super crappy spam filter, sending lots of legit email to junk, and lots of spam to your inbox.</p>\n" }, { "answer_id": 250857, "author": "SchizoDuckie", "author_id": 18077, "author_profile": "https://Stackoverflow.com/users/18077", "pm_score": 3, "selected": false, "text": "<p>My company does professional e-mail marketting campaigns (through strongmail servers) we send thousands of (sollicited) emails a day to all kinds of addresses.</p>\n\n<p>The problem you are facing is that you have no authority. You could just be some spammer trying to send loads of spam. </p>\n\n<p>The thing you need to do is:</p>\n\n<ul>\n<li>Add unsubscribe links</li>\n<li>Apply for hotmail's Junkmail reporting program (JMRP) and <em>MAKE SURE</em> people that press the 'this is junk' button do not get mailed again. This will up your 'sender score; @ hotmail and allow you messages to get through.</li>\n<li>Add SPF and other antispam solutions.</li>\n<li>Do not send more than 50 e-mails per minute to @hotmail.com (other domains have other limits)</li>\n</ul>\n\n<p>B.t.w we use PHPMailer to compose our messages, no problem at all with that :-)\nThe problem nowadays really is the restricting receiving mailservers.</p>\n" }, { "answer_id": 250870, "author": "Gary Richardson", "author_id": 2506, "author_profile": "https://Stackoverflow.com/users/2506", "pm_score": 3, "selected": false, "text": "<p>Email Deliverability is closer to an art than a science. I can pretty much guarantee that it has nothing to do with your headers. Trying to spoof headers is likely the worst thing you can do. The <em>received:</em> header is added by the mail servers as they receive the messages: spoofing this will cause your email to get flagged as spam: one of the spam filters commonly used is to count then number of relays (ie <em>received:</em> headers). If there's too many you get a higher spam score.</p>\n\n<p>Reverse DNS and SPF are the minimum entry barriers. For hotmail in particular, there are three other very important factors AFTER you get your SPF and DNS records in line:</p>\n\n<ul>\n<li>IP/Domain Reputation</li>\n<li>Volume</li>\n<li>Being in the Address Book</li>\n</ul>\n\n<p>Reputation isn't the same as being blacklisted. You need to build trust with hotmail. Hotmail uses <a href=\"http://senderscorecertified.com/\" rel=\"noreferrer\">Sender Score Certified</a> as their main reputation broker -- you can check your reputation with them if you want, but it may cost you.</p>\n\n<p>If you're on a shared host or an IP address that has a checkered past, you won't have much luck with hotmail.</p>\n\n<p>You build reputation by having a consistent volume with low spam complaints. You can send 1M messages an hour all day long, as long as you do it every day. If you're sending less than 10,000 messages a day, you likely won't be able to build up a decent reputation. You can get a report on your volume at <a href=\"http://www.senderbase.org/\" rel=\"noreferrer\">Sender Base</a>.</p>\n\n<p>Finally, the best way to make sure you end up in the inbox is to get your users to add the sending email address to their address book. Hotmail uses this as a safe sender list. In fact, I think there's an additional trusted sender option in Hotmail now too (it's been awhile since I've been in the delivery game and I don't use hotmail).</p>\n\n<p>Here are some other best practices for sending email:</p>\n\n<ul>\n<li>ALWAYS use the same IP address</li>\n<li>ALWAYS use the same FROM address</li>\n<li>if you have a large list that you send newsletters to, make sure you retire old addresses (ie, check open rates)</li>\n<li>if you have a large list, try segmenting it and sending from different IP addresses based on risk (ie, newer addresses may mark the message as spam)</li>\n</ul>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2083/" ]
I have been trying to get PEAR::mail to successfully deliver emails to hotmail users without being flagged as SPAM and ending up in the junk folder, i have no problems with yahoo/gmail only with hotmail. google suggested that this is a common problem with hotmail and that possible causes can include * incorrect reverse DNS for main IP of the server * lack of SenderId/SPF records * being blacklisted having checked all of the above i can only think of one other reason - incorrectly formatted headers ? to test this theory i set up outlook to send email via the same address that PEAR::mail uses and sent a quick test - it delivered straight to my inbox so i compared the headers from the email sent from PEAR::mail against the headers sent by Outlook and there are only a few differences - i have only listed the differences to save space (and peoples eyes) PEAR::mail headers (not in outlook headers) ``` X-PHP-Script: www.example.com/register.php for [users ip address] ``` Outlook headers (not in PEAR::mail headers) ``` X-Mailer: Microsoft Office Outlook 11 Thread-Index: Ack6CWSQlgV8s6+6SWyifka2NNpB7g== X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.3350 ``` the only other differences that i can see are * the order of the From: and To: headers are reversed * and in the Received: section of the headers Outlook ``` Received: from myhomehostname.com ([ip address] helo=simber) by mywebhostname.com with local (Exim 4.67) ``` PEAR::mail ``` Received: from apache by mywebhostname.com with local (Exim 4.67) ``` could these small differences in the headers be the cause or am i looking in the wrong place ? i knew this might be problematic hence why i chose to use the PEAR::mail class rather than rolling my own but now i really have no idea where to go with this, any help would be greatly appreciated. ***Update:*** as per changelog's suggestion i have tried adding the MS headers to the PEAR::mail class and i have tried replacing PEAR::mail with PHPMailer (with & without the extra headers) - they all end up in the junk folder. I am starting to believe that it may not be the headers afterall. ***Update 2:*** i should have mentioned that the emails are just a registration confirmation to validate the email address the user signed up with - no mailshots etc so our volume is extremely low. I have considered warning users who provide a @hotmail/live email address to add us to their address book or check their junk folder - but this just seems unprofessional to me - it may be that i have to resort to this. As for becoming Sender Score Certified - its very unlikely that i can justify the cost of this when considering the low volume and purpose of these emails.
My company does professional e-mail marketting campaigns (through strongmail servers) we send thousands of (sollicited) emails a day to all kinds of addresses. The problem you are facing is that you have no authority. You could just be some spammer trying to send loads of spam. The thing you need to do is: * Add unsubscribe links * Apply for hotmail's Junkmail reporting program (JMRP) and *MAKE SURE* people that press the 'this is junk' button do not get mailed again. This will up your 'sender score; @ hotmail and allow you messages to get through. * Add SPF and other antispam solutions. * Do not send more than 50 e-mails per minute to @hotmail.com (other domains have other limits) B.t.w we use PHPMailer to compose our messages, no problem at all with that :-) The problem nowadays really is the restricting receiving mailservers.
250,238
<p>We have a git project which has quite a big history.</p> <p>Specifically, early in the project there were quite a lot of binary resource files in the project, these have now been removed as they're effectively external resources.</p> <p>However, the size of our repository is >200MB (the total checkout is currently ~20MB) due to having these files previously committed.</p> <p>What we'd like to do is "collapse" the history so that the repository appears to have been created from a later revision than it was. For example</p> <pre><code>1-----2-----3-----4-----+---+---+ \ / +-----+---+---+ </code></pre> <ol> <li>Repository created</li> <li>Large set of binary files added</li> <li>Large set of binary files removed</li> <li>New intended 'start' of repository</li> </ol> <p>So effectively we want to lose the project history before a certain point. At this point there is only one branch, so there's no complication with trying to deal with multiple start points etc. However we don't want to lose all of the history and start a new repository with the current version.</p> <p>Is this possible, or are we doomed to have a bloated repository forever?</p>
[ { "answer_id": 250365, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 3, "selected": false, "text": "<p>Is <code>git-fast-export</code> what you are looking for?</p>\n\n<pre><code>NAME\n git-fast-export - Git data exporter\n\nSYNOPSIS\n git-fast-export [options] | git-fast-import\n\nDESCRIPTION\n This program dumps the given revisions in a form suitable to be piped into git-fast-\n import(1).\n\n You can use it as a human readable bundle replacement (see git-bundle(1)), or as a kind\n of an interactive git-filter-branch(1).\n</code></pre>\n" }, { "answer_id": 251252, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 4, "selected": false, "text": "<p>Thanks to JesperE's post I looked into <code>git-filter-branch</code> -- that may actually be what you want. It looks like you could retain your earlier commits too except they would be modified since your Big Files were removed. From the <a href=\"http://git-scm.com/docs/git-filter-branch\" rel=\"noreferrer\">git-filter-branch man page</a>:</p>\n\n<blockquote>\n <p>Suppose you want to remove a file (containing confidential information or copyright violation) from all commits:</p>\n \n <p>git filter-branch --tree-filter 'rm filename' HEAD</p>\n</blockquote>\n\n<p>Be sure to read that man page... obviously you'd want to do this on a spare clone of your repository to make sure it works as expected.</p>\n" }, { "answer_id": 251927, "author": "Paul", "author_id": 23356, "author_profile": "https://Stackoverflow.com/users/23356", "pm_score": 8, "selected": true, "text": "<p>You can remove the binary bloat and keep the rest of your history. Git allows you to reorder and 'squash' prior commits, so you can combine just the commits that add and remove your big binary files. If the adds were all done in one commit and the removals in another, this will be much easier than dealing with each file.</p>\n\n<pre><code>$ git log --stat # list all commits and commit messages \n</code></pre>\n\n<p>Search this for the commits that add and delete your binary files and note their SHA1s, say <code>2bcdef</code> and <code>3cdef3</code>.</p>\n\n<p>Then to edit the repo's history, use <code>rebase -i</code> command with its interactive option, starting with the parent of the commit where you added your binaries. It will launch your $EDITOR and you'll see a list of commits starting with <code>2bcdef</code>:</p>\n\n<pre><code>$ git rebase -i 2bcdef^ # generate a pick list of all commits starting with 2bcdef\n# Rebasing zzzzzz onto yyyyyyy \n# \n# Commands: \n# pick = use commit \n# edit = use commit, but stop for amending \n# squash = use commit, but meld into previous commit \n# \n# If you remove a line here THAT COMMIT WILL BE LOST.\n#\npick 2bcdef Add binary files and other edits\npick xxxxxx Another change\n .\n .\npick 3cdef3 Remove binary files; link to them as external resources\n .\n .\n</code></pre>\n\n<p>Insert <code>squash 3cdef3</code> as the second line and remove the line which says <code>pick 3cdef3</code> from the list. You now have a list of actions for the interactive <code>rebase</code> which will combine the commits which add and delete your binaries into one commit whose diff is just any other changes in those commits. Then it will reapply all of the subsequent commits in order, when you tell it to complete:</p>\n\n<pre><code>$ git rebase --continue\n</code></pre>\n\n<p>This will take a minute or two.<br>\nYou now have a repo that no longer has the binaries coming or going. But they will still take up space because, by default, Git keeps changes around for 30 days before they can be garbage-collected, so that you can change your mind.\nIf you want to remove them now:</p>\n\n<pre><code>$ git reflog expire --expire=1.minute refs/heads/master\n #all deletions up to 1 minute ago available to be garbage-collected\n$ git fsck --unreachable # lists all the blobs(files) that will be garbage-collected\n$ git prune\n$ git gc \n</code></pre>\n\n<p>Now you've removed the bloat but kept the rest of your history.</p>\n" }, { "answer_id": 475931, "author": "davitenio", "author_id": 50765, "author_profile": "https://Stackoverflow.com/users/50765", "pm_score": 5, "selected": false, "text": "<p>You can use <code>git filter-branch</code> with grafts to make the commit number 4 the new root commit of your branch. Just create the file <code>.git/info/grafts</code> with just one line in it containing the SHA1 of commit number 4.</p>\n\n<p>If you now do a <code>git log</code> or <code>gitk</code> you will see that those commands will display commit number 4 as the root of your branch. But nothing will have actually changed in your repository. You can delete <code>.git/info/grafts</code> and the output of <code>git log</code> or <code>gitk</code> will be as before. To actually make commit number 4 the new root you will have to run <code>git filter-branch</code>, with no arguments.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31582/" ]
We have a git project which has quite a big history. Specifically, early in the project there were quite a lot of binary resource files in the project, these have now been removed as they're effectively external resources. However, the size of our repository is >200MB (the total checkout is currently ~20MB) due to having these files previously committed. What we'd like to do is "collapse" the history so that the repository appears to have been created from a later revision than it was. For example ``` 1-----2-----3-----4-----+---+---+ \ / +-----+---+---+ ``` 1. Repository created 2. Large set of binary files added 3. Large set of binary files removed 4. New intended 'start' of repository So effectively we want to lose the project history before a certain point. At this point there is only one branch, so there's no complication with trying to deal with multiple start points etc. However we don't want to lose all of the history and start a new repository with the current version. Is this possible, or are we doomed to have a bloated repository forever?
You can remove the binary bloat and keep the rest of your history. Git allows you to reorder and 'squash' prior commits, so you can combine just the commits that add and remove your big binary files. If the adds were all done in one commit and the removals in another, this will be much easier than dealing with each file. ``` $ git log --stat # list all commits and commit messages ``` Search this for the commits that add and delete your binary files and note their SHA1s, say `2bcdef` and `3cdef3`. Then to edit the repo's history, use `rebase -i` command with its interactive option, starting with the parent of the commit where you added your binaries. It will launch your $EDITOR and you'll see a list of commits starting with `2bcdef`: ``` $ git rebase -i 2bcdef^ # generate a pick list of all commits starting with 2bcdef # Rebasing zzzzzz onto yyyyyyy # # Commands: # pick = use commit # edit = use commit, but stop for amending # squash = use commit, but meld into previous commit # # If you remove a line here THAT COMMIT WILL BE LOST. # pick 2bcdef Add binary files and other edits pick xxxxxx Another change . . pick 3cdef3 Remove binary files; link to them as external resources . . ``` Insert `squash 3cdef3` as the second line and remove the line which says `pick 3cdef3` from the list. You now have a list of actions for the interactive `rebase` which will combine the commits which add and delete your binaries into one commit whose diff is just any other changes in those commits. Then it will reapply all of the subsequent commits in order, when you tell it to complete: ``` $ git rebase --continue ``` This will take a minute or two. You now have a repo that no longer has the binaries coming or going. But they will still take up space because, by default, Git keeps changes around for 30 days before they can be garbage-collected, so that you can change your mind. If you want to remove them now: ``` $ git reflog expire --expire=1.minute refs/heads/master #all deletions up to 1 minute ago available to be garbage-collected $ git fsck --unreachable # lists all the blobs(files) that will be garbage-collected $ git prune $ git gc ``` Now you've removed the bloat but kept the rest of your history.
250,244
<p>I have a simple application with the following code:</p> <pre><code> FileInfo[] files = (new DirectoryInfo(initialDirectory)).GetFiles(); List&lt;Thread&gt; threads = new List&lt;Thread&gt;(files.Length); foreach (FileInfo f in files) { Thread t = new Thread(delegate() { Console.WriteLine(f.FullName); }); threads.Add(t); } foreach (Thread t in threads) t.Start(); </code></pre> <p>Lets say in 'I=initialDirectory' directory I have 3 files. This application should then create 3 threads, with each thread printing off one of the file names; however, instead each thread will print off the name of the last file in the 'files' array.</p> <p>Why is this? Why is the current file 'f' variable not getting setup in the anonymous method correctly?</p>
[ { "answer_id": 250249, "author": "Stewart Johnson", "author_id": 6408, "author_profile": "https://Stackoverflow.com/users/6408", "pm_score": 5, "selected": true, "text": "<p>The anonymous method keeps a <strong>reference</strong> to the variable in the enclosing block -- not the actual value of the variable.</p>\n\n<p>By the time the methods are actually executed (when you start the threads) <code>f</code> has been assigned to point to the last value in the collection, so all 3 threads print that last value.</p>\n" }, { "answer_id": 250260, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "<p>It's because <code>f.FullName</code> is a reference to a variable, and not a value (which is how you tried to use it). By the time you actually start the threads f.FullName was incremented all the way to the end of the array.</p>\n\n<p>Anyway, why iterate through things here twice?</p>\n\n<pre><code>foreach (FileInfo f in files)\n{\n Thread t = new Thread(delegate()\n {\n Console.WriteLine(f.FullName);\n });\n threads.Add(t);\n t.Start();\n}\n</code></pre>\n\n<p>However, this is still wrong, and perhaps even worse since you now have a race condition to see which thread goes faster: writing the console item or iterating to the next FileInfo.</p>\n" }, { "answer_id": 250323, "author": "Michał Piaskowski", "author_id": 1534, "author_profile": "https://Stackoverflow.com/users/1534", "pm_score": 3, "selected": false, "text": "<p>Here are some nice articles about anonymous methods in C# and the code that will be generated by compiler:</p>\n\n<p><a href=\"http://blogs.msdn.com/oldnewthing/archive/2006/08/02/686456.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/oldnewthing/archive/2006/08/02/686456.aspx</a><br/>\n<a href=\"http://blogs.msdn.com/oldnewthing/archive/2006/08/03/687529.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/oldnewthing/archive/2006/08/03/687529.aspx</a><br/>\n<a href=\"http://blogs.msdn.com/oldnewthing/archive/2006/08/04/688527.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/oldnewthing/archive/2006/08/04/688527.aspx</a><br/></p>\n\n<p>I think if you did:</p>\n\n<pre>\n foreach (FileInfo f in files)\n {\n FileInfo f2 = f; //variable declared inside the loop\n Thread t = new Thread(delegate()\n {\n Console.WriteLine(f2.FullName);\n });\n threads.Add(t);\n }\n</pre>\n\n<p>it would would work the way you wanted it to.</p>\n" }, { "answer_id": 251043, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 0, "selected": false, "text": "<p>It's because the underlying code for iterator (foreach) has already 'iterated' through all the values in the List before the threads start... So when they start, the value 'pointed' at by the iterator is the last one in the list...</p>\n\n<p>Start the thread inside the iteration instead.... </p>\n\n<pre><code>foreach (FileInfo f in files)\n { \n string filName = f.FullName;\n Thread t = new Thread(delegate() \n { Console.WriteLine(filName); }); \n t.Start();\n }\n</code></pre>\n\n<p>I don't believe a race is possible here since there's no shared memory accessible from all threads. </p>\n" }, { "answer_id": 251723, "author": "user22367", "author_id": 22367, "author_profile": "https://Stackoverflow.com/users/22367", "pm_score": 0, "selected": false, "text": "<p>The following would work as well.</p>\n\n<pre><code> Thread t = new Thread(delegate()\n {\n string name = f.Name;\n Console.WriteLine(name);\n });\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30006/" ]
I have a simple application with the following code: ``` FileInfo[] files = (new DirectoryInfo(initialDirectory)).GetFiles(); List<Thread> threads = new List<Thread>(files.Length); foreach (FileInfo f in files) { Thread t = new Thread(delegate() { Console.WriteLine(f.FullName); }); threads.Add(t); } foreach (Thread t in threads) t.Start(); ``` Lets say in 'I=initialDirectory' directory I have 3 files. This application should then create 3 threads, with each thread printing off one of the file names; however, instead each thread will print off the name of the last file in the 'files' array. Why is this? Why is the current file 'f' variable not getting setup in the anonymous method correctly?
The anonymous method keeps a **reference** to the variable in the enclosing block -- not the actual value of the variable. By the time the methods are actually executed (when you start the threads) `f` has been assigned to point to the last value in the collection, so all 3 threads print that last value.
250,256
<p>I have problem in some JavaScript that I am writing where the Switch statement does not seem to be working as expected.</p> <pre><code>switch (msg.ResultType) { case 0: $('#txtConsole').val("Some Val 0"); break; case 1: $('#txtConsole').val("Some Val 1"); break; case 2: $('#txtConsole').text("Some Val 2"); break; } </code></pre> <p>The ResultType is an integer value 0-2 and I can see that in FireBug. In all cases, the switch transfers control to the final break statement which means all the logic is completely skipped. What am I missing?</p>
[ { "answer_id": 250263, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I ran into a similar problem and the issue turned out to be that where as it was showing as an int value, the switch statement was reading it as a string variable. May not be the case here, but that is what happened to me.</p>\n" }, { "answer_id": 250264, "author": "Gareth", "author_id": 31582, "author_profile": "https://Stackoverflow.com/users/31582", "pm_score": 0, "selected": false, "text": "<p>Are you sure the ResultType is an integer (e.g. 0) and not a string (e.g. \"0\")?</p>\n\n<p>This could easily explain the difference in behaviour</p>\n" }, { "answer_id": 250270, "author": "Juan Pablo Califano", "author_id": 24170, "author_profile": "https://Stackoverflow.com/users/24170", "pm_score": 5, "selected": true, "text": "<p>I'm sure that a switch uses === for comparison in Actionscript and since JS and AS both follow the ECMAScript standard, I guess the same applies to JS. My guess is that the value is not actually a Number, but perhaps a String.</p>\n\n<p>You could try to use parseInt(msg.ResultType) in the switch or use strings in the cases.</p>\n" }, { "answer_id": 250276, "author": "Joe Brinkman", "author_id": 4820, "author_profile": "https://Stackoverflow.com/users/4820", "pm_score": 0, "selected": false, "text": "<p>It looks like changing it to parseInt(msg.ResultType) has forced the JavaScript engine to properly treat it as an integer. Thanks for the help.</p>\n" }, { "answer_id": 250279, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>switch (msg.ResultType-0) {\n case 0:\n $('#txtConsole').val(\"Some Val 0\");\n break;\n case 1:\n $('#txtConsole').val(\"Some Val 1\");\n break;\n case 2:\n $('#txtConsole').text(\"Some Val 2\");\n break;\n}\n</code></pre>\n\n<p>The <code>-0</code> will force (coerce) it to treating your value as an integer without changing the value, and it's much shorter than parseInt.</p>\n" }, { "answer_id": 250282, "author": "17 of 26", "author_id": 2284, "author_profile": "https://Stackoverflow.com/users/2284", "pm_score": 0, "selected": false, "text": "<p>First thing I noticed is that in two of the three cases, you're calling .val() and in the third you're calling .text(). </p>\n\n<p>If you tried changing the case statements to strings instead of ints, then the only thing I can think of is that you're hitting an exception somewhere along the line possibly caused by accessing an undefined variable.</p>\n" }, { "answer_id": 18312257, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Probably the most powerful coercion to int available in ES5 is: </p>\n\n<pre><code> msg.ResultType | 0 \n</code></pre>\n\n<p>This is one of the foundation stones on which asm.js resides. This leads to <strong>very</strong> optimised ES5 and is used by compiling on presence of: </p>\n\n<pre><code> \"use asm\" \n</code></pre>\n\n<p>directive (in FF and Chromium). This coercion results in Int32 type being used for Numbers in ES5 that do represent an \"int\". So the cook-book recipe solution for the original question from 5 years ago is this:</p>\n\n<pre><code> \"use strict\" ;\n$(\"#txtConsole\").val(\n switch (msg.ResultType | 0) {\n case 0:\n \"Some Val 0\";\n break;\n case 1:\n \"Some Val 1\";\n break;\n case 2:\n \"Some Val 2\";\n break;\n default :\n \"Illegal ResultType\";\n });\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4820/" ]
I have problem in some JavaScript that I am writing where the Switch statement does not seem to be working as expected. ``` switch (msg.ResultType) { case 0: $('#txtConsole').val("Some Val 0"); break; case 1: $('#txtConsole').val("Some Val 1"); break; case 2: $('#txtConsole').text("Some Val 2"); break; } ``` The ResultType is an integer value 0-2 and I can see that in FireBug. In all cases, the switch transfers control to the final break statement which means all the logic is completely skipped. What am I missing?
I'm sure that a switch uses === for comparison in Actionscript and since JS and AS both follow the ECMAScript standard, I guess the same applies to JS. My guess is that the value is not actually a Number, but perhaps a String. You could try to use parseInt(msg.ResultType) in the switch or use strings in the cases.
250,271
<p>How can I get the start and end positions of all matches using the <code>re</code> module? For example given the pattern <code>r'[a-z]'</code> and the string <code>'a1b2c3d4'</code> I'd want to get the positions where it finds each letter. Ideally, I'd like to get the text of the match back too.</p>
[ { "answer_id": 250303, "author": "Peter Hoffmann", "author_id": 720, "author_profile": "https://Stackoverflow.com/users/720", "pm_score": 9, "selected": true, "text": "<pre><code>import re\np = re.compile(\"[a-z]\")\nfor m in p.finditer('a1b2c3d4'):\n print(m.start(), m.group())\n</code></pre>\n" }, { "answer_id": 250306, "author": "gone", "author_id": 26880, "author_profile": "https://Stackoverflow.com/users/26880", "pm_score": 6, "selected": false, "text": "<p>Taken from </p>\n\n<p><a href=\"http://docs.python.org/3.3/howto/regex.html\" rel=\"noreferrer\"><em>Regular Expression HOWTO</em></a></p>\n\n<blockquote>\n <p>span() returns both start and end indexes in a single tuple. Since the\n match method only checks if the RE matches at the start of a string,\n start() will always be zero. However, the search method of RegexObject\n instances scans through the string, so the match may not start at zero\n in that case.</p>\n</blockquote>\n\n<pre><code>&gt;&gt;&gt; p = re.compile('[a-z]+')\n&gt;&gt;&gt; print p.match('::: message')\nNone\n&gt;&gt;&gt; m = p.search('::: message') ; print m\n&lt;re.MatchObject instance at 80c9650&gt;\n&gt;&gt;&gt; m.group()\n'message'\n&gt;&gt;&gt; m.span()\n(4, 11)\n</code></pre>\n\n<p>Combine that with:</p>\n\n<p>In Python 2.2, the finditer() method is also available, returning a sequence of MatchObject instances as an iterator.</p>\n\n<pre><code>&gt;&gt;&gt; p = re.compile( ... )\n&gt;&gt;&gt; iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')\n&gt;&gt;&gt; iterator\n&lt;callable-iterator object at 0x401833ac&gt;\n&gt;&gt;&gt; for match in iterator:\n... print match.span()\n...\n(0, 2)\n(22, 24)\n(29, 31)\n</code></pre>\n\n<p>you should be able to do something on the order of</p>\n\n<pre><code>for match in re.finditer(r'[a-z]', 'a1b2c3d4'):\n print match.span()\n</code></pre>\n" }, { "answer_id": 44927208, "author": "Rams Here", "author_id": 8259376, "author_profile": "https://Stackoverflow.com/users/8259376", "pm_score": 5, "selected": false, "text": "<p>For Python 3.x </p>\n\n<pre><code>from re import finditer\nfor match in finditer(\"pattern\", \"string\"):\n print(match.span(), match.group())\n</code></pre>\n\n<p>You shall get <code>\\n</code> separated tuples (comprising first and last indices of the match, respectively) and the match itself, for each hit in the string.</p>\n" }, { "answer_id": 57167463, "author": "StevenWernerCS", "author_id": 3390659, "author_profile": "https://Stackoverflow.com/users/3390659", "pm_score": 4, "selected": false, "text": "<p>note that the span &amp; group are indexed for multi capture groups in a regex</p>\n\n<pre><code>regex_with_3_groups=r\"([a-z])([0-9]+)([A-Z])\"\nfor match in re.finditer(regex_with_3_groups, string):\n for idx in range(0, 4):\n print(match.span(idx), match.group(idx))\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13009/" ]
How can I get the start and end positions of all matches using the `re` module? For example given the pattern `r'[a-z]'` and the string `'a1b2c3d4'` I'd want to get the positions where it finds each letter. Ideally, I'd like to get the text of the match back too.
``` import re p = re.compile("[a-z]") for m in p.finditer('a1b2c3d4'): print(m.start(), m.group()) ```
250,283
<p>What's the most pythonic way to scp a file in Python? The only route I'm aware of is </p> <pre><code>os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) </code></pre> <p>which is a hack, and which doesn't work outside Linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host.</p> <p>I'm aware of Twisted's <code>conch</code>, but I'd prefer to avoid implementing scp myself via low-level ssh modules.</p> <p>I'm aware of <code>paramiko</code>, a Python module that supports SSH and SFTP; but it doesn't support SCP.</p> <p>Background: I'm connecting to a router which doesn't support SFTP but does support SSH/SCP, so SFTP isn't an option.</p> <p><strong>EDIT</strong>: This is a duplicate of <a href="https://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh">How to copy a file to a remote server in Python using SCP or SSH?</a>. <strong>However</strong>, that question doesn't give an scp-specific answer that deals with keys from within Python. I'm hoping for a way to run code kind of like</p> <pre><code>import scp client = scp.Client(host=host, user=user, keyfile=keyfile) # or client = scp.Client(host=host, user=user) client.use_system_keys() # or client = scp.Client(host=host, user=user, password=password) # and then client.transfer('/etc/local/filename', '/etc/remote/filename') </code></pre>
[ { "answer_id": 250402, "author": "Blauohr", "author_id": 22176, "author_profile": "https://Stackoverflow.com/users/22176", "pm_score": 3, "selected": false, "text": "<p>if you install putty on win32 you get an pscp (putty scp).</p>\n\n<p>so you can use the os.system hack on win32 too.</p>\n\n<p>(and you can use the putty-agent for key-managment)</p>\n\n<hr>\n\n<p>sorry it is only a hack \n(but you can wrap it in a python class)</p>\n" }, { "answer_id": 250786, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 4, "selected": false, "text": "<p>You might be interested in trying <a href=\"https://pexpect.readthedocs.io/en/stable/\" rel=\"nofollow noreferrer\">Pexpect</a> (<a href=\"https://github.com/pexpect/pexpect\" rel=\"nofollow noreferrer\">source code</a>). This would allow you to deal with interactive prompts for your password.</p>\n\n<p>Here's a snip of example usage (for ftp) from the main website:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># This connects to the openbsd ftp site and\n# downloads the recursive directory listing.\nimport pexpect\nchild = pexpect.spawn ('ftp ftp.openbsd.org')\nchild.expect ('Name .*: ')\nchild.sendline ('anonymous')\nchild.expect ('Password:')\nchild.sendline ('[email protected]')\nchild.expect ('ftp&gt; ')\nchild.sendline ('cd pub')\nchild.expect('ftp&gt; ')\nchild.sendline ('get ls-lR.gz')\nchild.expect('ftp&gt; ')\nchild.sendline ('bye')\n</code></pre>\n" }, { "answer_id": 250797, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 1, "selected": false, "text": "<p>Hmmm, perhaps another option would be to use something like <a href=\"http://fuse.sourceforge.net/sshfs.html\" rel=\"nofollow noreferrer\">sshfs</a> (there an <a href=\"http://code.google.com/p/macfuse/wiki/MACFUSE_FS_SSHFS\" rel=\"nofollow noreferrer\">sshfs</a> for Mac too). Once your router is mounted you can just copy the files outright. I'm not sure if that works for your particular application but it's a nice solution to keep handy.</p>\n" }, { "answer_id": 251625, "author": "JimB", "author_id": 32880, "author_profile": "https://Stackoverflow.com/users/32880", "pm_score": 4, "selected": false, "text": "<p>You could also check out <a href=\"http://www.lag.net/paramiko/\" rel=\"noreferrer\">paramiko</a>. There's no scp module (yet), but it fully supports sftp.</p>\n\n<p>[EDIT]\nSorry, missed the line where you mentioned paramiko.\nThe following module is simply an implementation of the scp protocol for paramiko.\nIf you don't want to use paramiko or conch (the only ssh implementations I know of for python), you could rework this to run over a regular ssh session using pipes.</p>\n\n<p><a href=\"https://github.com/jbardin/scp.py\" rel=\"noreferrer\">scp.py for paramiko</a></p>\n" }, { "answer_id": 4282261, "author": "Tom Shen", "author_id": 259855, "author_profile": "https://Stackoverflow.com/users/259855", "pm_score": 7, "selected": false, "text": "<p>Try the <a href=\"https://github.com/jbardin/scp.py\" rel=\"noreferrer\">Python scp module for Paramiko</a>. It's very easy to use. See the following example:</p>\n\n<pre><code>import paramiko\nfrom scp import SCPClient\n\ndef createSSHClient(server, port, user, password):\n client = paramiko.SSHClient()\n client.load_system_host_keys()\n client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n client.connect(server, port, user, password)\n return client\n\nssh = createSSHClient(server, port, user, password)\nscp = SCPClient(ssh.get_transport())\n</code></pre>\n\n<p>Then call <code>scp.get()</code> or <code>scp.put()</code> to do SCP operations.</p>\n\n<p>(<a href=\"https://github.com/jbardin/scp.py/blob/master/scp.py\" rel=\"noreferrer\">SCPClient code</a>)</p>\n" }, { "answer_id": 8247987, "author": "user443854", "author_id": 443854, "author_profile": "https://Stackoverflow.com/users/443854", "pm_score": 3, "selected": false, "text": "<p>Have a look at <a href=\"http://docs.fabfile.org/en/2.4/api/transfer.html\" rel=\"nofollow noreferrer\">fabric.transfer</a>.</p>\n\n<pre><code>from fabric import Connection\n\nwith Connection(host=\"hostname\", \n user=\"admin\", \n connect_kwargs={\"key_filename\": \"/home/myuser/.ssh/private.key\"}\n ) as c:\n c.get('/foo/bar/file.txt', '/tmp/')\n</code></pre>\n" }, { "answer_id": 10685789, "author": "ccpizza", "author_id": 191246, "author_profile": "https://Stackoverflow.com/users/191246", "pm_score": 1, "selected": false, "text": "<p>I while ago I put together a python SCP copy script that depends on paramiko. It includes code to handle connections with a private key or SSH key agent with a fallback to password authentication.</p>\n\n<p><a href=\"http://code.activestate.com/recipes/576810-copy-files-over-ssh-using-paramiko/\" rel=\"nofollow\">http://code.activestate.com/recipes/576810-copy-files-over-ssh-using-paramiko/</a></p>\n" }, { "answer_id": 24049247, "author": "user178047", "author_id": 2345251, "author_profile": "https://Stackoverflow.com/users/2345251", "pm_score": 2, "selected": false, "text": "<p>If you are on *nix you can use <a href=\"http://sourceforge.net/projects/sshpass/\" rel=\"nofollow\">sshpass</a></p>\n\n<pre><code>sshpass -p password scp -o User=username -o StrictHostKeyChecking=no src dst:/path\n</code></pre>\n" }, { "answer_id": 24587238, "author": "smheidrich", "author_id": 2748899, "author_profile": "https://Stackoverflow.com/users/2748899", "pm_score": 2, "selected": false, "text": "<p>It has been quite a while since this question was asked, and in the meantime, another library that can handle this has cropped up:\nYou can use the <a href=\"http://plumbum.readthedocs.org/en/latest/api/path.html#plumbum.path.utils.copy\" rel=\"nofollow noreferrer\">copy</a> function included in the <a href=\"http://plumbum.readthedocs.org/en/latest/index.html\" rel=\"nofollow noreferrer\">Plumbum</a> library:</p>\n\n<pre><code>import plumbum\nr = plumbum.machines.SshMachine(\"example.net\")\n # this will use your ssh config as `ssh` from shell\n # depending on your config, you might also need additional\n # params, eg: `user=\"username\", keyfile=\".ssh/some_key\"`\nfro = plumbum.local.path(\"some_file\")\nto = r.path(\"/path/to/destination/\")\nplumbum.path.utils.copy(fro, to)\n</code></pre>\n" }, { "answer_id": 38556344, "author": "Maviles", "author_id": 2653486, "author_profile": "https://Stackoverflow.com/users/2653486", "pm_score": 4, "selected": false, "text": "<p>Couldn't find a straight answer, and this \"scp.Client\" module doesn't exist.\nInstead, <a href=\"https://pypi.python.org/pypi/scp\" rel=\"noreferrer\">this</a> suits me:</p>\n\n<pre><code>from paramiko import SSHClient\nfrom scp import SCPClient\n\nssh = SSHClient()\nssh.load_system_host_keys()\nssh.connect('example.com')\n\nwith SCPClient(ssh.get_transport()) as scp:\n scp.put('test.txt', 'test2.txt')\n scp.get('test2.txt')\n</code></pre>\n" }, { "answer_id": 42094822, "author": "user7529863", "author_id": 7529863, "author_profile": "https://Stackoverflow.com/users/7529863", "pm_score": 3, "selected": false, "text": "<p>You can use the package subprocess and the command call to use the scp command from the shell.</p>\n\n<pre><code>from subprocess import call\n\ncmd = \"scp user1@host1:files user2@host2:files\"\ncall(cmd.split(\" \"))\n</code></pre>\n" }, { "answer_id": 50423406, "author": "Loïc", "author_id": 3322400, "author_profile": "https://Stackoverflow.com/users/3322400", "pm_score": 3, "selected": false, "text": "<p>As of today, the best solution is probably <code>AsyncSSH</code></p>\n\n<p><a href=\"https://asyncssh.readthedocs.io/en/latest/#scp-client\" rel=\"noreferrer\">https://asyncssh.readthedocs.io/en/latest/#scp-client</a></p>\n\n<pre><code>async with asyncssh.connect('host.tld') as conn:\n await asyncssh.scp((conn, 'example.txt'), '.', recurse=True)\n</code></pre>\n" }, { "answer_id": 59855568, "author": "shrikkanth roxor", "author_id": 10835077, "author_profile": "https://Stackoverflow.com/users/10835077", "pm_score": 3, "selected": false, "text": "<pre><code>import paramiko\n\nclient = paramiko.SSHClient()\nclient.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n\nclient.connect('&lt;IP Address&gt;', username='&lt;User Name&gt;',password='' ,key_filename='&lt;.PEM File path')\n\n#Setup sftp connection and transmit this script \nprint (\"copying\")\n\nsftp = client.open_sftp() \nsftp.put(&lt;Source&gt;, &lt;Destination&gt;)\n\n\nsftp.close()\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4105/" ]
What's the most pythonic way to scp a file in Python? The only route I'm aware of is ``` os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) ``` which is a hack, and which doesn't work outside Linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host. I'm aware of Twisted's `conch`, but I'd prefer to avoid implementing scp myself via low-level ssh modules. I'm aware of `paramiko`, a Python module that supports SSH and SFTP; but it doesn't support SCP. Background: I'm connecting to a router which doesn't support SFTP but does support SSH/SCP, so SFTP isn't an option. **EDIT**: This is a duplicate of [How to copy a file to a remote server in Python using SCP or SSH?](https://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh). **However**, that question doesn't give an scp-specific answer that deals with keys from within Python. I'm hoping for a way to run code kind of like ``` import scp client = scp.Client(host=host, user=user, keyfile=keyfile) # or client = scp.Client(host=host, user=user) client.use_system_keys() # or client = scp.Client(host=host, user=user, password=password) # and then client.transfer('/etc/local/filename', '/etc/remote/filename') ```
Try the [Python scp module for Paramiko](https://github.com/jbardin/scp.py). It's very easy to use. See the following example: ``` import paramiko from scp import SCPClient def createSSHClient(server, port, user, password): client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(server, port, user, password) return client ssh = createSSHClient(server, port, user, password) scp = SCPClient(ssh.get_transport()) ``` Then call `scp.get()` or `scp.put()` to do SCP operations. ([SCPClient code](https://github.com/jbardin/scp.py/blob/master/scp.py))
250,304
<p>A VBScript cannot edit the registry by default on Vista. How do I get elevation (even if the user has to do something when they run the script) so that the script can edit the registry?</p> <p>The error is:</p> <pre><code>--------------------------- Windows Script Host --------------------------- Script: blah blah blah.vbs Line: 6 Char: 1 Error: Permission denied Code: 800A0046 Source: Microsoft VBScript runtime error --------------------------- OK --------------------------- </code></pre>
[ { "answer_id": 250343, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 0, "selected": false, "text": "<p>To make it work with native VBScript, you will most likely need a code signing certificate and sign your script with that. More info is in that thread at <a href=\"http://www.tek-tips.com/viewthread.cfm?qid=1475626\" rel=\"nofollow noreferrer\">tek-tips.com</a>.</p>\n\n<p>You could try to write the intended changes to a .reg file and call <code>regedit.exe</code> with that. Maybe this triggers UAC. Did not tried that, though. I have no Vista around right now. :-)</p>\n" }, { "answer_id": 250348, "author": "tloach", "author_id": 14092, "author_profile": "https://Stackoverflow.com/users/14092", "pm_score": 2, "selected": true, "text": "<p>My understanding was that you could edit HKCU as a normal user, but the others were restricted. I could be wrong. Regardless, there are a couple of example <a href=\"http://www.winhelponline.com/articles/185/1/VBScripts-and-UAC-elevation.html\" rel=\"nofollow noreferrer\">here</a> to do what you want to do.</p>\n" }, { "answer_id": 250358, "author": "pfunk", "author_id": 32528, "author_profile": "https://Stackoverflow.com/users/32528", "pm_score": 0, "selected": false, "text": "<p>Windows XP had the capability to \"Run As...\" when you right-clicked a program (like the shortcut to the command line). Doesn't Vista have something like this, \"Run as Administrator\" or something. </p>\n\n<p>Do this on the command line then have them run the script from the command line?</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1490/" ]
A VBScript cannot edit the registry by default on Vista. How do I get elevation (even if the user has to do something when they run the script) so that the script can edit the registry? The error is: ``` --------------------------- Windows Script Host --------------------------- Script: blah blah blah.vbs Line: 6 Char: 1 Error: Permission denied Code: 800A0046 Source: Microsoft VBScript runtime error --------------------------- OK --------------------------- ```
My understanding was that you could edit HKCU as a normal user, but the others were restricted. I could be wrong. Regardless, there are a couple of example [here](http://www.winhelponline.com/articles/185/1/VBScripts-and-UAC-elevation.html) to do what you want to do.
250,324
<p>I am wondering what the best way is using php to obtain a list of all the rows in the database, and when clicking on a row show the information in more detail, such as a related image etc.</p> <p>Should I use frames to do this? Are there good examples of this somewhere?</p> <p>Edit:</p> <p>I need much simpler instructions, as I am not a programmer and am just starting out. Can any links or examples be recommended?</p>
[ { "answer_id": 250329, "author": "Thomas Owens", "author_id": 572, "author_profile": "https://Stackoverflow.com/users/572", "pm_score": 2, "selected": false, "text": "<p>I use tables and JavaScript to do this.</p>\n\n<p>Data in a SQL database is, by nature, tabular. So I just select the data and create a table. Then, to drill down (when I need do), I provide a JavaScript \"more\" functionality and use CSS to hide/display the additional data.</p>\n" }, { "answer_id": 250331, "author": "changelog", "author_id": 5646, "author_profile": "https://Stackoverflow.com/users/5646", "pm_score": 0, "selected": false, "text": "<p>I tend to use two separate pages. One to list, which links to the one that shows the detailed record. The one that lists passes an ID parameter on the link (ie. show.php?id=145), as for the show.php page will get that parameter from <code>$_GET['id']</code>.</p>\n\n<p>This is the simplest approach to your problem.</p>\n" }, { "answer_id": 250362, "author": "philistyne", "author_id": 16597, "author_profile": "https://Stackoverflow.com/users/16597", "pm_score": 1, "selected": false, "text": "<p>You could begin with the <a href=\"http://www.php.net/manual/en/\" rel=\"nofollow noreferrer\">PHP manual</a>. It's rather well organised now. But now that my sarcastic bit's out of the way...</p>\n\n<p>One of the best ways to work with your database (at the moment, your choice is MySQL, but this <em>could</em> change) is to abstract your code from direct interaction with it.</p>\n\n<p>A tool such as <a href=\"http://adodb.sourceforge.net/\" rel=\"nofollow noreferrer\">ADODB</a> is well worth getting to know and makes the task of \"obtain a list of all the rows in the database\" rather trivial.</p>\n\n<p>The main advantage of this is that it insulates you somewhat from having to rewrite lots of code if you find you need to migrate your application to a server with a different database running on it.</p>\n\n<p>Better still (imho) would be to look at a framework such as <a href=\"http://framework.zend.com/\" rel=\"nofollow noreferrer\">Zend's</a> (well, they do MAKE php afterall) with it's DB abstraction called Zend_Db. This might be overkill for you right now as it appears, from looking at your other questions, that you're quite new to PHP/MySQL development.</p>\n\n<p>Also good: <a href=\"http://www.smarty.net/\" rel=\"nofollow noreferrer\">Smarty</a> (for abstracting your presentation from your logic)</p>\n" }, { "answer_id": 250432, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 0, "selected": false, "text": "<p>If you're not a programmer, but want to use php to show what's inside your mysql tables, perhaps <a href=\"http://www.phpmyadmin.net/home_page/index.php\" rel=\"nofollow noreferrer\">phpMyAdmin</a> is what you're looking for?</p>\n" }, { "answer_id": 251549, "author": "Alex Weinstein", "author_id": 16668, "author_profile": "https://Stackoverflow.com/users/16668", "pm_score": 0, "selected": false, "text": "<p>If you're building a simple database-driven application, and you're just starting to learn PHP, the approach I'd recommend is to use a framework that generates these for you. Take a look at QCodo (<a href=\"http://www.qcodo.com\" rel=\"nofollow noreferrer\">http://www.qcodo.com</a>), and in particular, this tutorial video: <a href=\"http://www.qcodo.com/view.php/demo_1_live\" rel=\"nofollow noreferrer\">http://www.qcodo.com/view.php/demo_1_live</a></p>\n" }, { "answer_id": 251880, "author": "kevtrout", "author_id": 1149, "author_profile": "https://Stackoverflow.com/users/1149", "pm_score": 3, "selected": true, "text": "<p>Contrary to other's recommendations, I would not recommend a framework or abstraction level. It will insulate you from understanding how php works and requires that you learn php and the framework structure/process at the same time. An abstraction layer is good practice in a commercial environment, but from the vibe of your question, you don't anticipate moving servers or migrating your db.</p>\n\n<p>I recommend working procedurally (not object-oriented) with the php and mysql until you understand what is going on and how the language works. </p>\n\n<p>To respond to your actual question:</p>\n\n<p>You need to connect to the database: <code>mysql_connect()</code></p>\n\n<p>You need to select the database you want to work with: <code>mysql_select_db()</code></p>\n\n<p>You need to define the query: <code>msyql_query()</code></p>\n\n<p>You need to use a while loop to get the data:</p>\n\n<pre><code>$query=mysql_query(\"select * from table_name\");\n while($row=mysql_fetch_assoc($query)){\n extract($row);\n echo $name of field 1.\": \".$name of field 2;\n }\n</code></pre>\n\n<p>To make each row of output a link to more info rewrite the echo statement like this:</p>\n\n<pre><code> echo \"&lt;a href=\\\"http://addresstomoreinfo.php?image_id=\".$image_id.\\\"&gt;\".$name \n of field 1.\": \".$name of field 2.\"&lt;/a&gt;\";\n</code></pre>\n\n<p>The \"name of field\" variables represent the column names of your db table and I have made up the layout of the field name, colon, and second field name. How the info is displayed is up to you.</p>\n\n<p>The question mark prepends the name of a variable that is defined in the addresstomoreinfo.php page that will be identified by <code>$var=$_GET['image_id'];</code></p>\n\n<p>Other php, html, css elements are involved in the big picture of accomplishing this. A good source for begining information is <a href=\"http://www.w3schools.com/\" rel=\"nofollow noreferrer\">http://www.w3schools.com/</a> <strong>I also live and die by the php manual linked to above</strong></p>\n" }, { "answer_id": 252027, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 0, "selected": false, "text": "<p>I think you don't really know what you're asking for! :-)</p>\n\n<p>With a suitable framework, database and object abstraction layers, this is trivial (I've done it several times). But they are <em>not</em> trivial to write from scratch and not helpful for learning PHP from the basics. Unless you've done this in other languages. </p>\n\n<p>OTOH, doing it all directly is still a good exercise (as <a href=\"https://stackoverflow.com/questions/250324/use-php-to-show-mysql-data#251880\">@kevtrout has described</a>), as long as you're willing to re-engineer the code repeatedly (even if you never really do) to develop suitable abstraction. IMO, there is far too much PHP kicking around that has long outgrown such a simple structure.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1246613/" ]
I am wondering what the best way is using php to obtain a list of all the rows in the database, and when clicking on a row show the information in more detail, such as a related image etc. Should I use frames to do this? Are there good examples of this somewhere? Edit: I need much simpler instructions, as I am not a programmer and am just starting out. Can any links or examples be recommended?
Contrary to other's recommendations, I would not recommend a framework or abstraction level. It will insulate you from understanding how php works and requires that you learn php and the framework structure/process at the same time. An abstraction layer is good practice in a commercial environment, but from the vibe of your question, you don't anticipate moving servers or migrating your db. I recommend working procedurally (not object-oriented) with the php and mysql until you understand what is going on and how the language works. To respond to your actual question: You need to connect to the database: `mysql_connect()` You need to select the database you want to work with: `mysql_select_db()` You need to define the query: `msyql_query()` You need to use a while loop to get the data: ``` $query=mysql_query("select * from table_name"); while($row=mysql_fetch_assoc($query)){ extract($row); echo $name of field 1.": ".$name of field 2; } ``` To make each row of output a link to more info rewrite the echo statement like this: ``` echo "<a href=\"http://addresstomoreinfo.php?image_id=".$image_id.\">".$name of field 1.": ".$name of field 2."</a>"; ``` The "name of field" variables represent the column names of your db table and I have made up the layout of the field name, colon, and second field name. How the info is displayed is up to you. The question mark prepends the name of a variable that is defined in the addresstomoreinfo.php page that will be identified by `$var=$_GET['image_id'];` Other php, html, css elements are involved in the big picture of accomplishing this. A good source for begining information is <http://www.w3schools.com/> **I also live and die by the php manual linked to above**
250,335
<p>I've created a batch job that running in 32bit mode as it using 32bit COM objectes, this need to connect to SharePoint to make updates to list. It works in my development environment as it is full 32bit. But in my test and prodution environment we use 64bit SharePoint and this is what I get from SPSite:</p> <pre><code>System.IO.FileNotFoundException: The Web application at http://&lt;my sp host&gt;/ could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application. at Microsoft.SharePoint.SPSite..ctor(SPFarm farm, Uri req... </code></pre> <p>this is what I do</p> <pre><code> using (SPSite site = new SPSite(_url)) { using (SPWeb web = site.OpenWeb()) { try { SPList list = web.Lists[new Guid(_listID)]; SPListItem item = list.GetItemById(id); item[field] = value; item.SystemUpdate(false); } catch (Exception x) { log.Error(x); } } } </code></pre>
[ { "answer_id": 250579, "author": "AdamBT", "author_id": 22426, "author_profile": "https://Stackoverflow.com/users/22426", "pm_score": 1, "selected": false, "text": "<p>I don't think this is a 32/64bit issue as I am in the same situation as far as developing on 32bit and deploying to 64bit. (Actually, we are running a 32bit and 64bit WFE'S) </p>\n\n<p>Since the exception is being thrown from the SPSite constructor, I would investigate further, as to whether the machine you are running you code on (the SP box) actually recognizes that URL.</p>\n" }, { "answer_id": 263887, "author": "Lars Fastrup", "author_id": 27393, "author_profile": "https://Stackoverflow.com/users/27393", "pm_score": 3, "selected": false, "text": "<p>You simply need to run your batch job in a 64-bit process. The problem is that SharePoint has many COM objects under the hood which are compiled for 64-bit in your test and production environment. The SPSite and SPWeb objects actually wrap the COM objects which is why they fail in your 32-bit process. </p>\n\n<p>One work-around could be to interact with SharePoint through its Web Services instead of the object model.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24595/" ]
I've created a batch job that running in 32bit mode as it using 32bit COM objectes, this need to connect to SharePoint to make updates to list. It works in my development environment as it is full 32bit. But in my test and prodution environment we use 64bit SharePoint and this is what I get from SPSite: ``` System.IO.FileNotFoundException: The Web application at http://<my sp host>/ could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application. at Microsoft.SharePoint.SPSite..ctor(SPFarm farm, Uri req... ``` this is what I do ``` using (SPSite site = new SPSite(_url)) { using (SPWeb web = site.OpenWeb()) { try { SPList list = web.Lists[new Guid(_listID)]; SPListItem item = list.GetItemById(id); item[field] = value; item.SystemUpdate(false); } catch (Exception x) { log.Error(x); } } } ```
You simply need to run your batch job in a 64-bit process. The problem is that SharePoint has many COM objects under the hood which are compiled for 64-bit in your test and production environment. The SPSite and SPWeb objects actually wrap the COM objects which is why they fail in your 32-bit process. One work-around could be to interact with SharePoint through its Web Services instead of the object model.
250,357
<p>I am looking for a way to truncate a string in Python that will not cut off the string in the middle of a word.</p> <p>For example:</p> <pre> Original: "This is really awesome." "Dumb" truncate: "This is real..." "Smart" truncate: "This is really..." </pre> <p>I'm looking for a way to accomplish the "smart" truncate from above.</p>
[ { "answer_id": 250373, "author": "Adam", "author_id": 30084, "author_profile": "https://Stackoverflow.com/users/30084", "pm_score": 7, "selected": true, "text": "<p>I actually wrote a solution for this on a recent project of mine. I've compressed the majority of it down to be a little smaller.</p>\n\n<pre><code>def smart_truncate(content, length=100, suffix='...'):\n if len(content) &lt;= length:\n return content\n else:\n return ' '.join(content[:length+1].split(' ')[0:-1]) + suffix\n</code></pre>\n\n<p>What happens is the if-statement checks if your content is already less than the cutoff point. If it's not, it truncates to the desired length, splits on the space, removes the last element (so that you don't cut off a word), and then joins it back together (while tacking on the '...').</p>\n" }, { "answer_id": 250406, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 6, "selected": false, "text": "<p>Here's a slightly better version of the last line in Adam's solution:</p>\n\n<pre><code>return content[:length].rsplit(' ', 1)[0]+suffix\n</code></pre>\n\n<p>(This is slightly more efficient, and returns a more sensible result in the case there are no spaces in the front of the string.)</p>\n" }, { "answer_id": 250409, "author": "Vebjorn Ljosa", "author_id": 17498, "author_profile": "https://Stackoverflow.com/users/17498", "pm_score": 2, "selected": false, "text": "<pre><code>def smart_truncate(s, width):\n if s[width].isspace():\n return s[0:width];\n else:\n return s[0:width].rsplit(None, 1)[0]\n</code></pre>\n\n<p>Testing it:</p>\n\n<pre><code>&gt;&gt;&gt; smart_truncate('The quick brown fox jumped over the lazy dog.', 23) + \"...\"\n'The quick brown fox...'\n</code></pre>\n" }, { "answer_id": 250471, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 3, "selected": false, "text": "<pre><code>def smart_truncate1(text, max_length=100, suffix='...'):\n \"\"\"Returns a string of at most `max_length` characters, cutting\n only at word-boundaries. If the string was truncated, `suffix`\n will be appended.\n \"\"\"\n\n if len(text) &gt; max_length:\n pattern = r'^(.{0,%d}\\S)\\s.*' % (max_length-len(suffix)-1)\n return re.sub(pattern, r'\\1' + suffix, text)\n else:\n return text\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>def smart_truncate2(text, min_length=100, suffix='...'):\n \"\"\"If the `text` is more than `min_length` characters long,\n it will be cut at the next word-boundary and `suffix`will\n be appended.\n \"\"\"\n\n pattern = r'^(.{%d,}?\\S)\\s.*' % (min_length-1)\n return re.sub(pattern, r'\\1' + suffix, text)\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>def smart_truncate3(text, length=100, suffix='...'):\n \"\"\"Truncates `text`, on a word boundary, as close to\n the target length it can come.\n \"\"\"\n\n slen = len(suffix)\n pattern = r'^(.{0,%d}\\S)\\s+\\S+' % (length-slen-1)\n if len(text) &gt; length:\n match = re.match(pattern, text)\n if match:\n length0 = match.end(0)\n length1 = match.end(1)\n if abs(length0+slen-length) &lt; abs(length1+slen-length):\n return match.group(0) + suffix\n else:\n return match.group(1) + suffix\n return text\n</code></pre>\n" }, { "answer_id": 250684, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 4, "selected": false, "text": "<p>There are a few subtleties that may or may not be issues for you, such as handling of tabs (Eg. if you're displaying them as 8 spaces, but treating them as 1 character internally), handling various flavours of breaking and non-breaking whitespace, or allowing breaking on hyphenation etc. If any of this is desirable, you may want to take a look at the textwrap module. eg:</p>\n\n<pre><code>def truncate(text, max_size):\n if len(text) &lt;= max_size:\n return text\n return textwrap.wrap(text, max_size-3)[0] + \"...\"\n</code></pre>\n\n<p>The default behaviour for words greater than max_size is to break them (making max_size a hard limit). You can change to the soft limit used by some of the other solutions here by passing break_long_words=False to wrap(), in which case it will return the whole word. If you want this behaviour change the last line to:</p>\n\n<pre><code> lines = textwrap.wrap(text, max_size-3, break_long_words=False)\n return lines[0] + (\"...\" if len(lines)&gt;1 else \"\")\n</code></pre>\n\n<p>There are a few other options like expand_tabs that may be of interest depending on the exact behaviour you want.</p>\n" }, { "answer_id": 20821663, "author": "Anthony", "author_id": 203204, "author_profile": "https://Stackoverflow.com/users/203204", "pm_score": 3, "selected": false, "text": "<pre><code>&gt;&gt;&gt; import textwrap\n&gt;&gt;&gt; textwrap.wrap('The quick brown fox jumps over the lazy dog', 12)\n['The quick', 'brown fox', 'jumps over', 'the lazy dog']\n</code></pre>\n\n<p>You just take the first element of that and you're done...</p>\n" }, { "answer_id": 47296254, "author": "marcanuy", "author_id": 1165509, "author_profile": "https://Stackoverflow.com/users/1165509", "pm_score": 2, "selected": false, "text": "<p>From Python 3.4+ you can use <a href=\"https://docs.python.org/3/library/textwrap.html#textwrap.shorten\" rel=\"nofollow noreferrer\">textwrap.shorten</a>. With the OP example:</p>\n\n<pre><code>&gt;&gt;&gt; import textwrap\n&gt;&gt;&gt; original = \"This is really awesome.\"\n&gt;&gt;&gt; textwrap.shorten(original, width=20, placeholder=\"...\")\n'This is really...'\n</code></pre>\n\n<blockquote>\n <p>textwrap.shorten(text, width, **kwargs)</p>\n \n <p>Collapse and truncate the given text to fit in the given width.</p>\n \n <p>First the whitespace in text is collapsed (all whitespace is replaced by single spaces). If the result fits in the width, it is\n returned. Otherwise, enough words are dropped from the end so that the\n remaining words plus the placeholder fit within width:</p>\n</blockquote>\n" }, { "answer_id": 65020386, "author": "Jorge Barata", "author_id": 959819, "author_profile": "https://Stackoverflow.com/users/959819", "pm_score": 0, "selected": false, "text": "<p>For Python 3.4+, I'd use <a href=\"https://docs.python.org/3/library/textwrap.html#textwrap.shorten\" rel=\"nofollow noreferrer\">textwrap.shorten</a>.</p>\n<p>For older versions:</p>\n<pre><code>def truncate(description, max_len=140, suffix='…'): \n description = description.strip()\n if len(description) &lt;= max_len:\n return description\n new_description = ''\n for word in description.split(' '):\n tmp_description = new_description + word\n if len(tmp_description) &lt;= max_len-len(suffix):\n new_description = tmp_description + ' '\n else:\n new_description = new_description.strip() + suffix\n break\n return new_description\n</code></pre>\n" }, { "answer_id": 65836694, "author": "CPBL", "author_id": 1159005, "author_profile": "https://Stackoverflow.com/users/1159005", "pm_score": 0, "selected": false, "text": "<p>In case you might actually prefer to truncate by full sentence rather than by word, here's something to start with:</p>\n<pre><code>def smart_truncate_by_sentence(content, length=100, suffix='...',):\n if not isinstance(content,str): return content\n if len(content) &lt;= length:\n return content\n else:\n sentences=content.split('.')\n cs=np.cumsum([len(s) for s in sentences])\n n = max(1, len(cs[cs&lt;length]) )\n return '.'.join(sentences[:n])+ '. ...'*(n&lt;len(sentences))\n</code></pre>\n" }, { "answer_id": 70512067, "author": "Claud", "author_id": 4844186, "author_profile": "https://Stackoverflow.com/users/4844186", "pm_score": 0, "selected": false, "text": "<p>C++ version:</p>\n<pre><code>string trim(string s, int k) {\n if (s.size()&lt;=k) return s;\n while(k&gt;=0 &amp;&amp; s[k]!=' ')\n k--;\n if (k&lt;0) return &quot;&quot;;\n string res=s.substr(0, k+1);\n while(res.size() &amp;&amp; (res.back()==' '))\n res.pop_back();\n return res; \n}\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24998/" ]
I am looking for a way to truncate a string in Python that will not cut off the string in the middle of a word. For example: ``` Original: "This is really awesome." "Dumb" truncate: "This is real..." "Smart" truncate: "This is really..." ``` I'm looking for a way to accomplish the "smart" truncate from above.
I actually wrote a solution for this on a recent project of mine. I've compressed the majority of it down to be a little smaller. ``` def smart_truncate(content, length=100, suffix='...'): if len(content) <= length: return content else: return ' '.join(content[:length+1].split(' ')[0:-1]) + suffix ``` What happens is the if-statement checks if your content is already less than the cutoff point. If it's not, it truncates to the desired length, splits on the space, removes the last element (so that you don't cut off a word), and then joins it back together (while tacking on the '...').
250,375
<p>for some reason, templatetags do not render in templates for django admin.</p> <p>with this snippet from: <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/?from=olddocs#shortcut-for-simple-tags" rel="nofollow noreferrer">http://docs.djangoproject.com/en/dev/ref/templates/api/?from=olddocs#shortcut-for-simple-tags</a></p> <pre><code>{% if is_logged_in %}Thanks for logging in!{% else %}Please log in.{% endif %} </code></pre> <p>when placed in admin index.html, if a user is logged in, it shows "Please log in"</p> <p>same with templatetags, can not get any app ones to show, do anything. there is no error/they do not get processed either </p>
[ { "answer_id": 250479, "author": "Brett", "author_id": 11958, "author_profile": "https://Stackoverflow.com/users/11958", "pm_score": 3, "selected": false, "text": "<p>That's only an example, the <code>is_logged_in</code> variable is not actually defined in any templates unless you put it in the context.</p>\n\n<p>If you added that line and got <code>Please log in.</code> it does mean that the tag is rendering. If it fails the <code>if</code> and goes to the <code>else</code> it is clearly being run. You need to find something in the template you can actually use for the <code>if</code> case, though. I haven't messed with the admin templates in newforms-admin, but depending if they use RequestContext and on which ContextProcessors you have enabled - you might be able to say <code>{% if not request.user.is_anonymous %} ...</code> or something similar.</p>\n" }, { "answer_id": 6434790, "author": "THLopes", "author_id": 762016, "author_profile": "https://Stackoverflow.com/users/762016", "pm_score": 0, "selected": false, "text": "<p>I just tried this one:</p>\n\n<p>request.user.is_authenticated</p>\n\n<p>Right in the template and just worked as we wish!</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
for some reason, templatetags do not render in templates for django admin. with this snippet from: <http://docs.djangoproject.com/en/dev/ref/templates/api/?from=olddocs#shortcut-for-simple-tags> ``` {% if is_logged_in %}Thanks for logging in!{% else %}Please log in.{% endif %} ``` when placed in admin index.html, if a user is logged in, it shows "Please log in" same with templatetags, can not get any app ones to show, do anything. there is no error/they do not get processed either
That's only an example, the `is_logged_in` variable is not actually defined in any templates unless you put it in the context. If you added that line and got `Please log in.` it does mean that the tag is rendering. If it fails the `if` and goes to the `else` it is clearly being run. You need to find something in the template you can actually use for the `if` case, though. I haven't messed with the admin templates in newforms-admin, but depending if they use RequestContext and on which ContextProcessors you have enabled - you might be able to say `{% if not request.user.is_anonymous %} ...` or something similar.
250,398
<p>I can't find any proper documentation on how to specify relations using the declarative syntax of SQLAlchemy.. Is it unsupported? That is, should I use the "traditional" syntax?<br> I am looking for a way to specify relations at a higher level, avoiding having to mess with foreign keys etc.. I'd like to just declare "addresses = OneToMany(Address)" and let the framework handle the details.. I know that Elixir can do that, but I was wondering if "plain" SQLA could do it too.<br> Thanks for your help!</p>
[ { "answer_id": 251077, "author": "Ali Afshar", "author_id": 28380, "author_profile": "https://Stackoverflow.com/users/28380", "pm_score": 3, "selected": true, "text": "<p>Assuming you are referring to <a href=\"http://www.sqlalchemy.org/docs/04/plugins.html#plugins_declarative\" rel=\"nofollow noreferrer\">the declarative plugin</a>, where everything I am about to say is documented with examples:</p>\n\n<pre><code>class User(Base):\n __tablename__ = 'users'\n\n id = Column('id', Integer, primary_key=True)\n addresses = relation(\"Address\", backref=\"user\")\n\nclass Address(Base):\n __tablename__ = 'addresses'\n\n id = Column('id', Integer, primary_key=True)\n user_id = Column('user_id', Integer, ForeignKey('users.id'))\n</code></pre>\n" }, { "answer_id": 1094626, "author": "Gregg Lind", "author_id": 15842, "author_profile": "https://Stackoverflow.com/users/15842", "pm_score": 0, "selected": false, "text": "<p>Look at the \"Configuring Relations\" section of the <a href=\"http://www.sqlalchemy.org/docs/05/reference/ext/declarative.html\" rel=\"nofollow noreferrer\">Declarative docs</a>. Not quite as high level as \"OneToMany\" but better than fully specifying the relation. </p>\n\n<pre><code>class Address(Base):\n __tablename__ = 'addresses'\n\n id = Column(Integer, primary_key=True)\n email = Column(String(50))\n user_id = Column(Integer, ForeignKey('users.id'))\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3497/" ]
I can't find any proper documentation on how to specify relations using the declarative syntax of SQLAlchemy.. Is it unsupported? That is, should I use the "traditional" syntax? I am looking for a way to specify relations at a higher level, avoiding having to mess with foreign keys etc.. I'd like to just declare "addresses = OneToMany(Address)" and let the framework handle the details.. I know that Elixir can do that, but I was wondering if "plain" SQLA could do it too. Thanks for your help!
Assuming you are referring to [the declarative plugin](http://www.sqlalchemy.org/docs/04/plugins.html#plugins_declarative), where everything I am about to say is documented with examples: ``` class User(Base): __tablename__ = 'users' id = Column('id', Integer, primary_key=True) addresses = relation("Address", backref="user") class Address(Base): __tablename__ = 'addresses' id = Column('id', Integer, primary_key=True) user_id = Column('user_id', Integer, ForeignKey('users.id')) ```
250,404
<p>I found <a href="https://stackoverflow.com/questions/122778/capture-console-output-for-debugging-in-vs">this question</a>, but what I want to know is different - does the output from Console.WriteLine go anywhere when debugging? I know that for it to go to the output window I should should Debug.WriteLine() or other methods, but where does the standard Console.WriteLine() go?</p> <p><strong>Edit</strong> When debugging, you don't see the black console window / test log - so the <strong>real question is</strong> how can I access/view this output during debugging?</p>
[ { "answer_id": 250411, "author": "chills42", "author_id": 23855, "author_profile": "https://Stackoverflow.com/users/23855", "pm_score": 0, "selected": false, "text": "<p>It goes to the console (standard output) or to the stream that the console is set to.</p>\n" }, { "answer_id": 250412, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": -1, "selected": false, "text": "<p>Console.writeline() goes to a console window: the black command / dos prompt.</p>\n" }, { "answer_id": 250507, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": -1, "selected": false, "text": "<p>Even in a WinForms app, you can create a console window, but you'll have to go through P/Invoke to call a Win32 method directly. See <a href=\"http://pinvoke.net/default.aspx/kernel32/AllocConsole.html\" rel=\"nofollow noreferrer\">http://pinvoke.net/default.aspx/kernel32/AllocConsole.html</a></p>\n" }, { "answer_id": 250552, "author": "Samuel", "author_id": 32465, "author_profile": "https://Stackoverflow.com/users/32465", "pm_score": 2, "selected": false, "text": "<p>Debug and Release do not control whether or not you get a console window. That is controlled by the project's output type. (Properties -> Application -> Output Type).\nConsole Application will get you a console window which will visualize and receive input from the window into the Error, In, and Out streams in System.Console.</p>\n\n<p>The System.Console class exposes several properties and methods for interacting with its streams even if you cannot see it. Most notably: Error, In, Out, SetError(), SetIn(), SetOut(), and the Read and Write methods.</p>\n" }, { "answer_id": 2075892, "author": "AMissico", "author_id": 163921, "author_profile": "https://Stackoverflow.com/users/163921", "pm_score": 3, "selected": false, "text": "<p><code>NullStream</code>, which is defined as \"A Stream with no backing store.\". All the methods do nothing or return nothing. It is an internal class to <code>Stream</code>. The following code is taken from Microsoft's source code.</p>\n\n<p>Basically, when one of the <code>Console</code> write methods is call the first time, a call is made to the Windows API function <code>GetStdHandle</code> for \"standard output\". If no handle is returned a <code>NullStream</code> is created and used.</p>\n\n<p>Samuel's answer is correct and provides general information. To actually redirect Console output, regardless of the project type, use <code>Console.SetOut(New System.IO.StreamWriter(\"C:\\ConsoleOutput.txt\"))</code>, which is a simple example.</p>\n\n<h3>Directing Console, Debug, and Trace to File</h3>\n\n<p>To answer your question directly. Use the <code>ConsoleTraceListener</code> and a <code>StreamWriter</code> to direct all three outputs to a file. I use the following for development only.</p>\n\n<pre><code> Dim oLogFile As New System.IO.StreamWriter(\"C:\\ConsoleOutput.txt\")\n oLogFile.AutoFlush = True 'so we do not have to worry about flushing before application exit\n\n Console.SetOut(oLogFile)\n\n 'note, writing to debug and trace causes output on console, so you will get double output in log file\n Dim oListener As New ConsoleTraceListener\n Debug.Listeners.Add(oListener)\n Trace.Listeners.Add(oListener)\n</code></pre>\n\n<h3>NullStream</h3>\n\n<pre><code>[Serializable]\nprivate sealed class NullStream : Stream {\n internal NullStream() { }\n\n public override bool CanRead {\n get { return true; }\n }\n\n public override bool CanWrite {\n get { return true; }\n }\n\n public override bool CanSeek {\n get { return true; }\n }\n\n public override long Length {\n get { return 0; }\n }\n\n public override long Position {\n get { return 0; }\n set { }\n }\n\n // No need to override Close\n\n public override void Flush() {\n }\n\n public override int Read([In, Out] byte[] buffer, int offset, int count) {\n return 0;\n }\n\n public override int ReadByte() {\n return -1;\n }\n\n public override void Write(byte[] buffer, int offset, int count) {\n }\n\n public override void WriteByte(byte value) {\n }\n\n public override long Seek(long offset, SeekOrigin origin) {\n return 0;\n }\n\n public override void SetLength(long length) {\n }\n} \n</code></pre>\n" }, { "answer_id": 5287537, "author": "rogerdpack", "author_id": 32453, "author_profile": "https://Stackoverflow.com/users/32453", "pm_score": 1, "selected": false, "text": "<p>I'll actually second James on this one.</p>\n\n<p><a href=\"http://www.csharp411.com/console-output-from-winforms-application\" rel=\"nofollow\">http://www.csharp411.com/console-output-from-winforms-application</a></p>\n\n<p>describes it in gross detail (if directing output to a file is enough though then you could easily use amissico's method). Most of the methods they describe mimic those described in <a href=\"http://dslweb.nwnexus.com/~ast/dload/guicon.htm\" rel=\"nofollow\">http://dslweb.nwnexus.com/~ast/dload/guicon.htm</a></p>\n\n<p>Changing your project to a \"console\" project would have a similar effect, as mentioned. Cheers!</p>\n" }, { "answer_id": 5577749, "author": "Carl R", "author_id": 480986, "author_profile": "https://Stackoverflow.com/users/480986", "pm_score": 4, "selected": false, "text": "<p>The console can redirect it's output to any textwriter. If you implement a textwriter that writes to Diagnostics.Debug, you are all set.</p>\n\n<p>Here's a textwriter that writes to the debugger.</p>\n\n<pre><code>using System.Diagnostics;\nusing System.IO;\nusing System.Text;\n\nnamespace TestConsole\n{\n public class DebugTextWriter : TextWriter\n {\n public override Encoding Encoding\n {\n get { return Encoding.UTF8; }\n }\n\n //Required\n public override void Write(char value)\n {\n Debug.Write(value);\n }\n\n //Added for efficiency\n public override void Write(string value)\n {\n Debug.Write(value);\n }\n\n //Added for efficiency\n public override void WriteLine(string value)\n {\n Debug.WriteLine(value);\n }\n }\n}\n</code></pre>\n\n<p>Since it uses Diagnostics.Debug it will adhere to your compiler settings to wether it should write any output or not. This output can also be seen in Sysinternals DebugView.</p>\n\n<p>Here's how you use it:</p>\n\n<pre><code>using System;\n\nnamespace TestConsole\n{\n class Program\n {\n static void Main(string[] args)\n {\n Console.SetOut(new DebugTextWriter());\n Console.WriteLine(\"This text goes to the Visual Studio output window.\");\n }\n }\n}\n</code></pre>\n\n<p>If you want to see the output in Sysinternals DebugView when you are compiling in Release mode, you can use a TextWriter that writes to the OutputDebugString API. It could look like this:</p>\n\n<pre><code>using System.IO;\nusing System.Runtime.InteropServices;\nusing System.Text;\n\nnamespace TestConsole\n{\n public class OutputDebugStringTextWriter : TextWriter\n {\n [DllImport(\"kernel32.dll\")]\n static extern void OutputDebugString(string lpOutputString);\n\n public override Encoding Encoding\n {\n get { return Encoding.UTF8; }\n }\n\n //Required\n public override void Write(char value)\n {\n OutputDebugString(value.ToString());\n }\n\n //Added for efficiency\n public override void Write(string value)\n {\n OutputDebugString(value);\n }\n\n //Added for efficiency\n public override void WriteLine(string value)\n {\n OutputDebugString(value);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 47306894, "author": "Remus Rusanu", "author_id": 105929, "author_profile": "https://Stackoverflow.com/users/105929", "pm_score": 1, "selected": false, "text": "<p>Visual Studio launches Windows programs (<a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/target-winexe-compiler-option\" rel=\"nofollow noreferrer\"><code>/target:winexe</code></a>) with the stdin/stdout/stderr <em>redirected</em> to Named Pipes. The other end of each pipe is owned by the VS debugger and anything read on stderr/stdout is displayed in the Debug Output Window. Hence, <code>Console.Write</code> auto-magically appears in the VS Debug output. Note that this does not happen if you <em>attach</em> to an already started process (since the redirect trick can only be done at process launch time). </p>\n\n<p>When launching console programs (<a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/target-exe-compiler-option\" rel=\"nofollow noreferrer\"><code>/target:exe</code></a>) this redirect does not occur so the <code>Console.Write</code> goes tothe actual console (or wherever the <code>stdout</code> is redirected).</p>\n\n<p>I couldn't find anything that documents this behavior, is just my conclusion from investigating how VS launches and debugs apps.</p>\n" }, { "answer_id": 50456898, "author": "Corey Byrum", "author_id": 7723049, "author_profile": "https://Stackoverflow.com/users/7723049", "pm_score": 3, "selected": false, "text": "<p>The best solution for me was to change Console.WriteLine() to System.Diagnostics.Debug.WriteLine().\nFor example:</p>\n\n<pre><code> catch (DbEntityValidationException dbEx)\n {\n foreach (var validationErrors in dbEx.EntityValidationErrors)\n {\n foreach (var validationError in validationErrors.ValidationErrors)\n {\n System.Diagnostics.Debug.WriteLine(\"Property: {0} Error: {1}\", validationError.PropertyName, validationError.ErrorMessage);\n }\n }\n</code></pre>\n\n<p>Then you can view your errors as an object in the output window.</p>\n" }, { "answer_id": 60656340, "author": "s3c", "author_id": 9583480, "author_profile": "https://Stackoverflow.com/users/9583480", "pm_score": 0, "selected": false, "text": "<p>As already commented on OP's question:</p>\n\n<p><strong>No need to write additional code</strong></p>\n\n<p>In Visual Studio uppermost menu choose</p>\n\n<blockquote>\n <p>Debug > Windows > Output</p>\n</blockquote>\n\n<p>The output windows will only be visible in debug mode and it will show all e.g.\n<code>Console.WriteLine(\"Debug MyVariable: \" + MyVariable)</code>\nwhen you get to them.</p>\n\n<p>Set a breakpoint before (click the different-coloured empty area before the line number at the start of a chosen line), debug (F5), and then step through code line by line (F11) until you do.</p>\n" }, { "answer_id": 73628954, "author": "Justin Edwards", "author_id": 13360064, "author_profile": "https://Stackoverflow.com/users/13360064", "pm_score": 1, "selected": false, "text": "<p>Just add <code>using System.Diagnostics;</code> to your namespace. Then, use Debug instead of Console.\n<br>Example: <code>Debug.WriteLine(&quot;Hello World&quot;);</code><br>Finally, press Ctrl+Alt+O to open the output window. Your text will be printed there. This window usually appears docked at the bottom of Visual Studio, but it can be dragged out and moved anywhere. <br>NOTE: There will be a dropdown box in the upper left corner that is called &quot;Show output from:&quot;<br>• &quot;Debug&quot; will need to be selected.<br> Alternatively, the output window can also be opened by selecting clicking the view tab and selecting Output.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11236/" ]
I found [this question](https://stackoverflow.com/questions/122778/capture-console-output-for-debugging-in-vs), but what I want to know is different - does the output from Console.WriteLine go anywhere when debugging? I know that for it to go to the output window I should should Debug.WriteLine() or other methods, but where does the standard Console.WriteLine() go? **Edit** When debugging, you don't see the black console window / test log - so the **real question is** how can I access/view this output during debugging?
The console can redirect it's output to any textwriter. If you implement a textwriter that writes to Diagnostics.Debug, you are all set. Here's a textwriter that writes to the debugger. ``` using System.Diagnostics; using System.IO; using System.Text; namespace TestConsole { public class DebugTextWriter : TextWriter { public override Encoding Encoding { get { return Encoding.UTF8; } } //Required public override void Write(char value) { Debug.Write(value); } //Added for efficiency public override void Write(string value) { Debug.Write(value); } //Added for efficiency public override void WriteLine(string value) { Debug.WriteLine(value); } } } ``` Since it uses Diagnostics.Debug it will adhere to your compiler settings to wether it should write any output or not. This output can also be seen in Sysinternals DebugView. Here's how you use it: ``` using System; namespace TestConsole { class Program { static void Main(string[] args) { Console.SetOut(new DebugTextWriter()); Console.WriteLine("This text goes to the Visual Studio output window."); } } } ``` If you want to see the output in Sysinternals DebugView when you are compiling in Release mode, you can use a TextWriter that writes to the OutputDebugString API. It could look like this: ``` using System.IO; using System.Runtime.InteropServices; using System.Text; namespace TestConsole { public class OutputDebugStringTextWriter : TextWriter { [DllImport("kernel32.dll")] static extern void OutputDebugString(string lpOutputString); public override Encoding Encoding { get { return Encoding.UTF8; } } //Required public override void Write(char value) { OutputDebugString(value.ToString()); } //Added for efficiency public override void Write(string value) { OutputDebugString(value); } //Added for efficiency public override void WriteLine(string value) { OutputDebugString(value); } } } ```
250,408
<p>I tried the example from Rails Cookbook and managed to get it to work. However the <code>text_field_with_auto_complete</code> works only for one value.</p> <pre><code>class Expense &lt; ActiveRecord::Base has_and_belongs_to_many :categories end </code></pre> <p>In the New Expense View rhtml</p> <pre><code>&lt;%= text_field_with_auto_complete :category, :name %&gt; </code></pre> <p>Auto complete works for the first category. How do I get it working for multiple categories? e.g. Category1, Category2<br> <em>Intended behavior: like the StackOverflow Tags textbox</em></p> <p><strong>Update:</strong><br> With some help and some more tinkering, I got multiple comma-seperated autocomplete to show up (will post code-sample here).<br> <em>However on selection, the last value replaces the content of the text_field_with_auto_complete.</em> So instead of Category1, Category2.. the textbox shows Category2 when the second Category is selected via auto-complete. Any ideas how to rectify this? </p>
[ { "answer_id": 265211, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>If you are just trying to support multiple instances of autocomplete per field, you can pass a delimiter to the autocomplete options with the symbol :token. This provides a delimiter to allow multiple results. Stackoverflow would use :token => ' ' (there should be a space between the quotes, but the autoformat is removing it) to specify space at the delimiter between multiple takes although ',' is more commonly used.</p>\n" }, { "answer_id": 272735, "author": "Cameron Price", "author_id": 35526, "author_profile": "https://Stackoverflow.com/users/35526", "pm_score": 0, "selected": false, "text": "<p>This is not quite your question, but I wouldn't recommend using HABTM anymore. You should create a join model and use has_many :through. (In your case you'd create a new model called ExpenseCategoryAssignment, or something)</p>\n\n<p>The problem is that HABTM creates ambiguities that rails doesn't like, and it tends to expose bugs you wouldn't see otherwise.</p>\n" }, { "answer_id": 9945411, "author": "Rustam A. Gasanov", "author_id": 644810, "author_profile": "https://Stackoverflow.com/users/644810", "pm_score": 0, "selected": false, "text": "<p>You need to use \"data-delimiter\" param like this<br>\n<code>&lt;%= f.autocomplete_field :brand_name, welcome_autocomplete_brand_name_path, \"data-delimiter\" =&gt; ', ' %&gt;</code></p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
I tried the example from Rails Cookbook and managed to get it to work. However the `text_field_with_auto_complete` works only for one value. ``` class Expense < ActiveRecord::Base has_and_belongs_to_many :categories end ``` In the New Expense View rhtml ``` <%= text_field_with_auto_complete :category, :name %> ``` Auto complete works for the first category. How do I get it working for multiple categories? e.g. Category1, Category2 *Intended behavior: like the StackOverflow Tags textbox* **Update:** With some help and some more tinkering, I got multiple comma-seperated autocomplete to show up (will post code-sample here). *However on selection, the last value replaces the content of the text\_field\_with\_auto\_complete.* So instead of Category1, Category2.. the textbox shows Category2 when the second Category is selected via auto-complete. Any ideas how to rectify this?
If you are just trying to support multiple instances of autocomplete per field, you can pass a delimiter to the autocomplete options with the symbol :token. This provides a delimiter to allow multiple results. Stackoverflow would use :token => ' ' (there should be a space between the quotes, but the autoformat is removing it) to specify space at the delimiter between multiple takes although ',' is more commonly used.
250,421
<p>I am writing a macro for Visual studio that will generate some code.</p> <p>I would like for the macro to generate for both C# and VB, is there a way to determine what language is being used in the active (current) document?</p>
[ { "answer_id": 250437, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 2, "selected": false, "text": "<p>Have you considered using <a href=\"http://www.hanselman.com/blog/T4TextTemplateTransformationToolkitCodeGenerationBestKeptVisualStudioSecret.aspx\" rel=\"nofollow noreferrer\">T4</a>?</p>\n\n<p>T4 is a code generator built right into Visual Studio. If you're using C#, you'll have a sub .cs file, or if you're using VB, a sub .vb file. That's the file that will hold the result of the generation. This is the same visual metaphor used to the express the template/generated file relationship with .designer files you've seen elsewhere in Visual Studio. </p>\n" }, { "answer_id": 250532, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 3, "selected": true, "text": "<p>I just located a bit of code, it seems that it's a hidden property:</p>\n\n<pre><code>DTE.ActiveDocument.Language = \"CSharp\"\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30492/" ]
I am writing a macro for Visual studio that will generate some code. I would like for the macro to generate for both C# and VB, is there a way to determine what language is being used in the active (current) document?
I just located a bit of code, it seems that it's a hidden property: ``` DTE.ActiveDocument.Language = "CSharp" ```
250,423
<p>I'm a web developer with no formal computing background behind me, I've been writing code now some years now, but every time I need to create a new class / function / variable, I spend about two minutes just deciding on a name and then how to type it.</p> <p>For instance, if I write a function to sum up a bunch of numbers. Should I call it</p> <pre><code>Sum() GetSum() getSum() get_sum() AddNumbersReturnTotal() </code></pre> <p>I know there is a right way to do this, and a link to a good definitive source is all I ask :D</p> <p><strong>Closed as a duplicate of <a href="https://stackoverflow.com/questions/14967/c-coding-standard-best-practices">c# Coding standard / Best practices</a></strong></p>
[ { "answer_id": 250430, "author": "chills42", "author_id": 23855, "author_profile": "https://Stackoverflow.com/users/23855", "pm_score": 3, "selected": false, "text": "<p>You're looking for <a href=\"http://code.msdn.microsoft.com/sourceanalysis\" rel=\"nofollow noreferrer\">StyleCop</a>.</p>\n" }, { "answer_id": 250435, "author": "Thomas Owens", "author_id": 572, "author_profile": "https://Stackoverflow.com/users/572", "pm_score": 1, "selected": false, "text": "<p>All of the above.</p>\n\n<p>I believe the official C# guidelines would say call it calculateSum() as getSum() would be used if the sum was an instance variable. But it depends on the coding style used and how any existing code in the project is written.</p>\n" }, { "answer_id": 250439, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Luckily enough I don't believe there is a standardized way this is done. I pick the one that I like, which consequently also seems to be the standard all other source code I've seen uses, and run with it.</p>\n" }, { "answer_id": 250440, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "<p><code>Sum()</code> if it's public and does the work itself.</p>\n\n<p><code>GetSum()</code> if it's public and it retrieves the information from somewhere else.</p>\n\n<p>sum() / getSum() as above, but for internal/private methods.</p>\n\n<p>(Hmm... That's a bit vague, since you shift the meaning of \"Sum\" there slightly. So, let try this again.</p>\n\n<p><code>XXX</code> if xxx is a process (summing values).\n<code>GetXXX</code> if xxx is a thing. (the sum of the values)</p>\n" }, { "answer_id": 250442, "author": "Nicholas Mancuso", "author_id": 8945, "author_profile": "https://Stackoverflow.com/users/8945", "pm_score": 3, "selected": true, "text": "<p>Classes should be in camel notation with the first letter capitalized</p>\n\n<pre><code>public class MyClass\n</code></pre>\n\n<p>Functions and Methods in C# should act in a similar fashion except for private methods</p>\n\n<pre><code>public void MyMethod()\nprivate void myPrivateMethod()\n</code></pre>\n\n<p>Variables I tend to do a little differently:</p>\n\n<p>Member Variables</p>\n\n<pre><code>private int _count;\n</code></pre>\n\n<p>Local variables</p>\n\n<pre><code>int count;\n</code></pre>\n" }, { "answer_id": 250449, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>I agree on the calculate vs get distinction: get() should be used for values that are already calculated or otherwise trivial to retrieve.</p>\n\n<p>Additionally, I would suggest in many cases adding a noun to the name, so that it's obvious exactly what sum you are calculating. Unless, of course, the noun you would add <em>is</em> the class name or type itself.</p>\n" }, { "answer_id": 250480, "author": "Tim Robinson", "author_id": 32133, "author_profile": "https://Stackoverflow.com/users/32133", "pm_score": 0, "selected": false, "text": "<p>Method names are verbs. Class, field and property names are nouns. In this case, <code>Sum</code> could pass as either a verb or a noun...</p>\n\n<p><code>AddNumbersReturnTotal</code> fits the above definition, but it's a little long. Out of kindness to the guy who gets to maintain my code (usually me!) I try and avoid including redundant words in identifiers, and I try to avoid words that are easy to make typos on.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31765/" ]
I'm a web developer with no formal computing background behind me, I've been writing code now some years now, but every time I need to create a new class / function / variable, I spend about two minutes just deciding on a name and then how to type it. For instance, if I write a function to sum up a bunch of numbers. Should I call it ``` Sum() GetSum() getSum() get_sum() AddNumbersReturnTotal() ``` I know there is a right way to do this, and a link to a good definitive source is all I ask :D **Closed as a duplicate of [c# Coding standard / Best practices](https://stackoverflow.com/questions/14967/c-coding-standard-best-practices)**
Classes should be in camel notation with the first letter capitalized ``` public class MyClass ``` Functions and Methods in C# should act in a similar fashion except for private methods ``` public void MyMethod() private void myPrivateMethod() ``` Variables I tend to do a little differently: Member Variables ``` private int _count; ``` Local variables ``` int count; ```
250,468
<p>Is the SqlClient.SqlDataReader a .NET managed object or not? Why do we have to call the Close() method explicitly close an open connection? Shouldn't running out of scope for such an object automatically close this? Shouldn't garbage collector clean it up anyway?</p> <p>Please help me understand what is the best practise here.</p> <p>I have seen a related question <a href="https://stackoverflow.com/questions/247311/sqldatareader-in-this-scenario-will-the-reader-get-closed">here</a> and it further illustrates the issue I have with a web application. The issue is that we were running out of connections. The detailed error is here:</p> <pre><code>Exception: System.InvalidOperationException Message: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached. Source: System.Data at System.Data.SqlClient.SqlConnectionPoolManager.GetPooledConnection(SqlConnectionString options, Boolean&amp; isInTransaction) at System.Data.SqlClient.SqlConnection.Open() </code></pre> <p>To fix this, I had to explicitly close all the SQLDataReader objects.</p> <p>I am using .NET Framework 3.5</p>
[ { "answer_id": 250478, "author": "wprl", "author_id": 17847, "author_profile": "https://Stackoverflow.com/users/17847", "pm_score": 6, "selected": true, "text": "<p>Sure, it will be collected when it goes out of scope (if their are no other references to it). When it is collected, it will be closed through its Dispose() method. However, you never really know when the GC is going to deallocate things; if you don't close your readers, you very quickly run out of available connections to the database.</p>\n\n<h2>Further Reading</h2>\n\n<ul>\n<li>O'Reilly's <a href=\"http://www.ondotnet.com/pub/a/dotnet/2004/02/09/connpool.html\" rel=\"noreferrer\">ADO.NET Connection Pool Explained</a></li>\n<li>Microsoft's <a href=\"http://msdn.microsoft.com/en-us/library/haa3afyz(VS.71).aspx\" rel=\"noreferrer\">Retrieving Data using a DataReader</a> has a general overview of DataReaders.</li>\n</ul>\n\n<p>~ William Riley-Land</p>\n" }, { "answer_id": 250493, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>The 'managed' resource referred to by the term 'managed code' is memory. That's it. Any other scarce resource needs to be wrapped with the disposable pattern, including database connections.</p>\n\n<p>The reason this is a problem for you is that the garbage collector doesn't run for every object the moment it goes out of scope. It's much more efficient to collect more items less frequently. So if you wait for the collector to dispose your objects (and yes, if you implement idisposable it eventually will) you maybe be holding a number of database connections open much longer than you realize.</p>\n" }, { "answer_id": 250513, "author": "Lieutenant Frost", "author_id": 2018855, "author_profile": "https://Stackoverflow.com/users/2018855", "pm_score": 1, "selected": false, "text": "<p>Also take into consideration what happens when an exception gets thrown - you never know if the connection will be closed if you suddenly are forced out of the executing code. </p>\n\n<p>As a rule in our shop, we explicitly wrap all database calls in a Try...Finally block, with the finally section catching and closing the data connections. It's worth the tiny bit of effort to save yourself a major troubleshooting headache.</p>\n" }, { "answer_id": 250535, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 4, "selected": false, "text": "<p>@Lieutenant Frost</p>\n\n<blockquote>\n <p>As a rule in our shop, we explicitly\n wrap all database calls in a\n Try...Finally block, with the finally\n section catching and closing the data\n connections. It's worth the tiny bit\n of effort to save yourself a major\n troubleshooting headache.</p>\n</blockquote>\n\n<p>I have a similar rule, but I require that objects implementing IDisposable use the 'using' block.</p>\n\n<pre><code>using (SqlConnection conn = new SqlConnection(conStr))\n{\n using (SqlCommand command = new SqlCommand())\n {\n // ETC\n } \n}\n</code></pre>\n\n<p>The using block calls Dispose immediately when leaving the scope, even with an exception. </p>\n" }, { "answer_id": 250551, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "<p>It's not the Connection that's the problem, but the SQL Cursor being held by the SqlDataReader. If you try to open a second without closing the first, it will throw an exception.</p>\n" }, { "answer_id": 250557, "author": "Jeffrey Harrington", "author_id": 4307, "author_profile": "https://Stackoverflow.com/users/4307", "pm_score": 4, "selected": false, "text": "<p>One good practice (as long as you aren't re-using connections) is to add the Command Behavior to the SqlDataReader to close the connection when it gets disposed:</p>\n\n<pre><code>SqlDataReader rdr = cmd.ExecuteReader( CommandBehavior.CloseConnection );\n</code></pre>\n\n<p>Adding this will ensure that the connection to the database is closed when the SqlDataReader object is closed (or garbage collected). </p>\n\n<p>As I stated before, though, you don't want to do this if you are planning on re-using the database connection for another operation within the same method. </p>\n" }, { "answer_id": 251084, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 2, "selected": false, "text": "<p>If you don't explicitly close it, then it sits there waiting for the garbage collector to \"collect\" it... Only after that happens does it get released back to the ADO.Net Connection pool to be reused by another Connection.Open request, so during all the intervening time, any other requests for a connection will have to create a brand new one, even though there is a perfectly good one sitting there unused that could be used... </p>\n\n<p>Depending on how long it is before the GC runs, and how many Database requests are being executed, you could run out of available connections to the database.</p>\n\n<p>But there is a optional parameter on the Command.ExecuteReader() method, called CommandBehavior. This is an enumeration, with values: \nCommandBehavior.Default, CommandBehavior.SingleResult, CommandBehavior.SchemaOnly, CommandBehavior.KeyInfo, CommandBehavior.SingleRow, CommandBehavior.SequentialAccess, and CommandBehavior.CloseConnection </p>\n\n<p>This enumeration has a FlagsAttribute attribute that allows a bitwise combination of its member values. It is the last value, (CommandBehavior.CloseConnection) that is relevant here. It tells the Command object to close the connection when the data reader is closed.\n<a href=\"http://msdn.microsoft.com/en-us/library/system.data.commandbehavior.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.data.commandbehavior.aspx</a> </p>\n\n<p>Unfortunately the default is NOT to close the connection when the data reader is closed, but you can, (and should) pass this parameter as CommandBehavior.CloseConnection when you want your method to release the connection back to the pool immediately when you are done with it... </p>\n" }, { "answer_id": 251228, "author": "Will Rickards", "author_id": 290835, "author_profile": "https://Stackoverflow.com/users/290835", "pm_score": 2, "selected": false, "text": "<p>I think everybody else said this but I wanted it to be clear: </p>\n\n<p>Out of scope doesn't mean immediate garbage collection.</p>\n\n<p>Your app needs to 'play nice' on a number of levels.\nClosing the connections helps you do that.\nLet's examine a few of those levels.</p>\n\n<p>1: You aren't relying on garbage collection.\nIdeally garbage collection shouldn't need to exist. But it does.\nBut most assuredly you should not rely on it.</p>\n\n<p>2: You aren't holding your database connections.\nWhile connections are usually pooled, as you've found there is a limit.\nHolding this longer than necessary makes your app the bad apple.</p>\n\n<p>3: You aren't generating network traffic.\nEvery database connection is essentially a TCP connection.\nKeeping it open probably generates network traffic along the lines of\nAre you still there? yes.\nSmall traffic yes, but on a crowded network this is bad practice.\nAnd SQL Server itself is using resources to keep your connection alive.\nResources other people trying to get to that sql server could make better use of.</p>\n\n<p>When thinking about database access you also have to think about network resources.\nSome ways to get the data are bad because they can bring unnecessary stuff along for the ride. The earlier versions of ADO were kind of notorious for this type of stuff. Bringing back the schema info when you just want the data. Sure, with only a few connections this isn't a problem. But since when does any database have only a few connections. So think about this stuff and try not to abuse the resources.</p>\n\n<p>When your web app only has 100 users you may not care.\nBut what about 100,000? Always consider what happens when you scale.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13370/" ]
Is the SqlClient.SqlDataReader a .NET managed object or not? Why do we have to call the Close() method explicitly close an open connection? Shouldn't running out of scope for such an object automatically close this? Shouldn't garbage collector clean it up anyway? Please help me understand what is the best practise here. I have seen a related question [here](https://stackoverflow.com/questions/247311/sqldatareader-in-this-scenario-will-the-reader-get-closed) and it further illustrates the issue I have with a web application. The issue is that we were running out of connections. The detailed error is here: ``` Exception: System.InvalidOperationException Message: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached. Source: System.Data at System.Data.SqlClient.SqlConnectionPoolManager.GetPooledConnection(SqlConnectionString options, Boolean& isInTransaction) at System.Data.SqlClient.SqlConnection.Open() ``` To fix this, I had to explicitly close all the SQLDataReader objects. I am using .NET Framework 3.5
Sure, it will be collected when it goes out of scope (if their are no other references to it). When it is collected, it will be closed through its Dispose() method. However, you never really know when the GC is going to deallocate things; if you don't close your readers, you very quickly run out of available connections to the database. Further Reading --------------- * O'Reilly's [ADO.NET Connection Pool Explained](http://www.ondotnet.com/pub/a/dotnet/2004/02/09/connpool.html) * Microsoft's [Retrieving Data using a DataReader](http://msdn.microsoft.com/en-us/library/haa3afyz(VS.71).aspx) has a general overview of DataReaders. ~ William Riley-Land
250,494
<p>I have a class that downloads, examines and saves some large XML files. Sometimes I want the UI to tell me what's going on, but sometimes I will use the class and ignore the events. So I have placed lines of code like this in a dozen places:</p> <pre><code>RaiseEvent Report("Sending request: " &amp; queryString) RaiseEvent Report("Saving file: " &amp; fileName) RaiseEvent Report("Finished") </code></pre> <p>My question is this - will these events slow down my code if nothing is listening for them? Will they even fire?</p>
[ { "answer_id": 250504, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "<p>There might be a small amount of overhead, but I wouldn't worry about it. Certainly the actual action is going to be the performance driver.</p>\n\n<p>As a side note: raising an event with no handlers in C# actually causes an exception to be thrown. VB.Net doesn't have this problem :)</p>\n" }, { "answer_id": 250830, "author": "Binary Worrier", "author_id": 18797, "author_profile": "https://Stackoverflow.com/users/18797", "pm_score": 4, "selected": true, "text": "<p>There is no magic, the code hiding under RaiseEvent does exactly what you'd expect, it iterates through a collection of handlers, and executes each one.\nThe overhead of checking to see are there any handlers is trivial, don't worry about it.</p>\n\n<p>If your <strong>REAL</strong> question is \"To save time, should I check that the events have handlers before raising the events?\" . . . then the answer is \"No\", you'll gain nothing by doing this.</p>\n\n<p>Also, don't worry about optimisation unless you need to (see this <a href=\"http://en.wikipedia.org/wiki/Code_optimization\" rel=\"nofollow noreferrer\">Wikipedia entry</a> to see why.)</p>\n\n<p>Re: Calling <code>GetMystring()</code>.</p>\n\n<p>Yes, this ties in with how you raise events in C#, where you check for the existence of handlers before raising the event.\nE.g.:</p>\n\n<pre><code>if (MyEvent != null)\n MyEvent(GetMyString())\n</code></pre>\n\n<p>Nice experiment by the way :)</p>\n" }, { "answer_id": 250897, "author": "Shane Miskin", "author_id": 16415, "author_profile": "https://Stackoverflow.com/users/16415", "pm_score": 3, "selected": false, "text": "<p>My own answer:</p>\n\n<p>In VB.NET the event does NOT fire if there are no handlers set up to listen for it.</p>\n\n<p>I did a little experiment where the code that raises the event passes the result of a function, and that function only executed when there was an event handler set up to handle the event.</p>\n\n<pre><code>RaiseEvent Report(GetMyString())\n</code></pre>\n\n<p>In other words, I am saying that the <code>GetMystring</code> function above does not get called unless handlers actually exist.</p>\n" }, { "answer_id": 12904131, "author": "Scott Marcus", "author_id": 695364, "author_profile": "https://Stackoverflow.com/users/695364", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>If your REAL question is \"To save time, should I check that the events\n have handlers before raising the events?\" . . . then the answer is\n \"No\", you'll gain nothing by doing this.</p>\n</blockquote>\n\n<p>In C#, if you don't check the event for null and there are no handlers registered, you will get a NullReferenceException.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16415/" ]
I have a class that downloads, examines and saves some large XML files. Sometimes I want the UI to tell me what's going on, but sometimes I will use the class and ignore the events. So I have placed lines of code like this in a dozen places: ``` RaiseEvent Report("Sending request: " & queryString) RaiseEvent Report("Saving file: " & fileName) RaiseEvent Report("Finished") ``` My question is this - will these events slow down my code if nothing is listening for them? Will they even fire?
There is no magic, the code hiding under RaiseEvent does exactly what you'd expect, it iterates through a collection of handlers, and executes each one. The overhead of checking to see are there any handlers is trivial, don't worry about it. If your **REAL** question is "To save time, should I check that the events have handlers before raising the events?" . . . then the answer is "No", you'll gain nothing by doing this. Also, don't worry about optimisation unless you need to (see this [Wikipedia entry](http://en.wikipedia.org/wiki/Code_optimization) to see why.) Re: Calling `GetMystring()`. Yes, this ties in with how you raise events in C#, where you check for the existence of handlers before raising the event. E.g.: ``` if (MyEvent != null) MyEvent(GetMyString()) ``` Nice experiment by the way :)
250,506
<p>I made a class that derives from Component:</p> <pre><code>public class MyComponent: System.ComponentModel.Component { } </code></pre> <p>I saw that Visual Studio put this code in for me:</p> <pre><code>protected override void Dispose(bool disposing) { try { if (disposing &amp;&amp; (components != null)) { components.Dispose(); } } catch { throw; } finally { base.Dispose(disposing); } } </code></pre> <p><code>MyComponent</code> has a member that is a <code>DataSet</code> and maybe there's some other members that implement <code>IDisposable</code>. What, if anything, do i need to modify with the <code>Dispose()</code> method to make sure things are cleaned up properly? Thanks for helping.</p>
[ { "answer_id": 250541, "author": "Nicholas Mancuso", "author_id": 8945, "author_profile": "https://Stackoverflow.com/users/8945", "pm_score": 3, "selected": true, "text": "<p>Change:</p>\n\n<pre><code>if (disposing &amp;&amp; (components != null))\n{\n components.Dispose();\n}\n</code></pre>\n\n<p>to be:</p>\n\n<pre><code>if (disposing &amp;&amp; (components != null))\n{\n _dataset.Dispose();\n components.Dispose();\n}\n</code></pre>\n" }, { "answer_id": 250548, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 0, "selected": false, "text": "<p>Check any disposable member objects and dispose them if they are not null.</p>\n" }, { "answer_id": 9169564, "author": "smoothdeveloper", "author_id": 17049, "author_profile": "https://Stackoverflow.com/users/17049", "pm_score": 0, "selected": false, "text": "<p>I came up with this class:</p>\n\n<pre><code>public class DisposableComponentWrapper : IComponent\n{\n private IDisposable disposable;\n\n public DisposableComponentWrapper(IDisposable disposable)\n {\n this.disposable = disposable;\n }\n\n public DisposableComponentWrapper(IDisposable disposable, ISite site)\n : this(disposable)\n {\n Site = site;\n }\n\n public void Dispose()\n {\n if (disposable != null)\n {\n disposable.Dispose();\n }\n if (Disposed != null)\n {\n Disposed(this, EventArgs.Empty);\n }\n }\n\n public ISite Site { get; set; }\n\n public event EventHandler Disposed;\n}\n</code></pre>\n\n<p>and extension method to IContainer:</p>\n\n<pre><code>public static void Add(this IContainer container, IDisposable disposableComponent)\n{\n var component = (disposableComponent as IComponent);\n if(component == null)\n {\n component = new DisposableComponentWrapper(disposableComponent);\n }\n container.Add(component);\n}\n</code></pre>\n\n<p>Which might help those willing to enlist disposable resources to their forms.</p>\n\n<p>Note: I'm not certain of the behaviour for IComponent.Disposed, <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.icomponent.disposed.aspx\" rel=\"nofollow\">MSDN</a> doesn't say much about how it should be called in implementation of this interface, the documentation sounds like talking about client code registering to the event more than when it should be triggered by implementations of this interface.</p>\n" }, { "answer_id": 59382238, "author": "Palec", "author_id": 2157640, "author_profile": "https://Stackoverflow.com/users/2157640", "pm_score": -1, "selected": false, "text": "<p>Wrap the disposables in components and add them in the <code>components</code> collection. The generated implementation of the dispose pattern will dispose of them correctly.</p>\n\n<pre><code>public partial class MyComponent : System.ComponentModel.Component\n{\n private readonly System.Data.DataSet _dataSet;\n\n public MyComponent(System.Data.DataSet dataSet)\n {\n _dataSet = dataSet ?? throw new System.ArgumentNullException(nameof(dataSet));\n components.Add(new DisposableWrapperComponent(dataSet));\n }\n}\n</code></pre>\n\n<p>The <code>DisposableWrapperComponent</code> is defined thus:</p>\n\n<pre><code>using System;\nusing System.ComponentModel;\n\npublic class DisposableWrapperComponent : Component\n{\n private bool disposed;\n\n public IDisposable Disposable { get; }\n\n public DisposableWrapperComponent(IDisposable disposable)\n {\n Disposable = disposable ?? throw new ArgumentNullException(nameof(disposable));\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposed) return;\n\n if (disposing)\n {\n Disposable.Dispose();\n }\n\n base.Dispose(disposing);\n\n disposed = true;\n }\n}\n</code></pre>\n\n<p><sup>Inspired by the answer by <a href=\"https://stackoverflow.com/users/17049/smoothdeveloper\">@smoothdeveloper</a>.</sup></p>\n\n<p>If you need to be able to reset the data set, encapsulating the lifetime management in a property works quite well.</p>\n\n<pre><code>using System;\nusing System.ComponentModel;\nusing System.Data;\n\npublic partial class MyComponent : Component\n{\n private const string DataSetComponentName = \"dataSet\";\n\n public DataSet DataSet\n {\n get =&gt; (DataSet)((DisposableWrapperComponent)components.Components[DataSetComponentName])\n ?.Disposable;\n set\n {\n var lastWrapper = (DisposableWrapperComponent)components.Components[DataSetComponentName];\n if (lastWrapper != null)\n {\n components.Remove(lastWrapper);\n lastWrapper.Dispose();\n }\n\n if (value != null)\n {\n components.Add(new DisposableWrapperComponent(value), DataSetComponentName);\n }\n }\n }\n\n public MyComponent(DataSet dataSet)\n {\n DataSet = dataSet ?? throw new ArgumentNullException(nameof(dataSet));\n }\n}\n</code></pre>\n\n<p>I used this when implementing a Windows Service that creates a disposable object in <code>OnStart</code> and disposes of it in <code>OnStop</code>.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I made a class that derives from Component: ``` public class MyComponent: System.ComponentModel.Component { } ``` I saw that Visual Studio put this code in for me: ``` protected override void Dispose(bool disposing) { try { if (disposing && (components != null)) { components.Dispose(); } } catch { throw; } finally { base.Dispose(disposing); } } ``` `MyComponent` has a member that is a `DataSet` and maybe there's some other members that implement `IDisposable`. What, if anything, do i need to modify with the `Dispose()` method to make sure things are cleaned up properly? Thanks for helping.
Change: ``` if (disposing && (components != null)) { components.Dispose(); } ``` to be: ``` if (disposing && (components != null)) { _dataset.Dispose(); components.Dispose(); } ```
250,508
<p>I am trying to pull data from an ACD call data system, <code>Nortel Contact Center 6.0</code> to be exact, and if you use that particular system what I am trying to capture is the daily call by call data. However when I use this code</p> <p>(sCW is a common word string that equals <code>eCallByCallStat</code> and sDate is </p> <p><code>dDate = Format(Month(deffDate) &amp; "/" &amp; iStartDay &amp; "/" &amp; Year(deffDate), "mm/dd/yyyy")</code></p> <p><code>sDate = Format(dDate, "yyyymmdd")</code> )</p> <pre><code>sSql = "" sConn = "ODBC;DSN=Aus1S002;UID=somevaliduser;PWD=avalidpassword;SRVR=Thecorrectserver;DB=blue" sSql = "SELECT " &amp; sCW &amp; sDate &amp; ".Timestamp, " sSql = sSql &amp; sCW &amp; sDate &amp; ".CallEvent, " sSql = sSql &amp; sCW &amp; sDate &amp; ".CallEventName, " sSql = sSql &amp; sCW &amp; sDate &amp; ".CallID, " sSql = sSql &amp; sCW &amp; sDate &amp; ".TelsetLoginID, " sSql = sSql &amp; sCW &amp; sDate &amp; ".AssociatedData, " sSql = sSql &amp; sCW &amp; sDate &amp; ".Destination, " sSql = sSql &amp; sCW &amp; sDate &amp; ".EventData, " sSql = sSql &amp; sCW &amp; sDate &amp; ".Source, " sSql = sSql &amp; sCW &amp; sDate &amp; ".Time " &amp; vbCrLf sSql = sSql &amp; "FROM blue.dbo.eCallByCallStat" &amp; sDate &amp; " " &amp; sCW &amp; sDate &amp; vbCrLf sSql = sSql &amp; " ORDER BY " &amp; sCW &amp; sDate &amp; ".Timestamp" Set oQT = ActiveSheet.QueryTables.Add(Connection:=sConn, Destination:=Range("A1"), Sql:=sSql) oQT.Refresh BackgroundQuery:=False Do While oQT.Refreshing = True Loop" </code></pre> <p>When I run this I get an odd error message at oQT.Refresh BackgroundQuery:=False</p> <p>Oddly enough it worked for a month or so then just died</p> <hr> <p>@ loopo I actually added the <code>""</code> to the connection string and actually have the user name and password hard coded into the query with out quotes, I have since removed them for clarity in the posting</p> <hr> <p>The error I recieve is </p> <blockquote> <p>Run-time error '-2147417848(80010108)': Method 'Refresh" of Object "_QueryTable' Failed</p> </blockquote> <hr> <p>Thanks for your input Kevin. The Database is never in a state where no one is accessing it, it is a Call Handling system that is on 24 x 7 and always connected to is clients. At least that is my understanding. If I do this manually through Excel I never get an error, or have any issues only when I am doing this via a macro does it give me issues which lead me to think that it was my code causing the issue.</p> <p>I am connecting to the database via ODBC as recommended by the manuafacturer, but I wonder if they ever envisioned this sort of thing.</p> <p>I will see if I can leverage this into a .NET project and see if that helps.</p>
[ { "answer_id": 250888, "author": "Kevin Fairchild", "author_id": 3743, "author_profile": "https://Stackoverflow.com/users/3743", "pm_score": 1, "selected": false, "text": "<p>Seems like an error with the query itself...</p>\n\n<p>If you can step through your code and post the contents of sSql, it would probably help troubleshoot...</p>\n\n<p>When you go through it, be sure quotes are getting escaped properly.</p>\n" }, { "answer_id": 250929, "author": "Loopo", "author_id": 32763, "author_profile": "https://Stackoverflow.com/users/32763", "pm_score": 1, "selected": false, "text": "<p>Looks like your connection string has double quotes in it.\nThis could potentially be due to some parsing by the website</p>\n\n<p>you should probably set sConn using \"double double\" quotes, as in:</p>\n\n<pre><code>sConn = \"ODBC;DSN=Aus1S002;UID=\"\"somevaliduser\"\";PWD=\"\"avalidpassword\"\";SRVR=\"\"Thecorrectserver\"\";DB=blue\"\n</code></pre>\n" }, { "answer_id": 250930, "author": "CABecker", "author_id": 32790, "author_profile": "https://Stackoverflow.com/users/32790", "pm_score": 0, "selected": false, "text": "<p>I start by deleting the contents of sSQL with <code>sSql=\"\"</code></p>\n\n<p>after that, because the query is run in a for loop I build the query in each of the next lines, each line builds on the previous line, I made it that way so it would be easier to edit and understand by the next guy.</p>\n\n<p>After running through the sSQL looks like this </p>\n\n<pre><code>sSQL=SELECT eCallByCallStat20081001.Timestamp, eCallByCallStat20081001.CallEvent,\neCallByCallStat20081001.CallEventName, eCallByCallStat20081001.CallID,\neCallByCallStat20081001.TelsetLoginID, eCallByCallStat20081001.AssociatedData,\neCallByCallStat20081001.Destination, eCallByCallStat20081001.EventData,\neCallByCallStat20081001.Source, eCallByCallStat20081001.Time FROM \nblue.dbo.eCallByCallStat20081001 eCallByCallStat20081001 ORDER BY\neCallByCallStat20081001.Timestamp\n</code></pre>\n" }, { "answer_id": 252479, "author": "Loopo", "author_id": 32763, "author_profile": "https://Stackoverflow.com/users/32763", "pm_score": 1, "selected": false, "text": "<p>What is the actual error message you're getting?</p>\n\n<p>In the FROM clause, are you trying to SELECT from 2 different tables, with the same name in different namespaces? (In which case I think they should be separated by a comma rather than a space) </p>\n\n<p>Or is there supposed to be another '.' instead of the space in the FROM clause? Or is it an alias?</p>\n\n<p>Do you need to specify the table for every field? why not just do:</p>\n\n<pre><code>SELECT Timestamp, CallEvent, ... ,Time \n FROM blue.dbo.eCallByCallStat\" &amp; sDate &amp; \" ORDER BY Timestamp \n</code></pre>\n" }, { "answer_id": 268981, "author": "Kevin Fairchild", "author_id": 3743, "author_profile": "https://Stackoverflow.com/users/3743", "pm_score": 1, "selected": false, "text": "<p>First off, if you're connecting to a non-generic database (SQL Server, Oracle, etc.), <strong>try using a database connection that's specific to it</strong>.</p>\n\n<p>Secondly, since you said this error comes and goes, can you test whether it still happens when no one else is accessing the system? <strong>Perhaps it is an issue with certain rows being locked</strong> while your query is trying to read them...</p>\n\n<p>Third, <strong>either switch to a different reporting method or find a different way to get the data</strong>. There are limits to this type of call within Excel. While, yes, it certainly does allow you to connect to databases and pull in data, you may find it falling short if you're working with large sets of data, complex queries, or finicky database connections.</p>\n" }, { "answer_id": 62076016, "author": "szabo357", "author_id": 8297311, "author_profile": "https://Stackoverflow.com/users/8297311", "pm_score": 0, "selected": false, "text": "<p>I was having this same issue when trying to refresh a Query. </p>\n\n<p>For some reason that I don't know. When refering to a <strong>QueryTable object</strong> the refresh only works the first time you run the vba code. If you run it again the runtime error will prompt <strong>Run-time error '-2147217842(80040e4e): Method 'Refresh' of object '_QueryTable' failed</strong> occurs</p>\n\n<p><strong>This is an example of a Query refresh that fails.</strong>\n<code>Ws.ListObjects(\"TableName\").QueryTable.Refresh BackgroundQuery:=False</code></p>\n\n<p><strong>Here is the solution found.</strong>\n<code>ThisWorkbook.Connections(\"ConnectionName\").Refresh</code></p>\n\n<p>If someone knows the reason why the refresh method of the QueryTable object fails. please let us know. </p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32790/" ]
I am trying to pull data from an ACD call data system, `Nortel Contact Center 6.0` to be exact, and if you use that particular system what I am trying to capture is the daily call by call data. However when I use this code (sCW is a common word string that equals `eCallByCallStat` and sDate is `dDate = Format(Month(deffDate) & "/" & iStartDay & "/" & Year(deffDate), "mm/dd/yyyy")` `sDate = Format(dDate, "yyyymmdd")` ) ``` sSql = "" sConn = "ODBC;DSN=Aus1S002;UID=somevaliduser;PWD=avalidpassword;SRVR=Thecorrectserver;DB=blue" sSql = "SELECT " & sCW & sDate & ".Timestamp, " sSql = sSql & sCW & sDate & ".CallEvent, " sSql = sSql & sCW & sDate & ".CallEventName, " sSql = sSql & sCW & sDate & ".CallID, " sSql = sSql & sCW & sDate & ".TelsetLoginID, " sSql = sSql & sCW & sDate & ".AssociatedData, " sSql = sSql & sCW & sDate & ".Destination, " sSql = sSql & sCW & sDate & ".EventData, " sSql = sSql & sCW & sDate & ".Source, " sSql = sSql & sCW & sDate & ".Time " & vbCrLf sSql = sSql & "FROM blue.dbo.eCallByCallStat" & sDate & " " & sCW & sDate & vbCrLf sSql = sSql & " ORDER BY " & sCW & sDate & ".Timestamp" Set oQT = ActiveSheet.QueryTables.Add(Connection:=sConn, Destination:=Range("A1"), Sql:=sSql) oQT.Refresh BackgroundQuery:=False Do While oQT.Refreshing = True Loop" ``` When I run this I get an odd error message at oQT.Refresh BackgroundQuery:=False Oddly enough it worked for a month or so then just died --- @ loopo I actually added the `""` to the connection string and actually have the user name and password hard coded into the query with out quotes, I have since removed them for clarity in the posting --- The error I recieve is > > Run-time error '-2147417848(80010108)': > Method 'Refresh" of Object "\_QueryTable' Failed > > > --- Thanks for your input Kevin. The Database is never in a state where no one is accessing it, it is a Call Handling system that is on 24 x 7 and always connected to is clients. At least that is my understanding. If I do this manually through Excel I never get an error, or have any issues only when I am doing this via a macro does it give me issues which lead me to think that it was my code causing the issue. I am connecting to the database via ODBC as recommended by the manuafacturer, but I wonder if they ever envisioned this sort of thing. I will see if I can leverage this into a .NET project and see if that helps.
Seems like an error with the query itself... If you can step through your code and post the contents of sSql, it would probably help troubleshoot... When you go through it, be sure quotes are getting escaped properly.
250,509
<p>Is there a way that you can have SERVEROUTPUT set to ON in sqlplus but somehow repress the message "PL/SQL procedure successfully completed" that is automatically generated upon completed execution of a plsql procedure?</p>
[ { "answer_id": 250540, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 7, "selected": true, "text": "<p>Use the command:</p>\n\n<pre><code>SET FEEDBACK OFF\n</code></pre>\n\n<p>before running the procedure. And afterwards you can turn it back on again:</p>\n\n<pre><code>SET FEEDBACK ON\n</code></pre>\n" }, { "answer_id": 58718276, "author": "MikeA", "author_id": 10807594, "author_profile": "https://Stackoverflow.com/users/10807594", "pm_score": 1, "selected": false, "text": "<p>This has worked well for me in sqlplus, but I did just notice that \"set feedback off\" suppresses errors in Sql Developer (at least version 17.2.0.188). Just something to be aware of if you use Sql Developer:</p>\n\n<pre><code>create or replace procedure test_throw_an_error as buzz number; begin dbms_output.put_line('In test_throw_an_error. Now, to infinity!'); buzz:=1/0; end;\n/\nset serveroutput on\nset feedback off\nexec test_throw_an_error;\nexec dbms_output.put_line('Done, with feedback off');\nset feedback on\nexec test_throw_an_error;\nexec dbms_output.put_line('Done, with feedback on');\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>Procedure TEST_THROW_AN_ERROR compiled\n\nIn test_throw_an_error. Now, to infinity!\n\nDone, with feedback off\n\nIn test_throw_an_error. Now, to infinity!\n\n\nError starting at line : 11 in command -\nBEGIN test_throw_an_error; END;\nError report -\nORA-01476: divisor is equal to zero\nORA-06512: at \"ECTRUNK.TEST_THROW_AN_ERROR\", line 1\nORA-06512: at line 1\n01476. 00000 - \"divisor is equal to zero\"\n*Cause: \n*Action:\nDone, with feedback on\n\nPL/SQL procedure successfully completed.\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5658/" ]
Is there a way that you can have SERVEROUTPUT set to ON in sqlplus but somehow repress the message "PL/SQL procedure successfully completed" that is automatically generated upon completed execution of a plsql procedure?
Use the command: ``` SET FEEDBACK OFF ``` before running the procedure. And afterwards you can turn it back on again: ``` SET FEEDBACK ON ```
250,550
<p>this is probably a newbie ruby question. I have several libraries and apps that I need to deploy to several different hosts. All of the apps and libs will share some common settings for those hosts-- e.g. host name, database server/user/pass, etc.</p> <p>My goal is to do something like:</p> <pre><code>cap host1 stage deploy cap host2 stage deploy cap host1 prod deploy # ... </code></pre> <p>My question is how do you include these common settings in all of your deploy.rb files? More specifically, I want to create a an rb file that I can include that has some common settings and several host specific task definitions:</p> <pre><code>set :use_sudo, false # set some other options task :host1 do role :app, "host1.example.com" role :web, "host1.example.com" role :db, "host1.example.com", :primary =&gt; true set :rodb_host, "dbhost" set :rodb_user, "user" set :rodb_pass, "pass" set :rodb_name, "db" end task :host2 do #... end deploy.task :carsala do transaction do setup update_code symlink end end </code></pre> <p>And then "include" this file in all of my deploy.rb files where I define stage, prod, etc and overwrite any "common" configuration parameters as necessary. Any suggestions would be appreciated. I've tried a few different things, but I get errors from cap for all of them. </p> <p>Edit: I've tried </p> <pre><code>require 'my_module' </code></pre> <p>But I get errors complaining about an undefined task object.</p>
[ { "answer_id": 250747, "author": "Jon Wood", "author_id": 25258, "author_profile": "https://Stackoverflow.com/users/25258", "pm_score": 2, "selected": false, "text": "<pre><code>require 'my_extension'\n</code></pre>\n\n<p>Save your extensions in my_extension.rb</p>\n" }, { "answer_id": 250985, "author": "Daniel Beardsley", "author_id": 13216, "author_profile": "https://Stackoverflow.com/users/13216", "pm_score": 0, "selected": false, "text": "<p>Jon has it right, that's the simplest way to go, just save it in a separate file and use <code>require 'filename'</code>. You could also use something fancy like <a href=\"http://labs.peritor.com/webistrano\" rel=\"nofollow noreferrer\">Webistrano</a> for deployment which also supports this in the form of Capistrano '<a href=\"http://labs.peritor.com/webistrano/wiki/Screencasts\" rel=\"nofollow noreferrer\">Recipes</a>'. I've been using it for a while on a few projects and have come to love it.</p>\n" }, { "answer_id": 251862, "author": "Damon Snyder", "author_id": 8243, "author_profile": "https://Stackoverflow.com/users/8243", "pm_score": 3, "selected": false, "text": "<p>I just experimented with it a little more and what I discovered is that you have to:</p>\n\n<pre><code>load 'config/my_module'\n</code></pre>\n\n<p>I can put all of my common definitions here and just load it into my deploy.rb.</p>\n\n<p>It appears from the docs that load loads and executes the file. Alternatively, require attempts to load the library specified. I'm not totally sure about real difference, but it appears that there is some separation between the current app symbol space and the library require'd (hence the errors about the undefined task object) that isn't a problem when you do a load. </p>\n" }, { "answer_id": 254327, "author": "Ian Terrell", "author_id": 9269, "author_profile": "https://Stackoverflow.com/users/9269", "pm_score": 0, "selected": false, "text": "<p>I'm not sure how complex your needs are, but this works well for me for deployment:</p>\n\n<pre><code>set :application, \"app\"\n\nset :scm, :subversion\n# ... set all your common variables\n\ntask :staging do\n set :repository, \"http://app/repository/trunk/\"\n # ... set other uncommon variables in task\nend\n\ntask :production do\n set :repository, \"http://app/repository/production/\"\n # ...\nend\n</code></pre>\n\n<p>Deployment is just</p>\n\n<pre><code>cap staging deploy\n</code></pre>\n\n<p>or</p>\n\n<pre><code>cap production deploy\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8243/" ]
this is probably a newbie ruby question. I have several libraries and apps that I need to deploy to several different hosts. All of the apps and libs will share some common settings for those hosts-- e.g. host name, database server/user/pass, etc. My goal is to do something like: ``` cap host1 stage deploy cap host2 stage deploy cap host1 prod deploy # ... ``` My question is how do you include these common settings in all of your deploy.rb files? More specifically, I want to create a an rb file that I can include that has some common settings and several host specific task definitions: ``` set :use_sudo, false # set some other options task :host1 do role :app, "host1.example.com" role :web, "host1.example.com" role :db, "host1.example.com", :primary => true set :rodb_host, "dbhost" set :rodb_user, "user" set :rodb_pass, "pass" set :rodb_name, "db" end task :host2 do #... end deploy.task :carsala do transaction do setup update_code symlink end end ``` And then "include" this file in all of my deploy.rb files where I define stage, prod, etc and overwrite any "common" configuration parameters as necessary. Any suggestions would be appreciated. I've tried a few different things, but I get errors from cap for all of them. Edit: I've tried ``` require 'my_module' ``` But I get errors complaining about an undefined task object.
I just experimented with it a little more and what I discovered is that you have to: ``` load 'config/my_module' ``` I can put all of my common definitions here and just load it into my deploy.rb. It appears from the docs that load loads and executes the file. Alternatively, require attempts to load the library specified. I'm not totally sure about real difference, but it appears that there is some separation between the current app symbol space and the library require'd (hence the errors about the undefined task object) that isn't a problem when you do a load.
250,553
<p>I'd like something like</p> <pre><code>int minIndex = list.FindMin(delegate (MyClass a, MyClass b) {returns a.CompareTo(b);}); </code></pre> <p>Is there a builtin way to do this in .NET?</p>
[ { "answer_id": 250567, "author": "Nicholas Mancuso", "author_id": 8945, "author_profile": "https://Stackoverflow.com/users/8945", "pm_score": 6, "selected": true, "text": "<p>Try looking at these:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb909313.aspx\" rel=\"noreferrer\">Min</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb909073.aspx\" rel=\"noreferrer\">Max</a></p>\n\n<p>As long as your class implements IComparable, all you have to do is:</p>\n\n<pre><code>List&lt;MyClass&gt; list = new List();\n//add whatever you need to add\n\nMyClass min = list.Min();\nMyClass max = list.Max();\n</code></pre>\n" }, { "answer_id": 250568, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 2, "selected": false, "text": "<p>Using Linq you have the Min() and Max() functions.</p>\n\n<p>So you can do <code>list.AsQueryable().Min();</code></p>\n" }, { "answer_id": 251800, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "<p>You note that \"I'm still in 2\" - you might, then, want to look at <a href=\"http://www.albahari.com/nutshell/linqbridge.aspx\" rel=\"nofollow noreferrer\">LINQBridge</a>. This is actually aimed at C# 3.0 and .NET 2.0, but you should be able to use it with C# 2.0 and .NET 2.0 - just you'll have to use the long-hand:</p>\n\n<pre><code>MyClass min = Enumerable.Min(list),\n max = Enumerable.Max(list);\n</code></pre>\n\n<p>Of course, it will be easier if you can switch to C# 3.0 (still targetting .NET 2.0).</p>\n\n<p>And if LINQBridge isn't an option, you can implement it yourself:</p>\n\n<pre><code>static void Main()\n{\n int[] data = { 3, 5, 1, 5, 5 };\n int min = Min(data);\n}\nstatic T Min&lt;T&gt;(IEnumerable&lt;T&gt; values)\n{\n return Min&lt;T&gt;(values, Comparer&lt;T&gt;.Default);\n}\nstatic T Min&lt;T&gt;(IEnumerable&lt;T&gt; values, IComparer&lt;T&gt; comparer)\n{\n bool first = true;\n T result = default(T);\n foreach(T value in values) {\n if(first)\n {\n result = value;\n first = false;\n }\n else\n {\n if(comparer.Compare(result, value) &gt; 0) \n {\n result = value;\n }\n }\n }\n return result;\n}\n</code></pre>\n" }, { "answer_id": 251841, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 4, "selected": false, "text": "<p>Well, if you can't use .NET 3.5, you could always sort the list and then return list[0]. It might not be the fastest way, but it's probably the shortest code, especially if your class already implements IComparable.</p>\n\n<pre><code>List&lt;SomeClass&gt; list = new List&lt;SomeClass&gt;();\n// populate the list\n// assume that SomeClass implements IComparable\nlist.Sort();\nreturn list[0]; // min, or\nreturn list[list.Count - 1]; // max\n</code></pre>\n\n<p>This also assumes, of course, that it doesn't matter which item you return if you have multiple items that are the minimum or maximum.</p>\n\n<p>If your class doesn't implement IComparable, you can pass in an anonymous delegate, something like this:</p>\n\n<pre><code>list.Sort(delegate(SomeClass x, SomeClass y) { return string.Compare(x.Name, y.Name); });\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11236/" ]
I'd like something like ``` int minIndex = list.FindMin(delegate (MyClass a, MyClass b) {returns a.CompareTo(b);}); ``` Is there a builtin way to do this in .NET?
Try looking at these: [Min](http://msdn.microsoft.com/en-us/library/bb909313.aspx) [Max](http://msdn.microsoft.com/en-us/library/bb909073.aspx) As long as your class implements IComparable, all you have to do is: ``` List<MyClass> list = new List(); //add whatever you need to add MyClass min = list.Min(); MyClass max = list.Max(); ```
250,576
<p>In Visual Studio, is there any way to make the debugger break whenever a certain file (or class) is entered? Please don't answer "just set a breakpoint at the beginning of every method" :)</p> <p>I am using C#.</p>
[ { "answer_id": 250584, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 1, "selected": false, "text": "<p>No. Or rather, yes, but it involves setting a breakpoint at the beginning of every method.</p>\n" }, { "answer_id": 250589, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 0, "selected": false, "text": "<p>Not that I'm aware of. The best you can do is to put a breakpoint in every method in the file or class. What are you trying to do? Are you trying to figure out what method is causing something to change? If so, perhaps a data breakpoint will be more appropriate.</p>\n" }, { "answer_id": 250594, "author": "JC.", "author_id": 3615, "author_profile": "https://Stackoverflow.com/users/3615", "pm_score": 2, "selected": false, "text": "<pre><code>System.Diagnostics.Debugger.Break();\n</code></pre>\n\n<p>(at the beginning of every method)</p>\n" }, { "answer_id": 250610, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": "<p>Well, as everyone is saying, it involves setting a breakpoint at the beginning of every method. But you're not seeing the bigger picture.</p>\n\n<p>For this to work at all, a breakpoint has to be set at the beginning of every method. Whether you do it manually, or the debugger does it automatically, those breakpoints must be set for this to work.</p>\n\n<p>So, the question really becomes, \"If there enough of a need for this functionality, that it is worth building into the debugger an automatic means of setting all those breakpoints?\". And the answer is, \"Not Really\".</p>\n" }, { "answer_id": 251534, "author": "ScottCher", "author_id": 24179, "author_profile": "https://Stackoverflow.com/users/24179", "pm_score": 0, "selected": false, "text": "<p>You could write a wrapper method through which you make EVERY call in your app. Then you set a breakpoint in that single method. But... you'd be crazy to do such a thing.</p>\n" }, { "answer_id": 539594, "author": "Steve Eisner", "author_id": 7104, "author_profile": "https://Stackoverflow.com/users/7104", "pm_score": 4, "selected": false, "text": "<p>You could start by introducing some sort of Aspect-Oriented Programming - see for instance\n<a href=\"http://blogs.msdn.com/saveenr/archive/2008/11/20/c-aop-elegant-tracing-with-postsharp-and-aspect-oriented-programming.aspx\" rel=\"nofollow noreferrer\">this explanation</a> - and then put a breakpoint in the single OnEnter method.</p>\n\n<p>Depending on which AOP framework you choose, it'd require a little decoration in your code and introduce a little overhead (that you can remove later) but at least you won't need to set breakpoints everywhere. In some frameworks you might even be able to introduce it with no code change at all, just an XML file on the side?</p>\n" }, { "answer_id": 539618, "author": "BigSandwich", "author_id": 26983, "author_profile": "https://Stackoverflow.com/users/26983", "pm_score": 0, "selected": false, "text": "<p>You could put a memory break point on this, and set it to on read. I think there should be a read most of the time you call a member function. I'm not sure about static functions.</p>\n" }, { "answer_id": 539655, "author": "devdimi", "author_id": 54983, "author_profile": "https://Stackoverflow.com/users/54983", "pm_score": 0, "selected": false, "text": "<pre><code>you can use the following macro:\n\n#ifdef _DEBUG\n#define DEBUG_METHOD(x) x DebugBreak();\n#else\n#define DEBUG_METHOD(x) x\n#endif\n\n#include &lt;windows.h&gt;\n\nDEBUG_METHOD(int func(int arg) {)\n return 0;\n}\n</code></pre>\n\n<p>on function enter it will break into the debugger</p>\n" }, { "answer_id": 539708, "author": "LarryF", "author_id": 18518, "author_profile": "https://Stackoverflow.com/users/18518", "pm_score": 0, "selected": false, "text": "<p>IF this is C++ you are talking about, then you could probably get away with, (a hell of a lot of work) setting a break point in the preamble code in the CRT, or writing code that modifies the preamble code to stick INT 3's in there only for functions generated from the class in question... This, BTW, CAN be done at runtime... You'd have to have the PE file that's generated modify itself, possibly before relocation, to stick all the break's in there...</p>\n\n<p>My only other suggestion would be to write a Macro that uses the predefined macro &#95;&#95;FUNCTION&#95;&#95;, in which you look for any function that's part of the class in question, and if necessary, stick a </p>\n\n<pre><code>__asm { int 3 }\n</code></pre>\n\n<p>in your macro to make VS break... This will prevent you from having to set break points at the start of every function, but you'd still have to stick a macro call, which is a lot better, if you ask me. I think I read somewhere on how you can define, or redefine the preamble code that's called per function.. I'll see what I can find.</p>\n\n<p>I would think I similar hack could be used to detect which FILE you enter, but you STILL have to place YOUR function macro's all over your code, or it will never get called, and, well, that's pretty much what you didn't want to do.</p>\n" }, { "answer_id": 539740, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": false, "text": "<p>You could write a Visual Studio macro that obtained a list of all of the class methods (say, by reading the <code>.map</code> file produced alongside the executable and searching it for the proper symbol names (and then demangling those names)), and then used <a href=\"http://msdn.microsoft.com/en-us/library/envdte.breakpoints.add(VS.80).aspx\" rel=\"nofollow noreferrer\"><code>Breakpoints.add()</code></a> to programmatically add breakpoints to those functions.</p>\n" }, { "answer_id": 539811, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": 3, "selected": false, "text": "<p>This works fine in WinDbg:</p>\n\n<pre><code>bm exename!CSomeClass::*\n</code></pre>\n\n<p>(Just to clarify, the above line sets a breakpoint on all functions in the class, just like the OP is asking for, without resorting to CRT hacking or macro silliness)</p>\n" }, { "answer_id": 540525, "author": "ShuggyCoUk", "author_id": 12748, "author_profile": "https://Stackoverflow.com/users/12748", "pm_score": 0, "selected": false, "text": "<p>If you are willing to use a macro then the accepted answer from <a href=\"https://stackoverflow.com/questions/73063/how-do-i-add-debug-breakpoints-to-lines-displayed-in-a-find-results-window-in-vis\">this question</a></p>\n\n<p>Should be trivially convertible to you needs by making the search function searching for methods, properties and constructors (as desired), there is also quite possibly a way to get the same information from the the ide/symbols which will be more stable (though perhaps a little more complex).</p>\n" }, { "answer_id": 540549, "author": "abelenky", "author_id": 34824, "author_profile": "https://Stackoverflow.com/users/34824", "pm_score": 1, "selected": false, "text": "<p>Use <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.debugger.break.aspx\" rel=\"nofollow noreferrer\">Debugger.Break();</a> (from the System.Diagnostics namespace)</p>\n\n<p>Put it at the top of each function you wish to have \"broken\"</p>\n\n<pre><code>void MyFunction()\n{\n Debugger.Break();\n Console.WriteLine(\"More stuff...\");\n}\n</code></pre>\n" }, { "answer_id": 540564, "author": "CraigTP", "author_id": 57477, "author_profile": "https://Stackoverflow.com/users/57477", "pm_score": 1, "selected": false, "text": "<p>Isn't the simplest method to get closest to this to simply set a break point in the constructor (assuming you have only one - or each of them in the case of multiple constructors) ?</p>\n\n<p>This will break into debugging when the class is first instantiated in the case of a non-static constructor, and in the case of a static constructor/class, you'll break into debugging as soon as Visual Studio decides to initialize your class.</p>\n\n<p>This certainly prevents you from having to set a breakpoint in <em>every</em> method within the class.</p>\n\n<p>Of course, you won't continue to break into debugging on subsequent re-entry to the class's code (assuming you're using the same instantiated object the next time around), however, if you re-instantiate a new object each time from within the calling code, you could simulate this.</p>\n\n<p>However, in conventional terms, there's no simple way to set a single break point in one place (for example) and have it break into debugging every time a class's code (from whichever method) is entered (as far as I know).</p>\n" }, { "answer_id": 540580, "author": "Daniel Daranas", "author_id": 96780, "author_profile": "https://Stackoverflow.com/users/96780", "pm_score": 1, "selected": false, "text": "<p>Assuming that you're only interested in public methods i.e. when the class methods are called \"from outside\", I will plug Design by Contract once more.</p>\n\n<p>You can get into the habit of writing your public functions like this:</p>\n\n<pre><code>public int Whatever(int blah, bool duh)\n{\n // INVARIANT (i)\n // PRECONDITION CHECK (ii)\n\n // BODY (iii)\n\n // POSTCONDITION CHECK (iv)\n // INVARIANT (v)\n\n}\n</code></pre>\n\n<p>Then you can use the Invariant() function that you will call in (i) and <strong>set a breakpoint in it</strong>. Then inspect the call stack to know where you're coming from. Of course you will call it in (v), too; if you're really interested in only entry points, you could use a helper function to call Invariant from (i) and another one from (v).</p>\n\n<p>Of course this is extra code but</p>\n\n<ol>\n<li>It's useful code anyway, and the structure is boilerplate if you use Design by Contract.</li>\n<li>Sometimes you want breakpoints to investigate some incorrect behaviour eg invalid object state, in that case invariants might be priceless.</li>\n</ol>\n\n<p>For an object which is always valid, the Invariant() function just has a body that returns true. You can still put a breakpoint there.</p>\n\n<p>It's just an idea, it admittedly has a footstep, so just consider it and use it if you like it.</p>\n" }, { "answer_id": 540586, "author": "thinkbeforecoding", "author_id": 47001, "author_profile": "https://Stackoverflow.com/users/47001", "pm_score": 0, "selected": false, "text": "<p>You can use <code>Debugger.Launch()</code> and <code>Debugger.Break()</code> in the assembly <code>System.Diagnostics</code></p>\n" }, { "answer_id": 540598, "author": "Richard Szalay", "author_id": 3603, "author_profile": "https://Stackoverflow.com/users/3603", "pm_score": 7, "selected": true, "text": "<p>Macros can be your friend. Here is a macro that will add a breakpoint to every method in the current class (put the cursor somewhere in the class before running it).</p>\n\n<pre><code>Public Module ClassBreak\n Public Sub BreakOnAnyMember()\n Dim debugger As EnvDTE.Debugger = DTE.Debugger\n Dim sel As EnvDTE.TextSelection = DTE.ActiveDocument.Selection\n Dim editPoint As EnvDTE.EditPoint = sel.ActivePoint.CreateEditPoint()\n Dim classElem As EnvDTE.CodeElement = editPoint.CodeElement(vsCMElement.vsCMElementClass)\n\n If Not classElem Is Nothing Then\n For Each member As EnvDTE.CodeElement In classElem.Children\n If member.Kind = vsCMElement.vsCMElementFunction Then\n debugger.Breakpoints.Add(member.FullName)\n End If\n Next\n End If\n End Sub\n\nEnd Module\n</code></pre>\n\n<p><strong>Edit:</strong> Updated to add breakpoint by function name, rather than file/line number. It 'feels' better and will be easier to recognise in the breakpoints window.</p>\n" }, { "answer_id": 543816, "author": "M4N", "author_id": 19635, "author_profile": "https://Stackoverflow.com/users/19635", "pm_score": 3, "selected": false, "text": "<p>Maybe you could use an AOP framework such as PostSharp to break into the debugger whenever a method is entered. Have a look at the very short tutorial on <a href=\"http://www.postsharp.org/about/getting-started\" rel=\"noreferrer\">this page</a> for an example, how you can log/trace whenever a method is entered.</p>\n\n<p>Instead of logging, in your case you could put the Debugger.Break() statement into the OnEntry-handler. Although, the debugger would not stop in your methods, but in the OnEntry-handler (so I'm not sure if this really helps).</p>\n\n<p>Here's a very basic sample:</p>\n\n<p>The aspect class defines an OnEntry handler, which calls Debugger.Break():</p>\n\n<pre><code>[Serializable]\npublic sealed class DebugBreakAttribute : PostSharp.Laos.OnMethodBoundaryAspect\n{\n public DebugBreakAttribute() {}\n public DebugBreakAttribute(string category) {}\n public string Category { get { return \"DebugBreak\"; } }\n\n public override void OnEntry(PostSharp.Laos.MethodExecutionEventArgs eventArgs)\n {\n base.OnEntry(eventArgs);\n // debugger will break here. Press F10 to continue to the \"real\" method\n System.Diagnostics.Debugger.Break();\n }\n}\n</code></pre>\n\n<p>I can then apply this aspect to my class, where I want the debugger to break whenever a method is called:</p>\n\n<pre><code>[DebugBreak(\"DebugBreak\")]\npublic class MyClass\n{\n public MyClass()\n {\n // ...\n }\n public void Test()\n {\n // ...\n }\n}\n</code></pre>\n\n<p>Now if I build and run the application, the debugger will stop in the OnEntry() handler whenever one of the methods of MyClass is called. All I have to do then, is to press F10, and I'm in the method of MyClass.</p>\n" }, { "answer_id": 556958, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 0, "selected": false, "text": "<p>Mad method using reflection. See the documentation for <code>MethodRental.SwapMethodBody</code> for details. In pseudocode:</p>\n\n<pre><code>void SetBreakpointsForAllMethodsAndConstructorsInClass (string classname)\n{\n find type information for class classname\n for each constructor and method\n get MSIL bytes\n prepend call to System.Diagnostics.Debugger.Break to MSIL bytes\n fix up MSIL code (I'm not familiar with the MSIL spec. Generally, absolute jump targets need fixing up)\n call SwapMethodBody with new MSIL\n}\n</code></pre>\n\n<p>You can then pass in classname as a runtime argument (via the command line if you want) to set breakpoints on all methods and constructors of the given class.</p>\n" }, { "answer_id": 557006, "author": "Richard", "author_id": 67392, "author_profile": "https://Stackoverflow.com/users/67392", "pm_score": 0, "selected": false, "text": "<p>Files have no existence at runtime (consider that partial classes are no different -- in terms of code -- from putting everything in a single file). Therefore a macro approach (or code in every method) is required.</p>\n\n<p>To do the same with a type (which does exist at runtime) may be able to be done, but likely to be highly intrusive, creating more potential for heisenbugs. The \"easiest\" route to this is likely to be making use of .NET remoting's proxy infrastructure (see MOQ's implementation for an example of using transparent proxy).</p>\n\n<p>Summary: use a macro, or select all followed by set breakpoint (ctrl-A, F9).</p>\n" }, { "answer_id": 559709, "author": "Steve Steiner", "author_id": 3892, "author_profile": "https://Stackoverflow.com/users/3892", "pm_score": 3, "selected": false, "text": "<p>This feature is implemented in VS for native C++. crtl-B and specify the 'function' as \"Classname::*\", this sets a breakpoint at the beginning of every method on the class. The breakpoints set are grouped together in the breakpoints window (ctrl-alt-B) so they can be enabled, disabled, and removed as a group. </p>\n\n<p>Sadly the macro is likely the best bet for managed code. </p>\n" }, { "answer_id": 561721, "author": "Andrew Arnott", "author_id": 46926, "author_profile": "https://Stackoverflow.com/users/46926", "pm_score": 1, "selected": false, "text": "<p>Joel, the answer seems to be \"no\". There isn't a way without a breakpoint at every method.</p>\n" }, { "answer_id": 3666880, "author": "Gustaf Carleson", "author_id": 270307, "author_profile": "https://Stackoverflow.com/users/270307", "pm_score": 1, "selected": false, "text": "<p>To remove the breakpoints set by the accepted answer add another macro with the following code</p>\n\n<pre><code>Public Sub RemoveBreakOnAnyMember()\n Dim debugger As EnvDTE.Debugger = DTE.Debugger\n\n Dim bps As Breakpoints\n bps = debugger.Breakpoints\n\n If (bps.Count &gt; 0) Then\n Dim bp As Breakpoint\n For Each bp In bps\n Dim split As String() = bp.File.Split(New [Char]() {\"\\\"c})\n\n If (split.Length &gt; 0) Then\n Dim strName = split(split.Length - 1)\n If (strName.Equals(DTE.ActiveDocument.Name)) Then\n bp.Delete()\n End If\n End If\n Next\n End If\nEnd Sub\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16012/" ]
In Visual Studio, is there any way to make the debugger break whenever a certain file (or class) is entered? Please don't answer "just set a breakpoint at the beginning of every method" :) I am using C#.
Macros can be your friend. Here is a macro that will add a breakpoint to every method in the current class (put the cursor somewhere in the class before running it). ``` Public Module ClassBreak Public Sub BreakOnAnyMember() Dim debugger As EnvDTE.Debugger = DTE.Debugger Dim sel As EnvDTE.TextSelection = DTE.ActiveDocument.Selection Dim editPoint As EnvDTE.EditPoint = sel.ActivePoint.CreateEditPoint() Dim classElem As EnvDTE.CodeElement = editPoint.CodeElement(vsCMElement.vsCMElementClass) If Not classElem Is Nothing Then For Each member As EnvDTE.CodeElement In classElem.Children If member.Kind = vsCMElement.vsCMElementFunction Then debugger.Breakpoints.Add(member.FullName) End If Next End If End Sub End Module ``` **Edit:** Updated to add breakpoint by function name, rather than file/line number. It 'feels' better and will be easier to recognise in the breakpoints window.
250,577
<p>I have an Ant script with a junit target where I want it to start up the VM with a different working directory than the basedir. How would I do this?</p> <p>Here's a pseudo version of my target.</p> <pre><code>&lt;target name="buildWithClassFiles"&gt; &lt;mkdir dir="${basedir}/UnitTest/junit-reports"/&gt; &lt;junit fork="true" printsummary="yes"&gt; &lt;classpath&gt; &lt;pathelement location="${basedir}/UnitTest/bin"/&gt; &lt;path refid="classpath.compile.tests.nojars"/&gt; &lt;/classpath&gt; &lt;jvmarg value="-javaagent:${lib}/jmockit/jmockit.jar=coverage=:html"/&gt; &lt;formatter type="xml" /&gt; &lt;test name="GlobalTests" todir="${basedir}/UnitTest/junit-reports" /&gt; &lt;/junit&gt; &lt;/target&gt; </code></pre>
[ { "answer_id": 250651, "author": "James Van Huis", "author_id": 31828, "author_profile": "https://Stackoverflow.com/users/31828", "pm_score": 3, "selected": false, "text": "<p>Have you tried:</p>\n\n<pre><code> &lt;junit fork=\"true\" printsummary=\"yes\" dir=\"workingdir\"&gt;\n</code></pre>\n" }, { "answer_id": 250927, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 0, "selected": false, "text": "<p>I think the other answers might be overlooking the fact that you want the working directory to be specified, not just that you want to run junit on a particular directory. In other words, you want to make sure that if a test creates a file with no path information, it is from the base directory you are specifying.</p>\n\n<p>Try to pass in the directory you want as a JVM arg to junit, overriding <code>user.dir</code>:</p>\n\n<pre><code> &lt;junit fork=\"true\" ...&gt;\n &lt;jvmarg value=\"-Duser.dir=${desired.current.dir}\"/&gt;\n ....\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
I have an Ant script with a junit target where I want it to start up the VM with a different working directory than the basedir. How would I do this? Here's a pseudo version of my target. ``` <target name="buildWithClassFiles"> <mkdir dir="${basedir}/UnitTest/junit-reports"/> <junit fork="true" printsummary="yes"> <classpath> <pathelement location="${basedir}/UnitTest/bin"/> <path refid="classpath.compile.tests.nojars"/> </classpath> <jvmarg value="-javaagent:${lib}/jmockit/jmockit.jar=coverage=:html"/> <formatter type="xml" /> <test name="GlobalTests" todir="${basedir}/UnitTest/junit-reports" /> </junit> </target> ```
Have you tried: ``` <junit fork="true" printsummary="yes" dir="workingdir"> ```
250,583
<p>I'm trying to get all property names / values from an Outlook item. I have custom properties in addition to the default outlook item properties. I'm using redemption to get around the Outlook warnings but I'm having some problems with the GetNamesFromIDs method on a Redemption.RDOMail Item....</p> <p>I'm using my redemption session to get the message and trying to use the message to get the names of all the properties.</p> <pre><code>Dim rMessage as Redemption.RDOMail = _RDOSession.GetMessageFromID(EntryID, getPublicStoreID()) Dim propertyList As Redemption.PropList = someMessage.GetPropList(Nothing) For i As Integer = 1 To propertyList.Count + 1 Console.WriteLine(propertyList(i).ToString()) Console.WriteLine(someMessage.GetNamesFromIDs(________, propertyList(i))) Next </code></pre> <p>I'm not totally sure what to pass in as the first parameter to getNamesFromIDs. The definition of GetNamesFromIDs is as follows:</p> <pre><code>GetNamesFromIDs(MAPIProp as Object, PropTag as Integer) As Redemption.NamedProperty </code></pre> <p>I'm not totally sure what should be passed in as the MAPIProp object. I don't see this property referenced in the documentation. <a href="http://www.dimastr.com/redemption/rdo/MAPIProp.htm#properties" rel="nofollow noreferrer">http://www.dimastr.com/redemption/rdo/MAPIProp.htm#properties</a></p> <p>Any help or insight would be greatly appreciated.</p>
[ { "answer_id": 250595, "author": "Marko", "author_id": 31141, "author_profile": "https://Stackoverflow.com/users/31141", "pm_score": 2, "selected": false, "text": "<p>Whatever you are most familiar with.</p>\n\n<p>Or whatever have better set of ready to go components, so either Java (Netbeans/Matise + wizards) or something else.</p>\n" }, { "answer_id": 250602, "author": "razong", "author_id": 29885, "author_profile": "https://Stackoverflow.com/users/29885", "pm_score": 2, "selected": false, "text": "<p>Try python with wxPython for UI programming. I suggest, that you look for an ORM mapper like SQLachemy.</p>\n\n<p>Somebody suggested <a href=\"http://dabodev.com/\" rel=\"nofollow noreferrer\">dabo</a> which is made especially for your purpose, but I have no experience with it (yet). It works with wxPython and databases like SQLite.</p>\n" }, { "answer_id": 250606, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 2, "selected": false, "text": "<p>Need more info. For in house or will you distribute? Desktop or web-based? If web-based, do you host it or will you have it hosted?</p>\n\n<p>Then there's your personal goals. Really, really do it quick, or let it be an opportunity to learn a language/technology you are curious about, like Ruby on Rails? Linq?</p>\n" }, { "answer_id": 250624, "author": "Bryan Oakley", "author_id": 7432, "author_profile": "https://Stackoverflow.com/users/7432", "pm_score": 1, "selected": false, "text": "<p>GUI development isn't much easier than with Tcl/tk. Also, Tcl has arguably the best interface to sqlite. If deployment is an issue there's definitely no language that can compete with tcl's tclkit/starkit/starpack packaging mechanism. </p>\n" }, { "answer_id": 250649, "author": "niXar", "author_id": 19979, "author_profile": "https://Stackoverflow.com/users/19979", "pm_score": 1, "selected": false, "text": "<p>Write a XulRunner app; this can run with Firefox 3.0. </p>\n\n<p><a href=\"http://developer.mozilla.org\" rel=\"nofollow noreferrer\">http://developer.mozilla.org</a></p>\n" }, { "answer_id": 250721, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.codegear.com\" rel=\"nofollow noreferrer\">Delphi</a>. It's an ideal fit for this kind of desktop application, and there's a <a href=\"http://www.itwriting.com/blog/a-simple-delphi-wrapper-for-sqlite-3\" rel=\"nofollow noreferrer\">SQLite wrapper available</a>. </p>\n" }, { "answer_id": 250967, "author": "robintw", "author_id": 1912, "author_profile": "https://Stackoverflow.com/users/1912", "pm_score": 3, "selected": true, "text": "<p>Ruby on Rails will do simple CRUD operations <strong>very</strong> easily - although doing more than that can be a little more complex (would require some reading about RoR's way of doing things). The latest version of Rails automatically uses sqlite databases, and in fact the whole database, and CRUD GUI code can be created with one command (<code>scaffold</code>).</p>\n\n<p>If this is to be deployed then that can be a bit more difficult (although I hear that Capistrano is good) - but for local or intranet use then that's what I'd do.</p>\n" }, { "answer_id": 251095, "author": "webclimber", "author_id": 23238, "author_profile": "https://Stackoverflow.com/users/23238", "pm_score": 0, "selected": false, "text": "<p>C# and WPF, it;s preatty easy and good to know (I've been playing with it for 1 week and fully wrote a twitter client in a few hours.</p>\n\n<p>now Cocoa, and the interface Builder, that is a cool approach even for a simple app.</p>\n" }, { "answer_id": 434570, "author": "Andy Dent", "author_id": 53870, "author_profile": "https://Stackoverflow.com/users/53870", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.realsoftware.com/\" rel=\"nofollow noreferrer\">REALbasic</a>, if you want to do a desktop app. The Personal edition comes with SQLite built in and is free on Linux, cheap on other platforms. It's a very clean OO language and reasonable IDE, about as productive as VB6 to work in but much cleaner.</p>\n\n<p>I've been doing cross-platform development for about 15 years and REALbasic is now my tool of choice for straightforward database form apps, including an enterprise accounting system I'm currently working on.</p>\n\n<p>I also am working in WPF/C#, C++ and Cocoa/Objective-C so I'm <a href=\"http://www.oofile.com.au\" rel=\"nofollow noreferrer\">not</a> just a \"Basic-weanie\" :-)</p>\n" }, { "answer_id": 2248046, "author": "mythz", "author_id": 85785, "author_profile": "https://Stackoverflow.com/users/85785", "pm_score": 0, "selected": false, "text": "<p>If you were developing a web app I would suggest a scaffold-enabled site like <strong>rails</strong>, <strong>django</strong> or <strong>ASP.NET MVC (dynamic data)</strong>. If its a windows app, nothing beats the productivity and features of WPF/Silverlight, if so consider using <a href=\"http://code.google.com/p/servicestack/wiki/OrmLite\" rel=\"nofollow noreferrer\">OrmLite</a>, a POCO-driven lightweight ORM providing a set of useful extension methods around the common ADO.NET IDbConnection and IDbCommand interfaces. Using only convention and DataAnnotation attributes for configuration, it's effortlessly able to persist models with deep complex object graphs. </p>\n\n<p>A live working example using Sqlite (with full source code) is available here:\n<a href=\"http://www.servicestack.net/ServiceStack.Examples.Clients/Default.htm\" rel=\"nofollow noreferrer\">http://www.servicestack.net/ServiceStack.Examples.Clients/Default.htm</a></p>\n\n<p>There is also a complete end-to-end example (i.e. stand-alone, no other config required) on stackoverflow:\n<a href=\"https://stackoverflow.com/questions/2106710/xml-to-sql-using-linq-and-c/2137249#2137249\">xml to sql using linq and C#</a></p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1385358/" ]
I'm trying to get all property names / values from an Outlook item. I have custom properties in addition to the default outlook item properties. I'm using redemption to get around the Outlook warnings but I'm having some problems with the GetNamesFromIDs method on a Redemption.RDOMail Item.... I'm using my redemption session to get the message and trying to use the message to get the names of all the properties. ``` Dim rMessage as Redemption.RDOMail = _RDOSession.GetMessageFromID(EntryID, getPublicStoreID()) Dim propertyList As Redemption.PropList = someMessage.GetPropList(Nothing) For i As Integer = 1 To propertyList.Count + 1 Console.WriteLine(propertyList(i).ToString()) Console.WriteLine(someMessage.GetNamesFromIDs(________, propertyList(i))) Next ``` I'm not totally sure what to pass in as the first parameter to getNamesFromIDs. The definition of GetNamesFromIDs is as follows: ``` GetNamesFromIDs(MAPIProp as Object, PropTag as Integer) As Redemption.NamedProperty ``` I'm not totally sure what should be passed in as the MAPIProp object. I don't see this property referenced in the documentation. <http://www.dimastr.com/redemption/rdo/MAPIProp.htm#properties> Any help or insight would be greatly appreciated.
Ruby on Rails will do simple CRUD operations **very** easily - although doing more than that can be a little more complex (would require some reading about RoR's way of doing things). The latest version of Rails automatically uses sqlite databases, and in fact the whole database, and CRUD GUI code can be created with one command (`scaffold`). If this is to be deployed then that can be a bit more difficult (although I hear that Capistrano is good) - but for local or intranet use then that's what I'd do.
250,597
<p>I have a WPF TreeView with just 1 level of items. The TreeView is data bound to an ObservableCollection of strings. How can I ensure that the same icon appears to the left of each node in the TreeView?</p>
[ { "answer_id": 253243, "author": "James Osborn", "author_id": 6686, "author_profile": "https://Stackoverflow.com/users/6686", "pm_score": 4, "selected": false, "text": "<p>I think the best approach is to set a Style on the TreeView that will change the Template of the TreeViewItems to have the Image that you want.</p>\n\n<p>The Template will probably need to be a StackPanel with an Image and a label control, you bind the image to your icon, and the label text to the strings from the Observable collection.</p>\n\n<p>I've copied the relevant code snippet from a <a href=\"http://www.codeproject.com/KB/WPF/WPF_Explorer_Tree.aspx\" rel=\"noreferrer\">Code Project article</a>, which covers this in more detail, but I think the below is all you'll need (This code goes in the TreeView.Resources element).</p>\n\n<pre><code>&lt;Style TargetType=\"{x:Type TreeViewItem}\"&gt;\n &lt;Setter Property=\"HeaderTemplate\"&gt;\n &lt;Setter.Value&gt;\n &lt;DataTemplate&gt;\n &lt;StackPanel Orientation=\"Horizontal\"&gt;\n &lt;Image Name=\"img\"\n Width=\"20\"\n Height=\"20\"\n Stretch=\"Fill\"\n Source=\"image.png\"/&gt;\n &lt;TextBlock Text=\"{Binding}\" Margin=\"5,0\" /&gt;\n &lt;/StackPanel&gt;\n &lt;/DataTemplate&gt;\n &lt;/Setter.Value&gt;\n &lt;/Setter&gt;\n&lt;/Style&gt;\n</code></pre>\n" }, { "answer_id": 253599, "author": "EisenbergEffect", "author_id": 24146, "author_profile": "https://Stackoverflow.com/users/24146", "pm_score": 4, "selected": false, "text": "<p>I think one of the best articles that will help you to understand the TreeView is this one <a href=\"http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx</a>. In general, this describes a good set of patterns that can make a lot of scenarios in WPF/SL much easier.</p>\n" }, { "answer_id": 571053, "author": "Zack Peterson", "author_id": 83, "author_profile": "https://Stackoverflow.com/users/83", "pm_score": 4, "selected": false, "text": "<p>I used <a href=\"https://stackoverflow.com/users/6686/james-osborn\">James Osborn</a>'s <a href=\"https://stackoverflow.com/questions/250597/how-do-i-add-icons-next-to-the-nodes-in-a-wpf-treeview/253243#253243\">StackPanel technique</a> in this way...</p>\n\n<p>XAML:</p>\n\n<pre><code>&lt;TreeView Name=\"TreeViewThings\" ItemsSource=\"{Binding}\"&gt;\n &lt;TreeView.Resources&gt;\n &lt;HierarchicalDataTemplate DataType=\"{x:Type local:Thing}\"\n ItemsSource=\"{Binding Children}\"&gt;\n &lt;StackPanel Orientation=\"Horizontal\" Margin=\"2\"&gt;\n &lt;Image Source=\"Thing.png\"\n Width=\"16\"\n Height=\"16\"\n SnapsToDevicePixels=\"True\"/&gt;\n &lt;TextBlock Text=\"{Binding Path=Name}\" Margin=\"5,0\"/&gt;\n &lt;/StackPanel&gt;\n &lt;/HierarchicalDataTemplate&gt;\n &lt;/TreeView.Resources&gt;\n&lt;/TreeView&gt;\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/132931/" ]
I have a WPF TreeView with just 1 level of items. The TreeView is data bound to an ObservableCollection of strings. How can I ensure that the same icon appears to the left of each node in the TreeView?
I think the best approach is to set a Style on the TreeView that will change the Template of the TreeViewItems to have the Image that you want. The Template will probably need to be a StackPanel with an Image and a label control, you bind the image to your icon, and the label text to the strings from the Observable collection. I've copied the relevant code snippet from a [Code Project article](http://www.codeproject.com/KB/WPF/WPF_Explorer_Tree.aspx), which covers this in more detail, but I think the below is all you'll need (This code goes in the TreeView.Resources element). ``` <Style TargetType="{x:Type TreeViewItem}"> <Setter Property="HeaderTemplate"> <Setter.Value> <DataTemplate> <StackPanel Orientation="Horizontal"> <Image Name="img" Width="20" Height="20" Stretch="Fill" Source="image.png"/> <TextBlock Text="{Binding}" Margin="5,0" /> </StackPanel> </DataTemplate> </Setter.Value> </Setter> </Style> ```
250,599
<p>In the following code, used to get a list of products in a particular line, the command only returns results when I hard code (concatenate) <code>productLine</code> into the SQL. The parameter substitution never happens.</p> <pre><code> + "lineName = '@productLine' " + "and isVisible = 1 "; MySqlDataAdapter adap = new MySqlDataAdapter(sql, msc); adap.SelectCommand.Parameters.Add("@productLine", productLine); </code></pre>
[ { "answer_id": 250611, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 2, "selected": false, "text": "<p>Remove the apostrophes (spelling?). The ' around the parameter. They should not be needed.</p>\n" }, { "answer_id": 250640, "author": "Ian G", "author_id": 31765, "author_profile": "https://Stackoverflow.com/users/31765", "pm_score": 0, "selected": false, "text": "<p>like he said</p>\n\n<pre><code>+ \"lineName = '@productLine' \" \n</code></pre>\n\n<p>should be</p>\n\n<pre><code>+ \"lineName = @productLine \" \n</code></pre>\n" }, { "answer_id": 250645, "author": "Robert", "author_id": 27412, "author_profile": "https://Stackoverflow.com/users/27412", "pm_score": 0, "selected": false, "text": "<p>That's correct it never happens you have</p>\n\n<ul>\n<li>\"lineName = '@productLine' \"</li>\n</ul>\n\n<p>try</p>\n\n<ul>\n<li>\"lineName = @productLine \" instead as @productLine will already be declared as a string type the quotes will be added secretly. You however are actually passing the string @productLine and not the variable value.</li>\n</ul>\n" }, { "answer_id": 250659, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 4, "selected": true, "text": "<pre><code> + \"lineName = ?productLine \" \n + \"and isVisible = 1 \";\n MySqlDataAdapter adap = new MySqlDataAdapter(sql, msc);\n adap.SelectCommand.Parameters.Add(\"?productLine\", productLine);\n</code></pre>\n\n<ol>\n<li>Remove the apostrophes (').</li>\n<li>Change @ to ?, which is the prefix of parameters in MySql queries.</li>\n</ol>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]
In the following code, used to get a list of products in a particular line, the command only returns results when I hard code (concatenate) `productLine` into the SQL. The parameter substitution never happens. ``` + "lineName = '@productLine' " + "and isVisible = 1 "; MySqlDataAdapter adap = new MySqlDataAdapter(sql, msc); adap.SelectCommand.Parameters.Add("@productLine", productLine); ```
``` + "lineName = ?productLine " + "and isVisible = 1 "; MySqlDataAdapter adap = new MySqlDataAdapter(sql, msc); adap.SelectCommand.Parameters.Add("?productLine", productLine); ``` 1. Remove the apostrophes ('). 2. Change @ to ?, which is the prefix of parameters in MySql queries.
250,603
<p>I'm sure I'm going to have to write supporting javascript code to do this. I have an autocomplete extender set up that selects values from a database table, when a selection is made, i would like it to set the ID of the value selected to a hidden control. I can do that by handling a value change on the text box and making a select call to the database, Select idCompany from Companies Where CompanyName = "the text box value"; </p> <p>The most important thing is to constrain the values of the text box that is the targetcontrol for the autocomplete extender to ONLY use values from the autocomplete drop down. Is this possible with that control, is there examples somewhere? is there a better control to use (within the ajax control toolkit or standard .net framework - not a third party control)?</p> <p>I'm going to be trying to work out some javascript, but I'll be checking back to this question to see if anyone has some useful links. I've been googling this last night for quite a while.</p> <p>Update: I did not get an answer or any useful links, I've posted an almost acceptable user control that does what I want, with a few workable issues. </p>
[ { "answer_id": 265532, "author": "stephenbayer", "author_id": 18893, "author_profile": "https://Stackoverflow.com/users/18893", "pm_score": 3, "selected": true, "text": "<p>No one was able to give me an answer. This has been an ongoing saga. It started when I was trying to find a <a href=\"https://stackoverflow.com/questions/247438/alternative-ui-control-for-large-data-lists-instead-of-dropdownlist\">solution not using drop down lists for large amounts of data</a>. I have run into issues with this so many times in previous projects. This seems to be workable code. Now I need to know how to supply a AutoPostBack Property, and allow for some events, such as SelectedValueChanged. And due to the javascript, it will conflict with another control, if I have more than one of them on the same page. Well, that's some of the known issues I'm looking at with the code, but it's a start and definately better than looking at a hung browser for 3 or 4 minutes while the drop down is loading 30k list items. </p>\n\n<p>This code is assuming there is an asmx file with the script methods GetCompanyListBySearchString and GetCompanyIDByCompanyName.</p>\n\n<p><strong>ASPX FILE</strong></p>\n\n<pre><code>&lt;%@ Control Language=\"C#\" AutoEventWireup=\"true\" CodeFile=\"SelectCompany.ascx.cs\" Inherits=\"Controls_SelectCompany\" %&gt;\n&lt;%@ Register TagPrefix=\"ajaxToolkit\" Namespace=\"AjaxControlToolkit\" Assembly=\"AjaxControlToolkit\" %&gt;\n&lt;script language=\"javascript\" type=\"text/javascript\"&gt;\n var txtCompanyIDHiddenField = '&lt;%= fldCompanyID.ClientID %&gt;';\n var txtCompanyIDTextBox = '&lt;%= txtCompany.ClientID %&gt;';\n function getCompanyID() {\n if (document.getElementById(txtCompanyIDTextBox).value != \"\")\n CompanyService.GetCompanyIDByCompanyName(document.getElementById(txtCompanyIDTextBox).value, onCompanyIDSuccess, onCompanyIDFail);\n }\n function onCompanyIDSuccess(sender, e) {\n if (sender == -1)\n document.getElementById(txtCompanyIDTextBox).value = \"\";\n document.getElementById(txtCompanyIDHiddenField).value = sender;\n }\n function onCompanyIDFail(sender, e) {\n document.getElementById(txtCompanyIDTextBox).value = \"\";\n document.getElementById(txtCompanyIDHiddenField).value = \"-1\";\n }\n function onCompanySelected() {\n document.getElementById(txtCompanyIDTextBox).blur();\n }\n&lt;/script&gt;\n&lt;asp:TextBox ID=\"txtCompany\" runat=\"server\" onblur='getCompanyID()' \n/&gt;&lt;ajaxToolkit:AutoCompleteExtender runat=\"server\" ID=\"aceCompany\" CompletionInterval=\"1000\" CompletionSetCount=\"10\"\n MinimumPrefixLength=\"2\" ServicePath=\"~/Company/CompanyService.asmx\" ServiceMethod=\"GetCompanyListBySearchString\"\n OnClientItemSelected=\"onCompanySelected\" TargetControlID=\"txtCompany\" /&gt;\n &lt;asp:HiddenField ID=\"fldCompanyID\" runat=\"server\" Value=\"0\" /&gt;\n</code></pre>\n\n<p><strong>CODE BEHIND</strong></p>\n\n<pre><code>[System.ComponentModel.DefaultProperty(\"Text\")]\n[ValidationProperty(\"Text\")] \npublic partial class ApplicationControls_SelectCompany : System.Web.UI.UserControl\n\n{\npublic string Text\n{\n get { return txtCompany.Text; }\n set\n {\n txtCompany.Text = value;\n //this should probably be read only and set the value based off of ID to \n // make certain this is a valid Company\n }\n}\npublic int CompanyID\n{\n get\n {\n int ret = -1; Int32.TryParse(fldCompanyID.Value, out ret); return ret;\n }\n set\n {\n fldCompanyID.Value = value.ToString();\n //Todo: should set code to set the Text based on the ID to keep things straight\n }\n}\n}\n</code></pre>\n" }, { "answer_id": 324131, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Thanks for your post here. It is useful, however, it is assuming that everyone knows the setup to get the webservice called by a javascript function.</p>\n\n<p>Sorry to be soo newbie, but I couldn't get the webservice called from client-side.\nI read this documentation: <a href=\"http://msdn.microsoft.com/en-us/magazine/cc163499.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/magazine/cc163499.aspx</a></p>\n\n<p>Furthermore, I found an interesting post that explains how to create/get a name value pair which is pretty much what you are expecting as far as I understood:</p>\n\n<p><a href=\"http://blogs.msdn.com/phaniraj/archive/2007/06/19/how-to-use-a-key-value-pair-in-your-autocompleteextender.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/phaniraj/archive/2007/06/19/how-to-use-a-key-value-pair-in-your-autocompleteextender.aspx</a></p>\n\n<p>Sorry if I misunderstood you, but I am just trying to guide other people that pass through the same situation.</p>\n\n<p>Thanks a lot.</p>\n" }, { "answer_id": 544064, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You can check the value of the selection by trapping on ClientItemSelected event and ensure that it is not blank.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18893/" ]
I'm sure I'm going to have to write supporting javascript code to do this. I have an autocomplete extender set up that selects values from a database table, when a selection is made, i would like it to set the ID of the value selected to a hidden control. I can do that by handling a value change on the text box and making a select call to the database, Select idCompany from Companies Where CompanyName = "the text box value"; The most important thing is to constrain the values of the text box that is the targetcontrol for the autocomplete extender to ONLY use values from the autocomplete drop down. Is this possible with that control, is there examples somewhere? is there a better control to use (within the ajax control toolkit or standard .net framework - not a third party control)? I'm going to be trying to work out some javascript, but I'll be checking back to this question to see if anyone has some useful links. I've been googling this last night for quite a while. Update: I did not get an answer or any useful links, I've posted an almost acceptable user control that does what I want, with a few workable issues.
No one was able to give me an answer. This has been an ongoing saga. It started when I was trying to find a [solution not using drop down lists for large amounts of data](https://stackoverflow.com/questions/247438/alternative-ui-control-for-large-data-lists-instead-of-dropdownlist). I have run into issues with this so many times in previous projects. This seems to be workable code. Now I need to know how to supply a AutoPostBack Property, and allow for some events, such as SelectedValueChanged. And due to the javascript, it will conflict with another control, if I have more than one of them on the same page. Well, that's some of the known issues I'm looking at with the code, but it's a start and definately better than looking at a hung browser for 3 or 4 minutes while the drop down is loading 30k list items. This code is assuming there is an asmx file with the script methods GetCompanyListBySearchString and GetCompanyIDByCompanyName. **ASPX FILE** ``` <%@ Control Language="C#" AutoEventWireup="true" CodeFile="SelectCompany.ascx.cs" Inherits="Controls_SelectCompany" %> <%@ Register TagPrefix="ajaxToolkit" Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit" %> <script language="javascript" type="text/javascript"> var txtCompanyIDHiddenField = '<%= fldCompanyID.ClientID %>'; var txtCompanyIDTextBox = '<%= txtCompany.ClientID %>'; function getCompanyID() { if (document.getElementById(txtCompanyIDTextBox).value != "") CompanyService.GetCompanyIDByCompanyName(document.getElementById(txtCompanyIDTextBox).value, onCompanyIDSuccess, onCompanyIDFail); } function onCompanyIDSuccess(sender, e) { if (sender == -1) document.getElementById(txtCompanyIDTextBox).value = ""; document.getElementById(txtCompanyIDHiddenField).value = sender; } function onCompanyIDFail(sender, e) { document.getElementById(txtCompanyIDTextBox).value = ""; document.getElementById(txtCompanyIDHiddenField).value = "-1"; } function onCompanySelected() { document.getElementById(txtCompanyIDTextBox).blur(); } </script> <asp:TextBox ID="txtCompany" runat="server" onblur='getCompanyID()' /><ajaxToolkit:AutoCompleteExtender runat="server" ID="aceCompany" CompletionInterval="1000" CompletionSetCount="10" MinimumPrefixLength="2" ServicePath="~/Company/CompanyService.asmx" ServiceMethod="GetCompanyListBySearchString" OnClientItemSelected="onCompanySelected" TargetControlID="txtCompany" /> <asp:HiddenField ID="fldCompanyID" runat="server" Value="0" /> ``` **CODE BEHIND** ``` [System.ComponentModel.DefaultProperty("Text")] [ValidationProperty("Text")] public partial class ApplicationControls_SelectCompany : System.Web.UI.UserControl { public string Text { get { return txtCompany.Text; } set { txtCompany.Text = value; //this should probably be read only and set the value based off of ID to // make certain this is a valid Company } } public int CompanyID { get { int ret = -1; Int32.TryParse(fldCompanyID.Value, out ret); return ret; } set { fldCompanyID.Value = value.ToString(); //Todo: should set code to set the Text based on the ID to keep things straight } } } ```
250,616
<p>A <a href="https://stackoverflow.com/questions/217618/construct-vs-sameasclassname-for-constructor-in-php">similar question discusses <code>__construct</code></a>, but I left it in my title for people searching who find this one.</p> <p>Apparently, __get and __set take a parameter that is the variable being gotten or set. However, you have to know the variable name (eg, know that the age of the person is $age instead of $myAge). So I don't see the point if you HAVE to know a variable name, especially if you are working with code that you aren't familiar with (such as a library).</p> <p>I found some pages that explain <a href="http://www.hudzilla.org/phpbook/read.php/6_14_2" rel="nofollow noreferrer"><code>__get()</code></a>, <a href="http://www.hudzilla.org/phpbook/read.php/6_14_3" rel="nofollow noreferrer"><code>__set()</code></a>, and <a href="http://www.hudzilla.org/phpbook/read.php/6_14_4" rel="nofollow noreferrer"><code>__call()</code></a>, but I still don't get why or when they are useful.</p>
[ { "answer_id": 250637, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<p><a href=\"http://uk.php.net/manual/en/language.oop5.overloading.php\" rel=\"nofollow noreferrer\">This page</a> will probably be useful. (Note that what you say is incorrect - <code>__set()</code> takes as a parameter both the name of the variable and the value. <code>__get()</code> just takes the name of the variable).</p>\n\n<p><code>__get()</code> and <code>__set()</code> are useful in library functions where you want to provide generic access to variables. For example in an ActiveRecord class, you might want people to be able to access database fields as object properties. For example, in Kohana PHP framework you might use:</p>\n\n<pre><code>$user = ORM::factory('user', 1);\n$email = $user-&gt;email_address;\n</code></pre>\n\n<p>This is accomplished by using <code>__get()</code> and <code>__set()</code>.</p>\n\n<p>Something similar can be accomplished when using <code>__call()</code>, i.e. you can detect when someone is calling getProperty() and setProperty() and handle accordingly.</p>\n" }, { "answer_id": 250639, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 0, "selected": false, "text": "<p>They're for doing \"clever\" things.</p>\n\n<p>For example you could use <code>__set()</code> and <code>__get()</code> to talk to a database. Your code would then be: <code>$myObject-&gt;foo = \"bar\";</code> and this could update a database record behind the scenes. Of course you'd have to be pretty careful with this or your performance could suffer, hence the quotes around \"clever\" :)</p>\n" }, { "answer_id": 250648, "author": "Aron Rotteveel", "author_id": 11568, "author_profile": "https://Stackoverflow.com/users/11568", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://uk.php.net/manual/en/language.oop5.overloading.php\" rel=\"nofollow noreferrer\">Overloading</a> methods is especially useful when working with PHP objects that contain data that should be easily accessable. <a href=\"http://www.hudzilla.org/phpbook/read.php/6_14_2\" rel=\"nofollow noreferrer\">__get()</a> is called when accessing a non-existent propery, <a href=\"http://www.hudzilla.org/phpbook/read.php/6_14_3\" rel=\"nofollow noreferrer\">__set()</a> is called when trying to write a non-existent property and <a href=\"http://www.hudzilla.org/phpbook/read.php/6_14_4\" rel=\"nofollow noreferrer\">__call()</a> is called when a non-existent method is invoked.</p>\n\n<p>For example, imagine having a class managing your config:</p>\n\n<pre><code>class Config\n{\n protected $_data = array();\n\n public function __set($key, $val)\n {\n $this-&gt;_data[$key] = $val;\n }\n\n public function __get($key)\n {\n return $this-&gt;_data[$key];\n }\n\n ...etc\n\n}\n</code></pre>\n\n<p>This makes it a lot easier to read and write to the object, and gives you the change to use custom functionality when reading or writing to object.\nExample:</p>\n\n<pre><code>$config = new Config();\n$config-&gt;foo = 'bar';\n\necho $config-&gt;foo; // returns 'bar'\n</code></pre>\n" }, { "answer_id": 250655, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 3, "selected": false, "text": "<p>__get(), __set(), and __call() are what PHP calls \"magic methods\" which is a moniker I think that is a bit silly - I think \"hook\" is a bit more apt. Anyway, I digress...</p>\n\n<p>The purpose of these is to provide execution cases for when datamembers (properties, or methods) that <em>are not</em> defined on the object are accessed, which can be used for all sorts of \"clever\" thinks like variable hiding, message forwarding, etc.</p>\n\n<p>There is a cost, however - a call that invokes these is around 10x slower than a call to defined datamembers.</p>\n" }, { "answer_id": 250666, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 2, "selected": false, "text": "<p>Redefining <code>__get</code> and <code>__set</code> can be especially useful in core classes. For example if you didn't want your config to be overwritten accidentally but still wanted to get data from it:</p>\n\n<pre><code>class Example\n{\n private $config = array('password' =&gt; 'pAsSwOrD');\n public function __get($name)\n {\n return $this-&gt;config[$name];\n }\n}\n</code></pre>\n" }, { "answer_id": 250668, "author": "JamShady", "author_id": 11905, "author_profile": "https://Stackoverflow.com/users/11905", "pm_score": 0, "selected": false, "text": "<p>One good reason to use them would be in terms of a registry system (I think Zend Framework implements this as a Registry or Config class iirc), so you can do things like</p>\n\n<pre><code>$conf = new Config();\n$conf-&gt;parent-&gt;child-&gt;grandchild = 'foo';\n</code></pre>\n\n<p>Each of those properties is an automatically generated Config object, something akin to:</p>\n\n<pre><code>function __get($key) {\n return new Config($key);\n}\n</code></pre>\n\n<p>Obviously if $conf->parent already existed, the __get() method wouldn't be called, so to use this to generate new variables is a nice trick.</p>\n\n<p>Bear in mind this code I've just quoted isn't functionality, I just wrote it quickly for the sake of example.</p>\n" }, { "answer_id": 250683, "author": "bobwienholt", "author_id": 24257, "author_profile": "https://Stackoverflow.com/users/24257", "pm_score": 0, "selected": false, "text": "<p>Probably not the cleanest design in the world but I had a situation where I had a lot of code that was referencing an instance variable in a class, i.e.:</p>\n\n<pre><code>$obj-&gt;value = 'blah';\necho $obj-&gt;value;\n</code></pre>\n\n<p>but then later, I wanted to do something special when \"value\" was set under certain circumstances so I renamed the value variable and implemented __set() and __get() with the changes I needed.</p>\n\n<p>The rest of the code didn't know the difference.</p>\n" }, { "answer_id": 250733, "author": "Michał Niedźwiedzki", "author_id": 2169, "author_profile": "https://Stackoverflow.com/users/2169", "pm_score": 2, "selected": false, "text": "<p>Another useful application of magic methods, especially <code>__get</code> and <code>__set</code> and <code>__toString</code> is templates. You can make your code independent from template engine just by writing simple adapter that uses magic methods. In case you want to move to another template engine, just change these methods only.</p>\n\n<pre><code>class View {\n\n public $templateFile;\n protected $properties = array();\n\n public function __set($property, $value) {\n $this-&gt;properties[$property] = $value;\n }\n\n public function __get($property) {\n return @$this-&gt;properties[$property];\n }\n\n public function __toString() {\n require_once 'smarty/libs/Smarty.class.php';\n $smarty = new Smarty();\n $smarty-&gt;template_dir = 'view';\n $smarty-&gt;compile_dir = 'smarty/compile';\n $smarty-&gt;config_dir = 'smarty/config';\n $smarty-&gt;cache_dir = 'smarty/cache';\n foreach ($this-&gt;properties as $property =&gt; $value) {\n $smarty-&gt;assign($property, $value);\n }\n return $smarty-&gt;fetch($this-&gt;templateFile);\n }\n\n}\n</code></pre>\n\n<p>Hidden benefit of this approach is that you can nest View objects one inside another:</p>\n\n<pre><code>$index = new View();\n$index-&gt;templateFile = 'index.tpl';\n\n$topNav = new View();\n$topNav-&gt;templateFile = 'topNav.tpl';\n\n$index-&gt;topNav = $topNav;\n</code></pre>\n\n<p>And in <code>index.tpl</code>, the nesting looks like that:</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;&lt;/head&gt;\n&lt;body&gt;\n {$topNav}\n Welcome to Foobar Corporation.\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>All nested View objects gets converted to string (HTML to be exact) on the fly, as soon as you <code>echo $index;</code></p>\n" }, { "answer_id": 1673562, "author": "guliy", "author_id": 202581, "author_profile": "https://Stackoverflow.com/users/202581", "pm_score": 1, "selected": false, "text": "<p>I think it is bad for design you code. If you know and do a good design then you will not need to use the <code>__set()</code> and <code>__get()</code> within your code. Also reading your code is very important and if you are using studio (e.g. Zend studio), with <code>__set()</code> and <code>__get()</code> you can't see your class properties.</p>\n" }, { "answer_id": 14907264, "author": "Jay Bhatt", "author_id": 2076598, "author_profile": "https://Stackoverflow.com/users/2076598", "pm_score": 1, "selected": false, "text": "<p>PHP allows us to create class variables dynamically which can cause problems. You can use __set and __get methods to restrict this behavior..see the example below...</p>\n\n<pre><code>class Person { \n public $name;\n public function printProperties(){\n print_r(get_object_vars($this));\n }\n}\n\n$person = new Person();\n$person-&gt;name = 'Jay'; //This is valid\n$person-&gt;printProperties();\n$person-&gt;age = '26'; //This shouldn't work...but it does \n$person-&gt;printProperties();\n</code></pre>\n\n<p>to prevent above you can do this..</p>\n\n<pre><code>public function __set($name, $value){\n $classVar = get_object_vars($this);\n if(in_array($name, $classVar)){\n $this-&gt;$name = $value;\n }\n}\n</code></pre>\n\n<p>Hope this helps...</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
A [similar question discusses `__construct`](https://stackoverflow.com/questions/217618/construct-vs-sameasclassname-for-constructor-in-php), but I left it in my title for people searching who find this one. Apparently, \_\_get and \_\_set take a parameter that is the variable being gotten or set. However, you have to know the variable name (eg, know that the age of the person is $age instead of $myAge). So I don't see the point if you HAVE to know a variable name, especially if you are working with code that you aren't familiar with (such as a library). I found some pages that explain [`__get()`](http://www.hudzilla.org/phpbook/read.php/6_14_2), [`__set()`](http://www.hudzilla.org/phpbook/read.php/6_14_3), and [`__call()`](http://www.hudzilla.org/phpbook/read.php/6_14_4), but I still don't get why or when they are useful.
[This page](http://uk.php.net/manual/en/language.oop5.overloading.php) will probably be useful. (Note that what you say is incorrect - `__set()` takes as a parameter both the name of the variable and the value. `__get()` just takes the name of the variable). `__get()` and `__set()` are useful in library functions where you want to provide generic access to variables. For example in an ActiveRecord class, you might want people to be able to access database fields as object properties. For example, in Kohana PHP framework you might use: ``` $user = ORM::factory('user', 1); $email = $user->email_address; ``` This is accomplished by using `__get()` and `__set()`. Something similar can be accomplished when using `__call()`, i.e. you can detect when someone is calling getProperty() and setProperty() and handle accordingly.
250,622
<p>I'd trying to style my ComboBoxes to match the rest of the UI but I'm having problems with the IsMouseOver highlighting. It highlights with the color I specify for a second and then fades back to the default color, kind of a cool effect but not what I'm going for. Here is my style:</p> <pre><code>&lt;Style TargetType="ComboBox"&gt; &lt;Style.Triggers&gt; &lt;Trigger Property="ComboBox.IsMouseOver" Value="True"&gt; &lt;Setter Property = "Background" Value="Red"/&gt; &lt;/Trigger&gt; &lt;/Style.Triggers&gt; &lt;/Style&gt; </code></pre> <p>What can I do to make the background color stay?</p>
[ { "answer_id": 252450, "author": "Todd White", "author_id": 30833, "author_profile": "https://Stackoverflow.com/users/30833", "pm_score": 3, "selected": true, "text": "<p>The problem is indeed due to the default template for the ComboBox. If you use <a href=\"http://www.red-gate.com/products/reflector/\" rel=\"nofollow noreferrer\">Reflector</a> to open the PresentationFramework.Aero assembly you can take a look at the ButtonChrome class. There is a method called OnRenderMouseOverChanged that is hiding the Red background.</p>\n\n<p>Even though it is a lot of work, for ComboBox at least, you probably will want to override the default template for the ComboBox. You can get the basic idea of what the ComboBox temlpate is like by using <a href=\"http://www.sellsbrothers.com/news/showTopic.aspx?ixTopic=2091\" rel=\"nofollow noreferrer\">Show Me The Template</a> or <a href=\"http://www.microsoft.com/expression/products/Overview.aspx?key=blend\" rel=\"nofollow noreferrer\">Blend</a>.</p>\n\n<p>You can use your same style to override the template.</p>\n\n<pre><code>&lt;Style TargetType=\"{x:Type ComboBox}\"&gt;\n &lt;Setter Property=\"Template\"&gt;\n &lt;Setter.Value&gt;\n &lt;ControlTemplate TargetType=\"{x:Type ComboBox}\"&gt;\n &lt;!-- Template Here --&gt;\n &lt;/ControlTemplate&gt;\n &lt;/Setter.Value&gt;\n &lt;/Setter&gt;\n&lt;/Style&gt;\n</code></pre>\n" }, { "answer_id": 34533372, "author": "user1290865", "author_id": 1290865, "author_profile": "https://Stackoverflow.com/users/1290865", "pm_score": 0, "selected": false, "text": "<p>You can override this behavior by getting a copy of the default template from the WPF Visual Studio Designer and then in the ComboBoxReadonlyToggleButton style comment out the ButtonChrome section and replace it with a Border. Here is a link to the site where I found the solution - <a href=\"http://www.scriptscoop.net/t/d346cf01d844/c-c-wpf-combobox-mouse-over-color.html\" rel=\"nofollow\">http://www.scriptscoop.net/t/d346cf01d844/c-c-wpf-combobox-mouse-over-color.html</a></p>\n\n<p>Here is my code snippet</p>\n\n<pre><code>&lt;Style x:Key=\"ComboBoxReadonlyToggleButton\" TargetType=\"{x:Type ToggleButton}\"&gt;\n &lt;Setter Property=\"OverridesDefaultStyle\" Value=\"true\"/&gt;\n &lt;Setter Property=\"IsTabStop\" Value=\"false\"/&gt;\n &lt;Setter Property=\"Focusable\" Value=\"false\"/&gt;\n &lt;Setter Property=\"ClickMode\" Value=\"Press\"/&gt;\n &lt;Setter Property=\"Background\" Value=\"Transparent\"/&gt;\n &lt;Setter Property=\"Template\"&gt;\n &lt;Setter.Value&gt;\n &lt;ControlTemplate TargetType=\"{x:Type ToggleButton}\"&gt;\n &lt;!-- Replace the ButtonChrome - this eliminated the following\n problem: When the mouse was moved over the ComboBox\n the color would change to the color defined in ___ but \n then would \n immediately change to the default Aero blue\n gradient background of 2 powder blue colors - \n Had to comment out the \n below code and replace it as shown\n &lt;Themes:ButtonChrome x:Name=\"Chrome\" BorderBrush=\" {TemplateBinding BorderBrush}\" Background=\"{TemplateBinding Background}\" RenderMouseOver=\"{TemplateBinding IsMouseOver}\" RenderPressed=\"{TemplateBinding IsPressed}\" SnapsToDevicePixels=\"true\"&gt;\n &lt;Grid HorizontalAlignment=\"Right\" Width=\"{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}\"&gt;\n &lt;Path x:Name=\"Arrow\" Data=\"{StaticResource DownArrowGeometry}\" Fill=\"Black\" HorizontalAlignment=\"Center\" Margin=\"3,1,0,0\" VerticalAlignment=\"Center\"/&gt;\n &lt;/Grid&gt;\n &lt;/Themes:ButtonChrome&gt;--&gt;\n\n &lt;!-- Here is the code to replace the ButtonChrome code --&gt;\n &lt;Border x:Name=\"Chrome\" BorderBrush=\"{TemplateBinding BorderBrush}\" Background=\"{TemplateBinding Background}\" SnapsToDevicePixels=\"true\"&gt;\n &lt;Grid HorizontalAlignment=\"Right\" Width=\"{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}\"&gt;\n &lt;Path x:Name=\"Arrow\" Data=\"{StaticResource DownArrowGeometry}\" Fill=\"Black\" HorizontalAlignment=\"Center\" Margin=\"3,1,0,0\" VerticalAlignment=\"Center\"/&gt;\n &lt;/Grid&gt;\n &lt;/Border&gt;\n &lt;!-- End of code to replace the Button Chrome --&gt;\n</code></pre>\n\n<p>I also added some code to change the background color to DarkOrange - \nThis code went into the ControlTemplate (in the section) for the Style for the ComboBox.</p>\n\n<pre><code>&lt;!-- Hover Code - Code that was added to change the ComboBox background \n color when the use hovers over it with the mouse --&gt;\n&lt;Trigger Property=\"IsMouseOver\" Value=\"True\"&gt;\n &lt;Setter Property=\"Background\" Value=\"DarkOrange\"&gt;&lt;/Setter&gt;\n&lt;/Trigger&gt;\n&lt;!-- Hover Code - End --&gt;\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21186/" ]
I'd trying to style my ComboBoxes to match the rest of the UI but I'm having problems with the IsMouseOver highlighting. It highlights with the color I specify for a second and then fades back to the default color, kind of a cool effect but not what I'm going for. Here is my style: ``` <Style TargetType="ComboBox"> <Style.Triggers> <Trigger Property="ComboBox.IsMouseOver" Value="True"> <Setter Property = "Background" Value="Red"/> </Trigger> </Style.Triggers> </Style> ``` What can I do to make the background color stay?
The problem is indeed due to the default template for the ComboBox. If you use [Reflector](http://www.red-gate.com/products/reflector/) to open the PresentationFramework.Aero assembly you can take a look at the ButtonChrome class. There is a method called OnRenderMouseOverChanged that is hiding the Red background. Even though it is a lot of work, for ComboBox at least, you probably will want to override the default template for the ComboBox. You can get the basic idea of what the ComboBox temlpate is like by using [Show Me The Template](http://www.sellsbrothers.com/news/showTopic.aspx?ixTopic=2091) or [Blend](http://www.microsoft.com/expression/products/Overview.aspx?key=blend). You can use your same style to override the template. ``` <Style TargetType="{x:Type ComboBox}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ComboBox}"> <!-- Template Here --> </ControlTemplate> </Setter.Value> </Setter> </Style> ```
250,643
<p>I want to attach a 'click' event handler to the first child of an element with ID 'foo' using <a href="http://en.wikipedia.org/wiki/JQuery" rel="nofollow noreferrer">jQuery</a>. I understand that the syntax for doing this is:</p> <pre><code>$('#foo:first-child').bind('click', function(event) { // I want to access the first child here }) </code></pre> <p>Within the handler body I want to access the element which caused the event to be fired. I've read somewhere that you can't simply refer to it via 'this', so how can I access it?</p>
[ { "answer_id": 250656, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 2, "selected": false, "text": "<pre><code>$(this).doStuff()\n</code></pre>\n" }, { "answer_id": 250661, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 1, "selected": true, "text": "<p>Just use \"this\":</p>\n\n<pre><code>$('#foo:first-child').bind('click', function(event) {\n alert(this === $('#foo:first-child')); // True\n this.style.color = \"red\"; // First child now has red text.\n})\n</code></pre>\n" }, { "answer_id": 250672, "author": "Svante Svenson", "author_id": 19707, "author_profile": "https://Stackoverflow.com/users/19707", "pm_score": 2, "selected": false, "text": "<p>Forget what you read somewhere and go ahead and use the this keyword:</p>\n\n<pre><code>$(\"#foo:first-child\").click(function(event) {\n $(this).css(\"background\", \"pink\");\n});\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
I want to attach a 'click' event handler to the first child of an element with ID 'foo' using [jQuery](http://en.wikipedia.org/wiki/JQuery). I understand that the syntax for doing this is: ``` $('#foo:first-child').bind('click', function(event) { // I want to access the first child here }) ``` Within the handler body I want to access the element which caused the event to be fired. I've read somewhere that you can't simply refer to it via 'this', so how can I access it?
Just use "this": ``` $('#foo:first-child').bind('click', function(event) { alert(this === $('#foo:first-child')); // True this.style.color = "red"; // First child now has red text. }) ```
250,652
<p>I use <code>_vimrc</code> to configure my vim 7.2 (windows) default settings. One setting "set number" will display line numbers on the left side. My vim background color is white (I cannot find setting for this. Maybe the default is white. Anyway I accept this setting).</p> <p>I would like the background color for line numbers to be Grey or dimmed color. What is the command I can put in my <code>_vimrc</code> to configure this default setting?</p>
[ { "answer_id": 250686, "author": "robert", "author_id": 32805, "author_profile": "https://Stackoverflow.com/users/32805", "pm_score": 7, "selected": true, "text": "<pre class=\"lang-vim prettyprint-override\"><code>highlight LineNr ctermfg=grey ctermbg=white\n</code></pre>\n" }, { "answer_id": 250964, "author": "David.Chu.ca", "author_id": 62776, "author_profile": "https://Stackoverflow.com/users/62776", "pm_score": 3, "selected": false, "text": "<p>In my <code>_vimrc</code>, here is the setting:</p>\n\n<pre><code>highlight LineNr guibg=grey\n</code></pre>\n\n<p>or</p>\n\n<pre><code>hi LineNr guibg=grey\n</code></pre>\n\n<p>I don't need to set fore-color, the default is yellow and it is OK for me.</p>\n" }, { "answer_id": 33576970, "author": "Petur Subev", "author_id": 332124, "author_profile": "https://Stackoverflow.com/users/332124", "pm_score": 3, "selected": false, "text": "<p><strong>guibg</strong> and <strong>guifg</strong> are for vims which are not in terminal. For terminal you use <strong>ctermfg</strong> <strong>ctermbg</strong>. Usually in GUI vims you have more colors support and you simply want to avoid the background.\nSo I usually use this:</p>\n\n<pre><code>highlight LineNr guibg=NONE\n</code></pre>\n" }, { "answer_id": 41587510, "author": "sepehr", "author_id": 65732, "author_profile": "https://Stackoverflow.com/users/65732", "pm_score": 5, "selected": false, "text": "<p>To make the line number column transparent (the same color as the main background) you can try setting this in your <code>.vimrc</code>: </p>\n\n<pre><code>highlight clear LineNr\n</code></pre>\n\n<p>You can also clear the so-called sign column (used by gitgutter, etc) as well: </p>\n\n<pre><code>highlight clear SignColumn\n</code></pre>\n\n<p>This way, no matter what color scheme you use, both columns' background will be compatible.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/62776/" ]
I use `_vimrc` to configure my vim 7.2 (windows) default settings. One setting "set number" will display line numbers on the left side. My vim background color is white (I cannot find setting for this. Maybe the default is white. Anyway I accept this setting). I would like the background color for line numbers to be Grey or dimmed color. What is the command I can put in my `_vimrc` to configure this default setting?
```vim highlight LineNr ctermfg=grey ctermbg=white ```
250,688
<p>I have the following HTML node structure:</p> <pre><code>&lt;div id="foo"&gt; &lt;div id="bar"&gt;&lt;/div&gt; &lt;div id="baz"&gt; &lt;div id="biz"&gt;&lt;/div&gt; &lt;/div&gt; &lt;span&gt;&lt;/span&gt; &lt;/div&gt; </code></pre> <p>How do I count the number of immediate children of <code>foo</code>, that are of type <code>div</code>? In the example above, the result should be two (<code>bar</code> and <code>baz</code>).</p>
[ { "answer_id": 250694, "author": "Garry Shutler", "author_id": 6369, "author_profile": "https://Stackoverflow.com/users/6369", "pm_score": 9, "selected": true, "text": "<pre><code>$(\"#foo &gt; div\").length\n</code></pre>\n\n<p>Direct children of the element with the id 'foo' which are divs. Then retrieving the size of the wrapped set produced.</p>\n" }, { "answer_id": 250702, "author": "gizmo", "author_id": 9396, "author_profile": "https://Stackoverflow.com/users/9396", "pm_score": 3, "selected": false, "text": "<pre><code>$('#foo &gt; div').size()\n</code></pre>\n" }, { "answer_id": 252348, "author": "Darko", "author_id": 32943, "author_profile": "https://Stackoverflow.com/users/32943", "pm_score": 5, "selected": false, "text": "<pre><code>$(\"#foo &gt; div\") \n</code></pre>\n\n<p>selects all divs that are immediate descendants of #foo<br>\nonce you have the set of children you can either use the size function:</p>\n\n<pre><code>$(\"#foo &gt; div\").size()\n</code></pre>\n\n<p>or you can use </p>\n\n<pre><code>$(\"#foo &gt; div\").length\n</code></pre>\n\n<p>Both will return you the same result</p>\n" }, { "answer_id": 1937264, "author": "Andrew Perkins", "author_id": 235669, "author_profile": "https://Stackoverflow.com/users/235669", "pm_score": 2, "selected": false, "text": "<pre><code>var n_numTabs = $(\"#superpics div\").size();\n</code></pre>\n\n<p><strong>or</strong></p>\n\n<pre><code>var n_numTabs = $(\"#superpics div\").length;\n</code></pre>\n\n<hr>\n\n<p>As was already said, both return the same result.\n<br>But the size() function is more jQuery \"P.C\".\n<br>I had a similar problem with my page.\n<br>For now on, just omit the > and it should work fine.</p>\n" }, { "answer_id": 4358865, "author": "zholdas", "author_id": 272776, "author_profile": "https://Stackoverflow.com/users/272776", "pm_score": 3, "selected": false, "text": "<pre><code>$(\"#foo &gt; div\").length\n</code></pre>\n\n<p>jQuery has a .size() function which will return the number of times that an element appears but, as specified in the jQuery documentation, it is slower and returns the same value as the .length property so it is best to simply use the .length property.\nFrom here: <a href=\"http://www.electrictoolbox.com/get-total-number-matched-elements-jquery/\" rel=\"noreferrer\">http://www.electrictoolbox.com/get-total-number-matched-elements-jquery/</a></p>\n" }, { "answer_id": 4429790, "author": "Alexandros Ioannou", "author_id": 540628, "author_profile": "https://Stackoverflow.com/users/540628", "pm_score": 1, "selected": false, "text": "<pre><code>$(\"div\", \"#superpics\").size();\n</code></pre>\n" }, { "answer_id": 7084389, "author": "manikanta", "author_id": 340290, "author_profile": "https://Stackoverflow.com/users/340290", "pm_score": 6, "selected": false, "text": "<p>I recommend using <code>$('#foo').children().size()</code> for better performance.</p>\n\n<p>I've created a <a href=\"http://jsperf.com/jquery-child-ele-size\">jsperf</a> test to see the speed difference and the <code>children()</code> method beaten the child selector (#foo > div) approach by at least <strong>60%</strong> in Chrome (canary build v15) <strong>20-30%</strong> in Firefox (v4).</p>\n\n<p>By the way, needless to say, these two approaches produce same results (in this case, 1000).</p>\n\n<p>[Update] I've updated the test to include the size() vs length test, and they doesn't make much difference (result: <code>length</code> usage is slightly faster (2%) than <code>size()</code>)</p>\n\n<p><em>[Update] Due to the incorrect markup seen in the OP (before 'markup validated' update by me), both <code>$(\"#foo &gt; div\").length</code> &amp; <code>$('#foo').children().length</code> resulted the same (<a href=\"http://jsfiddle.net/LavMc/\">jsfiddle</a>). But for correct answer to get ONLY 'div' children, one SHOULD use child selector for correct &amp; better performance</em></p>\n" }, { "answer_id": 7364918, "author": "HaxElit", "author_id": 182703, "author_profile": "https://Stackoverflow.com/users/182703", "pm_score": 3, "selected": false, "text": "<p>In response to mrCoders answer using jsperf why not just use the dom node ?</p>\n\n<pre><code>var $foo = $('#foo');\nvar count = $foo[0].childElementCount\n</code></pre>\n\n<p>You can try the test here: <a href=\"http://jsperf.com/jquery-child-ele-size/7\" rel=\"noreferrer\">http://jsperf.com/jquery-child-ele-size/7</a></p>\n\n<p>This method gets 46,095 op/s while the other methods at best 2000 op/s</p>\n" }, { "answer_id": 12864373, "author": "Kent Thomas", "author_id": 1741947, "author_profile": "https://Stackoverflow.com/users/1741947", "pm_score": 2, "selected": false, "text": "<p>With the most recent version of jquery, you can use <code>$(\"#superpics div\").children().length</code>.</p>\n" }, { "answer_id": 15511389, "author": "John Alvarez", "author_id": 2188540, "author_profile": "https://Stackoverflow.com/users/2188540", "pm_score": 3, "selected": false, "text": "<pre><code>var divss = 0;\n$(function(){\n $(\"#foo div\").each(function(){\n divss++;\n\n });\n console.log(divss); \n}); \n&lt;div id=\"foo\"&gt;\n &lt;div id=\"bar\" class=\"1\"&gt;&lt;/div&gt;\n &lt;div id=\"baz\" class=\"1\"&gt;&lt;/div&gt;\n &lt;div id=\"bam\" class=\"1\"&gt;&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 19539030, "author": "Abdennour TOUMI", "author_id": 747579, "author_profile": "https://Stackoverflow.com/users/747579", "pm_score": 4, "selected": false, "text": "<pre><code>$('#foo').children('div').length\n</code></pre>\n" }, { "answer_id": 58214614, "author": "talent makhanya", "author_id": 8607598, "author_profile": "https://Stackoverflow.com/users/8607598", "pm_score": -1, "selected": false, "text": "<p>Try this for immediate child elements of type div</p>\n\n<pre><code>$(\"#foo &gt; div\")[0].children.length\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
I have the following HTML node structure: ``` <div id="foo"> <div id="bar"></div> <div id="baz"> <div id="biz"></div> </div> <span></span> </div> ``` How do I count the number of immediate children of `foo`, that are of type `div`? In the example above, the result should be two (`bar` and `baz`).
``` $("#foo > div").length ``` Direct children of the element with the id 'foo' which are divs. Then retrieving the size of the wrapped set produced.
250,690
<p>I'm looking for a good JavaScript RegEx to convert names to proper cases. For example:</p> <pre><code>John SMITH = John Smith Mary O'SMITH = Mary O'Smith E.t MCHYPHEN-SMITH = E.T McHyphen-Smith John Middlename SMITH = John Middlename SMITH </code></pre> <p>Well you get the idea.</p> <p>Anyone come up with a comprehensive solution?</p>
[ { "answer_id": 250707, "author": "harriyott", "author_id": 5744, "author_profile": "https://Stackoverflow.com/users/5744", "pm_score": 0, "selected": false, "text": "<p>Unfortunately there are too many different name formats to do this correctly. John-Joe MacDonald is always going to be a nuisance!</p>\n" }, { "answer_id": 250716, "author": "raccettura", "author_id": 262775, "author_profile": "https://Stackoverflow.com/users/262775", "pm_score": 0, "selected": false, "text": "<p>Agreed it will never be perfect, but looking to get the most common cases. Which is pretty much to camel case any \"word\" and handle hyphens and apostrophe's I guess as spaces. </p>\n" }, { "answer_id": 250772, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 1, "selected": false, "text": "<p>Wimps!.... Here's my second attempt. Handles \"John SMITH\", \"Mary O'SMITH\" \"John Middlename SMITH\", \"E.t MCHYPHEN-SMITH\" and \"JoHn-JOE MacDoNAld\"</p>\n\n<pre><code>Regex fixnames = new Regex(\"(Ma?C)?(\\w)(\\w*)(\\W*)\");\nstring newName = fixnames.Replace(badName, NameFixer);\n\n\nstatic public string NameFixer(Match match) \n{\n string mc = \"\";\n if (match.Groups[1].Captures.Count &gt; 0)\n {\n if (match.Groups[1].Captures[0].Length == 3)\n mc = \"Mac\";\n else\n mc = \"Mc\";\n }\n\n return \n mc\n +match.Groups[2].Captures[0].Value.ToUpper()\n +match.Groups[3].Captures[0].Value.ToLower()\n +match.Groups[4].Captures[0].Value;\n}\n</code></pre>\n\n<p>NOTE: By the time I realized you wanted a Javascript solution instead of a .NET one, I was having too much funny to stop....</p>\n" }, { "answer_id": 250785, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 3, "selected": true, "text": "<p>Something like this?</p>\n\n<pre><code>function fix_name(name) {\n var replacer = function (whole,prefix,word) {\n ret = [];\n if (prefix) {\n ret.push(prefix.charAt(0).toUpperCase());\n ret.push(prefix.substr(1).toLowerCase());\n }\n ret.push(word.charAt(0).toUpperCase());\n ret.push(word.substr(1).toLowerCase());\n return ret.join('');\n }\n var pattern = /\\b(ma?c)?([a-z]+)/ig;\n return name.replace(pattern, replacer);\n}\n</code></pre>\n" }, { "answer_id": 251755, "author": "Robert Krimen", "author_id": 25171, "author_profile": "https://Stackoverflow.com/users/25171", "pm_score": 1, "selected": false, "text": "<p>Mark Summerfield has done a comprehensive job of this with <a href=\"http://search.cpan.org/perldoc?Lingua::EN::NameCase\" rel=\"nofollow noreferrer\">Lingua::EN::NameCase</a>:</p>\n\n<pre><code>KEITH Keith\nLEIGH-WILLIAMS Leigh-Williams\nMCCARTHY McCarthy\nO'CALLAGHAN O'Callaghan\nST. JOHN St. John\nVON STREIT von Streit\nVAN DYKE van Dyke\nAP LLWYD DAFYDD ap Llwyd Dafydd\nhenry viii Henry VIII\nlouis xiv Louis XIV\n</code></pre>\n\n<p>The above is written in Perl, but it makes heavy use of regular expressions, so you should be able to glean some good techniques.</p>\n\n<p>Here the relevant source:</p>\n\n<pre><code>sub nc {\n\n croak \"Usage: nc [[\\\\]\\$SCALAR]\"\n if scalar @_ &gt; 1 or ( ref $_[0] and ref $_[0] ne 'SCALAR' ) ;\n\n local( $_ ) = @_ if @_ ;\n $_ = ${$_} if ref( $_ ) ; # Replace reference with value.\n\n $_ = lc ; # Lowercase the lot.\n s{ \\b (\\w) }{\\u$1}gox ; # Uppercase first letter of every word.\n s{ (\\'\\w) \\b }{\\L$1}gox ; # Lowercase 's.\n\n # Name case Mcs and Macs - taken straight from NameParse.pm incl. comments.\n # Exclude names with 1-2 letters after prefix like Mack, Macky, Mace\n # Exclude names ending in a,c,i,o, or j are typically Polish or Italian\n\n if ( /\\bMac[A-Za-z]{2,}[^aciozj]\\b/o or /\\bMc/o ) {\n s/\\b(Ma?c)([A-Za-z]+)/$1\\u$2/go ;\n\n # Now correct for \"Mac\" exceptions\n s/\\bMacEvicius/Macevicius/go ; # Lithuanian\n s/\\bMacHado/Machado/go ; # Portuguese\n s/\\bMacHar/Machar/go ;\n s/\\bMacHin/Machin/go ;\n s/\\bMacHlin/Machlin/go ;\n s/\\bMacIas/Macias/go ; \n s/\\bMacIulis/Maciulis/go ; \n s/\\bMacKie/Mackie/go ;\n s/\\bMacKle/Mackle/go ;\n s/\\bMacKlin/Macklin/go ;\n s/\\bMacQuarie/Macquarie/go ;\n s/\\bMacOmber/Macomber/go ;\n s/\\bMacIn/Macin/go ;\n s/\\bMacKintosh/Mackintosh/go ;\n s/\\bMacKen/Macken/go ;\n s/\\bMacHen/Machen/go ;\n s/\\bMacisaac/MacIsaac/go ;\n s/\\bMacHiel/Machiel/go ;\n s/\\bMacIol/Maciol/go ;\n s/\\bMacKell/Mackell/go ;\n s/\\bMacKlem/Macklem/go ;\n s/\\bMacKrell/Mackrell/go ;\n s/\\bMacLin/Maclin/go ;\n s/\\bMacKey/Mackey/go ;\n s/\\bMacKley/Mackley/go ;\n s/\\bMacHell/Machell/go ;\n s/\\bMacHon/Machon/go ;\n }\n s/Macmurdo/MacMurdo/go ;\n\n # Fixes for \"son (daughter) of\" etc. in various languages.\n s{ \\b Al(?=\\s+\\w) }{al}gox ; # al Arabic or forename Al.\n s{ \\b Ap \\b }{ap}gox ; # ap Welsh.\n s{ \\b Ben(?=\\s+\\w) }{ben}gox ; # ben Hebrew or forename Ben.\n s{ \\b Dell([ae])\\b }{dell$1}gox ; # della and delle Italian.\n s{ \\b D([aeiu]) \\b }{d$1}gox ; # da, de, di Italian; du French.\n s{ \\b De([lr]) \\b }{de$1}gox ; # del Italian; der Dutch/Flemish.\n s{ \\b El \\b }{el}gox unless $SPANISH ; # el Greek or El Spanish.\n s{ \\b La \\b }{la}gox unless $SPANISH ; # la French or La Spanish.\n s{ \\b L([eo]) \\b }{l$1}gox ; # lo Italian; le French.\n s{ \\b Van(?=\\s+\\w) }{van}gox ; # van German or forename Van.\n s{ \\b Von \\b }{von}gox ; # von Dutch/Flemish\n\n # Fixes for roman numeral names, e.g. Henry VIII, up to 89, LXXXIX\n s{ \\b ( (?: [Xx]{1,3} | [Xx][Ll] | [Ll][Xx]{0,3} )?\n (?: [Ii]{1,3} | [Ii][VvXx] | [Vv][Ii]{0,3} )? ) \\b }{\\U$1}gox ;\n\n $_ ;\n}\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/262775/" ]
I'm looking for a good JavaScript RegEx to convert names to proper cases. For example: ``` John SMITH = John Smith Mary O'SMITH = Mary O'Smith E.t MCHYPHEN-SMITH = E.T McHyphen-Smith John Middlename SMITH = John Middlename SMITH ``` Well you get the idea. Anyone come up with a comprehensive solution?
Something like this? ``` function fix_name(name) { var replacer = function (whole,prefix,word) { ret = []; if (prefix) { ret.push(prefix.charAt(0).toUpperCase()); ret.push(prefix.substr(1).toLowerCase()); } ret.push(word.charAt(0).toUpperCase()); ret.push(word.substr(1).toLowerCase()); return ret.join(''); } var pattern = /\b(ma?c)?([a-z]+)/ig; return name.replace(pattern, replacer); } ```
250,700
<p>I'm trying to write a python script that packages our software. This script needs to build our product, and package it. Currently we have other scripts that do each piece individually which include csh, and perl scripts. One such script is run like:</p> <pre><code>sudo mod args </code></pre> <p>where mod is a perl script; so in python I would do </p> <pre><code>proc = Popen(['sudo', 'mod', '-p', '-c', 'noresource', '-u', 'dtt', '-Q'], stderr=PIPE, stdout=PIPE, stdin=PIPE) </code></pre> <p>The problem is that this mod script needs a few questions answered. For this I thought that the traditional </p> <pre><code>(stdout, stderr) = proc.communicate(input='y') </code></pre> <p>would work. I don't think it's working because the process that Popen is controlling is sudo, not the mod script that is asking the question. Is there any way to communicate with the mod script and still run it through sudo?</p>
[ { "answer_id": 250804, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 1, "selected": false, "text": "<p>The simplest thing to do would be the run the controlling script (the Python script) via <code>sudo</code>. Are you able to do that, or is that not an option?</p>\n" }, { "answer_id": 250819, "author": "Rômulo Ceccon", "author_id": 23193, "author_profile": "https://Stackoverflow.com/users/23193", "pm_score": 2, "selected": false, "text": "<p>I think you should remove the <code>sudo</code> in your <code>Popen</code> call and require the user of <em>your</em> script to type <code>sudo</code>.</p>\n\n<p>This additionally makes more explicit the need for elevated privileges in your script, instead of hiding it inside <code>Popen</code>.</p>\n" }, { "answer_id": 251052, "author": "Ali Afshar", "author_id": 28380, "author_profile": "https://Stackoverflow.com/users/28380", "pm_score": 0, "selected": false, "text": "<p>We need more information.</p>\n\n<ol>\n<li>Is sudo asking you for a password?</li>\n<li>What kind of interface does the mod script have for asking questions?</li>\n</ol>\n\n<p>Because these kind of things are not handled as normal over the pipe.</p>\n\n<p>A solution for both of these might be <a href=\"http://www.noah.org/wiki/Pexpect\" rel=\"nofollow noreferrer\">Pexpect</a>, which is rather expert at handling funny scripts that ask for passwords, and various other input issues.</p>\n" }, { "answer_id": 252100, "author": "miya", "author_id": 293, "author_profile": "https://Stackoverflow.com/users/293", "pm_score": 3, "selected": true, "text": "<p>I would choose to go with Pexpect. </p>\n\n<pre><code>import pexpect\nchild = pexpect.spawn ('sudo mod -p -c noresource -u dtt -Q')\nchild.expect ('First question:')\nchild.sendline ('Y')\nchild.expect ('Second question:')\nchild.sendline ('Yup')\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7949/" ]
I'm trying to write a python script that packages our software. This script needs to build our product, and package it. Currently we have other scripts that do each piece individually which include csh, and perl scripts. One such script is run like: ``` sudo mod args ``` where mod is a perl script; so in python I would do ``` proc = Popen(['sudo', 'mod', '-p', '-c', 'noresource', '-u', 'dtt', '-Q'], stderr=PIPE, stdout=PIPE, stdin=PIPE) ``` The problem is that this mod script needs a few questions answered. For this I thought that the traditional ``` (stdout, stderr) = proc.communicate(input='y') ``` would work. I don't think it's working because the process that Popen is controlling is sudo, not the mod script that is asking the question. Is there any way to communicate with the mod script and still run it through sudo?
I would choose to go with Pexpect. ``` import pexpect child = pexpect.spawn ('sudo mod -p -c noresource -u dtt -Q') child.expect ('First question:') child.sendline ('Y') child.expect ('Second question:') child.sendline ('Yup') ```
250,713
<p>Why would a stored procedure that returns a table with 9 columns, 89 rows using this code take 60 seconds to execute (.NET 1.1) when it takes &lt; 1 second to run in SQL Server Management Studio? It's being run on the local machine so little/no network latency, fast dev machine</p> <pre><code>Dim command As SqlCommand = New SqlCommand(procName, CreateConnection()) command.CommandType = CommandType.StoredProcedure command.CommandTimeout = _commandTimeOut Try Dim adapter As new SqlDataAdapter(command) Dim i as Integer For i=0 to parameters.Length-1 command.Parameters.Add(parameters(i)) Next adapter.Fill(tableToFill) adapter.Dispose() Finally command.Dispose() End Try </code></pre> <p>my paramter array is typed (for this SQL it's only a single parameter)</p> <pre><code>parameters(0) = New SqlParameter("@UserID", SqlDbType.BigInt, 0, ParameterDirection.Input, True, 19, 0, "", DataRowVersion.Current, userID) </code></pre> <p>The Stored procedure is only a select statement like so:</p> <pre><code>ALTER PROC [dbo].[web_GetMyStuffFool] (@UserID BIGINT) AS SELECT Col1, Col2, Col3, Col3, Col3, Col3, Col3, Col3, Col3 FROM [Table] </code></pre>
[ { "answer_id": 250734, "author": "Marcus King", "author_id": 19840, "author_profile": "https://Stackoverflow.com/users/19840", "pm_score": 1, "selected": false, "text": "<p>Why not make it a DataReader instead of DataAdapter, it looks like you have a singel result set and if you aren't going to be pushing changes back in the DB and don't need constraints applied in .NET code you shouldn't use the Adapter.</p>\n\n<p>EDIT:</p>\n\n<p>If you need it to be a DataTable you can still pull the data from the DB via a DataReader and then in .NET code use the DataReader to populate a DataTable. That should still be faster than relying on the DataSet and DataAdapter</p>\n" }, { "answer_id": 250765, "author": "fuzzbone", "author_id": 5027, "author_profile": "https://Stackoverflow.com/users/5027", "pm_score": 0, "selected": false, "text": "<p>I don't know \"Why\" it's so slow per se - but as Marcus is pointing out - comparing Mgmt Studio to filling a dataset is apples to oranges. Datasets contain a LOT of overhead. I hate them and NEVER use them if I can help it.</p>\n\n<p>You may be having issues with mismatches of old versions of the SQL stack or some such (esp given you are obviously stuck in .NET 1.1 as well) The Framework is likely trying to do database equivilant of \"Reflection\" to infer schema etc etc etc</p>\n\n<p>One thing to consider try with your unfortunate constraint is to access the database with a datareader and build your own dataset in code. You should be able to find samples easily via google.</p>\n" }, { "answer_id": 250961, "author": "HTTP 410", "author_id": 13118, "author_profile": "https://Stackoverflow.com/users/13118", "pm_score": 7, "selected": true, "text": "<p>First, make sure you are profiling the performance properly. For example, run the query twice from ADO.NET and see if the second time is much faster than the first time. This removes the overhead of waiting for the app to compile and the debugging infrastructure to ramp up.</p>\n<p>Next, check the default settings in ADO.NET and SSMS. For example, if you run <code>SET ARITHABORT OFF</code> in SSMS, you might find that it now runs as slow as when using ADO.NET.</p>\n<p>What I found once was that <code>SET ARITHABORT OFF</code> in SSMS caused the stored proc to be recompiled and/or different statistics to be used. And suddenly both SSMS and ADO.NET were reporting roughly the same execution time. Note that <code>ARITHABORT</code> is not <em>itself</em> the cause of the slowdown, it's that it causes a recompilation, and you are ending up with two different plans <a href=\"http://www.sommarskog.se/query-plan-mysteries.html\" rel=\"nofollow noreferrer\">due to parameter sniffing</a>. It is likely that parameter sniffing is the actual problem needing to be solved.</p>\n<p>To check this, look at the execution plans for each run, specifically the <code>sys.dm_exec_cached_plans</code> table. They will probably be different.</p>\n<p>Running 'sp_recompile' on a specific stored procedure will drop the associated execution plan from the cache, which then gives SQL Server a chance to create a possibly more appropriate plan at the next execution of the procedure.</p>\n<p>Finally, you can try the &quot;<a href=\"http://knowyourmeme.com/memes/nuke-it-from-orbit\" rel=\"nofollow noreferrer\">nuke it from orbit</a>&quot; approach of cleaning out the entire procedure cache and memory buffers using SSMS:</p>\n<pre><code>DBCC DROPCLEANBUFFERS\nDBCC FREEPROCCACHE\n</code></pre>\n<p>Doing so before you test your query prevents usage of cached execution plans and previous results cache.</p>\n" }, { "answer_id": 492868, "author": "Steve Wright", "author_id": 3256, "author_profile": "https://Stackoverflow.com/users/3256", "pm_score": 3, "selected": false, "text": "<p>Here is what I ended up doing: </p>\n\n<p>I executed the following SQL statement to rebuild the indexes on all tables in the database:</p>\n\n<pre><code>EXEC &lt;databasename&gt;..sp_MSforeachtable @command1='DBCC DBREINDEX (''*'')', @replacechar='*'\n-- Replace &lt;databasename&gt; with the name of your database\n</code></pre>\n\n<p>If I wanted to see the same behavior in SSMS, I ran the proc like this:</p>\n\n<pre><code>SET ARITHABORT OFF\nEXEC [dbo].[web_GetMyStuffFool] @UserID=1\nSET ARITHABORT ON\n</code></pre>\n\n<p>Another way to bypass this is to add this to your code:</p>\n\n<pre><code>MyConnection.Execute \"SET ARITHABORT ON\"\n</code></pre>\n" }, { "answer_id": 33570461, "author": "user5534139", "author_id": 5534139, "author_profile": "https://Stackoverflow.com/users/5534139", "pm_score": 2, "selected": false, "text": "<p>I ran into the same issue, but when I've rebuilt indexes on SQL table, it worked fine, so you might want to consider rebuilding index on sql server side</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3256/" ]
Why would a stored procedure that returns a table with 9 columns, 89 rows using this code take 60 seconds to execute (.NET 1.1) when it takes < 1 second to run in SQL Server Management Studio? It's being run on the local machine so little/no network latency, fast dev machine ``` Dim command As SqlCommand = New SqlCommand(procName, CreateConnection()) command.CommandType = CommandType.StoredProcedure command.CommandTimeout = _commandTimeOut Try Dim adapter As new SqlDataAdapter(command) Dim i as Integer For i=0 to parameters.Length-1 command.Parameters.Add(parameters(i)) Next adapter.Fill(tableToFill) adapter.Dispose() Finally command.Dispose() End Try ``` my paramter array is typed (for this SQL it's only a single parameter) ``` parameters(0) = New SqlParameter("@UserID", SqlDbType.BigInt, 0, ParameterDirection.Input, True, 19, 0, "", DataRowVersion.Current, userID) ``` The Stored procedure is only a select statement like so: ``` ALTER PROC [dbo].[web_GetMyStuffFool] (@UserID BIGINT) AS SELECT Col1, Col2, Col3, Col3, Col3, Col3, Col3, Col3, Col3 FROM [Table] ```
First, make sure you are profiling the performance properly. For example, run the query twice from ADO.NET and see if the second time is much faster than the first time. This removes the overhead of waiting for the app to compile and the debugging infrastructure to ramp up. Next, check the default settings in ADO.NET and SSMS. For example, if you run `SET ARITHABORT OFF` in SSMS, you might find that it now runs as slow as when using ADO.NET. What I found once was that `SET ARITHABORT OFF` in SSMS caused the stored proc to be recompiled and/or different statistics to be used. And suddenly both SSMS and ADO.NET were reporting roughly the same execution time. Note that `ARITHABORT` is not *itself* the cause of the slowdown, it's that it causes a recompilation, and you are ending up with two different plans [due to parameter sniffing](http://www.sommarskog.se/query-plan-mysteries.html). It is likely that parameter sniffing is the actual problem needing to be solved. To check this, look at the execution plans for each run, specifically the `sys.dm_exec_cached_plans` table. They will probably be different. Running 'sp\_recompile' on a specific stored procedure will drop the associated execution plan from the cache, which then gives SQL Server a chance to create a possibly more appropriate plan at the next execution of the procedure. Finally, you can try the "[nuke it from orbit](http://knowyourmeme.com/memes/nuke-it-from-orbit)" approach of cleaning out the entire procedure cache and memory buffers using SSMS: ``` DBCC DROPCLEANBUFFERS DBCC FREEPROCCACHE ``` Doing so before you test your query prevents usage of cached execution plans and previous results cache.
250,717
<p>I'm trying to write a log parsing script to extract failed events. I can pull these with grep:</p> <pre><code>$ grep -A5 "FAILED" log.txt 2008-08-19 17:50:07 [7052] [14] DEBUG: data: 3a 46 41 49 4c 45 44 20 20 65 72 72 3a 30 32 33 :FAILED err:023 2008-08-19 17:50:07 [7052] [14] DEBUG: data: 20 74 65 78 74 3a 20 00 text: . 2008-08-19 17:50:07 [7052] [14] DEBUG: Octet string dump ends. 2008-08-19 17:50:07 [7052] [14] DEBUG: SMPP PDU dump ends. 2008-08-19 17:50:07 [7052] [14] DEBUG: SMPP[test] handle_pdu, got DLR 2008-08-19 17:50:07 [7052] [14] DEBUG: DLR[internal]: Looking for DLR smsc=test, ts=1158667543, dst=447872123456, type=2 -- 2008-08-19 17:50:07 [7052] [8] DEBUG: data: 3a 46 41 49 4c 45 44 20 20 65 72 72 3a 30 32 34 :FAILED err:024 2008-08-19 17:50:07 [7052] [8] DEBUG: data: 20 74 65 78 74 3a 20 00 text: . 2008-08-19 17:50:07 [7052] [8] DEBUG: Octet string dump ends. 2008-08-19 17:50:07 [7052] [8] DEBUG: SMPP PDU dump ends. 2008-08-19 17:50:07 [7052] [8] DEBUG: SMPP[test] handle_pdu, got DLR 2008-08-19 17:50:07 [7052] [8] DEBUG: DLR[internal]: Looking for DLR smsc=test, ts=1040097716, dst=447872987654, type=2 </code></pre> <p>What I'm interested in is, for each block, the error code (i.e. the "023" part of ":FAILED err:023" on the first line) and the dst number (i.e."447872123456" from "dst=447872123456" on the last line.)</p> <p>Can anyone help with a shell one-liner to extract those two values, or provide some hints as to how I should approach this?</p>
[ { "answer_id": 250761, "author": "Michael Gundlach", "author_id": 4105, "author_profile": "https://Stackoverflow.com/users/4105", "pm_score": 3, "selected": true, "text": "<pre><code>grep -A 5 FAILED log.txt | \\ # Get FAILED and dst and other lines\n egrep '(FAILED|dst=)' | \\ # Just the FAILED/dst lines\n egrep -o \"err:[0-9]*|dst=[0-9]*\" | \\ # Just the err: and dst= phrases\n cut -d':' -f 2 | \\ # Strip \"err:\" from err: lines\n cut -d '=' -f 2 | \\ # Strip \"dst=\" from dst= lines\n xargs -n 2 # Combine pairs of numbers\n\n023 447872123456\n024 447872987654\n</code></pre>\n\n<p>As with all shell \"one\"-liners, there is almost certainly a more elegant way to do this. However, I find the iterative approach very successful for getting what I want: start with too much information (your grep), then narrow down the lines I want (with grep), then snip out the parts of each line that I want (with cut).</p>\n\n<p>While using the linux toolbox takes more lines, you only have to know the basics of a few commands to do just about anything you want. An alternative is to use awk, python, or other scripting languages, which require more specialized programming knowledge but will take less screen space.</p>\n" }, { "answer_id": 250770, "author": "bltxd", "author_id": 11892, "author_profile": "https://Stackoverflow.com/users/11892", "pm_score": 0, "selected": false, "text": "<p>A simple solution in Ruby, here is <code>filter.rb</code>:</p>\n\n<pre><code>#! /usr/bin/env ruby\nFile.read(ARGV.first).scan(/:FAILED\\s+err:(\\d+).*?, dst=(\\d+),/m).each do |err, dst|\n puts \"#{err} #{dst}\"\nend\n</code></pre>\n\n<p>Run it with:</p>\n\n<pre><code>ruby filter.rb my_log_file.txt\n</code></pre>\n\n<p>And you get:</p>\n\n<pre><code>023 447872123456\n024 447872987654\n</code></pre>\n" }, { "answer_id": 266152, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If there is always the same number of fields you could just </p>\n\n<pre><code>grep -A5 \"FAILED\" log.txt | awk '$24~/err/ {print $24} $12~/dst/{print $12}' error.txt\n\nerr:023\ndst=447872123456,\nerr:024\ndst=447872987654,\n</code></pre>\n\n<p>And depending on how the rest of the file looks you might be able to skip the grep all togther.</p>\n\n<p>The \"<em>$24~/err/ {print $24}</em>\" part tells awk to print field number 24 if it contains err, ~/XXX/ where XXX is a regular expression.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm trying to write a log parsing script to extract failed events. I can pull these with grep: ``` $ grep -A5 "FAILED" log.txt 2008-08-19 17:50:07 [7052] [14] DEBUG: data: 3a 46 41 49 4c 45 44 20 20 65 72 72 3a 30 32 33 :FAILED err:023 2008-08-19 17:50:07 [7052] [14] DEBUG: data: 20 74 65 78 74 3a 20 00 text: . 2008-08-19 17:50:07 [7052] [14] DEBUG: Octet string dump ends. 2008-08-19 17:50:07 [7052] [14] DEBUG: SMPP PDU dump ends. 2008-08-19 17:50:07 [7052] [14] DEBUG: SMPP[test] handle_pdu, got DLR 2008-08-19 17:50:07 [7052] [14] DEBUG: DLR[internal]: Looking for DLR smsc=test, ts=1158667543, dst=447872123456, type=2 -- 2008-08-19 17:50:07 [7052] [8] DEBUG: data: 3a 46 41 49 4c 45 44 20 20 65 72 72 3a 30 32 34 :FAILED err:024 2008-08-19 17:50:07 [7052] [8] DEBUG: data: 20 74 65 78 74 3a 20 00 text: . 2008-08-19 17:50:07 [7052] [8] DEBUG: Octet string dump ends. 2008-08-19 17:50:07 [7052] [8] DEBUG: SMPP PDU dump ends. 2008-08-19 17:50:07 [7052] [8] DEBUG: SMPP[test] handle_pdu, got DLR 2008-08-19 17:50:07 [7052] [8] DEBUG: DLR[internal]: Looking for DLR smsc=test, ts=1040097716, dst=447872987654, type=2 ``` What I'm interested in is, for each block, the error code (i.e. the "023" part of ":FAILED err:023" on the first line) and the dst number (i.e."447872123456" from "dst=447872123456" on the last line.) Can anyone help with a shell one-liner to extract those two values, or provide some hints as to how I should approach this?
``` grep -A 5 FAILED log.txt | \ # Get FAILED and dst and other lines egrep '(FAILED|dst=)' | \ # Just the FAILED/dst lines egrep -o "err:[0-9]*|dst=[0-9]*" | \ # Just the err: and dst= phrases cut -d':' -f 2 | \ # Strip "err:" from err: lines cut -d '=' -f 2 | \ # Strip "dst=" from dst= lines xargs -n 2 # Combine pairs of numbers 023 447872123456 024 447872987654 ``` As with all shell "one"-liners, there is almost certainly a more elegant way to do this. However, I find the iterative approach very successful for getting what I want: start with too much information (your grep), then narrow down the lines I want (with grep), then snip out the parts of each line that I want (with cut). While using the linux toolbox takes more lines, you only have to know the basics of a few commands to do just about anything you want. An alternative is to use awk, python, or other scripting languages, which require more specialized programming knowledge but will take less screen space.
250,718
<p>If I grant execute permissions to a role via</p> <pre><code>GRANT EXECUTE ON [DBO].[MYPROC] TO MY_ROLE </code></pre> <p>what's the equivalent syntax to remove them?</p>
[ { "answer_id": 250723, "author": "mathieu", "author_id": 971, "author_profile": "https://Stackoverflow.com/users/971", "pm_score": 5, "selected": true, "text": "<p>REVOKE EXECUTE ON [DBO].[MYPROC] TO MY_ROLE</p>\n" }, { "answer_id": 250724, "author": "Godeke", "author_id": 28006, "author_profile": "https://Stackoverflow.com/users/28006", "pm_score": 4, "selected": false, "text": "<pre><code>DENY EXECUTE ON [DBO].[MYPROC] TO MY_ROLE\n</code></pre>\n\n<p>or</p>\n\n<pre><code>REVOKE EXECUTE ON [DBO].[MYPROC] TO MY_ROLE\n</code></pre>\n\n<p>depending on your goal. The first acts as a filter for any granted permissions, the second removes an explict permission.</p>\n" }, { "answer_id": 250726, "author": "Marcus King", "author_id": 19840, "author_profile": "https://Stackoverflow.com/users/19840", "pm_score": 1, "selected": false, "text": "<pre><code>DENY EXECUTE ON [DBO].[MYPROC] TO MY_ROLE\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4540/" ]
If I grant execute permissions to a role via ``` GRANT EXECUTE ON [DBO].[MYPROC] TO MY_ROLE ``` what's the equivalent syntax to remove them?
REVOKE EXECUTE ON [DBO].[MYPROC] TO MY\_ROLE
250,755
<p>I'm trying to export a Crystal Report to an HTML file, but when I call the Export method, I immediately get this error:</p> <blockquote> <p><strong>Source</strong>: Crystal Reports ActiveX Designer </p> <p><strong>Description</strong>: Failed to export the report.</p> </blockquote> <p>I have tried both crEFTHTML40 and crEFTHTML32Standard as export format types - and both result in the same error.</p> <p>Here is a highly simplified version of what I'm doing:</p> <pre><code>Dim objCRReport As CRAXDRT.Report [...] objCRReport.ExportOptions.FormatType = 32 'crEFTHTML40 objCRReport.ExportOptions.DestinationType = 1 'crEDTDiskFile objCRReport.ExportOptions.DiskFileName = "C:\reportInHtmlFormat.html" objCRReport.Export False '&lt;--- "Failed to export the report" error here </code></pre> <p>Please note that I am referencing the "Crystal Reports 9 ActiveX Designer Runtime Library" specifically.</p>
[ { "answer_id": 269715, "author": "user35193", "author_id": 35193, "author_profile": "https://Stackoverflow.com/users/35193", "pm_score": 2, "selected": true, "text": "<p>I'm not sure what you have in the <code>[...]</code> section but your code should include a call to open the report with an instance of the CRAXDRT Application.</p>\n\n<pre><code>Dim objCRReport As CRAXDRT.Report\n\n'***********************************\nDim objCRApp As New CRAXDRT.Application\n\nobjCRReport = objCRApp.OpenReport(\"&lt;YOUR REPORT FILENAME&gt;\", 1)\n'***********************************\n\n[...]\nobjCRReport.ExportOptions.FormatType = 32 'crEFTHTML40\nobjCRReport.ExportOptions.DestinationType = 1 'crEDTDiskFile\nobjCRReport.ExportOptions.DiskFileName = \"C:\\reportInHtmlFormat.html\"\nobjCRReport.Export False '&lt;--- \"Failed to export the report\" error here\n</code></pre>\n" }, { "answer_id": 2149646, "author": "ANeto", "author_id": 260378, "author_profile": "https://Stackoverflow.com/users/260378", "pm_score": 0, "selected": false, "text": "<p>Try setting the <code>HTMLFileName</code> option instead:</p>\n\n<pre><code>objCRReport.ExportOptions.HTMLFileName = \"C:\\reportInHtmlFormat.html\"\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21263/" ]
I'm trying to export a Crystal Report to an HTML file, but when I call the Export method, I immediately get this error: > > **Source**: Crystal Reports ActiveX Designer > > > **Description**: Failed to export the report. > > > I have tried both crEFTHTML40 and crEFTHTML32Standard as export format types - and both result in the same error. Here is a highly simplified version of what I'm doing: ``` Dim objCRReport As CRAXDRT.Report [...] objCRReport.ExportOptions.FormatType = 32 'crEFTHTML40 objCRReport.ExportOptions.DestinationType = 1 'crEDTDiskFile objCRReport.ExportOptions.DiskFileName = "C:\reportInHtmlFormat.html" objCRReport.Export False '<--- "Failed to export the report" error here ``` Please note that I am referencing the "Crystal Reports 9 ActiveX Designer Runtime Library" specifically.
I'm not sure what you have in the `[...]` section but your code should include a call to open the report with an instance of the CRAXDRT Application. ``` Dim objCRReport As CRAXDRT.Report '*********************************** Dim objCRApp As New CRAXDRT.Application objCRReport = objCRApp.OpenReport("<YOUR REPORT FILENAME>", 1) '*********************************** [...] objCRReport.ExportOptions.FormatType = 32 'crEFTHTML40 objCRReport.ExportOptions.DestinationType = 1 'crEDTDiskFile objCRReport.ExportOptions.DiskFileName = "C:\reportInHtmlFormat.html" objCRReport.Export False '<--- "Failed to export the report" error here ```
250,757
<p>I'm writing an application using Qt4.</p> <p>I need to download a very short text file from a given http address.</p> <p>The file is short and is needed for my app to be able to continue, so I would like to make sure the download is blocking (or will timeout after a few seconds if the file in not found/not available).</p> <p>I wanted to use QHttp::get(), but this is a non-blocking method.</p> <p>I thought I could use a thread : my app would start it, and wait for it to finish. The thread would handle the download and quit when the file is downloaded or after a timeout.</p> <p>But I cannot make it work :</p> <pre><code>class JSHttpGetterThread : public QThread { Q_OBJECT public: JSHttpGetterThread(QObject* pParent = NULL); ~JSHttpGetterThread(); virtual void run() { m_pHttp = new QHttp(this); connect(m_pHttp, SIGNAL(requestFinished(int, bool)), this, SLOT(onRequestFinished(int, bool))); m_pHttp-&gt;setHost("127.0.0.1"); m_pHttp-&gt;get("Foo.txt", &amp;m_GetBuffer); exec(); } const QString&amp; getDownloadedFileContent() const { return m_DownloadedFileContent; } private: QHttp* m_pHttp; QBuffer m_GetBuffer; QString m_DownloadedFileContent; private slots: void onRequestFinished(int Id, bool Error) { m_DownloadedFileContent = ""; m_DownloadedFileContent.append(m_GetBuffer.buffer()); } }; </code></pre> <p>In the method creating the thread to initiate the download, here is what I'm doing :</p> <pre><code>JSHttpGetterThread* pGetter = new JSHttpGetterThread(this); pGetter-&gt;start(); pGetter-&gt;wait(); </code></pre> <p>But that doesn't work and my app keeps waiting. It looks lit the slot 'onRequestFinished' is never called.</p> <p>Any idea ?</p> <p>Is there a better way to do what I'm trying to do ?</p>
[ { "answer_id": 250950, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>you have to call <code>QThread::quit()</code> or <code>exit()</code> if you are done - otherwise your thread will run forever...</p>\n" }, { "answer_id": 251631, "author": "Dusty Campbell", "author_id": 2174, "author_profile": "https://Stackoverflow.com/users/2174", "pm_score": -1, "selected": false, "text": "<p>How about giving the GUI some amount of time to wait on the thread and then give up.</p>\n\n<p>Something like:</p>\n\n<pre><code>JSHttpGetterThread* pGetter = new JSHttpGetterThread(this);\npGetter-&gt;start();\npGetter-&gt;wait(10000); //give the thread 10 seconds to download\n</code></pre>\n\n<p>Or...</p>\n\n<p>Why does the GUI thread have to wait for the \"downloader thread\" at all? When the app fires up create the downloader thread, connect the finished() signal to some other object, start the downloader thread, and return. When the thread has finished, it will signal the other object which can resume your process.</p>\n" }, { "answer_id": 252821, "author": "David Dibben", "author_id": 5022, "author_profile": "https://Stackoverflow.com/users/5022", "pm_score": 4, "selected": true, "text": "<p>Instead of using a thread you can just go into a loop which calls <code>processEvents</code>:</p>\n\n<pre><code>while (notFinished) {\n qApp-&gt;processEvents(QEventLoop::WaitForMore | QEventLoop::ExcludeUserInput);\n}\n</code></pre>\n\n<p>Where <code>notFinished</code> is a flag which can be set from the <code>onRequestFinished</code> slot.</p>\n\n<p>The <code>ExcludeUserInput</code> will ensure that GUI related events are ignored while waiting. </p>\n" }, { "answer_id": 258496, "author": "Jérôme", "author_id": 2796, "author_profile": "https://Stackoverflow.com/users/2796", "pm_score": 1, "selected": false, "text": "<p>I chose to implement David's solution, which seemed to be the easiest.</p>\n\n<p>However, I had handle a few more things :</p>\n\n<ul>\n<li>I had to adapt the QEventLoop enum values for Qt4.3.3 (the version I'm using);</li>\n<li>I had to track the request Id, to make sure to exit the while loop when the download request is finished, and not when another request is finished;</li>\n<li>I added a timeout, to make sure to exit the while loop if there is any problem.</li>\n</ul>\n\n<p>Here is the result as (more or less) pseudo-code :</p>\n\n<pre><code>class BlockingDownloader : public QObject\n{\n Q_OBJECT\npublic:\n BlockingDownloaderBlockingDownloader()\n {\n m_pHttp = new QHttp(this);\n connect(m_pHttp, SIGNAL(requestFinished(int, bool)), this, SLOT(onRequestFinished(int, bool)));\n }\n\n ~BlockingDownloader()\n {\n delete m_pHttp;\n }\n\n QString getFileContent()\n {\n m_pHttp-&gt;setHost(\"www.xxx.com\");\n m_DownloadId = m_pHttp-&gt;get(\"/myfile.txt\", &amp;m_GetBuffer);\n\n QTimer::singleShot(m_TimeOutTime, this, SLOT(onTimeOut()));\n while (!m_FileIsDownloaded)\n {\n qApp-&gt;processEvents(QEventLoop::WaitForMoreEvents | QEventLoop::ExcludeUserInputEvents);\n }\n return m_DownloadedFileContent;\n }\n\nprivate slots:\n void BlockingDownloader::onRequestFinished(int Id, bool Error)\n {\n if (Id == m_DownloadId)\n {\n m_DownloadedFileContent = \"\";\n m_DownloadedFileContent.append(m_GetBuffer.buffer());\n m_FileIsDownloaded = true;\n }\n }\n\n void BlockingDownloader::onTimeOut()\n {\n m_FileIsDownloaded = true;\n }\n\nprivate:\n QHttp* m_pHttp;\n bool m_FileIsDownloaded;\n QBuffer m_GetBuffer;\n QString m_DownloadedFileContent;\n int m_DownloadId;\n};\n</code></pre>\n" }, { "answer_id": 265526, "author": "Phil Hannent", "author_id": 24459, "author_profile": "https://Stackoverflow.com/users/24459", "pm_score": 3, "selected": false, "text": "<p>A little late but:\nDo not use these wait loops, the correct way is to use the done() signal from QHttp.</p>\n\n<p>The requestFinished signal from what I have seen is just for when your application has finished the request, the data may still be on its way down.</p>\n\n<p>You do not need a new thread, just setup the qhttp:</p>\n\n<pre><code>httpGetFile= new QHttp();\nconnect(httpGetFile, SIGNAL(done(bool)), this, SLOT(processHttpGetFile(bool)));\n</code></pre>\n\n<p>Also do not forget to flush the file in processHttpGetFile as it might not all be on the disk.</p>\n" }, { "answer_id": 26377678, "author": "myd0", "author_id": 1923256, "author_profile": "https://Stackoverflow.com/users/1923256", "pm_score": 0, "selected": false, "text": "<p>I used QNetworkAccsessManager for same necessity. Because this class managing connections RFC base (6 proccess same time) and non-blocking.</p>\n\n<p><a href=\"http://qt-project.org/doc/qt-4.8/qnetworkaccessmanager.html\" rel=\"nofollow\">http://qt-project.org/doc/qt-4.8/qnetworkaccessmanager.html</a></p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2796/" ]
I'm writing an application using Qt4. I need to download a very short text file from a given http address. The file is short and is needed for my app to be able to continue, so I would like to make sure the download is blocking (or will timeout after a few seconds if the file in not found/not available). I wanted to use QHttp::get(), but this is a non-blocking method. I thought I could use a thread : my app would start it, and wait for it to finish. The thread would handle the download and quit when the file is downloaded or after a timeout. But I cannot make it work : ``` class JSHttpGetterThread : public QThread { Q_OBJECT public: JSHttpGetterThread(QObject* pParent = NULL); ~JSHttpGetterThread(); virtual void run() { m_pHttp = new QHttp(this); connect(m_pHttp, SIGNAL(requestFinished(int, bool)), this, SLOT(onRequestFinished(int, bool))); m_pHttp->setHost("127.0.0.1"); m_pHttp->get("Foo.txt", &m_GetBuffer); exec(); } const QString& getDownloadedFileContent() const { return m_DownloadedFileContent; } private: QHttp* m_pHttp; QBuffer m_GetBuffer; QString m_DownloadedFileContent; private slots: void onRequestFinished(int Id, bool Error) { m_DownloadedFileContent = ""; m_DownloadedFileContent.append(m_GetBuffer.buffer()); } }; ``` In the method creating the thread to initiate the download, here is what I'm doing : ``` JSHttpGetterThread* pGetter = new JSHttpGetterThread(this); pGetter->start(); pGetter->wait(); ``` But that doesn't work and my app keeps waiting. It looks lit the slot 'onRequestFinished' is never called. Any idea ? Is there a better way to do what I'm trying to do ?
Instead of using a thread you can just go into a loop which calls `processEvents`: ``` while (notFinished) { qApp->processEvents(QEventLoop::WaitForMore | QEventLoop::ExcludeUserInput); } ``` Where `notFinished` is a flag which can be set from the `onRequestFinished` slot. The `ExcludeUserInput` will ensure that GUI related events are ignored while waiting.
250,789
<p>I have a CSV data file with rows that may have lots of columns 500+ and some with a lot less. I need to transpose it so that each row becomes a column in the output file. The problem is that the rows in the original file may not all have the same number of columns so when I try the transpose method of array I get:</p> <blockquote> <p>`transpose': element size differs (12 should be 5) (IndexError)</p> </blockquote> <p>Is there an alternative to transpose that works with uneven array length?</p>
[ { "answer_id": 250926, "author": "bltxd", "author_id": 11892, "author_profile": "https://Stackoverflow.com/users/11892", "pm_score": 4, "selected": true, "text": "<p>I would insert nulls to fill the holes in your matrix, something such as:</p>\n\n<pre><code>a = [[1, 2, 3], [3, 4]]\n\n# This would throw the error you're talking about\n# a.transpose\n\n# Largest row\nsize = a.max { |r1, r2| r1.size &lt;=&gt; r2.size }.size\n\n# Enlarge matrix inserting nils as needed\na.each { |r| r[size - 1] ||= nil }\n\n# So now a == [[1, 2, 3], [3, 4, nil]]\naa = a.transpose\n\n# aa == [[1, 3], [2, 4], [3, nil]]\n</code></pre>\n" }, { "answer_id": 4526254, "author": "Vlad Alive", "author_id": 345182, "author_profile": "https://Stackoverflow.com/users/345182", "pm_score": 2, "selected": false, "text": "<pre><code># Intitial CSV table data\ncsv_data = [ [1,2,3,4,5], [10,20,30,40], [100,200] ]\n\n# Finding max length of rows\nrow_length = csv_data.map(&amp;:length).max\n\n# Inserting nil to the end of each row\ncsv_data.map do |row|\n (row_length - row.length).times { row.insert(-1, nil) }\nend\n\n# Let's check\ncsv_data\n# =&gt; [[1, 2, 3, 4, 5], [10, 20, 30, 40, nil], [100, 200, nil, nil, nil]]\n\n# Transposing...\ntransposed_csv_data = csv_data.transpose\n\n# Hooray!\n# =&gt; [[1, 10, 100], [2, 20, 200], [3, 30, nil], [4, 40, nil], [5, nil, nil]]\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6805/" ]
I have a CSV data file with rows that may have lots of columns 500+ and some with a lot less. I need to transpose it so that each row becomes a column in the output file. The problem is that the rows in the original file may not all have the same number of columns so when I try the transpose method of array I get: > > `transpose': element size differs (12 should be 5) (IndexError) > > > Is there an alternative to transpose that works with uneven array length?
I would insert nulls to fill the holes in your matrix, something such as: ``` a = [[1, 2, 3], [3, 4]] # This would throw the error you're talking about # a.transpose # Largest row size = a.max { |r1, r2| r1.size <=> r2.size }.size # Enlarge matrix inserting nils as needed a.each { |r| r[size - 1] ||= nil } # So now a == [[1, 2, 3], [3, 4, nil]] aa = a.transpose # aa == [[1, 3], [2, 4], [3, nil]] ```
250,790
<p>So I'm creating some HTML using javascript based on where the user clicks on the page. On page load the script replaces an empty div with a ul and some data. The user clicks on that data to receive more and so on. Now when the user navigates off the page and then hits the back button to go back to the page, IE displays a blank page with the replaced divs, in all other browsers, FF, Opera, Safari, the page either reloads to the initial ul or goes back to the last state with the dynamic data in it.</p> <p>Anyone have an idea as to what might be happening here? Any help is appreciated.</p>
[ { "answer_id": 250926, "author": "bltxd", "author_id": 11892, "author_profile": "https://Stackoverflow.com/users/11892", "pm_score": 4, "selected": true, "text": "<p>I would insert nulls to fill the holes in your matrix, something such as:</p>\n\n<pre><code>a = [[1, 2, 3], [3, 4]]\n\n# This would throw the error you're talking about\n# a.transpose\n\n# Largest row\nsize = a.max { |r1, r2| r1.size &lt;=&gt; r2.size }.size\n\n# Enlarge matrix inserting nils as needed\na.each { |r| r[size - 1] ||= nil }\n\n# So now a == [[1, 2, 3], [3, 4, nil]]\naa = a.transpose\n\n# aa == [[1, 3], [2, 4], [3, nil]]\n</code></pre>\n" }, { "answer_id": 4526254, "author": "Vlad Alive", "author_id": 345182, "author_profile": "https://Stackoverflow.com/users/345182", "pm_score": 2, "selected": false, "text": "<pre><code># Intitial CSV table data\ncsv_data = [ [1,2,3,4,5], [10,20,30,40], [100,200] ]\n\n# Finding max length of rows\nrow_length = csv_data.map(&amp;:length).max\n\n# Inserting nil to the end of each row\ncsv_data.map do |row|\n (row_length - row.length).times { row.insert(-1, nil) }\nend\n\n# Let's check\ncsv_data\n# =&gt; [[1, 2, 3, 4, 5], [10, 20, 30, 40, nil], [100, 200, nil, nil, nil]]\n\n# Transposing...\ntransposed_csv_data = csv_data.transpose\n\n# Hooray!\n# =&gt; [[1, 10, 100], [2, 20, 200], [3, 30, nil], [4, 40, nil], [5, nil, nil]]\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
So I'm creating some HTML using javascript based on where the user clicks on the page. On page load the script replaces an empty div with a ul and some data. The user clicks on that data to receive more and so on. Now when the user navigates off the page and then hits the back button to go back to the page, IE displays a blank page with the replaced divs, in all other browsers, FF, Opera, Safari, the page either reloads to the initial ul or goes back to the last state with the dynamic data in it. Anyone have an idea as to what might be happening here? Any help is appreciated.
I would insert nulls to fill the holes in your matrix, something such as: ``` a = [[1, 2, 3], [3, 4]] # This would throw the error you're talking about # a.transpose # Largest row size = a.max { |r1, r2| r1.size <=> r2.size }.size # Enlarge matrix inserting nils as needed a.each { |r| r[size - 1] ||= nil } # So now a == [[1, 2, 3], [3, 4, nil]] aa = a.transpose # aa == [[1, 3], [2, 4], [3, nil]] ```
250,801
<p>Hi does anybody know how to initialize two list at the same time with ajax?</p> <p>This is my code</p> <pre><code>&lt;html&gt; &lt;body onload="iniciaListas()"&gt; &lt;script type="text/javascript"&gt; var xmlHttp function iniciaListas() { muestraListaPaises(); muestraListaProfesiones(); } function muestraListaProfesiones() { //Se inicializa el objeto ajax para manipular los eventos asincronos al servidor xmlHttp=GetXmlHttpObject(); if (xmlHttp==null) { alert ("Your browser does not support AJAX!"); return; } //Se obtine el id de la lista var obCon = document.getElementById("ocupacion"); //Por medio del metodo GET se llama nuestra pagina PHP xmlHttp.open("GET", "../Listas/listaProfesiones.php"); //On ready funcion es la funcion que se da cuenta cuando la pagina php acaba de hacer su proceso xmlHttp.onreadystatechange = function() { //el estado 4 indica que esta listo para procesar la instruccion if (xmlHttp.readyState == 4 &amp;&amp; xmlHttp.status == 200) { //despues que nuestro objeto ajax proceso la pagina php recupera un xml generado obXML = xmlHttp.responseXML; //despues obtine los datos contenidos en las siguites etiquetas obCod = obXML.getElementsByTagName("ID"); obDes = obXML.getElementsByTagName("NOMPROFESION"); //esta funcion devuelve en su la longitud de todos los registros obCon.length=obCod.length; //cilclo de llenado para las listas for (var i=0; i&lt;obCod.length;i++) { obCon.options[i].value=obCod[i].firstChild.nodeValue; obCon.options[i].text=obDes[i].firstChild.nodeValue; } } } //este objeto envia un nulll debido a que el metodo utilizado es get xmlHttp.send(null); } function muestraListaPaises() { //Se inicializa el objeto ajax para manipular los eventos asincronos al servidor xmlHttp=GetXmlHttpObject(); if (xmlHttp==null) { alert ("Your browser does not support AJAX!"); return; } //Se obtine el id de la lista var obCon = document.getElementById("pais"); //Por medio del metodo GET se llama nuestra pagina PHP xmlHttp.open("GET", "../Listas/listaPaises.php"); //On ready funcion es la funcion que se da cuenta cuando la pagina php acaba de hacer su proceso xmlHttp.onreadystatechange = function() { //el estado 4 indica que esta listo para procesar la instruccion if (xmlHttp.readyState == 4 &amp;&amp; xmlHttp.status == 200) { //despues que nuestro objeto ajax proceso la pagina php recupera un xml generado obXML = xmlHttp.responseXML; //despues obtine los datos contenidos en las siguites etiquetas obCod = obXML.getElementsByTagName("ID"); obDes = obXML.getElementsByTagName("NOMPAIS"); //esta funcion devuelve en su la longitud de todos los registros obCon.length=obCod.length; //cilclo de llenado para las listas for (var i=0; i&lt;obCod.length;i++) { obCon.options[i].value=obCod[i].firstChild.nodeValue; obCon.options[i].text=obDes[i].firstChild.nodeValue; } } } //este objeto envia un nulll debido a que el metodo utilizado es get xmlHttp.send(null); } function GetXmlHttpObject() { var xmlHttp=null; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } &lt;/script&gt; &lt;html&gt; &lt;body onload="iniciaListas()"&gt; &lt;script type="text/javascript" src="lists.js"&gt; &lt;/script&gt; &lt;b&gt;Country&lt;/b&gt;&lt;br&gt; &lt;select name="pais" id="pais" &gt;&lt;/select&gt; &lt;b&gt;Ocupation&lt;/b&gt;&lt;br&gt; &lt;select name="pais" id="pais" &gt;&lt;/select&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 250820, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 2, "selected": false, "text": "<p>I would recommend using a different ID for the Ocupation node, and double the adding:</p>\n\n<p>JS Snip - grab the other list, add to both:</p>\n\n<pre><code>//Se obtine el id de la lista\nvar obCon = document.getElementById(\"pais\");\nvar obOcupation = document.getElementById(\"ocupation\");\n\n...\n\nfor (var i=0; i&lt;obCod.length;i++) {\n obCon.options[i].value=obCod[i].firstChild.nodeValue;\n obCon.options[i].text=obDes[i].firstChild.nodeValue;\n obOcupation.options[i].value=obCod[i].firstChild.nodeValue;\n obOcupation.options[i].text=obDes[i].firstChild.nodeValue;\n}\n</code></pre>\n\n<p>HTML - give the second select a different name (for the server side) and id (for the javascript):</p>\n\n<pre><code>&lt;html&gt;\n&lt;body onload=\"iniciaListas()\"&gt;\n&lt;script type=\"text/javascript\" src=\"lists.js\"&gt; &lt;/script&gt;\n&lt;b&gt;Country&lt;/b&gt;&lt;br&gt;\n&lt;select name=\"pais\" id=\"pais\" &gt;&lt;/select&gt;\n\n&lt;b&gt;Ocupation&lt;/b&gt;&lt;br&gt;\n&lt;select name=\"ocupation-pais\" id=\"ocupation\" &gt;&lt;/select&gt;\n&lt;/body&gt;\n\n&lt;/html&gt;\n</code></pre>\n\n<p>Your code could be greatly simplified by using an existing JS framework, like <a href=\"http://jquery.com\" rel=\"nofollow noreferrer\">jQuery</a>...</p>\n" }, { "answer_id": 250823, "author": "stephanea", "author_id": 8776, "author_profile": "https://Stackoverflow.com/users/8776", "pm_score": -1, "selected": false, "text": "<p>With ajax is perhaps not specific enough. Do you mean in JavaScript?</p>\n" }, { "answer_id": 250836, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "<p>Presumably, the Ajax call is going to get the data in the form of a string or JSON object, and then call some OnComplete function that you specify. In the OnComplete, normally, you take that data and use it to fill the list. Just put double the fill code in that function</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Hi does anybody know how to initialize two list at the same time with ajax? This is my code ``` <html> <body onload="iniciaListas()"> <script type="text/javascript"> var xmlHttp function iniciaListas() { muestraListaPaises(); muestraListaProfesiones(); } function muestraListaProfesiones() { //Se inicializa el objeto ajax para manipular los eventos asincronos al servidor xmlHttp=GetXmlHttpObject(); if (xmlHttp==null) { alert ("Your browser does not support AJAX!"); return; } //Se obtine el id de la lista var obCon = document.getElementById("ocupacion"); //Por medio del metodo GET se llama nuestra pagina PHP xmlHttp.open("GET", "../Listas/listaProfesiones.php"); //On ready funcion es la funcion que se da cuenta cuando la pagina php acaba de hacer su proceso xmlHttp.onreadystatechange = function() { //el estado 4 indica que esta listo para procesar la instruccion if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { //despues que nuestro objeto ajax proceso la pagina php recupera un xml generado obXML = xmlHttp.responseXML; //despues obtine los datos contenidos en las siguites etiquetas obCod = obXML.getElementsByTagName("ID"); obDes = obXML.getElementsByTagName("NOMPROFESION"); //esta funcion devuelve en su la longitud de todos los registros obCon.length=obCod.length; //cilclo de llenado para las listas for (var i=0; i<obCod.length;i++) { obCon.options[i].value=obCod[i].firstChild.nodeValue; obCon.options[i].text=obDes[i].firstChild.nodeValue; } } } //este objeto envia un nulll debido a que el metodo utilizado es get xmlHttp.send(null); } function muestraListaPaises() { //Se inicializa el objeto ajax para manipular los eventos asincronos al servidor xmlHttp=GetXmlHttpObject(); if (xmlHttp==null) { alert ("Your browser does not support AJAX!"); return; } //Se obtine el id de la lista var obCon = document.getElementById("pais"); //Por medio del metodo GET se llama nuestra pagina PHP xmlHttp.open("GET", "../Listas/listaPaises.php"); //On ready funcion es la funcion que se da cuenta cuando la pagina php acaba de hacer su proceso xmlHttp.onreadystatechange = function() { //el estado 4 indica que esta listo para procesar la instruccion if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { //despues que nuestro objeto ajax proceso la pagina php recupera un xml generado obXML = xmlHttp.responseXML; //despues obtine los datos contenidos en las siguites etiquetas obCod = obXML.getElementsByTagName("ID"); obDes = obXML.getElementsByTagName("NOMPAIS"); //esta funcion devuelve en su la longitud de todos los registros obCon.length=obCod.length; //cilclo de llenado para las listas for (var i=0; i<obCod.length;i++) { obCon.options[i].value=obCod[i].firstChild.nodeValue; obCon.options[i].text=obDes[i].firstChild.nodeValue; } } } //este objeto envia un nulll debido a que el metodo utilizado es get xmlHttp.send(null); } function GetXmlHttpObject() { var xmlHttp=null; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } </script> <html> <body onload="iniciaListas()"> <script type="text/javascript" src="lists.js"> </script> <b>Country</b><br> <select name="pais" id="pais" ></select> <b>Ocupation</b><br> <select name="pais" id="pais" ></select> </body> </html> ```
I would recommend using a different ID for the Ocupation node, and double the adding: JS Snip - grab the other list, add to both: ``` //Se obtine el id de la lista var obCon = document.getElementById("pais"); var obOcupation = document.getElementById("ocupation"); ... for (var i=0; i<obCod.length;i++) { obCon.options[i].value=obCod[i].firstChild.nodeValue; obCon.options[i].text=obDes[i].firstChild.nodeValue; obOcupation.options[i].value=obCod[i].firstChild.nodeValue; obOcupation.options[i].text=obDes[i].firstChild.nodeValue; } ``` HTML - give the second select a different name (for the server side) and id (for the javascript): ``` <html> <body onload="iniciaListas()"> <script type="text/javascript" src="lists.js"> </script> <b>Country</b><br> <select name="pais" id="pais" ></select> <b>Ocupation</b><br> <select name="ocupation-pais" id="ocupation" ></select> </body> </html> ``` Your code could be greatly simplified by using an existing JS framework, like [jQuery](http://jquery.com)...
250,818
<p>How do I find a stored procedure in a Sybase database given a text string that appears somewhere in the proc? I want to see if any other proc in the db has similar logic to the one I'm looking at, and I think I have a pretty unique search string (literal)</p> <p>Edit:</p> <p>I'm using Sybase version 11.2</p>
[ { "answer_id": 250862, "author": "Graeme Perrow", "author_id": 1821, "author_profile": "https://Stackoverflow.com/users/1821", "pm_score": 3, "selected": false, "text": "<p>In SQL Anywhere and Sybase IQ:</p>\n\n<pre><code>select * from SYS.SYSPROCEDURE where proc_defn like '%whatever%'\n</code></pre>\n\n<p>I'm not that familiar with ASE, but according to the docs (available from sybooks.sybase.com), it's something like:</p>\n\n<pre><code>select * from syscomments where texttype = 0 and text like '%whatever%'\n</code></pre>\n" }, { "answer_id": 268773, "author": "AdamH", "author_id": 21081, "author_profile": "https://Stackoverflow.com/users/21081", "pm_score": 4, "selected": false, "text": "<p>Two variations on Graeme's answer (So this also won't work on 11.2):</p>\n\n<p>This lists the name of the sproc too, but will return multiple rows for each sproc if the text appears several times:</p>\n\n<pre><code>select object_name(id),* from syscomments \n where texttype = 0 and text like '%whatever%'\n</code></pre>\n\n<p>This lists each sproc just once:</p>\n\n<pre><code>select distinct object_name(id) from syscomments \n where texttype = 0 and text like '%whatever%'\n</code></pre>\n" }, { "answer_id": 3237687, "author": "Tom", "author_id": 390487, "author_profile": "https://Stackoverflow.com/users/390487", "pm_score": 3, "selected": false, "text": "<pre><code>select * from sysobjects where \n id in ( select distinct (id) from syscomments where text like '%SearchTerm%')\n and xtype = 'P'\n</code></pre>\n" }, { "answer_id": 3464875, "author": "Nishad", "author_id": 418003, "author_profile": "https://Stackoverflow.com/users/418003", "pm_score": 2, "selected": false, "text": "<pre><code>select distinct object_name(syscomments.id) 'SearchText', syscomments.id from syscomments ,sysobjects \n where texttype = 0 and text like '%SearchText%' and syscomments.id=sysobjects.id and sysobjects.type='P'\n</code></pre>\n" }, { "answer_id": 8668228, "author": "B0rG", "author_id": 122093, "author_profile": "https://Stackoverflow.com/users/122093", "pm_score": 3, "selected": false, "text": "<p>Please remember, that text column in syscomments is varchar(255), so one big procedure can consist of many lines in syscomments, thus, the above selects will not find the procedure name if it has been splitted into 2 text rows in syscomments.</p>\n\n<p>I suggest the following select, which will handle the above case:</p>\n\n<pre><code>declare @text varchar(100)\nselect @text = \"%whatever%\"\n\nselect distinct o.name object\nfrom sysobjects o,\n syscomments c\nwhere o.id=c.id\nand o.type='P'\nand (c.text like @text\nor exists(\n select 1 from syscomments c2 \n where c.id=c2.id \n and c.colid+1=c2.colid \n and right(c.text,100)+ substring(c2.text, 1, 100) like @text \n )\n)\norder by 1\n</code></pre>\n\n<p>-- kudos for this go to the creator of <a href=\"http://code.google.com/p/aseisql/\" rel=\"noreferrer\">ASEisql</a></p>\n" }, { "answer_id": 50725116, "author": "Fadi Hatem", "author_id": 2351954, "author_profile": "https://Stackoverflow.com/users/2351954", "pm_score": 0, "selected": false, "text": "<p>Multiple rows are used to store text for database objects the value might be accross two rows. So the more accurate answer is:</p>\n\n<pre><code>select distinct object_name(sc1.id)\nfrom syscomments sc1\nleft join syscomments sc2\non (sc2.id = sc1.id and \nsc2.number = sc1.number and\nsc2.colid2 = sc1.colid2 + ((sc1.colid + 1) / 32768) and\nsc2.colid = (sc1.colid + 1) % 32768)\nwhere\nsc1.texttype = 0 and\nsc2.texttype = 0 and\nlower(sc1.text + sc2.text) like lower('%' || @textSearched || '%')\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5472/" ]
How do I find a stored procedure in a Sybase database given a text string that appears somewhere in the proc? I want to see if any other proc in the db has similar logic to the one I'm looking at, and I think I have a pretty unique search string (literal) Edit: I'm using Sybase version 11.2
Two variations on Graeme's answer (So this also won't work on 11.2): This lists the name of the sproc too, but will return multiple rows for each sproc if the text appears several times: ``` select object_name(id),* from syscomments where texttype = 0 and text like '%whatever%' ``` This lists each sproc just once: ``` select distinct object_name(id) from syscomments where texttype = 0 and text like '%whatever%' ```
250,840
<p>The TextWrapping property of the TextBox has three possible values:</p> <ul> <li>Wrap</li> <li>NoWrap</li> <li>WrapWithOverflow</li> </ul> <p>I would like to bind to the IsChecked property of a MenuItem. If the MenuItem is checked, I want to set the TextWrapping property of a TextBox to Wrap. If the MenuItem is not checked, I want to set the TextWrapping property of the TextBox to NoWrap.</p> <p>To sum up, I am trying to bind a control that has two states to two values of an enumeration that has more than two values.</p> <p><strong>[edit]</strong> I would like to accomplish this in XAML, if possible.</p> <p><strong>[edit]</strong> I figured out how to do this using an IValueConverter. Perhaps there is a better way to do this? Here is what I did:</p> <hr> <p>In Window.Resources, I declared a reference to my ValueConverter.</p> <pre><code>&lt;local:Boolean2TextWrapping x:Key="Boolean2TextWrapping" /&gt; </code></pre> <p>In my TextBox, I created the binding to a MenuItem and included the Converter in the binding statement.</p> <pre><code>TextWrapping="{Binding ElementName=MenuItemWordWrap, Path=IsChecked, Converter={StaticResource Boolean2TextWrapping}}" </code></pre> <p>and the ValueConverter looks like this:</p> <pre><code>public class Boolean2TextWrapping : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo cultureInfo) { if (((bool)value) == false) { return TextWrapping.NoWrap; } return TextWrapping.Wrap; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } </code></pre>
[ { "answer_id": 250959, "author": "DCNYAM", "author_id": 30419, "author_profile": "https://Stackoverflow.com/users/30419", "pm_score": -1, "selected": false, "text": "<p>I assume you are talking about .NET. I don't think databinding will work here because the values are not of the same type (boolean vs enum). The easiest solution would be to handle the CheckedChanged event of that menu item and adjust the wrap mode of the textbox accordingly.</p>\n" }, { "answer_id": 251458, "author": "cplotts", "author_id": 22294, "author_profile": "https://Stackoverflow.com/users/22294", "pm_score": 0, "selected": false, "text": "<p>I think that <strike>the only and right</strike> the typical way to do this is to use a value converter like you already have done.</p>\n\n<p>Sometimes you can find an existing value converter that you have built already ... or even better that Microsoft has built for you. For example, in System.Windows.Controls, Microsoft has written a BooleanToVisibilityConverter ... which converts a bool into a Visibility enum ... converting True to Visible and False to Collapsed (and not worrying about Hidden).</p>\n\n<p>One idea is to use .NET Reflector, navigate to the System.Windows.Data.IValueConverter, and then use the Analyze feature (in particular, 'Used by') and see what things have implemented IValueConverter ... and you just might get lucky to find a converter that suits your purpose.</p>\n\n<p>On a related note, BooleanToVisibilityConverter is very similar to what you are trying to do above.</p>\n\n<p><strong>Edit:</strong>\nI really like Todd White's suggestion of styling the TextBox and using a DataTrigger in the Style. It is a very good idea if you want to avoid a Converter.</p>\n" }, { "answer_id": 252284, "author": "Todd White", "author_id": 30833, "author_profile": "https://Stackoverflow.com/users/30833", "pm_score": 4, "selected": true, "text": "<p>If you want to do this all in xaml you need to use a <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.style.aspx\" rel=\"noreferrer\">Style</a> and a <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.datatrigger.aspx\" rel=\"noreferrer\">DataTrigger</a>.</p>\n\n<pre><code>&lt;StackPanel&gt;\n &lt;CheckBox x:Name=\"WordWrap\"&gt;Word Wrap&lt;/CheckBox&gt;\n &lt;TextBlock Width=\"50\"&gt;\n Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Proin lacinia nibh non augue. Pellentesque pretium neque et neque auctor adipiscing.\n\n &lt;TextBlock.Style&gt;\n &lt;Style TargetType=\"{x:Type TextBlock}\"&gt;\n &lt;Style.Triggers&gt;\n &lt;DataTrigger Binding=\"{Binding IsChecked, ElementName=WordWrap}\" Value=\"True\"&gt;\n &lt;Setter Property=\"TextWrapping\" Value=\"Wrap\" /&gt;\n &lt;/DataTrigger&gt;\n &lt;/Style.Triggers&gt;\n &lt;/Style&gt;\n &lt;/TextBlock.Style&gt;\n &lt;/TextBlock&gt;\n&lt;/StackPanel&gt;\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12919/" ]
The TextWrapping property of the TextBox has three possible values: * Wrap * NoWrap * WrapWithOverflow I would like to bind to the IsChecked property of a MenuItem. If the MenuItem is checked, I want to set the TextWrapping property of a TextBox to Wrap. If the MenuItem is not checked, I want to set the TextWrapping property of the TextBox to NoWrap. To sum up, I am trying to bind a control that has two states to two values of an enumeration that has more than two values. **[edit]** I would like to accomplish this in XAML, if possible. **[edit]** I figured out how to do this using an IValueConverter. Perhaps there is a better way to do this? Here is what I did: --- In Window.Resources, I declared a reference to my ValueConverter. ``` <local:Boolean2TextWrapping x:Key="Boolean2TextWrapping" /> ``` In my TextBox, I created the binding to a MenuItem and included the Converter in the binding statement. ``` TextWrapping="{Binding ElementName=MenuItemWordWrap, Path=IsChecked, Converter={StaticResource Boolean2TextWrapping}}" ``` and the ValueConverter looks like this: ``` public class Boolean2TextWrapping : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo cultureInfo) { if (((bool)value) == false) { return TextWrapping.NoWrap; } return TextWrapping.Wrap; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } ```
If you want to do this all in xaml you need to use a [Style](http://msdn.microsoft.com/en-us/library/system.windows.style.aspx) and a [DataTrigger](http://msdn.microsoft.com/en-us/library/system.windows.datatrigger.aspx). ``` <StackPanel> <CheckBox x:Name="WordWrap">Word Wrap</CheckBox> <TextBlock Width="50"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Proin lacinia nibh non augue. Pellentesque pretium neque et neque auctor adipiscing. <TextBlock.Style> <Style TargetType="{x:Type TextBlock}"> <Style.Triggers> <DataTrigger Binding="{Binding IsChecked, ElementName=WordWrap}" Value="True"> <Setter Property="TextWrapping" Value="Wrap" /> </DataTrigger> </Style.Triggers> </Style> </TextBlock.Style> </TextBlock> </StackPanel> ```
250,850
<p>I've got a little c# windows service that periodically pulls xml from a web service and stores the data in a database table.</p> <p>Unfortunately it's failing because the web service has occasional bad data in it - strings instead of decimals. I don't have any control over the web service (unvalidated user input from software we can't change) but I would like to log the bad data so that it can be re-input.</p> <p>It's simple data that looks something like this:</p> <pre><code>&lt;ROWS&gt; &lt;ROW&gt; &lt;COL1&gt;5405&lt;/COL1&gt; &lt;COL2&gt;102.24&lt;/COL1&gt; &lt;/ROW&gt; &lt;ROW&gt; &lt;COL1&gt;5406&lt;/COL1&gt; &lt;COL2&gt;2.25&lt;/COL1&gt; &lt;/ROW&gt; &lt;/ROWS&gt; </code></pre> <p>The table just has two columns, COL1 (NUMBER, 10), COL2 (NUMBER, 10,2).</p> <p>I was using a validating XmlReader and this XSD: </p> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;xs:schema id="ROWS" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"&gt; &lt;xs:element name="ROWS" msdata:IsDataSet="true" msdata:Locale="en-US"&gt; &lt;xs:complexType&gt; &lt;xs:choice minOccurs="0" maxOccurs="unbounded"&gt; &lt;xs:element name="ROW"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name="COL1" type="xs:decimal" minOccurs="0" /&gt; &lt;xs:element name="COL2" type="xs:decimal" minOccurs="0" /&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:choice&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:schema&gt; </code></pre> <p>then a dataset.ReadXml() and Update()ing the dataset.</p> <p>Whenever it hits bad data I get the following exception:</p> <blockquote> <p>System.Xml.Schema.XmlSchemaValidationException was unhandled</p> <p>Message="The 'COL1' element is invalid - The value 'A40' is invalid according to its datatype '<a href="http://www.w3.org/2001/XMLSchema:decimal" rel="nofollow noreferrer">http://www.w3.org/2001/XMLSchema:decimal</a>' - The string 'A40' is not a valid Decimal value."</p> </blockquote> <p>I can think of several ways of ways of getting around the problem but they all feel like a bit of a kludge and I'd like to learn something more elegant, and improve my knowledge. Here's what I've come up with so far:</p> <ul> <li>Pre-process the XML provided by the web service before loading into the validating XML reader, removing any bad nodes entirely.</li> <li>Catch the XmlSchemaValidationExceptions and try to continue from them gracefully (not sure about that one)</li> <li>Don't use a validating XML reader, but instead catch exceptions when loading the unvalidated xml into the dataset. (again not sure about that)</li> <li>have string columns in the dataset, and ignore bad data until I update it, and catch anything the database rejects.</li> <li>go and stand over the users with a large mallet until they learn to get it right first time (too time consuming)</li> <li>something else?</li> </ul> <p><strong>UPDATE:</strong> The data can be bad because it comes from a application that doesn't validate the user input for COL1 - but the numbers in COL2 are calculated correctly, and COL1 should correspond with a different system. Any invalid entries should be recorded so they can be corrected. After the data is written to the database, another system verifies that COL1 is valid, and the users will soon spot if it doesn't show correctly in the other system - they used to load it by hand anyway :) </p>
[ { "answer_id": 250859, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<blockquote>\n <p>Pre-process the XML provided by the\n web service before loading into the\n validating XML reader, removing any\n bad nodes entirely.</p>\n</blockquote>\n\n<p>This is the option I would choose, it would allow you to grab the bad input before the exception and store it somewhere so it can be looked at later. Then you can find the offending user and use another of your methods </p>\n\n<blockquote>\n <p>go and stand over the users with a\n large mallet until they learn to get\n it right first time</p>\n</blockquote>\n" }, { "answer_id": 250881, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 0, "selected": false, "text": "<p>The question for me is: What do you want to do with the erroneus data?\nDo you want to ignore it, sanitize it (remove the 'A' from 'A40'), or collect it to one day finally show it to the users (speaking of a large mallet;-) ?</p>\n\n<p>If you just want to leave out any rows with incorrect data, the strip out the ones with errors before doing anything else. You have to decide yourself if you still need to validate the remaining xml before entering it into the DB. If you do the stripping in a restrictive way, it should no longer be necessary.</p>\n" }, { "answer_id": 250886, "author": "C. Dragon 76", "author_id": 5682, "author_profile": "https://Stackoverflow.com/users/5682", "pm_score": 0, "selected": false, "text": "<p>If it's only occasional, I'd probably cache the last known good result and ignore any bad feeds altogether. (Maybe log a warning.) I'd try to avoid trying to correct a bad feed. If it's not even valid against the schema, who's to say the actual data is correct.</p>\n\n<p>Also, you should definitely raise the issue with the feed provider to try to get them to correct the issue.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12744/" ]
I've got a little c# windows service that periodically pulls xml from a web service and stores the data in a database table. Unfortunately it's failing because the web service has occasional bad data in it - strings instead of decimals. I don't have any control over the web service (unvalidated user input from software we can't change) but I would like to log the bad data so that it can be re-input. It's simple data that looks something like this: ``` <ROWS> <ROW> <COL1>5405</COL1> <COL2>102.24</COL1> </ROW> <ROW> <COL1>5406</COL1> <COL2>2.25</COL1> </ROW> </ROWS> ``` The table just has two columns, COL1 (NUMBER, 10), COL2 (NUMBER, 10,2). I was using a validating XmlReader and this XSD: ``` <?xml version="1.0" encoding="utf-8"?> <xs:schema id="ROWS" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xs:element name="ROWS" msdata:IsDataSet="true" msdata:Locale="en-US"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="ROW"> <xs:complexType> <xs:sequence> <xs:element name="COL1" type="xs:decimal" minOccurs="0" /> <xs:element name="COL2" type="xs:decimal" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema> ``` then a dataset.ReadXml() and Update()ing the dataset. Whenever it hits bad data I get the following exception: > > System.Xml.Schema.XmlSchemaValidationException > was unhandled > > > Message="The 'COL1' > element is invalid - The value 'A40' > is invalid according to its datatype > '<http://www.w3.org/2001/XMLSchema:decimal>' > - The string 'A40' is not a valid Decimal value." > > > I can think of several ways of ways of getting around the problem but they all feel like a bit of a kludge and I'd like to learn something more elegant, and improve my knowledge. Here's what I've come up with so far: * Pre-process the XML provided by the web service before loading into the validating XML reader, removing any bad nodes entirely. * Catch the XmlSchemaValidationExceptions and try to continue from them gracefully (not sure about that one) * Don't use a validating XML reader, but instead catch exceptions when loading the unvalidated xml into the dataset. (again not sure about that) * have string columns in the dataset, and ignore bad data until I update it, and catch anything the database rejects. * go and stand over the users with a large mallet until they learn to get it right first time (too time consuming) * something else? **UPDATE:** The data can be bad because it comes from a application that doesn't validate the user input for COL1 - but the numbers in COL2 are calculated correctly, and COL1 should correspond with a different system. Any invalid entries should be recorded so they can be corrected. After the data is written to the database, another system verifies that COL1 is valid, and the users will soon spot if it doesn't show correctly in the other system - they used to load it by hand anyway :)
> > Pre-process the XML provided by the > web service before loading into the > validating XML reader, removing any > bad nodes entirely. > > > This is the option I would choose, it would allow you to grab the bad input before the exception and store it somewhere so it can be looked at later. Then you can find the offending user and use another of your methods > > go and stand over the users with a > large mallet until they learn to get > it right first time > > >
250,867
<p>Assuming a table of tags like the stackoverflow question tags:</p> <blockquote> <p>TagID (bigint), QuestionID (bigint), Tag (varchar)</p> </blockquote> <p>What is the most efficient way to get the 25 most used tags using LINQ? In SQL, a simple GROUP BY will do:</p> <pre><code>SELECT Tag, COUNT(Tag) FROM Tags GROUP BY Tag </code></pre> <p>I've written some LINQ that works:</p> <pre><code>var groups = from t in DataContext.Tags group t by t.Tag into g select new { Tag = g.Key, Frequency = g.Count() }; return groups.OrderByDescending(g =&gt; g.Frequency).Take(25); </code></pre> <p>Like, really? Isn't this mega-verbose? The sad thing is that I'm doing this to save a massive number of queries, as my Tag objects already contain a Frequency property that would otherwise need to check back with the database for every Tag if I actually used the property.</p> <p>So I then parse these anonymous types <em>back</em> into Tag objects:</p> <pre><code>groups.OrderByDescending(g =&gt; g.Frequency).Take(25).ToList().ForEach(t =&gt; tags.Add(new Tag() { Tag = t.Tag, Frequency = t.Frequency })); </code></pre> <p>I'm a LINQ newbie, and this doesn't seem right. Please show me how it's really done.</p>
[ { "answer_id": 250906, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 4, "selected": true, "text": "<p>I'm pretty sure you've got it right. And, the SQL that LINQ generates and will send to your db will look just like the SQL you started with, so while you're doing a bit more typing, your database isn't doing any more work.</p>\n" }, { "answer_id": 250910, "author": "GalacticCowboy", "author_id": 29638, "author_profile": "https://Stackoverflow.com/users/29638", "pm_score": 5, "selected": false, "text": "<p>If you want Tag objects, why not create them directly from your Linq query?</p>\n\n<pre><code>var groups = from t in DataContext.Tags\n group t by t.Tag into g\n select new Tag() { Tag = g.Key, Frequency = g.Count() };\n\nreturn groups.OrderByDescending(g =&gt; g.Frequency).Take(25);\n</code></pre>\n" }, { "answer_id": 251226, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 4, "selected": false, "text": "<p>If you use the verbose form of the syntax, your code will be verbose. Here's an alternative:</p>\n\n<pre><code>List&lt;Tag&gt; result = \n db.Tags\n .GroupBy(t =&gt; t.Tag)\n .Select(g =&gt; new {Tag = g.Key, Frequency = g.Count()})\n .OrderByDescending(t =&gt; t.Frequency)\n .Take(25)\n .ToList()\n .Select(t =&gt; new Tag(){Tag = t.Tag, Frequency = t.Frequency})\n .ToList();\n</code></pre>\n" }, { "answer_id": 2877478, "author": "NetMage", "author_id": 2557128, "author_profile": "https://Stackoverflow.com/users/2557128", "pm_score": 2, "selected": false, "text": "<p>I think you are also be unfair in that your SQL query does not do the same thing as your LINQ query - it doesn't return the top 25.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192/" ]
Assuming a table of tags like the stackoverflow question tags: > > TagID (bigint), QuestionID (bigint), Tag (varchar) > > > What is the most efficient way to get the 25 most used tags using LINQ? In SQL, a simple GROUP BY will do: ``` SELECT Tag, COUNT(Tag) FROM Tags GROUP BY Tag ``` I've written some LINQ that works: ``` var groups = from t in DataContext.Tags group t by t.Tag into g select new { Tag = g.Key, Frequency = g.Count() }; return groups.OrderByDescending(g => g.Frequency).Take(25); ``` Like, really? Isn't this mega-verbose? The sad thing is that I'm doing this to save a massive number of queries, as my Tag objects already contain a Frequency property that would otherwise need to check back with the database for every Tag if I actually used the property. So I then parse these anonymous types *back* into Tag objects: ``` groups.OrderByDescending(g => g.Frequency).Take(25).ToList().ForEach(t => tags.Add(new Tag() { Tag = t.Tag, Frequency = t.Frequency })); ``` I'm a LINQ newbie, and this doesn't seem right. Please show me how it's really done.
I'm pretty sure you've got it right. And, the SQL that LINQ generates and will send to your db will look just like the SQL you started with, so while you're doing a bit more typing, your database isn't doing any more work.
250,868
<p>I've heard that there are some things one cannot do as a computer programmer, but I don't know what they are. One thing that occurred to me recently was: wouldn't it be nice to have a class that could make a copy of the source of the program it runs, modify that program and add a method to the class that it is, and then run the copy of the program and terminate itself. Is it possible for code to write code?</p>
[ { "answer_id": 250872, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 3, "selected": false, "text": "<p>Sure it is. That's how a lot of viruses work!</p>\n" }, { "answer_id": 250876, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 2, "selected": false, "text": "<p>Yes it is possible to create code generators.\nMost of the time they take user input and produce valid code. But there are other possibilities. </p>\n\n<p>Self modifying programes are also possible. But they were more common in the dos era.</p>\n" }, { "answer_id": 250877, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 1, "selected": false, "text": "<p>There is a whole class of such things called \"Code Generators\". (Although, a compiler also fits the description as you set it). And those describe the two areas of these beasts.</p>\n\n<p>Most code generates, take some form of user input (most take a Database schema) and product source code which is then compiled.</p>\n\n<p>More advanced ones can output executable code. With .NET, there's a whole namespace (System.CodeDom) dedicated to the create of executable code. The these objects, you can take C# (or another language) code, compile it, and link it into your currently running program. </p>\n" }, { "answer_id": 250882, "author": "Marcus King", "author_id": 19840, "author_profile": "https://Stackoverflow.com/users/19840", "pm_score": 2, "selected": false, "text": "<p>Yes it certainly is, though maybe not in the context you are referring to check out this <a href=\"http://www.hanselman.com/blog/T4TextTemplateTransformationToolkitCodeGenerationBestKeptVisualStudioSecret.aspx\" rel=\"nofollow noreferrer\">post</a> on t4.</p>\n" }, { "answer_id": 250885, "author": "Justin Voss", "author_id": 5616, "author_profile": "https://Stackoverflow.com/users/5616", "pm_score": 2, "selected": false, "text": "<p>Of course you can! In fact, if you use a dynamic language, the class can change itself (or another class) while the program is still running. It can even create new classes that didn't exist before. This is called metaprogramming, and it lets your code become very flexible.</p>\n" }, { "answer_id": 250889, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 4, "selected": false, "text": "<p>If you want to learn about the limits of computability, read about the <a href=\"http://en.wikipedia.org/wiki/Halting_problem\" rel=\"noreferrer\">halting problem</a></p>\n\n<blockquote>\n <p>In computability theory, the halting\n problem is a decision problem which\n can be stated as follows: given a\n description of a program and a finite\n input, decide whether the program\n finishes running or will run forever,\n given that input.</p>\n \n <p>Alan Turing proved in 1936 that a\n general algorithm to solve the halting problem for all \n possible program-input pairs cannot exist</p>\n</blockquote>\n" }, { "answer_id": 250892, "author": "slashmais", "author_id": 15161, "author_profile": "https://Stackoverflow.com/users/15161", "pm_score": 2, "selected": false, "text": "<p>Get your head around this: <a href=\"http://en.wikipedia.org/wiki/Computability_theory_(computer_science)\" rel=\"nofollow noreferrer\">computability theory</a>.</p>\n" }, { "answer_id": 250893, "author": "dlamblin", "author_id": 459, "author_profile": "https://Stackoverflow.com/users/459", "pm_score": 5, "selected": true, "text": "<p>Start by looking at <a href=\"http://en.wikipedia.org/wiki/Quines\" rel=\"nofollow noreferrer\">quines</a>, then at Macro-Assemblers and then <a href=\"http://www.google.com/search?q=lex+yacc\" rel=\"nofollow noreferrer\">lex &amp; yacc</a>, and <a href=\"http://www.google.com/search?q=flex+bison\" rel=\"nofollow noreferrer\">flex &amp; bison</a>. Then consider <a href=\"http://en.wikipedia.org/wiki/Self-modifying_code\" rel=\"nofollow noreferrer\">self-modifying code</a>.</p>\n\n<p>Here's a quine (formatted, use the output as the new input):</p>\n\n<pre><code>#include&lt;stdio.h&gt;\n\nmain()\n{\n char *a = \"main(){char *a = %c%s%c; int b = '%c'; printf(a,b,a,b,b);}\";\n int b = '\"';\n printf(a,b,a,b,b);\n}\n</code></pre>\n\n<p>Now if you're just looking for things programmers can't do look for the opposite of np-complete.</p>\n" }, { "answer_id": 250894, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 1, "selected": false, "text": "<p>I do this in PHP.</p>\n\n<p>To persist settings for a class, I keep a local variable called <code>$data</code>. $data is just a dictionary/hashtable/assoc-array (depending on where you come from).</p>\n\n<p>When you load the class, it includes a php file which basically defines data. When I save the class, it writes the PHP out for each value of data. It's a slow write process (and there are currently some concurrency issues) but it's faster than light to read. So much faster (and lighter) than using a database.</p>\n\n<p>Something like this wouldn't work for all languages. It works for me in PHP because PHP is very much on-the-fly.</p>\n" }, { "answer_id": 250898, "author": "florin", "author_id": 18308, "author_profile": "https://Stackoverflow.com/users/18308", "pm_score": 2, "selected": false, "text": "<p>You are confusing/conflating two meanings of the word \"write\". One meaning is the physical writing of bytes to a medium, and the other is designing software. Of course you can have the program do the former, if it was designed to do so.</p>\n\n<p>The only way for a program to do something that the programmer did not explicitly intend it to do, is to behave like a living creature: mutate (incorporate in itself bits of environment), and replicate different mutants at different rates (to avoid complete extinction, if a mutation is terminal).</p>\n" }, { "answer_id": 250904, "author": "glenatron", "author_id": 15394, "author_profile": "https://Stackoverflow.com/users/15394", "pm_score": 2, "selected": false, "text": "<p>If you look at Functional Programming that has many opportunities to write code that generates further code, the way that a language like Lisp doesn't differentiate between code and data is a significant part of it's power.</p>\n\n<p>Rails generates the various default model and controller classes from the database schema when it's creating a new application. It's quite standard to do this kind of thing with dynamic languages- I have a few bits of PHP around that generate php files, just because it was the simplest solution to the problem I was dealing with at the time.</p>\n\n<p>So it is possible. As for the question you are asking, though- that is perhaps a little vague- what environment and language are you using? What do you expect the code to do and why does it need to be added to? A concrete example may bring more directly relevant responses.</p>\n" }, { "answer_id": 250905, "author": "BoltBait", "author_id": 20848, "author_profile": "https://Stackoverflow.com/users/20848", "pm_score": 2, "selected": false, "text": "<p>Sure it is. I wrote an effect for Paint.NET* that gives you an editor and allows you to write a graphical effect \"on the fly\". When you pause typing it compiles it to a dll, loads it and executes it. Now, in the editor, you only need to write the actual render function, <strong>everything else necessary to create a dll is written by the editor</strong> and sent to the C# compiler.</p>\n\n<p>You can download it free here: <a href=\"http://www.boltbait.com/pdn/codelab/\" rel=\"nofollow noreferrer\">http://www.boltbait.com/pdn/codelab/</a></p>\n\n<p>In fact, there is even an option to see all the code that was written for you before it is sent to the compiler. The help file (linked above) talks all about it.</p>\n\n<p>The source code is available to download from that page as well.</p>\n\n<p>*Paint.NET is a free image editor that you can download here: <a href=\"http://getpaint.net\" rel=\"nofollow noreferrer\">http://getpaint.net</a></p>\n" }, { "answer_id": 250920, "author": "Scottm", "author_id": 22061, "author_profile": "https://Stackoverflow.com/users/22061", "pm_score": 0, "selected": false, "text": "<p>This is one of the fundamental questions of Artificial Intelligence. Personally I hope it is not possible - otherwise soon I'll be out of a job!!! :)</p>\n" }, { "answer_id": 250968, "author": "Rik", "author_id": 5409, "author_profile": "https://Stackoverflow.com/users/5409", "pm_score": 2, "selected": false, "text": "<p>In relation to artificial intelligence, take a look at <a href=\"http://en.wikipedia.org/wiki/Evolutionary_algorithms\" rel=\"nofollow noreferrer\">Evolutionary algorithms</a>.</p>\n" }, { "answer_id": 251044, "author": "Vern Takebayashi", "author_id": 23089, "author_profile": "https://Stackoverflow.com/users/23089", "pm_score": 1, "selected": false, "text": "<p>It has always been possible to write code generators. With XML technology, the use of code generators can be an essential tool. Suppose you work for a company that has to deal with XML files from other companies. It is relatively straightforward to write a program that uses the XML parser to parse the new XML file and write another program that has all the callback functions set up to read XML files of that format. You would still have to edit the new program to make it specific to your needs, but the development time when a new XML file (new structure, new names) is cut down a lot by using this type of code generator. In my opinion, this is part of the strength of XML technology.</p>\n" }, { "answer_id": 251063, "author": "KeyserSoze", "author_id": 14116, "author_profile": "https://Stackoverflow.com/users/14116", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>make a copy of the source of the program it runs, modify that program and add a method to the class that it is, and then run the copy of the program and terminate itself</p>\n</blockquote>\n\n<p>You can also generate code, build it into a library instead of an executable, and then dynamically load the library without even exiting the program that is currently running.</p>\n" }, { "answer_id": 251092, "author": "David Thornley", "author_id": 14148, "author_profile": "https://Stackoverflow.com/users/14148", "pm_score": 2, "selected": false, "text": "<p>Dynamic languages usually don't work quite as you suggest, in that they don't have a completely separate compilation step. It isn't necessary for a program to modify its own source code, recompile, and start from scratch. Typically the new functionality is compiled and linked in on the fly.</p>\n\n<p>Common Lisp is a very good language to practice this in, but there are others where you can created code and run it then and there. Typically, this will be through a function called \"eval\" or something similar. Perl has an \"eval\" function, and it's generally common for scripting languages to have the ability.</p>\n\n<p>There are a lot of programs that write other programs, such as yacc or bison, but they don't have the same dynamic quality you seem to be looking for. </p>\n" }, { "answer_id": 251106, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 2, "selected": false, "text": "<p>Yes, that's what most Lisp macros do (for just one example).</p>\n" }, { "answer_id": 263666, "author": "fmsf", "author_id": 26004, "author_profile": "https://Stackoverflow.com/users/26004", "pm_score": 1, "selected": false, "text": "<p>Lisp lisp lisp lisp :p</p>\n\n<p>Joking, if you want code that generates code to run and you got time to loose learning it and breaking your mind with recursive stuff generating more code, try to learn lisp :)</p>\n\n<pre><code>(eval '(or true false))\n</code></pre>\n" }, { "answer_id": 263783, "author": "Roman Plášil", "author_id": 16590, "author_profile": "https://Stackoverflow.com/users/16590", "pm_score": 2, "selected": false, "text": "<p>Take a look at <a href=\"http://www.alesdar.org/oldSite/IS/Langton/LangtonLoops.html\" rel=\"nofollow noreferrer\">Langtom's loop</a>. This is the simplest example of self-reproducing \"program\".</p>\n" }, { "answer_id": 263848, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>wouldn't it be nice to have a class that could make a copy of the source of the program it runs, modify that program and add a method to the class that it is, and then run the copy of the program and terminate itself</p>\n</blockquote>\n\n<p>There are almost no cases where that would solve a problem that cannot be solved \"better\" using non-self-modifying code..</p>\n\n<p>That said, there are some very common (useful) cases of code writing other code.. The most obvious being any server-side web-application, which generates HTML/Javascript (well, HTML is markup, but it's identical in theory). Also any script that alters a terminals environment usually outputs a shell script that is eval'd by the parent shell. wxGlade generates code to that creates bare-bone wx-based GUIs.</p>\n" }, { "answer_id": 7035146, "author": "Ira Baxter", "author_id": 120163, "author_profile": "https://Stackoverflow.com/users/120163", "pm_score": 1, "selected": false, "text": "<p>See our <a href=\"http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html\" rel=\"nofollow\">DMS Software Reengineering Toolkit</a>. This is general purpose machinery to read and modify programs, or generate programs by assembling fragments. </p>\n" }, { "answer_id": 8625715, "author": "Basile Starynkevitch", "author_id": 841108, "author_profile": "https://Stackoverflow.com/users/841108", "pm_score": 0, "selected": false, "text": "<p>It is called <a href=\"http://en.wikipedia.org/wiki/Meta-programming\" rel=\"nofollow\">meta-programming</a> and is both a nice way of writing useful programs, and an interesting research topic. Jacques Pitrat's <a href=\"http://onlinelibrary.wiley.com/book/10.1002/9780470611791\" rel=\"nofollow\">Artificial Beings: the conscience of a conscious machine</a> book should interest you a lot. It is mostly related to meta-knowledge based computer programs.</p>\n\n<p>Another related term is <a href=\"http://www.cs.rice.edu/~taha/MSP/\" rel=\"nofollow\">multi-staged programming</a> (because there are several stages of programs, each generating the next one).</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29182/" ]
I've heard that there are some things one cannot do as a computer programmer, but I don't know what they are. One thing that occurred to me recently was: wouldn't it be nice to have a class that could make a copy of the source of the program it runs, modify that program and add a method to the class that it is, and then run the copy of the program and terminate itself. Is it possible for code to write code?
Start by looking at [quines](http://en.wikipedia.org/wiki/Quines), then at Macro-Assemblers and then [lex & yacc](http://www.google.com/search?q=lex+yacc), and [flex & bison](http://www.google.com/search?q=flex+bison). Then consider [self-modifying code](http://en.wikipedia.org/wiki/Self-modifying_code). Here's a quine (formatted, use the output as the new input): ``` #include<stdio.h> main() { char *a = "main(){char *a = %c%s%c; int b = '%c'; printf(a,b,a,b,b);}"; int b = '"'; printf(a,b,a,b,b); } ``` Now if you're just looking for things programmers can't do look for the opposite of np-complete.
250,874
<p>How do implement the iterator pattern in <a href="http://en.wikipedia.org/wiki/Visual_Basic_.NET" rel="nofollow noreferrer">VB.NET</a>, which does not have the <code>yield</code> keyword?</p>
[ { "answer_id": 250899, "author": "Jeff Atwood", "author_id": 1, "author_profile": "https://Stackoverflow.com/users/1", "pm_score": 1, "selected": false, "text": "<p>Hmm, looks like you might be <a href=\"http://weblogs.asp.net/jgaylord/archive/2007/10/17/vb-net-s-quot-yield-return-quot.aspx\" rel=\"nofollow noreferrer\">out of luck</a>:</p>\n\n<blockquote>\n <p>I was struggling with an issue today when converting some C# to VB.NET. C# has a really cool \"yield return\" statement that is used in an iterator block to provide a value to the enumerator object. VB.NET does not have the \"yield\" keyword. So, there are a few solutions (none of which are really clean) to get around this. You could use a return statement to return the value if you are looping through and would like to break an enumerator and return a single value. However, if you'd like to return the entire enumeration, create a List() of the child type and return the list. Since you are usually using this with an IEnumerable, the List() will work nice.</p>\n</blockquote>\n\n<p>That was written a year ago, not sure if anyone has come up with anything else better since then..</p>\n\n<hr>\n\n<p>Edit: this will be possible in the version 11 of VB.NET (the one after VS2010), support for iterators is planned. The spec <a href=\"http://www.microsoft.com/downloads/en/details.aspx?FamilyID=7DE30BAF-B897-453E-AD18-E1EE2226EA86\" rel=\"nofollow noreferrer\">is available here</a>.</p>\n" }, { "answer_id": 250918, "author": "Jasper Bekkers", "author_id": 31486, "author_profile": "https://Stackoverflow.com/users/31486", "pm_score": 2, "selected": false, "text": "<p>VB.NET does not support the creation of custom iterators and thus has no equivalent to the C# yield keyword. However, you might want to look at the KB article <em><a href=\"http://support.microsoft.com/kb/322025\" rel=\"nofollow noreferrer\">How to make a Visual Basic .NET or Visual Basic 2005 class usable in a For Each statement</a></em> for more information.</p>\n" }, { "answer_id": 251059, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "<p>C#'s yield keyword forces the compiler to create a state machine in the background to support it. VB.Net does not have the yield keyword. But it does have a construct that would allow you to create a state machine within a function: <a href=\"http://msdn.microsoft.com/en-us/library/z2cty7t8.aspx\" rel=\"nofollow noreferrer\">Static function members</a>.</p>\n\n<p>It should be possible to mimic the effects of a yield return function by creating a generic class that implements IEnumerable as well as the needed state machine and placing an instance as a static member inside your function. </p>\n\n<p>This would, of course, require implementing the class outside of the function. But if done properly the class should be re-usable in the general case. I haven't played with the idea enough to provide any implementation details, though.</p>\n" }, { "answer_id": 5712861, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 5, "selected": true, "text": "<p>This is now supported in VS 2010 SP1, with the Async CTP, see: <a href=\"http://msdn.microsoft.com/en-us/vstudio/gg497937\" rel=\"noreferrer\">Iterators (C# and Visual Basic) on MSDN</a> and <a href=\"http://www.microsoft.com/en-us/download/details.aspx?id=9983\" rel=\"noreferrer\">download Visual Studio Async CTP (Version 3)</a>.</p>\n\n<p>Code such as this, works: </p>\n\n<pre><code>Private Iterator Function SomeNumbers() As IEnumerable\n ' Use multiple yield statements.\n Yield 3\n Yield 5\n Yield 8\nEnd Function\n</code></pre>\n" }, { "answer_id": 5856403, "author": "meenakshisundaram muthukrishna", "author_id": 734254, "author_profile": "https://Stackoverflow.com/users/734254", "pm_score": -1, "selected": false, "text": "<p>Below gives output: 2, 4, 8, 16, 32</p>\n\n<p>In VB.NET</p>\n\n<pre><code>Public Shared Function setofNumbers() As Integer()\n\n Dim counter As Integer = 0\n Dim results As New List(Of Integer)\n Dim result As Integer = 1\n While counter &lt; 5\n result = result * 2\n results.Add(result)\n counter += 1\n End While\n Return results.ToArray()\nEnd Function\n\nPrivate Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n For Each i As Integer In setofNumbers()\n MessageBox.Show(i)\n Next\nEnd Sub\n</code></pre>\n\n<p>In C#</p>\n\n<pre><code>private void Form1_Load(object sender, EventArgs e)\n{\n foreach (int i in setofNumbers())\n {\n MessageBox.Show(i.ToString());\n }\n}\n\npublic static IEnumerable&lt;int&gt; setofNumbers()\n{\n int counter=0;\n //List&lt;int&gt; results = new List&lt;int&gt;();\n int result=1;\n while (counter &lt; 5)\n {\n result = result * 2;\n counter += 1;\n yield return result;\n }\n}\n</code></pre>\n" }, { "answer_id": 9181839, "author": "Richard Collette", "author_id": 107683, "author_profile": "https://Stackoverflow.com/users/107683", "pm_score": 0, "selected": false, "text": "<p>Keep in mind that deferred execution and lazy evaluation properties of LINQ expresssions and methods allow us to effectively implement custom iterators until the yield statement is available in .NET 4.5. Yield is used internally by LINQ expressions and methods.</p>\n\n<p>The following code demonstrates this.</p>\n\n<pre><code> Private Sub AddOrRemoveUsersFromRoles(procName As String,\n applicationId As Integer,\n userNames As String(),\n rolenames As String())\n Dim sqldb As SqlDatabase = CType(db, SqlDatabase)\n Dim command As DbCommand = sqldb.GetStoredProcCommand(procName)\n Dim record As New SqlDataRecord({New SqlMetaData(\"value\", SqlDbType.VarChar,200)})\n Dim setRecord As Func(Of String, SqlDataRecord) =\n Function(value As String)\n record.SetString(0, value)\n Return record\n End Function\n Dim userNameRecords As IEnumerable(Of SqlDataRecord) = userNames.Select(setRecord)\n Dim roleNameRecords As IEnumerable(Of SqlDataRecord) = rolenames.Select(setRecord)\n With sqldb\n .AddInParameter(command, \"userNames\", SqlDbType.Structured, userNameRecords)\n .AddInParameter(command, \"roleNames\", SqlDbType.Structured, roleNameRecords)\n .AddInParameter(command, \"applicationId\", DbType.Int32, applicationId)\n .AddInParameter(command, \"currentUserName\", DbType.String, GetUpdatingUserName)\n .ExecuteNonQuery(command)\n End With\nEnd Sub\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31766/" ]
How do implement the iterator pattern in [VB.NET](http://en.wikipedia.org/wiki/Visual_Basic_.NET), which does not have the `yield` keyword?
This is now supported in VS 2010 SP1, with the Async CTP, see: [Iterators (C# and Visual Basic) on MSDN](http://msdn.microsoft.com/en-us/vstudio/gg497937) and [download Visual Studio Async CTP (Version 3)](http://www.microsoft.com/en-us/download/details.aspx?id=9983). Code such as this, works: ``` Private Iterator Function SomeNumbers() As IEnumerable ' Use multiple yield statements. Yield 3 Yield 5 Yield 8 End Function ```
250,911
<p>An application I am working on reads information from files to populate a database. Some of the characters in the files are non-English, for example accented French characters.</p> <p>The application is working fine in Windows but on our Solaris machine it is failing to recognise the special characters and is throwing an exception. For example when it encounters the accented e in "Gérer" it says :-</p> <pre> Encountered: "\u0161" (353), after : "\'G\u00c3\u00a9rer les mod\u00c3"</pre> <p>(an exception which is thrown from our application)</p> <p>I suspect that in order to stop this from happening I need to change the file.encoding property of the JVM. I tried to do this via System.setProperty() but it has not stopped the error from occurring.</p> <p>Are there any suggestions for what I could do? I was thinking about setting the basic locale of the solaris platform in /etc/default/init to be UTF-8. Does anyone think this might help?</p> <p>Any thoughts are much appreciated.</p>
[ { "answer_id": 250944, "author": "sakana", "author_id": 28921, "author_profile": "https://Stackoverflow.com/users/28921", "pm_score": 2, "selected": false, "text": "<p>Try to use</p>\n\n<pre><code>java -Dfile.encoding=UTF-8 ...\n</code></pre>\n\n<p>when starting the application in both systems.</p>\n\n<p>Another way to solve the problem is to change the encoding from both system to UTF-8, but i prefer the first option (less intrusive on the system).</p>\n\n<p>EDIT:</p>\n\n<p>Check this answer on stackoverflow, It might help either:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/81323/changing-the-default-encoding-for-stringbyte\">Changing the default encoding for String(byte[])</a></p>\n" }, { "answer_id": 250947, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 0, "selected": false, "text": "<p>You can also set the encoding at the command line, like so <code>java -Dfile.encoding=utf-8</code>.</p>\n" }, { "answer_id": 251286, "author": "Alan Moore", "author_id": 20938, "author_profile": "https://Stackoverflow.com/users/20938", "pm_score": 2, "selected": false, "text": "<p>That looks like a file that was converted by <code>native2ascii</code> using the wrong parameters. To demonstrate, create a file with the contents</p>\n\n<pre><code>Gérer les modÚ\n</code></pre>\n\n<p>and save it as \"a.txt\" with the encoding UTF-8. Then run this command:</p>\n\n<pre><code>native2ascii -encoding windows-1252 a.txt b.txt\n</code></pre>\n\n<p>Open the new file and you should see this:</p>\n\n<pre><code>G\\u00c3\\u00a9rer les mod\\u00c3\\u0161\n</code></pre>\n\n<p>Now reverse the process, but specify ISO-8859-1 this time:</p>\n\n<pre><code>native2ascii -reverse -encoding ISO-8859-1 b.txt c.txt\n</code></pre>\n\n<p>Read the new file as UTF-8 and you should see this:</p>\n\n<pre><code>Gérer les modÀ\\u0161\n</code></pre>\n\n<p>It recovers the \"é\" okay, but chokes on the \"Ú\", like your app did. </p>\n\n<p>I don't know what all is going wrong in your app, but I'm pretty sure incorrect use of native2ascii is part of it. And that was probably the result of letting the app use the system default encoding. You should always specify the encoding when you save text, whether it's to a file or a database or what--never let it default. And if you don't have a good reason to choose something else, use UTF-8.</p>\n" }, { "answer_id": 252146, "author": "Dov Wasserman", "author_id": 26010, "author_profile": "https://Stackoverflow.com/users/26010", "pm_score": 1, "selected": false, "text": "<p>Instead of setting the system-wide character encoding, it might be easier and more robust, to specify the character encoding when reading and writing specific text data. How is your application reading the files? All the Java I/O package readers and writers support passing in a character encoding name to be used when reading/writing text to/from bytes. If you don't specify one, it will then use the platform default encoding, as you are likely experiencing.</p>\n\n<p>Some databases are surprisingly limited in the text encodings they can accept. If your Java application reads the files as text, in the proper encoding, then it can output it to the database however it needs it. If your database doesn't support any encoding whose character repetoire includes the non-ASCII characters you have, then you may need to encode your non-English text first, for example into UTF-8 bytes, then Base64 encode those bytes as ASCII text.</p>\n\n<p>PS: Never use <code>String.getBytes()</code> with no character encoding argument for exactly the reasons you are seeing.</p>\n" }, { "answer_id": 252280, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 0, "selected": false, "text": "<p>I think we'll need more information to be able to help you with your problem:</p>\n\n<ol>\n<li>What exception are you getting exactly, and which method are you calling when it occurs.</li>\n<li>What is the encoding of the input file? UTF8? UTF16/Unicode? ISO8859-1?</li>\n</ol>\n\n<p>It'll also be helpful if you could provide us with relevant code snippets.</p>\n\n<p>Also, a few things I want to point out:</p>\n\n<ol>\n<li>The problem isn't occurring at the 'é' but later on.</li>\n<li>It sounds like the character encoding may be hard coded in your application somewhere.</li>\n</ol>\n" }, { "answer_id": 252350, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 0, "selected": false, "text": "<p>Also, you may want to verify that operating system packages to support UTF-8 (SUNWeulux, SUNWeuluf etc) are installed.</p>\n" }, { "answer_id": 253255, "author": "Scottm", "author_id": 22061, "author_profile": "https://Stackoverflow.com/users/22061", "pm_score": 1, "selected": false, "text": "<p>I managed to get past this error by running the command </p>\n\n<pre>export LC_ALL='en_GB.UTF-8'</pre>\n\n<p>This command set the locale for the shell that I was in. This set all of the LC_ environment variables to the Unicode file encoding.</p>\n\n<p>Many thanks for all of your suggestions. </p>\n" }, { "answer_id": 2895105, "author": "mohitsoni", "author_id": 154917, "author_profile": "https://Stackoverflow.com/users/154917", "pm_score": 0, "selected": false, "text": "<p>Java uses operating system's default encoding while reading and writing files. Now, one should never rely on that. It's always a good practice to specify the encoding explicitly.</p>\n\n<p>In Java you can use following for reading and writing:</p>\n\n<p>Reading:</p>\n\n<pre><code>BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(inputPath),\"UTF-8\"));\n</code></pre>\n\n<p>Writing:</p>\n\n<pre><code>PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputPath), \"UTF-8\")));\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22061/" ]
An application I am working on reads information from files to populate a database. Some of the characters in the files are non-English, for example accented French characters. The application is working fine in Windows but on our Solaris machine it is failing to recognise the special characters and is throwing an exception. For example when it encounters the accented e in "Gérer" it says :- ``` Encountered: "\u0161" (353), after : "\'G\u00c3\u00a9rer les mod\u00c3" ``` (an exception which is thrown from our application) I suspect that in order to stop this from happening I need to change the file.encoding property of the JVM. I tried to do this via System.setProperty() but it has not stopped the error from occurring. Are there any suggestions for what I could do? I was thinking about setting the basic locale of the solaris platform in /etc/default/init to be UTF-8. Does anyone think this might help? Any thoughts are much appreciated.
Try to use ``` java -Dfile.encoding=UTF-8 ... ``` when starting the application in both systems. Another way to solve the problem is to change the encoding from both system to UTF-8, but i prefer the first option (less intrusive on the system). EDIT: Check this answer on stackoverflow, It might help either: [Changing the default encoding for String(byte[])](https://stackoverflow.com/questions/81323/changing-the-default-encoding-for-stringbyte)
250,931
<p>I have some HTML that displays fine on FireFox3/Opera/Safari but not with IE7. The snippet is as follows:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt;&lt;/head&gt; &lt;body bgcolor="#AA5566" &gt; &lt;table width="100%"&gt; &lt;tr&gt; &lt;td height="37" valign="top"&gt;&lt;img style="float:right;" border="0" src="foo.png" width="37" height="37"/&gt;&lt;/td&gt; &lt;td width="600" rowspan="2" &gt; &lt;table width="600" height="800"&gt;&lt;tr&gt;&lt;td&gt;&lt;img src="bar.jpg" width="600" height="800"/&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt; &lt;/td&gt; &lt;td height="37" valign="top"&gt;&lt;img style="float:left;" border="0" src="foo.png" width="37" height="37"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;!-- This row doesnt fill the vertical space on IE7 //--&gt; &lt;tr&gt; &lt;td valign="top" bgcolor="#112233"&gt;&amp;nbsp;&lt;/td&gt; &lt;td valign="top" bgcolor="#112233"&gt;&amp;nbsp;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; </code></pre> <p>The second row wont fill the vertical space created by the first rows middle column (notice the rowspan="2") correctly. Instead the first rows 1st and 3rd columns expand down even though I set their height to 37. The image below shows what happens in IE7 and Firefox3...</p> <p><img src="https://i.stack.imgur.com/DpxMK.png" alt="alt text"></p> <p>EDIT: added the HTML doc type to the code snippit. Added a screenshot.</p> <p>Any help appreciated, thanks :)</p>
[ { "answer_id": 251049, "author": "Andrew Bullock", "author_id": 28543, "author_profile": "https://Stackoverflow.com/users/28543", "pm_score": 0, "selected": false, "text": "<p>I'm not quite sure why that is happening. What layout are you trying to achieve, does it really need to be a table? You shouldn't layout pages with tables, they should only be used for true tabular data.</p>\n\n<p>Have you considered using divs?</p>\n" }, { "answer_id": 251217, "author": "Steve Perks", "author_id": 16124, "author_profile": "https://Stackoverflow.com/users/16124", "pm_score": 0, "selected": false, "text": "<p>Throw it through a <a href=\"http://validator.w3.org/check\" rel=\"nofollow noreferrer\">validator</a> and I'm sure you'll get a little closer.</p>\n\n<p>Actually - what you're seeing is normal behavour for IE: add border=\"1\" to your main table and it'll show you what's happening a little clearer.</p>\n" }, { "answer_id": 251291, "author": "postback", "author_id": 32849, "author_profile": "https://Stackoverflow.com/users/32849", "pm_score": 2, "selected": false, "text": "<p>The right answer would be: don't layout your page using tables.</p>\n\n<p>The technical answer would be: your table cells are doing what they are supposed to do, i.e. you can't solve your problem with the code structure you use.</p>\n\n<p>The hacky answer would be: having the cells on the left and right to be exactly 37px high, you'll have to add 2 additional nested tables in the left and right cell.</p>\n" }, { "answer_id": 251315, "author": "Eli", "author_id": 27580, "author_profile": "https://Stackoverflow.com/users/27580", "pm_score": 3, "selected": true, "text": "<p>What if you try it like this:</p>\n\n<pre><code>&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\"&gt;\n&lt;head&gt;&lt;/head&gt;\n &lt;body bgcolor=\"#AA5566\" &gt;\n &lt;table width=\"100%\" border='1'&gt;\n\n &lt;tr&gt;\n\n &lt;td valign=\"top\"&gt;\n &lt;table bgcolor=\"#112233\" height=\"37\" width='100%'&gt;&lt;tr&gt;&lt;td&gt;asdf&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;br /&gt;\n Other content\n &lt;/td&gt;\n\n &lt;td width=\"600\" rowspan=\"2\" &gt;\n &lt;table width=\"600\" height=\"800\"&gt;&lt;tr&gt;&lt;td&gt;asdf&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;\n &lt;/td&gt;\n\n &lt;td valign=\"top\"&gt;\n &lt;table bgcolor=\"#112233\" height=\"37\" width='100%'&gt;&lt;tr&gt;&lt;td&gt;asdf&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;br /&gt;\n Other content\n &lt;/td&gt;\n\n &lt;/tr&gt;\n\n\n\n &lt;/table&gt;\n &lt;/body&gt;\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14260/" ]
I have some HTML that displays fine on FireFox3/Opera/Safari but not with IE7. The snippet is as follows: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head></head> <body bgcolor="#AA5566" > <table width="100%"> <tr> <td height="37" valign="top"><img style="float:right;" border="0" src="foo.png" width="37" height="37"/></td> <td width="600" rowspan="2" > <table width="600" height="800"><tr><td><img src="bar.jpg" width="600" height="800"/></td></tr></table> </td> <td height="37" valign="top"><img style="float:left;" border="0" src="foo.png" width="37" height="37"/></td> </tr> <!-- This row doesnt fill the vertical space on IE7 //--> <tr> <td valign="top" bgcolor="#112233">&nbsp;</td> <td valign="top" bgcolor="#112233">&nbsp;</td> </tr> </table> </body> ``` The second row wont fill the vertical space created by the first rows middle column (notice the rowspan="2") correctly. Instead the first rows 1st and 3rd columns expand down even though I set their height to 37. The image below shows what happens in IE7 and Firefox3... ![alt text](https://i.stack.imgur.com/DpxMK.png) EDIT: added the HTML doc type to the code snippit. Added a screenshot. Any help appreciated, thanks :)
What if you try it like this: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head></head> <body bgcolor="#AA5566" > <table width="100%" border='1'> <tr> <td valign="top"> <table bgcolor="#112233" height="37" width='100%'><tr><td>asdf</td></tr></table><br /> Other content </td> <td width="600" rowspan="2" > <table width="600" height="800"><tr><td>asdf</td></tr></table> </td> <td valign="top"> <table bgcolor="#112233" height="37" width='100%'><tr><td>asdf</td></tr></table><br /> Other content </td> </tr> </table> </body> ```
250,932
<p>I have a hyper link like this :</p> <pre><code>&lt;A Href=My_Java_Servlet?User_Action=Admin_Download_Records&amp;User_Id=Admin onClick=\"Check_Password();\" target=_blank&gt;Download Records&lt;/A&gt; </code></pre> <p>When a user clicks on it, a password window will open, the user can try 3 times for the right password.</p> <p>The Javascript looks like this :</p> <pre><code>&lt;Script Language="JavaScript"&gt; function Check_Password() { var testV=1; var pass1=prompt('Password',''); while (testV&lt;3) { if (!pass1) history.go(-1); if (pass1=="password") { return true; } testV+=1; var pass1=prompt('Access Denied - Password Incorrect.',''); } return "false"; } &lt;/Script&gt; </code></pre> <p>If user enters the wrong password 3 times, it's supposed to not do anything, but it still opens a new window and displays the protected info, how to fix the javascript or my html hyper link so only the right password will open a new target window, a wrong password will make it do nothing ?</p>
[ { "answer_id": 250941, "author": "Geo", "author_id": 31610, "author_profile": "https://Stackoverflow.com/users/31610", "pm_score": 0, "selected": false, "text": "<p>Why are you returning <strong>\"false\"</strong> instead of <strong>false</strong> ?</p>\n" }, { "answer_id": 250943, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 1, "selected": false, "text": "<p>You might to try returning <code>false</code> rather than <code>\"false\"</code></p>\n\n<p>However, you might be better off doing this kind of thing on the server, as I'd image all but novice users will know how to \"copy link address\" and paste this into their address bar.</p>\n" }, { "answer_id": 250954, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 4, "selected": false, "text": "<p>Clientside JavaScript is perhaps the worst possible way to provide \"security\". Users can just view the source to see all of your passwords, or just disable JavaScript altogether. <strong>Do not do this.</strong></p>\n" }, { "answer_id": 250972, "author": "Lance McNearney", "author_id": 25549, "author_profile": "https://Stackoverflow.com/users/25549", "pm_score": 3, "selected": false, "text": "<p>Other people have answered your question with the true/false return value but here's some of the problems with the whole idea of checking the password in javascript on the client:</p>\n\n<ol>\n<li><p>Your javascript source is freely readable by anyone downloading the page - thus showing them the password needed to view the page.</p></li>\n<li><p>If they don't have javascript enabled then they'll just go straight to the page without getting the javascript prompt.</p></li>\n<li><p>They could always just copy the link and paste it into their address bar to bypass the password protection. They could also just middle-click the link (which should open it in a new tab/window depending on their browser.)</p></li>\n</ol>\n\n<p>Even on a private/intranet-only application this would be a laughable security method. :) Please consider re-desinging it so that the password is checked on the server-side portion (like when someone attempts to access the servlet it would render a password box and then post that password back to the server and then allow/deny access.)</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32834/" ]
I have a hyper link like this : ``` <A Href=My_Java_Servlet?User_Action=Admin_Download_Records&User_Id=Admin onClick=\"Check_Password();\" target=_blank>Download Records</A> ``` When a user clicks on it, a password window will open, the user can try 3 times for the right password. The Javascript looks like this : ``` <Script Language="JavaScript"> function Check_Password() { var testV=1; var pass1=prompt('Password',''); while (testV<3) { if (!pass1) history.go(-1); if (pass1=="password") { return true; } testV+=1; var pass1=prompt('Access Denied - Password Incorrect.',''); } return "false"; } </Script> ``` If user enters the wrong password 3 times, it's supposed to not do anything, but it still opens a new window and displays the protected info, how to fix the javascript or my html hyper link so only the right password will open a new target window, a wrong password will make it do nothing ?
Clientside JavaScript is perhaps the worst possible way to provide "security". Users can just view the source to see all of your passwords, or just disable JavaScript altogether. **Do not do this.**
250,937
<p>I have a very simple ASP.Net page that acts as a front end for a stored procedure. It just runs the procedure and shows the output using a gridview control: less than 40 lines of total code, including aspx markup. The stored procedure itself is very... volatile. It's used for a number of purposes and the output format changes regularly. </p> <p>The whole thing works great, because the gridview control doesn't really need to care what columns the stored procedure returns: it just shows them on the page, which is exactly what I want.</p> <p>However, the database this runs against has a number of datetime columns all over the place where the time portion isn't really important- it's always zeroed out. What I would like to be able to do is control the formatting of just the datetime columns in the gridview, without ever knowing precisely which columns those will be. Any time a column in the results has a datetime type, just apply a given format string that will trim off the time component.</p> <p>I know I could convert to a varchar at the database, but I'd really don't want to have to make developers care about formatting in the query and this belongs at the presentation level anyway. Any other ideas?</p> <hr> <p>Finally got this working in an acceptable (or at least improved) way using this code:</p> <pre><code>Protected Sub OnRowDatabound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) If e.Row.RowType = DataControlRowType.DataRow Then Dim d As DateTime For Each cell As TableCell In e.Row.Cells If Date.TryParse(cell.Text, d) AndAlso d.TimeOfDay.Ticks = 0 Then cell.Text = d.ToShortDateString() End If Next cell End If End Sub </code></pre>
[ { "answer_id": 250958, "author": "Mischa Kroon", "author_id": 30600, "author_profile": "https://Stackoverflow.com/users/30600", "pm_score": 0, "selected": false, "text": "<p>You can use the isDate() function to see if something is a valid date and then use dateformatting options to make it look like you want.</p>\n\n<p>Some examples for date formating:\n<a href=\"http://datawebcontrols.com/faqs/CustomizingAppearance/FormatDateTimeData.shtml\" rel=\"nofollow noreferrer\">http://datawebcontrols.com/faqs/CustomizingAppearance/FormatDateTimeData.shtml</a></p>\n" }, { "answer_id": 250960, "author": "Robert", "author_id": 27412, "author_profile": "https://Stackoverflow.com/users/27412", "pm_score": 3, "selected": true, "text": "<p>If you are auto generating the columns which it sounds like you are. The procedure for using the grids formatting is awful.</p>\n\n<p>You would need to loop through all the columns of the grid, probably in the databound event and apply a formatting expression to any column you find is a date column.</p>\n\n<p>If you are not auto generating and you are hadcoding columns in your grid you will also know alreayd which columns are date columns and you can apply the same format expression to that column. It's something like {0:ddMMyyyy} but you will have to look it up as that's probably not quite right.</p>\n\n<p>so to summarise hook into the databound event. loop through the column collection and ascertain if the column is a date column. I wonder how you might do this :). If you decide a column is a date column set its format expression. </p>\n\n<p>Voila</p>\n\n<p>---------------------- EDIT</p>\n\n<p>Ok how about you write you method that returns the data from the proc to return a datatable. You can bind the datatable to your grid after formatting the data in the datatable. The datatable.Columns collection is a colection of DataColumns and these have a DataType property. You may be looking for System.DateTime or DateTime and it may be one of the properties of the DataType property itself :). I know it's cumbersome but what you are asking is definitly going to be cumbersome. Once you've identified date columns you may be able to do something with it.</p>\n\n<p>If not i'd start looking at the data readers and see if there's anything you can do there or with data adapters. I wish I could give you a proper answer but i think however you manage to do it, it's not going to be pretty. Sorry</p>\n" }, { "answer_id": 250963, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 2, "selected": false, "text": "<p>if using explicit bound columns is an option, add a DataFormatString to your boundField</p>\n\n<pre><code>&lt;asp:BoundField DataField=\"Whatever\" ... DataFormatString=\"{0:dd/MM/yyyy}\" HtmlEncode=\"False\"/ &gt; \n</code></pre>\n\n<p>otherwise you could look at doing the formatting the GridView.OnRowDataBound event</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ]
I have a very simple ASP.Net page that acts as a front end for a stored procedure. It just runs the procedure and shows the output using a gridview control: less than 40 lines of total code, including aspx markup. The stored procedure itself is very... volatile. It's used for a number of purposes and the output format changes regularly. The whole thing works great, because the gridview control doesn't really need to care what columns the stored procedure returns: it just shows them on the page, which is exactly what I want. However, the database this runs against has a number of datetime columns all over the place where the time portion isn't really important- it's always zeroed out. What I would like to be able to do is control the formatting of just the datetime columns in the gridview, without ever knowing precisely which columns those will be. Any time a column in the results has a datetime type, just apply a given format string that will trim off the time component. I know I could convert to a varchar at the database, but I'd really don't want to have to make developers care about formatting in the query and this belongs at the presentation level anyway. Any other ideas? --- Finally got this working in an acceptable (or at least improved) way using this code: ``` Protected Sub OnRowDatabound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) If e.Row.RowType = DataControlRowType.DataRow Then Dim d As DateTime For Each cell As TableCell In e.Row.Cells If Date.TryParse(cell.Text, d) AndAlso d.TimeOfDay.Ticks = 0 Then cell.Text = d.ToShortDateString() End If Next cell End If End Sub ```
If you are auto generating the columns which it sounds like you are. The procedure for using the grids formatting is awful. You would need to loop through all the columns of the grid, probably in the databound event and apply a formatting expression to any column you find is a date column. If you are not auto generating and you are hadcoding columns in your grid you will also know alreayd which columns are date columns and you can apply the same format expression to that column. It's something like {0:ddMMyyyy} but you will have to look it up as that's probably not quite right. so to summarise hook into the databound event. loop through the column collection and ascertain if the column is a date column. I wonder how you might do this :). If you decide a column is a date column set its format expression. Voila ---------------------- EDIT Ok how about you write you method that returns the data from the proc to return a datatable. You can bind the datatable to your grid after formatting the data in the datatable. The datatable.Columns collection is a colection of DataColumns and these have a DataType property. You may be looking for System.DateTime or DateTime and it may be one of the properties of the DataType property itself :). I know it's cumbersome but what you are asking is definitly going to be cumbersome. Once you've identified date columns you may be able to do something with it. If not i'd start looking at the data readers and see if there's anything you can do there or with data adapters. I wish I could give you a proper answer but i think however you manage to do it, it's not going to be pretty. Sorry
250,970
<p>The object I’m working on is instantiated in JavaScript, but used in VBScript. In one code path, the variable <code>M.DOM.IPt</code> is defined and has a value, in the other however it is not. I need to detect if it has been defined or not. I checked that <code>M.DOM</code> is defined and accessable in both code paths. Every test I have tried simply results in this error:</p> <blockquote> <p>Error: Object doesn't support this property or method</p> </blockquote> <p>I have tried:</p> <ul> <li><code>IsEmpty(M.DOM.IPt)</code></li> <li><code>M.DOM.IPt is Nothing</code></li> <li><code>isNull(M.DOM.IPt)</code></li> </ul> <p>Is there any way to detect the variable isn’t defined and avoid the error?</p> <p>Note: I can put <code>On Error Resume Next</code> in and it will simply ignore the error, but I actually need to detect it and conditionally do something about it.</p>
[ { "answer_id": 251062, "author": "Joseph Bui", "author_id": 3275, "author_profile": "https://Stackoverflow.com/users/3275", "pm_score": 0, "selected": false, "text": "<p>Have you tried On Error Goto label?</p>\n" }, { "answer_id": 251107, "author": "Arvo", "author_id": 35777, "author_profile": "https://Stackoverflow.com/users/35777", "pm_score": 1, "selected": false, "text": "<pre><code>On Error Resume Next\nErr.Clear\nMyVariable=M.DOM.Ipt\nIf Err.Number&lt;&gt; 0 Then\n 'error occured - Ipt not defined\n 'do your processing here\nElse\n 'no error - Ipt is defined\n 'do your processing here\nEnd If\n</code></pre>\n" }, { "answer_id": 251125, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": true, "text": "<pre>\n Function SupportsMember(object, memberName)\n On Error Resume Next\n\n Dim x\n Eval(\"x = object.\"+memberName)\n\n If Err = 438 Then \n SupportsMember = False\n Else \n SupportsMember = True\n End If\n\n On Error Goto 0 'clears error\n End Function\n</pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/80/" ]
The object I’m working on is instantiated in JavaScript, but used in VBScript. In one code path, the variable `M.DOM.IPt` is defined and has a value, in the other however it is not. I need to detect if it has been defined or not. I checked that `M.DOM` is defined and accessable in both code paths. Every test I have tried simply results in this error: > > Error: Object doesn't support this property or method > > > I have tried: * `IsEmpty(M.DOM.IPt)` * `M.DOM.IPt is Nothing` * `isNull(M.DOM.IPt)` Is there any way to detect the variable isn’t defined and avoid the error? Note: I can put `On Error Resume Next` in and it will simply ignore the error, but I actually need to detect it and conditionally do something about it.
``` Function SupportsMember(object, memberName) On Error Resume Next Dim x Eval("x = object."+memberName) If Err = 438 Then SupportsMember = False Else SupportsMember = True End If On Error Goto 0 'clears error End Function ```
250,973
<p>I wanted to write a Visual Studio Macro or something similar which can fetch function name and insert into preset location in the error report part. It's clearer if you look at the example</p> <pre><code>Class SampleClass { public void FunctionA() { try { //Do some work here } catch (Exception ex) { Logger.WriteLine(LogLevelEnum.Error, "SampleClass", "FunctionA Failed"); Logger.WriteLine(LogLevelEnum.Error, "FunctionA", ex.ToString()); } finally { } } } </code></pre> <p>So, I followed the similar pattern of most of the critical functions of my common library. I would like to be able to insert "FunctionA" into the logging section during pre-built so that I don't have to remember to type in the right name or forgetting to rename it after copy and paste. Either that can be invoke manually from the toolbar or via shortcut key.</p> <p>So, where should I start?</p> <p>NOTE: I'm considered intermediate in .Net, been writting in C# and VB for more than 3 years, but I'm fresh on Macro, don't mind to learn though. Don't worry about the code itself and the exception, this is just an example.</p> <p>EDIT: Thanks Ovidiu Pacurar and cfeduke. What I wanted here was a one off way to change-and-forget. PostSharp will incur overhead on every one of those function, even when exception is not thrown. Digging from the stacktrace is feasible, but at some point I would also like to just log "FunctionA Failed" without spending too much processing in getting the stacktrace. Further more, if the library is obfuscated, the stacktrace would be cryptic.</p> <p>Actually there was another need for this feature, which I forgot to mention earlier. When the library is ready to be delivered, I would want to change all the function name into function code, "FunctionA" might be "0001", by referring to a table, so as to solve the "obfuscated" log problem.</p>
[ { "answer_id": 251001, "author": "Ovidiu Pacurar", "author_id": 28419, "author_profile": "https://Stackoverflow.com/users/28419", "pm_score": 1, "selected": false, "text": "<p>Take a look at System.Diagnostics.StackTrace and then you can create just one log call getting the function from the stack. </p>\n" }, { "answer_id": 251038, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 0, "selected": false, "text": "<p>Look at <a href=\"http://www.postsharp.org/about/features/\" rel=\"nofollow noreferrer\">PostSharp</a>. It allows you do this with very easy way and much more.</p>\n\n<p>There is samples with loging too.</p>\n" }, { "answer_id": 251042, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 1, "selected": false, "text": "<p>I wish C# had <code>__FILE__</code> and <code>__LINE__</code>-like macros but it doesn't. You can, however, post-compile process C# using <a href=\"http://www.postsharp.org\" rel=\"nofollow noreferrer\">PostSharp</a>. This has the advantage of not having to invoke the overhead of a stack trace to get a method name at runtime. The performance overhead may not be something you are concerned about during an exception handler, but in any case PostSharp is another tool which is available that can perform the job.</p>\n\n<p>The example video for PostSharp does something similar to what you are attempting to do. Take a look at this sample code right off the front page of the PostSharp site to get your gears turning:</p>\n\n<pre><code>public class SimplestTraceAttribute : OnMethodBoundaryAspect\n{\n public override void OnEntry( MethodExecutionEventArgs eventArgs)\n {\n Trace.TraceInformation(\"Entering {0}.\", eventArgs.Method);\n Trace.Indent();\n }\n public override void OnExit( MethodExecutionEventArgs eventArgs)\n {\n Trace.Unindent();\n Trace.TraceInformation(\"Leaving {0}.\", eventArgs.Method);\n }\n}\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/250973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20007/" ]
I wanted to write a Visual Studio Macro or something similar which can fetch function name and insert into preset location in the error report part. It's clearer if you look at the example ``` Class SampleClass { public void FunctionA() { try { //Do some work here } catch (Exception ex) { Logger.WriteLine(LogLevelEnum.Error, "SampleClass", "FunctionA Failed"); Logger.WriteLine(LogLevelEnum.Error, "FunctionA", ex.ToString()); } finally { } } } ``` So, I followed the similar pattern of most of the critical functions of my common library. I would like to be able to insert "FunctionA" into the logging section during pre-built so that I don't have to remember to type in the right name or forgetting to rename it after copy and paste. Either that can be invoke manually from the toolbar or via shortcut key. So, where should I start? NOTE: I'm considered intermediate in .Net, been writting in C# and VB for more than 3 years, but I'm fresh on Macro, don't mind to learn though. Don't worry about the code itself and the exception, this is just an example. EDIT: Thanks Ovidiu Pacurar and cfeduke. What I wanted here was a one off way to change-and-forget. PostSharp will incur overhead on every one of those function, even when exception is not thrown. Digging from the stacktrace is feasible, but at some point I would also like to just log "FunctionA Failed" without spending too much processing in getting the stacktrace. Further more, if the library is obfuscated, the stacktrace would be cryptic. Actually there was another need for this feature, which I forgot to mention earlier. When the library is ready to be delivered, I would want to change all the function name into function code, "FunctionA" might be "0001", by referring to a table, so as to solve the "obfuscated" log problem.
Take a look at System.Diagnostics.StackTrace and then you can create just one log call getting the function from the stack.
251,030
<p>In <a href="https://stackoverflow.com/questions/226206/alternating-item-style">this question</a>, I was given a really cool answer to alternating an image and its description between left and right, respectively. Now I want to apply styling to both, e.g. padding-top, padding-bottom etc. How do I apply a style to both the RowStyle and AlternatingRowStyle in this scenario.</p> <pre><code>&lt;AlternatingRowStyle CssClass="ProductAltItemStyle" /&gt; &lt;RowStyle CssClass="ProductItemStyle" /&gt; &lt;Columns&gt; &lt;asp:TemplateField&gt; &lt;ItemTemplate&gt; &lt;div class="Image"&gt;&lt;asp:Image runat="server" ID="productImage" ImageUrl='&lt;%# Eval("imageUrl") %&gt;' /&gt;&lt;/div&gt; &lt;div class="Description"&gt;&lt;asp:Label runat="server" ID="lblProductDesc" Width="100%" Text='&lt;%# Eval("productDesc") %&gt;'&gt;&lt;/asp:Label&gt;&lt;/div&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; </code></pre>
[ { "answer_id": 251037, "author": "changelog", "author_id": 5646, "author_profile": "https://Stackoverflow.com/users/5646", "pm_score": 5, "selected": false, "text": "<p>Here's how you do it:</p>\n\n<pre><code>.ProductAltItemStyle, .ProductItemStyle {\n // CSS Rules that apply to both go here\n}</code></pre>\n" }, { "answer_id": 251160, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 3, "selected": true, "text": "<p>Alternatively you can do this:</p>\n\n<pre><code>&lt;AlternatingRowStyle CssClass=\"ProductAltItemStyle ProductCommonStyle\" /&gt; \n&lt;RowStyle CssClass=\"ProductItemStyle ProductCommonStyle\" /&gt;\n</code></pre>\n\n<p>ProductCommonStyle contains formatting that is common to both alternating and standard rows. </p>\n\n<p>Even better, you can assign a style to your whole gridview, and use that to define the shared classes:</p>\n\n<pre><code>table.GridViewStyle tr td\n{\n padding:3px 5px;\n border:1px solid gray;\n}\n\ntr.ProductAltItemStyle td\n{\n background:white;\n}\n\ntr.ProductItemSTyle td\n{\n background:silver;\n}\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]
In [this question](https://stackoverflow.com/questions/226206/alternating-item-style), I was given a really cool answer to alternating an image and its description between left and right, respectively. Now I want to apply styling to both, e.g. padding-top, padding-bottom etc. How do I apply a style to both the RowStyle and AlternatingRowStyle in this scenario. ``` <AlternatingRowStyle CssClass="ProductAltItemStyle" /> <RowStyle CssClass="ProductItemStyle" /> <Columns> <asp:TemplateField> <ItemTemplate> <div class="Image"><asp:Image runat="server" ID="productImage" ImageUrl='<%# Eval("imageUrl") %>' /></div> <div class="Description"><asp:Label runat="server" ID="lblProductDesc" Width="100%" Text='<%# Eval("productDesc") %>'></asp:Label></div> </ItemTemplate> </asp:TemplateField> ```
Alternatively you can do this: ``` <AlternatingRowStyle CssClass="ProductAltItemStyle ProductCommonStyle" /> <RowStyle CssClass="ProductItemStyle ProductCommonStyle" /> ``` ProductCommonStyle contains formatting that is common to both alternating and standard rows. Even better, you can assign a style to your whole gridview, and use that to define the shared classes: ``` table.GridViewStyle tr td { padding:3px 5px; border:1px solid gray; } tr.ProductAltItemStyle td { background:white; } tr.ProductItemSTyle td { background:silver; } ```
251,033
<p>How can I convert a varchar field of the form YYYYMMDD to a datetime in T-SQL?</p> <p>Thank you.</p>
[ { "answer_id": 251045, "author": "bobwienholt", "author_id": 24257, "author_profile": "https://Stackoverflow.com/users/24257", "pm_score": 5, "selected": true, "text": "<pre><code>select convert(datetime, '20081030')\n</code></pre>\n" }, { "answer_id": 251046, "author": "JGW", "author_id": 26288, "author_profile": "https://Stackoverflow.com/users/26288", "pm_score": 0, "selected": false, "text": "<p>Use the CONVERT() function?</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms187928.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms187928.aspx</a></p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
How can I convert a varchar field of the form YYYYMMDD to a datetime in T-SQL? Thank you.
``` select convert(datetime, '20081030') ```
251,090
<p>I like Vim's visual mode. <kbd>v</kbd> for highlight/select chars or lines, <kbd>Ctrl</kbd><kbd>v</kbd> for rectangle highlighting, as far as I know (I am a beginner). Is there any way to use visual mode to highlight last two chars, for example, on each line for some selected lines? The selected lines are in different length. Basically, I would like to find a quick way to remove the last two chars for some selected lines. Not sure I can use visual mode to highlight irregular area.</p>
[ { "answer_id": 251132, "author": "ryan_s", "author_id": 13728, "author_profile": "https://Stackoverflow.com/users/13728", "pm_score": 2, "selected": false, "text": "<p>I can't think of a way to do this in visual mode, but you could use a command like this to do it...</p>\n\n<pre><code>:10,20 normal $xx\n</code></pre>\n\n<p>This would go to each line between line number 10 and 20, use $ to go to the end of the line, and then use x twice to delete two characters. Normal just tells vim to use the following symbols as if they were keyboard shortcuts entered in normal mode (i.e after hitting esc).</p>\n\n<p>Does that help?</p>\n" }, { "answer_id": 251137, "author": "reedstrm", "author_id": 5430, "author_profile": "https://Stackoverflow.com/users/5430", "pm_score": 3, "selected": false, "text": "<p>My approach to this sort of problem is to use line selection (shift-V, cursor movement) to select the lines-of-interest, then type:</p>\n\n<pre><code> :s/..$//\n</code></pre>\n\n<p>That's a substitution, using the regex <code>..$</code> which will match the last two characters at the end of the line. Then substitute 'nothing' i.e. delete.</p>\n\n<p>In vim, once you hit the <code>:</code> with a line selection active, the command prompt will actually show:</p>\n\n<pre><code>:'&lt;,'&gt;\n</code></pre>\n\n<p>Which is the start and end of selection addresses for the next command (s in this case)</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/62776/" ]
I like Vim's visual mode. `v` for highlight/select chars or lines, `Ctrl``v` for rectangle highlighting, as far as I know (I am a beginner). Is there any way to use visual mode to highlight last two chars, for example, on each line for some selected lines? The selected lines are in different length. Basically, I would like to find a quick way to remove the last two chars for some selected lines. Not sure I can use visual mode to highlight irregular area.
My approach to this sort of problem is to use line selection (shift-V, cursor movement) to select the lines-of-interest, then type: ``` :s/..$// ``` That's a substitution, using the regex `..$` which will match the last two characters at the end of the line. Then substitute 'nothing' i.e. delete. In vim, once you hit the `:` with a line selection active, the command prompt will actually show: ``` :'<,'> ``` Which is the start and end of selection addresses for the next command (s in this case)
251,091
<p>I've got a small web form with 2 radio buttons, call them PickFromList and EnterValue. When PickFromList is checked I want to show a GridView that I've configured to bind to an ObjectDataSource. When EnterValue is checked I want the GridView to disappear.</p> <p>This form is laid out using a table and want to hide/show the appropriate rows based on appropriate data and user input. </p> <p>Unfortunately the GridView doesn't bind when the trPickFromList2 row specifies the id and the runat="server" attributes. If I remove id and runat="server" from the trPickFromList2 row it binds successfully.</p> <p>Any ideas?</p> <pre><code>&lt;table id="tblOptions" runat="server"&gt; &lt;tr id="trPickFromList1" runat="server"&gt; &lt;td&gt; &lt;asp:RadioButton ID="rbFromList" runat="server" GroupName="Selection" Text="Get Data From Existing Item" AutoPostBack="True" oncheckedchanged="rbromList_CheckedChanged" /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr id="trPickFromList2" runat="server"&gt; &lt;td style="padding-left:20px"&gt; &lt;asp:GridView ID="gvList" runat="server" AutoGenerateColumns="False" DataSourceID="odsList" Width="400px" onrowdatabound="gvList_RowDataBound"&gt; &lt;Columns&gt; ... &lt;/Columns&gt; &lt;/asp:GridView&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr id="trEnterValue1" runat="server"&gt; &lt;td&gt; &lt;asp:RadioButton ID="rbEnterValue" runat="server" GroupName="Selection" Text="Create a New Item" AutoPostBack="True" oncheckedchanged="rbEntered_CheckedChanged" /&gt; ... </code></pre>
[ { "answer_id": 251170, "author": "the-undefined", "author_id": 32792, "author_profile": "https://Stackoverflow.com/users/32792", "pm_score": 0, "selected": false, "text": "<p>hmm.. not quite sure but something which has got me a few times is have the AutoWireEvents set to false, its at the top in the &lt;% page /%> section. sorry if it's no help, but something annoying and insignificant like that is prob the problem.</p>\n" }, { "answer_id": 251270, "author": "wulimaster", "author_id": 21749, "author_profile": "https://Stackoverflow.com/users/21749", "pm_score": 0, "selected": false, "text": "<p>If the AutoWireEvents answer Joe suggested is not the issue, you could also try removing the runat=server from the tr tags, and instead wrap them with placeholders and use the placeholders to control visibility. (Note, don't use panels, as it will result in invalid html)</p>\n" }, { "answer_id": 251281, "author": "Andrew Bullock", "author_id": 28543, "author_profile": "https://Stackoverflow.com/users/28543", "pm_score": 2, "selected": true, "text": "<p>Why dont you just show/hide the TRs with javascript? That way you won't have this problem and you'll have a much more responsive UI.</p>\n\n<p>With jQuery:</p>\n\n<p>$('.classOnShowRadioButton').click(function(){\n $('.trToShow').show();\n $('.trToHide').hide();\n});</p>\n\n<p>then obviously do the reverse for the other radio button.</p>\n" }, { "answer_id": 251384, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 0, "selected": false, "text": "<p>I <a href=\"http://devio.wordpress.com/2008/04/24/formview-no-update-inside-run-at-server-table-control/\" rel=\"nofollow noreferrer\">noticed the same behavior</a> with a FormView inside a TR tag with runat=\"server\"</p>\n" }, { "answer_id": 251551, "author": "sliderhouserules", "author_id": 31385, "author_profile": "https://Stackoverflow.com/users/31385", "pm_score": 0, "selected": false, "text": "<p>Any particular reason you're using a table for layout? Try taking all your controls out of the table, and make the radio buttons just make the actual GridView visible/invisible.</p>\n" }, { "answer_id": 261835, "author": "marc", "author_id": 12260, "author_profile": "https://Stackoverflow.com/users/12260", "pm_score": 2, "selected": false, "text": "<p>I ended up implementing <a href=\"http://www.wilcob.com/Wilco/News/RowSelectorFieldForGridView.aspx\" rel=\"nofollow noreferrer\">Wilco Bauwer's RowSelectorField control</a> to solve this problem. It's not a perfect solution in that the control surfaces the the selected row's index value rather than the selected data key value(s); however, it worked out well.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12260/" ]
I've got a small web form with 2 radio buttons, call them PickFromList and EnterValue. When PickFromList is checked I want to show a GridView that I've configured to bind to an ObjectDataSource. When EnterValue is checked I want the GridView to disappear. This form is laid out using a table and want to hide/show the appropriate rows based on appropriate data and user input. Unfortunately the GridView doesn't bind when the trPickFromList2 row specifies the id and the runat="server" attributes. If I remove id and runat="server" from the trPickFromList2 row it binds successfully. Any ideas? ``` <table id="tblOptions" runat="server"> <tr id="trPickFromList1" runat="server"> <td> <asp:RadioButton ID="rbFromList" runat="server" GroupName="Selection" Text="Get Data From Existing Item" AutoPostBack="True" oncheckedchanged="rbromList_CheckedChanged" /> </td> </tr> <tr id="trPickFromList2" runat="server"> <td style="padding-left:20px"> <asp:GridView ID="gvList" runat="server" AutoGenerateColumns="False" DataSourceID="odsList" Width="400px" onrowdatabound="gvList_RowDataBound"> <Columns> ... </Columns> </asp:GridView> </td> </tr> <tr id="trEnterValue1" runat="server"> <td> <asp:RadioButton ID="rbEnterValue" runat="server" GroupName="Selection" Text="Create a New Item" AutoPostBack="True" oncheckedchanged="rbEntered_CheckedChanged" /> ... ```
Why dont you just show/hide the TRs with javascript? That way you won't have this problem and you'll have a much more responsive UI. With jQuery: $('.classOnShowRadioButton').click(function(){ $('.trToShow').show(); $('.trToHide').hide(); }); then obviously do the reverse for the other radio button.
251,110
<p>I tried this:</p> <pre><code>ALTER TABLE My.Table DROP MyField </code></pre> <p>and got this error:</p> <p>-MyField is not a constraint.</p> <p>-Could not drop constraint. See previous errors.</p> <p>There is just one row of data in the table and the field was just added.</p> <p><strong>EDIT:</strong> Just to follow up, the sql was missing COLUMN indeed. Now I get even more seriously looking errors though:</p> <ul> <li>The object 'some_object__somenumbers' is dependent on column 'MyField'</li> <li>ALTER TABLE DROP COLUMN MyField failed because one or more objects access this column.</li> </ul> <p><strong>EDIT:</strong></p> <pre><code>ALTER TABLE TableName DROP Constraint ConstraintName </code></pre> <p>worked, after that I was able to use the previous code to remove the column. Credit goes to both of you, thanks.</p>
[ { "answer_id": 251114, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 3, "selected": false, "text": "<p>I think you are just missing the COLUMN keyword:</p>\n\n<pre><code>ALTER TABLE TableName DROP COLUMN ColumnName\n</code></pre>\n\n<p>You will also need to make sure that any constraint that is depending on ColumnName is dropped first. </p>\n\n<p>You can do this by:</p>\n\n<pre><code>ALTER TABLE TableName DROP ConstraintName\n</code></pre>\n\n<p>For each constraint that you have. </p>\n\n<p>If you have indexes based on the column, you will also need to drop those indexes first.</p>\n\n<pre><code>DROP INDEX TableName.IndexName\n</code></pre>\n" }, { "answer_id": 251184, "author": "Lance McNearney", "author_id": 25549, "author_profile": "https://Stackoverflow.com/users/25549", "pm_score": 3, "selected": true, "text": "<p>Brian solved your original problem - for your new problem (The object 'some_object__somenumbers' is dependent on column 'MyField') it means you have a dependancy issue. Something like an index, foreign key reference, default value, etc. To drop the constraint use:</p>\n\n<pre><code>ALTER TABLE TableName DROP ConstraintName\n</code></pre>\n\n<p>Also - you'll need to drop all the constraints dependant on that column before it'll let you drop the column itself.</p>\n" }, { "answer_id": 2537365, "author": "SAI", "author_id": 304137, "author_profile": "https://Stackoverflow.com/users/304137", "pm_score": 0, "selected": false, "text": "<pre><code>ALTER TABLE TABLE_NAME ADD COLUMN SR_NO INTEGER(10)NOT NULL;\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2631856/" ]
I tried this: ``` ALTER TABLE My.Table DROP MyField ``` and got this error: -MyField is not a constraint. -Could not drop constraint. See previous errors. There is just one row of data in the table and the field was just added. **EDIT:** Just to follow up, the sql was missing COLUMN indeed. Now I get even more seriously looking errors though: * The object 'some\_object\_\_somenumbers' is dependent on column 'MyField' * ALTER TABLE DROP COLUMN MyField failed because one or more objects access this column. **EDIT:** ``` ALTER TABLE TableName DROP Constraint ConstraintName ``` worked, after that I was able to use the previous code to remove the column. Credit goes to both of you, thanks.
Brian solved your original problem - for your new problem (The object 'some\_object\_\_somenumbers' is dependent on column 'MyField') it means you have a dependancy issue. Something like an index, foreign key reference, default value, etc. To drop the constraint use: ``` ALTER TABLE TableName DROP ConstraintName ``` Also - you'll need to drop all the constraints dependant on that column before it'll let you drop the column itself.
251,115
<p>I am working on a project where I search through a large text file (large is relative, file size is about 1 Gig) for a piece of data. I am looking for a token and I want a dollar value immediately after that token. For example,</p> <p>this is the token 9,999,999.99</p> <p>So here's is how I am approaching this problem. After a little analysis it appears that the token is usually near the end of the file so I thought I would start searching from the end of the file. Here is the code I have so far (vb.net):</p> <pre><code> Dim sToken As String = "This is a token" Dim sr As New StreamReader(sFileName_IN) Dim FileSize As Long = GetFileSize(sFileName_IN) Dim BlockSize As Integer = CInt(FileSize / 1000) Dim buffer(BlockSize) As Char Dim Position As Long = -BlockSize Dim sBuffer As String Dim CurrentBlock As Integer = 0 Dim Value As Double Dim i As Integer Dim found As Boolean = False While Not found And CurrentBlock &lt; 1000 CurrentBlock += 1 Position = -CurrentBlock * BlockSize sr.BaseStream.Seek(Position, SeekOrigin.End) i = sr.ReadBlock(buffer, 0, BlockSize) sBuffer = New String(buffer) found = SearchBuffer(sBuffer, sToken, Value) End While </code></pre> <p>GetFileSize is a function that returns the filesize. SearchBuffer is a function that will search a string for the token. I am not familiar with regular expressions but will explore it for that function.</p> <p>Basically I read in a small chunk of the file search it and if I don't find it load another chunk and so on...</p> <p>Am I on the right track or is there a better way? </p>
[ { "answer_id": 251131, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 2, "selected": false, "text": "<p>I think you've got the right idea in chunking the file. You may want to read chunks in at line breaks rather than a set number of bytes, though. In your current implementation, if the token lies on a 1000 byte boundary it could get cut in half, preventing you from finding it. The same thing could cause the data to be cut off as well.</p>\n" }, { "answer_id": 251166, "author": "Will Dean", "author_id": 987, "author_profile": "https://Stackoverflow.com/users/987", "pm_score": 0, "selected": false, "text": "<p>If you're going to use chunks, it would be wise to use blocks which are multiples of 512 bytes long, and seek on a 512 byte alignment, because that will tend to be more efficient in accessing the disk (which ultimately will be in 512 byte blocks).</p>\n\n<p>There may be other granularities even better than that, but 512 would be a good start.</p>\n" }, { "answer_id": 251178, "author": "Will Dean", "author_id": 987, "author_profile": "https://Stackoverflow.com/users/987", "pm_score": 0, "selected": false, "text": "<p>If you wanted to do something more complicated but possibly faster, then you could look at reading the blocks asynchronously, so that you're searching one while the next is loading.</p>\n\n<p>That way you get to perform the search at the same time as the data is chugging into memory.</p>\n\n<p>I have to say though that unless your search is very expensive, disk read time will probably completely dominate this, and so complicated overlapping won't be worth the additional complexity.</p>\n" }, { "answer_id": 257722, "author": "Andrei Rînea", "author_id": 1796, "author_profile": "https://Stackoverflow.com/users/1796", "pm_score": 1, "selected": false, "text": "<p>Wait you people...</p>\n\n<p>What if the token is broken between two chunks? Have you considered this?</p>\n" }, { "answer_id": 9757796, "author": "Yes Man", "author_id": 1231202, "author_profile": "https://Stackoverflow.com/users/1231202", "pm_score": 0, "selected": false, "text": "<p>You could always search through the file using a FileStream (or continue doing it your way, your choice). If you decide to use the FileStream approach then what you would want to do is something like this:</p>\n\n<pre><code>Dim stream As New FileStream(\"something.txt\")\nDim findBytes As [Byte]() = BitConverter.GetBytes(\"whatever\")\nDim f As Integer = 0\n\n' remaining = Length - Position\nWhile stream.Length - stream.Position &gt; 0\n If stream.ReadByte() = findBytes(f) Then\n If ++f &gt;= findBytes.Length Then\n Console.WriteLine(stream.Position)\n Exit While\n End If\n Else\n f = 0\n End If\nEnd While\n</code></pre>\n\n<p>Just to note that I used a c# to vb converter because I don't like vb.</p>\n\n<p>The basic idea applies to just searching the block for a string. It's pretty simple if you want to add reading in blocks.</p>\n" }, { "answer_id": 42233484, "author": "Stuart Kearney", "author_id": 7564564, "author_profile": "https://Stackoverflow.com/users/7564564", "pm_score": 0, "selected": false, "text": "<p>\"What if the token is broken between two chunks? Have you considered this?\"</p>\n\n<p>Have done this just recently. I saved the CurrentBlock into a PreviousBlock, before overwriting the CurrentBlock, then marry the two Blocks and check if no joy in finding the search term you are looking for! Works well. The search term can't escape, unless the search term is bigger than the length of the block. </p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am working on a project where I search through a large text file (large is relative, file size is about 1 Gig) for a piece of data. I am looking for a token and I want a dollar value immediately after that token. For example, this is the token 9,999,999.99 So here's is how I am approaching this problem. After a little analysis it appears that the token is usually near the end of the file so I thought I would start searching from the end of the file. Here is the code I have so far (vb.net): ``` Dim sToken As String = "This is a token" Dim sr As New StreamReader(sFileName_IN) Dim FileSize As Long = GetFileSize(sFileName_IN) Dim BlockSize As Integer = CInt(FileSize / 1000) Dim buffer(BlockSize) As Char Dim Position As Long = -BlockSize Dim sBuffer As String Dim CurrentBlock As Integer = 0 Dim Value As Double Dim i As Integer Dim found As Boolean = False While Not found And CurrentBlock < 1000 CurrentBlock += 1 Position = -CurrentBlock * BlockSize sr.BaseStream.Seek(Position, SeekOrigin.End) i = sr.ReadBlock(buffer, 0, BlockSize) sBuffer = New String(buffer) found = SearchBuffer(sBuffer, sToken, Value) End While ``` GetFileSize is a function that returns the filesize. SearchBuffer is a function that will search a string for the token. I am not familiar with regular expressions but will explore it for that function. Basically I read in a small chunk of the file search it and if I don't find it load another chunk and so on... Am I on the right track or is there a better way?
I think you've got the right idea in chunking the file. You may want to read chunks in at line breaks rather than a set number of bytes, though. In your current implementation, if the token lies on a 1000 byte boundary it could get cut in half, preventing you from finding it. The same thing could cause the data to be cut off as well.
251,116
<p>I use Eclipse with "external" projects - i.e. projects created from existing source.</p> <p>Poking around in the workspace files, I cannot find any reference to these projects. My question is: how does Eclipse keep track of these projects?</p> <p>I'd like to be able to add such a project to the workspace automatically (by generating <code>.project</code> and <code>.classpath</code> files).</p>
[ { "answer_id": 251129, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 8, "selected": true, "text": "<p>Windows:</p>\n<pre><code>&lt;workspace&gt;\\.metadata\\.plugins\\org.eclipse.core.resources\\.projects\\\n</code></pre>\n<p>Linux / osx:</p>\n<pre><code>&lt;workspace&gt;/.metadata/.plugins/org.eclipse.core.resources/.projects/\n</code></pre>\n<p>Your project can exist outside the workspace, but all Eclipse-specific <code>metadata</code> are stored in that <code>org.eclipse.core.resources\\.projects</code> directory\nAs noted in <a href=\"https://stackoverflow.com/questions/251116/where-in-an-eclipse-workspace-is-the-list-of-projects-stored/251129?noredirect=1#comment122812680_251129\">the comments</a> by <a href=\"https://stackoverflow.com/users/2344699/tk421storm\">tk421storm</a>, and in <a href=\"https://stackoverflow.com/users/775964/jeegar-patel\">Jeegar Patel</a>'s <a href=\"https://stackoverflow.com/a/24114078/6309\">answer</a>:</p>\n<blockquote>\n<p>In order for manual changes to take effect, make sure to do <code>File -&gt; Refresh</code> afterwards.</p>\n</blockquote>\n" }, { "answer_id": 251163, "author": "Dave DiFranco", "author_id": 30547, "author_profile": "https://Stackoverflow.com/users/30547", "pm_score": 3, "selected": false, "text": "<p>In Eclipse 3.3:</p>\n\n<p>It's installed under your Eclipse workspace. Something like:</p>\n\n<pre><code>.metadata\\.plugins\\org.eclipse.core.resources\\.projects\\\n</code></pre>\n\n<p><strong>within</strong> your workspace folder.</p>\n\n<p>Under that folder is one folder per project.\nThere's a file in there called <em>.location</em>, but it's binary.</p>\n\n<p>So it looks like you can't do what you want, without interacting w/ Eclipse programmatically.</p>\n" }, { "answer_id": 251185, "author": "silverbugg", "author_id": 29650, "author_profile": "https://Stackoverflow.com/users/29650", "pm_score": 0, "selected": false, "text": "<p>You can also have several workspaces - so you can connect to one and have set \"A\" of projects - and then connect to a different set when ever you like. </p>\n" }, { "answer_id": 2429939, "author": "Magne Land", "author_id": 292035, "author_profile": "https://Stackoverflow.com/users/292035", "pm_score": 4, "selected": false, "text": "<p>In Mac OS X, it is under</p>\n\n<pre><code>&lt;workspace&gt;/.metadata/.plugins/org.eclipse.core.resources/.projects\n</code></pre>\n" }, { "answer_id": 10231720, "author": "Sebastian", "author_id": 1344456, "author_profile": "https://Stackoverflow.com/users/1344456", "pm_score": 2, "selected": false, "text": "<p>If you are using Perforce (imported the project as a Perforce project), then .cproject and .project will be located under the root of the PERFORCE project, not on the workspace folder.</p>\n\n<p>Hope this helps :)</p>\n" }, { "answer_id": 24114078, "author": "Jeegar Patel", "author_id": 775964, "author_profile": "https://Stackoverflow.com/users/775964", "pm_score": 1, "selected": false, "text": "<p>In Linux after deleting</p>\n\n<pre><code>&lt;workspace&gt;\\.metadata\\.plugins\\org.eclipse.core.resources\\.projects\\\n</code></pre>\n\n<p>Does not worked.</p>\n\n<p>After that i have done <strong>File->Refresh</strong> </p>\n\n<p>Then it cleared all old project listed from eclipse.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16977/" ]
I use Eclipse with "external" projects - i.e. projects created from existing source. Poking around in the workspace files, I cannot find any reference to these projects. My question is: how does Eclipse keep track of these projects? I'd like to be able to add such a project to the workspace automatically (by generating `.project` and `.classpath` files).
Windows: ``` <workspace>\.metadata\.plugins\org.eclipse.core.resources\.projects\ ``` Linux / osx: ``` <workspace>/.metadata/.plugins/org.eclipse.core.resources/.projects/ ``` Your project can exist outside the workspace, but all Eclipse-specific `metadata` are stored in that `org.eclipse.core.resources\.projects` directory As noted in [the comments](https://stackoverflow.com/questions/251116/where-in-an-eclipse-workspace-is-the-list-of-projects-stored/251129?noredirect=1#comment122812680_251129) by [tk421storm](https://stackoverflow.com/users/2344699/tk421storm), and in [Jeegar Patel](https://stackoverflow.com/users/775964/jeegar-patel)'s [answer](https://stackoverflow.com/a/24114078/6309): > > In order for manual changes to take effect, make sure to do `File -> Refresh` afterwards. > > >
251,117
<p>So yeah, I'm a Java guy in this crazy iPhone world. When it comes to memory management I stiill don't have a very good idea of what I'm doing. </p> <p>I have an app that uses a navigation controller, and when it's time to go on to the next view I have code that looks like this:</p> <pre><code>UIViewController *myController = [[MyViewController alloc] initWithNibName:@"MyView" bundle:[NSBundle mainBundle]; [[self navigationController] pushViewController:myController animated:YES]; </code></pre> <p>Now according to Apple's fundamental rule on memory management</p> <blockquote> <p>You take ownership of an object if you create it using a method whose name begins with “alloc” or “new” or contains “copy” (for example, <code>alloc</code>, <code>newObject</code>, or <code>mutableCopy</code>), or if you send it a <code>retain</code> message. You are responsible for relinquishing ownership of objects you own using <code>release</code> or <code>autorelease</code>. Any other time you receive an object, you must not release it.</p> </blockquote> <p>To me that means that I should be releasing <code>myController</code>, or giving it an <code>autorelease</code> message. But, whenever I try doing that my application winds up crashing as I push and pop views off of the stack. </p> <p>This didn't smell right to me, but in running Instruments it claims that I don't have any memory leaks. </p> <p>So I my question is</p> <ol> <li>Am I doing this right?</li> <li>Is the Navigation Controller taking ownership of MyViewController, explaining the lack of a memory leak?</li> <li>Should I assign myController to an instance variable in my root ViewController? In that case it would be marked retain and I would release in the root's dealloc method</li> </ol>
[ { "answer_id": 251233, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 3, "selected": false, "text": "<p>The problem is (most likely) you're releasing your viewController <em>before</em> the Navigation Controller has a chance to claim ownership. There are two ways around this:</p>\n\n<ul>\n<li><code>-release</code> your controller <em>after</em> pushing it to the Nav Controller</li>\n<li><code>-autorelease</code> your controller <em>before</em> pushing it. If you do this, the active NSAutoreleasePool (which you don't need to worry about) will take care of releasing your controller at a later time.</li>\n</ul>\n" }, { "answer_id": 251847, "author": "dnolen", "author_id": 32797, "author_profile": "https://Stackoverflow.com/users/32797", "pm_score": 3, "selected": true, "text": "<p>@Ben Gottlieb why do you need to autorelease before pushing it? Retain count at object allocation is 1, autorelease before or after pushing doesn't affect the retain count, though generally autoreleasing as a matter of style is applied afer object alloc/init:</p>\n\n<pre><code>[[[object alloc] init] autorelease];\n</code></pre>\n\n<p>@bpapa, </p>\n\n<p>2) When pushing, the navigation controller will retain the view controller. Later when this view is popped off the navigation controller stack, the navigation controller will release it.</p>\n\n<p>3) Unless there's a explicit reason to hold onto that view no you should not assign it to an instance variable. In general you want your views to exist only as long as you need them.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/251117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/543/" ]
So yeah, I'm a Java guy in this crazy iPhone world. When it comes to memory management I stiill don't have a very good idea of what I'm doing. I have an app that uses a navigation controller, and when it's time to go on to the next view I have code that looks like this: ``` UIViewController *myController = [[MyViewController alloc] initWithNibName:@"MyView" bundle:[NSBundle mainBundle]; [[self navigationController] pushViewController:myController animated:YES]; ``` Now according to Apple's fundamental rule on memory management > > You take ownership of an object if you create it using a method whose name begins with “alloc” or “new” or contains “copy” (for example, `alloc`, `newObject`, or `mutableCopy`), or if you send it a `retain` message. You are responsible for relinquishing ownership of objects you own using `release` or `autorelease`. Any other time you receive an object, you must not release it. > > > To me that means that I should be releasing `myController`, or giving it an `autorelease` message. But, whenever I try doing that my application winds up crashing as I push and pop views off of the stack. This didn't smell right to me, but in running Instruments it claims that I don't have any memory leaks. So I my question is 1. Am I doing this right? 2. Is the Navigation Controller taking ownership of MyViewController, explaining the lack of a memory leak? 3. Should I assign myController to an instance variable in my root ViewController? In that case it would be marked retain and I would release in the root's dealloc method
@Ben Gottlieb why do you need to autorelease before pushing it? Retain count at object allocation is 1, autorelease before or after pushing doesn't affect the retain count, though generally autoreleasing as a matter of style is applied afer object alloc/init: ``` [[[object alloc] init] autorelease]; ``` @bpapa, 2) When pushing, the navigation controller will retain the view controller. Later when this view is popped off the navigation controller stack, the navigation controller will release it. 3) Unless there's a explicit reason to hold onto that view no you should not assign it to an instance variable. In general you want your views to exist only as long as you need them.