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
|
---|---|---|---|---|---|---|
134,127 | <p>I've created a VB 2008 program to track work requests. It all works perfectly on a VISTA box, but I am having an issue with the program on an XP environment with adding new records.</p>
<p>Basically I've got 2 tabs: TAB 1 holds a datagridview with limited info and a calendar. Selecting dates on the calendar change the info in the datagridview. TAB 2 holds all the available info for that record in text/combo boxes. Both the datagridview and text boxes use the same Binding Source, so they are always in sync whenever the user selects a row from the datagridview. When you select the NEW button, TAB 2 appears with all the text boxes empty so the user can add data. If you look back on TAB 1, you see an empty, new row added to the datagridview (user can not directly add a row in the datagridview as AllowUserToAdd is set to false). If you let the app stay in the AddNew record state on VISTA, you remain on that new record until you select SAVE or CANCEL. On XP, however, after 1 minute time lapse, all the empty fields will eventually fill in with an existing record for that particular calendar day. When you look back on TAB 1, you no longer see the new empty row, you only see existing records previously saved.</p>
<p>Any ideas on how to resolve?? Thanks for any assistance.</p>
<p>Here is the code for adding new records:</p>
<pre><code>Private Sub cmdNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdNew.Click
'Focus on Work tab
TabControl1.SelectedTab = tabWork
'Change the files from read-only
bEditMode = True
ChangeEditMode()
'Clear the current information stored in the fields
Try
Me.BindingContext(WorkRequestBindingSource).AddNew()
Catch ex As Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
'Hidden text boxes populate with current selected calendar
'Used to populate TimeIn and DateNeed because if never clicked on, will populate as NULL on save
dtpDateNeed.Text = txtDate.Text
dtpTimeIn.Text = txtTime.Text
End Sub
</code></pre>
| [
{
"answer_id": 146849,
"author": "alexmac",
"author_id": 23066,
"author_profile": "https://Stackoverflow.com/users/23066",
"pm_score": 0,
"selected": false,
"text": "<p>If the code is exactly the same I wonder if it is an environment issue e.g. something like different international options or version of framework? </p>\n"
},
{
"answer_id": 951718,
"author": "Craig",
"author_id": 2894,
"author_profile": "https://Stackoverflow.com/users/2894",
"pm_score": 1,
"selected": false,
"text": "<p>This is definitely an environmental issue. To solve the problem I would need to know which browsers you are using on each machine and some of the settings on each. </p>\n\n<p>It <strong>sounds</strong> like the XP machine is refreshing the page after a timeout period and therefore munging the new record. I have seen that happen before and it stinks.</p>\n\n<p>You might need to consider saving some more state information in the viewstate to catch that kind of thing.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I've created a VB 2008 program to track work requests. It all works perfectly on a VISTA box, but I am having an issue with the program on an XP environment with adding new records.
Basically I've got 2 tabs: TAB 1 holds a datagridview with limited info and a calendar. Selecting dates on the calendar change the info in the datagridview. TAB 2 holds all the available info for that record in text/combo boxes. Both the datagridview and text boxes use the same Binding Source, so they are always in sync whenever the user selects a row from the datagridview. When you select the NEW button, TAB 2 appears with all the text boxes empty so the user can add data. If you look back on TAB 1, you see an empty, new row added to the datagridview (user can not directly add a row in the datagridview as AllowUserToAdd is set to false). If you let the app stay in the AddNew record state on VISTA, you remain on that new record until you select SAVE or CANCEL. On XP, however, after 1 minute time lapse, all the empty fields will eventually fill in with an existing record for that particular calendar day. When you look back on TAB 1, you no longer see the new empty row, you only see existing records previously saved.
Any ideas on how to resolve?? Thanks for any assistance.
Here is the code for adding new records:
```
Private Sub cmdNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdNew.Click
'Focus on Work tab
TabControl1.SelectedTab = tabWork
'Change the files from read-only
bEditMode = True
ChangeEditMode()
'Clear the current information stored in the fields
Try
Me.BindingContext(WorkRequestBindingSource).AddNew()
Catch ex As Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
'Hidden text boxes populate with current selected calendar
'Used to populate TimeIn and DateNeed because if never clicked on, will populate as NULL on save
dtpDateNeed.Text = txtDate.Text
dtpTimeIn.Text = txtTime.Text
End Sub
``` | This is definitely an environmental issue. To solve the problem I would need to know which browsers you are using on each machine and some of the settings on each.
It **sounds** like the XP machine is refreshing the page after a timeout period and therefore munging the new record. I have seen that happen before and it stinks.
You might need to consider saving some more state information in the viewstate to catch that kind of thing. |
134,131 | <p>I've recently installed the MVC CTP5 and VS is now crashing on me when I try to open an aspx, I get the following error in event viewer:</p>
<pre><code>.NET Runtime version 2.0.50727.3053 - Fatal Execution Engine Error (7A035E00) (80131506)
</code></pre>
<p>I was able to find <a href="http://forums.asp.net/t/1313452.aspx" rel="nofollow noreferrer">This</a> post on the asp.net forums relating to the same issue but nobody has had a working solution yet (at least not for me).</p>
<p>Just wondering if anyone else has run into this issue and what they have done to resolve it?</p>
<p>EDIT: Wanted to add that I have tried all the tips in the article and can open the markup with a code editor but was wondering an actual solution had been found to resolve this issue.. Thanks!</p>
<p>EDIT: I don't have this issue on my Vista box, seems to only occur on my XP VM.</p>
| [
{
"answer_id": 134143,
"author": "alex",
"author_id": 19268,
"author_profile": "https://Stackoverflow.com/users/19268",
"pm_score": 2,
"selected": false,
"text": "<p>Here are a steps to work around from <strong>the post</strong> that work for me:</p>\n\n<p>1.Open project based on CTP5</p>\n\n<p>2.IN solution Explorer, enable \"Show All files\"</p>\n\n<p>3.Open \"bin\" folder and delete \"Microsoft.Web.Mvc.dll\", \"System.Web.Mvc.dll\", \"System.Web.Abstractions.dll\", \"System.Web.Routing.dll\"</p>\n\n<p>4.Open \"References\" folder, click ONCE \"System.Web.Abstractions\" and in Properties window change \"Copy Local\" to true. Repeat same with System.Web.Routing.</p>\n\n<p>5.Build application (Ctrl+Shift+B)</p>\n\n<p>6.Open site.master in designer. VS will not crash.</p>\n"
},
{
"answer_id": 136794,
"author": "Ant",
"author_id": 3709,
"author_profile": "https://Stackoverflow.com/users/3709",
"pm_score": 1,
"selected": false,
"text": "<p>A bit of a null answer but I’ve been having this too. Not that I restart VS often but cleaning out the bin folder before opening the web project is my workaround.</p>\n"
},
{
"answer_id": 140864,
"author": "Robert Dean",
"author_id": 3396,
"author_profile": "https://Stackoverflow.com/users/3396",
"pm_score": 3,
"selected": true,
"text": "<p>I had a problem with Power Commands and Preview 5. If you have Power Commands installed, try updating or uninstalling it to fix the issue.</p>\n"
},
{
"answer_id": 166820,
"author": "Hrvoje Hudo",
"author_id": 1407,
"author_profile": "https://Stackoverflow.com/users/1407",
"pm_score": 0,
"selected": false,
"text": "<p>Have same problem, on vista x64 and vs2008 sp1. Have to do probably something with cleaning bin folder and system.web.routing/abstraction, because it crashes even on webforms project with (mvc) routing in it. When I delete all files from bin, and add references again, it works fine.<br>\nReally annoying bug in vs2008+ctp5! </p>\n"
},
{
"answer_id": 597505,
"author": "KristoferA",
"author_id": 11241,
"author_profile": "https://Stackoverflow.com/users/11241",
"pm_score": 2,
"selected": false,
"text": "<p>FYI - Microsoft has released a hotfix that fixes [at least some variations of] this problem:</p>\n\n<p><a href=\"https://connect.microsoft.com/VisualStudio/Downloads/DownloadDetails.aspx?DownloadID=16827&wa=wsignin1.0\" rel=\"nofollow noreferrer\">https://connect.microsoft.com/VisualStudio/Downloads/DownloadDetails.aspx?DownloadID=16827&wa=wsignin1.0</a></p>\n\n<p><a href=\"http://blogs.msdn.com/jnak/archive/2009/02/26/fix-available-asp-net-mvc-rc-crash-in-a-windows-azure-cloud-service-project.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/jnak/archive/2009/02/26/fix-available-asp-net-mvc-rc-crash-in-a-windows-azure-cloud-service-project.aspx</a></p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12707/"
]
| I've recently installed the MVC CTP5 and VS is now crashing on me when I try to open an aspx, I get the following error in event viewer:
```
.NET Runtime version 2.0.50727.3053 - Fatal Execution Engine Error (7A035E00) (80131506)
```
I was able to find [This](http://forums.asp.net/t/1313452.aspx) post on the asp.net forums relating to the same issue but nobody has had a working solution yet (at least not for me).
Just wondering if anyone else has run into this issue and what they have done to resolve it?
EDIT: Wanted to add that I have tried all the tips in the article and can open the markup with a code editor but was wondering an actual solution had been found to resolve this issue.. Thanks!
EDIT: I don't have this issue on my Vista box, seems to only occur on my XP VM. | I had a problem with Power Commands and Preview 5. If you have Power Commands installed, try updating or uninstalling it to fix the issue. |
134,161 | <p>I want to create a class which implements IEnumerable<T> but, using reflection, generates T's and returns them via IEnumerable<T>, where T' is a entirely constructed subclass of T with some properties hidden and others read-only. </p>
<p>Okay., that might not be very clear. Let me explain this via the medium of code - I'd like to have a class CollectionView<T> as follows:-</p>
<pre><code>public class CollectionView<T> : IEnumerable<T> {
public CollectionView(IEnumerable<T> inputCollection,
List<string> hiddenProperties, List<string> readonlyProperties) {
// ...
}
// IEnumerable<T> implementation which returns a collection of T' where T':T.
}
...
public class SomeObject {
public A { get; set; }
public B { get; set; }
public C { get; set; }
}
...
var hiddenProperties = new List<string>(new[] { "A" });
var readOnlyProperties = new List<string>(new[] { "C" });
IEnumerable<SomeObject> someObjects = CollectionView<SomeObject>(hiddenProperties,
readOnlyProperties);
...
dataGridView1.DataSource = someObjects;
</code></pre>
<p>(When displayed in dataGridView1 shows columns B and C and C has an underlying store which is read-only)</p>
<p>Is this possible/desirable or have I completely lost my mind/does this question demonstrate my deep inadequacy as a programmer?</p>
<p>I want to do this so I can manipulate a collection that is to be passed into a DataGridView, <em>without having to directly manipulate the DataGridView to hide columns/make columns read-only</em>. So no 'oh just use dataGridView1.Columns.Remove(blah) / dataGridView1.Columns[blah].ReadOnly = true' answers please!!</p>
<p>Help!</p>
| [
{
"answer_id": 134318,
"author": "Gilligan",
"author_id": 12356,
"author_profile": "https://Stackoverflow.com/users/12356",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.castleproject.org/dynamicproxy/index.html\" rel=\"nofollow noreferrer\">Castle.DynamicProxy</a> will help you accomplish this. \nWhat you would do is create an interceptor that inherits T. You would store the collection of hidden and read-only properties. When a getter or setter is called, the interceptor would check to see if the property exists in either collection and then take appropriate action. </p>\n\n<p>However, I know not how you would hide a property. You cannot change the access modifier of a base class in a derived class. You MAY be able to use the <code>new</code> keyword, but I know not how to do that with Castle.DynamicProxy.</p>\n"
},
{
"answer_id": 134369,
"author": "Romain Verdier",
"author_id": 4687,
"author_profile": "https://Stackoverflow.com/users/4687",
"pm_score": 0,
"selected": false,
"text": "<p>You just can't hide properties, even by creating subclassed proxies. You could at least construct a different type dynamically, which holds good properties, but it would not be a <code>T</code>.</p>\n\n<p>But returning an object list could be sufficient if you just need to use databinding.</p>\n"
},
{
"answer_id": 139058,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 0,
"selected": false,
"text": "<p>I decided to take a different approach to this problem, I really wasn't seeing the wood for the trees! I decided to create an extension method which converts my IEnumerable to a data table which can then be passed around as required:-</p>\n\n<pre><code>public static DataTable ToDataTable<T>(this IEnumerable<T> collection)\n{\n DataTable ret = new DataTable();\n\n Type type = typeof(T);\n\n foreach (PropertyInfo propertyInfo in type.GetProperties())\n {\n // Ignore indexed properties.\n if (propertyInfo.GetIndexParameters().Length > 0) continue;\n ret.Columns.Add(propertyInfo.Name);\n }\n\n foreach (T data in collection)\n {\n DataRow row = ret.NewRow();\n foreach (PropertyInfo propertyInfo in type.GetProperties())\n {\n // Ignore indexed properties.\n if (propertyInfo.GetIndexParameters().Length > 0) continue;\n\n row[propertyInfo.Name] = propertyInfo.GetValue(data, null);\n }\n\n ret.Rows.Add(row);\n }\n\n return ret;\n}\n</code></pre>\n"
},
{
"answer_id": 12979726,
"author": "Stephen",
"author_id": 1272132,
"author_profile": "https://Stackoverflow.com/users/1272132",
"pm_score": 0,
"selected": false,
"text": "<p>You can also use ICustomTypeDescriptor to filter the property list. To do this, I created a wrapper class for the data object (MyWrapper), a custom property descriptor (MypropertyDescriptor), and the collection class. I extended the collection class to also observe IList so the data can be modified, and ITypedList so that the datagrid can build the columns. You might also want to inherit ObservableCollection<> or BindingList<>.</p>\n\n<p>The custom descriptor is to handle setting and retrieving the property value:</p>\n\n<pre><code>public sealed class MyPropertyDescriptor : System.ComponentModel.PropertyDescriptor\n{\n private PropertyDescriptor innerProperty;\n private Boolean isReadonly;\n\n public MyPropertyDescriptor(PropertyDescriptor innerProperty, Boolean isReadonly)\n : base(innerProperty.Name, GetAttributeArray(innerProperty.Attributes))\n {\n this.innerProperty = innerProperty;\n this.isReadonly = isReadonly;\n if (!isReadonly) this.isReadonly = innerProperty.IsReadOnly;\n }\n\n public override Type ComponentType\n {\n get { return this.innerProperty.ComponentType; }\n }\n public override Boolean IsReadOnly\n {\n get { return this.isReadonly; }\n }\n public override Type PropertyType\n {\n get { return this.innerProperty.PropertyType; }\n }\n public override String Name\n {\n get\n {\n return this.innerProperty.Name;\n }\n }\n public override String DisplayName\n {\n get\n {\n return this.innerProperty.DisplayName;\n }\n }\n public override Boolean SupportsChangeEvents\n {\n get\n {\n return true;\n }\n }\n public override void SetValue(Object component, Object value)\n {\n if (!this.isReadonly)\n {\n this.innerProperty.SetValue(component, value);\n if (component is MyWrapper) (component as MyWrapper).NotifyPropertyChanged(this.innerProperty.Name);\n }\n }\n public override Object GetValue(Object component)\n {\n return this.innerProperty.GetValue(component);\n }\n\n public override Boolean CanResetValue(Object component)\n {\n return false;\n }\n public override void ResetValue(Object component)\n {\n }\n public override Boolean ShouldSerializeValue(Object component)\n {\n return true;\n }\n\n private static Attribute[] GetAttributeArray(AttributeCollection attributes)\n {\n List<Attribute> attr = new List<Attribute>();\n foreach (Attribute a in attributes) attr.Add(a);\n\n return attr.ToArray();\n }\n}\n</code></pre>\n\n<p>The wrapper class is to control access to the properties via ICustomTypeDescriptor:</p>\n\n<pre><code>public sealed class MyWrapper : System.ComponentModel.ICustomTypeDescriptor, System.ComponentModel.INotifyPropertyChanged\n{\n private Object innerObject;\n private String[] hiddenProps;\n private String[] readonlyProps;\n\n private Type innerType;\n\n public MyWrapper(Object innerObject, String[] hiddenProps, String[] readonlyProps)\n : base()\n {\n this.innerObject = innerObject;\n this.hiddenProps = hiddenProps;\n this.readonlyProps = readonlyProps;\n this.innerType = innerObject.GetType();\n }\n\n public static PropertyDescriptorCollection FilterProperties(PropertyDescriptorCollection pdc, String[] hiddenProps, String[] readonlyProps)\n {\n List<PropertyDescriptor> list = new List<PropertyDescriptor>();\n\n foreach (PropertyDescriptor pd in pdc)\n {\n if (hiddenProps != null)\n {\n Boolean isHidden = false;\n foreach (String hidden in hiddenProps)\n {\n if (hidden.Equals(pd.Name, StringComparison.OrdinalIgnoreCase))\n {\n isHidden = true;\n break;\n }\n }\n if (isHidden) continue; // skip hidden\n }\n\n Boolean isReadonly = false;\n if (readonlyProps != null)\n {\n foreach (String rp in readonlyProps)\n {\n if (rp.Equals(pd.Name, StringComparison.OrdinalIgnoreCase))\n {\n isReadonly = true;\n break;\n }\n }\n }\n\n list.Add(new MyPropertyDescriptor(pd, isReadonly));\n }\n\n return new PropertyDescriptorCollection(list.ToArray());\n }\n\n #region ICustomTypeDescriptor Members\n\n PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)\n {\n return FilterProperties(TypeDescriptor.GetProperties(this.innerType, attributes), hiddenProps, readonlyProps);\n }\n PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()\n {\n return FilterProperties(TypeDescriptor.GetProperties(this.innerType), hiddenProps, readonlyProps);\n }\n\n AttributeCollection ICustomTypeDescriptor.GetAttributes()\n {\n return TypeDescriptor.GetAttributes(this.innerType);\n }\n\n String ICustomTypeDescriptor.GetClassName()\n {\n return TypeDescriptor.GetClassName(this.GetType());\n }\n String ICustomTypeDescriptor.GetComponentName()\n {\n return TypeDescriptor.GetComponentName(this.GetType());\n }\n TypeConverter ICustomTypeDescriptor.GetConverter()\n {\n return TypeDescriptor.GetConverter(this.GetType());\n }\n EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()\n {\n return TypeDescriptor.GetDefaultEvent(this.GetType());\n }\n PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()\n {\n return null;\n }\n Object ICustomTypeDescriptor.GetEditor(Type editorBaseType)\n {\n return TypeDescriptor.GetEditor(this.GetType(), editorBaseType);\n }\n EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)\n {\n return null;\n }\n EventDescriptorCollection ICustomTypeDescriptor.GetEvents()\n {\n return null;\n }\n\n Object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)\n {\n return this.innerObject;\n }\n\n #endregion\n\n #region INotifyPropertyChanged Members\n internal void NotifyPropertyChanged(String propertyName)\n {\n if (this.propertyChanged != null) this.propertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));\n }\n private event PropertyChangedEventHandler propertyChanged;\n event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged\n {\n add { propertyChanged += value; }\n remove { propertyChanged -= value; }\n }\n #endregion\n}\n</code></pre>\n\n<p>And the modified version of your CollectionView<>. The bulk of this sample just maps the interface methods to the inner list.</p>\n\n<pre><code>public sealed class CollectionView<T> : IEnumerable<MyWrapper>, System.Collections.IList, IList<MyWrapper>, ITypedList\n{\n private String[] hiddenProps;\n private String[] readonlyProps;\n private List<MyWrapper> collection;\n\n public CollectionView(IEnumerable<T> innerCollection, String[] hiddenProps, String[] readonlyProps)\n : base()\n {\n this.hiddenProps = hiddenProps;\n this.readonlyProps = readonlyProps;\n\n this.collection = new List<MyWrapper>();\n foreach (T item in innerCollection)\n {\n this.collection.Add(new MyWrapper(item, hiddenProps, readonlyProps));\n }\n }\n\n #region ITypedList Members\n\n PropertyDescriptorCollection ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors)\n {\n return MyWrapper.FilterProperties(TypeDescriptor.GetProperties(typeof(T)), this.hiddenProps, this.readonlyProps);\n }\n\n String ITypedList.GetListName(PropertyDescriptor[] listAccessors)\n {\n return null;\n }\n #endregion\n\n #region IEnumerable<MyWrapper> Members\n\n IEnumerator<MyWrapper> IEnumerable<MyWrapper>.GetEnumerator()\n {\n return this.collection.GetEnumerator();\n }\n\n #endregion\n\n #region IEnumerable Members\n\n System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n {\n return this.collection.GetEnumerator();\n }\n\n #endregion\n\n #region IList Members\n Int32 System.Collections.IList.Add(Object value)\n {\n return (this.collection as System.Collections.IList).Add(value);\n }\n void System.Collections.IList.Clear()\n {\n (this.collection as System.Collections.IList).Clear();\n }\n Boolean System.Collections.IList.Contains(Object value)\n {\n return (this.collection as System.Collections.IList).Contains(value);\n }\n Int32 System.Collections.IList.IndexOf(Object value)\n {\n return (this.collection as System.Collections.IList).IndexOf(value);\n }\n void System.Collections.IList.Insert(Int32 index, Object value)\n {\n (this.collection as System.Collections.IList).Insert(index, value);\n }\n Boolean System.Collections.IList.IsFixedSize\n {\n get { return (this.collection as System.Collections.IList).IsFixedSize; }\n }\n Boolean System.Collections.IList.IsReadOnly\n {\n get { return (this.collection as System.Collections.IList).IsReadOnly; }\n }\n void System.Collections.IList.Remove(Object value)\n {\n (this.collection as System.Collections.IList).Remove(value);\n }\n void System.Collections.IList.RemoveAt(Int32 index)\n {\n (this.collection as System.Collections.IList).RemoveAt(index);\n }\n Object System.Collections.IList.this[Int32 index]\n {\n get\n {\n return (this.collection as System.Collections.IList)[index];\n }\n set\n {\n (this.collection as System.Collections.IList)[index] = value;\n }\n }\n #endregion\n\n #region ICollection Members\n void System.Collections.ICollection.CopyTo(Array array, Int32 index)\n {\n (this.collection as System.Collections.ICollection).CopyTo(array, index);\n }\n Int32 System.Collections.ICollection.Count\n {\n get { return (this.collection as System.Collections.ICollection).Count; }\n }\n Boolean System.Collections.ICollection.IsSynchronized\n {\n get { return (this.collection as System.Collections.ICollection).IsSynchronized; }\n }\n Object System.Collections.ICollection.SyncRoot\n {\n get { return (this.collection as System.Collections.ICollection).SyncRoot; }\n }\n #endregion\n\n #region IList<MyWrapper> Members\n Int32 IList<MyWrapper>.IndexOf(MyWrapper item)\n {\n return this.collection.IndexOf(item);\n }\n void IList<MyWrapper>.Insert(Int32 index, MyWrapper item)\n {\n this.collection.Insert(index, item);\n }\n void IList<MyWrapper>.RemoveAt(Int32 index)\n {\n this.collection.RemoveAt(index);\n }\n MyWrapper IList<MyWrapper>.this[Int32 index]\n {\n get\n {\n return this.collection[index];\n }\n set\n {\n this.collection[index] = value;\n }\n }\n #endregion\n\n #region ICollection<MyWrapper> Members\n void ICollection<MyWrapper>.Add(MyWrapper item)\n {\n this.collection.Add(item);\n }\n void ICollection<MyWrapper>.Clear()\n {\n this.collection.Clear();\n }\n Boolean ICollection<MyWrapper>.Contains(MyWrapper item)\n {\n return this.collection.Contains(item);\n }\n void ICollection<MyWrapper>.CopyTo(MyWrapper[] array, Int32 arrayIndex)\n {\n this.collection.CopyTo(array, arrayIndex);\n }\n Int32 ICollection<MyWrapper>.Count\n {\n get { return this.collection.Count; }\n }\n Boolean ICollection<MyWrapper>.IsReadOnly\n {\n get { return false; }\n }\n Boolean ICollection<MyWrapper>.Remove(MyWrapper item)\n {\n return this.collection.Remove(item);\n }\n #endregion\n}\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
]
| I want to create a class which implements IEnumerable<T> but, using reflection, generates T's and returns them via IEnumerable<T>, where T' is a entirely constructed subclass of T with some properties hidden and others read-only.
Okay., that might not be very clear. Let me explain this via the medium of code - I'd like to have a class CollectionView<T> as follows:-
```
public class CollectionView<T> : IEnumerable<T> {
public CollectionView(IEnumerable<T> inputCollection,
List<string> hiddenProperties, List<string> readonlyProperties) {
// ...
}
// IEnumerable<T> implementation which returns a collection of T' where T':T.
}
...
public class SomeObject {
public A { get; set; }
public B { get; set; }
public C { get; set; }
}
...
var hiddenProperties = new List<string>(new[] { "A" });
var readOnlyProperties = new List<string>(new[] { "C" });
IEnumerable<SomeObject> someObjects = CollectionView<SomeObject>(hiddenProperties,
readOnlyProperties);
...
dataGridView1.DataSource = someObjects;
```
(When displayed in dataGridView1 shows columns B and C and C has an underlying store which is read-only)
Is this possible/desirable or have I completely lost my mind/does this question demonstrate my deep inadequacy as a programmer?
I want to do this so I can manipulate a collection that is to be passed into a DataGridView, *without having to directly manipulate the DataGridView to hide columns/make columns read-only*. So no 'oh just use dataGridView1.Columns.Remove(blah) / dataGridView1.Columns[blah].ReadOnly = true' answers please!!
Help! | [Castle.DynamicProxy](http://www.castleproject.org/dynamicproxy/index.html) will help you accomplish this.
What you would do is create an interceptor that inherits T. You would store the collection of hidden and read-only properties. When a getter or setter is called, the interceptor would check to see if the property exists in either collection and then take appropriate action.
However, I know not how you would hide a property. You cannot change the access modifier of a base class in a derived class. You MAY be able to use the `new` keyword, but I know not how to do that with Castle.DynamicProxy. |
134,182 | <p>Here's the code that I'm attempting to do:</p>
<pre><code>public IList<IOperator> GetAll()
{
using (var c = new MyDataContext())
{
return c.Operators.ToList();
}
}
</code></pre>
<p>Operator implements IOperator, but I'm getting the following compilation error:</p>
<pre><code>Cannot implicitly convert type 'System.Collections.Generic.List<MyProject.Core.Operator>' to 'System.Collections.Generic.IList<MyProject.Core.Model.IOperator>'. An explicit conversion exists (are you missing a cast?)
</code></pre>
<p>How do I cast this to get what I need?</p>
| [
{
"answer_id": 134268,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 3,
"selected": false,
"text": "<p>Try the <code>Cast<>()</code> method:</p>\n\n<pre><code>return c.Operators.Cast<IOperator>().ToList();\n</code></pre>\n"
},
{
"answer_id": 134277,
"author": "Grank",
"author_id": 12975,
"author_profile": "https://Stackoverflow.com/users/12975",
"pm_score": 0,
"selected": false,
"text": "<p>Edit: Actually,</p>\n\n<p>return (List< IOperator >)c.Operators.ToList();</p>\n\n<p>would <em>not</em> do the trick. Sorry</p>\n"
},
{
"answer_id": 134370,
"author": "kenstone",
"author_id": 11097,
"author_profile": "https://Stackoverflow.com/users/11097",
"pm_score": 2,
"selected": false,
"text": "<p>If I change the code to the following:</p>\n\n<pre><code>public IList<IOperator> GetAll()\n{\n using (var c = new MyDataContext())\n {\n var operators = (from o in c.Operators\n select o).Cast<IOperator>();\n\n return operators.ToList();\n }\n}\n</code></pre>\n\n<p>it not only compiles but actually works! Thanks for the nudges in the right direction.</p>\n"
},
{
"answer_id": 2068765,
"author": "Frank Tzanabetis",
"author_id": 251210,
"author_profile": "https://Stackoverflow.com/users/251210",
"pm_score": 0,
"selected": false,
"text": "<p>Use ConvertAll<></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/kt456a2y.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/kt456a2y.aspx</a></p>\n\n<p>e.g.: In this case, TEntity must be an IBusinessUnit, but is a class, so i have the same trouble of converting <code>List<Operator> to List<IOperator></code> (assuming Operator implements IOperator).</p>\n\n<p>In your case, like you said, Operator doesn't impelement IOperator, but that doesn't matter - this will still work - </p>\n\n<pre><code> public static IList<IBusinessUnit> toIBusinessUnitIList(List<TEntity> items)\n {\n\n return items.ConvertAll<IBusinessUnit>(new Converter<TEntity, IBusinessUnit>(TEntityToIBuisinessUnit));\n }\n\n /// <summary>\n /// Callback for List<>.ConvertAll() used above.\n /// </summary>\n /// <param name=\"md\"></param>\n /// <returns></returns>\n private static IBusinessUnit TEntityToIBuisinessUnit(TEntity te)\n {\n return te; // In your case, do whatever magic you need to do to convert an Operator to an IOperator here.\n }\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11097/"
]
| Here's the code that I'm attempting to do:
```
public IList<IOperator> GetAll()
{
using (var c = new MyDataContext())
{
return c.Operators.ToList();
}
}
```
Operator implements IOperator, but I'm getting the following compilation error:
```
Cannot implicitly convert type 'System.Collections.Generic.List<MyProject.Core.Operator>' to 'System.Collections.Generic.IList<MyProject.Core.Model.IOperator>'. An explicit conversion exists (are you missing a cast?)
```
How do I cast this to get what I need? | Try the `Cast<>()` method:
```
return c.Operators.Cast<IOperator>().ToList();
``` |
134,214 | <p>Right now, I have code that looks something like this:</p>
<pre><code>Private Sub ShowReport(ByVal reportName As String)
Select Case reportName
Case "Security"
Me.ShowSecurityReport()
Case "Configuration"
Me.ShowConfigurationReport()
Case "RoleUsers"
Me.ShowRoleUsersReport()
Case Else
pnlMessage.Visible = True
litMessage.Text = "The report name """ + reportName + """ is invalid."
End Select
End Sub
</code></pre>
<p>Is there any way to create code that would use my method naming conventions to simplify things? Here's some pseudocode that describes what I'm looking for:</p>
<pre><code>Private Sub ShowReport(ByVal reportName As String)
Try
Call("Show" + reportName + "Report")
Catch ex As Exception
'method not found
End Try
End Sub
</code></pre>
| [
{
"answer_id": 134225,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 2,
"selected": false,
"text": "<p>You could use reflection to do this but to be honest I think it's overcomplicating things for your particular scenario i.e. code and switch() in the same class.</p>\n\n<p>Now, if you had designed the app to have each report type in its own assembly (kinda like an add-in/plugin architecture) or bundled in a single external assembly then you could load the reporting assemblie(s) into an appdomain and then use reflection to do this kinda thing.</p>\n"
},
{
"answer_id": 134231,
"author": "Rick Minerich",
"author_id": 9251,
"author_profile": "https://Stackoverflow.com/users/9251",
"pm_score": 0,
"selected": false,
"text": "<p>You can, using <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.reflection\" rel=\"nofollow noreferrer\">System.Reflection</a>. See <a href=\"http://www.codeproject.com/KB/codegen/Run-Time_Code_Generation2.aspx\" rel=\"nofollow noreferrer\">this code project article</a> for more information. </p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>string ModuleName = \"TestAssembly.dll\";\nstring TypeName = \"TestClass\";\nstring MethodName = \"TestMethod\";\n\nAssembly myAssembly = Assembly.LoadFrom(ModuleName);\n\nBindingFlags flags = (BindingFlags.NonPublic | BindingFlags.Public | \n BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly);\n\nModule [] myModules = myAssembly.GetModules();\nforeach (Module Mo in myModules) \n{\n if (Mo.Name == ModuleName) \n {\n Type[] myTypes = Mo.GetTypes();\n foreach (Type Ty in myTypes)\n {\n if (Ty.Name == TypeName) \n {\n MethodInfo[] myMethodInfo = Ty.GetMethods(flags);\n foreach(MethodInfo Mi in myMethodInfo)\n {\n if (Mi.Name == MethodName) \n {\n Object obj = Activator.CreateInstance(Ty);\n Object response = Mi.Invoke(obj, null);\n }\n }\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 134236,
"author": "Chris Wenham",
"author_id": 5548,
"author_profile": "https://Stackoverflow.com/users/5548",
"pm_score": 2,
"selected": false,
"text": "<p>Use reflection. In the <code>System.Reflection</code> namespace you need to get a <code>MethodInfo</code> object for the method you want, using <code>GetMethod(\"methodName\")</code> on the type containing the method.</p>\n\n<p>Once you have the <code>MethodInfo</code> object, you can call <code>.Invoke()</code> with the object instance and any parameters.</p>\n\n<p>For Example:</p>\n\n<pre><code>System.Reflection.MethodInfo method = this.GetType().GetMethod(\"foo\");\nmethod.Invoke(this, null);\n</code></pre>\n"
},
{
"answer_id": 134238,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 5,
"selected": true,
"text": "<pre><code>Type type = GetType();\nMethodInfo method = type.GetMethod(\"Show\"+reportName+\"Report\");\nif (method != null)\n{\n method.Invoke(this, null);\n}\n</code></pre>\n\n<p>This is C#, should be easy enough to turn it into VB. If you need to pass parameter into the method, they can be added in the 2nd argument to Invoke.</p>\n"
},
{
"answer_id": 134246,
"author": "Romain Verdier",
"author_id": 4687,
"author_profile": "https://Stackoverflow.com/users/4687",
"pm_score": 2,
"selected": false,
"text": "<p>Reflection API allows you to get a <code>MethodInfo</code> from a method, then calling <code>Invoke</code> dynamically on it. But it is overkill in your case. </p>\n\n<p>You should consider having a dictionary of delegates indexed by strings.</p>\n"
},
{
"answer_id": 134247,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 0,
"selected": false,
"text": "<p>Python (and IronPython) can do this thing very easily. With .Net though, you need to use reflection.</p>\n\n<p>In C#: <a href=\"http://www.dotnetspider.com/resources/4634-Invoke-me-ods-dynamically-using-reflection.aspx\" rel=\"nofollow noreferrer\">http://www.dotnetspider.com/resources/4634-Invoke-me-ods-dynamically-using-reflection.aspx</a></p>\n\n<p>My quick port to VB.Net:</p>\n\n<pre><code>Private Sub InvokeMethod(instance as object, methodName as string )\n 'Getting the method information using the method info class\n Dim mi as MethodInfo = instance.GetType().GetMethod(methodName)\n\n 'invoing the method\n 'null- no parameter for the function [or] we can pass the array of parameters\n mi.Invoke(instance, Nothing)\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 134250,
"author": "jop",
"author_id": 11830,
"author_profile": "https://Stackoverflow.com/users/11830",
"pm_score": 2,
"selected": false,
"text": "<p>You can use reflection. Though personally, I think you should just stick with the switch statement.</p>\n\n<pre><code>private void ShowReport(string methodName)\n{\n Type type = this.GetType();\n MethodInfo method = type.GetMethod(\"Show\"+methodName+\"Report\", BindingFlags.Public)\n method.Invoke(this, null);\n}\n</code></pre>\n\n<p>Sorry, I'm doing C#. Just translate it to VB.NET.</p>\n"
},
{
"answer_id": 134292,
"author": "axel_c",
"author_id": 20272,
"author_profile": "https://Stackoverflow.com/users/20272",
"pm_score": 0,
"selected": false,
"text": "<p>If i understand the question correctly, you'll have to use Reflection to find the method \"show\" + reportName and then invoke it indirectly:</p>\n\n<p>Half-baked example:</p>\n\n<pre><code>Case \"financial\" :\n{\n Assembly asm = Assembly.GetExecutingAssembly ();\n\n MethodInfo mi = asm.GetType (\"thisClassType\").GetMethod (\"showFinancialReport\");\n\n if (mi != null)\n mi.Invoke (null, new object[] {});\n\n}\n</code></pre>\n\n<p>Insert your own logic there to make up the name for the method to call.</p>\n\n<p>See MSDN documentation of MethodInfo and Assembly for details.</p>\n"
},
{
"answer_id": 134293,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 0,
"selected": false,
"text": "<p>Using reflection:</p>\n\n<pre><code>Type t = this.GetType();\ntry \n{\n MethodInfo mi = t.GetMethod(methodName, ...);\n\n if (mi != null)\n {\n mi.Invoke(this, parameters);\n }\n} \n</code></pre>\n\n<p>But I agree with ago, better not change your original code ;-)</p>\n"
},
{
"answer_id": 134514,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 3,
"selected": false,
"text": "<p>You've got a deeper problem. Your strings are too important. Who is passing you strings? can you make them not do that? </p>\n\n<p>Stick with the switch statement, as it decouples your internal implementation (method names) from your external view.</p>\n\n<p>Suppose you localize this to German. You gonna rename all those methods?</p>\n"
},
{
"answer_id": 134941,
"author": "Dustman",
"author_id": 16398,
"author_profile": "https://Stackoverflow.com/users/16398",
"pm_score": 0,
"selected": false,
"text": "<p>The \"Closest to your question\" solution.</p>\n\n<p>You could make delegates out of those reports, and call them by looking up the matching String in a Hashtable:</p>\n\n<pre><code>Public Sub New()\n '...\n ReportTable.Add(\"Security\", New ReportDelegate(AddressOf ShowSecurityReport))\n ReportTable.Add(\"Config\", New ReportDelegate(AddressOf ShowConfigReport))\n ReportTable.Add(\"RoleUsers\", New ReportDelegate(AddressOf ShowRoleUsersReport))\n '...\nEnd Sub\n\nPrivate Sub ShowSecurityReport()\n '...\nEnd Sub\n\nPrivate Sub ShowConfigReport()\n '...\nEnd Sub\n\nPrivate Sub ShowRoleUsersReport()\n '...\nEnd Sub\n\nPrivate Delegate Sub ReportDelegate()\n\nPrivate ReportTable As New Dictionary(Of String, ReportDelegate)\n\nPrivate Sub ShowReport(ByVal reportName As String)\n Dim ReportToRun As ReportDelegate\n If ReportTable.TryGetValue(reportName, ReportToRun) Then\n ReportToRun()\n Else\n pnlMessage.Visible = True\n litMessage.Text = \"The report name \"\"\" + reportName + \"\"\" is invalid.\"\n End If\nEnd Sub\n</code></pre>\n\n<p>That way you can add as many reports as you like, and your ability to reflect them, and the perf hit of reflection, aren't an issue.</p>\n"
},
{
"answer_id": 54516322,
"author": "Andrew Xxx",
"author_id": 11012407,
"author_profile": "https://Stackoverflow.com/users/11012407",
"pm_score": 0,
"selected": false,
"text": "<p>Worked for me in VB .Net MSVS 2015</p>\n\n<pre><code>Dim tip As Type = GetType(MODULENAME)'if sub() or function() in module\n Dim method As MethodInfo = tip.GetMethod(\"MaxV\") 'name of function (gets 2 params double type)\n Dim res As Double = 0 'temporary variable\n If (Not Nothing = method) Then 'if found function \"MaxV\"\n\n res = method.Invoke(Me, New Object() {10, 20})\n End If\n MsgBox(res.ToString())\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/681/"
]
| Right now, I have code that looks something like this:
```
Private Sub ShowReport(ByVal reportName As String)
Select Case reportName
Case "Security"
Me.ShowSecurityReport()
Case "Configuration"
Me.ShowConfigurationReport()
Case "RoleUsers"
Me.ShowRoleUsersReport()
Case Else
pnlMessage.Visible = True
litMessage.Text = "The report name """ + reportName + """ is invalid."
End Select
End Sub
```
Is there any way to create code that would use my method naming conventions to simplify things? Here's some pseudocode that describes what I'm looking for:
```
Private Sub ShowReport(ByVal reportName As String)
Try
Call("Show" + reportName + "Report")
Catch ex As Exception
'method not found
End Try
End Sub
``` | ```
Type type = GetType();
MethodInfo method = type.GetMethod("Show"+reportName+"Report");
if (method != null)
{
method.Invoke(this, null);
}
```
This is C#, should be easy enough to turn it into VB. If you need to pass parameter into the method, they can be added in the 2nd argument to Invoke. |
134,224 | <p>This code produces a FileNotFoundException, but ultimately runs without issue:</p>
<pre><code>void ReadXml()
{
XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
//...
}
</code></pre>
<p>Here is the exception:</p>
<hr>
<p>A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll</p>
<p>Additional information: Could not load file or assembly 'MyAssembly.XmlSerializers, Version=1.4.3190.15950, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.</p>
<hr>
<p><strong>It appears that the framework automatically generates the serialization assembly if it isn't found.</strong> I can generate it manually using sgen.exe, which alleviates the exception. </p>
<p><strong>How do I get visual studio to generate the XML Serialization assembly automatically?</strong></p>
<hr>
<p><strong>Update: The Generate Serialization Assembly: On setting doesn't appear to do anything.</strong></p>
| [
{
"answer_id": 134273,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 1,
"selected": false,
"text": "<p>Look in the properties on the solution. On the build tab at the bottom there is a dropdown called \"Generate Serialization assembly\"</p>\n"
},
{
"answer_id": 204993,
"author": "flipdoubt",
"author_id": 470,
"author_profile": "https://Stackoverflow.com/users/470",
"pm_score": 7,
"selected": true,
"text": "<p>This is how I managed to do it by modifying the MSBUILD script in my .CSPROJ file:</p>\n\n<p>First, open your .CSPROJ file as a file rather than as a project. Scroll to the bottom of the file until you find this commented out code, just before the close of the Project tag: </p>\n\n<pre><code><!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets.\n<Target Name=\"BeforeBuild\">\n</Target>\n<Target Name=\"AfterBuild\">\n</Target>\n-->\n</code></pre>\n\n<p>Now we just insert our own AfterBuild target to delete any existing XmlSerializer and SGen our own, like so:</p>\n\n<pre><code><Target Name=\"AfterBuild\" DependsOnTargets=\"AssignTargetPaths;Compile;ResolveKeySource\" Inputs=\"$(MSBuildAllProjects);@(IntermediateAssembly)\" Outputs=\"$(OutputPath)$(_SGenDllName)\">\n <!-- Delete the file because I can't figure out how to force the SGen task. -->\n <Delete\n Files=\"$(TargetDir)$(TargetName).XmlSerializers.dll\"\n ContinueOnError=\"true\" />\n <SGen\n BuildAssemblyName=\"$(TargetFileName)\"\n BuildAssemblyPath=\"$(OutputPath)\"\n References=\"@(ReferencePath)\"\n ShouldGenerateSerializer=\"true\"\n UseProxyTypes=\"false\"\n KeyContainer=\"$(KeyContainerName)\"\n KeyFile=\"$(KeyOriginatorFile)\"\n DelaySign=\"$(DelaySign)\"\n ToolPath=\"$(TargetFrameworkSDKToolsDirectory)\"\n Platform=\"$(Platform)\">\n <Output\n TaskParameter=\"SerializationAssembly\"\n ItemName=\"SerializationAssembly\" />\n </SGen>\n</Target>\n</code></pre>\n\n<p>That works for me.</p>\n"
},
{
"answer_id": 264464,
"author": "Martin Hollingsworth",
"author_id": 29491,
"author_profile": "https://Stackoverflow.com/users/29491",
"pm_score": 5,
"selected": false,
"text": "<p>The other answers to this question have already mentioned the Project Properties->Build-><strong>Generate Serialization Assemblies</strong> setting but by default this will only generate the assembly if there are \"<strong>XML Web service proxy types</strong>\" in the project.</p>\n\n<p>The best way to understand the exact behaviour of Visual Studio is to to examine the <strong>GenerateSerializationAssemblies</strong> target within the C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727**Microsoft.Common.targets** file. </p>\n\n<p>You can check the result of this build task from the Visual Studio <strong>Output</strong> window and select <strong>Build</strong> from the <strong>Show output from</strong>: drop down box. You should see something along the lines of</p>\n\n<p>C:\\Program Files\\Microsoft Visual Studio 8\\SDK\\v2.0\\bin\\sgen.exe /assembly:D:\\Temp\\LibraryA\\obj\\Debug\\LibraryA.dll /<strong>proxytypes</strong> /reference:.. /compiler:/delaysign- \nLibraryA -> D:\\Temp\\LibraryA\\bin\\Debug\\LibraryA.dll</p>\n\n<p>The key point here is the /<strong>proxytypes</strong> switch. You can read about the various switches for the <a href=\"http://msdn.microsoft.com/en-us/library/bk3w6240(VS.80).aspx\" rel=\"noreferrer\">XML Serializer Generator Tool (Sgen.exe)</a></p>\n\n<p>If you are familiar with MSBuild you could customise the GenerateSerializationAssemblies target so that SGen task has an attribute of UseProxyTypes=\"false\" instead of true but\nthen you need to take on board all of the associated responsibility of customising the Visual Studio / MSBuild system. Alternatively you could just extend your build process to call SGen manually without the /proxytypes switch.</p>\n\n<p>If you read the documentation for SGen they are fairly clear that Microsoft wanted to limit the use of this facility. Given the amount of noise on this topic, it's pretty clear that Microsoft did not do a great job with documenting the Visual Studio experience. There is even a <a href=\"http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=123088\" rel=\"noreferrer\">Connect Feedback</a> item for this issue and the response is not great.</p>\n"
},
{
"answer_id": 2260708,
"author": "joniba",
"author_id": 163341,
"author_profile": "https://Stackoverflow.com/users/163341",
"pm_score": 2,
"selected": false,
"text": "<p>In case someone else runs into this problem suddenly after everything was working fine before: For me it had to do with the \"Enable Just My Code (Managed Only)\" checkbox being unchecked in the options menu (Options -> Debugging) (which was automatically switched off after installing .NET Reflector).</p>\n\n<p>EDIT:\nWhich is to say, of course, that this exception was happening before, but when \"enable just my code\" is off, the debugging assistant (if enabled), will stop at this point when thrown.</p>\n"
},
{
"answer_id": 8798289,
"author": "heavyd",
"author_id": 94928,
"author_profile": "https://Stackoverflow.com/users/94928",
"pm_score": 6,
"selected": false,
"text": "<p>As Martin has explained in <a href=\"https://stackoverflow.com/a/264464/94928\">his answer</a>, turning on generation of the serialization assembly through the project properties is not enough because the SGen task is adding the <code>/proxytypes</code> switch to the sgen.exe command line.</p>\n\n<p>Microsoft has a <a href=\"http://msdn.microsoft.com/en-us/library/bb629394.aspx\" rel=\"noreferrer\">documented MSBuild property</a> which allows you to disable the <code>/proxytypes</code> switch and causes the SGen Task to generate the serialization assemblies even if there are no proxy types in the assembly.</p>\n\n<blockquote>\n <p>SGenUseProxyTypes</p>\n \n <p>A boolean value that indicates whether proxy types\n should be generated by SGen.exe. The SGen target uses this property to\n set the UseProxyTypes flag. This property defaults to true, and there\n is no UI to change this. To generate the serialization assembly for\n non-webservice types, add this property to the project file and set it\n to false before importing the Microsoft.Common.Targets or the\n C#/VB.targets</p>\n</blockquote>\n\n<p>As the documentation suggests you must modify your project file by hand, but you can add the <code>SGenUseProxyTypes</code> property to your configuration to enable generation. Your project files configuration would end up looking something like this:</p>\n\n<pre><code> <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|x86' \">\n <!-- Snip... -->\n <GenerateSerializationAssemblies>On</GenerateSerializationAssemblies>\n <SGenUseProxyTypes>false</SGenUseProxyTypes>\n </PropertyGroup>\n <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|x86' \">\n <!-- Snip... -->\n <GenerateSerializationAssemblies>On</GenerateSerializationAssemblies>\n <SGenUseProxyTypes>false</SGenUseProxyTypes>\n </PropertyGroup>\n</code></pre>\n"
},
{
"answer_id": 15538240,
"author": "brain backup",
"author_id": 2043133,
"author_profile": "https://Stackoverflow.com/users/2043133",
"pm_score": 4,
"selected": false,
"text": "<p>creating a new sgen task definition breaks a fly on the wheel. just set the needed variables to make the task work as intended. Anyway the microsoft documentation lacks some important info.</p>\n\n<h2>Steps to pre-generate serialization assemblies</h2>\n\n<p>(with parts from <a href=\"http://msdn.microsoft.com/en-us/library/ff798449.aspx\">http://msdn.microsoft.com/en-us/library/ff798449.aspx</a>)</p>\n\n<ol>\n<li>In Visual Studio 2010, in Solution Explorer, right-click the project for which you want to generate serialization assemblies, and then click Unload Project. </li>\n<li>In Solution Explorer, right-click the project for which you want to generate serialization assemblies, and then click Edit .csproj. </li>\n<li><p>In the .csproj file, immediately after the <code><TargetFrameworkVersion>v?.?</TargetFrameworkVersion></code> element, add the following elements: </p>\n\n<blockquote>\n <p><code><SGenUseProxyTypes>false</SGenUseProxyTypes></code>\n <code><SGenPlatformTarget>$(Platform)</SGenPlatformTarget></code></p>\n</blockquote></li>\n<li><p>In the .csproj file, in each platform configuration</p>\n\n<p>e.g. <code><PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'Debug|x86'\"></code></p>\n\n<p>add the following line: </p>\n\n<p><code><GenerateSerializationAssemblies>On</GenerateSerializationAssemblies></code></p></li>\n<li><p>Save and close the .csproj file. </p></li>\n<li>In Solution Explorer, right-click the project you just edited, and then click Reload Project. </li>\n</ol>\n\n<p>This procedure generates an additional assembly named .xmlSerializers.dll in your output folder. You will need to deploy this assembly with your solution.</p>\n\n<hr>\n\n<h2>Explanation</h2>\n\n<p>SGen by default only for proxy types generates for “Any CPU”. This happens if you don't set the according variables in your project file.</p>\n\n<p>SGenPlatformTarget is required to match your PlatformTarget. I tend to think this is a bug in the project template. Why should the sgen target platform differ from your project's? If it does you will get a runtime exception</p>\n\n<blockquote>\n <p>0x80131040: The located assembly's manifest definition does not match the assembly reference</p>\n</blockquote>\n\n<p>You can locate the msbuild task definition by analyzing your project file:</p>\n\n<pre><code><Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n</code></pre>\n\n<p>where MSBuildToolsPath depends on your <code><TargetFrameworkVersion></code> <a href=\"http://msdn.microsoft.com/en-us/library/bb397428.aspx\">http://msdn.microsoft.com/en-us/library/bb397428.aspx</a></p>\n\n<p>Look inside the SGen task definition for TargetFrameworkVersion 4.0 from </p>\n\n<blockquote>\n <p>Windows installation path\\Microsoft.NET\\Framework\\v4.0.30319\\Microsoft.CSharp.targets</p>\n</blockquote>\n\n<p>to see the undocumented variables like $(SGenPlatformTarget) you are free to set in your project file</p>\n\n<pre><code><Target\n Name=\"GenerateSerializationAssemblies\"\n Condition=\"'$(_SGenGenerateSerializationAssembliesConfig)' == 'On' or ('@(WebReferenceUrl)'!='' and '$(_SGenGenerateSerializationAssembliesConfig)' == 'Auto')\"\n DependsOnTargets=\"AssignTargetPaths;Compile;ResolveKeySource\"\n Inputs=\"$(MSBuildAllProjects);@(IntermediateAssembly)\"\n Outputs=\"$(IntermediateOutputPath)$(_SGenDllName)\">\n\n <SGen\n BuildAssemblyName=\"$(TargetFileName)\"\n BuildAssemblyPath=\"$(IntermediateOutputPath)\"\n References=\"@(ReferencePath)\"\n ShouldGenerateSerializer=\"$(SGenShouldGenerateSerializer)\"\n UseProxyTypes=\"$(SGenUseProxyTypes)\"\n KeyContainer=\"$(KeyContainerName)\"\n KeyFile=\"$(KeyOriginatorFile)\"\n DelaySign=\"$(DelaySign)\"\n ToolPath=\"$(SGenToolPath)\"\n SdkToolsPath=\"$(TargetFrameworkSDKToolsDirectory)\"\n EnvironmentVariables=\"$(SGenEnvironment)\"\n SerializationAssembly=\"$(IntermediateOutputPath)$(_SGenDllName)\"\n Platform=\"$(SGenPlatformTarget)\"\n Types=\"$(SGenSerializationTypes)\">\n <Output TaskParameter=\"SerializationAssembly\" ItemName=\"SerializationAssembly\"/>\n </SGen>\n</Target>\n</code></pre>\n"
},
{
"answer_id": 21015945,
"author": "Timoty Weis",
"author_id": 2416998,
"author_profile": "https://Stackoverflow.com/users/2416998",
"pm_score": 1,
"selected": false,
"text": "<p>A slightly different solution from the one provided by <a href=\"https://stackoverflow.com/a/15538240\">brain backup</a> could be to directly specify the platform target right where you have to use it like so:</p>\n\n<pre><code><!-- Check the platform target value and if present use that for a correct *.XmlSerializer.dll platform setup (default is MSIL)-->\n<PropertyGroup Condition=\" '$(PlatformTarget)'=='' \">\n <SGenPlatform>$(Platform)</SGenPlatform>\n</PropertyGroup>\n<PropertyGroup Condition=\" '$(PlatformTarget)'!='' \">\n <SGenPlatform>$(PlatformTarget)</SGenPlatform>\n</PropertyGroup>\n\n<!-- Delete the file because I can't figure out how to force the SGen task. -->\n<Delete Files=\"$(TargetDir)$(TargetName).XmlSerializers.dll\" ContinueOnError=\"true\" />\n<SGen\n BuildAssemblyName=\"$(TargetFileName)\"\n BuildAssemblyPath=\"$(OutputPath)\"\n References=\"@(ReferencePath)\"\n ShouldGenerateSerializer=\"true\"\n UseProxyTypes=\"false\"\n KeyContainer=\"$(KeyContainerName)\"\n KeyFile=\"$(KeyOriginatorFile)\"\n DelaySign=\"$(DelaySign)\"\n ToolPath=\"$(SGenToolPath)\"\n SdkToolsPath=\"$(TargetFrameworkSDKToolsDirectory)\"\n EnvironmentVariables=\"$(SGenEnvironment)\"\n Platform=\"$(SGenPlatform)\">\n <Output TaskParameter=\"SerializationAssembly\" ItemName=\"SerializationAssembly\" />\n</SGen>\n</code></pre>\n"
},
{
"answer_id": 25247534,
"author": "mcfea",
"author_id": 984463,
"author_profile": "https://Stackoverflow.com/users/984463",
"pm_score": 2,
"selected": false,
"text": "<p>I'm a little late to the party, but I found the previous answer difficult to work with. Specifically Visual Studio would crash whenever I tried to view the properties of my project. I figure this was due to the fact that it no longer understood how to read the csproj file. That said...</p>\n\n<p>Add the following to your post-build event command line:</p>\n\n<pre><code>\"C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v7.0A\\Bin\\NETFX 4.0 Tools\\sgen.exe\" \"$(TargetPath)\" /force\n</code></pre>\n\n<p>This will leverage sgen.exe directly to rebuild the Xml Serialization assembly every time you build your project for Debug or Release.</p>\n"
},
{
"answer_id": 71662336,
"author": "Alex from Jitbit",
"author_id": 56621,
"author_profile": "https://Stackoverflow.com/users/56621",
"pm_score": 0,
"selected": false,
"text": "<p>For anyone interested in doing so for <strong>.NET Core</strong> - please refer to this MS article: <a href=\"https://learn.microsoft.com/en-us/dotnet/core/additional-tools/xml-serializer-generator\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/core/additional-tools/xml-serializer-generator</a></p>\n<p>Basically, you just need to add one nuget package to your project.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4066/"
]
| This code produces a FileNotFoundException, but ultimately runs without issue:
```
void ReadXml()
{
XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
//...
}
```
Here is the exception:
---
A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
Additional information: Could not load file or assembly 'MyAssembly.XmlSerializers, Version=1.4.3190.15950, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
---
**It appears that the framework automatically generates the serialization assembly if it isn't found.** I can generate it manually using sgen.exe, which alleviates the exception.
**How do I get visual studio to generate the XML Serialization assembly automatically?**
---
**Update: The Generate Serialization Assembly: On setting doesn't appear to do anything.** | This is how I managed to do it by modifying the MSBUILD script in my .CSPROJ file:
First, open your .CSPROJ file as a file rather than as a project. Scroll to the bottom of the file until you find this commented out code, just before the close of the Project tag:
```
<!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
```
Now we just insert our own AfterBuild target to delete any existing XmlSerializer and SGen our own, like so:
```
<Target Name="AfterBuild" DependsOnTargets="AssignTargetPaths;Compile;ResolveKeySource" Inputs="$(MSBuildAllProjects);@(IntermediateAssembly)" Outputs="$(OutputPath)$(_SGenDllName)">
<!-- Delete the file because I can't figure out how to force the SGen task. -->
<Delete
Files="$(TargetDir)$(TargetName).XmlSerializers.dll"
ContinueOnError="true" />
<SGen
BuildAssemblyName="$(TargetFileName)"
BuildAssemblyPath="$(OutputPath)"
References="@(ReferencePath)"
ShouldGenerateSerializer="true"
UseProxyTypes="false"
KeyContainer="$(KeyContainerName)"
KeyFile="$(KeyOriginatorFile)"
DelaySign="$(DelaySign)"
ToolPath="$(TargetFrameworkSDKToolsDirectory)"
Platform="$(Platform)">
<Output
TaskParameter="SerializationAssembly"
ItemName="SerializationAssembly" />
</SGen>
</Target>
```
That works for me. |
134,251 | <p>I have a basic C# console application that reads a text file (CSV format) line by line and puts the data into a HashTable. The first CSV item in the line is the key (id num) and the rest of the line is the value. However I've discovered that my import file has a few duplicate keys that it shouldn't have. When I try to import the file the application errors out because you can't have duplicate keys in a HashTable. I want my program to be able to handle this error though. When I run into a duplicate key I would like to put that key into a arraylist and continue importing the rest of the data into the hashtable. How can I do this in C#</p>
<p>Here is my code:</p>
<hr>
<p>private static Hashtable importFile(Hashtable myHashtable, String myFileName)
{</p>
<pre><code> StreamReader sr = new StreamReader(myFileName);
CSVReader csvReader = new CSVReader();
ArrayList tempArray = new ArrayList();
int count = 0;
while (!sr.EndOfStream)
{
String temp = sr.ReadLine();
if (temp.StartsWith(" "))
{
ServMissing.Add(temp);
}
else
{
tempArray = csvReader.CSVParser(temp);
Boolean first = true;
String key = "";
String value = "";
foreach (String x in tempArray)
{
if (first)
{
key = x;
first = false;
}
else
{
value += x + ",";
}
}
myHashtable.Add(key, value);
}
count++;
}
Console.WriteLine("Import Count: " + count);
return myHashtable;
}
</code></pre>
| [
{
"answer_id": 134283,
"author": "Dror Helper",
"author_id": 11361,
"author_profile": "https://Stackoverflow.com/users/11361",
"pm_score": 2,
"selected": false,
"text": "<p>A better solution is to call ContainsKey to check if the key exist before adding it to the hash table instead. Throwing exception on this kind of error is a performance hit and doesn't improve the program flow.</p>\n"
},
{
"answer_id": 134326,
"author": "jop",
"author_id": 11830,
"author_profile": "https://Stackoverflow.com/users/11830",
"pm_score": 4,
"selected": true,
"text": "<pre><code>if (myHashtable.ContainsKey(key))\n duplicates.Add(key);\nelse\n myHashtable.Add(key, value);\n</code></pre>\n"
},
{
"answer_id": 134360,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "<p>ContainsKey has a constant O(1) overhead for every item, while catching an Exception incurs a performance hit on JUST the duplicate items.</p>\n\n<p>In most situations, I'd say check for the key, but in this case, its better to catch the exception.</p>\n"
},
{
"answer_id": 134431,
"author": "Morten Christiansen",
"author_id": 4055,
"author_profile": "https://Stackoverflow.com/users/4055",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a solution which avoids multiple hits in the secondary list with a small overhead to all insertions:</p>\n\n<pre><code>Dictionary<T, List<K>> dict = new Dictionary<T, List<K>>();\n\n//Insert item\nif (!dict.ContainsKey(key))\n dict[key] = new List<string>();\ndict[key].Add(value);\n</code></pre>\n\n<p>You can wrap the dictionary in a type that hides this or put it in a method or even extension method on dictionary.</p>\n"
},
{
"answer_id": 134567,
"author": "MaxGeek",
"author_id": 8664,
"author_profile": "https://Stackoverflow.com/users/8664",
"pm_score": 0,
"selected": false,
"text": "<p>Thank you all.\nI ended up using the ContainsKey() method. It takes maybe 30 secs longer, which is fine for my purposes. I'm loading about 1.7 million lines and the program takes about 7 mins total to load up two files, compare them, and write out a few files. It only takes about 2 secs to do the compare and write out the files.</p>\n"
},
{
"answer_id": 134783,
"author": "woany",
"author_id": 15623,
"author_profile": "https://Stackoverflow.com/users/15623",
"pm_score": 1,
"selected": false,
"text": "<p>If you have more than 4 (for example) CSV values, it might be worth setting the <em>value</em> variable to use a StringBuilder as well since the string concatenation is a slow function.</p>\n"
},
{
"answer_id": 134831,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 1,
"selected": false,
"text": "<p>Hmm, 1.7 Million lines? I hesitate to offer this for that kind of load.</p>\n\n<p>Here's one way to do this using LINQ.</p>\n\n<pre><code>CSVReader csvReader = new CSVReader();\nList<string> source = new List<string>();\nusing(StreamReader sr = new StreamReader(myFileName))\n{\n while (!sr.EndOfStream)\n {\n source.Add(sr.ReadLine());\n }\n}\nList<string> ServMissing =\n source\n .Where(s => s.StartsWith(\" \")\n .ToList();\n//--------------------------------------------------\nList<IGrouping<string, string>> groupedSource = \n(\n from s in source\n where !s.StartsWith(\" \")\n let parsed = csvReader.CSVParser(s)\n where parsed.Any()\n let first = parsed.First()\n let rest = String.Join( \",\" , parsed.Skip(1).ToArray())\n select new {first, rest}\n)\n.GroupBy(x => x.first, x => x.rest) //GroupBy(keySelector, elementSelector)\n.ToList()\n//--------------------------------------------------\nList<string> myExtras = new List<string>();\nforeach(IGrouping<string, string> g in groupedSource)\n{\n myHashTable.Add(g.Key, g.First());\n if (g.Skip(1).Any())\n {\n myExtras.Add(g.Key);\n } \n}\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8664/"
]
| I have a basic C# console application that reads a text file (CSV format) line by line and puts the data into a HashTable. The first CSV item in the line is the key (id num) and the rest of the line is the value. However I've discovered that my import file has a few duplicate keys that it shouldn't have. When I try to import the file the application errors out because you can't have duplicate keys in a HashTable. I want my program to be able to handle this error though. When I run into a duplicate key I would like to put that key into a arraylist and continue importing the rest of the data into the hashtable. How can I do this in C#
Here is my code:
---
private static Hashtable importFile(Hashtable myHashtable, String myFileName)
{
```
StreamReader sr = new StreamReader(myFileName);
CSVReader csvReader = new CSVReader();
ArrayList tempArray = new ArrayList();
int count = 0;
while (!sr.EndOfStream)
{
String temp = sr.ReadLine();
if (temp.StartsWith(" "))
{
ServMissing.Add(temp);
}
else
{
tempArray = csvReader.CSVParser(temp);
Boolean first = true;
String key = "";
String value = "";
foreach (String x in tempArray)
{
if (first)
{
key = x;
first = false;
}
else
{
value += x + ",";
}
}
myHashtable.Add(key, value);
}
count++;
}
Console.WriteLine("Import Count: " + count);
return myHashtable;
}
``` | ```
if (myHashtable.ContainsKey(key))
duplicates.Add(key);
else
myHashtable.Add(key, value);
``` |
134,344 | <p>Is there a way to retrieve the time zone choices in Windows Mobile in order to display them in a GUI? It would be much better not to have to show every 15 minutes just to be
able to display GMT+5:45 for Kathmandu.</p>
| [
{
"answer_id": 135540,
"author": "ctacke",
"author_id": 13154,
"author_profile": "https://Stackoverflow.com/users/13154",
"pm_score": 0,
"selected": false,
"text": "<p>Windows Mobile stores timezone info in a <a href=\"http://msdn.microsoft.com/en-us/library/aa458853.aspx\" rel=\"nofollow noreferrer\">file called Timezones.csv</a></p>\n"
},
{
"answer_id": 161522,
"author": "prakash",
"author_id": 123,
"author_profile": "https://Stackoverflow.com/users/123",
"pm_score": 0,
"selected": false,
"text": "<p>Timezones.csv & CityList.csv files are provided in the \\Resource folder of the Windows Mobile SDK!</p>\n\n<p>You could modify the list and decide the ones which you want to show to the user.</p>\n"
},
{
"answer_id": 232925,
"author": "prakash",
"author_id": 123,
"author_profile": "https://Stackoverflow.com/users/123",
"pm_score": 1,
"selected": false,
"text": "<p>As per <a href=\"http://msdn.microsoft.com/en-us/library/aa458853.aspx\" rel=\"nofollow noreferrer\">MSDN:City List and Time Zone Data Files</a>, </p>\n\n<blockquote>\n <p>You can add or remove content to these\n files. You can redistribute these\n files as is or repackage this data by\n including it in source code, a\n database, or another format. You are\n permitted to use excerpts of this data\n rather than the entire data set.</p>\n</blockquote>\n\n<pre><code>Note Microsoft bears no responsibility for the content or\nusage of these files. Certain locales have specific legal requirements with\nregard to providing data of this type; ensure you are in compliance with such\nregulations. \n</code></pre>\n\n<blockquote>\n <p>If you use the city data\n provided or if you use any type of\n geographical information from any\n source, you are encouraged to provide\n a way for users to edit, add, and\n delete information.</p>\n</blockquote>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| Is there a way to retrieve the time zone choices in Windows Mobile in order to display them in a GUI? It would be much better not to have to show every 15 minutes just to be
able to display GMT+5:45 for Kathmandu. | As per [MSDN:City List and Time Zone Data Files](http://msdn.microsoft.com/en-us/library/aa458853.aspx),
>
> You can add or remove content to these
> files. You can redistribute these
> files as is or repackage this data by
> including it in source code, a
> database, or another format. You are
> permitted to use excerpts of this data
> rather than the entire data set.
>
>
>
```
Note Microsoft bears no responsibility for the content or
usage of these files. Certain locales have specific legal requirements with
regard to providing data of this type; ensure you are in compliance with such
regulations.
```
>
> If you use the city data
> provided or if you use any type of
> geographical information from any
> source, you are encouraged to provide
> a way for users to edit, add, and
> delete information.
>
>
> |
134,374 | <p>I would like to listen to method calls.</p>
<p>For example, when an element is appended by anything to the document, I would like to be passed that element to act on it, like:</p>
<p>//somewhere</p>
<pre><code>aParent.appendChild(aChild);
</code></pre>
<p>//when the former, a function I defined as listener is called with the <code>aChild</code> as argument</p>
<p>Does anybody know how to do that?</p>
| [
{
"answer_id": 134420,
"author": "Filini",
"author_id": 21162,
"author_profile": "https://Stackoverflow.com/users/21162",
"pm_score": 1,
"selected": false,
"text": "<p>don't know if that's possible with the core functions, but you could always create your own functions, for the actions you want to monitor:</p>\n\n<pre><code>\nfunction AppendChild(oParent, oChild) {\n\n // your stuff on oParent\n\n // append oChild\n oParent.appendChild(oChild)\n}\n</code></pre>\n\n<p>or, maybe, modify the actual appendChild(), but that would be tricky...</p>\n"
},
{
"answer_id": 134447,
"author": "Rakesh Pai",
"author_id": 20089,
"author_profile": "https://Stackoverflow.com/users/20089",
"pm_score": 0,
"selected": false,
"text": "<p>I know that the Dojo Toolkit provides this functionality. You can some explanation <a href=\"http://dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/event-system/simple-connections-dojo-connect\" rel=\"nofollow noreferrer\">here</a> - jump to the section that says \"Connecting Functions to One Another\". If you are interested, you can look at <a href=\"http://archive.dojotoolkit.org/nightly/dojotoolkit/dojo/_base/connect.js\" rel=\"nofollow noreferrer\">the source of dojo.connect</a> to see what's going on.</p>\n"
},
{
"answer_id": 134451,
"author": "Zach",
"author_id": 9128,
"author_profile": "https://Stackoverflow.com/users/9128",
"pm_score": 0,
"selected": false,
"text": "<p>In Firefox you could rewrite <a href=\"http://www.xulplanet.com/references/objref/Node.html\" rel=\"nofollow noreferrer\">Node</a>.prototype.appendChild to call your own function (saving the original appendChild first, then calling it within) to perform additional actions. </p>\n\n<pre><code>Node.prototype._appendChild = Node.prototype.appendChild;\nNode.prototype.appendChild = function myFunct(el){....; this._appendChild(el);}\n</code></pre>\n\n<p>Internet Explorer doesn't implement these interfaces (but there might be a workaround floating around, maybe using .htc..). IE8 will have Element instead of Node.</p>\n"
},
{
"answer_id": 134681,
"author": "Chris Noe",
"author_id": 14749,
"author_profile": "https://Stackoverflow.com/users/14749",
"pm_score": 0,
"selected": false,
"text": "<p>What you're describing is <a href=\"http://en.wikipedia.org/wiki/Aspect-oriented_programming\" rel=\"nofollow noreferrer\">Aspect Oriented programming</a>. In AOP parlance, your \"join point\" would be element.appendChild(), and your \"advice\" is the function that you would like to execute (before and/or after) every matching join point executes.</p>\n\n<p>I've been keenly interested in possibilties for JavaScript AOP this for some time, and I just found this <a href=\"http://www.dotvoid.com/2005/06/aspect-oriented-programming-and-javascript/\" rel=\"nofollow noreferrer\">Aspect Oriented Programming and javascript</a>, which looks promising without needed to adopt a big old API. -- I'm really glad that you brought this up. I have uses for this, like temporary logging, timing code segments, etc.</p>\n"
},
{
"answer_id": 134754,
"author": "Rontologist",
"author_id": 13925,
"author_profile": "https://Stackoverflow.com/users/13925",
"pm_score": 0,
"selected": false,
"text": "<p>Multiple browsers handle the DOM in different ways, and unfortunately the way IE handles things is not as powerful as the way Mozilla does. The easiest way to do it is by using a custom function like the one that Filini mentioned.</p>\n\n<p>However you could also wrap the different browsers DOM objects in a facade and use it for all element access. This is a bit more work but you would then be able to handle all the browsers in the same way and be able to add/remove listeners with ease. I'm not sure if it would be anymore useful than the custom functions, but worth a look at.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I would like to listen to method calls.
For example, when an element is appended by anything to the document, I would like to be passed that element to act on it, like:
//somewhere
```
aParent.appendChild(aChild);
```
//when the former, a function I defined as listener is called with the `aChild` as argument
Does anybody know how to do that? | don't know if that's possible with the core functions, but you could always create your own functions, for the actions you want to monitor:
```
function AppendChild(oParent, oChild) {
// your stuff on oParent
// append oChild
oParent.appendChild(oChild)
}
```
or, maybe, modify the actual appendChild(), but that would be tricky... |
134,379 | <p>Is it possible to do a <code>SELECT</code> statement with a predetermined order, ie. selecting IDs 7,2,5,9 and 8 <strong>and returning them in that order</strong>, based on nothing more than the ID field?</p>
<p>Both these statements return them in the same order: </p>
<pre><code>SELECT id FROM table WHERE id in (7,2,5,9,8)
</code></pre>
<pre><code>SELECT id FROM table WHERE id in (8,2,5,9,7)
</code></pre>
| [
{
"answer_id": 134391,
"author": "Teifion",
"author_id": 1384652,
"author_profile": "https://Stackoverflow.com/users/1384652",
"pm_score": 0,
"selected": false,
"text": "<p>All ordering is done by the ORDER BY keywords, you can only however sort ascending and descending. If you are using a language such as PHP you can then sort them accordingly using some code but I do not believe it is possible with MySQL alone.</p>\n"
},
{
"answer_id": 134394,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 0,
"selected": false,
"text": "<p>This works in Oracle. Can you do something similar in MySql?</p>\n\n<pre><code>SELECT ID_FIELD\nFROM SOME_TABLE\nWHERE ID_FIELD IN(11,10,14,12,13)\nORDER BY\n CASE WHEN ID_FIELD = 11 THEN 0\n WHEN ID_FIELD = 10 THEN 1\n WHEN ID_FIELD = 14 THEN 2\n WHEN ID_FIELD = 12 THEN 3\n WHEN ID_FIELD = 13 THEN 4\n END\n</code></pre>\n"
},
{
"answer_id": 134395,
"author": "Jonathan Tran",
"author_id": 12887,
"author_profile": "https://Stackoverflow.com/users/12887",
"pm_score": 1,
"selected": false,
"text": "<p>Could you include a case expression that maps your IDs 7,2,5,... to the ordinals 1,2,3,... and then order by that expression?</p>\n"
},
{
"answer_id": 134401,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 6,
"selected": true,
"text": "<p>I didn't think this was possible, but found a <a href=\"http://www.handgestrickt.biz/item/21/\" rel=\"noreferrer\">blog entry here</a> that seems to do the type of thing you're after:</p>\n\n<pre><code>SELECT id FROM table WHERE id in (7,2,5,9,8) \nORDER BY FIND_IN_SET(id,\"7,2,5,9,8\");\n</code></pre>\n\n<p>will give different results to</p>\n\n<pre><code>SELECT id FROM table WHERE id in (7,2,5,9,8) \nORDER BY FIND_IN_SET(id,\"8,2,5,9,7\");\n</code></pre>\n\n<p><code><a href=\"http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set\" rel=\"noreferrer\">FIND_IN_SET</a></code> returns the position of <code>id</code> in the second argument given to it, so for the first case above, <code>id</code> of 7 is at position 1 in the set, 2 at 2 and so on - mysql internally works out something like</p>\n\n<pre><code>id | FIND_IN_SET\n---|-----------\n7 | 1\n2 | 2\n5 | 3\n</code></pre>\n\n<p>then orders by the results of <code>FIND_IN_SET</code>.</p>\n"
},
{
"answer_id": 134404,
"author": "Brian",
"author_id": 2831,
"author_profile": "https://Stackoverflow.com/users/2831",
"pm_score": 0,
"selected": false,
"text": "<p>You may need to create a temp table with an autonumber field and insert into it in the desired order. Then sort on the new autonumber field.</p>\n"
},
{
"answer_id": 134410,
"author": "Chris Vest",
"author_id": 13251,
"author_profile": "https://Stackoverflow.com/users/13251",
"pm_score": 0,
"selected": false,
"text": "<p>It's hacky (and probably slow), but you can get the effect with UNION ALL:</p>\n\n<pre><code>SELECT id FROM table WHERE id = 7\nUNION ALL SELECT id FROM table WHERE id = 2\nUNION ALL SELECT id FROM table WHERE id = 5\nUNION ALL SELECT id FROM table WHERE id = 9\nUNION ALL SELECT id FROM table WHERE id = 8;\n</code></pre>\n\n<p><strong>Edit:</strong> Other people mentioned the find_in_set function which is documented <a href=\"http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 134412,
"author": "Carra",
"author_id": 21679,
"author_profile": "https://Stackoverflow.com/users/21679",
"pm_score": -1,
"selected": false,
"text": "<p>Best I can think of is adding a second Column orderColumn:</p>\n\n<pre><code>7 1\n2 2\n5 3\n9 4 \n8 5\n</code></pre>\n\n<p>And then just do a ORDER BY orderColumn</p>\n"
},
{
"answer_id": 134417,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 0,
"selected": false,
"text": "<p>Erm, not really. Closest you can get is probably:</p>\n\n<pre><code>SELECT * FROM table WHERE id IN (3, 2, 1, 4) ORDER BY id=4, id=1, id=2, id=3\n</code></pre>\n\n<p>But you probably don't want that :)</p>\n\n<p>It's hard to give you any more specific advice without more information about what's in the tables.</p>\n"
},
{
"answer_id": 134432,
"author": "Matthias Winkelmann",
"author_id": 4494,
"author_profile": "https://Stackoverflow.com/users/4494",
"pm_score": 2,
"selected": false,
"text": "<p>Your best bet is:</p>\n\n<pre><code>ORDER BY FIELD(ID,7,2,4,5,8) \n</code></pre>\n\n<p>...but it's still ugly.</p>\n"
},
{
"answer_id": 134461,
"author": "kari.patila",
"author_id": 21716,
"author_profile": "https://Stackoverflow.com/users/21716",
"pm_score": 0,
"selected": false,
"text": "<p>You get answers fast around here, don't you…</p>\n\n<p>The reason I'm asking this is that it's the only way I can think of to avoid sorting a complex multidimensional array. I'm not saying it would be difficult to sort, but if there were a simpler way to do it with straight sql, then why not.</p>\n"
},
{
"answer_id": 341907,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>One Oracle solution is:</p>\n\n<pre><code>SELECT id FROM table WHERE id in (7,2,5,9,8)\nORDER BY DECODE(id,7,1,2,2,5,3,9,4,8,5,6);\n</code></pre>\n\n<p>This assigns an order number to each ID. Works OK for a small set of values.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21716/"
]
| Is it possible to do a `SELECT` statement with a predetermined order, ie. selecting IDs 7,2,5,9 and 8 **and returning them in that order**, based on nothing more than the ID field?
Both these statements return them in the same order:
```
SELECT id FROM table WHERE id in (7,2,5,9,8)
```
```
SELECT id FROM table WHERE id in (8,2,5,9,7)
``` | I didn't think this was possible, but found a [blog entry here](http://www.handgestrickt.biz/item/21/) that seems to do the type of thing you're after:
```
SELECT id FROM table WHERE id in (7,2,5,9,8)
ORDER BY FIND_IN_SET(id,"7,2,5,9,8");
```
will give different results to
```
SELECT id FROM table WHERE id in (7,2,5,9,8)
ORDER BY FIND_IN_SET(id,"8,2,5,9,7");
```
`[FIND\_IN\_SET](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set)` returns the position of `id` in the second argument given to it, so for the first case above, `id` of 7 is at position 1 in the set, 2 at 2 and so on - mysql internally works out something like
```
id | FIND_IN_SET
---|-----------
7 | 1
2 | 2
5 | 3
```
then orders by the results of `FIND_IN_SET`. |
134,387 | <p>I have a Pylons app where I would like to move some of the logic to a separate batch process. I've been running it under the main app for testing, but it is going to be doing a lot of work in the database, and I'd like it to be a separate process that will be running in the background constantly. The main pylons app will submit jobs into the database, and the new process will do the work requested in each job.</p>
<p>How can I launch a controller as a stand alone script?</p>
<p>I currently have:</p>
<pre><code>from warehouse2.controllers import importServer
importServer.runServer(60)
</code></pre>
<p>and in the controller file, but not part of the controller class:</p>
<pre><code>def runServer(sleep_secs):
try:
imp = ImportserverController()
while(True):
imp.runImport()
sleepFor(sleep_secs)
except Exception, e:
log.info("Unexpected error: %s" % sys.exc_info()[0])
log.info(e)
</code></pre>
<p>But starting ImportServer.py on the command line results in:</p>
<pre><code>2008-09-25 12:31:12.687000 Could not locate a bind configured on mapper Mapper|I
mportJob|n_imports, SQL expression or this Session
</code></pre>
| [
{
"answer_id": 135290,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 2,
"selected": true,
"text": "<p>I'm redacting my response and upvoting the other answer by Ben Bangert, as it's the correct one. I answered and have since learned the correct way (mentioned below). If you really want to, check out the history of this answer to see the wrong (but working) solution I originally proposed.</p>\n"
},
{
"answer_id": 784421,
"author": "Ben Bangert",
"author_id": 95274,
"author_profile": "https://Stackoverflow.com/users/95274",
"pm_score": 4,
"selected": false,
"text": "<p>If you want to load parts of a Pylons app, such as the models from outside Pylons, load the Pylons app in the script first:</p>\n\n<pre><code>from paste.deploy import appconfig\nfrom pylons import config\n\nfrom YOURPROJ.config.environment import load_environment\n\nconf = appconfig('config:development.ini', relative_to='.')\nload_environment(conf.global_conf, conf.local_conf)\n</code></pre>\n\n<p>That will load the Pylons app, which sets up most of the state so that you can proceed to use the SQLAlchemy models and Session to work with the database.</p>\n\n<p>Note that if your code is using the pylons globals such as request/response/etc then that won't work since they require a request to be in progress to exist.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1566663/"
]
| I have a Pylons app where I would like to move some of the logic to a separate batch process. I've been running it under the main app for testing, but it is going to be doing a lot of work in the database, and I'd like it to be a separate process that will be running in the background constantly. The main pylons app will submit jobs into the database, and the new process will do the work requested in each job.
How can I launch a controller as a stand alone script?
I currently have:
```
from warehouse2.controllers import importServer
importServer.runServer(60)
```
and in the controller file, but not part of the controller class:
```
def runServer(sleep_secs):
try:
imp = ImportserverController()
while(True):
imp.runImport()
sleepFor(sleep_secs)
except Exception, e:
log.info("Unexpected error: %s" % sys.exc_info()[0])
log.info(e)
```
But starting ImportServer.py on the command line results in:
```
2008-09-25 12:31:12.687000 Could not locate a bind configured on mapper Mapper|I
mportJob|n_imports, SQL expression or this Session
``` | I'm redacting my response and upvoting the other answer by Ben Bangert, as it's the correct one. I answered and have since learned the correct way (mentioned below). If you really want to, check out the history of this answer to see the wrong (but working) solution I originally proposed. |
134,392 | <p>I have a form in which people will be entering dollar values.</p>
<p>Possible inputs:<br>
$999,999,999.99<br>
999,999,999.99<br>
999999999<br>
99,999<br>
$99,999<br></p>
<p>The user can enter a dollar value however they wish. I want to read the inputs as doubles so I can total them.</p>
<p>I tried just typecasting the strings to doubles but that didn't work. Total just equals 50 when it is output:</p>
<pre><code>$string1 = "$50,000";
$string2 = "$50000";
$string3 = "50,000";
$total = (double)$string1 + (double)$string2 + (double)$string3;
echo $total;
</code></pre>
| [
{
"answer_id": 134402,
"author": "tim_yates",
"author_id": 6509,
"author_profile": "https://Stackoverflow.com/users/6509",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://p2p.wrox.com/topic.asp?TOPIC_ID=3099\" rel=\"nofollow noreferrer\">http://p2p.wrox.com/topic.asp?TOPIC_ID=3099</a></p>\n\n<p>goes through it step by step</p>\n\n<p>[edit] typical...the site seems to be down now... :(</p>\n"
},
{
"answer_id": 134458,
"author": "Frosty",
"author_id": 7476,
"author_profile": "https://Stackoverflow.com/users/7476",
"pm_score": 0,
"selected": false,
"text": "<p>not a one liner, but if you strip out the ','s you can do: (this is pseudocode)</p>\n\n<pre><code> m/^\\$?(\\d+)(?:\\.(\\d\\d))?$/\n $value = $1 + $2/100;\n</code></pre>\n\n<p>That allows $9.99 but not $9. or $9.9 and fails to complain about missplaced thousands separators (bug or feature?)</p>\n\n<p>There is a potential 'locality' issue here because you are assuming that thousands are done with ',' and cents as '.' but in europe it is opposite (e.g. 1.000,99)</p>\n"
},
{
"answer_id": 134467,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 3,
"selected": true,
"text": "<p>A regex won't convert your string into a number. I would suggest that you use a regex to validate the field (confirm that it fits one of your allowed formats), and then just loop over the string, discarding all non-digit and non-period characters. If you don't care about validation, you could skip the first step. The second step will still strip it down to digits and periods only.</p>\n\n<p>By the way, you cannot safely use floats when calculating currency values. You will lose precision, and very possibly end up with totals that do not exactly match the inputs.</p>\n\n<p>Update: Here are two functions you could use to verify your input and to convert it into a decimal-point representation.</p>\n\n<pre><code>function validateCurrency($string)\n{\n return preg_match('/^\\$?(\\d{1,3})(,\\d{3})*(.\\d{2})?$/', $string) ||\n preg_match('/^\\$?\\d+(.\\d{2})?$/', $string);\n}\n\nfunction makeCurrency($string)\n{\n $newstring = \"\";\n\n $array = str_split($string);\n foreach($array as $char)\n {\n if (($char >= '0' && $char <= '9') || $char == '.')\n {\n $newstring .= $char;\n }\n }\n\n return $newstring;\n}\n</code></pre>\n\n<p>The first function will match the bulk of currency formats you can expect \"$99\", \"99,999.00\", etc. It will not match \".00\" or \"99.\", nor will it match most European-style numbers (99.999,00). Use this on your original string to verify that it is a valid currency string.</p>\n\n<p>The second function will just strip out everything except digits and decimal points. Note that by itself it may still return invalid strings (e.g. \"\", \"....\", and \"abc\" come out as \"\", \"....\", and \"\"). Use this to eliminate extraneous commas once the string is validated, or possibly use this by itself if you want to skip validation.</p>\n"
},
{
"answer_id": 134471,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 0,
"selected": false,
"text": "<p>I recommend not to use a float for storing currency values. You can get rounding errors if the sum gets large. (Ok, if it gets <strong>very</strong> large.)</p>\n\n<p>Better use an integer variable with a large enough range, and store the input in cents, not dollars. </p>\n"
},
{
"answer_id": 134476,
"author": "The Brawny Man",
"author_id": 11936,
"author_profile": "https://Stackoverflow.com/users/11936",
"pm_score": 0,
"selected": false,
"text": "<p>I belive that you can accomplish this with printf, which is similar to the c function of the same name. its parameters can be somewhat esoteric though. you can also use php's <a href=\"http://us3.php.net/manual/en/function.number-format.php\" rel=\"nofollow noreferrer\">number_format</a> function</p>\n"
},
{
"answer_id": 134881,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 2,
"selected": false,
"text": "<p>You don't ever want to represent monetary values as floats!</p>\n\n<p>For example, take the following (seemingly straight forward) code:</p>\n\n<pre><code>$x = 1.0;\nfor ($ii=0; $ii < 10; $ii++) {\n $x = $x - .1;\n}\nvar_dump($x);\n</code></pre>\n\n<p>You might assume that it would produce the value zero, but that is not the case. Since <code>$x</code> is a floating point, it actually ends up being a tiny bit more than zero (1.38777878078E-16), which isn't a big deal in itself, but it means that comparing the value with another value isn't guaranteed to be correct. For example <code>$x == 0</code> would produce false.</p>\n"
},
{
"answer_id": 135175,
"author": "Ben Doom",
"author_id": 12267,
"author_profile": "https://Stackoverflow.com/users/12267",
"pm_score": 0,
"selected": false,
"text": "<p>Assuming that you are getting real money values, you could simply strip characters that are not digits or the decimal point:</p>\n\n<pre><code>(pseudocode) \nnewnumber = replace(oldnumber, /[^0-9.]/, //)\n</code></pre>\n\n<p>Now you can convert using something like </p>\n\n<pre><code>double(newnumber)\n</code></pre>\n\n<p>However, this will not take care of strings such as \"5.6.3\" and other such non-money strings. Which raises the question, \"Do you need to handle badly formatted strings?\"</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16292/"
]
| I have a form in which people will be entering dollar values.
Possible inputs:
$999,999,999.99
999,999,999.99
999999999
99,999
$99,999
The user can enter a dollar value however they wish. I want to read the inputs as doubles so I can total them.
I tried just typecasting the strings to doubles but that didn't work. Total just equals 50 when it is output:
```
$string1 = "$50,000";
$string2 = "$50000";
$string3 = "50,000";
$total = (double)$string1 + (double)$string2 + (double)$string3;
echo $total;
``` | A regex won't convert your string into a number. I would suggest that you use a regex to validate the field (confirm that it fits one of your allowed formats), and then just loop over the string, discarding all non-digit and non-period characters. If you don't care about validation, you could skip the first step. The second step will still strip it down to digits and periods only.
By the way, you cannot safely use floats when calculating currency values. You will lose precision, and very possibly end up with totals that do not exactly match the inputs.
Update: Here are two functions you could use to verify your input and to convert it into a decimal-point representation.
```
function validateCurrency($string)
{
return preg_match('/^\$?(\d{1,3})(,\d{3})*(.\d{2})?$/', $string) ||
preg_match('/^\$?\d+(.\d{2})?$/', $string);
}
function makeCurrency($string)
{
$newstring = "";
$array = str_split($string);
foreach($array as $char)
{
if (($char >= '0' && $char <= '9') || $char == '.')
{
$newstring .= $char;
}
}
return $newstring;
}
```
The first function will match the bulk of currency formats you can expect "$99", "99,999.00", etc. It will not match ".00" or "99.", nor will it match most European-style numbers (99.999,00). Use this on your original string to verify that it is a valid currency string.
The second function will just strip out everything except digits and decimal points. Note that by itself it may still return invalid strings (e.g. "", "....", and "abc" come out as "", "....", and ""). Use this to eliminate extraneous commas once the string is validated, or possibly use this by itself if you want to skip validation. |
134,453 | <p>Are there any tools available to log the page load time for a php site?</p>
<p>Mainly looking for something that I can see trends of load times over time, I was considering dumping them into a file using error_log(), but I don't know what I could use to parse it and display graphs</p>
| [
{
"answer_id": 134491,
"author": "Matthias Winkelmann",
"author_id": 4494,
"author_profile": "https://Stackoverflow.com/users/4494",
"pm_score": 2,
"selected": false,
"text": "<p>Use the Firebug extension for Firefox, it has a Net panel that shows you load times. </p>\n\n<p>If you want to do load testing, apache comes with a utility called apache bench, try ab --help in a console window near you.</p>\n"
},
{
"answer_id": 134503,
"author": "Buzz",
"author_id": 13113,
"author_profile": "https://Stackoverflow.com/users/13113",
"pm_score": 3,
"selected": false,
"text": "<p>You can record the microtime at the start of execution, hold that variable until the end, check the time, subtract them, and there you have your execution time. Output buffering will be required to make this work in most cases, unless it's a situation in which a particular thing always runs last (like <code>footer()</code>).</p>\n\n<pre><code>$time_start = microtime_float();\n\nfunction microtime_float() {\n list($usec, $sec) = explode(\" \", microtime());\n return ((float)$usec + (float)$sec);\n}\n\n//at the start. \n\n//at the end:\n\n$time_end = microtime_float();\n$time = round($time_end - $time_start, 4);\n\necho \"Last uncached content render took $time seconds\";\n</code></pre>\n"
},
{
"answer_id": 134723,
"author": "Gary Richardson",
"author_id": 2506,
"author_profile": "https://Stackoverflow.com/users/2506",
"pm_score": 0,
"selected": false,
"text": "<p>See <a href=\"http://pear.php.net/package/Benchmark/\" rel=\"nofollow noreferrer\">PEAR Benchmark</a>. It allows you to add benchmarks into your code. You can have it dump an HTML table on your pages, or you can loop through the data and write to a log file.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| Are there any tools available to log the page load time for a php site?
Mainly looking for something that I can see trends of load times over time, I was considering dumping them into a file using error\_log(), but I don't know what I could use to parse it and display graphs | You can record the microtime at the start of execution, hold that variable until the end, check the time, subtract them, and there you have your execution time. Output buffering will be required to make this work in most cases, unless it's a situation in which a particular thing always runs last (like `footer()`).
```
$time_start = microtime_float();
function microtime_float() {
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
//at the start.
//at the end:
$time_end = microtime_float();
$time = round($time_end - $time_start, 4);
echo "Last uncached content render took $time seconds";
``` |
134,456 | <p>This</p>
<pre><code>SELECT * FROM SOME_TABLE WHERE SOME_FIELD LIKE '%some_value%';
</code></pre>
<p>is slower than this</p>
<pre><code>SELECT * FROM SOME_TABLE WHERE SOME_FIELD = 'some_value';
</code></pre>
<p>but what about this?</p>
<pre><code>SELECT * FROM SOME_TABLE WHERE SOME_FIELD LIKE 'some_value';
</code></pre>
<p>My testing indicates the second and third examples are exactly the same. If that's true, my question is, why ever use "=" ?</p>
| [
{
"answer_id": 134472,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 3,
"selected": false,
"text": "<p>Check out the <a href=\"http://www.adp-gmbh.ch/ora/explainplan.html\" rel=\"nofollow noreferrer\">EXPLAIN PLAN</a> for both. They generate the same execution plan, so to the database, they're the same thing.</p>\n\n<p>You would use = to test for equality, not similarity. If you're controlling the comparison value as well, then it doesn't make much of a difference. If that's being submitted by a user, then 'apple' and 'apple%' would give you much different results.</p>\n"
},
{
"answer_id": 134527,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried it? Testing is the only sure way to know.</p>\n\n<p>As an aside, none of these statements are certain to return the same rows. Try out:</p>\n\n<pre><code>insert into some_table (some_field) values ('some_value');\ninsert into some_table (some_fieled) values ('1some_value2');\ninsert into some_table (some_field) values ('some1value');\n\nSELECT * FROM SOME_TABLE WHERE SOME_FIELD LIKE '%some_value%';\n\nSELECT * FROM SOME_TABLE WHERE SOME_FIELD = 'some_value';\n\nSELECT * FROM SOME_TABLE WHERE SOME_FIELD LIKE 'some_value';\n</code></pre>\n\n<p>In terms of clarity and to avoid subtle bugs, it's best to never use <strong>LIKE</strong> unless you need it's wildcard functionality. (Obviously, when doing ad-hoc queries, it's probably alright.)</p>\n"
},
{
"answer_id": 134533,
"author": "oglester",
"author_id": 2017,
"author_profile": "https://Stackoverflow.com/users/2017",
"pm_score": 1,
"selected": false,
"text": "<p>LIKE '%WHATEVER%' will have to do a full index scan.</p>\n\n<p>If there is not percent, then it acts like an equals.</p>\n\n<p>If the % is on one end, then the index can be a range scan. </p>\n\n<p>I'm not sure how the optimizer handles bound fields. </p>\n"
},
{
"answer_id": 134553,
"author": "David Aldridge",
"author_id": 6742,
"author_profile": "https://Stackoverflow.com/users/6742",
"pm_score": 5,
"selected": true,
"text": "<p>There is a clear difference when you use bind variables, which you should be using in Oracle for anything other than data warehousing or other bulk data operations.</p>\n\n<p>Take the case of:</p>\n\n<pre><code>SELECT * FROM SOME_TABLE WHERE SOME_FIELD LIKE :b1\n</code></pre>\n\n<p>Oracle cannot know that the value of :b1 is '%some_value%', or 'some_value' etc. until execution time, so it will make an estimation of the cardinality of the result based on heuristics and come up with an appropriate plan that either may or may not be suitable for various values of :b, such as '%A','%', 'A' etc.</p>\n\n<p>Similar issues can apply with an equality predicate but the range of cardinalities that might result is much more easily estimated based on column statistics or the presence of a unique constraint, for example.</p>\n\n<p>So, personally I wouldn't start using LIKE as a replacement for =. The optimizer is pretty easy to fool sometimes.</p>\n"
},
{
"answer_id": 134604,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>If that's true, my question is, why\n ever use \"=\" ?</p>\n</blockquote>\n\n<p>A better question: If that's true, why use \"LIKE\" to test for equality? You get to save hitting the shift key, and everyone who reads the script gets to be confused.</p>\n"
},
{
"answer_id": 134717,
"author": "borjab",
"author_id": 16206,
"author_profile": "https://Stackoverflow.com/users/16206",
"pm_score": 1,
"selected": false,
"text": "<p><code>like</code> is formally the same if you do not have characters like <code>$%</code> etc so it is not a big surprise to find that it has the same cost. </p>\n\n<p>I find David Aldridge answer interesting as your application should be using bind variables. With a <code>like '%foobar'</code> you cannot make use of ordering in the index. If the query is pre-compiled It will lead to more index or table full Scans.</p>\n\n<p>Furthermore, I find it dangerous as it can lead to SQL Injections and strange bugs ( for example, if there is a user called john a hacker can create a user named <code>'joh$'</code> and try to log in)</p>\n\n<p>why take the risk? <code>'='</code> is clearer and has none of those problems. </p>\n"
},
{
"answer_id": 52987687,
"author": "user3260035",
"author_id": 3260035,
"author_profile": "https://Stackoverflow.com/users/3260035",
"pm_score": 0,
"selected": false,
"text": "<p>1) % and = are intended to be used in different scenarios. \nEven though we can search with exact value in like clause and get the desired result, one should still be using = in all such scenarios. Therefore whenever we have exact value to be searched we always should be using =.</p>\n\n<p>2) performance of like and = whenever no % is provided in search clause:\nIn all such cases, query optimizer automatically converts like cluase to =. And this can be evident from query plan (Please see screenshots attached) . Therefore performance should be exactly the same in this case. Thanks to query optimizer!</p>\n\n<p>I am providing the screenshots of the execution plans of both the queries i.e. query with like clause but without % and query with like clause and with %.</p>\n\n<p><a href=\"https://i.stack.imgur.com/goXca.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/goXca.png\" alt=\"like Cluase with % query execution plan\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/FPR7f.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FPR7f.png\" alt=\"like clause without % query execution plan\"></a></p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672/"
]
| This
```
SELECT * FROM SOME_TABLE WHERE SOME_FIELD LIKE '%some_value%';
```
is slower than this
```
SELECT * FROM SOME_TABLE WHERE SOME_FIELD = 'some_value';
```
but what about this?
```
SELECT * FROM SOME_TABLE WHERE SOME_FIELD LIKE 'some_value';
```
My testing indicates the second and third examples are exactly the same. If that's true, my question is, why ever use "=" ? | There is a clear difference when you use bind variables, which you should be using in Oracle for anything other than data warehousing or other bulk data operations.
Take the case of:
```
SELECT * FROM SOME_TABLE WHERE SOME_FIELD LIKE :b1
```
Oracle cannot know that the value of :b1 is '%some\_value%', or 'some\_value' etc. until execution time, so it will make an estimation of the cardinality of the result based on heuristics and come up with an appropriate plan that either may or may not be suitable for various values of :b, such as '%A','%', 'A' etc.
Similar issues can apply with an equality predicate but the range of cardinalities that might result is much more easily estimated based on column statistics or the presence of a unique constraint, for example.
So, personally I wouldn't start using LIKE as a replacement for =. The optimizer is pretty easy to fool sometimes. |
134,463 | <p>I am using a popup menu in Delphi. I want to use it in a "radio group" fashion where if the user selects an item it is checked and the other items are not checked. I tried using the AutoCheck property, but this allows multiple items to be checked. Is there a way to set the popup menu so that only one item can be checked?</p>
| [
{
"answer_id": 134583,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 4,
"selected": true,
"text": "<p>Zartog is right, but if you want to keep the checkbox, assign this event to every item in the popup menu.</p>\n\n<p>Note that this code is a little hairy looking because it does not depend on knowing the name of your popup menu (hence, looking it up with \"GetParentComponent\").</p>\n\n<pre><code>procedure TForm2.OnPopupItemClick(Sender: TObject);\nvar\n i : integer;\nbegin\n with (Sender as TMenuItem) do begin\n //if they just checked something...\n if Checked then begin\n //go through the list and *un* check everything *else*\n for i := 0 to (GetParentComponent as TPopupMenu).Items.Count - 1 do begin\n if i <> MenuIndex then begin //don't uncheck the one they just clicked!\n (GetParentComponent as TPopupMenu).Items[i].Checked := False;\n end; //if not the one they just clicked\n end; //for each item in the popup\n end; //if we checked something\n end; //with\nend;\n</code></pre>\n\n<p>You can assign the event at runtime to every popup box on your form like this (if you want to do that):</p>\n\n<pre><code>procedure TForm2.FormCreate(Sender: TObject);\nvar\n i,j: integer;\nbegin\n inherited;\n\n //look for any popup menus, and assign our custom checkbox handler to them\n if Sender is TForm then begin\n with (Sender as TForm) do begin\n for i := 0 to ComponentCount - 1 do begin\n if (Components[i] is TPopupMenu) then begin\n for j := 0 to (Components[i] as TPopupMenu).Items.Count - 1 do begin\n (Components[i] as TPopupMenu).Items[j].OnClick := OnPopupItemClick;\n end; //for every item in the popup list we found\n end; //if we found a popup list\n end; //for every component on the form\n end; //with the form\n end; //if we are looking at a form\nend;\n</code></pre>\n\n<p>In response to a comment below this answer: If you want to require at least one item to be checked, then use this instead of the first code block. You may want to set a default checked item in the oncreate event.</p>\n\n<pre><code>procedure TForm2.OnPopupItemClick(Sender: TObject);\nvar\n i : integer;\nbegin\n with (Sender as TMenuItem) do begin\n //go through the list and make sure *only* the clicked item is checked\n for i := 0 to (GetParentComponent as TPopupMenu).Items.Count - 1 do begin\n (GetParentComponent as TPopupMenu).Items[i].Checked := (i = MenuIndex);\n end; //for each item in the popup\n end; //with\nend;\n</code></pre>\n"
},
{
"answer_id": 134607,
"author": "Zartog",
"author_id": 9467,
"author_profile": "https://Stackoverflow.com/users/9467",
"pm_score": 4,
"selected": false,
"text": "<p>To treat the popup (or any other) menu items like radio group items, set the 'RadioItem' property to true for each item you want to have in the radio group.</p>\n\n<p>Instead of showing a checkmark, it will show a bullet by the selected item, but it will work the way you want, and the visual cue will actually match a windows standard.</p>\n"
},
{
"answer_id": 137920,
"author": "Gerry Coll",
"author_id": 22545,
"author_profile": "https://Stackoverflow.com/users/22545",
"pm_score": 2,
"selected": false,
"text": "<p>To enlarge on Zartog's post: Popup menus in Delphi (from at least D6) have a GroupIndex property which allow you to have multiple sets of radio items within a menu. Set GroupIndex to 1 for the first group, 2 for a second etc.</p>\n\n<p>So:\n Set AutoCheck = True\n Set RadioItem = True\n Set GroupIndex if you need more than one group of radio items</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12833/"
]
| I am using a popup menu in Delphi. I want to use it in a "radio group" fashion where if the user selects an item it is checked and the other items are not checked. I tried using the AutoCheck property, but this allows multiple items to be checked. Is there a way to set the popup menu so that only one item can be checked? | Zartog is right, but if you want to keep the checkbox, assign this event to every item in the popup menu.
Note that this code is a little hairy looking because it does not depend on knowing the name of your popup menu (hence, looking it up with "GetParentComponent").
```
procedure TForm2.OnPopupItemClick(Sender: TObject);
var
i : integer;
begin
with (Sender as TMenuItem) do begin
//if they just checked something...
if Checked then begin
//go through the list and *un* check everything *else*
for i := 0 to (GetParentComponent as TPopupMenu).Items.Count - 1 do begin
if i <> MenuIndex then begin //don't uncheck the one they just clicked!
(GetParentComponent as TPopupMenu).Items[i].Checked := False;
end; //if not the one they just clicked
end; //for each item in the popup
end; //if we checked something
end; //with
end;
```
You can assign the event at runtime to every popup box on your form like this (if you want to do that):
```
procedure TForm2.FormCreate(Sender: TObject);
var
i,j: integer;
begin
inherited;
//look for any popup menus, and assign our custom checkbox handler to them
if Sender is TForm then begin
with (Sender as TForm) do begin
for i := 0 to ComponentCount - 1 do begin
if (Components[i] is TPopupMenu) then begin
for j := 0 to (Components[i] as TPopupMenu).Items.Count - 1 do begin
(Components[i] as TPopupMenu).Items[j].OnClick := OnPopupItemClick;
end; //for every item in the popup list we found
end; //if we found a popup list
end; //for every component on the form
end; //with the form
end; //if we are looking at a form
end;
```
In response to a comment below this answer: If you want to require at least one item to be checked, then use this instead of the first code block. You may want to set a default checked item in the oncreate event.
```
procedure TForm2.OnPopupItemClick(Sender: TObject);
var
i : integer;
begin
with (Sender as TMenuItem) do begin
//go through the list and make sure *only* the clicked item is checked
for i := 0 to (GetParentComponent as TPopupMenu).Items.Count - 1 do begin
(GetParentComponent as TPopupMenu).Items[i].Checked := (i = MenuIndex);
end; //for each item in the popup
end; //with
end;
``` |
134,470 | <p>I have two controllers which share most of their code (but must be, nonetheless, different controllers). The obvious solution (to me, at least) is to create a class, and make the two controllers inherit from it. The thing is... where to put it? Now I have it in app_controller.php, but it's kind of messy there.</p>
| [
{
"answer_id": 134504,
"author": "tyshock",
"author_id": 16448,
"author_profile": "https://Stackoverflow.com/users/16448",
"pm_score": 4,
"selected": true,
"text": "<p>In cake, components are used to store logic that can be used by multiple controllers. The directory is /app/controllers/components. For instance, if you had some sharable utility logic, you would have an object called UtilComponent and a file in /app/controlers/components called UtilComponent.php. </p>\n\n<pre><code><?php\nclass UtilComponent extends Object {\n function yourMethod($param) {\n // logic here.......\n\n return $param;\n }\n}\n?>\n</code></pre>\n\n<p>Then, in your controller classes, you would add:</p>\n\n<pre><code>var $components = array('Util');\n</code></pre>\n\n<p>Then you call the methods like:</p>\n\n<pre><code>$this->Util->yourMethod($yourparam);\n</code></pre>\n\n<p>More Info:</p>\n\n<p><a href=\"http://book.cakephp.org/view/315/Components\" rel=\"noreferrer\">Documentation</a></p>\n"
},
{
"answer_id": 138542,
"author": "Alexander Morland",
"author_id": 4013,
"author_profile": "https://Stackoverflow.com/users/4013",
"pm_score": 2,
"selected": false,
"text": "<p>Btw, if the reason for \"they must be seperate controllers\" is the URLs you require. Remember you can use routing:</p>\n\n<pre><code>Router::connect('/posts', array('controller' => 'posts', 'action' => 'index'));\nRouter::connect('/comments', array('controller' => 'posts', 'action' => 'list_comments'));\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18396/"
]
| I have two controllers which share most of their code (but must be, nonetheless, different controllers). The obvious solution (to me, at least) is to create a class, and make the two controllers inherit from it. The thing is... where to put it? Now I have it in app\_controller.php, but it's kind of messy there. | In cake, components are used to store logic that can be used by multiple controllers. The directory is /app/controllers/components. For instance, if you had some sharable utility logic, you would have an object called UtilComponent and a file in /app/controlers/components called UtilComponent.php.
```
<?php
class UtilComponent extends Object {
function yourMethod($param) {
// logic here.......
return $param;
}
}
?>
```
Then, in your controller classes, you would add:
```
var $components = array('Util');
```
Then you call the methods like:
```
$this->Util->yourMethod($yourparam);
```
More Info:
[Documentation](http://book.cakephp.org/view/315/Components) |
134,481 | <p>What I have now (which successfully loads the plug-in) is this:</p>
<pre><code>Assembly myDLL = Assembly.LoadFrom("my.dll");
IMyClass myPluginObject = myDLL.CreateInstance("MyCorp.IMyClass") as IMyClass;
</code></pre>
<p>This only works for a class that has a constructor with no arguments. How do I pass in an argument to a constructor?</p>
| [
{
"answer_id": 134484,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 2,
"selected": false,
"text": "<p>You can with <a href=\"http://msdn.microsoft.com/en-us/library/wcxyzt4d.aspx\" rel=\"nofollow noreferrer\">Activator.CreateInstance</a></p>\n"
},
{
"answer_id": 134497,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "<p>Activator.CreateInstance takes a Type and whatever you want to pass to the Types constructor.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx</a></p>\n"
},
{
"answer_id": 134502,
"author": "MagicKat",
"author_id": 8505,
"author_profile": "https://Stackoverflow.com/users/8505",
"pm_score": 2,
"selected": false,
"text": "<p>call</p>\n\n<pre><code>public object CreateInstance(string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)\n</code></pre>\n\n<p>instead. \n<a href=\"http://msdn.microsoft.com/en-us/library/ck6xe688.aspx\" rel=\"nofollow noreferrer\">MSDN Docs</a></p>\n\n<p>EDIT: If you are going to vote this down, please give insight into why this approach is wrong/or not the best way.</p>\n"
},
{
"answer_id": 134768,
"author": "Magnus Akselvoll",
"author_id": 4683,
"author_profile": "https://Stackoverflow.com/users/4683",
"pm_score": 5,
"selected": true,
"text": "<p>You cannot. Instead use <a href=\"http://msdn.microsoft.com/en-us/library/wcxyzt4d.aspx\" rel=\"noreferrer\">Activator.CreateInstance</a> as shown in the example below (note that the Client namespace is in one DLL and the Host in another. Both must be found in the same directory for code to work.)</p>\n\n<p>However, if you want to create a truly pluggable interface, I suggest you use an Initialize method that take the given parameters in your interface, instead of relying on constructors. That way you can just demand that the plugin class implement your interface, instead of \"hoping\" that it accepts the accepted parameters in the constructor.</p>\n\n<pre><code>using System;\nusing Host;\n\nnamespace Client\n{\n public class MyClass : IMyInterface\n {\n public int _id;\n public string _name;\n\n public MyClass(int id,\n string name)\n {\n _id = id;\n _name = name;\n }\n\n public string GetOutput()\n {\n return String.Format(\"{0} - {1}\", _id, _name);\n }\n }\n}\n\n\nnamespace Host\n{\n public interface IMyInterface\n {\n string GetOutput();\n }\n}\n\n\nusing System;\nusing System.Reflection;\n\nnamespace Host\n{\n internal class Program\n {\n private static void Main()\n {\n //These two would be read in some configuration\n const string dllName = \"Client.dll\";\n const string className = \"Client.MyClass\";\n\n try\n {\n Assembly pluginAssembly = Assembly.LoadFrom(dllName);\n Type classType = pluginAssembly.GetType(className);\n\n var plugin = (IMyInterface) Activator.CreateInstance(classType,\n 42, \"Adams\");\n\n if (plugin == null)\n throw new ApplicationException(\"Plugin not correctly configured\");\n\n Console.WriteLine(plugin.GetOutput());\n }\n catch (Exception e)\n {\n Console.Error.WriteLine(e.ToString());\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 3058651,
"author": "thames",
"author_id": 79057,
"author_profile": "https://Stackoverflow.com/users/79057",
"pm_score": 0,
"selected": false,
"text": "<p>You can also not use Activator.CreateInstance, which could perform better. See below StackOverflow question.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/2024435/how-to-pass-ctor-args-in-activator-createinstance\">How to pass ctor args in Activator.CreateInstance or use IL?</a></p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22252/"
]
| What I have now (which successfully loads the plug-in) is this:
```
Assembly myDLL = Assembly.LoadFrom("my.dll");
IMyClass myPluginObject = myDLL.CreateInstance("MyCorp.IMyClass") as IMyClass;
```
This only works for a class that has a constructor with no arguments. How do I pass in an argument to a constructor? | You cannot. Instead use [Activator.CreateInstance](http://msdn.microsoft.com/en-us/library/wcxyzt4d.aspx) as shown in the example below (note that the Client namespace is in one DLL and the Host in another. Both must be found in the same directory for code to work.)
However, if you want to create a truly pluggable interface, I suggest you use an Initialize method that take the given parameters in your interface, instead of relying on constructors. That way you can just demand that the plugin class implement your interface, instead of "hoping" that it accepts the accepted parameters in the constructor.
```
using System;
using Host;
namespace Client
{
public class MyClass : IMyInterface
{
public int _id;
public string _name;
public MyClass(int id,
string name)
{
_id = id;
_name = name;
}
public string GetOutput()
{
return String.Format("{0} - {1}", _id, _name);
}
}
}
namespace Host
{
public interface IMyInterface
{
string GetOutput();
}
}
using System;
using System.Reflection;
namespace Host
{
internal class Program
{
private static void Main()
{
//These two would be read in some configuration
const string dllName = "Client.dll";
const string className = "Client.MyClass";
try
{
Assembly pluginAssembly = Assembly.LoadFrom(dllName);
Type classType = pluginAssembly.GetType(className);
var plugin = (IMyInterface) Activator.CreateInstance(classType,
42, "Adams");
if (plugin == null)
throw new ApplicationException("Plugin not correctly configured");
Console.WriteLine(plugin.GetOutput());
}
catch (Exception e)
{
Console.Error.WriteLine(e.ToString());
}
}
}
}
``` |
134,492 | <p>I am able to serialize an object into a file and then restore it again as is shown in the next code snippet. I would like to serialize the object into a string and store into a database instead. Can anyone help me?</p>
<pre><code>LinkedList<Diff_match_patch.Patch> patches = // whatever...
FileOutputStream fileStream = new FileOutputStream("foo.ser");
ObjectOutputStream os = new ObjectOutputStream(fileStream);
os.writeObject(patches1);
os.close();
FileInputStream fileInputStream = new FileInputStream("foo.ser");
ObjectInputStream oInputStream = new ObjectInputStream(fileInputStream);
Object one = oInputStream.readObject();
LinkedList<Diff_match_patch.Patch> patches3 = (LinkedList<Diff_match_patch.Patch>) one;
os.close();
</code></pre>
| [
{
"answer_id": 134525,
"author": "Tim Frey",
"author_id": 1471,
"author_profile": "https://Stackoverflow.com/users/1471",
"pm_score": 4,
"selected": false,
"text": "<p>How about writing the data to a ByteArrayOutputStream instead of a FileOutputStream?</p>\n\n<p>Otherwise, you could serialize the object using XMLEncoder, persist the XML, then deserialize via XMLDecoder.</p>\n"
},
{
"answer_id": 134538,
"author": "Kristian",
"author_id": 11429,
"author_profile": "https://Stackoverflow.com/users/11429",
"pm_score": 2,
"selected": false,
"text": "<p>How about persisting the object as a <a href=\"https://docs.oracle.com/javase/7/docs/api/java/sql/Blob.html\" rel=\"nofollow noreferrer\">blob</a></p>\n"
},
{
"answer_id": 134550,
"author": "CiNN",
"author_id": 2566,
"author_profile": "https://Stackoverflow.com/users/2566",
"pm_score": 0,
"selected": false,
"text": "<p>you can use UUEncoding</p>\n"
},
{
"answer_id": 134556,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 2,
"selected": false,
"text": "<p>If you're storing an object as binary data in the database, then you really should use a <code>BLOB</code> datatype. The database is able to store it more efficiently, and you don't have to worry about encodings and the like. JDBC provides methods for creating and retrieving blobs in terms of streams. Use Java 6 if you can, it made some additions to the JDBC API that make dealing with blobs a whole lot easier.</p>\n\n<p>If you absolutely need to store the data as a String, I would recommend <a href=\"http://xstream.codehaus.org/\" rel=\"nofollow noreferrer\">XStream</a> for XML-based storage (much easier than <code>XMLEncoder</code>), but alternative object representations might be just as useful (e.g. JSON). Your approach depends on why you actually need to store the object in this way.</p>\n"
},
{
"answer_id": 134564,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 1,
"selected": false,
"text": "<p>The serialised stream is just a sequence of bytes (octets). So the question is how to convert a sequence of bytes to a String, and back again. Further it needs to use a limited set of character codes if it is going to be stored in a database.</p>\n\n<p>The obvious solution to the problem is to change the field to a binary LOB. If you want to stick with a characer LOB, then you'll need to encode in some scheme such as base64, hex or uu.</p>\n"
},
{
"answer_id": 134661,
"author": "Sergio del Amo",
"author_id": 2138,
"author_profile": "https://Stackoverflow.com/users/2138",
"pm_score": 3,
"selected": false,
"text": "<p>Thanks for great and quick replies. I will gives some up votes inmediately to acknowledge your help. I have coded the best solution in my opinion based on your answers. </p>\n\n<pre><code>LinkedList<Patch> patches1 = diff.patch_make(text2, text1);\ntry {\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\n ObjectOutputStream os = new ObjectOutputStream(bos);\n os.writeObject(patches1);\n String serialized_patches1 = bos.toString();\n os.close();\n\n\n ByteArrayInputStream bis = new ByteArrayInputStream(serialized_patches1.getBytes());\n ObjectInputStream oInputStream = new ObjectInputStream(bis);\n LinkedList<Patch> restored_patches1 = (LinkedList<Patch>) oInputStream.readObject(); \n\n\n\n // patches1 equals restored_patches1\n oInputStream.close();\n} catch(Exception ex) {\n ex.printStackTrace();\n}\n</code></pre>\n\n<p><strong>Note</strong> i did not considered using JSON because is less efficient.</p>\n\n<p><strong>Note:</strong> I will considered your advice about not storing serialized object as strings in the database but byte[] instead. </p>\n"
},
{
"answer_id": 134918,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 9,
"selected": true,
"text": "<p>Sergio:</p>\n\n<p>You should use <a href=\"http://docs.oracle.com/javase/6/docs/api/java/sql/Blob.html\" rel=\"noreferrer\">BLOB</a>. It is pretty straighforward with JDBC. </p>\n\n<p>The problem with the second code you posted is the encoding. You should additionally encode the bytes to make sure none of them fails.</p>\n\n<p>If you still want to write it down into a String you can encode the bytes using <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html\" rel=\"noreferrer\">java.util.Base64</a>. </p>\n\n<p>Still you should use CLOB as data type because you don't know how long the serialized data is going to be.</p>\n\n<p>Here is a sample of how to use it.</p>\n\n<pre><code>import java.util.*;\nimport java.io.*;\n\n/** \n * Usage sample serializing SomeClass instance \n */\npublic class ToStringSample {\n\n public static void main( String [] args ) throws IOException,\n ClassNotFoundException {\n String string = toString( new SomeClass() );\n System.out.println(\" Encoded serialized version \" );\n System.out.println( string );\n SomeClass some = ( SomeClass ) fromString( string );\n System.out.println( \"\\n\\nReconstituted object\");\n System.out.println( some );\n\n\n }\n\n /** Read the object from Base64 string. */\n private static Object fromString( String s ) throws IOException ,\n ClassNotFoundException {\n byte [] data = Base64.getDecoder().decode( s );\n ObjectInputStream ois = new ObjectInputStream( \n new ByteArrayInputStream( data ) );\n Object o = ois.readObject();\n ois.close();\n return o;\n }\n\n /** Write the object to a Base64 string. */\n private static String toString( Serializable o ) throws IOException {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream( baos );\n oos.writeObject( o );\n oos.close();\n return Base64.getEncoder().encodeToString(baos.toByteArray()); \n }\n}\n\n/** Test subject. A very simple class. */ \nclass SomeClass implements Serializable {\n\n private final static long serialVersionUID = 1; // See Nick's comment below\n\n int i = Integer.MAX_VALUE;\n String s = \"ABCDEFGHIJKLMNOP\";\n Double d = new Double( -1.0 );\n public String toString(){\n return \"SomeClass instance says: Don't worry, \" \n + \"I'm healthy. Look, my data is i = \" + i \n + \", s = \" + s + \", d = \" + d;\n }\n}\n</code></pre>\n\n<p>Output: </p>\n\n<pre><code>C:\\samples>javac *.java\n\nC:\\samples>java ToStringSample\nEncoded serialized version\nrO0ABXNyAAlTb21lQ2xhc3MAAAAAAAAAAQIAA0kAAWlMAAFkdAASTGphdmEvbGFuZy9Eb3VibGU7T\nAABc3QAEkxqYXZhL2xhbmcvU3RyaW5nO3hwf////3NyABBqYXZhLmxhbmcuRG91YmxlgLPCSilr+w\nQCAAFEAAV2YWx1ZXhyABBqYXZhLmxhbmcuTnVtYmVyhqyVHQuU4IsCAAB4cL/wAAAAAAAAdAAQQUJ\nDREVGR0hJSktMTU5PUA==\n\n\nReconstituted object\nSomeClass instance says: Don't worry, I'm healthy. Look, my data is i = 2147483647, s = ABCDEFGHIJKLMNOP, d = -1.0\n</code></pre>\n\n<p><strong>NOTE</strong>: for Java 7 and earlier you can see the original <a href=\"https://stackoverflow.com/revisions/134918/9\">answer here</a></p>\n"
},
{
"answer_id": 135008,
"author": "Josh",
"author_id": 2204759,
"author_profile": "https://Stackoverflow.com/users/2204759",
"pm_score": 2,
"selected": false,
"text": "<p>Take a look at the java.sql.PreparedStatement class, specifically the function</p>\n\n<p><a href=\"http://java.sun.com/javase/6/docs/api/java/sql/PreparedStatement.html#setBinaryStream(int,%20java.io.InputStream)\" rel=\"nofollow noreferrer\">http://java.sun.com/javase/6/docs/api/java/sql/PreparedStatement.html#setBinaryStream(int,%20java.io.InputStream)</a></p>\n\n<p>Then take a look at the java.sql.ResultSet class, specifically the function</p>\n\n<p><a href=\"http://java.sun.com/javase/6/docs/api/java/sql/ResultSet.html#getBinaryStream(int)\" rel=\"nofollow noreferrer\">http://java.sun.com/javase/6/docs/api/java/sql/ResultSet.html#getBinaryStream(int)</a></p>\n\n<p>Keep in mind that if you are serializing an object into a database, and then you change the object in your code in a new version, the deserialization process can easily fail because your object's signature changed. I once made this mistake with storing a custom Preferences serialized and then making a change to the Preferences definition. Suddenly I couldn't read any of the previously serialized information.</p>\n\n<p>You might be better off writing clunky per property columns in a table and composing and decomposing the object in this manner instead, to avoid this issue with object versions and deserialization. Or writing the properties into a hashmap of some sort, like a java.util.Properties object, and then serializing the properties object which is extremely unlikely to change.</p>\n"
},
{
"answer_id": 135133,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the build in classes sun.misc.Base64Decoder and sun.misc.Base64Encoder to convert the binary data of the serialize to a string. You das not need additional classes because it are build in.</p>\n"
},
{
"answer_id": 135622,
"author": "skaffman",
"author_id": 21234,
"author_profile": "https://Stackoverflow.com/users/21234",
"pm_score": 2,
"selected": false,
"text": "<p>XStream provides a simple utility for serializing/deserializing to/from XML, and it's <em>very</em> quick. Storing XML CLOBs rather than binary BLOBS is going to be less fragile, not to mention more readable.</p>\n"
},
{
"answer_id": 44328319,
"author": "Markus Schulte",
"author_id": 1645517,
"author_profile": "https://Stackoverflow.com/users/1645517",
"pm_score": 3,
"selected": false,
"text": "<p>Java8 approach, converting Object from/to String, inspired by answer from <a href=\"https://stackoverflow.com/a/134918/1645517\">OscarRyz</a>. For de-/encoding, <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html\" rel=\"nofollow noreferrer\" title=\"java.util.Base64\">java.util.Base64</a> is required and used.</p>\n\n<pre><code>import java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.io.Serializable;\nimport java.util.Base64;\nimport java.util.Optional;\n\nfinal class ObjectHelper {\n\n private ObjectHelper() {}\n\n static Optional<String> convertToString(final Serializable object) {\n try (final ByteArrayOutputStream baos = new ByteArrayOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream(baos)) {\n oos.writeObject(object);\n return Optional.of(Base64.getEncoder().encodeToString(baos.toByteArray()));\n } catch (final IOException e) {\n e.printStackTrace();\n return Optional.empty();\n }\n }\n\n static <T extends Serializable> Optional<T> convertFrom(final String objectAsString) {\n final byte[] data = Base64.getDecoder().decode(objectAsString);\n try (final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data))) {\n return Optional.of((T) ois.readObject());\n } catch (final IOException | ClassNotFoundException e) {\n e.printStackTrace();\n return Optional.empty();\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 44646354,
"author": "priyanka_rao",
"author_id": 3568094,
"author_profile": "https://Stackoverflow.com/users/3568094",
"pm_score": 1,
"selected": false,
"text": "<p>Simple Solution,worked for me</p>\n\n<pre><code>public static byte[] serialize(Object obj) throws IOException {\n ByteArrayOutputStream out = new ByteArrayOutputStream();\n ObjectOutputStream os = new ObjectOutputStream(out);\n os.writeObject(obj);\n return out.toByteArray();\n}\n</code></pre>\n"
},
{
"answer_id": 64569159,
"author": "yurin",
"author_id": 2534191,
"author_profile": "https://Stackoverflow.com/users/2534191",
"pm_score": 0,
"selected": false,
"text": "<ol start=\"2020\">\n<li></li>\n</ol>\n<p>Today the most obvious approach is to save the object(s) to JSON.</p>\n<ol>\n<li>JSON is readable</li>\n<li>JSON is more readable and easier to work with than XML.</li>\n<li>A lot of Non-SQL databases that allow storing JSON directly.</li>\n<li>Your client already communicates with the server using JSON. (If it doesn't, it is very likely a mistake.)</li>\n</ol>\n<p>Example using <a href=\"https://github.com/google/gson\" rel=\"nofollow noreferrer\">Gson</a>.</p>\n<pre><code>Gson gson = new Gson();\nPerson[] persons = getArrayOfPersons();\nString json = gson.toJson(persons);\nSystem.out.println(json);\n//output: [{"name":"Tom","age":11},{"name":"Jack","age":12}]\nPerson[] personsFromJson = gson.fromJson(json, Person[].class);\n//...\nclass Person {\n public String name;\n public int age;\n} \n</code></pre>\n<blockquote>\n<p>Gson allows converting List directly. Examples can be easily\ngoogled. I prefer to convert lists to arrays first.</p>\n</blockquote>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
]
| I am able to serialize an object into a file and then restore it again as is shown in the next code snippet. I would like to serialize the object into a string and store into a database instead. Can anyone help me?
```
LinkedList<Diff_match_patch.Patch> patches = // whatever...
FileOutputStream fileStream = new FileOutputStream("foo.ser");
ObjectOutputStream os = new ObjectOutputStream(fileStream);
os.writeObject(patches1);
os.close();
FileInputStream fileInputStream = new FileInputStream("foo.ser");
ObjectInputStream oInputStream = new ObjectInputStream(fileInputStream);
Object one = oInputStream.readObject();
LinkedList<Diff_match_patch.Patch> patches3 = (LinkedList<Diff_match_patch.Patch>) one;
os.close();
``` | Sergio:
You should use [BLOB](http://docs.oracle.com/javase/6/docs/api/java/sql/Blob.html). It is pretty straighforward with JDBC.
The problem with the second code you posted is the encoding. You should additionally encode the bytes to make sure none of them fails.
If you still want to write it down into a String you can encode the bytes using [java.util.Base64](https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html).
Still you should use CLOB as data type because you don't know how long the serialized data is going to be.
Here is a sample of how to use it.
```
import java.util.*;
import java.io.*;
/**
* Usage sample serializing SomeClass instance
*/
public class ToStringSample {
public static void main( String [] args ) throws IOException,
ClassNotFoundException {
String string = toString( new SomeClass() );
System.out.println(" Encoded serialized version " );
System.out.println( string );
SomeClass some = ( SomeClass ) fromString( string );
System.out.println( "\n\nReconstituted object");
System.out.println( some );
}
/** Read the object from Base64 string. */
private static Object fromString( String s ) throws IOException ,
ClassNotFoundException {
byte [] data = Base64.getDecoder().decode( s );
ObjectInputStream ois = new ObjectInputStream(
new ByteArrayInputStream( data ) );
Object o = ois.readObject();
ois.close();
return o;
}
/** Write the object to a Base64 string. */
private static String toString( Serializable o ) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream( baos );
oos.writeObject( o );
oos.close();
return Base64.getEncoder().encodeToString(baos.toByteArray());
}
}
/** Test subject. A very simple class. */
class SomeClass implements Serializable {
private final static long serialVersionUID = 1; // See Nick's comment below
int i = Integer.MAX_VALUE;
String s = "ABCDEFGHIJKLMNOP";
Double d = new Double( -1.0 );
public String toString(){
return "SomeClass instance says: Don't worry, "
+ "I'm healthy. Look, my data is i = " + i
+ ", s = " + s + ", d = " + d;
}
}
```
Output:
```
C:\samples>javac *.java
C:\samples>java ToStringSample
Encoded serialized version
rO0ABXNyAAlTb21lQ2xhc3MAAAAAAAAAAQIAA0kAAWlMAAFkdAASTGphdmEvbGFuZy9Eb3VibGU7T
AABc3QAEkxqYXZhL2xhbmcvU3RyaW5nO3hwf////3NyABBqYXZhLmxhbmcuRG91YmxlgLPCSilr+w
QCAAFEAAV2YWx1ZXhyABBqYXZhLmxhbmcuTnVtYmVyhqyVHQuU4IsCAAB4cL/wAAAAAAAAdAAQQUJ
DREVGR0hJSktMTU5PUA==
Reconstituted object
SomeClass instance says: Don't worry, I'm healthy. Look, my data is i = 2147483647, s = ABCDEFGHIJKLMNOP, d = -1.0
```
**NOTE**: for Java 7 and earlier you can see the original [answer here](https://stackoverflow.com/revisions/134918/9) |
134,501 | <p>Usually when I need to fork in C, I do something like this:</p>
<pre><code>pid_t p = fork();
if(p == 0) { /* do child stuff */ }
else { /* do parent stuff and pray there wasn't an error */ }
</code></pre>
<p>It occured to me that I could ditch the extra variable and use:</p>
<pre><code>if(fork() == 0) { /* child */ }
else { /* parent/pray */ }
</code></pre>
<p>Improper error handling aside, (why) does this work/not work?</p>
| [
{
"answer_id": 134528,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 2,
"selected": false,
"text": "<p>You lose the child process ID in the parent, which is what is returned to the parent. I think you could recover that information, but perhaps not uniquely (that is, I think you could get the PID of all of your children, but not necessarily the PID of the child you just forked). If you don't need to know the child's PID, I think the second way is fine.</p>\n\n<p>Also, -1 is returned if there's an error in forking, which you aren't testing for in either case, which is usually a mistake.</p>\n"
},
{
"answer_id": 134531,
"author": "Charles Graham",
"author_id": 7705,
"author_profile": "https://Stackoverflow.com/users/7705",
"pm_score": 2,
"selected": false,
"text": "<p>You should do this instead. I've never known it to not work. It's how it's done in the Stevens books.</p>\n\n<pre><code>int p;\nif((p = fork()) == 0) { /* child */ }\nelse { /* parent/pray */ }\n</code></pre>\n"
},
{
"answer_id": 134541,
"author": "AdamC",
"author_id": 16476,
"author_profile": "https://Stackoverflow.com/users/16476",
"pm_score": 1,
"selected": false,
"text": "<p>You are free to do that in C and it will work because the parent and child will receive different return values from the fork - and it is evaluated first. The only issues are the error handling as you mentioned. Also, you won't have any other way to recover the child PID in case you wanted to operate on it, such as with a waitpid, etc.</p>\n"
},
{
"answer_id": 134545,
"author": "Diomidis Spinellis",
"author_id": 20520,
"author_profile": "https://Stackoverflow.com/users/20520",
"pm_score": 5,
"selected": true,
"text": "<p>What you are suggesting will certainly work. However, error handling is not optional in any well-behaved application. The following implementation pattern is similarly succinct and also handles errors. Furthermore, it saves the fork() return value in the pid variable, in case you want to use it later in the parent to, say, wait for the child.</p>\n\n<pre><code>switch (pid = fork()) {\ncase -1: /* Failure */\n /* ... */\ncase 0: /* Child */\n /* ... */\ndefault: /* Parent */\n /* ... */\n}\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12926/"
]
| Usually when I need to fork in C, I do something like this:
```
pid_t p = fork();
if(p == 0) { /* do child stuff */ }
else { /* do parent stuff and pray there wasn't an error */ }
```
It occured to me that I could ditch the extra variable and use:
```
if(fork() == 0) { /* child */ }
else { /* parent/pray */ }
```
Improper error handling aside, (why) does this work/not work? | What you are suggesting will certainly work. However, error handling is not optional in any well-behaved application. The following implementation pattern is similarly succinct and also handles errors. Furthermore, it saves the fork() return value in the pid variable, in case you want to use it later in the parent to, say, wait for the child.
```
switch (pid = fork()) {
case -1: /* Failure */
/* ... */
case 0: /* Child */
/* ... */
default: /* Parent */
/* ... */
}
``` |
134,505 | <p>I've found mention of a data application block existing for ODBC, but can't seem to find it anywhere. If i didn't have a copy of the Access DB application block I wouldn't believe it ever existed either.</p>
<p>Anyone know where to download either the DLL or the code-base from?</p>
<p>--UPDATE: It is NOT included in either the v1, v2, or Enterprise Library versions of the Data ApplicationBlocks</p>
<p>Thanks,
Brian Swanson</p>
| [
{
"answer_id": 134521,
"author": "ScaleOvenStove",
"author_id": 12268,
"author_profile": "https://Stackoverflow.com/users/12268",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyId=F63D1F0A-9877-4A7B-88EC-0426B48DF275&displaylang=en\" rel=\"nofollow noreferrer\">http://www.microsoft.com/downloads/details.aspx?FamilyId=F63D1F0A-9877-4A7B-88EC-0426B48DF275&displaylang=en</a></p>\n\n<p>pretty sure its in there</p>\n"
},
{
"answer_id": 1014310,
"author": "ChrisC_46259",
"author_id": 95063,
"author_profile": "https://Stackoverflow.com/users/95063",
"pm_score": 3,
"selected": true,
"text": "<p>Which version of .net are you interested in using the ODBC block on?</p>\n\n<p>The Enterprise library has a Data Access component. It is useful on SQL, Oracle, and ODBC. Just set a different provider name in the .config file \nEX: </p>\n\n<p><add name=\"MyConnection\" connectionString=\"Dsn=Datasource;uid=UserID;pwd=Password\"\n providerName=<strong>\"System.Data.Odbc\"</strong> /></p>\n\n<p>At that point, the data access code is \"standardized\" and looks identical for SQL, Oracle, and ODBC </p>\n\n<p>EX: </p>\n\n<pre><code>Imports Microsoft.Practices.EnterpriseLibrary.Data\nImports Microsoft.Practices.EnterpriseLibrary.ExceptionHandling\n\n Public Class MyClass\n\n Private dbMyDatabase As Database\n\n dbMyDatabase = DatabaseFactory.CreateDatabase(\"MyConnection\")\n\n Public Function GetMyData(ByVal FacilityCode As String) As Data.DataSet\n\n Try\n Dim SQL As String\n SQL = \"SELECT * from MyDataTable\"\n Dim cmd As Data.Common.DbCommand = dbMyDatabase.GetSqlStringCommand(SQL)\n Return dbMyDatabase.ExecuteDataSet(cmd)\n Catch ex As Exception\n ExceptionPolicy.HandleException(ex, \"All\")\n Throw\n End Try\n End Function \n\n End Class\n</code></pre>\n\n<p>The address for the latest Enterprise Library is:\n<a href=\"http://msdn.microsoft.com/en-us/library/cc467894.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/cc467894.aspx</a></p>\n\n<p>This is assuming you are using .net 3x.</p>\n\n<p>Also note that we are using the Exception Handling block in the above code. </p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1795/"
]
| I've found mention of a data application block existing for ODBC, but can't seem to find it anywhere. If i didn't have a copy of the Access DB application block I wouldn't believe it ever existed either.
Anyone know where to download either the DLL or the code-base from?
--UPDATE: It is NOT included in either the v1, v2, or Enterprise Library versions of the Data ApplicationBlocks
Thanks,
Brian Swanson | Which version of .net are you interested in using the ODBC block on?
The Enterprise library has a Data Access component. It is useful on SQL, Oracle, and ODBC. Just set a different provider name in the .config file
EX:
<add name="MyConnection" connectionString="Dsn=Datasource;uid=UserID;pwd=Password"
providerName=**"System.Data.Odbc"** />
At that point, the data access code is "standardized" and looks identical for SQL, Oracle, and ODBC
EX:
```
Imports Microsoft.Practices.EnterpriseLibrary.Data
Imports Microsoft.Practices.EnterpriseLibrary.ExceptionHandling
Public Class MyClass
Private dbMyDatabase As Database
dbMyDatabase = DatabaseFactory.CreateDatabase("MyConnection")
Public Function GetMyData(ByVal FacilityCode As String) As Data.DataSet
Try
Dim SQL As String
SQL = "SELECT * from MyDataTable"
Dim cmd As Data.Common.DbCommand = dbMyDatabase.GetSqlStringCommand(SQL)
Return dbMyDatabase.ExecuteDataSet(cmd)
Catch ex As Exception
ExceptionPolicy.HandleException(ex, "All")
Throw
End Try
End Function
End Class
```
The address for the latest Enterprise Library is:
<http://msdn.microsoft.com/en-us/library/cc467894.aspx>
This is assuming you are using .net 3x.
Also note that we are using the Exception Handling block in the above code. |
134,520 | <p>Okay, this is just a crazy idea I have. Stack Overflow looks very structured and integrable into development applications. So would it be possible, even useful, to have a Stack Overflow plugin for, say, Eclipse? </p>
<p>Which features of Stack Overflow would you like to have directly integrated into your IDE so you can use it "natively" without changing to a browser?</p>
<p>EDIT: I'm thinking about ways of deeper integration than just using the web page inside the IDE. Like when you use a certain Java class and have a problem, answers from SO might flare up. There would probably be cases where something like this is annoying, but others may be very helpful.</p>
| [
{
"answer_id": 134534,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 0,
"selected": false,
"text": "<p>You could just set it as your Start Page in Visual Studio.</p>\n\n<p>Not sure what benefit this would provide... but to each his own.</p>\n"
},
{
"answer_id": 134551,
"author": "Ryan Farley",
"author_id": 1627,
"author_profile": "https://Stackoverflow.com/users/1627",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know about Eclipse, but for Visual Studio, if someone really wanted this they could easily add the SO RSS feed for the \"Start Page News Channel\" so the SO question list appeared in the start page, or even better, narrow it down with a tag (<a href=\"https://stackoverflow.com/feeds/tag/c%23\">like for C#</a>). It's not exactly \"integration\", but it would provide a quick look at recent things with extremely little effort. However, not sure how \"useful\" it would be.</p>\n"
},
{
"answer_id": 134571,
"author": "Josh Sklare",
"author_id": 21277,
"author_profile": "https://Stackoverflow.com/users/21277",
"pm_score": 3,
"selected": false,
"text": "<p>In Visual Studio, you could add a shortcut to search for a highlighted term in StackOverflow. Jeff Atwood wrote about doing something similar with Google in his <a href=\"https://blog.codinghorror.com/google-search-vsnet-macro/\" rel=\"nofollow noreferrer\">Google search VS.NET macro</a> blog entry.</p>\n\n<p>Using this approach would allow you to highlight a term or error message (or any other selectable text in the IDE), press the shortcut keys, and then see all the matching results on StackOverflow.</p>\n\n<p>I'm sure there's a way to do this in other IDE's as well.</p>\n"
},
{
"answer_id": 134582,
"author": "Kristian",
"author_id": 11429,
"author_profile": "https://Stackoverflow.com/users/11429",
"pm_score": 1,
"selected": false,
"text": "<p>You have the <a href=\"http://morphine.sourceforge.net/presence/projects/rss/index.html\" rel=\"nofollow noreferrer\">RSS plugin</a> for Eclipse to read the StackOverflow feed.</p>\n\n<p>But I'm with you, a SO Eclipse plugin would be really cool.</p>\n"
},
{
"answer_id": 134588,
"author": "Chris Wenham",
"author_id": 5548,
"author_profile": "https://Stackoverflow.com/users/5548",
"pm_score": 2,
"selected": false,
"text": "<p>If StackOverflow can begin identifying the language that each code snippet contains, then I could see an code-completion/code-snippet plugin to an IDE that responds to a special syntax for performing searches on SO and inserting the code portion of accepted answers.</p>\n\n<p>Eg: in my source I might type:</p>\n\n<pre><code>//# read an XML file\n</code></pre>\n\n<p>The //# syntax prompts the plugin to start a search and display a list of question titles. When I pick one, it inserts the code portion of the accepted answer. </p>\n"
},
{
"answer_id": 134589,
"author": "Kevin Chan",
"author_id": 1877,
"author_profile": "https://Stackoverflow.com/users/1877",
"pm_score": 4,
"selected": false,
"text": "<p>I don't think I'll be able to get any work done with SO integrated into an IDE. Its almost as bad, if not worst than integrating Digg/Reddit into an IDE.</p>\n"
},
{
"answer_id": 134935,
"author": "Chris Lawlor",
"author_id": 21245,
"author_profile": "https://Stackoverflow.com/users/21245",
"pm_score": 5,
"selected": true,
"text": "<p>Following up on Josh's answer. This VS Macro will search StackOverflow for highlighted text in the Visual Studio IDE. Just highlight and press Alt+F1</p>\n\n<pre><code>Public Sub SearchStackOverflowForSelectedText()\n Dim s As String = ActiveWindowSelection().Trim()\n If s.Length > 0 Then\n DTE.ItemOperations.Navigate(\"http://www.stackoverflow.com/search?q=\" & _\n Web.HttpUtility.UrlEncode(s))\n End If\nEnd Sub\n\nPrivate Function ActiveWindowSelection() As String\n If DTE.ActiveWindow.ObjectKind = EnvDTE.Constants.vsWindowKindOutput Then\n Return OutputWindowSelection()\n End If\n If DTE.ActiveWindow.ObjectKind = \"{57312C73-6202-49E9-B1E1-40EA1A6DC1F6}\" Then\n Return HTMLEditorSelection()\n End If\n Return SelectionText(DTE.ActiveWindow.Selection)\nEnd Function\n\nPrivate Function HTMLEditorSelection() As String\n Dim hw As HTMLWindow = ActiveDocument.ActiveWindow.Object\n Dim tw As TextWindow = hw.CurrentTabObject\n Return SelectionText(tw.Selection)\nEnd Function\n\nPrivate Function OutputWindowSelection() As String\n Dim w As Window = DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput)\n Dim ow As OutputWindow = w.Object\n Dim owp As OutputWindowPane = ow.OutputWindowPanes.Item(ow.ActivePane.Name)\n Return SelectionText(owp.TextDocument.Selection)\nEnd Function\n\nPrivate Function SelectionText(ByVal sel As EnvDTE.TextSelection) As String\n If sel Is Nothing Then\n Return \"\"\n End If\n If sel.Text.Length = 0 Then\n SelectWord(sel)\n End If\n If sel.Text.Length <= 2 Then\n Return \"\"\n End If\n Return sel.Text\nEnd Function\n\nPrivate Sub SelectWord(ByVal sel As EnvDTE.TextSelection)\n Dim leftPos As Integer\n Dim line As Integer\n Dim pt As EnvDTE.EditPoint = sel.ActivePoint.CreateEditPoint()\n\n sel.WordLeft(True, 1)\n line = sel.TextRanges.Item(1).StartPoint.Line\n leftPos = sel.TextRanges.Item(1).StartPoint.LineCharOffset\n pt.MoveToLineAndOffset(line, leftPos)\n sel.MoveToPoint(pt)\n sel.WordRight(True, 1)\nEnd Sub\n</code></pre>\n\n<p>To install:</p>\n\n<ol>\n<li>go to Tools - Macros - IDE</li>\n<li>create a new Module with a name of your choice under \"MyMacros\". Or use an existing module.</li>\n<li>paste the above code into the module</li>\n<li>add a reference to the System.Web namespace (for HttpUtility) to the module</li>\n<li>close the macro IDE window</li>\n<li>go to Tools - Options - Environment - Keyboard</li>\n<li>type \"google\" in the Show Commands Containing textbox. The SearchGoogleForSelectedText macro should show up</li>\n<li>click in the Press Shortcut Keys textbox, then press ALT+F1</li>\n<li>click the Assign button</li>\n<li>click OK</li>\n</ol>\n\n<p>This is all taken from Jeff Atwood's <a href=\"https://blog.codinghorror.com/google-search-vsnet-macro/\" rel=\"nofollow noreferrer\">Google Search VS Macro</a> post, just modified to search StackOverflow instead.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19734/"
]
| Okay, this is just a crazy idea I have. Stack Overflow looks very structured and integrable into development applications. So would it be possible, even useful, to have a Stack Overflow plugin for, say, Eclipse?
Which features of Stack Overflow would you like to have directly integrated into your IDE so you can use it "natively" without changing to a browser?
EDIT: I'm thinking about ways of deeper integration than just using the web page inside the IDE. Like when you use a certain Java class and have a problem, answers from SO might flare up. There would probably be cases where something like this is annoying, but others may be very helpful. | Following up on Josh's answer. This VS Macro will search StackOverflow for highlighted text in the Visual Studio IDE. Just highlight and press Alt+F1
```
Public Sub SearchStackOverflowForSelectedText()
Dim s As String = ActiveWindowSelection().Trim()
If s.Length > 0 Then
DTE.ItemOperations.Navigate("http://www.stackoverflow.com/search?q=" & _
Web.HttpUtility.UrlEncode(s))
End If
End Sub
Private Function ActiveWindowSelection() As String
If DTE.ActiveWindow.ObjectKind = EnvDTE.Constants.vsWindowKindOutput Then
Return OutputWindowSelection()
End If
If DTE.ActiveWindow.ObjectKind = "{57312C73-6202-49E9-B1E1-40EA1A6DC1F6}" Then
Return HTMLEditorSelection()
End If
Return SelectionText(DTE.ActiveWindow.Selection)
End Function
Private Function HTMLEditorSelection() As String
Dim hw As HTMLWindow = ActiveDocument.ActiveWindow.Object
Dim tw As TextWindow = hw.CurrentTabObject
Return SelectionText(tw.Selection)
End Function
Private Function OutputWindowSelection() As String
Dim w As Window = DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput)
Dim ow As OutputWindow = w.Object
Dim owp As OutputWindowPane = ow.OutputWindowPanes.Item(ow.ActivePane.Name)
Return SelectionText(owp.TextDocument.Selection)
End Function
Private Function SelectionText(ByVal sel As EnvDTE.TextSelection) As String
If sel Is Nothing Then
Return ""
End If
If sel.Text.Length = 0 Then
SelectWord(sel)
End If
If sel.Text.Length <= 2 Then
Return ""
End If
Return sel.Text
End Function
Private Sub SelectWord(ByVal sel As EnvDTE.TextSelection)
Dim leftPos As Integer
Dim line As Integer
Dim pt As EnvDTE.EditPoint = sel.ActivePoint.CreateEditPoint()
sel.WordLeft(True, 1)
line = sel.TextRanges.Item(1).StartPoint.Line
leftPos = sel.TextRanges.Item(1).StartPoint.LineCharOffset
pt.MoveToLineAndOffset(line, leftPos)
sel.MoveToPoint(pt)
sel.WordRight(True, 1)
End Sub
```
To install:
1. go to Tools - Macros - IDE
2. create a new Module with a name of your choice under "MyMacros". Or use an existing module.
3. paste the above code into the module
4. add a reference to the System.Web namespace (for HttpUtility) to the module
5. close the macro IDE window
6. go to Tools - Options - Environment - Keyboard
7. type "google" in the Show Commands Containing textbox. The SearchGoogleForSelectedText macro should show up
8. click in the Press Shortcut Keys textbox, then press ALT+F1
9. click the Assign button
10. click OK
This is all taken from Jeff Atwood's [Google Search VS Macro](https://blog.codinghorror.com/google-search-vsnet-macro/) post, just modified to search StackOverflow instead. |
134,569 | <p>I would like to throw an exception when my C++ methods encounter something weird and can't recover. Is it OK to throw a <code>std::string</code> pointer?</p>
<p>Here's what I was looking forward to doing:</p>
<pre><code>void Foo::Bar() {
if(!QueryPerformanceTimer(&m_baz)) {
throw new std::string("it's the end of the world!");
}
}
void Foo::Caller() {
try {
this->Bar(); // should throw
}
catch(std::string *caught) { // not quite sure the syntax is OK here...
std::cout << "Got " << caught << std::endl;
}
}
</code></pre>
| [
{
"answer_id": 134596,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 3,
"selected": false,
"text": "<p>It works, but I wouldn't do it if I were you. You don't seem to be deleting that heap data when you're done, which means that you've created a memory leak. The C++ compiler takes care of ensuring that exception data is kept alive even as the stack is popped, so don't feel that you need to use the heap.</p>\n\n<p>Incidentally, throwing a <code>std::string</code> isn't the best approach to begin with. You'll have a lot more flexibility down the road if you use a simple wrapper object. It may just encapsulate a <code>string</code> for now, but maybe in future you will want to include other information, like some data which caused the exception or maybe a line number (very common, that). You don't want to change all of your exception handling in every spot in your code-base, so take the high road now and don't throw raw objects.</p>\n"
},
{
"answer_id": 134612,
"author": "PierreBdR",
"author_id": 7136,
"author_profile": "https://Stackoverflow.com/users/7136",
"pm_score": 6,
"selected": false,
"text": "<p>A few principles:</p>\n\n<ol>\n<li><p>you have a std::exception base class, you should have your exceptions derive from it. That way general exception handler still have some information.</p></li>\n<li><p>Don't throw pointers but object, that way memory is handled for you.</p></li>\n</ol>\n\n<p>Example:</p>\n\n<pre><code>struct MyException : public std::exception\n{\n std::string s;\n MyException(std::string ss) : s(ss) {}\n ~MyException() throw () {} // Updated\n const char* what() const throw() { return s.c_str(); }\n};\n</code></pre>\n\n<p>And then use it in your code:</p>\n\n<pre><code>void Foo::Bar(){\n if(!QueryPerformanceTimer(&m_baz)){\n throw MyException(\"it's the end of the world!\");\n }\n}\n\nvoid Foo::Caller(){\n try{\n this->Bar();// should throw\n }catch(MyException& caught){\n std::cout<<\"Got \"<<caught.what()<<std::endl;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 134623,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>All these work:</p>\n\n<pre><code>#include <iostream>\nusing namespace std;\n\n//Good, because manual memory management isn't needed and this uses\n//less heap memory (or no heap memory) so this is safer if\n//used in a low memory situation\nvoid f() { throw string(\"foo\"); }\n\n//Valid, but avoid manual memory management if there's no reason to use it\nvoid g() { throw new string(\"foo\"); }\n\n//Best. Just a pointer to a string literal, so no allocation is needed,\n//saving on cleanup, and removing a chance for an allocation to fail.\nvoid h() { throw \"foo\"; }\n\nint main() {\n try { f(); } catch (string s) { cout << s << endl; }\n try { g(); } catch (string* s) { cout << *s << endl; delete s; }\n try { h(); } catch (const char* s) { cout << s << endl; }\n return 0;\n}\n</code></pre>\n\n<p>You should prefer h to f to g. Note that in the least preferable option you need to free the memory explicitly.</p>\n"
},
{
"answer_id": 134640,
"author": "christopher_f",
"author_id": 9224,
"author_profile": "https://Stackoverflow.com/users/9224",
"pm_score": 8,
"selected": true,
"text": "<p>Yes. <a href=\"http://en.cppreference.com/w/cpp/error/exception\" rel=\"noreferrer\"><code>std::exception</code></a> is the base exception class in the C++ standard library. You may want to avoid using strings as exception classes because they themselves can throw an exception during use. If that happens, then where will you be?</p>\n\n<p>boost has an excellent <a href=\"http://www.boost.org/community/error_handling.html\" rel=\"noreferrer\">document</a> on good style for exceptions and error handling. It's worth a read.</p>\n"
},
{
"answer_id": 135184,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 3,
"selected": false,
"text": "<p>In addition to probably throwing something derived from std::exception you should throw anonymous temporaries and catch by reference:</p>\n\n<pre><code>void Foo::Bar(){\n if(!QueryPerformanceTimer(&m_baz)){\n throw std::string(\"it's the end of the world!\");\n }\n}\n\nvoid Foo:Caller(){\n try{\n this->Bar();// should throw\n }catch(std::string& caught){ // not quite sure the syntax is ok here...\n std::cout<<\"Got \"<<caught<<std::endl;\n }\n}\n</code></pre>\n\n<ul>\n<li>You should throw anonymous\ntemporaries so the compiler deals\nwith the object lifetime of whatever\nyou're throwing - if you throw\nsomething new-ed off the heap,\nsomeone else needs to free the\nthing.</li>\n<li>You should catch references to\nprevent object slicing</li>\n</ul>\n\n<p>.</p>\n\n<p>See Meyer's \"Effective C++ - 3rd edition\" for details or visit <a href=\"https://www.securecoding.cert.org/confluence/display/cplusplus/ERR02-A.+Throw+anonymous+temporaries+and+catch+by+reference\" rel=\"noreferrer\">https://www.securecoding.cert.org/.../ERR02-A.+Throw+anonymous+temporaries+and+catch+by+reference</a></p>\n"
},
{
"answer_id": 17600616,
"author": "Eric Leschinski",
"author_id": 445131,
"author_profile": "https://Stackoverflow.com/users/445131",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Simplest way to throw an Exception in C++:</strong></p>\n\n<pre><code>#include <iostream>\nusing namespace std;\nvoid purturb(){\n throw \"Cannot purturb at this time.\";\n}\nint main() {\n try{\n purturb();\n }\n catch(const char* msg){\n cout << \"We caught a message: \" << msg << endl;\n }\n cout << \"done\";\n return 0;\n}\n</code></pre>\n\n<p>This prints:</p>\n\n<pre><code>We caught a message: Cannot purturb at this time.\ndone\n</code></pre>\n\n<p>If you catch the thrown exception, the exception is contained and the program will ontinue. If you do not catch the exception, then the program exists and prints: </p>\n\n<p><code>This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.</code></p>\n"
},
{
"answer_id": 47619071,
"author": "GPMueller",
"author_id": 4069571,
"author_profile": "https://Stackoverflow.com/users/4069571",
"pm_score": 2,
"selected": false,
"text": "<p>Though this question is rather old and has already been answered, I just want to add a note on how to do proper exception handling <strong>in C++11</strong>:</p>\n\n<h2>Use <a href=\"http://en.cppreference.com/w/cpp/error/nested_exception\" rel=\"nofollow noreferrer\"><code>std::nested_exception</code></a> and <a href=\"http://en.cppreference.com/w/cpp/error/throw_with_nested\" rel=\"nofollow noreferrer\"><code>std::throw_with_nested</code></a></h2>\n\n<p>Using these, in my opinion, leads to cleaner exception design and makes it unnecessary to create an exception class hierarchy.</p>\n\n<p>Note that this enables you to <strong>get a backtrace on your exceptions</strong> inside your code without need for a debugger or cumbersome logging. It is described on StackOverflow <a href=\"https://stackoverflow.com/a/37227893/4069571\">here</a> and <a href=\"https://stackoverflow.com/a/348862/4069571\">here</a>, how to write a proper exception handler which will rethrow nested exceptions.</p>\n\n<p>Since you can do this with any derived exception class, you can add a lot of information to such a backtrace!\nYou may also take a look at my <a href=\"https://github.com/GPMueller/mwe-cpp-exception\" rel=\"nofollow noreferrer\">MWE on GitHub</a>, where a backtrace would look something like this:</p>\n\n<pre><code>Library API: Exception caught in function 'api_function'\nBacktrace:\n~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed\n~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file \"nonexistent.txt\"\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22187/"
]
| I would like to throw an exception when my C++ methods encounter something weird and can't recover. Is it OK to throw a `std::string` pointer?
Here's what I was looking forward to doing:
```
void Foo::Bar() {
if(!QueryPerformanceTimer(&m_baz)) {
throw new std::string("it's the end of the world!");
}
}
void Foo::Caller() {
try {
this->Bar(); // should throw
}
catch(std::string *caught) { // not quite sure the syntax is OK here...
std::cout << "Got " << caught << std::endl;
}
}
``` | Yes. [`std::exception`](http://en.cppreference.com/w/cpp/error/exception) is the base exception class in the C++ standard library. You may want to avoid using strings as exception classes because they themselves can throw an exception during use. If that happens, then where will you be?
boost has an excellent [document](http://www.boost.org/community/error_handling.html) on good style for exceptions and error handling. It's worth a read. |
134,572 | <p>I am using the jQuery AutoComplete plugin in an html page where I also have an accordion menu which uses prototype.</p>
<p>They both work perfectly separately but when I tried to implement both components in a single page I get an error that I have not been able to understand.</p>
<blockquote>
<p>uncaught exception: [Exception... "Component returned failure code:
0x80004005 (NS_ERROR_FAILURE) [nsIDOMViewCSS.getComputedStyle]"
nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame ::
file:///C:/Documents and
Settings/Administrator/Desktop/website/js/jquery-1.2.6.pack.js ::
anonymous :: line 11" data: no]</p>
</blockquote>
<p>I found out the file conflicting with jQuery is 'effects.js' which is used by the accordion menu. I tried replacing this file with a newer version but newer seems to break the accordion behavior. </p>
<p>My guess is that the 'effects.js' file used in the accordion was modified to obtain the accordion demo output. I also tried using the overriding methods jQuery needs to avoid conflict with other libraries and that did not work.</p>
<p>I obtained the accordion demo from <a href="http://www.stickmanlabs.com/accordion/" rel="nofollow noreferrer">stickmanlabs.com</a>.</p>
<p>And the jQuery AutoComplete can be obtained from <a href="http://docs.jquery.com/Plugins/Autocomplete#Setup" rel="nofollow noreferrer">jQuery site</a>.</p>
<p>Has any one else experienced this issue?</p>
| [
{
"answer_id": 134635,
"author": "Tahir Akhtar",
"author_id": 18027,
"author_profile": "https://Stackoverflow.com/users/18027",
"pm_score": 3,
"selected": false,
"text": "<p>jQuery lets you rename the jQuery function from <code>$</code> to something else to avoid namespace conflicts with other libraries. </p>\n\n<p>You can do something like this</p>\n\n<pre><code>var J = jQuery.noConflict();\n</code></pre>\n\n<p>Details here: <a href=\"http://michaelshadle.com/2007/07/03/jquerys-no-conflict-mode-yet-another-reason-why-its-the-best/\" rel=\"nofollow noreferrer\">michaelshadle.com — jQuery's no-conflict mode: yet another reason why it's the best</a></p>\n"
},
{
"answer_id": 136502,
"author": "John Resig",
"author_id": 6524,
"author_profile": "https://Stackoverflow.com/users/6524",
"pm_score": 7,
"selected": false,
"text": "<p>There are two possible solutions: There was a conflict with an older version of Scriptaculous and jQuery (Scriptaculous was attempting to extend the native Array prototype incorrectly) - first try upgrading your copy of Scriptaculous.</p>\n\n<p>If that does not work you will need to use <code>noConflict()</code> (as alluded to above). However, there's a catch. Since you're including a plugin you'll need to do the includes in a specific order, for example:</p>\n\n<pre><code><script src=\"jquery.js\"></script>\n<script src=\"jquery.autocomplete.js\"></script>\n<script>\n jQuery.noConflict();\n jQuery(document).ready(function($){\n $(\"#example\").autocomplete(options);\n });\n</script>\n<script src=\"prototype.js\"></script>\n<script src=\"effects.js\"></script>\n<script src=\"accordion.js\"></script>\n</code></pre>\n\n<p>Hope this helps to clarify the situation.</p>\n"
},
{
"answer_id": 142937,
"author": "Fczbkk",
"author_id": 22920,
"author_profile": "https://Stackoverflow.com/users/22920",
"pm_score": 3,
"selected": false,
"text": "<p>I don't really see the reason for using both libraries at the same time in this case.</p>\n\n<p>You can either use Prototype's (well, Scriptaculous' actually) <a href=\"http://github.com/madrobby/scriptaculous/wikis/ajax-autocompleter\" rel=\"noreferrer\">Ajax.Autocompleter</a> and ditch jQuery, or you can use jQuery's <a href=\"http://docs.jquery.com/UI/Accordion\" rel=\"noreferrer\">Accordion</a> and get rid of Prototype.</p>\n\n<p>Using both libraries at once is not really a good idea, because:</p>\n\n<ol>\n<li>They can cause conflicts.</li>\n<li>By including them both you force your users to download them both. Which is not bandwith friendly approach.</li>\n</ol>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I am using the jQuery AutoComplete plugin in an html page where I also have an accordion menu which uses prototype.
They both work perfectly separately but when I tried to implement both components in a single page I get an error that I have not been able to understand.
>
> uncaught exception: [Exception... "Component returned failure code:
> 0x80004005 (NS\_ERROR\_FAILURE) [nsIDOMViewCSS.getComputedStyle]"
> nsresult: "0x80004005 (NS\_ERROR\_FAILURE)" location: "JS frame ::
> file:///C:/Documents and
> Settings/Administrator/Desktop/website/js/jquery-1.2.6.pack.js ::
> anonymous :: line 11" data: no]
>
>
>
I found out the file conflicting with jQuery is 'effects.js' which is used by the accordion menu. I tried replacing this file with a newer version but newer seems to break the accordion behavior.
My guess is that the 'effects.js' file used in the accordion was modified to obtain the accordion demo output. I also tried using the overriding methods jQuery needs to avoid conflict with other libraries and that did not work.
I obtained the accordion demo from [stickmanlabs.com](http://www.stickmanlabs.com/accordion/).
And the jQuery AutoComplete can be obtained from [jQuery site](http://docs.jquery.com/Plugins/Autocomplete#Setup).
Has any one else experienced this issue? | There are two possible solutions: There was a conflict with an older version of Scriptaculous and jQuery (Scriptaculous was attempting to extend the native Array prototype incorrectly) - first try upgrading your copy of Scriptaculous.
If that does not work you will need to use `noConflict()` (as alluded to above). However, there's a catch. Since you're including a plugin you'll need to do the includes in a specific order, for example:
```
<script src="jquery.js"></script>
<script src="jquery.autocomplete.js"></script>
<script>
jQuery.noConflict();
jQuery(document).ready(function($){
$("#example").autocomplete(options);
});
</script>
<script src="prototype.js"></script>
<script src="effects.js"></script>
<script src="accordion.js"></script>
```
Hope this helps to clarify the situation. |
134,581 | <p>This is a follow-up to <a href="https://stackoverflow.com/questions/43778/sqlite3-ruby-gem-failed-to-build-gem-native-extension">this question</a>.</p>
<p>When I issue the <strong><code>gem update</code></strong> command on Windows, whenever it gets to a
gem whose latest version DOESN'T have Windows binaries, it'll attempt to
build the native extension which will, of course, fail. For example:</p>
<pre><code>Updating sqlite3-ruby
Building native extensions. This could take a while...
ERROR: While executing gem ... (Gem::Installer::ExtensionBuildError)
ERROR: Failed to build gem native extension.
c:/ruby/bin/ruby.exe extconf.rb update
checking for fdatasync() in rt.lib... no
checking for sqlite3.h... no
nmake
'nmake' is not recognized as an internal or external command,
operable program or batch file.
</code></pre>
<p>The old pre-1.x behavior of asking for the required platform at least
made updating possible. Now I can't update at all unless I uninstall the
troublesome gems (currently sqlite3-ruby and hpricot), run the update,
then re-install the gems using the --version switch.</p>
<p>Does anyone have a solution to this conundrum or are we stuck with it?</p>
<hr>
<p><strong>Note:</strong></p>
<pre><code>$ gem -v
1.2.0
$ ruby -v
ruby 1.8.6 (2007-09-24 patchlevel 111) [i386-mswin32]
</code></pre>
<hr>
<p><strong>Note (26 September 2008):</strong> I just updated to gems 1.3.0 and this problem persists.</p>
<p><strong>Note (18 November 2008):</strong> Just updated to gems 1.3.1 and the problem persists.</p>
<p><strong>Note (28 April 2009):</strong> The latest version of Gems (<a href="http://blog.segment7.net/articles/2009/04/15/rubygems-1-3-2" rel="nofollow noreferrer">1.3.2</a>) now skips any gems where building of native extensions fails during update; in other words, the problem is fixed. Hooray!</p>
| [
{
"answer_id": 136226,
"author": "hectorsq",
"author_id": 14755,
"author_profile": "https://Stackoverflow.com/users/14755",
"pm_score": 2,
"selected": false,
"text": "<p>It seems that we are stuck. I have found <a href=\"http://rubyforge.org/frs/?group_id=254\" rel=\"nofollow noreferrer\">here</a> that there is no mswin32 gem for the last version (1.2.4), I tried to install it on my computer and got the same problem.</p>\n\n<p>Installing the previous version works fine:</p>\n\n<pre><code>gem install sqlite3-ruby --version '1.2.3'\n</code></pre>\n"
},
{
"answer_id": 144510,
"author": "Charles Roper",
"author_id": 1944,
"author_profile": "https://Stackoverflow.com/users/1944",
"pm_score": 3,
"selected": true,
"text": "<p>Gems, as of <a href=\"http://blog.segment7.net/articles/2009/04/15/rubygems-1-3-2\" rel=\"nofollow noreferrer\">version 1.3.2</a>, will now skip gems that fail to build, so update Rubygems to the latest version and the problem discussed here should be solved.</p>\n\n<pre><code>gem update --system\n</code></pre>\n\n<p><strong><em>The following solution is now deprecated, but I leave it here for the record.</em></strong></p>\n\n<p>I <a href=\"http://www.ruby-forum.com/topic/166693\" rel=\"nofollow noreferrer\">started a thread on this issue</a> on the Ruby Forum (it's a front end to the mailing list). There's some interesting discussion; it's worth a read. There's even a very hacky solution to this problem on there:</p>\n\n<pre><code>`gem.bat outdated`.split(/\\n/).map{|z|z.scan(/^[^[:space:]]+/)}.flatten.each{|z| `gem.bat update #{z}`}\n</code></pre>\n\n<p>It calls the <code>gem outdated</code> command and builds a list of all of the outdated gems. It then iterates over the list and calls <code>gem update</code> for each individual outdated gem. If one fails, it just moves onto the next.</p>\n"
},
{
"answer_id": 155882,
"author": "Alan Hecht",
"author_id": 624,
"author_profile": "https://Stackoverflow.com/users/624",
"pm_score": 1,
"selected": false,
"text": "<p>Looking at the <a href=\"http://rubyforge.org/frs/?group_id=254\" rel=\"nofollow noreferrer\">RubyForge file list</a> for sqlite3-ruby reveals that version 1.2.3 has gems that were built using Visual Studio 6 and MinGW (sqlite3-ruby-1.2.3-mswin32.gem & sqlite3-ruby-1.2.3-x86-mingw32.gem). However, version 1.2.4 doesn't not have any such pre-built gems.</p>\n\n<p>If you have Visual Studio 6 or <a href=\"http://www.mingw.org/\" rel=\"nofollow noreferrer\">MinGW</a> installed and have the compiler environment variables set up (at least for Visual Studio 6 but not sure about MinGW), the gem should build during installation. I'm not sure if the gems will build under newer versions of Visual Studio.</p>\n"
},
{
"answer_id": 3772754,
"author": "AMIC MING",
"author_id": 206401,
"author_profile": "https://Stackoverflow.com/users/206401",
"pm_score": 2,
"selected": false,
"text": "<p>Execute the below command and it should work:</p>\n\n<pre><code>gem install sqlite3-ruby --platform=mswin32\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1944/"
]
| This is a follow-up to [this question](https://stackoverflow.com/questions/43778/sqlite3-ruby-gem-failed-to-build-gem-native-extension).
When I issue the **`gem update`** command on Windows, whenever it gets to a
gem whose latest version DOESN'T have Windows binaries, it'll attempt to
build the native extension which will, of course, fail. For example:
```
Updating sqlite3-ruby
Building native extensions. This could take a while...
ERROR: While executing gem ... (Gem::Installer::ExtensionBuildError)
ERROR: Failed to build gem native extension.
c:/ruby/bin/ruby.exe extconf.rb update
checking for fdatasync() in rt.lib... no
checking for sqlite3.h... no
nmake
'nmake' is not recognized as an internal or external command,
operable program or batch file.
```
The old pre-1.x behavior of asking for the required platform at least
made updating possible. Now I can't update at all unless I uninstall the
troublesome gems (currently sqlite3-ruby and hpricot), run the update,
then re-install the gems using the --version switch.
Does anyone have a solution to this conundrum or are we stuck with it?
---
**Note:**
```
$ gem -v
1.2.0
$ ruby -v
ruby 1.8.6 (2007-09-24 patchlevel 111) [i386-mswin32]
```
---
**Note (26 September 2008):** I just updated to gems 1.3.0 and this problem persists.
**Note (18 November 2008):** Just updated to gems 1.3.1 and the problem persists.
**Note (28 April 2009):** The latest version of Gems ([1.3.2](http://blog.segment7.net/articles/2009/04/15/rubygems-1-3-2)) now skips any gems where building of native extensions fails during update; in other words, the problem is fixed. Hooray! | Gems, as of [version 1.3.2](http://blog.segment7.net/articles/2009/04/15/rubygems-1-3-2), will now skip gems that fail to build, so update Rubygems to the latest version and the problem discussed here should be solved.
```
gem update --system
```
***The following solution is now deprecated, but I leave it here for the record.***
I [started a thread on this issue](http://www.ruby-forum.com/topic/166693) on the Ruby Forum (it's a front end to the mailing list). There's some interesting discussion; it's worth a read. There's even a very hacky solution to this problem on there:
```
`gem.bat outdated`.split(/\n/).map{|z|z.scan(/^[^[:space:]]+/)}.flatten.each{|z| `gem.bat update #{z}`}
```
It calls the `gem outdated` command and builds a list of all of the outdated gems. It then iterates over the list and calls `gem update` for each individual outdated gem. If one fails, it just moves onto the next. |
134,626 | <p>I mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior.</p>
<p>Here are some trivial examples where they functionally do the same thing if either were found within another function:</p>
<p><strong>Lambda function</strong></p>
<pre><code>>>> a = lambda x : 1 + x
>>> a(5)
6
</code></pre>
<p><strong>Nested function</strong></p>
<pre><code>>>> def b(x): return 1 + x
>>> b(5)
6
</code></pre>
<p>Are there advantages to using one over the other? (Performance? Readability? Limitations? Consistency? etc.)</p>
<p>Does it even matter? If it doesn't then does that violate the Pythonic principle:</p>
<blockquote>
<p><a href="https://www.python.org/dev/peps/pep-0020/" rel="noreferrer">There should be one-- and preferably only one --obvious way to do it.</a>.</p>
</blockquote>
| [
{
"answer_id": 134638,
"author": "nosklo",
"author_id": 17160,
"author_profile": "https://Stackoverflow.com/users/17160",
"pm_score": 8,
"selected": true,
"text": "<p>If you need to assign the <code>lambda</code> to a name, use a <code>def</code> instead. <code>def</code>s are just syntactic sugar for an assignment, so the result is the same, and they are a lot more flexible and readable.</p>\n\n<p><code>lambda</code>s can be used for <em>use once, throw away</em> functions which won't have a name.</p>\n\n<p>However, this use case is very rare. You rarely need to pass around unnamed function objects.</p>\n\n<p>The builtins <code>map()</code> and <code>filter()</code> need function objects, but <strong>list comprehensions</strong> and <strong>generator expressions</strong> are generally more readable than those functions and can cover all use cases, without the need of lambdas. </p>\n\n<p>For the cases you really need a small function object, you should use the <code>operator</code> module functions, like <code>operator.add</code> instead of <code>lambda x, y: x + y</code></p>\n\n<p>If you still need some <code>lambda</code> not covered, you might consider writing a <code>def</code>, just to be more readable. If the function is more complex than the ones at <code>operator</code> module, a <code>def</code> is probably better. </p>\n\n<p>So, real world good <code>lambda</code> use cases are very rare.</p>\n"
},
{
"answer_id": 134664,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 3,
"selected": false,
"text": "<p>I agree with nosklo's advice: if you need to give the function a name, use <code>def</code>. I reserve <code>lambda</code> functions for cases where I'm just passing a brief snippet of code to another function, e.g.:</p>\n\n<pre><code>a = [ (1,2), (3,4), (5,6) ]\nb = map( lambda x: x[0]+x[1], a )\n</code></pre>\n"
},
{
"answer_id": 134709,
"author": "Chris Lawlor",
"author_id": 21245,
"author_profile": "https://Stackoverflow.com/users/21245",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"http://www.linuxjournal.com/article/2959\" rel=\"noreferrer\">In this interview, </a> Guido van Rossum says he wishes he hadn't let 'lambda' into Python:</p>\n\n<blockquote>\n <p>\"<strong>Q. What feature of Python are you least pleased with?</strong><br /><br />\n Sometimes I've been too quick in accepting contributions, and later realized that it was a mistake. One example would be some of the functional programming features, such as lambda functions. lambda is a keyword that lets you create a small anonymous function; built-in functions such as map, filter, and reduce run a function over a sequence type, such as a list.<br /><br />\n In practice, it didn't turn out that well. Python only has two scopes: local and global. This makes writing lambda functions painful, because you often want to access variables in the scope where the lambda was defined, but you can't because of the two scopes. There's a way around this, but it's something of a kludge. Often it seems much easier in Python to just use a for loop instead of messing around with lambda functions. map and friends work well only when there's already a built-in function that does what you want.</p>\n</blockquote>\n\n<p>IMHO, Iambdas can be convenient sometimes, but usually are convenient at the expense of readibility. Can you tell me what this does:</p>\n\n<pre><code>str(reduce(lambda x,y:x+y,map(lambda x:x**x,range(1,1001))))[-10:]\n</code></pre>\n\n<p>I wrote it, and it took me a minute to figure it out. This is from Project Euler - i won't say which problem because i hate spoilers, but it runs in 0.124 seconds :)</p>\n"
},
{
"answer_id": 135353,
"author": "apg",
"author_id": 22277,
"author_profile": "https://Stackoverflow.com/users/22277",
"pm_score": 2,
"selected": false,
"text": "<p>The primary use of lambda has always been for simple callback functions, and for map, reduce, filter, which require a function as an argument. With list comprehensions becoming the norm, and the added allowed if as in:</p>\n\n<pre><code>x = [f for f in range(1, 40) if f % 2]\n</code></pre>\n\n<p>it's hard to imagine a real case for the use of lambda in daily use. As a result, I'd say, avoid lambda and create nested functions.</p>\n"
},
{
"answer_id": 135815,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 0,
"selected": false,
"text": "<p>I agree with nosklo. By the way, even with a <em>use once, throw away</em> function, most of the time you just want to use something from the operator module.</p>\n\n<p>E.G : </p>\n\n<p>You have a function with this signature : myFunction(data, callback function).</p>\n\n<p>You want to pass a function that add 2 elements.</p>\n\n<p>Using lambda :</p>\n\n<pre><code>myFunction(data, (lambda x, y : x + y))\n</code></pre>\n\n<p>The pythonic way :</p>\n\n<pre><code>import operator\nmyFunction(data, operator.add)\n</code></pre>\n\n<p>Or course this is a simple example, but there is a lot of stuff the operator module provides, including the items setters / getters for list and dict. Really cool.</p>\n"
},
{
"answer_id": 138625,
"author": "Thomas Vander Stichele",
"author_id": 2900,
"author_profile": "https://Stackoverflow.com/users/2900",
"pm_score": 5,
"selected": false,
"text": "<p>Practically speaking, to me there are two differences:</p>\n\n<p>The first is about what they do and what they return:</p>\n\n<ul>\n<li><p>def is a keyword that doesn't return anything and creates a 'name' in the local namespace.</p></li>\n<li><p>lambda is a keyword that returns a function object and does not create a 'name' in the local namespace.</p></li>\n</ul>\n\n<p>Hence, if you need to call a function that takes a function object, the only way to do that in one line of python code is with a lambda. There's no equivalent with def.</p>\n\n<p>In some frameworks this is actually quite common; for example, I use <a href=\"http://twistedmatrix.com/\" rel=\"noreferrer\">Twisted</a> a lot, and so doing something like</p>\n\n<pre><code>d.addCallback(lambda result: setattr(self, _someVariable, result))\n</code></pre>\n\n<p>is quite common, and more concise with lambdas.</p>\n\n<p>The second difference is about what the actual function is allowed to do.</p>\n\n<ul>\n<li>A function defined with 'def' can contain any python code</li>\n<li>A function defined with 'lambda' has to evaluate to an expression, and can thus not contain statements like print, import, raise, ... </li>\n</ul>\n\n<p>For example,</p>\n\n<pre><code>def p(x): print x\n</code></pre>\n\n<p>works as expected, while</p>\n\n<pre><code>lambda x: print x\n</code></pre>\n\n<p>is a SyntaxError.</p>\n\n<p>Of course, there are workarounds - substitute <code>print</code> with <code>sys.stdout.write</code>, or <code>import</code> with <code>__import__</code>. But usually you're better off going with a function in that case.</p>\n"
},
{
"answer_id": 298045,
"author": "too much php",
"author_id": 28835,
"author_profile": "https://Stackoverflow.com/users/28835",
"pm_score": 1,
"selected": false,
"text": "<p>If you are just going to assign the lambda to a variable in the local scope, you may as well use def because it is more readable and can be expanded more easily in the future:</p>\n\n<pre><code>fun = lambda a, b: a ** b # a pointless use of lambda\nmap(fun, someList)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>def fun(a, b): return a ** b # more readable\nmap(fun, someList)\n</code></pre>\n"
},
{
"answer_id": 788533,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>lambda is useful for generating new functions:</p>\n\n<pre><code>>>> def somefunc(x): return lambda y: x+y\n>>> f = somefunc(10)\n>>> f(2)\n12\n>>> f(4)\n14\n</code></pre>\n"
},
{
"answer_id": 1004492,
"author": "SingleNegationElimination",
"author_id": 65696,
"author_profile": "https://Stackoverflow.com/users/65696",
"pm_score": 2,
"selected": false,
"text": "<p>An important limitation of lambdas is that they cannot contain anything besides an expression. It's nearly impossible for a lambda expression to produce anything besides trivial side effects, since it cannot have anywhere near as rich a body as a <code>def</code>'ed function.</p>\n\n<p>That being said, Lua influenced my programming style toward the extensive use of anonymous functions, and I litter my code with them. On top of that, I tend to think about map/reduce as abstract operators in ways I don't consider list comprehensions or generators, almost as If I'm deferring an implementation decision explicitly by using those operators. </p>\n\n<p><strong>Edit:</strong> This is a pretty old question, and my opinions on the matter have changed, somewhat.</p>\n\n<p>First off, I am strongly biased against assigning a <code>lambda</code> expression to a variable; as python has a special syntax just for that (hint, <code>def</code>). In addition to that, many of the uses for lambda, even when they don't get a name, have predefined (and more efficient) implementations. For instance, the example in question can be abbreviated to just <code>(1).__add__</code>, without the need to wrap it in a <code>lambda</code> or <code>def</code>. Many other common uses can be satisfied with some combination of the <code>operator</code>, <code>itertools</code> and <code>functools</code> modules.</p>\n"
},
{
"answer_id": 11988012,
"author": "Andy Hayden",
"author_id": 1240268,
"author_profile": "https://Stackoverflow.com/users/1240268",
"pm_score": 4,
"selected": false,
"text": "<p>For n=1000 here's some timeit's of calling a function vs a lambda:</p>\n\n<pre><code>In [11]: def f(a, b):\n return a * b\n\nIn [12]: g = lambda x, y: x * y\n\nIn [13]: %%timeit -n 100\nfor a in xrange(n):\n for b in xrange(n):\n f(a, b)\n ....:\n100 loops, best of 3: 285 ms per loop\n\nIn [14]: %%timeit -n 100\nfor a in xrange(n):\n for b in xrange(n):\n g(a, b)\n ....:\n100 loops, best of 3: 298 ms per loop\n\nIn [15]: %%timeit -n 100\nfor a in xrange(n):\n for b in xrange(n):\n (lambda x, y: x * y)(a, b)\n ....:\n100 loops, best of 3: 462 ms per loop\n</code></pre>\n"
},
{
"answer_id": 20799400,
"author": "Jonathan Livni",
"author_id": 348545,
"author_profile": "https://Stackoverflow.com/users/348545",
"pm_score": 3,
"selected": false,
"text": "<p>While agreeing with the other answers, sometimes it's more readable. Here's an example where <code>lambda</code> comes in handy, in a use case I keep encountering of an N dimensional <a href=\"http://docs.python.org/2/library/collections.html#collections.defaultdict\" rel=\"noreferrer\"><code>defaultdict</code></a>.<br>Here's an example:</p>\n\n<pre><code>from collections import defaultdict\nd = defaultdict(lambda: defaultdict(list))\nd['Foo']['Bar'].append(something)\n</code></pre>\n\n<p>I find it more readable than creating a <code>def</code> for the second dimension. This is even more significant for higher dimensions.</p>\n"
},
{
"answer_id": 33269715,
"author": "Glushiator",
"author_id": 1284183,
"author_profile": "https://Stackoverflow.com/users/1284183",
"pm_score": 1,
"selected": false,
"text": "<p>One use for lambdas I have found... is in debug messages.</p>\n\n<p>Since lambdas can be lazily evaluated you can have code like this:</p>\n\n<pre><code>log.debug(lambda: \"this is my message: %r\" % (some_data,))\n</code></pre>\n\n<p>instead of possibly expensive:</p>\n\n<pre><code>log.debug(\"this is my message: %r\" % (some_data,))\n</code></pre>\n\n<p>which processes the format string even if the debug call does not produce output because of current logging level.</p>\n\n<p>Of course for it to work as described the logging module in use must support lambdas as \"lazy parameters\" (as my logging module does).</p>\n\n<p>The same idea may be applied to any other case of lazy evaluation for on demand content value creation.</p>\n\n<p>For example this custom ternary operator:</p>\n\n<pre><code>def mif(condition, when_true, when_false):\n if condition:\n return when_true()\n else:\n return when_false()\n\nmif(a < b, lambda: a + a, lambda: b + b)\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>def mif(condition, when_true, when_false):\n if condition:\n return when_true\n else:\n return when_false\n\nmif(a < b, a + a, b + b)\n</code></pre>\n\n<p>with lambdas only the expression selected by the condition will be evaluated, without lambdas both will be evaluated.</p>\n\n<p>Of course you could simply use functions instead of lambdas, but for short expressions lambdas are (c)leaner.</p>\n"
},
{
"answer_id": 35346979,
"author": "Pi Marillion",
"author_id": 2892254,
"author_profile": "https://Stackoverflow.com/users/2892254",
"pm_score": 3,
"selected": false,
"text": "<p><em>Performance:</em></p>\n\n<p>Creating a function with <code>lambda</code> is <em>slightly faster</em> than creating it with <code>def</code>. The difference is due to <code>def</code> creating a name entry in the locals table. The resulting function has the same execution speed.</p>\n\n<hr>\n\n<p>Readability:</p>\n\n<p>Lambda functions are somewhat less readable for most Python users, but also much more concise in some circumstances. Consider converting from using non-functional to functional routine:</p>\n\n<pre><code># Using non-functional version.\n\nheading(math.sqrt(v.x * v.x + v.y * v.y), math.atan(v.y / v.x))\n\n# Using lambda with functional version.\n\nfheading(v, lambda v: math.sqrt(v.x * v.x + v.y * v.y), lambda v: math.atan(v.y / v.x))\n\n# Using def with functional version.\n\ndef size(v):\n return math.sqrt(v.x * v.x + v.y * v.y)\n\ndef direction(v):\n return math.atan(v.y / v.x)\n\ndeal_with_headings(v, size, direction)\n</code></pre>\n\n<p>As you can see, the <code>lambda</code> version is shorter and \"easier\" in the sense that you only need to add <code>lambda v:</code> to the original non-functional version to convert to the functional version. It's also a lot more concise. But remember, a lot of Python users will be confused by the lambda syntax, so what you lose in length and real complexity might be gained back in confusion from fellow coders.</p>\n\n<hr>\n\n<p>Limitations:</p>\n\n<ul>\n<li><code>lambda</code> functions can only be used once, unless assigned to a variable name.</li>\n<li><code>lambda</code> functions assigned to variable names have no advantage over <code>def</code> functions.</li>\n<li><code>lambda</code> functions can be difficult or impossible to pickle.</li>\n<li><code>def</code> functions' names must be carefully chosen to be reasonably descriptive and unique or at least otherwise unused in scope.</li>\n</ul>\n\n<hr>\n\n<p>Consistency:</p>\n\n<p>Python mostly avoids functional programming conventions in favor of procedural and simpler objective semantics. The <code>lambda</code> operator stands in direct contrast to this bias. Moreover, as an alternative to the already prevalent <code>def</code>, the <code>lambda</code> function adds diversity to your syntax. Some would consider that less consistent.</p>\n\n<hr>\n\n<p>Pre-existing functions:</p>\n\n<p>As noted by others, many uses of <code>lambda</code> in the field can be replaced by members of the <code>operator</code> or other modules. For instance:</p>\n\n<pre><code>do_something(x, y, lambda x, y: x + y)\ndo_something(x, y, operator.add)\n</code></pre>\n\n<p>Using the pre-existing function can make code more readable in many cases.</p>\n\n<hr>\n\n<p>The Pythonic principle: “There should be one—and preferably only one—obvious way to do it”</p>\n\n<p>That's similar to the <a href=\"https://en.wikipedia.org/wiki/Single_source_of_truth\" rel=\"noreferrer\">single source of truth</a> doctrine. Unfortunately, the single-obvious-way-to-do-it principle has always been more an wistful aspiration for Python, rather than a true guiding principal. Consider the very-powerful array comprehensions in Python. They are functionally equivalent to the <code>map</code> and <code>filter</code> functions:</p>\n\n<pre><code>[e for e in some_array if some_condition(e)]\nfilter(some_array, some_condition)\n</code></pre>\n\n<p><code>lambda</code> and <code>def</code> are the same.</p>\n\n<p>It's a matter of opinion, but I would say that anything in the Python language intended for general use which doesn't obviously break anything is \"Pythonic\" enough.</p>\n"
},
{
"answer_id": 46809756,
"author": "Ali Rasim Kocal",
"author_id": 2230666,
"author_profile": "https://Stackoverflow.com/users/2230666",
"pm_score": 0,
"selected": false,
"text": "<p>A major difference is that you can not use <code>def</code> functions inline, which is in my opinion the most convenient use case for a <code>lambda</code> function. For example when sorting a list of objects:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>my_list.sort(key=lambda o: o.x)\n</code></pre>\n\n<p>I would therefore suggest keeping the use of lambdas to this kind of trivial operations, which also do not really benefit from the automatic documentation provided by naming the function. </p>\n"
},
{
"answer_id": 49520604,
"author": "Russia Must Remove Putin",
"author_id": 541136,
"author_profile": "https://Stackoverflow.com/users/541136",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n <h2>More preferable: lambda functions or nested functions (<code>def</code>)?</h2>\n</blockquote>\n\n<p>There is one advantage to using a lambda over a regular function: they are created in an expression.</p>\n\n<p>There are several drawbacks:</p>\n\n<ul>\n<li>no name (just <code>'<lambda>'</code>)</li>\n<li>no docstrings</li>\n<li>no annotations</li>\n<li>no complex statements</li>\n</ul>\n\n<p>They are also both the same type of object. For those reasons, I generally prefer to create functions with the <code>def</code> keyword instead of with lambdas.</p>\n\n<h2>First point - they're the same type of object</h2>\n\n<p>A lambda results in the same type of object as a regular function</p>\n\n<pre><code>>>> l = lambda: 0\n>>> type(l)\n<class 'function'>\n>>> def foo(): return 0\n... \n>>> type(foo)\n<class 'function'>\n>>> type(foo) is type(l)\nTrue\n</code></pre>\n\n<p>Since lambdas are functions, they're first-class objects.</p>\n\n<p>Both lambdas and functions:</p>\n\n<ul>\n<li>can be passed around as an argument (same as a regular function)</li>\n<li>when created within an outer function become a closure over that outer functions' locals</li>\n</ul>\n\n<p>But lambdas are, by default, missing some things that functions get via full function definition syntax.</p>\n\n<h3>A lamba's <code>__name__</code> is <code>'<lambda>'</code></h3>\n\n<p>Lambdas are anonymous functions, after all, so they don't know their own name.</p>\n\n<pre><code>>>> l.__name__\n'<lambda>'\n>>> foo.__name__\n'foo'\n</code></pre>\n\n<p>Thus lambda's can't be looked up programmatically in their namespace.</p>\n\n<p>This limits certain things. For example, <code>foo</code> can be looked up with serialized code, while <code>l</code> cannot:</p>\n\n<pre><code>>>> import pickle\n>>> pickle.loads(pickle.dumps(l))\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n_pickle.PicklingError: Can't pickle <function <lambda> at 0x7fbbc0464e18>: \nattribute lookup <lambda> on __main__ failed\n</code></pre>\n\n<p>We can lookup <code>foo</code> just fine - because it knows its own name:</p>\n\n<pre><code>>>> pickle.loads(pickle.dumps(foo))\n<function foo at 0x7fbbbee79268>\n</code></pre>\n\n<h3>Lambdas have no annotations and no docstring</h3>\n\n<p>Basically, lambdas are not documented. Let's rewrite <code>foo</code> to be better documented:</p>\n\n<pre><code>def foo() -> int:\n \"\"\"a nullary function, returns 0 every time\"\"\"\n return 0\n</code></pre>\n\n<p>Now, foo has documentation:</p>\n\n<pre><code>>>> foo.__annotations__\n{'return': <class 'int'>}\n>>> help(foo)\nHelp on function foo in module __main__:\n\nfoo() -> int\n a nullary function, returns 0 every time\n</code></pre>\n\n<p>Whereas, we don't have the same mechanism to give the same information to lambdas:</p>\n\n<pre><code>>>> help(l)\nHelp on function <lambda> in module __main__:\n\n<lambda> lambda (...)\n</code></pre>\n\n<p>But we can hack them on:</p>\n\n<pre><code>>>> l.__doc__ = 'nullary -> 0'\n>>> l.__annotations__ = {'return': int}\n>>> help(l)\nHelp on function <lambda> in module __main__:\n\n<lambda> lambda ) -> in\n nullary -> 0\n</code></pre>\n\n<p>But there's probably some error messing up the output of help, though.</p>\n\n<h3>Lambdas can only return an expression</h3>\n\n<p>Lambdas can't return complex statements, only expressions.</p>\n\n<pre><code>>>> lambda: if True: 0\n File \"<stdin>\", line 1\n lambda: if True: 0\n ^\nSyntaxError: invalid syntax\n</code></pre>\n\n<p>Expressions can admittedly be rather complex, and if you try <em>very</em> hard you can probably accomplish the same with a lambda, but the added complexity is more of a detriment to writing clear code. </p>\n\n<p>We use Python for clarity and maintainability. Overuse of lambdas can work against that.</p>\n\n<h3>The <em>only</em> upside for lambdas: can be created in a single expression</h3>\n\n<p>This is the only possible upside. Since you can create a lambda with an expression, you can create it inside of a function call. </p>\n\n<p>Creating a function inside a function call avoids the (inexpensive) name lookup versus one created elsewhere. </p>\n\n<p>However, since Python is strictly evaluated, there is no other performance gain to doing so aside from avoiding the name lookup.</p>\n\n<p>For a very simple expression, I might choose a lambda.</p>\n\n<p>I also tend to use lambdas when doing interactive Python, to avoid multiple lines when one will do. I use the following sort of code format when I want to pass in an argument to a constructor when calling <code>timeit.repeat</code>:</p>\n\n<pre><code>import timeit\n\ndef return_nullary_lambda(return_value=0):\n return lambda: return_value\n\ndef return_nullary_function(return_value=0):\n def nullary_fn():\n return return_value\n return nullary_fn\n</code></pre>\n\n<p>And now:</p>\n\n<pre><code>>>> min(timeit.repeat(lambda: return_nullary_lambda(1)))\n0.24312214995734394\n>>> min(timeit.repeat(lambda: return_nullary_function(1)))\n0.24894469301216304\n</code></pre>\n\n<p>I believe the slight time difference above can be attributed to the name lookup in <code>return_nullary_function</code> - note that it is <em>very</em> negligible.</p>\n\n<h2>Conclusion</h2>\n\n<p>Lambdas are good for informal situations where you want to minimize lines of code in favor of making a singular point.</p>\n\n<p>Lambdas are bad for more formal situations where you need clarity for editors of code who will come later, especially in cases where they are non-trivial.</p>\n\n<p>We know we are supposed to give our objects good names. How can we do so when the object has <em>no</em> name?</p>\n\n<p>For all of these reasons, I generally prefer to create functions with <code>def</code> instead of with <code>lambda</code>.</p>\n"
},
{
"answer_id": 51536929,
"author": "bhargav patel",
"author_id": 4977235,
"author_profile": "https://Stackoverflow.com/users/4977235",
"pm_score": 2,
"selected": false,
"text": "<ul>\n<li>Computation time.</li>\n<li>Function without name.</li>\n<li>To achieve One function and many use functionality.</li>\n</ul>\n\n<p>Considering a simple example,</p>\n\n<pre><code># CREATE ONE FUNCTION AND USE IT TO PERFORM MANY OPERATIONS ON SAME TYPE OF DATA STRUCTURE.\ndef variousUse(a,b=lambda x:x[0]):\n return [b(i) for i in a]\n\ndummyList = [(0,1,2,3),(4,5,6,7),(78,45,23,43)]\nvariousUse(dummyList) # extract first element\nvariousUse(dummyList,lambda x:[x[0],x[2],x[3]]) # extract specific indexed element\nvariousUse(dummyList,lambda x:x[0]+x[2]) # add specific elements\nvariousUse(dummyList,lambda x:x[0]*x[2]) # multiply specific elements\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
]
| I mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior.
Here are some trivial examples where they functionally do the same thing if either were found within another function:
**Lambda function**
```
>>> a = lambda x : 1 + x
>>> a(5)
6
```
**Nested function**
```
>>> def b(x): return 1 + x
>>> b(5)
6
```
Are there advantages to using one over the other? (Performance? Readability? Limitations? Consistency? etc.)
Does it even matter? If it doesn't then does that violate the Pythonic principle:
>
> [There should be one-- and preferably only one --obvious way to do it.](https://www.python.org/dev/peps/pep-0020/).
>
>
> | If you need to assign the `lambda` to a name, use a `def` instead. `def`s are just syntactic sugar for an assignment, so the result is the same, and they are a lot more flexible and readable.
`lambda`s can be used for *use once, throw away* functions which won't have a name.
However, this use case is very rare. You rarely need to pass around unnamed function objects.
The builtins `map()` and `filter()` need function objects, but **list comprehensions** and **generator expressions** are generally more readable than those functions and can cover all use cases, without the need of lambdas.
For the cases you really need a small function object, you should use the `operator` module functions, like `operator.add` instead of `lambda x, y: x + y`
If you still need some `lambda` not covered, you might consider writing a `def`, just to be more readable. If the function is more complex than the ones at `operator` module, a `def` is probably better.
So, real world good `lambda` use cases are very rare. |
134,629 | <p>In my <code>urls.py</code> file, I have:</p>
<pre><code>from myapp import views
...
(r'^categories/$', views.categories)
</code></pre>
<p>Where <code>categories</code> is a view function inside <code>myapp/views.py</code>. No other URLconf lines reference <code>views.categories</code>.</p>
<p>In a unit test file, I’m trying to grab this URL using <code>django.core.urlresolvers.reverse()</code>, instead of just copying '/categories/' (DRY and all that). So, I have:</p>
<pre><code>from django.core.urlresolvers import reverse
from myapp import views
...
url = reverse(views.categories)
</code></pre>
<p>When I run my tests, I get a <code>NoReverseMatch</code> error:</p>
<pre><code>NoReverseMatch: Reverse for '<function categories at 0x1082f30>' with arguments '()' and keyword arguments '{}' not found.
</code></pre>
<p>It matches just fine if I make the URL pattern a named pattern, like this:</p>
<pre><code>url(r'^categories/$', views.categories, 'myapp-categories')
</code></pre>
<p>And use the pattern name to match it:</p>
<pre><code>url = reverse('myapp-categories')
</code></pre>
<p>But as far as I can tell from <a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#reverse" rel="noreferrer">the <code>reverse</code> documentation</a>, I shouldn’t need to make it a named URL pattern just to use <code>reverse</code>.</p>
<p>Any ideas what I’m doing wrong?</p>
| [
{
"answer_id": 134651,
"author": "Jack M.",
"author_id": 3421,
"author_profile": "https://Stackoverflow.com/users/3421",
"pm_score": -1,
"selected": false,
"text": "<p>The reverse function actually uses the \"name\" of the URL. This is defined like so:</p>\n\n<pre><code>urlpatterns = patterns('',\n (r'^no_monkeys/$', 'views.noMonkeys', {}, \"no-monkeys\"),\n (r'^admin/(.*)', admin.site.root),\n)\n</code></pre>\n\n<p>Now you would call reverse with the string \"no-monkeys\" to get the correct url.</p>\n\n<p>Ninja Edit: <a href=\"http://docs.djangoproject.com/en/dev/topics/http/urls/#id2\" rel=\"nofollow noreferrer\">Here is a link</a> to the django docs on the subject.</p>\n"
},
{
"answer_id": 135899,
"author": "Carl Meyer",
"author_id": 3207,
"author_profile": "https://Stackoverflow.com/users/3207",
"pm_score": 0,
"selected": false,
"text": "<p>This does work, and all the code that you've pasted is correct and works fine (I just copied it into a clean test/project app and it reversed the URL without any problem). So there's something else going on here that you haven't showed us. Simplify down to the bare-bones basics until it works, then start adding complexity back in and see where it's breaking.</p>\n\n<p>Also, you can do \"./manage.py shell\" and then interactively import the reverse function and your view function and try the reverse. That'll remove the test setup as a possible cause.</p>\n"
},
{
"answer_id": 136721,
"author": "camflan",
"author_id": 22445,
"author_profile": "https://Stackoverflow.com/users/22445",
"pm_score": 2,
"selected": false,
"text": "<p>Jack M.'s example is nearly correct.</p>\n\n<p>It needs to be a url function, not a tuple, if you want to use named urls.</p>\n\n<pre><code>url(r'^no_monkeys/$', 'views.noMonkeys', {}, \"no-monkeys\"),\n</code></pre>\n"
},
{
"answer_id": 146596,
"author": "Paul D. Waite",
"author_id": 20578,
"author_profile": "https://Stackoverflow.com/users/20578",
"pm_score": 3,
"selected": true,
"text": "<p>After futher investigation, turns out it was an issue with how I was importing the views module:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/146522/how-do-i-successfully-pass-a-function-reference-to-djangos-reverse-function\">How do I successfully pass a function reference to Django’s reverse() function?</a></p>\n\n<p>Thanks for the help though, guys: you inspired me to look at it properly.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20578/"
]
| In my `urls.py` file, I have:
```
from myapp import views
...
(r'^categories/$', views.categories)
```
Where `categories` is a view function inside `myapp/views.py`. No other URLconf lines reference `views.categories`.
In a unit test file, I’m trying to grab this URL using `django.core.urlresolvers.reverse()`, instead of just copying '/categories/' (DRY and all that). So, I have:
```
from django.core.urlresolvers import reverse
from myapp import views
...
url = reverse(views.categories)
```
When I run my tests, I get a `NoReverseMatch` error:
```
NoReverseMatch: Reverse for '<function categories at 0x1082f30>' with arguments '()' and keyword arguments '{}' not found.
```
It matches just fine if I make the URL pattern a named pattern, like this:
```
url(r'^categories/$', views.categories, 'myapp-categories')
```
And use the pattern name to match it:
```
url = reverse('myapp-categories')
```
But as far as I can tell from [the `reverse` documentation](http://docs.djangoproject.com/en/dev/topics/http/urls/#reverse), I shouldn’t need to make it a named URL pattern just to use `reverse`.
Any ideas what I’m doing wrong? | After futher investigation, turns out it was an issue with how I was importing the views module:
[How do I successfully pass a function reference to Django’s reverse() function?](https://stackoverflow.com/questions/146522/how-do-i-successfully-pass-a-function-reference-to-djangos-reverse-function)
Thanks for the help though, guys: you inspired me to look at it properly. |
134,644 | <p>Suppose you have a collection of <code>Foo</code> classes:</p>
<pre><code>class Foo
{
public string Bar;
public string Baz;
}
List<Foo> foolist;
</code></pre>
<p>And you want to check this collection to see if another entry has a matching <code>Bar</code>.</p>
<pre><code>bool isDuplicate = false;
foreach (Foo f in foolist)
{
if (f.Bar == SomeBar)
{
isDuplicate = true;
break;
}
}
</code></pre>
<p><code>Contains()</code> doesn't work because it compares the classes as whole.</p>
<p>Does anyone have a better way to do this that works for .NET 2.0?</p>
| [
{
"answer_id": 134662,
"author": "Karg",
"author_id": 12685,
"author_profile": "https://Stackoverflow.com/users/12685",
"pm_score": 0,
"selected": false,
"text": "<p>fooList.Exists(item => item.Bar == SomeBar)</p>\n\n<p>or with anonymous delegate</p>\n\n<p>fooList.Exists(delegate(Foo item) {return item.Bar == SomeBar;})</p>\n"
},
{
"answer_id": 134669,
"author": "ripper234",
"author_id": 11236,
"author_profile": "https://Stackoverflow.com/users/11236",
"pm_score": -1,
"selected": false,
"text": "<p>You probably want to use C5.HashSet, and implement Equals and GetHashCode() for Foo.</p>\n"
},
{
"answer_id": 134675,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 2,
"selected": false,
"text": "<p>Implement the <a href=\"http://msdn.microsoft.com/en-us/library/ms132151.aspx\" rel=\"nofollow noreferrer\">IEqualityComparer<T></a> interface, and use the matching <a href=\"http://msdn.microsoft.com/en-us/library/bb339118.aspx\" rel=\"nofollow noreferrer\">Contains</a> method.</p>\n\n<pre><code>public class MyFooComparer: IEqualityComparer<Foo> {\n\n public bool Equals(Foo foo1, Foo foo2) {\n return Equals(foo1.Bar, foo2.Bar);\n }\n\n public int GetHashCode(Foo foo) {\n return foo.Bar.GetHashCode();\n }\n}\n\nFoo exampleFoo = new Foo();\nexampleFoo.Bar = \"someBar\";\nif(myList.Contains(exampleFoo, new MyFooComparer())) {\n ...\n}\n</code></pre>\n"
},
{
"answer_id": 134676,
"author": "readonly",
"author_id": 4883,
"author_profile": "https://Stackoverflow.com/users/4883",
"pm_score": 0,
"selected": false,
"text": "<p>If you need the element, you can also use List.Find() and pass in a delegate that returns true for your definition of a \"match\" (<a href=\"http://msdn.microsoft.com/en-us/library/x0b5b5bc.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/x0b5b5bc.aspx</a>). </p>\n\n<p>There's an example of how to define a delegate on that MSDN doc.</p>\n"
},
{
"answer_id": 134679,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>If the 'Bar's for your class are unique (a key to class Foo), then you can try implementing a System.Collections.ObjectModel.KeyedCollection. It's pretty simple: just implement the GetKeyForItem() method.</p>\n\n<pre><code>class Foo\n{\n public string Bar;\n public string Baz;\n}\n\nclass FooList : KeyedCollection<string, Foo>\n{\n protected override string GetKeyForItem(Foo item)\n {\n return item.Bar;\n }\n}\n\nFooList fooList;\n</code></pre>\n"
},
{
"answer_id": 134700,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 4,
"selected": true,
"text": "<pre><code>fooList.Exists(item => item.Bar == SomeBar)\n</code></pre>\n\n<p>That's not LINQ, but a Lambda expression, but nevertheless, it uses a v3.5 feature. No problem:</p>\n\n<pre><code>fooList.Exists(delegate(Foo Item) { return item.Bar == SomeBar});\n</code></pre>\n\n<p>That should work in 2.0.</p>\n"
},
{
"answer_id": 134734,
"author": "Austin Salonen",
"author_id": 4068,
"author_profile": "https://Stackoverflow.com/users/4068",
"pm_score": 0,
"selected": false,
"text": "<p>If you override Equals on Foo to make key on Bar, Contains() will work.</p>\n"
},
{
"answer_id": 135131,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If you can use LINQ you can do the following:</p>\n\n<pre><code>bool contains = foolist.Where(f => f.Bar == someBar).Count() != 0;\n</code></pre>\n"
},
{
"answer_id": 74630064,
"author": "Majid Shahabfar",
"author_id": 2053617,
"author_profile": "https://Stackoverflow.com/users/2053617",
"pm_score": 0,
"selected": false,
"text": "<p>Here are 4 ways to check if the collection has no duplicates:</p>\n<pre><code>public static bool LinqAll<T>(IEnumerable<T> enumerable)\n{\n HashSet<T> set = new();\n\n return !enumerable.All(set.Add);\n}\n\npublic static bool LinqAny<T>(IEnumerable<T> enumerable)\n{\n HashSet<T> set = new();\n\n return enumerable.Any(element => !set.Add(element));\n}\n\npublic static bool LinqDistinct<T>(IEnumerable<T> enumerable)\n{\n return enumerable.Distinct().Count() != enumerable.Count();\n}\n\npublic static bool ToHashSet<T>(IEnumerable<T> enumerable)\n{\n return enumerable.ToHashSet().Count != enumerable.Count();\n}\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
]
| Suppose you have a collection of `Foo` classes:
```
class Foo
{
public string Bar;
public string Baz;
}
List<Foo> foolist;
```
And you want to check this collection to see if another entry has a matching `Bar`.
```
bool isDuplicate = false;
foreach (Foo f in foolist)
{
if (f.Bar == SomeBar)
{
isDuplicate = true;
break;
}
}
```
`Contains()` doesn't work because it compares the classes as whole.
Does anyone have a better way to do this that works for .NET 2.0? | ```
fooList.Exists(item => item.Bar == SomeBar)
```
That's not LINQ, but a Lambda expression, but nevertheless, it uses a v3.5 feature. No problem:
```
fooList.Exists(delegate(Foo Item) { return item.Bar == SomeBar});
```
That should work in 2.0. |
134,653 | <p><b>Summary:</b> C#/.NET is supposed to be garbage collected. C# has a destructor, used to clean resources. What happen when an object A is garbage collected the same line I try to clone one of its variable members? Apparently, on multiprocessors, sometimes, the garbage collector wins...</p>
<p><b>The problem</b></p>
<p>Today, on a training session on C#, the teacher showed us some code which contained a bug only when run on multiprocessors.</p>
<p>I'll summarize to say that sometimes, the compiler or the JIT screws up by calling the finalizer of a C# class object before returning from its called method.</p>
<p>The full code, given in Visual C++ 2005 documentation, will be posted as an "answer" to avoid making a very very large questions, but the essential are below:</p>
<p>The following class has a "Hash" property which will return a cloned copy of an internal array. At is construction, the first item of the array has a value of 2. In the destructor, its value is set to zero.</p>
<p>The point is: If you try to get the "Hash" property of "Example", you'll get a clean copy of the array, whose first item is still 2, as the object is being used (and as such, not being garbage collected/finalized):</p>
<pre><code>public class Example
{
private int nValue;
public int N { get { return nValue; } }
// The Hash property is slower because it clones an array. When
// KeepAlive is not used, the finalizer sometimes runs before
// the Hash property value is read.
private byte[] hashValue;
public byte[] Hash { get { return (byte[])hashValue.Clone(); } }
public Example()
{
nValue = 2;
hashValue = new byte[20];
hashValue[0] = 2;
}
~Example()
{
nValue = 0;
if (hashValue != null)
{
Array.Clear(hashValue, 0, hashValue.Length);
}
}
}
</code></pre>
<p>But nothing is so simple...
The code using this class is wokring inside a thread, and of course, for the test, the app is heavily multithreaded:</p>
<pre><code>public static void Main(string[] args)
{
Thread t = new Thread(new ThreadStart(ThreadProc));
t.Start();
t.Join();
}
private static void ThreadProc()
{
// running is a boolean which is always true until
// the user press ENTER
while (running) DoWork();
}
</code></pre>
<p>The DoWork static method is the code where the problem happens:</p>
<pre><code>private static void DoWork()
{
Example ex = new Example();
byte[] res = ex.Hash; // [1]
// If the finalizer runs before the call to the Hash
// property completes, the hashValue array might be
// cleared before the property value is read. The
// following test detects that.
if (res[0] != 2)
{
// Oops... The finalizer of ex was launched before
// the Hash method/property completed
}
}
</code></pre>
<p>Once every 1,000,000 excutions of DoWork, apparently, the Garbage Collector does its magic, and tries to reclaim "ex", as it is not anymore referenced in the remaning code of the function, and this time, it is faster than the "Hash" get method. So what we have in the end is a clone of a zero-ed byte array, instead of having the right one (with the 1st item at 2).</p>
<p>My guess is that there is inlining of the code, which essentially replaces the line marked [1] in the DoWork function by something like:</p>
<pre><code> // Supposed inlined processing
byte[] res2 = ex.Hash2;
// note that after this line, "ex" could be garbage collected,
// but not res2
byte[] res = (byte[])res2.Clone();
</code></pre>
<p>If we supposed Hash2 is a simple accessor coded like:</p>
<pre><code>// Hash2 code:
public byte[] Hash2 { get { return (byte[])hashValue; } }
</code></pre>
<p>So, the question is: <b>Is this supposed to work that way in C#/.NET, or could this be considered as a bug of either the compiler of the JIT?</b></p>
<h1>edit</h1>
<p>See Chris Brumme's and Chris Lyons' blogs for an explanation.</p>
<p><a href="http://blogs.msdn.com/cbrumme/archive/2003/04/19/51365.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/cbrumme/archive/2003/04/19/51365.aspx</a><br>
<a href="http://blogs.msdn.com/clyon/archive/2004/09/21/232445.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/clyon/archive/2004/09/21/232445.aspx</a></p>
<p>Everyone's answer was interesting, but I couldn't choose one better than the other. So I gave you all a +1...</p>
<p>Sorry</p>
<p>:-)</p>
<h1>Edit 2</h1>
<p>I was unable to reproduce the problem on Linux/Ubuntu/Mono, despite using the same code on the same conditions (multiple same executable running simultaneously, release mode, etc.)</p>
| [
{
"answer_id": 134687,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 0,
"selected": false,
"text": "<h2>The Full Code</h2>\n<p>You'll find below the full code, copy/pasted from a Visual C++ 2008 .cs file. As I'm now on Linux, and without any Mono compiler or knowledge about its use, there's no way I can do tests now. Still, a couple of hours ago, I saw this code work and its bug:</p>\n<pre><code>using System;\nusing System.Threading;\n\npublic class Example\n{\n private int nValue;\n public int N { get { return nValue; } }\n\n // The Hash property is slower because it clones an array. When\n // KeepAlive is not used, the finalizer sometimes runs before \n // the Hash property value is read.\n\n private byte[] hashValue;\n public byte[] Hash { get { return (byte[])hashValue.Clone(); } }\n public byte[] Hash2 { get { return (byte[])hashValue; } }\n\n public int returnNothing() { return 25; }\n\n public Example()\n {\n nValue = 2;\n hashValue = new byte[20];\n hashValue[0] = 2;\n }\n\n ~Example()\n {\n nValue = 0;\n\n if (hashValue != null)\n {\n Array.Clear(hashValue, 0, hashValue.Length);\n }\n }\n}\n\npublic class Test\n{\n private static int totalCount = 0;\n private static int finalizerFirstCount = 0;\n\n // This variable controls the thread that runs the demo.\n private static bool running = true;\n\n // In order to demonstrate the finalizer running first, the\n // DoWork method must create an Example object and invoke its\n // Hash property. If there are no other calls to members of\n // the Example object in DoWork, garbage collection reclaims\n // the Example object aggressively. Sometimes this means that\n // the finalizer runs before the call to the Hash property\n // completes. \n\n private static void DoWork()\n {\n totalCount++;\n\n // Create an Example object and save the value of the \n // Hash property. There are no more calls to members of \n // the object in the DoWork method, so it is available\n // for aggressive garbage collection.\n\n Example ex = new Example();\n\n // Normal processing\n byte[] res = ex.Hash;\n\n // Supposed inlined processing\n //byte[] res2 = ex.Hash2;\n //byte[] res = (byte[])res2.Clone();\n\n // successful try to keep reference alive\n //ex.returnNothing();\n\n // Failed try to keep reference alive\n //ex = null;\n\n // If the finalizer runs before the call to the Hash \n // property completes, the hashValue array might be\n // cleared before the property value is read. The \n // following test detects that.\n\n if (res[0] != 2)\n {\n finalizerFirstCount++;\n Console.WriteLine("The finalizer ran first at {0} iterations.", totalCount);\n }\n\n //GC.KeepAlive(ex);\n }\n\n public static void Main(string[] args)\n {\n Console.WriteLine("Test:");\n\n // Create a thread to run the test.\n Thread t = new Thread(new ThreadStart(ThreadProc));\n t.Start();\n\n // The thread runs until Enter is pressed.\n Console.WriteLine("Press Enter to stop the program.");\n Console.ReadLine();\n\n running = false;\n\n // Wait for the thread to end.\n t.Join();\n\n Console.WriteLine("{0} iterations total; the finalizer ran first {1} times.", totalCount, finalizerFirstCount);\n }\n\n private static void ThreadProc()\n {\n while (running) DoWork();\n }\n}\n</code></pre>\n<p>For those interested, I can send the zipped project through email.</p>\n"
},
{
"answer_id": 134703,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 1,
"selected": false,
"text": "<p>this looks like a race condition between your work thread and the GC thread(s); to avoid it, i think there are two options:</p>\n\n<p>(1) change your if statement to use ex.Hash[0] instead of res, so that ex cannot be GC'd prematurely, or</p>\n\n<p>(2) lock ex for the duration of the call to Hash</p>\n\n<p>that's a pretty spiffy example - was the teacher's point that there may be a bug in the JIT compiler that only manifests on multicore systems, or that this kind of coding can have subtle race conditions with garbage collection?</p>\n"
},
{
"answer_id": 134710,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 1,
"selected": false,
"text": "<p>I think what you are seeing is <strong>reasonable</strong> behavior due to the fact that things are running on multiple threads. This is the reason for the GC.KeepAlive() method, which should be used in this case to tell the GC that the object is still being used and that it isn't a candidate for cleanup.</p>\n\n<p>Looking at the DoWork function in your \"full code\" response, the problem is that immediately after this line of code:</p>\n\n<pre><code>byte[] res = ex.Hash;\n</code></pre>\n\n<p>the function no longer makes any references to the <em>ex</em> object, so it becomes eligible for garbage collection at that point. Adding the call to GC.KeepAlive would prevent this from happening.</p>\n"
},
{
"answer_id": 134756,
"author": "Palad1",
"author_id": 22187,
"author_profile": "https://Stackoverflow.com/users/22187",
"pm_score": 1,
"selected": false,
"text": "<p>That's perfectly nornal for the finalizer to be called in your do work method as after the\nex.Hash call, the CLR knows that the ex instance won't be needed anymore...</p>\n\n<p>Now, if you want to keep the instance alive do this:</p>\n\n<pre><code>private static void DoWork()\n{\n Example ex = new Example();\n\n byte[] res = ex.Hash; // [1]\n\n // If the finalizer runs before the call to the Hash \n // property completes, the hashValue array might be\n // cleared before the property value is read. The \n // following test detects that.\n\n if (res[0] != 2) // NOTE\n {\n // Oops... The finalizer of ex was launched before\n // the Hash method/property completed\n }\n GC.KeepAlive(ex); // keep our instance alive in case we need it.. uh.. we don't\n}\n</code></pre>\n\n<p>GC.KeepAlive does... nothing :) it's an empty not inlinable /jittable method whose only purpose is to trick the GC into thinking the object will be used after this.</p>\n\n<p>WARNING: Your example is perfectly valid if the DoWork method were a managed C++ method... You <em>DO</em> have to manually keep the managed instances alive manually if you don't want the destructor to be called from within another thread. IE. you pass a reference to a managed object who is going to delete a blob of unmanaged memory when finalized, and the method is using this same blob. If you don't hold the instance alive, you're going to have a race condition between the GC and your method's thread. </p>\n\n<p>And this will end up in tears. And managed heap corruption...</p>\n"
},
{
"answer_id": 134758,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 2,
"selected": false,
"text": "<p>What you're seeing is perfectly natural.</p>\n\n<p>You don't keep a reference to the object that owns the byte array, so that object (not the byte array) is actually free for the garbage collector to collect.</p>\n\n<p>The garbage collector really can be that aggressive.</p>\n\n<p>So if you call a method on your object, which returns a reference to an internal data structure, and the finalizer for your object mess up that data structure, you need to keep a live reference to the object as well.</p>\n\n<p>The garbage collector sees that the ex variable isn't used in that method any more, so it can, and as you notice, will garbage collect it under the right circumstances (ie. timing and need).</p>\n\n<p>The correct way to do this is to call GC.KeepAlive on ex, so add this line of code to the bottom of your method, and all should be well:</p>\n\n<pre><code>GC.KeepAlive(ex);\n</code></pre>\n\n<p>I learned about this aggressive behavior by reading the book <a href=\"http://www.microsoft.com/mspress/books/5353.aspx\" rel=\"nofollow noreferrer\">Applied .NET Framework Programming</a> by Jeffrey Richter.</p>\n"
},
{
"answer_id": 135168,
"author": "Jack Bolding",
"author_id": 5882,
"author_profile": "https://Stackoverflow.com/users/5882",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, this is an <a href=\"http://blogs.microsoft.co.il/blogs/sasha/archive/2008/07/28/finalizer-vs-application-a-race-condition-from-hell.aspx\" rel=\"nofollow noreferrer\">issue</a> that has <a href=\"http://blogs.msdn.com/ricom/archive/2004/05/19/135332.aspx\" rel=\"nofollow noreferrer\">come up before</a>. </p>\n\n<p>Its even more fun in that you need to run release for this to happen and you end up stratching your head going 'huh, how can that be null?'.</p>\n"
},
{
"answer_id": 135598,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 1,
"selected": false,
"text": "<h1>Interesting comment from Chris Brumme's blog</h1>\n<p><a href=\"http://blogs.msdn.com/cbrumme/archive/2003/04/19/51365.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/cbrumme/archive/2003/04/19/51365.aspx</a></p>\n<pre><code>class C {<br>\n IntPtr _handle;\n Static void OperateOnHandle(IntPtr h) { ... }\n void m() {\n OperateOnHandle(_handle);\n ...\n }\n ...\n}\n\nclass Other {\n void work() {\n if (something) {\n C aC = new C();\n aC.m();\n ... // most guess here\n } else {\n ...\n }\n }\n}\n</code></pre>\n<blockquote>\n<p>So we can’t say how long ‘aC’ might live in the above code. The JIT might report the reference until Other.work() completes. It might inline Other.work() into some other method, and report aC even longer. Even if you add “aC = null;” after your usage of it, the JIT is free to consider this assignment to be dead code and eliminate it. Regardless of when the JIT stops reporting the reference, the GC might not get around to collecting it for some time.</p>\n<p>It’s more interesting to worry about the earliest point that aC could be collected. If you are like most people, you’ll guess that the soonest aC becomes eligible for collection is at the closing brace of Other.work()’s “if” clause, where I’ve added the comment. In fact, braces don’t exist in the IL. They are a syntactic contract between you and your language compiler. <b>Other.work() is free to stop reporting aC as soon as it has initiated the call to aC.m().</b></p>\n</blockquote>\n"
},
{
"answer_id": 143599,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 4,
"selected": true,
"text": "<p>It's simply a bug in your code: finalizers should not be accessing managed objects.</p>\n\n<p>The only reason to implement a finalizer is to release unmanaged resources. And in this case, you should carefully implement <a href=\"http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx\" rel=\"noreferrer\">the standard IDisposable pattern</a>.</p>\n\n<p>With this pattern, you implement a protected method \"protected Dispose(bool disposing)\". When this method is called from the finalizer, it cleans up unmanaged resources, but does not attempt to clean up managed resources.</p>\n\n<p>In your example, you don't have any unmanaged resources, so should not be implementing a finalizer.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14089/"
]
| **Summary:** C#/.NET is supposed to be garbage collected. C# has a destructor, used to clean resources. What happen when an object A is garbage collected the same line I try to clone one of its variable members? Apparently, on multiprocessors, sometimes, the garbage collector wins...
**The problem**
Today, on a training session on C#, the teacher showed us some code which contained a bug only when run on multiprocessors.
I'll summarize to say that sometimes, the compiler or the JIT screws up by calling the finalizer of a C# class object before returning from its called method.
The full code, given in Visual C++ 2005 documentation, will be posted as an "answer" to avoid making a very very large questions, but the essential are below:
The following class has a "Hash" property which will return a cloned copy of an internal array. At is construction, the first item of the array has a value of 2. In the destructor, its value is set to zero.
The point is: If you try to get the "Hash" property of "Example", you'll get a clean copy of the array, whose first item is still 2, as the object is being used (and as such, not being garbage collected/finalized):
```
public class Example
{
private int nValue;
public int N { get { return nValue; } }
// The Hash property is slower because it clones an array. When
// KeepAlive is not used, the finalizer sometimes runs before
// the Hash property value is read.
private byte[] hashValue;
public byte[] Hash { get { return (byte[])hashValue.Clone(); } }
public Example()
{
nValue = 2;
hashValue = new byte[20];
hashValue[0] = 2;
}
~Example()
{
nValue = 0;
if (hashValue != null)
{
Array.Clear(hashValue, 0, hashValue.Length);
}
}
}
```
But nothing is so simple...
The code using this class is wokring inside a thread, and of course, for the test, the app is heavily multithreaded:
```
public static void Main(string[] args)
{
Thread t = new Thread(new ThreadStart(ThreadProc));
t.Start();
t.Join();
}
private static void ThreadProc()
{
// running is a boolean which is always true until
// the user press ENTER
while (running) DoWork();
}
```
The DoWork static method is the code where the problem happens:
```
private static void DoWork()
{
Example ex = new Example();
byte[] res = ex.Hash; // [1]
// If the finalizer runs before the call to the Hash
// property completes, the hashValue array might be
// cleared before the property value is read. The
// following test detects that.
if (res[0] != 2)
{
// Oops... The finalizer of ex was launched before
// the Hash method/property completed
}
}
```
Once every 1,000,000 excutions of DoWork, apparently, the Garbage Collector does its magic, and tries to reclaim "ex", as it is not anymore referenced in the remaning code of the function, and this time, it is faster than the "Hash" get method. So what we have in the end is a clone of a zero-ed byte array, instead of having the right one (with the 1st item at 2).
My guess is that there is inlining of the code, which essentially replaces the line marked [1] in the DoWork function by something like:
```
// Supposed inlined processing
byte[] res2 = ex.Hash2;
// note that after this line, "ex" could be garbage collected,
// but not res2
byte[] res = (byte[])res2.Clone();
```
If we supposed Hash2 is a simple accessor coded like:
```
// Hash2 code:
public byte[] Hash2 { get { return (byte[])hashValue; } }
```
So, the question is: **Is this supposed to work that way in C#/.NET, or could this be considered as a bug of either the compiler of the JIT?**
edit
====
See Chris Brumme's and Chris Lyons' blogs for an explanation.
<http://blogs.msdn.com/cbrumme/archive/2003/04/19/51365.aspx>
<http://blogs.msdn.com/clyon/archive/2004/09/21/232445.aspx>
Everyone's answer was interesting, but I couldn't choose one better than the other. So I gave you all a +1...
Sorry
:-)
Edit 2
======
I was unable to reproduce the problem on Linux/Ubuntu/Mono, despite using the same code on the same conditions (multiple same executable running simultaneously, release mode, etc.) | It's simply a bug in your code: finalizers should not be accessing managed objects.
The only reason to implement a finalizer is to release unmanaged resources. And in this case, you should carefully implement [the standard IDisposable pattern](http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx).
With this pattern, you implement a protected method "protected Dispose(bool disposing)". When this method is called from the finalizer, it cleans up unmanaged resources, but does not attempt to clean up managed resources.
In your example, you don't have any unmanaged resources, so should not be implementing a finalizer. |
134,656 | <p>Where can I find a Perl module for converting a Perl data structure into a JavaScript one?</p>
<p>e.g. this is my code (Mason):</p>
<pre><code>% # convert our @cti data structure into a javascript one
var cti = [
% foreach my $cti_category (@cti) {
{
label: "<% $cti_category->{'label'} %>",
value: "<% $cti_category->{'value'} %>",
children: [
% foreach my $cti_type (@{$cti_category->{'children'}}) {
{
label: "<% $cti_type->{'label'} %>",
value: "<% $cti_type->{'value'} %>",
},
% }
]
},
% }
];
</code></pre>
<p>is there a module for this?</p>
| [
{
"answer_id": 134672,
"author": "moritz",
"author_id": 14132,
"author_profile": "https://Stackoverflow.com/users/14132",
"pm_score": 3,
"selected": false,
"text": "<p>Check out <a href=\"http://search.cpan.org/perldoc?JSON\" rel=\"noreferrer\">JSON</a> or <a href=\"http://search.cpan.org/perldoc?JSON::XS\" rel=\"noreferrer\">JSON::XS</a>.</p>\n\n<p>To elaborate a bit more, JSON is \"JavaScript Object Notation\", and the two modules above convert perl data structures into that format.</p>\n"
},
{
"answer_id": 134678,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://search.cpan.org/~makamaka/JSON-2.53/lib/JSON.pm\" rel=\"nofollow noreferrer\">JSON</a> !</p>\n\n<blockquote>\n <p>This module converts Perl data structures to JSON and vice versa using either JSON::XS or JSON::PP.</p>\n</blockquote>\n"
},
{
"answer_id": 134682,
"author": "Kyle Burton",
"author_id": 19784,
"author_profile": "https://Stackoverflow.com/users/19784",
"pm_score": 0,
"selected": false,
"text": "<p>The <a href=\"http://search.cpan.org/~makamaka/JSON-2.12/lib/JSON.pm\" rel=\"nofollow noreferrer\">JSON</a> module will convert data structures - it's basically a to/from JSON serializer. </p>\n"
},
{
"answer_id": 135182,
"author": "Penfold",
"author_id": 11952,
"author_profile": "https://Stackoverflow.com/users/11952",
"pm_score": 4,
"selected": false,
"text": "<p>JSON stands for JavaScript Object Notation, which is the format you're looking for.</p>\n\n<p>Unfortunately, none of the modules you're looking for are in the Perl core, but they are available on CPAN, as a quick <a href=\"http://search.cpan.org/search?query=JSON&mode=all\" rel=\"noreferrer\">search</a> will reveal.</p>\n\n<p>I'd actually recommend installing <a href=\"http://search.cpan.org/author/RBERJON/JSON-Any-1.17/lib/JSON/Any.pm\" rel=\"noreferrer\">JSON::Any</a> as a wrapper, as well as <a href=\"http://search.cpan.org/author/MLEHMANN/JSON-XS-2.2222/XS.pm\" rel=\"noreferrer\">JSON::XS</a> (if you have a C compiler) or one of <a href=\"http://search.cpan.org/author/MAKAMAKA/JSON-2.12/lib/JSON.pm\" rel=\"noreferrer\">JSON</a> and <a href=\"http://search.cpan.org/~audreyt/YAML-Syck-1.05/lib/JSON/Syck.pm\" rel=\"noreferrer\">JSON::Syck</a> if you don't. JSON::Any provides an <a href=\"http://en.wikipedia.org/wiki/Interface_pattern\" rel=\"noreferrer\">interface class</a> on top of several other JSON modules (you can choose, or let it pick from what's installed) that's independent of which module you wind up using. That way, if your code should need to be ported elsewhere, and (say) the target machine can install JSON::XS when you can't, you get a performance boost without any extra code.</p>\n\n<pre><code>use JSON::Any;\n\nmy $j = JSON::Any->new;\n\n$json = $j->objToJson($perl_data);\n</code></pre>\n\n<p>Like so.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8913/"
]
| Where can I find a Perl module for converting a Perl data structure into a JavaScript one?
e.g. this is my code (Mason):
```
% # convert our @cti data structure into a javascript one
var cti = [
% foreach my $cti_category (@cti) {
{
label: "<% $cti_category->{'label'} %>",
value: "<% $cti_category->{'value'} %>",
children: [
% foreach my $cti_type (@{$cti_category->{'children'}}) {
{
label: "<% $cti_type->{'label'} %>",
value: "<% $cti_type->{'value'} %>",
},
% }
]
},
% }
];
```
is there a module for this? | JSON stands for JavaScript Object Notation, which is the format you're looking for.
Unfortunately, none of the modules you're looking for are in the Perl core, but they are available on CPAN, as a quick [search](http://search.cpan.org/search?query=JSON&mode=all) will reveal.
I'd actually recommend installing [JSON::Any](http://search.cpan.org/author/RBERJON/JSON-Any-1.17/lib/JSON/Any.pm) as a wrapper, as well as [JSON::XS](http://search.cpan.org/author/MLEHMANN/JSON-XS-2.2222/XS.pm) (if you have a C compiler) or one of [JSON](http://search.cpan.org/author/MAKAMAKA/JSON-2.12/lib/JSON.pm) and [JSON::Syck](http://search.cpan.org/~audreyt/YAML-Syck-1.05/lib/JSON/Syck.pm) if you don't. JSON::Any provides an [interface class](http://en.wikipedia.org/wiki/Interface_pattern) on top of several other JSON modules (you can choose, or let it pick from what's installed) that's independent of which module you wind up using. That way, if your code should need to be ported elsewhere, and (say) the target machine can install JSON::XS when you can't, you get a performance boost without any extra code.
```
use JSON::Any;
my $j = JSON::Any->new;
$json = $j->objToJson($perl_data);
```
Like so. |
134,658 | <p>I am trying to encrypt the "system.web.membership" element within the Web.Config of our .Net application to secure username and password to Active Directory. I am using the aspnet_regiis command to encrypt, and have tried several different strings for the value of the "pe" option with no success. I have successfully encrypted the "connectstrings" element on my web.config.</p>
<p>Cmd</p>
<pre>C:\Windows\Microsoft.NET\Framework\v2.0.50727>aspnet_regiis -pe "connectionStrings" -site MySite -app /MyApp
Encrypting configuration section...
Succeeded!
C:\Windows\Microsoft.NET\Framework\v2.0.50727>aspnet_regiis -pe "membership" -site MySite -app /MyApp
Encrypting configuration section...
The configuration section 'membership' was not found.
Failed!
C:\Windows\Microsoft.NET\Framework\v2.0.50727>aspnet_regiis -pe "system.web.membership" -site MySite -app /MyApp
Encrypting configuration section...
The configuration section 'system.web.membership' was not found.
Failed!</pre>
<p>Web.Config</p>
<pre><code><configuration>
...
<system.web>
...
<authentication mode="Forms">
<forms name=".ADAuthCookie"
timeout="30"/>
</authentication>
<authorization>
<deny users="?"/>
<allow users="*"/>
</authorization>
<membership defaultProvider="MyADMembershipProvider">
<providers>
<add name="MyADMembershipProvider"
type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0,Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="ADConnectionString"
connectionUsername="MyUserName"
connectionPassword="MyPassowrd"/>
</providers>
</membership>
...
</system.web>
...
</configuration>
</code></pre>
<p>So what gives? What am I missing?</p>
| [
{
"answer_id": 134733,
"author": "Paul Lalonde",
"author_id": 5782,
"author_profile": "https://Stackoverflow.com/users/5782",
"pm_score": 4,
"selected": true,
"text": "<p>The configuration section is identified by \"<code>system.web/membership</code>\", not \"<code>membership</code>\" nor \"<code>system.web.membership</code>\".</p>\n"
},
{
"answer_id": 638730,
"author": "Ben Mills",
"author_id": 203,
"author_profile": "https://Stackoverflow.com/users/203",
"pm_score": 2,
"selected": false,
"text": "<p>I know that your issue has already been solved, but for other people getting this error message, it seems that only certain sections of the web.config can be encrypted. I was trying to encrypt the SMTP settings in my web config:</p>\n\n<pre><code><?xml version=\"1.0\"?>\n<configuration>\n <system.net>\n <mailSettings>\n <smtp>\n <network host=\"myhost\" port=\"25\" userName=\"myusername\" password=\"mypassword\" />\n </smtp>\n </mailSettings>\n </system.net>\n</configuration>\n</code></pre>\n\n<p>This worked:</p>\n\n<pre><code>aspnet_regiis.exe -pef \"system.net/mailSettings/smtp\" \"path_to_site\" -prov \"DataProtectionConfigurationProvider\"\n</code></pre>\n\n<p>but these didn't:</p>\n\n<pre><code>aspnet_regiis.exe -pef \"system.net/mailSettings\" \"path_to_site\" -prov \"DataProtectionConfigurationProvider\"\n\naspnet_regiis.exe -pef \"system.net\" \"path_to_site\" -prov \"DataProtectionConfigurationProvider\"\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/576/"
]
| I am trying to encrypt the "system.web.membership" element within the Web.Config of our .Net application to secure username and password to Active Directory. I am using the aspnet\_regiis command to encrypt, and have tried several different strings for the value of the "pe" option with no success. I have successfully encrypted the "connectstrings" element on my web.config.
Cmd
```
C:\Windows\Microsoft.NET\Framework\v2.0.50727>aspnet_regiis -pe "connectionStrings" -site MySite -app /MyApp
Encrypting configuration section...
Succeeded!
C:\Windows\Microsoft.NET\Framework\v2.0.50727>aspnet_regiis -pe "membership" -site MySite -app /MyApp
Encrypting configuration section...
The configuration section 'membership' was not found.
Failed!
C:\Windows\Microsoft.NET\Framework\v2.0.50727>aspnet_regiis -pe "system.web.membership" -site MySite -app /MyApp
Encrypting configuration section...
The configuration section 'system.web.membership' was not found.
Failed!
```
Web.Config
```
<configuration>
...
<system.web>
...
<authentication mode="Forms">
<forms name=".ADAuthCookie"
timeout="30"/>
</authentication>
<authorization>
<deny users="?"/>
<allow users="*"/>
</authorization>
<membership defaultProvider="MyADMembershipProvider">
<providers>
<add name="MyADMembershipProvider"
type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0,Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="ADConnectionString"
connectionUsername="MyUserName"
connectionPassword="MyPassowrd"/>
</providers>
</membership>
...
</system.web>
...
</configuration>
```
So what gives? What am I missing? | The configuration section is identified by "`system.web/membership`", not "`membership`" nor "`system.web.membership`". |
134,673 | <p>I've got a VS2008 deployment project that builds an installer for a couple of Windows services.</p>
<p>Each service references several different projects:</p>
<pre>
CustomerName.MailSendingService
-> CustomerName.Network
-> CustomerName.Data
-> CustomerName.Security
CustomerName.ProductIntegrationService
-> CustomerName.Core
-> CustomerName.Security
</pre>
<p>The Windows service projects, the projects they reference, and the deployment project are all in the same VS2008 solution.</p>
<p>I've added the primary output from the Windows service projects in the deployment project's file system editor. </p>
<p>My expectation is that the primary output for the Windows service projects would include the DLLs from the referenced projects. However, when the deployment project is built, the DLL from one of the referenced projects is missing. (<code>CustomerName.ProductIntegrationService</code> is missing <code>CustomerName.Security</code>) </p>
<p>Maddeningly, the DLLs for the other projects referenced by the Windows service are present; just one project's output is missing.</p>
<p>(Edit) I've verified that the reference is set to Copy Local in the reference properties window. The DLL for the referenced project is placed in the windows service project's <code>bin\Release</code> folder, but isn't packaged in the MSI file built for the deployment project.</p>
<p>(Edit 2) Following Joseph Daigle's suggestion, I checked that the dependency is in the dependencies list for the primary output, and it's not marked "excluded," so that doesn't appear to be the cause of this issue.</p>
<p>Why would just one project's output be missing?</p>
| [
{
"answer_id": 134759,
"author": "hectorsq",
"author_id": 14755,
"author_profile": "https://Stackoverflow.com/users/14755",
"pm_score": 0,
"selected": false,
"text": "<p>I have not used Visual Studio 2008 yet, however in 2005 you have to verify that the missing reference on the project has the Copy Local property set to true.</p>\n\n<p>This will copy the missing file to the output directory.</p>\n"
},
{
"answer_id": 134795,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 0,
"selected": false,
"text": "<p>In addition to <strong>hectorsq</strong>'s response, verify that the depedency is in the deployment project dependencies list, and that the DLL in question is marked to be included.</p>\n"
},
{
"answer_id": 152295,
"author": "Benjol",
"author_id": 11410,
"author_profile": "https://Stackoverflow.com/users/11410",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried looking at your dll in reflector to see if it really does depend on the other dll? VS is smart enough to not include a referenced assembly if it can see that you are not actually using it.</p>\n\n<p>Added to that, even if you 'think' you're using it, VS can optimise away your use - this is a limit case but I have seen it:</p>\n\n<p>For example, if you have a 'constants' assembly with this in:</p>\n\n<pre><code>public const string LockPanelUrn = \"ApplicationRack.LockPanel\";\n</code></pre>\n\n<p>VS will stick the string directly in your referencing code.</p>\n\n<p>Beyond that, I'd suggest deleting and rebuilding your install solution.</p>\n"
},
{
"answer_id": 309879,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Did you add this assembly dependency after initially creating the deployment project? If so, you may need to right-click the Detected Dependencies folder and select Refresh Dependencies. It will pick up anything new that has been added since the last time you did this.</p>\n"
},
{
"answer_id": 624892,
"author": "Sam",
"author_id": 47636,
"author_profile": "https://Stackoverflow.com/users/47636",
"pm_score": 2,
"selected": false,
"text": "<p>I can verify this is an issue for us as well. I suspect it's a bug in the deployment project - it only adds dependent project output in one location (maybe it thinks it's a COM dll?)</p>\n\n<p>Manually adding Primary Output for the missing dll seems to be a viable workaround.</p>\n"
},
{
"answer_id": 1077365,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>check this out - maybe this not explains why is that, but at least it provides some workaround :)</p>\n\n<p><a href=\"http://lo-sharpdevs.blogspot.com/2009/07/vs-2008-disappearing-dependencies.html\" rel=\"nofollow noreferrer\">http://lo-sharpdevs.blogspot.com/2009/07/vs-2008-disappearing-dependencies.html</a></p>\n"
},
{
"answer_id": 3189578,
"author": "Chad Pavliska",
"author_id": 71656,
"author_profile": "https://Stackoverflow.com/users/71656",
"pm_score": 4,
"selected": true,
"text": "<p>I have a couple more things to add after reproducing the same suspected msi defect.</p>\n\n<p>1) When I added the second project output sharing the same detected dependency to the installer it did not automatically add the dependency. I removed both project output's and added them back in reverse order. The second project output added never added the detected dependency. This excludes any configuration or code issue with the projects and how the references were added. It's always the second one that fails.</p>\n\n<p>2) My team actually hit a second problem after using the 'Manually add detected assembly' workaround. Initially we added the dependency from the location in '\\Program Files\\xxx' but ran into build problems on 64 bit machines where that same dependency was in the '\\Program Files (x86)\\xxx' folder even though VS is smart enough to handle this problem when picking up references.</p>\n\n<ul>\n<li>The proper way to manually add the assembly is by navigating to the bin folder and adding the assembly that is copied local. This ensures that the right assembly will be present on x86 or x64 machines.</li>\n</ul>\n"
},
{
"answer_id": 4872460,
"author": "Max Power",
"author_id": 431569,
"author_profile": "https://Stackoverflow.com/users/431569",
"pm_score": 0,
"selected": false,
"text": "<p>I have had a similar issue with Microsoft SMO objects usage. I have a binary component (X.dll) that uses these Microsoft SMO objects that i've made myself. After compiling X.dll, I reference it in another EXE project using X.dll (and not the code). The installer project attached to that detects that it needs the Microsoft SMO Objects and detects that they are local to my SQL Server installation on the machine.</p>\n\n<p>The component X.dll that uses the SMO Objects references the Microsoft SMO Objects via a local \"Externals\" folder i keep on a shared drive. All modules are compiled with reference to those, however my install project with my EXE project detects the ones from my SQL Server installation.</p>\n\n<p>Because of this, we have another machine that has the \"Externals\" folder with SMO Objects, but the install project won't find the SMO objects from 'Detected Dependancies' anymore as it's not realising the SMO Objects are in the externals module! I'm not sure where it searches for the Detected Dependancy files, but it's not looking at where X.dll originally picked them up from, or even the EXE folder perhaps...</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18102/"
]
| I've got a VS2008 deployment project that builds an installer for a couple of Windows services.
Each service references several different projects:
```
CustomerName.MailSendingService
-> CustomerName.Network
-> CustomerName.Data
-> CustomerName.Security
CustomerName.ProductIntegrationService
-> CustomerName.Core
-> CustomerName.Security
```
The Windows service projects, the projects they reference, and the deployment project are all in the same VS2008 solution.
I've added the primary output from the Windows service projects in the deployment project's file system editor.
My expectation is that the primary output for the Windows service projects would include the DLLs from the referenced projects. However, when the deployment project is built, the DLL from one of the referenced projects is missing. (`CustomerName.ProductIntegrationService` is missing `CustomerName.Security`)
Maddeningly, the DLLs for the other projects referenced by the Windows service are present; just one project's output is missing.
(Edit) I've verified that the reference is set to Copy Local in the reference properties window. The DLL for the referenced project is placed in the windows service project's `bin\Release` folder, but isn't packaged in the MSI file built for the deployment project.
(Edit 2) Following Joseph Daigle's suggestion, I checked that the dependency is in the dependencies list for the primary output, and it's not marked "excluded," so that doesn't appear to be the cause of this issue.
Why would just one project's output be missing? | I have a couple more things to add after reproducing the same suspected msi defect.
1) When I added the second project output sharing the same detected dependency to the installer it did not automatically add the dependency. I removed both project output's and added them back in reverse order. The second project output added never added the detected dependency. This excludes any configuration or code issue with the projects and how the references were added. It's always the second one that fails.
2) My team actually hit a second problem after using the 'Manually add detected assembly' workaround. Initially we added the dependency from the location in '\Program Files\xxx' but ran into build problems on 64 bit machines where that same dependency was in the '\Program Files (x86)\xxx' folder even though VS is smart enough to handle this problem when picking up references.
* The proper way to manually add the assembly is by navigating to the bin folder and adding the assembly that is copied local. This ensures that the right assembly will be present on x86 or x64 machines. |
134,683 | <p>This might be a stupid question but if there's a better or proper way to do this, I'd love to learn it.</p>
<p>I have run across this a few times, including recently, where small spaces show up in the rendered version of my HTML page. Intuitively I think these should not be there because outside of text or entities the formatting of a page's HTML shouldn't matter but apparently it does.</p>
<p>What I'm referring to is this - I have some Photoshop file from the client on how they want their site to look. They want it to look basically pixel perfect to the image in this file. </p>
<p>One of the places in the page calls for a menu bar, where each one does the changing bit on hovering, acts like a hyperlink, etc. In the Photoshop file this is one long bar, so a cheap and easy way to do this is to just split that segment into multiple images and then place them next to each other in the file. </p>
<p>So instinctively I lay it out like so (there's more to it but this is the gist)</p>
<pre><code><a href="page1.html">
<img src="image1.png" />
</a>
<a href="page2.html">
<img src="image2.png" />
</a>
<a href="page3.html">
<img src="image3.png" />
</a>
</code></pre>
<p>and so forth. </p>
<p>The problem is the images have this tiny space between them which is unacceptable since the client wants this thing pixel-perfect (and it just plain looks bad).</p>
<p>One way to get it to render properly is to remove the carriage returns between the images</p>
<pre><code><a href="page1.html">
<img src="image1.png" />
</a>
<a href="page2.html">
<img src="image2.png" />
</a>
<a href="page3.html">
<img src="image3.png" />
</a>
</code></pre>
<p>Which makes the images go right up against each other (the desired effect) but it makes the line incredibly long and the code more difficult to maintain (it wraps here in SO and this is a simplified version - the real one has longer filenames and JavaScript sprinkled in to do the hovering).</p>
<p>It seems to me that this shouldn't happen but it looks like the carriage return in the HTML is being rendered as a small empty space. And this happens in all browsers, looks like.</p>
<p>Am I right or wrong for thinking the two snippets above should render the same? And is there something I'm doing wrong? Maybe saving the file with the wrong encoding? Should I make every one of these links a perfectly positioned CSS element instead?</p>
| [
{
"answer_id": 134701,
"author": "rslite",
"author_id": 15682,
"author_profile": "https://Stackoverflow.com/users/15682",
"pm_score": 5,
"selected": true,
"text": "<p>The whitespace (carriage return included) is usually rendered as space in all browsers.</p>\n\n<p>You need to put the elements one after another, but you can use a trick:</p>\n\n<pre><code><a href=\"page1.html\"><img src=\"image1.png\" \n/></a><a href=\"page2.html\"><img src=\"image2.png\" \n/></a><a href=\"page3.html\"><img src=\"image3.png\" \n/></a>\n</code></pre>\n\n<p>This also looks a little ugly, but it's still better than one single line. You might change the formatting, but the idea is to add carriage returns inside the elements and not between them.</p>\n"
},
{
"answer_id": 134706,
"author": "Kyle Burton",
"author_id": 19784,
"author_profile": "https://Stackoverflow.com/users/19784",
"pm_score": 2,
"selected": false,
"text": "<p>That's part of the HTML specification - the spaces are in the markup so they're considered part of the document.</p>\n\n<p>The only other options you've got, since you dislike the formatting, is to break the html tags:</p>\n\n<pre><code> <a href=\"...\"><img src=\"..\" /></a\n ><a href=\"...\"><img src=\"..\" /></a\n ><a href=\"...\"><img src=\"..\" /></a\n</code></pre>\n\n<p>which is undesirable in my opinion, or create the html dynamically - either via JavaScript or using a templating system and dynamic html.</p>\n"
},
{
"answer_id": 134714,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 3,
"selected": false,
"text": "<p>I don't know if this is general enough for your page, but you could class these particular <strong>a</strong> tags and float them all left, then they'll bunch together no matter how your HTML is formatted. </p>\n\n<pre><code><style>\n a.together {\n float:left;\n }\n</style>\n\n<a class='together' href=\"page1.html\"><img src=\"image1.png\" /></a>\n<a class='together' href=\"page2.html\"><img src=\"image2.png\" /></a>\n<a class='together' href=\"page3.html\"><img src=\"image3.png\" /></a>\n</code></pre>\n"
},
{
"answer_id": 134736,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "<p>The reason is simple: In HTML white space matters, but only once. Repeated white space is ignored, only the first is shown.</p>\n\n<p>The only reliable way to avoid this is, as you did, by putting no white space between elements.</p>\n\n<p>When table based layout would be less out than it is currently, you could use a zero-border, zero padding table to align your elements while having them on separate lines in the source code.</p>\n"
},
{
"answer_id": 134738,
"author": "Dan Udey",
"author_id": 21450,
"author_profile": "https://Stackoverflow.com/users/21450",
"pm_score": 1,
"selected": false,
"text": "<p>If you're going to do a tabbed interface on a website, take great pains to do it properly, and it will be worthwhile. There are many websites with great examples of CSS tab implementations. Consider using one of them.</p>\n\n<p><a href=\"http://www.noupe.com/javascript/37-great-ajax-css-tab-based-interfaces.html\" rel=\"nofollow noreferrer\">This one</a> has a lot of CSS+Javascript/AJAX tabs. Or see <a href=\"http://htmldog.com/articles/tabs/\" rel=\"nofollow noreferrer\">this set of simple CSS examples</a> (some styled). Finally, check out this actually-pretty-cool <a href=\"http://www.tabsgenerator.com/\" rel=\"nofollow noreferrer\">tabs generator</a>.</p>\n"
},
{
"answer_id": 134739,
"author": "Kevin Chan",
"author_id": 1877,
"author_profile": "https://Stackoverflow.com/users/1877",
"pm_score": 2,
"selected": false,
"text": "<p>The behavior you demonstrated above is true as the browser treats carriage returns as a space. To fix it, you can style it like so with:</p>\n\n<pre><code>a { display: block; float: left; }\n</code></pre>\n\n<p>Please note that the above rule applies it to all links, so you might want to narrow the selector to certain elements only, ie:</p>\n\n<pre><code>#nav a { display: block; float: left; }\n</code></pre>\n"
},
{
"answer_id": 134753,
"author": "Matthew Rapati",
"author_id": 15000,
"author_profile": "https://Stackoverflow.com/users/15000",
"pm_score": 2,
"selected": false,
"text": "<p>The way I handle this is to use an unordered list, and make each image/link an item.\nThen use CSS to display each item inline and and float them to the left.</p>\n\n<p>This will give you a lot more flexibility and make the markup very readable.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2577/"
]
| This might be a stupid question but if there's a better or proper way to do this, I'd love to learn it.
I have run across this a few times, including recently, where small spaces show up in the rendered version of my HTML page. Intuitively I think these should not be there because outside of text or entities the formatting of a page's HTML shouldn't matter but apparently it does.
What I'm referring to is this - I have some Photoshop file from the client on how they want their site to look. They want it to look basically pixel perfect to the image in this file.
One of the places in the page calls for a menu bar, where each one does the changing bit on hovering, acts like a hyperlink, etc. In the Photoshop file this is one long bar, so a cheap and easy way to do this is to just split that segment into multiple images and then place them next to each other in the file.
So instinctively I lay it out like so (there's more to it but this is the gist)
```
<a href="page1.html">
<img src="image1.png" />
</a>
<a href="page2.html">
<img src="image2.png" />
</a>
<a href="page3.html">
<img src="image3.png" />
</a>
```
and so forth.
The problem is the images have this tiny space between them which is unacceptable since the client wants this thing pixel-perfect (and it just plain looks bad).
One way to get it to render properly is to remove the carriage returns between the images
```
<a href="page1.html">
<img src="image1.png" />
</a>
<a href="page2.html">
<img src="image2.png" />
</a>
<a href="page3.html">
<img src="image3.png" />
</a>
```
Which makes the images go right up against each other (the desired effect) but it makes the line incredibly long and the code more difficult to maintain (it wraps here in SO and this is a simplified version - the real one has longer filenames and JavaScript sprinkled in to do the hovering).
It seems to me that this shouldn't happen but it looks like the carriage return in the HTML is being rendered as a small empty space. And this happens in all browsers, looks like.
Am I right or wrong for thinking the two snippets above should render the same? And is there something I'm doing wrong? Maybe saving the file with the wrong encoding? Should I make every one of these links a perfectly positioned CSS element instead? | The whitespace (carriage return included) is usually rendered as space in all browsers.
You need to put the elements one after another, but you can use a trick:
```
<a href="page1.html"><img src="image1.png"
/></a><a href="page2.html"><img src="image2.png"
/></a><a href="page3.html"><img src="image3.png"
/></a>
```
This also looks a little ugly, but it's still better than one single line. You might change the formatting, but the idea is to add carriage returns inside the elements and not between them. |
134,691 | <p>I am trying to create a jar file which includes some class and java files needed, but I also would like to include some extra xml, xsl, html, txt (README) files.</p>
<p>I am using Eclipse on Windows XP.</p>
<p>Is there an easy way for me to set up a directory structure and package all my files into a jar?</p>
| [
{
"answer_id": 134716,
"author": "Roman Plášil",
"author_id": 16590,
"author_profile": "https://Stackoverflow.com/users/16590",
"pm_score": 1,
"selected": false,
"text": "<p>A .jar is nothing but a ZIP archive, so you can use any program capable of creating ZIPs. Just make sure that you include the manifest and all the class files.</p>\n"
},
{
"answer_id": 134721,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 2,
"selected": false,
"text": "<p>Add the files to a source folder and they can be included in the jar.</p>\n\n<p>One common way is to have, at the root of your project, a src folder. Within that, folders for java files, and others. something like:</p>\n\n<pre>src/\n css/\n java/\n html/\n images/</pre>\n\n<p>Then you can make each of those subfolders a source folder (Right click, Use as Source Folder) and they should be available to add to the jar.</p>\n"
},
{
"answer_id": 134744,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": 0,
"selected": false,
"text": "<p>If you move to an ANT (or Maven, for you Maven fans) then you can automate the Jar building very nicely, and also use it outside of Eclipse (e.g., in an automated build environment). All you need to do is copy the files from your src, jsp, foobar and resources locations into a build staging folder, then Jar the resulting files using ANT's Jar task.</p>\n\n<pre><code><target name=\"makejar\" depends=\"compile, copyfiles\">\n\n <jar destfile=\"${jars.dir}/myjarfile.jar\" index=\"true\" basedir=\"${build.dir}\" />\n\n</target>\n</code></pre>\n\n<p>One thing I look down on is including non-source (except package.html files for Javadoc) within the src folder. If you feel you have to do this to achieve something, then you are doing it wrong.</p>\n"
},
{
"answer_id": 134751,
"author": "Sam Martin",
"author_id": 19088,
"author_profile": "https://Stackoverflow.com/users/19088",
"pm_score": 1,
"selected": false,
"text": "<p>If you're using Ant, you can use the <a href=\"http://ant.apache.org/manual/Tasks/jar.html\" rel=\"nofollow noreferrer\"><code>jar</code> task</a> (see the examples section for how to include/exclude certain files, etc.)</p>\n"
},
{
"answer_id": 136370,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I just added all the files into my Eclipse project (including the txt, html, xml, etc files).</p>\n\n<p>Then I used Eclipse to File->Export->Jar File->Next\nCheck the \"Export Java source files and resources\" box.</p>\n\n<p>Done.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I am trying to create a jar file which includes some class and java files needed, but I also would like to include some extra xml, xsl, html, txt (README) files.
I am using Eclipse on Windows XP.
Is there an easy way for me to set up a directory structure and package all my files into a jar? | Add the files to a source folder and they can be included in the jar.
One common way is to have, at the root of your project, a src folder. Within that, folders for java files, and others. something like:
```
src/
css/
java/
html/
images/
```
Then you can make each of those subfolders a source folder (Right click, Use as Source Folder) and they should be available to add to the jar. |
134,712 | <p>I would like to sort a matrix according to a particular column. There is a <code>sort</code> function, but it sorts all columns independently.</p>
<p>For example, if my matrix <code>data</code> is:</p>
<pre><code> 1 3
5 7
-1 4
</code></pre>
<p>Then the desired output (sorting by the first column) would be:</p>
<pre><code>-1 4
1 3
5 7
</code></pre>
<p>But the output of <code>sort(data)</code> is:</p>
<pre><code>-1 3
1 4
5 7
</code></pre>
<p>How can I sort this matrix by the first column?</p>
| [
{
"answer_id": 135115,
"author": "Kena",
"author_id": 8027,
"author_profile": "https://Stackoverflow.com/users/8027",
"pm_score": 7,
"selected": true,
"text": "<p>I think the <a href=\"http://www.mathworks.com/help/matlab/ref/sortrows.html\" rel=\"noreferrer\">sortrows</a> function is what you're looking for.</p>\n\n<pre><code>>> sortrows(data,1)\n\nans =\n\n -1 4\n 1 3\n 5 7\n</code></pre>\n"
},
{
"answer_id": 35832813,
"author": "AlessioX",
"author_id": 5149764,
"author_profile": "https://Stackoverflow.com/users/5149764",
"pm_score": 3,
"selected": false,
"text": "<p>An alternative to <code>sortrows()</code>, which can be applied to broader scenarios.</p>\n\n<ol>\n<li><p>save the sorting indices of the row/column you want to order by:</p>\n\n<pre><code>[~,idx]=sort(data(:,1));\n</code></pre></li>\n<li><p>reorder all the rows/columns according to the previous sorted indices</p>\n\n<pre><code>data=data(idx,:)\n</code></pre></li>\n</ol>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9425/"
]
| I would like to sort a matrix according to a particular column. There is a `sort` function, but it sorts all columns independently.
For example, if my matrix `data` is:
```
1 3
5 7
-1 4
```
Then the desired output (sorting by the first column) would be:
```
-1 4
1 3
5 7
```
But the output of `sort(data)` is:
```
-1 3
1 4
5 7
```
How can I sort this matrix by the first column? | I think the [sortrows](http://www.mathworks.com/help/matlab/ref/sortrows.html) function is what you're looking for.
```
>> sortrows(data,1)
ans =
-1 4
1 3
5 7
``` |
134,728 | <p>I have a class declared as follows:</p>
<pre><code>Public MustInherit Container(Of T As {New, BaseClass}) Inherits ArrayList(Of T)
</code></pre>
<p>I have classes that inherit this class.</p>
<p>I have another class that I must pass instances in this method:</p>
<pre><code>Public Sub LoadCollection(Of T As {BaseClass, New})(ByRef Collection As Container(Of T))
</code></pre>
<p>I need to store the passed in object in a global variable, but i can't simply declare it:</p>
<pre><code>Private _Container as Collection(Of BaseClass)
</code></pre>
<p>What is the syntax to declare this object?</p>
| [
{
"answer_id": 134811,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": "<p>It cannot be a global variable. Container is an idea, not a thing.</p>\n\n<p>As you have it designed, that idea is only formed into an actual thing inside LoadCollection(). You need to convey the information outside of that method.</p>\n"
},
{
"answer_id": 137165,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Hmmm. \"Collection\" is a variable name, not a Type. I think this is what you want:</p>\n\n<pre><code>Private _Container as Container(Of BaseClass)\n</code></pre>\n\n<p>Also, ArrayList is not a Generic class; don't you mean Inherits <strong><em>List</em></strong>(of T) ?</p>\n"
},
{
"answer_id": 157052,
"author": "Ian Horwill",
"author_id": 5816,
"author_profile": "https://Stackoverflow.com/users/5816",
"pm_score": 3,
"selected": true,
"text": "<p>Sorry haven't got time to expand on this right now, but I think <a href=\"http://rasor.wordpress.com/2008/08/19/cast-a-generic-list-c/\" rel=\"nofollow noreferrer\">this link</a> describes your underlying problem and a solution.</p>\n\n<p>(You might also find <a href=\"http://blogs.msdn.com/lucian/archive/2008/10/02/co-and-contra-variance-how-do-i-convert-a-list-of-apple-into-a-list-of-fruit.aspx\" rel=\"nofollow noreferrer\">this</a> interesting.)</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4770/"
]
| I have a class declared as follows:
```
Public MustInherit Container(Of T As {New, BaseClass}) Inherits ArrayList(Of T)
```
I have classes that inherit this class.
I have another class that I must pass instances in this method:
```
Public Sub LoadCollection(Of T As {BaseClass, New})(ByRef Collection As Container(Of T))
```
I need to store the passed in object in a global variable, but i can't simply declare it:
```
Private _Container as Collection(Of BaseClass)
```
What is the syntax to declare this object? | Sorry haven't got time to expand on this right now, but I think [this link](http://rasor.wordpress.com/2008/08/19/cast-a-generic-list-c/) describes your underlying problem and a solution.
(You might also find [this](http://blogs.msdn.com/lucian/archive/2008/10/02/co-and-contra-variance-how-do-i-convert-a-list-of-apple-into-a-list-of-fruit.aspx) interesting.) |
134,731 | <p>Whilst refactoring some code I came across some getter methods that returns a std::string. Something like this for example:</p>
<pre><code>class foo
{
private:
std::string name_;
public:
std::string name()
{
return name_;
}
};
</code></pre>
<p>Surely the getter would be better returning a <code>const std::string&</code>? The current method is returning a copy which isn't as efficient. Would returning a const reference instead cause any problems?</p>
| [
{
"answer_id": 134743,
"author": "Kristopher Johnson",
"author_id": 1175,
"author_profile": "https://Stackoverflow.com/users/1175",
"pm_score": 2,
"selected": false,
"text": "<p>I'd change it to return const std::string&. The caller will probably make a copy of the result anyway if you don't change all the calling code, but it won't introduce any problems.</p>\n\n<p>One potential wrinkle arises if you have multiple threads calling name(). If you return a reference, but then later change the underlying value, then the caller's value will change. But the existing code doesn't look thread-safe anyway.</p>\n\n<p>Take a look at Dima's answer for a related potential-but-unlikely problem.</p>\n"
},
{
"answer_id": 134749,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>Depends what you need to do. Maybe you want to all the caller to change the returned value without changing the class. If you return the const reference that won't fly. </p>\n\n<p>Of course, the next argument is that the caller could then make their own copy. But if you know how the function will be used and know that happens anyway, then maybe doing this saves you a step later in code.</p>\n"
},
{
"answer_id": 134761,
"author": "Airsource Ltd",
"author_id": 18017,
"author_profile": "https://Stackoverflow.com/users/18017",
"pm_score": 2,
"selected": false,
"text": "<p>It is conceivable that you could break something if the caller really wanted a copy, because they were about to alter the original and wanted to preserve a copy of it. However it is far more likely that it should, indeed, just be returning a const reference.</p>\n\n<p>The easiest thing to do is try it and then test it to see if it still works, provided that you have some sort of test you can run. If not, I'd focus on writing the test first, before continuing with refactoring.</p>\n"
},
{
"answer_id": 134777,
"author": "Dima",
"author_id": 13313,
"author_profile": "https://Stackoverflow.com/users/13313",
"pm_score": 7,
"selected": true,
"text": "<p>The only way this can cause a problem is if the caller stores the reference, rather than copy the string, and tries to use it after the object is destroyed. Like this:</p>\n<pre><code>foo *pFoo = new foo;\nconst std::string &myName = pFoo->getName();\ndelete pFoo;\ncout << myName; // error! dangling reference\n</code></pre>\n<p>However, since your existing function returns a copy, then you would\nnot break any of the existing code.</p>\n<p><strong>Edit:</strong> Modern C++ (i. e. C++11 and up) supports <a href=\"https://en.wikipedia.org/wiki/Copy_elision\" rel=\"nofollow noreferrer\">Return Value Optimization</a>, so returning things by value is no longer frowned upon. One should still be mindful of returning extremely large objects by value, but in most cases it should be ok.</p>\n"
},
{
"answer_id": 134789,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 1,
"selected": false,
"text": "<p>Odds are pretty good that typical usage of that function won't break if you change to a const reference.</p>\n\n<p>If all of the code calling that function is under your control, just make the change and see if the compiler complains.</p>\n"
},
{
"answer_id": 135108,
"author": "Brett Hall",
"author_id": 22310,
"author_profile": "https://Stackoverflow.com/users/22310",
"pm_score": 0,
"selected": false,
"text": "<p>I normally return const& unless I can't. QBziZ gives an example of where this is the case. Of course QBziZ also claims that std::string has copy-on-write semantics which is rarely true today since COW involves a lot of overhead in a multi-threaded environment. By returning const & you put the onus on the caller to do the right thing with the string on their end. But since you are dealing with code that is already in use you probably shouldn't change it unless profiling shows that the copying of this string is causing massive performance problems. Then if you decide to change it you will need to test thouroughly to make sure you didn't break anything. Hopefully the other developers you work with don't do sketchy stuff like in Dima's answer.</p>\n"
},
{
"answer_id": 135242,
"author": "christopher_f",
"author_id": 9224,
"author_profile": "https://Stackoverflow.com/users/9224",
"pm_score": 1,
"selected": false,
"text": "<p>Does it matter? As soon as you use a modern optimizing compiler, functions that return by value will not involve a copy unless they are semantically required to.</p>\n\n<p>See <a href=\"http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.9\" rel=\"nofollow noreferrer\">the C++ lite FAQ</a> on this.</p>\n"
},
{
"answer_id": 136053,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 4,
"selected": false,
"text": "<p>One problem for the const reference return would be if the user coded something like:</p>\n\n<pre><code>const std::string & str = myObject.getSomeString() ;\n</code></pre>\n\n<p>With a <code>std::string</code> return, the temporary object would remain alive and attached to str until str goes out of scope.</p>\n\n<p>But what happens with a <code>const std::string &</code>? My guess is that we would have a const reference to an object that could die when its parent object deallocates it:</p>\n\n<pre><code>MyObject * myObject = new MyObject(\"My String\") ;\nconst std::string & str = myObject->getSomeString() ;\ndelete myObject ;\n// Use str... which references a destroyed object.\n</code></pre>\n\n<p>So my preference goes to the const reference return (because, anyway, I'm just more confortable with sending a reference than hoping the compiler will optimize the extra temporary), as long as the following contract is respected: \"if you want it beyond my object's existence, they copy it before my object's destruction\"</p>\n"
},
{
"answer_id": 136301,
"author": "rlerallut",
"author_id": 20055,
"author_profile": "https://Stackoverflow.com/users/20055",
"pm_score": 3,
"selected": false,
"text": "<p>Some implementations of std::string share memory with copy-on-write semantics, so return-by-value can be almost as efficient as return-by-reference <em>and</em> you don't have to worry about the lifetime issues (the runtime does it for you). </p>\n\n<p>If you're worried about performance, then <em>benchmark it</em> (<= can't stress that enough) !!! Try both approaches and measure the gain (or lack thereof). If one is better and you really care, then use it. If not, then prefer by-value for the protection it offers agains lifetime issues mentioned by other people.</p>\n\n<p>You know what they say about making assumptions...</p>\n"
},
{
"answer_id": 701398,
"author": "Frank",
"author_id": 60628,
"author_profile": "https://Stackoverflow.com/users/60628",
"pm_score": 3,
"selected": false,
"text": "<p>Okay, so the <strong>differences</strong> between returning a copy and returning the reference are:</p>\n\n<ul>\n<li><p><strong>Performance</strong>: Returning the reference may or may not be faster; it depends on how <code>std::string</code> is implemented by your compiler implementation (as others have pointed out). But even if you return the reference the assignment after the function call usually involves a copy, as in <code>std::string name = obj.name();</code></p></li>\n<li><p><strong>Safety</strong>: Returning the reference may or may not cause problems (dangling reference). If the users of your function don't know what they are doing, storing the reference as reference and using it after the providing object goes out of scope then there's a problem.</p></li>\n</ul>\n\n<p>If you want it <strong>fast and safe</strong> use <strong>boost::shared_ptr</strong>. Your object can internally store the string as <code>shared_ptr</code> and return a <code>shared_ptr</code>. That way, there will be no copying of the object going and and it's always safe (unless your users pull out the raw pointer with <code>get()</code> and do stuff with it after your object goes out of scope).</p>\n"
},
{
"answer_id": 5095204,
"author": "Ogre Psalm33",
"author_id": 13140,
"author_profile": "https://Stackoverflow.com/users/13140",
"pm_score": 5,
"selected": false,
"text": "<p>Actually, another issue <strong>specifically</strong> with returning a string <em>not</em> by reference, is the fact that <code>std::string</code> provides access via pointer to an internal <code>const char*</code> via the <a href=\"http://www.cplusplus.com/reference/string/string/c_str/\" rel=\"noreferrer\">c_str()</a> method. This has caused me many hours of debugging headache. For instance, let's say I want to get the name from foo, and pass it to JNI to be used to construct a jstring to pass into Java later on, and that <code>name()</code> is returning a copy and not a reference. I might write something like this:</p>\n\n<pre><code>foo myFoo = getFoo(); // Get the foo from somewhere.\nconst char* fooCName = foo.name().c_str(); // Woops! foo.name() creates a temporary that's destructed as soon as this line executes!\njniEnv->NewStringUTF(fooCName); // No good, fooCName was released when the temporary was deleted.\n</code></pre>\n\n<p>If your caller is going to be doing this kind of thing, it might be better to use some type of smart pointer, or a const reference, or at the very least have a nasty warning comment header over your foo.name() method. I mention JNI because former Java coders might be particularly vulnerable to this type of method chaining that may seem otherwise harmless.</p>\n"
},
{
"answer_id": 42898222,
"author": "Xavier Nguyen-Thai",
"author_id": 7725818,
"author_profile": "https://Stackoverflow.com/users/7725818",
"pm_score": -1,
"selected": false,
"text": "<p>Returning a reference to a member exposes the implementation of the class.\nThat's could prevent to change the class. May be usefull for private or protected methods incase the optimization is needed.\n<a href=\"https://stackoverflow.com/questions/20091046/what-should-a-c-getter-return\">What should a C++ getter return</a></p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
]
| Whilst refactoring some code I came across some getter methods that returns a std::string. Something like this for example:
```
class foo
{
private:
std::string name_;
public:
std::string name()
{
return name_;
}
};
```
Surely the getter would be better returning a `const std::string&`? The current method is returning a copy which isn't as efficient. Would returning a const reference instead cause any problems? | The only way this can cause a problem is if the caller stores the reference, rather than copy the string, and tries to use it after the object is destroyed. Like this:
```
foo *pFoo = new foo;
const std::string &myName = pFoo->getName();
delete pFoo;
cout << myName; // error! dangling reference
```
However, since your existing function returns a copy, then you would
not break any of the existing code.
**Edit:** Modern C++ (i. e. C++11 and up) supports [Return Value Optimization](https://en.wikipedia.org/wiki/Copy_elision), so returning things by value is no longer frowned upon. One should still be mindful of returning extremely large objects by value, but in most cases it should be ok. |
134,742 | <p>I have a data table with a variable number of columns and a data scroller. How can I enable server side sorting? I prefer that it be fired by the user clicking the column header.</p>
<pre><code><rich:datascroller for="instanceList" actionListener="#{pageDataModel.pageChange}"/>
<rich:dataTable id="instanceList" rows="10" value="#{pageDataModel}"
var="fieldValues" rowKeyVar="rowKey">
<rich:columns value="#{pageDataModel.columnNames}" var="column" index="idx">
<f:facet name="header">
<h:outputText value="#{column}"/>
</f:facet>
<h:outputText value="#{classFieldValues[idx]}" />
</rich:columns>
</rich:dataTable>
</code></pre>
<p>I already have a method on the bean for executing the sort.</p>
<pre><code>public void sort(int column)
</code></pre>
| [
{
"answer_id": 135958,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 4,
"selected": true,
"text": "<p>I ended up doing it manually. I adding a support tag to the header text tag, like so.</p>\n\n<pre><code><h:outputText value=\"#{column}\">\n <a4j:support event=\"onclick\" action=\"#{pageDataModel.sort(idx)}\"\n eventsQueue=\"instancesQueue\"\n reRender=\"instanceList,instanceListScroller\"/>\n</h:outputText>\n</code></pre>\n\n<p>To get the ascending/descending arrows, I added a css class.</p>\n\n<pre><code><h:outputText value=\"#{column}\" styleClass=\"#{pageDataModel.getOrderClass(idx)}\" >\n <a4j:support event=\"onclick\" action=\"#{pageDataModel.sort(idx)}\"\n eventsQueue=\"instancesQueue\"\n reRender=\"instanceList,instanceListScroller\"/>\n</h:outputText>\n</code></pre>\n"
},
{
"answer_id": 226018,
"author": "Patrick",
"author_id": 30390,
"author_profile": "https://Stackoverflow.com/users/30390",
"pm_score": 0,
"selected": false,
"text": "<p>Have a look at the \"sortBy\" property of \"rich:columns\", maybe that's what you're looking for.\n<a href=\"http://www.jboss.org/file-access/default/members/jbossrichfaces/freezone/docs/devguide/en/html_single/index.html#columns\" rel=\"nofollow noreferrer\">Richfaces Reference</a></p>\n"
},
{
"answer_id": 289616,
"author": "Shervin Asgari",
"author_id": 37298,
"author_profile": "https://Stackoverflow.com/users/37298",
"pm_score": 0,
"selected": false,
"text": "<p>Cant you just use Collection.sort() when you retrieve the List? </p>\n"
},
{
"answer_id": 2835046,
"author": "Philipp",
"author_id": 341340,
"author_profile": "https://Stackoverflow.com/users/341340",
"pm_score": 1,
"selected": false,
"text": "<p>Your datamodel needs to implement \"Modifiable\" interface.</p>\n\n<p>The datatable will call it's <code>modify()</code> method to do serverside \nsorting and filtering.</p>\n"
},
{
"answer_id": 3256782,
"author": "Marco",
"author_id": 376390,
"author_profile": "https://Stackoverflow.com/users/376390",
"pm_score": 1,
"selected": false,
"text": "<p>There is a fairly elegant solution to this solution here: </p>\n\n<p><a href=\"http://livedemo.exadel.com/richfaces-demo/richfaces/sortingFeature.jsf?tab=ex-usage\" rel=\"nofollow noreferrer\">http://livedemo.exadel.com/richfaces-demo/richfaces/sortingFeature.jsf?tab=ex-usage</a></p>\n\n<p>This demo avoids using the tag. </p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4893/"
]
| I have a data table with a variable number of columns and a data scroller. How can I enable server side sorting? I prefer that it be fired by the user clicking the column header.
```
<rich:datascroller for="instanceList" actionListener="#{pageDataModel.pageChange}"/>
<rich:dataTable id="instanceList" rows="10" value="#{pageDataModel}"
var="fieldValues" rowKeyVar="rowKey">
<rich:columns value="#{pageDataModel.columnNames}" var="column" index="idx">
<f:facet name="header">
<h:outputText value="#{column}"/>
</f:facet>
<h:outputText value="#{classFieldValues[idx]}" />
</rich:columns>
</rich:dataTable>
```
I already have a method on the bean for executing the sort.
```
public void sort(int column)
``` | I ended up doing it manually. I adding a support tag to the header text tag, like so.
```
<h:outputText value="#{column}">
<a4j:support event="onclick" action="#{pageDataModel.sort(idx)}"
eventsQueue="instancesQueue"
reRender="instanceList,instanceListScroller"/>
</h:outputText>
```
To get the ascending/descending arrows, I added a css class.
```
<h:outputText value="#{column}" styleClass="#{pageDataModel.getOrderClass(idx)}" >
<a4j:support event="onclick" action="#{pageDataModel.sort(idx)}"
eventsQueue="instancesQueue"
reRender="instanceList,instanceListScroller"/>
</h:outputText>
``` |
134,796 | <p>I know I can compile individual source files, but sometimes -- say, when editing a header file used by many <code>.cpp</code> files -- multiple source files need to be recompiled. That's what Build is for.</p>
<p>Default behavior of the "Build" command in VC9 (Visual C++ 2008) is to attempt to compile all files that need it. Sometimes this just results in many failed compiles. I usually just watch for errors and hit ctrl-break to stop the build manually.</p>
<p>Is there a way to configure it such the build stops at the <strong>very first compile error</strong> (not the first failed project build) automatically?</p>
| [
{
"answer_id": 134929,
"author": "Martin Beckett",
"author_id": 10897,
"author_profile": "https://Stackoverflow.com/users/10897",
"pm_score": 1,
"selected": false,
"text": "<p>There is <a href=\"http://old.stevenharman.net/blog/archive/2008/01/17/visual-studio-tip-kill-that-build.aspx\" rel=\"nofollow noreferrer\">this post</a> - not sure if it stops the build at the first error or the first failed project in a solution.</p>\n\n<p>Ctrl-break will also stop it manually.</p>\n\n<p>Now if there was some way to stop it spending 10mins rebuilding intelisense after a build failed!</p>\n"
},
{
"answer_id": 194748,
"author": "jmatthias",
"author_id": 2768,
"author_profile": "https://Stackoverflow.com/users/2768",
"pm_score": 4,
"selected": false,
"text": "<p>This can be done by adding a macro that is run in response to the event OnBuildProjConfigDone.</p>\n\n<p>The macro is as follows:</p>\n\n<pre><code>Private Sub BuildEvents_OnBuildProjConfigDone(ByVal Project As String, ByVal ProjectConfig As String, ByVal Platform As String, ByVal SolutionConfig As String, ByVal Success As Boolean) Handles BuildEvents.OnBuildProjConfigDone\n\n If Success = False Then\n DTE.ExecuteCommand(\"Build.Cancel\")\n End If\n\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 1085245,
"author": "Eric",
"author_id": 119301,
"author_profile": "https://Stackoverflow.com/users/119301",
"pm_score": 6,
"selected": true,
"text": "<p>I came up with a better macro guys. It stops immediately after the first error/s (soon as build window is updated).</p>\n\n<p>Visual Studio -> Tools -> Macros -> Macro IDE... (or ALT+F11)</p>\n\n<pre><code>Private Sub OutputWindowEvents_OnPaneUpdated(ByVal pPane As OutputWindowPane) Handles OutputWindowEvents.PaneUpdated\n If Not (pPane.Name = \"Build\") Then Exit Sub\n\n pPane.TextDocument.Selection.SelectAll()\n Dim Context As String = pPane.TextDocument.Selection.Text\n pPane.TextDocument.Selection.EndOfDocument()\n\n Dim found As Integer = Context.IndexOf(\": error \")\n\n If found > 0 Then\n DTE.ExecuteCommand(\"Build.Cancel\")\n End If\n\nEnd Sub \n</code></pre>\n\n<p>Hope it works out for you guys.</p>\n"
},
{
"answer_id": 4757629,
"author": "Anders Glent Buch",
"author_id": 584300,
"author_profile": "https://Stackoverflow.com/users/584300",
"pm_score": 3,
"selected": false,
"text": "<p>Yeah, this works fine on MSVC 2005-2010:</p>\n\n<pre><code>Public Module EnvironmentEvents\n Private Sub OutputWindowEvents_OnPaneUpdated(ByVal pPane As OutputWindowPane) Handles OutputWindowEvents.PaneUpdated\n If Not (pPane.Name = \"Build\") Then Exit Sub\n\n Dim foundError As Boolean = pPane.TextDocument.StartPoint.CreateEditPoint().FindPattern(\": error\")\n Dim foundFatal As Boolean = pPane.TextDocument.StartPoint.CreateEditPoint().FindPattern(\": fatal error\")\n\n If foundError Or foundFatal Then\n DTE.ExecuteCommand(\"Build.Cancel\")\n End If\n End Sub\nEnd Module\n</code></pre>\n"
},
{
"answer_id": 20991350,
"author": "RKG",
"author_id": 2396122,
"author_profile": "https://Stackoverflow.com/users/2396122",
"pm_score": 2,
"selected": false,
"text": "<p>I know the question was for VS 2008, but I stumbled across it when searching for the same answer for VS 2012. Since macros are no longer supported in 2012, macro solutions won't work anymore.</p>\n\n<p>You can download an extension that apparently works in VS 2010 and 2012 <a href=\"http://visualstudiogallery.msdn.microsoft.com/92a14c1d-82ce-409d-8e16-3f2aac0a00ea\" rel=\"nofollow noreferrer\">here</a>. I can confirm that it works well in VS 2012.</p>\n\n<p>The original link to the extension was given in <a href=\"https://stackoverflow.com/a/3042159/2396122\">this</a> response.</p>\n"
},
{
"answer_id": 32328648,
"author": "QuantumBlack",
"author_id": 1275065,
"author_profile": "https://Stackoverflow.com/users/1275065",
"pm_score": 1,
"selected": false,
"text": "<p>You can also download <a href=\"https://visualstudiogallery.msdn.microsoft.com/91aaa139-5d3c-43a7-b39f-369196a84fa5\" rel=\"nofollow\">this</a> extension, seems to work for every version of Visual Studio</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10559/"
]
| I know I can compile individual source files, but sometimes -- say, when editing a header file used by many `.cpp` files -- multiple source files need to be recompiled. That's what Build is for.
Default behavior of the "Build" command in VC9 (Visual C++ 2008) is to attempt to compile all files that need it. Sometimes this just results in many failed compiles. I usually just watch for errors and hit ctrl-break to stop the build manually.
Is there a way to configure it such the build stops at the **very first compile error** (not the first failed project build) automatically? | I came up with a better macro guys. It stops immediately after the first error/s (soon as build window is updated).
Visual Studio -> Tools -> Macros -> Macro IDE... (or ALT+F11)
```
Private Sub OutputWindowEvents_OnPaneUpdated(ByVal pPane As OutputWindowPane) Handles OutputWindowEvents.PaneUpdated
If Not (pPane.Name = "Build") Then Exit Sub
pPane.TextDocument.Selection.SelectAll()
Dim Context As String = pPane.TextDocument.Selection.Text
pPane.TextDocument.Selection.EndOfDocument()
Dim found As Integer = Context.IndexOf(": error ")
If found > 0 Then
DTE.ExecuteCommand("Build.Cancel")
End If
End Sub
```
Hope it works out for you guys. |
134,815 | <p>Is there a way to listen for a javascript function to exit? A trigger that could be setup when a function has completed?</p>
<p>I am attempting to use a user interface obfuscation technique (BlockUI) while an AJAX object is retrieving data from the DB, but the function doesn't necessarily execute last, even if you put it at the end of the function call. </p>
<p>Example:</p>
<pre><code>function doStuff() {
blockUI();
ajaxCall();
unblockUI();
};
</code></pre>
<p>Is there a way for doStuff to listen for ajaxCall to complete, before firing the unBlockUI? As it is, it processes the function linearly, calling each object in order, then a separate thread is spawned to complete each one. So, though my AJAX call might take 10-15 seconds to complete, I am only blocking the user for just a split-second, due to the linear execution of the function.</p>
<p>There are less elegant ways around this...putting a loop to end only when a return value set by the AJAX function is set to true, or something of that nature. But that seems unnecessarily complicated and inefficient.</p>
| [
{
"answer_id": 134828,
"author": "jgreep",
"author_id": 16345,
"author_profile": "https://Stackoverflow.com/users/16345",
"pm_score": 1,
"selected": false,
"text": "<p>Your AJAX call should specify a callback function. You can call the unblockUI from within the callback.</p>\n\n<p><a href=\"http://www.modernmethod.com/sajax/\" rel=\"nofollow noreferrer\">SAJAX</a> is a simple AJAX library that has more help on how to do AJAX calls.</p>\n\n<p>There's also <a href=\"https://stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-req\">another post</a> that describes what you're looking for.</p>\n"
},
{
"answer_id": 134830,
"author": "Steve g",
"author_id": 12092,
"author_profile": "https://Stackoverflow.com/users/12092",
"pm_score": 0,
"selected": false,
"text": "<p>You can do a synchronous xhr. This would cause the entire UI block for the duration of the call (no matter how long it might take).</p>\n"
},
{
"answer_id": 134839,
"author": "Adam Tuttle",
"author_id": 751,
"author_profile": "https://Stackoverflow.com/users/751",
"pm_score": 3,
"selected": true,
"text": "<p>However you're accomplishing your Ajax routines, what you need is a \"callback\" function that will run once it's complete:</p>\n\n<pre><code>function ajaxCall(callback){\n //do ajax stuff...\n callback();\n}\n</code></pre>\n\n<p>Then:</p>\n\n<pre><code>function doStuff(){\n blockUI();\n ajaxCall(unblockUI);\n}\n</code></pre>\n"
},
{
"answer_id": 134857,
"author": "artificialidiot",
"author_id": 7988,
"author_profile": "https://Stackoverflow.com/users/7988",
"pm_score": 0,
"selected": false,
"text": "<p>You need to redesign your program flow to be compatible with asynchronus flow, like specifying a callback function to be called after the response is processed. Check out how Prototype or JQuery or ... accomplishes this.</p>\n"
},
{
"answer_id": 136995,
"author": "Ahmad",
"author_id": 22449,
"author_profile": "https://Stackoverflow.com/users/22449",
"pm_score": 0,
"selected": false,
"text": "<p>The answer is simple, you have to call unblockUI() when your ajax request returns the result, using jQuery you can do it like this:</p>\n\n<pre><code>function doStuff(){\n\n blockUI();\n\n jQuery.ajax({\n url: \"example.com\",\n type: \"POST\", //you can use GET or POST\n success: function(){\n\n unblockUI();\n }\n });\n}\n</code></pre>\n"
},
{
"answer_id": 137205,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>It sounds to me that you want the user to wait while info is being fetched from the db. What I do when I make an Ajax call for some info from the database is to display an animated gif that says \"getting it...\" - it flashes continually until the info is retrieved and displayed in the webpage. When the info is displayed, the animated gif is turned off/hidden and the focus is moved to the new info being displayed. The animated gif lets the user know that something is happening.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5405/"
]
| Is there a way to listen for a javascript function to exit? A trigger that could be setup when a function has completed?
I am attempting to use a user interface obfuscation technique (BlockUI) while an AJAX object is retrieving data from the DB, but the function doesn't necessarily execute last, even if you put it at the end of the function call.
Example:
```
function doStuff() {
blockUI();
ajaxCall();
unblockUI();
};
```
Is there a way for doStuff to listen for ajaxCall to complete, before firing the unBlockUI? As it is, it processes the function linearly, calling each object in order, then a separate thread is spawned to complete each one. So, though my AJAX call might take 10-15 seconds to complete, I am only blocking the user for just a split-second, due to the linear execution of the function.
There are less elegant ways around this...putting a loop to end only when a return value set by the AJAX function is set to true, or something of that nature. But that seems unnecessarily complicated and inefficient. | However you're accomplishing your Ajax routines, what you need is a "callback" function that will run once it's complete:
```
function ajaxCall(callback){
//do ajax stuff...
callback();
}
```
Then:
```
function doStuff(){
blockUI();
ajaxCall(unblockUI);
}
``` |
134,833 | <p>I have an <em>index.php</em> file which has to process many different file types. How do I guess the filetype based on the <code>REQUEST_URI</code>?</p>
<p>If I request <code>http://site/image.jpg</code>, and all requests redirect through <em>index.php</em>, which looks like this</p>
<pre><code><?php
include('/www/site'.$_SERVER['REQUEST_URI']);
?>
</code></pre>
<p>How would I make that work correctly?</p>
<p>Should I test based on the extension of the file requested, or is there a way to get the filetype?</p>
| [
{
"answer_id": 134893,
"author": "leek",
"author_id": 3765,
"author_profile": "https://Stackoverflow.com/users/3765",
"pm_score": 7,
"selected": true,
"text": "<p>If you are sure you're only ever working with images, you can check out the <a href=\"http://us3.php.net/manual/en/function.exif-imagetype.php\" rel=\"nofollow noreferrer\">exif_imagetype()</a> PHP function, which attempts to return the image MIME type.</p>\n<p>If you don't mind external dependencies, you can also check out the excellent <a href=\"http://getid3.sourceforge.net\" rel=\"nofollow noreferrer\">getID3</a> library which can determine the MIME type of many different file types.</p>\n<p>Lastly, you can check out the <a href=\"http://us3.php.net/manual/en/function.mime-content-type.php\" rel=\"nofollow noreferrer\">mime_content_type()</a> function - but it has been deprecated for the <a href=\"http://us3.php.net/manual/en/ref.fileinfo.php\" rel=\"nofollow noreferrer\">Fileinfo</a> PECL extension.</p>\n"
},
{
"answer_id": 134900,
"author": "enobrev",
"author_id": 14651,
"author_profile": "https://Stackoverflow.com/users/14651",
"pm_score": 0,
"selected": false,
"text": "<p>I haven't used it, but there's a <a href=\"http://pecl.php.net/package/Fileinfo\" rel=\"nofollow noreferrer\">PECL extension</a> for getting a file's MIME type. The official documentation for it is in <a href=\"http://www.php.net/manual/en/ref.fileinfo.php\" rel=\"nofollow noreferrer\">the manual</a>.</p>\n<p>Depending on your purpose, a file extension can be ok, but it's not incredibly reliable since it's so easily changed.</p>\n"
},
{
"answer_id": 134907,
"author": "Devon",
"author_id": 13850,
"author_profile": "https://Stackoverflow.com/users/13850",
"pm_score": 1,
"selected": false,
"text": "<p>According to the PHP manual, the <a href=\"http://us2.php.net/manual/en/function.finfo-file.php\" rel=\"nofollow noreferrer\">finfo-file</a> function is best way to do this. However, you will need to install the <a href=\"http://us2.php.net/manual/en/ref.fileinfo.php\" rel=\"nofollow noreferrer\">FileInfo</a> PECL extension.</p>\n<p>If the extension is not an option, you can use the outdated <a href=\"http://us2.php.net/mime_content_type\" rel=\"nofollow noreferrer\">mime_content_type</a> function.</p>\n"
},
{
"answer_id": 134916,
"author": "phatduckk",
"author_id": 3896,
"author_profile": "https://Stackoverflow.com/users/3896",
"pm_score": 0,
"selected": false,
"text": "<p>If you're only dealing with images, you can use the <code>[getimagesize()][1]</code> function which contains all sorts of information about the image, including the type.</p>\n<p>A more general approach would be to use the FileInfo extension from <a href=\"http://us.php.net/manual/en/ref.fileinfo.php\" rel=\"nofollow noreferrer\">PECL</a>.</p>\n<p>Some people have serious complaints about that extension... so if you run into serious issues or cannot install the extension for some reason you might want to check out the deprecated function <a href=\"http://us.php.net/manual/en/function.mime-content-type.php\" rel=\"nofollow noreferrer\"><code>mime_content_type()</code></a>.</p>\n"
},
{
"answer_id": 134930,
"author": "Eric_WVGG",
"author_id": 82944,
"author_profile": "https://Stackoverflow.com/users/82944",
"pm_score": 5,
"selected": false,
"text": "<p><em>mime_content_type()</em> is deprecated, so you won't be able to count on it working in the future. There is a "fileinfo" PECL extension, but I haven't heard good things about it.</p>\n<p>If you are running on a Unix-like server, you can do the following, which has worked fine for me:</p>\n<pre><code>$file = escapeshellarg($filename);\n$mime = shell_exec("file -bi " . $file);\n$filename should probably include the absolute path.\n</code></pre>\n"
},
{
"answer_id": 12191939,
"author": "Ale",
"author_id": 1593459,
"author_profile": "https://Stackoverflow.com/users/1593459",
"pm_score": 4,
"selected": false,
"text": "<pre><code>function get_mime($file) {\n if (function_exists("finfo_file")) {\n $finfo = finfo_open(FILEINFO_MIME_TYPE); // Return MIME type a la the 'mimetype' extension\n $mime = finfo_file($finfo, $file);\n finfo_close($finfo);\n return $mime;\n } else if (function_exists("mime_content_type")) {\n return mime_content_type($file);\n } else if (!stristr(ini_get("disable_functions"), "shell_exec")) {\n // http://stackoverflow.com/a/134930/1593459\n $file = escapeshellarg($file);\n $mime = shell_exec("file -bi " . $file);\n return $mime;\n } else {\n return false;\n }\n}\n</code></pre>\n<p>For me, nothing of this works—<code>mime_content_type</code> is deprecated, <code>finfo</code> is not installed, and <code>shell_exec</code> is not allowed.</p>\n"
},
{
"answer_id": 12387464,
"author": "vizzy",
"author_id": 1665635,
"author_profile": "https://Stackoverflow.com/users/1665635",
"pm_score": -1,
"selected": false,
"text": "<p>I got very good results using a user function from\n<a href=\"http://php.net/manual/de/function.mime-content-type.php\" rel=\"nofollow noreferrer\">http://php.net/manual/de/function.mime-content-type.php</a>\n@''john dot howard at prismmg dot com 26-Oct-2009 03:43''</p>\n<pre><code>function get_mime_type($filename, $mimePath = '../etc') { ...\n</code></pre>\n<p>which doesn’t use <em>finfo</em>, <em>exec</em> or a deprecated function.</p>\n<p>It works well also with remote resources!</p>\n"
},
{
"answer_id": 15256393,
"author": "Andrew",
"author_id": 560972,
"author_profile": "https://Stackoverflow.com/users/560972",
"pm_score": 3,
"selected": false,
"text": "<p>If you are working with <em>images</em> only and you need a MIME type (e.g., for headers), then this is the fastest and most direct answer:</p>\n<pre><code>$file = 'path/to/image.jpg';\n$image_mime = image_type_to_mime_type(exif_imagetype($file));\n</code></pre>\n<p>It will output true image MIME type even if you rename your image file.</p>\n"
},
{
"answer_id": 17984348,
"author": "Shane",
"author_id": 1042193,
"author_profile": "https://Stackoverflow.com/users/1042193",
"pm_score": 3,
"selected": false,
"text": "<p>I actually got fed up by the lack of <em>standard</em> MIME sniffing methods in PHP. Install fileinfo... Use deprecated functions... Oh, these work, but only for images! I got fed up of it, so I did some research and found the <a href=\"http://mimesniff.spec.whatwg.org/\" rel=\"nofollow noreferrer\">WHATWG MIME sniffing specification</a> - I believe this is still a draft specification though.</p>\n<p>Anyway, using this specification, I was able to implement a MIME sniffer in PHP. Performance is not an issue. In fact, on my humble machine, I was able to open and sniff thousands of files before PHP timed out.</p>\n<p>Here is the <a href=\"https://github.com/shanept/MimeSniffer/\" rel=\"nofollow noreferrer\">MimeReader class</a>.</p>\n<pre><code>require_once("MimeReader.php");\n\n$mime = new MimeReader(<YOUR FILE PATH>);\n$mime_type_string = $mime->getType(); // "image/jpeg", etc.\n</code></pre>\n"
},
{
"answer_id": 35110617,
"author": "David",
"author_id": 867903,
"author_profile": "https://Stackoverflow.com/users/867903",
"pm_score": 1,
"selected": false,
"text": "<p><code>mime_content_type()</code> appears to be the way to go, notwithstanding the previous comments saying it is deprecated. It is not -- or at least this incarnation of <code>mime_content_type()</code> is not deprecated, according to <a href=\"http://php.net/manual/en/function.mime-content-type.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/function.mime-content-type.php</a>. It is part of the FileInfo extension, but the PHP documentation now tells us it is enabled by default as of PHP 5.3.0.</p>\n"
},
{
"answer_id": 39131097,
"author": "Klemen Tusar",
"author_id": 1040452,
"author_profile": "https://Stackoverflow.com/users/1040452",
"pm_score": 0,
"selected": false,
"text": "<p>If you run Linux and have the extension you could simply read the MIME type from /etc/mime.types by making a hash array. You can then store that in memory and simply call the MIME by array key :)</p>\n\n<pre><code>/**\n * Helper function to extract all mime types from the default Linux /etc/mime.types\n */\nfunction get_mime_types() {\n $mime_types = array();\n if (\n file_exists('/etc/mime.types') &&\n ($fh = fopen('/etc/mime.types', 'r')) !== false\n ) {\n while (($line = fgets($fh)) !== false) {\n if (!trim($line) || substr($line, 0, 1) === '#') continue;\n $mime_type = preg_split('/\\t+/', rtrim($line));\n if (\n is_array($mime_type) &&\n isset($mime_type[0]) && $mime_type[0] &&\n isset($mime_type[1]) && $mime_type[1]\n ) {\n foreach (explode(' ', $mime_type[1]) as $ext) {\n $mime_types[$ext] = $mime_type[0];\n }\n }\n }\n fclose($fh);\n }\n return $mime_types;\n}\n</code></pre>\n"
},
{
"answer_id": 40004903,
"author": "jhaagsma",
"author_id": 2444435,
"author_profile": "https://Stackoverflow.com/users/2444435",
"pm_score": 1,
"selected": false,
"text": "<p>You can use finfo to accomplish this as of PHP 5.3:</p>\n\n<pre><code><?php\n$info = new finfo(FILEINFO_MIME_TYPE);\necho $info->file('myImage.jpg');\n// prints \"image/jpeg\"\n</code></pre>\n\n<p>The FILEINFO_MIME_TYPE flag is optional; without it you get a more verbose string for some files; (apparently some image types will return size and colour depth information). Using the FILEINFO_MIME flag returns the mime-type and encoding if available (e.g. image/png; charset=binary or text/x-php; charset=us-ascii). See <a href=\"https://www.inanimatt.com/php-files.html\" rel=\"nofollow\">this site</a> for more info.</p>\n"
},
{
"answer_id": 47522347,
"author": "Joshua",
"author_id": 6768138,
"author_profile": "https://Stackoverflow.com/users/6768138",
"pm_score": 0,
"selected": false,
"text": "<p>The MIME type of any file on your server can be gotten with this:</p>\n<pre><code><?php\n function get_mime($file_path){\n $finfo = new finfo(FILEINFO_MIME_TYPE);\n $type = $finfo->file(file_path);\n }\n\n $mime = get_mime('path/to/file.ext');\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/144/"
]
| I have an *index.php* file which has to process many different file types. How do I guess the filetype based on the `REQUEST_URI`?
If I request `http://site/image.jpg`, and all requests redirect through *index.php*, which looks like this
```
<?php
include('/www/site'.$_SERVER['REQUEST_URI']);
?>
```
How would I make that work correctly?
Should I test based on the extension of the file requested, or is there a way to get the filetype? | If you are sure you're only ever working with images, you can check out the [exif\_imagetype()](http://us3.php.net/manual/en/function.exif-imagetype.php) PHP function, which attempts to return the image MIME type.
If you don't mind external dependencies, you can also check out the excellent [getID3](http://getid3.sourceforge.net) library which can determine the MIME type of many different file types.
Lastly, you can check out the [mime\_content\_type()](http://us3.php.net/manual/en/function.mime-content-type.php) function - but it has been deprecated for the [Fileinfo](http://us3.php.net/manual/en/ref.fileinfo.php) PECL extension. |
134,834 | <p>This is really the first thing that I have written in python. I come from Java background. I don't want to just learn how to program java code with Python syntax. I want to learn how to program in a pythonic paradigm.</p>
<p>Could you guys please comment on how I can make the following code more pythonic?</p>
<pre><code>from math import sqrt
# recursively computes the factors of a number
def factors(num):
factorList = []
numroot = int(sqrt(num)) + 1
numleft = num
# brute force divide the number until you find a factor
for i in range(2, numroot):
if num % i == 0:
# if we found a factor, add it to the list and compute the remainder
factorList.append(i)
numleft = num / i
break
# if we didn't find a factor, get out of here!
if numleft == num:
factorList.append(num)
return factorList
# now recursively find the rest of the factors
restFactors = factors(numleft)
factorList.extend(restFactors)
return factorList
# grabs all of the twos in the list and puts them into 2 ^ x form
def transformFactorList(factorList):
num2s = 0
# remove all twos, counting them as we go
while 2 in factorList:
factorList.remove(2)
num2s += 1
# simply return the list with the 2's back in the right spot
if num2s == 0: return factorList
if num2s == 1:
factorList.insert(0, 2)
return factorList
factorList.insert(0, '2 ^ ' + str(num2s))
return factorList
print transformFactorList(factors(#some number))
</code></pre>
| [
{
"answer_id": 134946,
"author": "mbac32768",
"author_id": 18446,
"author_profile": "https://Stackoverflow.com/users/18446",
"pm_score": 2,
"selected": false,
"text": "<p>Here's what jumps out at me:</p>\n\n<pre><code>def transformFactorList(factorList):\n oldsize = len(factorList)\n factorList = [f for f in factorList if f != 2]\n num2s = oldsize - len(factorList)\n if num2s == 0:\n return []\n if num2s == 1:\n return [2]+factorList\n return ['2 ^ %s' % num2s] + [factorList]\n</code></pre>\n\n<p>The form <code>[f for f in factorList if f != 2]</code> is called a list-comprehension.</p>\n"
},
{
"answer_id": 134954,
"author": "Dan Udey",
"author_id": 21450,
"author_profile": "https://Stackoverflow.com/users/21450",
"pm_score": 3,
"selected": false,
"text": "<p>A few comments:</p>\n\n<ol>\n<li>I would replace <code>range()</code> with <code>xrange()</code>; when you call <code>range()</code>, it allocates the entire range all at once, whereas when you iterate over <code>xrange()</code>, it returns each result one at a time, saving memory.</li>\n<li>Don't put expressions after conditionals on the same line (<code>if num2s -- 0: return factorList</code>). It makes it harder to see at a glance what it's doing (that it's a block).</li>\n<li>Don't be afraid to use modules. The <code>[sympy][1]</code> module already has code to compute factors, which may simplify your code by eliminating most of it.</li>\n<li>Python's string formatting is simple and effective.</li>\n</ol>\n\n<p>For example:</p>\n\n<pre><code>factorList.insert(0, '2 ^ ' + str(num2s))\n</code></pre>\n\n<p>could be changed to </p>\n\n<pre><code>factorlist.insert(0, '2 ^ %s' % num2s)\n</code></pre>\n\n<p>All in all, I don't find your code to be extensively un-pythonic. Just make sure you want to use <a href=\"http://www.python.org/doc/2.2.3/whatsnew/node7.html\" rel=\"nofollow noreferrer\">floor division</a>, because that's what tends to happen by default with integer values. Otherwise, you'll need to fix up the division operator:</p>\n\n<pre><code>from __future__ import division\n</code></pre>\n\n<p>A sometimes-frustrating caveat of the language.</p>\n"
},
{
"answer_id": 135001,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 2,
"selected": false,
"text": "<pre><code>from itertools import takewhile\n\ndef transform_factor_list(factor_list):\n num_2s = len(list(takewhile(lambda e: e == 2, factor_list)))\n if num_2s > 1:\n factor_list[:num_2s] = [\"2 ^ %i\" % (num_2s, )]\n return factor_list\n</code></pre>\n\n<p>That's what I would make out of the second function. </p>\n\n<p>Most pythonic changes:</p>\n\n<ul>\n<li><a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a> compatible naming</li>\n<li>slicing (and assigning to slices)</li>\n<li>iterators</li>\n<li>string formatting</li>\n</ul>\n\n<p>The function assumes that the input is ordered, which is fulfilled by factors.</p>\n\n<p><strong>Edit</strong>: removed special cases for some lists, more compact this way</p>\n"
},
{
"answer_id": 135009,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 4,
"selected": false,
"text": "<p>Just use 'import math' and 'math.sqrt()' instead of 'from math import sqrt' and 'sqrt()'; you don't win anything by just importing 'sqrt', and code quickly gets unwieldy with too many from-imports. Also, things like reload() and mocking out for tests break a lot faster when you use from-import a lot.</p>\n\n<p>The divmod() function is a convenient way to perform both division and modulo. You can use for/else instead of the separate check on numleft. Your factors function is a natural candidate for a generator. xrange() was already mentioned in another answer. Here's it all done that way:</p>\n\n<pre><code>import math\n\n# recursively computes the factors of a number as a generator\ndef factors(num):\n numroot = int(math.sqrt(num)) + 1\n # brute force divide the number until you find a factor\n for i in xrange(2, numroot):\n divider, remainder = divmod(num, i)\n if not remainder:\n # if we found a factor, add it to the list and compute the\n # remainder\n yield i\n break\n else:\n # if we didn't find a factor, get out of here!\n yield num\n return\n # now recursively find the rest of the factors\n for factor in factors(divider):\n yield factor\n</code></pre>\n\n<p>Using a generator does mean you can only iterate over the result once; if you simply want a list (like you do in translateFactorsList) you will have to wrap the call to factors() in list().</p>\n"
},
{
"answer_id": 136657,
"author": "unmounted",
"author_id": 11596,
"author_profile": "https://Stackoverflow.com/users/11596",
"pm_score": 5,
"selected": false,
"text": "<p>There is an excellent primer by David Goodger called \"Code Like a Pythonista\" <a href=\"http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html\" rel=\"nofollow noreferrer\">here</a>. A couple of things from that text re naming (quoting):</p>\n\n<ul>\n<li><p><code>joined_lower</code> for functions, methods,\nattributes</p></li>\n<li><p><code>joined_lower</code> or ALL_CAPS for\nconstants</p></li>\n<li><p><code>StudlyCaps</code> for classes</p></li>\n<li><p><code>camelCase</code> only to conform to\npre-existing conventions</p></li>\n</ul>\n"
},
{
"answer_id": 136713,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 4,
"selected": false,
"text": "<p>One other thing you might want to look at is the docstring. For example, the comment for this function:</p>\n\n<pre><code># recursively computes the factors of a number\ndef factors(num):\n</code></pre>\n\n<p>Could be converted into this:</p>\n\n<pre><code>def factors(num):\n \"\"\" recursively computes the factors of a number\"\"\"\n</code></pre>\n\n<p>It's not really 100% necessary to do it this way, but it's a good habit to get into in case you ever start using something along the lines of pydoc.</p>\n\n<p>You can also do this:</p>\n\n<h3>docstring.py</h3>\n\n<pre><code>\"\"\"This is a docstring\"\"\"\n</code></pre>\n\n<h3>at the command line:</h3>\n\n<pre><code>>>> import docstring\n>>> help(docstring)\n</code></pre>\n\n<h3>results:</h3>\n\n<pre><code>Help on module docstring:\n\nNAME\n docstring - This is a docstring\n\nFILE\n /Users/jason/docstring.py\n</code></pre>\n"
},
{
"answer_id": 434498,
"author": "Nope",
"author_id": 41718,
"author_profile": "https://Stackoverflow.com/users/41718",
"pm_score": 2,
"selected": false,
"text": "<p>Don't be afraid of list comprehensions. Switching from Java to Python and discovering them was a good day.</p>\n\n<p>For the factors function, maybe something like this:</p>\n\n<pre><code>def factors(num):\n return [i for i in xrange(1, num+1) if num % i == 0]\n</code></pre>\n\n<p>Probably not the best code but it's short and easy to understand.</p>\n\n<p>Good luck with Python, it's a great language. </p>\n"
},
{
"answer_id": 434525,
"author": "Evan Fosmark",
"author_id": 49701,
"author_profile": "https://Stackoverflow.com/users/49701",
"pm_score": 2,
"selected": false,
"text": "<p>Since this post seems to be resurrected by Casey (lol), I'll add in my 2 cents.</p>\n\n<p>Go over everything in <strong><a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a></strong>. It helped me out substantially when I had code formatting issues.</p>\n"
},
{
"answer_id": 1160144,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>this is how I'd do this...</p>\n\n<pre><code>import itertools\nimport collections\n\ndef factorize(n):\n # ideally an iterator of prime numbers\n # this'll work though\n divisors = itertools.count(2)\n\n divisor = divisors.next()\n while True:\n if divisor**2 > n:\n yield n\n break\n\n a,b = divmod(n, divisor)\n\n if b == 0:\n yield divisor\n n = a\n else:\n divisor = divisors.next()\n\ndef compress(factors):\n summands = collections.defaultdict(lambda: 0)\n\n for factor in factors:\n summands[factor] += 1\n\n return [(base, summands[base]) for base in sorted(summands)]\n\ndef tostring(compressed):\n return ' * '.join(\"%d**%d\" % factor for factor in compressed)\n</code></pre>\n"
},
{
"answer_id": 2021548,
"author": "Beni Cherniavsky-Paskin",
"author_id": 239657,
"author_profile": "https://Stackoverflow.com/users/239657",
"pm_score": 2,
"selected": false,
"text": "<p>Based on chris's answer, slightly simplified:</p>\n\n<ul>\n<li>for instead of external while</li>\n<li>internal while to preserve ability to use same divisor repeatedly</li>\n<li>use itertools.groupby simplifies compress() by much</li>\n<li>fix a small bug in tostring()</li>\n</ul>\n\n<p>HTH:</p>\n\n<pre><code>import itertools\n\ndef factorize(n):\n # ideally an iterator of prime numbers\n # this'll work though\n divisors = itertools.count(2)\n\n for divisor in divisors:\n # This condition is very clever!\n # Note that `n` is decreasing, while `divisor` is increasing.\n # And we know that `n` is not divisible by anything smaller,\n # so this stops as soon as the remaining `n` is obviously prime.\n if divisor**2 > n:\n yield n\n break\n\n while n % divisor == 0:\n yield divisor\n n //= divisor\n\ndef compress(factors):\n for (factor, copies) in itertools.groupby(factors):\n # The second object yielded by groupby is a generator of equal factors.\n # Using list() to count its length.\n power = len(list(copies))\n yield (factor, power)\n\ndef tostring(compressed):\n return ' * '.join(\"%d**%d\" % (factor, power) for (factor, power) in compressed)\n\n# test\nassert tostring(compress(factorize(12))) == '2**2 * 3**1'\n</code></pre>\n"
},
{
"answer_id": 2021849,
"author": "fortran",
"author_id": 106979,
"author_profile": "https://Stackoverflow.com/users/106979",
"pm_score": 1,
"selected": false,
"text": "<p>Using recursion (where not necessary) is not pythonic. Python doesn't have tail recursion elimination and <em>flat is better than nested</em>.</p>\n\n<p>When in doubt, try <code>import this</code></p>\n\n<p><strong>update</strong>: by popular request, here goes the iterative factorization (sigh):</p>\n\n<pre><code>\"\"\"returns an iterator of tuples (factor, power) such that \nreduce(operator.mul, (factor**power for factor, power in factors(n))) == n \"\"\"\ndef factors(n):\n i = 2\n while n > 1:\n p = 0\n while n > 1 and n % i == 0:\n p += 1\n n /= i\n if p:\n yield (i, p)\n i += 1\n</code></pre>\n"
},
{
"answer_id": 2023313,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 2,
"selected": false,
"text": "<p>I'd use a list comprehension to get the twos out:</p>\n\n<pre><code>def transformFactorList(factorList):\n twos = [x for x in factorList if x == 2]\n rest = [x for x in factorList if x != 2]\n rest.insert(0, \"2 ^ %d\" % len(twos))\n return rest\n</code></pre>\n\n<p>Note that this will give you <code>2^0</code> and <code>2^1</code>, which your code didn't. What you're doing with the twos seems arbitraty (sometimes you get a string, sometimes a number, sometimes nothing), so I figured that would be fine. You can change that easily if you want:</p>\n\n<pre><code>def transformFactorList(factorList):\n twos = [x for x in factorList if x == 2]\n rest = [x for x in factorList if x != 2]\n if twos:\n rest.insert(0, 2 if len(twos)==1 else \"2 ^ %d\" % len(twos))\n return rest\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2598/"
]
| This is really the first thing that I have written in python. I come from Java background. I don't want to just learn how to program java code with Python syntax. I want to learn how to program in a pythonic paradigm.
Could you guys please comment on how I can make the following code more pythonic?
```
from math import sqrt
# recursively computes the factors of a number
def factors(num):
factorList = []
numroot = int(sqrt(num)) + 1
numleft = num
# brute force divide the number until you find a factor
for i in range(2, numroot):
if num % i == 0:
# if we found a factor, add it to the list and compute the remainder
factorList.append(i)
numleft = num / i
break
# if we didn't find a factor, get out of here!
if numleft == num:
factorList.append(num)
return factorList
# now recursively find the rest of the factors
restFactors = factors(numleft)
factorList.extend(restFactors)
return factorList
# grabs all of the twos in the list and puts them into 2 ^ x form
def transformFactorList(factorList):
num2s = 0
# remove all twos, counting them as we go
while 2 in factorList:
factorList.remove(2)
num2s += 1
# simply return the list with the 2's back in the right spot
if num2s == 0: return factorList
if num2s == 1:
factorList.insert(0, 2)
return factorList
factorList.insert(0, '2 ^ ' + str(num2s))
return factorList
print transformFactorList(factors(#some number))
``` | There is an excellent primer by David Goodger called "Code Like a Pythonista" [here](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html). A couple of things from that text re naming (quoting):
* `joined_lower` for functions, methods,
attributes
* `joined_lower` or ALL\_CAPS for
constants
* `StudlyCaps` for classes
* `camelCase` only to conform to
pre-existing conventions |
134,845 | <p>The following are two methods of building a link that has the sole purpose of running JavaScript code. Which is better, in terms of functionality, page load speed, validation purposes, etc.?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function myJsFunc() {
alert("myJsFunc");
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><a href="#" onclick="myJsFunc();">Run JavaScript Code</a></code></pre>
</div>
</div>
</p>
<p>or</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function myJsFunc() {
alert("myJsFunc");
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <a href="javascript:void(0)" onclick="myJsFunc();">Run JavaScript Code</a></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 134853,
"author": "Adam Tuttle",
"author_id": 751,
"author_profile": "https://Stackoverflow.com/users/751",
"pm_score": 8,
"selected": false,
"text": "<p><code>'#'</code> will take the user back to the top of the page, so I usually go with <code>void(0)</code>.</p>\n\n<p><code>javascript:;</code> also behaves like <code>javascript:void(0);</code></p>\n"
},
{
"answer_id": 134865,
"author": "Zach",
"author_id": 9128,
"author_profile": "https://Stackoverflow.com/users/9128",
"pm_score": 7,
"selected": false,
"text": "<p>The first one, ideally with a real link to follow in case the user has JavaScript disabled. Just make sure to return false to prevent the click event from firing if the JavaScript executes.</p>\n\n<pre><code><a href=\"#\" onclick=\"myJsFunc(); return false;\">Link</a>\n</code></pre>\n\n<p>If you use Angular2, this way works:</p>\n\n<p><code><a [routerLink]=\"\" (click)=\"passTheSalt()\">Click me</a></code>.</p>\n\n<p>See here <a href=\"https://stackoverflow.com/a/45465728/2803344\">https://stackoverflow.com/a/45465728/2803344</a></p>\n"
},
{
"answer_id": 134870,
"author": "nathaniel",
"author_id": 11947,
"author_profile": "https://Stackoverflow.com/users/11947",
"pm_score": 3,
"selected": false,
"text": "<p>Don't lose sight of the fact that your URL may be necessary -- onclick is fired before the reference is followed, so sometimes you will need to process something clientside before navigating off the page.</p>\n"
},
{
"answer_id": 134910,
"author": "Simon Forrest",
"author_id": 4733,
"author_profile": "https://Stackoverflow.com/users/4733",
"pm_score": 5,
"selected": false,
"text": "<p>Unless you're writing out the link using JavaScript (so that you know it's enabled in the browser), you should ideally be providing a proper link for people who are browsing with JavaScript disabled and then prevent the default action of the link in your onclick event handler. This way those with JavaScript enabled will run the function and those with JavaScript disabled will jump to an appropriate page (or location within the same page) rather than just clicking on the link and having nothing happen.</p>\n"
},
{
"answer_id": 134957,
"author": "Aaron Wagner",
"author_id": 3909,
"author_profile": "https://Stackoverflow.com/users/3909",
"pm_score": 10,
"selected": false,
"text": "<p>Neither. </p>\n\n<p>If you can have an actual URL that makes sense use that as the HREF. The onclick won't fire if someone middle-clicks on your link to open a new tab or if they have JavaScript disabled.</p>\n\n<p>If that is not possible, then you should at least inject the anchor tag into the document with JavaScript and the appropriate click event handlers. </p>\n\n<p>I realize this isn't always possible, but in my opinion it should be striven for in developing any public website.</p>\n\n<p>Check out <em><a href=\"http://en.wikipedia.org/wiki/Unobtrusive_JavaScript\" rel=\"noreferrer\">Unobtrusive JavaScript</a></em> and <em><a href=\"http://en.wikipedia.org/wiki/Progressive_enhancement\" rel=\"noreferrer\">Progressive enhancement</a></em> (both Wikipedia).</p>\n"
},
{
"answer_id": 135120,
"author": "Steve Paulo",
"author_id": 9414,
"author_profile": "https://Stackoverflow.com/users/9414",
"pm_score": 7,
"selected": false,
"text": "<p>Ideally you'd do this:</p>\n\n<pre><code><a href=\"javascriptlessDestination.html\" onclick=\"myJSFunc(); return false;\">Link text</a>\n</code></pre>\n\n<p>Or, even better, you'd have the default action link in the HTML, and you'd add the onclick event to the element unobtrusively via JavaScript after the DOM renders, thus ensuring that if JavaScript is not present/utilized you don't have useless event handlers riddling your code and potentially obfuscating (or at least distracting from) your actual content.</p>\n"
},
{
"answer_id": 135139,
"author": "mmacaulay",
"author_id": 22152,
"author_profile": "https://Stackoverflow.com/users/22152",
"pm_score": 4,
"selected": false,
"text": "<p>It's nice to have your site be accessible by users with JavaScript disabled, in which case the href points to a page that performs the same action as the JavaScript being executed. Otherwise I use \"<strong>#</strong>\" with a \"<code>return false;</code>\" to prevent the default action (scroll to top of the page) as others have mentioned.</p>\n\n<p>Googling for \"<code>javascript:void(0)</code>\" provides a lot of information on this topic. Some of them, like <a href=\"https://web.archive.org/web/20090210041609/http://blog.reindel.com/2006/08/11/a-hrefjavascriptvoid0-avoid-the-void/\" rel=\"noreferrer\">this one</a> mention reasons to <strong>NOT use void(0)</strong>.</p>\n"
},
{
"answer_id": 135200,
"author": "Peter",
"author_id": 8792,
"author_profile": "https://Stackoverflow.com/users/8792",
"pm_score": 3,
"selected": false,
"text": "<p>Ideally you should have a real URL as fallback for non-JavaScript users.</p>\n\n<p>If this doesn't make sense, use <code>#</code> as the <code>href</code> attribute. I don't like using the <code>onclick</code> attribute since it embeds JavaScript directly in the HTML. A better idea would be to use an external JS file and then add the event handler to that link. You can then prevent the default event so that the URL doesn't change to append the <code>#</code> after the user clicks it.</p>\n"
},
{
"answer_id": 135248,
"author": "fijter",
"author_id": 3215,
"author_profile": "https://Stackoverflow.com/users/3215",
"pm_score": 7,
"selected": false,
"text": "<p>Neither if you ask me;</p>\n\n<p>If your \"link\" has the sole purpose of running some JavaScript code it doesn't qualify as a link; rather a piece of text with a JavaScript function coupled to it. I would recommend to use a <code><span></code> tag with an <code>onclick handler</code> attached to it and some basic CSS to immitate a link. Links are made for navigation, and if your JavaScript code isn't for navigation it should not be an <code><a></code> tag.</p>\n\n<p>Example:</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>function callFunction() { console.log(\"function called\"); }</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.jsAction {\r\n cursor: pointer;\r\n color: #00f;\r\n text-decoration: underline;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><p>I want to call a JavaScript function <span class=\"jsAction\" onclick=\"callFunction();\">here</span>.</p></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 136103,
"author": "Will Read",
"author_id": 22396,
"author_profile": "https://Stackoverflow.com/users/22396",
"pm_score": 4,
"selected": false,
"text": "<p>Depending on what you want to accomplish, you could forget the onclick and just use the href:</p>\n\n<pre><code><a href=\"javascript:myJsFunc()\">Link Text</a>\n</code></pre>\n\n<p>It gets around the need to return false. I don't like the <code>#</code> option because, as mentioned, it will take the user to the top of the page. If you have somewhere else to send the user if they don't have JavaScript enabled (which is rare where I work, but a very good idea), then Steve's proposed method works great. </p>\n\n<pre><code><a href=\"javascriptlessDestination.html\" onclick=\"myJSFunc(); return false;\">Link text</a>\n</code></pre>\n\n<p>Lastly, you can use <code>javascript:void(0)</code> if you do not want anyone to go anywhere and if you don't want to call a JavaScript function. It works great if you have an image you want a mouseover event to happen with, but there's not anything for the user to click on.</p>\n"
},
{
"answer_id": 136225,
"author": "CleverPatrick",
"author_id": 22399,
"author_profile": "https://Stackoverflow.com/users/22399",
"pm_score": 4,
"selected": false,
"text": "<p>I believe you are presenting a false dichotomy. These are not the only two options. </p>\n\n<p>I agree with Mr. D4V360 who suggested that, even though you are using the anchor tag, you do not truly have an anchor here. All you have is a special section of a document that should behave slightly different. A <code><span></code> tag is far more appropriate.</p>\n"
},
{
"answer_id": 136340,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 3,
"selected": false,
"text": "<p><strong>If</strong> you use a link as a way to <strong>just</strong> execute some JavaScript code (instead of using a span like D4V360 greatly suggested), just do:</p>\n\n<pre><code><a href=\"javascript:(function()%7Balert(%22test%22)%3B%7D)()%3B\">test</a>\n</code></pre>\n\n<p>If you're using a link with onclick for navigation, don't use href=\"#\" as the fallback when JavaScript is off. It's usually very annoying when the user clicks on the link. Instead, provide the same link the onclick handler would provide if possible. If you can't do that, skip the onclick and just use a JavaScript URI in the href.</p>\n"
},
{
"answer_id": 138233,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 11,
"selected": false,
"text": "<p>I use <code>javascript:void(0)</code>.</p>\n\n<p>Three reasons. Encouraging the use of <code>#</code> amongst a team of developers inevitably leads to some using the return value of the function called like this:</p>\n\n<pre><code>function doSomething() {\n //Some code\n return false;\n}\n</code></pre>\n\n<p>But then they forget to use <code>return doSomething()</code> in the onclick and just use <code>doSomething()</code>.</p>\n\n<p>A second reason for avoiding <code>#</code> is that the final <code>return false;</code> will not execute if the called function throws an error. Hence the developers have to also remember to handle any error appropriately in the called function.</p>\n\n<p>A third reason is that there are cases where the <code>onclick</code> event property is assigned dynamically. I prefer to be able to call a function or assign it dynamically without having to code the function specifically for one method of attachment or another. Hence my <code>onclick</code> (or on anything) in HTML markup look like this:</p>\n\n<pre><code>onclick=\"someFunc.call(this)\"\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>onclick=\"someFunc.apply(this, arguments)\"\n</code></pre>\n\n<p>Using <code>javascript:void(0)</code> avoids all of the above headaches, and I haven't found any examples of a downside.</p>\n\n<p>So if you're a lone developer then you can clearly make your own choice, but if you work as a team you have to either state:</p>\n\n<p>Use <code>href=\"#\"</code>, make sure <code>onclick</code> always contains <code>return false;</code> at the end, that any called function does not throw an error and if you attach a function dynamically to the <code>onclick</code> property make sure that as well as not throwing an error it returns <code>false</code>.</p>\n\n<p>OR</p>\n\n<p>Use <code>href=\"javascript:void(0)\"</code></p>\n\n<p>The second is clearly much easier to communicate.</p>\n"
},
{
"answer_id": 138934,
"author": "Pablo Cabrera",
"author_id": 12540,
"author_profile": "https://Stackoverflow.com/users/12540",
"pm_score": 3,
"selected": false,
"text": "<p>If you are using an <code><a></code> element, just use this:</p>\n\n<pre><code><a href=\"javascript:myJSFunc();\" />myLink</a>\n</code></pre>\n\n<p>Personally I'd attach an event handler with JavaScript later on instead (using <code>attachEvent</code> or <code>addEventListener</code> or maybe <put your favorite JavaScript framework here > also).</p>\n"
},
{
"answer_id": 143410,
"author": "Fczbkk",
"author_id": 22920,
"author_profile": "https://Stackoverflow.com/users/22920",
"pm_score": 6,
"selected": false,
"text": "<p>I agree with suggestions elsewhere stating that you should use regular URL in <code>href</code> attribute, then call some JavaScript function in onclick. The flaw is, that they automaticaly add <code>return false</code> after the call.</p>\n\n<p>The problem with this approach is, that if the function will not work or if there will be any problem, the link will become unclickable. Onclick event will always return <code>false</code>, so the normal URL will not be called.</p>\n\n<p>There's very simple solution. Let function return <code>true</code> if it works correctly. Then use the returned value to determine if the click should be cancelled or not:</p>\n\n<p><strong>JavaScript</strong></p>\n\n<pre><code>function doSomething() {\n alert( 'you clicked on the link' );\n return true;\n}\n</code></pre>\n\n<p><strong>HTML</strong></p>\n\n<pre><code><a href=\"path/to/some/url\" onclick=\"return !doSomething();\">link text</a>\n</code></pre>\n\n<hr>\n\n<p>Note, that I negate the result of the <code>doSomething()</code> function. If it works, it will return <code>true</code>, so it will be negated (<code>false</code>) and the <code>path/to/some/URL</code> will not be called. If the function will return <code>false</code> (for example, the browser doesn't support something used within the function or anything else goes wrong), it is negated to <code>true</code> and the <code>path/to/some/URL</code> is called.</p>\n"
},
{
"answer_id": 209580,
"author": "treat your mods well",
"author_id": 20772,
"author_profile": "https://Stackoverflow.com/users/20772",
"pm_score": 6,
"selected": false,
"text": "<p>I recommend using a <code><button></code> element instead, <em>especially</em> if the control is supposed to produce a change in the data. (Something like a POST.)</p>\n\n<p>It's even better if you inject the elements unobtrusively, a type of progressive enhancement. (See <a href=\"https://stackoverflow.com/questions/134845/href-for-javascript-links-or-javascriptvoid0#134957\">this comment</a>.)</p>\n"
},
{
"answer_id": 209618,
"author": "Andrew Moore",
"author_id": 26210,
"author_profile": "https://Stackoverflow.com/users/26210",
"pm_score": 4,
"selected": false,
"text": "<p>Usually, you should always have a fall back link to make sure that clients with JavaScript disabled still has some functionality. This concept is called unobtrusive JavaScript. </p>\n\n<p>Example... Let's say you have the following search link:</p>\n\n<pre><code><a href=\"search.php\" id=\"searchLink\">Search</a>\n</code></pre>\n\n<p>You can always do the following:</p>\n\n<pre><code>var link = document.getElementById('searchLink');\n\nlink.onclick = function() {\n try {\n // Do Stuff Here \n } finally {\n return false;\n }\n};\n</code></pre>\n\n<p>That way, people with JavaScript disabled are directed to <code>search.php</code> while your viewers with JavaScript view your enhanced functionality.</p>\n"
},
{
"answer_id": 229157,
"author": "naveen",
"author_id": 17447,
"author_profile": "https://Stackoverflow.com/users/17447",
"pm_score": 5,
"selected": false,
"text": "<p>It would be better to use jQuery,</p>\n\n<pre><code>$(document).ready(function() {\n $(\"a\").css(\"cursor\", \"pointer\");\n});\n</code></pre>\n\n<p>and omit both <code>href=\"#\"</code> and <code>href=\"javascript:void(0)\"</code>.</p>\n\n<p>The anchor tag markup will be like </p>\n\n<pre><code><a onclick=\"hello()\">Hello</a>\n</code></pre>\n\n<p>Simple enough!</p>\n"
},
{
"answer_id": 229926,
"author": "Matt Goddard",
"author_id": 5185,
"author_profile": "https://Stackoverflow.com/users/5185",
"pm_score": 3,
"selected": false,
"text": "<p>Just to pick up the point some of the other have mentioned.</p>\n\n<p>It's much better to bind the event 'onload'a or $('document').ready{}; then to put JavaScript directly into the click event.</p>\n\n<p>In the case that JavaScript isn't available, I would use a href to the current URL, and perhaps an anchor to the position of the link. The page is still be usable for the people without JavaScript those who have won't notice any difference.</p>\n\n<p>As I have it to hand, here is some jQuery which might help:</p>\n\n<pre><code>var [functionName] = function() {\n // do something\n};\n\njQuery(\"[link id or other selector]\").bind(\"click\", [functionName]);\n</code></pre>\n"
},
{
"answer_id": 598317,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>You can also write a hint in an anchor like this:</p>\n\n<pre><code><a href=\"javascript:void('open popup image')\" onclick=\"return f()\">...</a>\n</code></pre>\n\n<p>so the user will know what this link does.</p>\n"
},
{
"answer_id": 759284,
"author": "se_pavel",
"author_id": 80917,
"author_profile": "https://Stackoverflow.com/users/80917",
"pm_score": 6,
"selected": false,
"text": "<p>I use the following</p>\n\n<pre><code><a href=\"javascript:;\" onclick=\"myJsFunc();\">Link</a>\n</code></pre>\n\n<p>instead</p>\n\n<pre><code><a href=\"javascript:void(0);\" onclick=\"myJsFunc();\">Link</a>\n</code></pre>\n"
},
{
"answer_id": 1691745,
"author": "Free Consulting",
"author_id": 205376,
"author_profile": "https://Stackoverflow.com/users/205376",
"pm_score": 5,
"selected": false,
"text": "<p>Definitely hash (<code>#</code>) is better because in JavaScript it is a pseudoscheme:</p>\n\n<ol>\n<li>pollutes history </li>\n<li>instantiates new copy of engine </li>\n<li>runs in global scope and doesn't respect event system. </li>\n</ol>\n\n<p>Of course \"#\" with an onclick handler which prevents default action is [much] better. Moreover, a link that has the sole purpose to run JavaScript is not really \"a link\" unless you are sending user to some sensible anchor on the page (just # will send to top) when something goes wrong. You can simply simulate look and feel of link with stylesheet and forget about href at all.</p>\n\n<p>In addition, regarding cowgod's suggestion, particularly this: <code>...href=\"javascript_required.html\" onclick=\"...</code> This is good approach, but it doesn't distinguish between \"JavaScript disabled\" and \"onclick fails\" scenarios.</p>\n"
},
{
"answer_id": 1785783,
"author": "Justin Johnson",
"author_id": 126562,
"author_profile": "https://Stackoverflow.com/users/126562",
"pm_score": 6,
"selected": false,
"text": "<p><code>#</code> is better than <code>javascript:anything</code>, but the following is even better:</p>\n\n<p>HTML:</p>\n\n<pre><code><a href=\"/gracefully/degrading/url/with/same/functionality.ext\" class=\"some-selector\">For great justice</a>\n</code></pre>\n\n<p>JavaScript:</p>\n\n<pre><code>$(function() {\n $(\".some-selector\").click(myJsFunc);\n});\n</code></pre>\n\n<p>You should always strive for graceful degradation (in the event that the user doesn't have JavaScript enabled...and when it is with specs. and budget). Also, it is considered bad form to use JavaScript attributes and protocol directly in HTML.</p>\n"
},
{
"answer_id": 3273564,
"author": "user394888",
"author_id": 394888,
"author_profile": "https://Stackoverflow.com/users/394888",
"pm_score": 3,
"selected": false,
"text": "<p>In total agreement with the overall sentiment, use <code>void(0)</code> when you need it, and use a valid URL when you need it.</p>\n\n<p>Using <a href=\"http://en.wikipedia.org/wiki/Rewrite_engine\" rel=\"noreferrer\">URL rewriting</a> you can make URLs that not only do what you want to do with JavaScript disabled, but also tell you exactly what its going to do.</p>\n\n<pre><code><a href=\"./Readable/Text/URL/Pointing/To/Server-Side/Script\" id=\"theLinkId\">WhyClickHere</a>\n</code></pre>\n\n<p>On the server side, you just have to parse the URL and query string and do what you want. If you are clever, you can allow the server side script to respond to both Ajax and standard requests differently. Allowing you to have concise centralized code that handles all the links on your page.</p>\n\n<p><a href=\"http://www.easymodrewrite.com/\" rel=\"noreferrer\">URL rewriting tutorials</a></p>\n\n<p>Pros</p>\n\n<ul>\n<li>Shows up in status bar</li>\n<li>Easily upgraded to Ajax via onclick handler in JavaScript</li>\n<li>Practically comments itself</li>\n<li>Keeps your directories from becoming littered with single use HTML files</li>\n</ul>\n\n<p>Cons</p>\n\n<ul>\n<li>Should still use event.preventDefault() in JavaScript</li>\n<li>Fairly complex path handling and URL parsing on the server side.</li>\n</ul>\n\n<p>I am sure there are tons more cons out there. Feel free to discuss them.</p>\n"
},
{
"answer_id": 4539617,
"author": "rcof",
"author_id": 555075,
"author_profile": "https://Stackoverflow.com/users/555075",
"pm_score": 3,
"selected": false,
"text": "<p>There is one more important thing to remember here. <a href=\"http://en.wikipedia.org/wiki/Section_508_Amendment_to_the_Rehabilitation_Act_of_1973\">Section 508</a> compliance.\nBecause of it, I feel it's necessary to point out that you need the anchor tag for screen readers such as <a href=\"http://en.wikipedia.org/wiki/JAWS_%28screen_reader%29\">JAWS</a> to be able to focus it through tabbing. So the solution \"just use JavaScript and forget the anchor to begin with\" is not an option for some of this. Firing the JavaScript inside the href is only necessary if you can't afford for the screen to jump back up to the top. You can use a settimeout for 0 seconds and have JavaScript fire to where you need focus but even the apage will jump to the top and then back. </p>\n"
},
{
"answer_id": 6829393,
"author": "user564706",
"author_id": 564706,
"author_profile": "https://Stackoverflow.com/users/564706",
"pm_score": 5,
"selected": false,
"text": "<p>I choose use <code>javascript:void(0)</code>, because use this could prevent right click to open the content menu. But <code>javascript:;</code> is shorter and does the same thing.</p>\n"
},
{
"answer_id": 7536475,
"author": "Spammer Joe",
"author_id": 962185,
"author_profile": "https://Stackoverflow.com/users/962185",
"pm_score": 6,
"selected": false,
"text": "<p>Using just <code>#</code> makes some funny movements, so I would recommend to use <code>#self</code> if you would like to save on typing efforts of <code>JavaScript bla, bla,</code>.</p>\n"
},
{
"answer_id": 8511644,
"author": "Jesse Atkinson",
"author_id": 762889,
"author_profile": "https://Stackoverflow.com/users/762889",
"pm_score": 3,
"selected": false,
"text": "<p>I strongly prefer to keep my JavaScript out of my HTML markup as much as possible. If I'm using <code><a></code> as click event handlers then I'd recommend using <code><a class=\"trigger\" href=\"#\">Click me!</a></code>.</p>\n\n<pre><code>$('.trigger').click(function (e) {\n e.preventDefault();\n // Do stuff...\n});\n</code></pre>\n\n<p>It's very important to note that many developers out there believe that using anchor tags for click-event handlers isn't good. They'd prefer you to use a <code><span></code> or <code><div></code> with some CSS that adds <code>cursor: pointer;</code> to it. This is a matter if much debate.</p>\n"
},
{
"answer_id": 8512410,
"author": "Josh Simerman",
"author_id": 200292,
"author_profile": "https://Stackoverflow.com/users/200292",
"pm_score": 4,
"selected": false,
"text": "<p>I'm basically paraphrasing from <a href=\"http://www.matthidinger.com/archive/2011/02/22/Progressive-enhancement-tutorial-with-ASP-NET-MVC-3-and-jQuery.aspx\" rel=\"noreferrer\">this practical article using progressive enhancement</a>. <strong>The short answer is that you never use <code>javascript:void(0);</code> or <code>#</code> unless your user interface has already inferred that JavaScript is enabled, in which case you should use <code>javascript:void(0);</code></strong>. Also, do not use span as links, since that is semantically false to begin with.</p>\n\n<p>Using <a href=\"http://en.wikipedia.org/wiki/Search_engine_optimization\" rel=\"noreferrer\">SEO</a> friendly URL routes in your application, such as /Home/Action/Parameters is a good practice as well. If you have a link to a page that works without JavaScript first, you can enhance the experience afterward. Use a real link to a working page, then add an onlick event to enhance the presentation.</p>\n\n<p>Here is a sample. Home/ChangePicture is a working link to a form on a page complete with user interface and standard HTML submit buttons, but it looks nicer injected into a modal dialog with jQueryUI buttons. Either way works, depending on the browser, which satisfies mobile first development.</p>\n\n<pre><code><p><a href=\"Home/ChangePicture\" onclick=\"return ChangePicture_onClick();\" title=\"Change Picture\">Change Picture</a></p>\n\n<script type=\"text/javascript\">\n function ChangePicture_onClick() {\n $.get('Home/ChangePicture',\n function (htmlResult) {\n $(\"#ModalViewDiv\").remove(); //Prevent duplicate dialogs\n $(\"#modalContainer\").append(htmlResult);\n $(\"#ModalViewDiv\").dialog({\n width: 400,\n modal: true,\n buttons: {\n \"Upload\": function () {\n if(!ValidateUpload()) return false;\n $(\"#ModalViewDiv\").find(\"form\").submit();\n },\n Cancel: function () { $(this).dialog(\"close\"); }\n },\n close: function () { }\n });\n }\n );\n return false;\n }\n</script>\n</code></pre>\n"
},
{
"answer_id": 8517735,
"author": "Berker Yüceer",
"author_id": 861019,
"author_profile": "https://Stackoverflow.com/users/861019",
"pm_score": 3,
"selected": false,
"text": "<p>What I understand from your words is that you want to create a link just to run JavaScript code.</p>\n\n<p>Then you should consider that there are people who blocks JavaScript out there in their browsers.</p>\n\n<p>So if you are really going to use that link only for running a JavaScript function then you should add it dynamically so it won't be even seen if the users didn't enable their JavaScript in the browser and you are using that link just to trigger a JavaScript function which makes no sense to use a link like that when JavaScript is disabled in the browser.</p>\n\n<p>For that reason neither of them is good when JavaScript is disabled.</p>\n\n<p>Aand if JavaScript is enabled and you only want to use that link to invoke a JavaScript function then</p>\n\n<pre><code><a href=\"javascript:void(0)\" onclick=\"myJsFunc();\">Link</a>\n</code></pre>\n\n<p>is far better way than using</p>\n\n<pre><code><a href=\"#\" onclick=\"myJsFunc();\">Link</a>\n</code></pre>\n\n<p>because href=\"#\" is going to cause the page to do actions that are not needed.</p>\n\n<p>Also, another reason why <code><a href=\"javascript:void(0)\" onclick=\"myJsFunc();\">Link</a></code> is better than <code><a href=\"#\" onclick=\"myJsFunc();\">Link</a></code> is that JavaScript is used as the default scripting language for most of the browsers. As an example Internet Explorer, uses an onclick attribute to define the type of scripting language that would be used. Unless another good scripting language pops up, JavaScript will be used by Internet Explorer as the default too, but if another scripting language used <code>javascript:</code>, it would let Internet Explorer to understand which scripting language is being used.</p>\n\n<p>Considering this, I would prefer using and exercising on</p>\n\n<pre><code><a href=\"javascript:void(0)\" onclick=\"myJsFunc();\">Link</a>\n</code></pre>\n\n<p>enough to make it a habit and to be more user friendly please add that kind of links within the JavaScript code:</p>\n\n<pre><code>$(document).ready(function(){\n $(\".blabla\").append('<a href=\"javascript:void(0)\" onclick=\"myJsFunc();\">Link</a>')\n});\n</code></pre>\n"
},
{
"answer_id": 8525002,
"author": "Tracker1",
"author_id": 43906,
"author_profile": "https://Stackoverflow.com/users/43906",
"pm_score": 8,
"selected": false,
"text": "<p>I would honestly suggest neither. I would use a stylized <code><button></button></code> for that behavior.</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-css lang-css prettyprint-override\"><code>button.link {\r\n display: inline-block;\r\n position: relative;\r\n background-color: transparent;\r\n cursor: pointer;\r\n border: 0;\r\n padding: 0;\r\n color: #00f;\r\n text-decoration: underline;\r\n font: inherit;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><p>A button that looks like a <button type=\"button\" class=\"link\">link</button>.</p></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>This way you can assign your onclick. I also suggest binding via script, not using the <code>onclick</code> attribute on the element tag. The only gotcha is the psuedo 3d text effect in older IEs that cannot be disabled.</p>\n\n<hr>\n\n<p>If you <em>MUST</em> use an A element, use <code>javascript:void(0);</code> for reasons already mentioned.</p>\n\n<ul>\n<li>Will always intercept in case your onclick event fails.</li>\n<li>Will not have errant load calls happen, or trigger other events based on a hash change</li>\n<li>The hash tag can cause unexpected behavior if the click falls through (onclick throws), avoid it unless it's an appropriate fall-through behavior, and you want to change the navigation history.</li>\n</ul>\n\n<p>NOTE: You can replace the <code>0</code> with a string such as <code>javascript:void('Delete record 123')</code> which can serve as an extra indicator that will show what the click will actually do.</p>\n"
},
{
"answer_id": 8528329,
"author": "Eric Yin",
"author_id": 939713,
"author_profile": "https://Stackoverflow.com/users/939713",
"pm_score": 5,
"selected": false,
"text": "<p>I would use:</p>\n\n<pre><code><a href=\"#\" onclick=\"myJsFunc();return false;\">Link</a>\n</code></pre>\n\n<p><strong>Reasons:</strong></p>\n\n<ol>\n<li>This makes the <code>href</code> simple, search engines need it. If you use anything else ( such as a string), it may cause a <code>404 not found</code> error.</li>\n<li>When mouse hovers over the link, it doesn't show that it is a script.</li>\n<li>By using <code>return false;</code>, the page doesn't jump to the top or break the <code>back</code> button.</li>\n</ol>\n"
},
{
"answer_id": 9440536,
"author": "balupton",
"author_id": 130638,
"author_profile": "https://Stackoverflow.com/users/130638",
"pm_score": 10,
"selected": false,
"text": "<p>Doing <code><a href=\"#\" onclick=\"myJsFunc();\">Link</a></code> or <code><a href=\"javascript:void(0)\" onclick=\"myJsFunc();\">Link</a></code> or whatever else that contains an <code>onclick</code> attribute - was okay back five years ago, though now it can be a bad practice. Here's why:</p>\n\n<ol>\n<li><p>It promotes the practice of obtrusive JavaScript - which has turned out to be difficult to maintain and difficult to scale. More on this in <em><a href=\"http://en.wikipedia.org/wiki/Unobtrusive_JavaScript\" rel=\"noreferrer\">Unobtrusive JavaScript</a></em>.</p></li>\n<li><p>You're spending your time writing incredibly overly verbose code - which has very little (if any) benefit to your codebase.</p></li>\n<li><p>There are now better, easier, and more maintainable and scalable ways of accomplishing the desired result.</p></li>\n</ol>\n\n<h2>The unobtrusive JavaScript way</h2>\n\n<p>Just don't have a <code>href</code> attribute at all! Any good CSS reset would take care of the missing default cursor style, so that is a non-issue. Then attach your JavaScript functionality using graceful and unobtrusive best practices - which are more maintainable as your JavaScript logic stays in JavaScript, instead of in your markup - which is essential when you start developing large scale JavaScript applications which require your logic to be split up into blackboxed components and templates. More on this in <em><a href=\"http://speakerdeck.com/u/addyosmani/p/large-scale-javascript-application-architecture\" rel=\"noreferrer\">Large-scale JavaScript Application Architecture</a></em></p>\n\n<h2>Simple code example</h2>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// Cancel click event\r\n$('.cancel-action').click(function(){\r\n alert('Cancel action occurs!');\r\n});\r\n\r\n// Hover shim for Internet Explorer 6 and Internet Explorer 7.\r\n$(document.body).on('hover','a',function(){\r\n $(this).toggleClass('hover');\r\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>a { cursor: pointer; color: blue; }\r\na:hover,a.hover { text-decoration: underline; }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\r\n<a class=\"cancel-action\">Cancel this action</a></code></pre>\r\n</div>\r\n</div>\r\n </p>\n\n<h2>A blackboxed <em><a href=\"http://documentcloud.github.com/backbone/\" rel=\"noreferrer\">Backbone.js</a></em> example</h2>\n\n<p>For a scalable, blackboxed, Backbone.js component example - <em><a href=\"http://jsfiddle.net/balupton/sTzdD/\" rel=\"noreferrer\">see this working jsfiddle example here</a></em>. Notice how we utilize unobtrusive JavaScript practices, and in a tiny amount of code have a component that can be repeated across the page multiple times without side-effects or conflicts between the different component instances. Amazing!</p>\n\n<h2>Notes</h2>\n\n<ul>\n<li><p>Omitting the <code>href</code> attribute on the <code>a</code> element will cause the element to not be accessible using <code>tab</code> key navigation. If you wish for those elements to be accessible via the <code>tab</code> key, you can set the <code>tabindex</code> attribute, or use <code>button</code> elements instead. You can easily style button elements to look like normal links as mentioned in <em><a href=\"https://stackoverflow.com/a/8525002/130638\">Tracker1's answer</a></em>.</p></li>\n<li><p>Omitting the <code>href</code> attribute on the <code>a</code> element will cause <a href=\"http://en.wikipedia.org/wiki/Internet_Explorer_6\" rel=\"noreferrer\">Internet Explorer 6</a> and <a href=\"http://en.wikipedia.org/wiki/Internet_Explorer_7\" rel=\"noreferrer\">Internet Explorer 7</a> to not take on the <code>a:hover</code> styling, which is why we have added a simple JavaScript shim to accomplish this via <code>a.hover</code> instead. Which is perfectly okay, as if you don't have a href attribute and no graceful degradation then your link won't work anyway - and you'll have bigger issues to worry about.</p></li>\n<li><p>If you want your action to still work with JavaScript disabled, then using an <code>a</code> element with a <code>href</code> attribute that goes to some URL that will perform the action manually instead of via an Ajax request or whatever should be the way to go. If you are doing this, then you want to ensure you do an <code>event.preventDefault()</code> on your click call to make sure when the button is clicked it does not follow the link. This option is called graceful degradation.</p></li>\n</ul>\n"
},
{
"answer_id": 9717217,
"author": "Timo Huovinen",
"author_id": 175071,
"author_profile": "https://Stackoverflow.com/users/175071",
"pm_score": 2,
"selected": false,
"text": "<p>Here is one more option for completeness sake, that prevents the link from doing anything even if JavaScript is disabled, and it's short :)</p>\n\n<pre><code><a href=\"#void\" onclick=\"myJsFunc()\">Run JavaScript function</a>\n</code></pre>\n\n<p>If the id is not present on the page, then the link will do nothing.</p>\n\n<p>Generally, I agree with the Aaron Wagner's answer, the JavaScript link should be injected with JavaScript code into the document.</p>\n"
},
{
"answer_id": 9730961,
"author": "dazbradbury",
"author_id": 892397,
"author_profile": "https://Stackoverflow.com/users/892397",
"pm_score": 3,
"selected": false,
"text": "<p>I see a lot of answers by people who want to keep using <code>#</code> values for <code>href</code>, hence, here is an answer hopefully satisfying both camps:</p>\n\n<p><strong>A)</strong> I'm happy to have <code>javascript:void(0)</code> as my <code>href</code> value:</p>\n\n<pre><code><a href=\"javascript:void(0)\" onclick=\"someFunc.call(this)\">Link Text</a>\n</code></pre>\n\n<p><strong>B)</strong> I am using jQuery, and want <code>#</code> as my <code>href</code> value:</p>\n\n<pre><code><a href=\"#\" onclick=\"someFunc.call(this)\">Link Text</a>\n\n<script type=\"text/javascript\">\n /* Stop page jumping when javascript links are clicked.\n Only select links where the href value is a #. */\n $('a[href=\"#\"]').live(\"click\", function(e) {\n return false; // prevent default click action from happening!\n e.preventDefault(); // same thing as above\n });\n</script>\n</code></pre>\n\n<p>Note, if you know links won't be created dynamically, use the <code>click</code> function instead: </p>\n\n<p><code>$('a[href=\"#\"]').click(function(e) {</code></p>\n"
},
{
"answer_id": 11196124,
"author": "Stacks on Stacks on Stacks",
"author_id": 800471,
"author_profile": "https://Stackoverflow.com/users/800471",
"pm_score": 4,
"selected": false,
"text": "<p>When I've got several faux-links, I prefer to give them a class of 'no-link'.</p>\n\n<p>Then in jQuery, I add the following code:</p>\n\n<pre><code>$(function(){\n $('.no-link').click(function(e){\n e.preventDefault();\n });\n});\n</code></pre>\n\n<p>And for the HTML, the link is simply</p>\n\n<pre><code><a href=\"/\" class=\"no-link\">Faux-Link</a>\n</code></pre>\n\n<p>I don't like using Hash-Tags unless they're used for anchors, and I only do the above when I've got more than two faux-links, otherwise I go with javascript:void(0).</p>\n\n<pre><code><a href=\"javascript:void(0)\" class=\"no-link\">Faux-Link</a>\n</code></pre>\n\n<p>Typically, I like to just avoid using a link at all and just wrap something around in a span and use that as a way to active some JavaScript code, like a pop-up or a content-reveal.</p>\n"
},
{
"answer_id": 12077178,
"author": "vol7ron",
"author_id": 183181,
"author_profile": "https://Stackoverflow.com/users/183181",
"pm_score": 3,
"selected": false,
"text": "<p>You could use the href and remove all links that have only hashes:</p>\n\n<p>HTML:</p>\n\n<pre><code><a href=\"#\" onclick=\"run_foo()\"> foo </a>\n</code></pre>\n\n<p>JS:</p>\n\n<pre><code>$(document).ready(function(){ // on DOM ready or some other event\n\n $('a[href=#]').attr('href',''); // set all reference handles to blank strings\n // for anchors that have only hashes\n\n});\n</code></pre>\n"
},
{
"answer_id": 14774496,
"author": "G. Ghez",
"author_id": 67276,
"author_profile": "https://Stackoverflow.com/users/67276",
"pm_score": 3,
"selected": false,
"text": "<p>You <strong>should not use</strong> inline <code>onclick=\"something();\"</code> in your HTML to not polluate it with meaningless code; all click bindings must be set in Javascript files (*.js).</p>\n\n<p>Set binding like this : <code>$('#myAnchor').click(function(){... **return false**;});</code> or <code>$('#myAnchor').bind('click', function(){... **return false**;});</code></p>\n\n<p>Then you have a clean HTML file easy to load (and seo friendly) without thousands of <code>href=\"javascript:void(0);\"</code> and just <code>href=\"#\"</code></p>\n"
},
{
"answer_id": 17869905,
"author": "whirlwin",
"author_id": 490315,
"author_profile": "https://Stackoverflow.com/users/490315",
"pm_score": 4,
"selected": false,
"text": "<p>If you happen to be using <a href=\"http://angularjs.org/\" rel=\"noreferrer\"><strong>AngularJS</strong></a>, you can use the following:</p>\n\n<pre><code><a href=\"\">Do some fancy JavaScript</a>\n</code></pre>\n\n<p>Which will not do anything.</p>\n\n<p>In addition</p>\n\n<ul>\n<li>It will not take you to the top of the page, as with (#)\n\n<ul>\n<li>Therefore, you don't need to explicitly return <code>false</code> with JavaScript</li>\n</ul></li>\n<li>It is short an concise</li>\n</ul>\n"
},
{
"answer_id": 21744656,
"author": "Ashish Kumar",
"author_id": 1562258,
"author_profile": "https://Stackoverflow.com/users/1562258",
"pm_score": 5,
"selected": false,
"text": "<p>So, when you are doing some JavaScript things with an <code><a /></code> tag and if you put <code>href=\"#\"</code> as well, you can add <strong>return false</strong> at the end of the event <em>(in case of inline event binding)</em> like:</p>\n\n<pre><code><a href=\"#\" onclick=\"myJsFunc(); return false;\">Run JavaScript Code</a>\n</code></pre>\n\n<p><em>Or you can change the <strong>href</strong> attribute with JavaScript like:</em></p>\n\n<pre><code><a href=\"javascript://\" onclick=\"myJsFunc();\">Run JavaScript Code</a>\n</code></pre>\n\n<p><strong>or</strong></p>\n\n<pre><code><a href=\"javascript:void(0)\" onclick=\"myJsFunc();\">Run JavaScript Code</a>\n</code></pre>\n\n<hr>\n\n<p>But semantically, all the above ways to achieve this are wrong <em>(it works fine though)</em>. If any element is not created to navigate the page and that have some JavaScript things associated with it, then it should not be a <code><a></code> tag. </p>\n\n<p>You can simply use a <code><button /></code> instead to do things or any other element like b, span or whatever fits there as per your need, because you are allowed to add events on all the elements.</p>\n\n<hr>\n\n<p>So, <strong>there is one benefit</strong> to use <code><a href=\"#\"></code>. You get the cursor pointer by default on that element when you do <code>a href=\"#\"</code>. For that, I think you can use CSS for this like <code>cursor:pointer;</code> which solves this problem also.</p>\n\n<p>And at the end, if you are binding the event from the JavaScript code itself, there you can do <code>event.preventDefault()</code> to achieve this if you are using <code><a></code> tag, but if you are not using a <code><a></code> tag for this, there you get an advantage, you don't need to do this.</p>\n\n<p>So, if you see, it's better not to use a tag for this kind of stuff.</p>\n"
},
{
"answer_id": 22252785,
"author": "Vinny Fonseca",
"author_id": 1145945,
"author_profile": "https://Stackoverflow.com/users/1145945",
"pm_score": 3,
"selected": false,
"text": "<p>I use href=\"#\" for links that I want a dummy behaviour for. Then I use this code:</p>\n\n<pre><code>$(document).ready(function() {\n $(\"a[href='#']\").click(function(event) {\n event.preventDefault();\n });\n});\n</code></pre>\n\n<p>Meaning if the href equals to a hash (*=\"#\") it prevents the default link behaviour, thus still allowing you to write functionality for it, and it doesn't affect anchor clicks.</p>\n"
},
{
"answer_id": 22530755,
"author": "Anders M.",
"author_id": 1617103,
"author_profile": "https://Stackoverflow.com/users/1617103",
"pm_score": 3,
"selected": false,
"text": "<p>I'd say the best way is to make an href anchor to an ID you'd never use, like #Do1Not2Use3This4Id5 or a similar ID, that you are 100% sure no one will use and won't offend people.</p>\n\n<ol>\n<li><code>Javascript:void(0)</code> is a bad idea and violates Content Security Policy on CSP-enabled HTTPS pages <a href=\"https://developer.mozilla.org/en/docs/Security/CSP\" rel=\"noreferrer\">https://developer.mozilla.org/en/docs/Security/CSP</a> (thanks to @jakub.g)</li>\n<li>Using just <code>#</code> will have the user jump back to the top when pressed</li>\n<li>Won't ruin the page if JavaScript isn't enabled (unless you have JavaScript detecting code</li>\n<li>If JavaScript is enabled you can disable the default event</li>\n<li>You have to use href unless you know how to prevent your browser from selecting some text, (don't know if using 4 will remove the thing that stops the browser from selecting text)</li>\n</ol>\n\n<p>Basically no one mentioned 5 in this article which I think is important as your site comes off as unprofessional if it suddenly starts selecting things around the link.</p>\n"
},
{
"answer_id": 23315028,
"author": "Milan and Friends",
"author_id": 2666313,
"author_profile": "https://Stackoverflow.com/users/2666313",
"pm_score": 4,
"selected": false,
"text": "<p>I personally use them in combination. For example:</p>\n\n<p>HTML</p>\n\n<pre><code><a href=\"#\">Link</a>\n</code></pre>\n\n<hr>\n\n<p>with little bit of jQuery</p>\n\n<pre><code>$('a[href=\"#\"]').attr('href','javascript:void(0);');\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$('a[href=\"#\"]').click(function(e) {\n e.preventDefault();\n});\n</code></pre>\n\n<p>But I'm using that just for preventing the page jumping to the top when the user clicks on an empty anchor. I'm rarely using onClick and other <code>on</code> events directly in HTML.</p>\n\n<p>My suggestion would be to use <code><span></code> element with the <code>class</code> attribute instead of\nan anchor. For example:</p>\n\n<pre><code><span class=\"link\">Link</span>\n</code></pre>\n\n<hr>\n\n<p>Then assign the function to <code>.link</code> with a script wrapped in the body and just before the <code></body></code> tag or in an external JavaScript document.</p>\n\n<pre><code><script>\n (function($) {\n $('.link').click(function() {\n // do something\n });\n })(jQuery);\n</script>\n</code></pre>\n\n<p><strong>*Note:</strong> For dynamically created elements, use:</p>\n\n<pre><code>$('.link').on('click', function() {\n // do something\n});\n</code></pre>\n\n<p>And for dynamically created elements which are created with dynamically created elements, use:</p>\n\n<pre><code>$(document).on('click','.link', function() {\n // do something\n});\n</code></pre>\n\n<hr>\n\n<p>Then you can style the span element to look like an anchor with a little CSS:</p>\n\n<pre><code>.link {\n color: #0000ee;\n text-decoration: underline;\n cursor: pointer;\n}\n.link:active {\n color: red;\n}\n</code></pre>\n\n<p>Here's <strong><a href=\"http://jsFiddle.net/mdesdev/Dn8YT/\" rel=\"noreferrer\">a jsFiddle</a></strong> example of above aforementioned.</p>\n"
},
{
"answer_id": 26998181,
"author": "AlxGol",
"author_id": 3010765,
"author_profile": "https://Stackoverflow.com/users/3010765",
"pm_score": 3,
"selected": false,
"text": "<p>Why not using this? This doesn't scroll page up.</p>\n\n<pre><code><span role=\"button\" onclick=\"myJsFunc();\">Run JavaScript Code</span>\n</code></pre>\n"
},
{
"answer_id": 31977848,
"author": "dnetix",
"author_id": 3295095,
"author_profile": "https://Stackoverflow.com/users/3295095",
"pm_score": 5,
"selected": false,
"text": "<p>I usually go for</p>\n\n<pre><code><a href=\"javascript:;\" onclick=\"yourFunction()\">Link description</a>\n</code></pre>\n\n<p>It's shorter than javascript:void(0) and does the same.</p>\n"
},
{
"answer_id": 35022676,
"author": "Garrett",
"author_id": 261439,
"author_profile": "https://Stackoverflow.com/users/261439",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Don't use links for the sole purpose of running JavaScript.</strong> </p>\n\n<p>The use of href=\"#\" scrolls the page to the top; the use of void(0) creates navigational problems within the browser.</p>\n\n<p>Instead, use an element other than a link:</p>\n\n<pre><code><span onclick=\"myJsFunc()\" class=\"funcActuator\">myJsFunc</span>\n</code></pre>\n\n<p>And style it with CSS:</p>\n\n<pre><code>.funcActuator { \n cursor: default;\n}\n\n.funcActuator:hover { \n color: #900;\n}\n</code></pre>\n"
},
{
"answer_id": 40322672,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>I tried both in google chrome with the developer tools, and the <code>id=\"#\"</code> took 0.32 seconds. While the <code>javascript:void(0)</code> method took only 0.18 seconds. So in google chrome, <code>javascript:void(0)</code> works better and faster.</p>\n"
},
{
"answer_id": 43035799,
"author": "TomDK",
"author_id": 2032618,
"author_profile": "https://Stackoverflow.com/users/2032618",
"pm_score": 4,
"selected": false,
"text": "<p>On a modern website the use of href should be avoided if the element is only doing JavaScript functionality (not a real link).</p>\n\n<p>Why?\nThe presence of this element tells the browser that this is a link with a destination. \nWith that, the browser will show the Open In New Tab / Window function (also triggered when you use shift+click). \nDoing so will result in opening the same page without the desired function triggered (resulting in user frustration).</p>\n\n<p>In regards to IE:\nAs of IE8, element styling (including hover) works if the doctype is set. Other versions of IE are not really to worry about anymore.</p>\n\n<p>Only Drawback:\nRemoving HREF removes the tabindex.\nTo overcome this, you can use a button that's styled as a link or add a tabindex attribute using JS.</p>\n"
},
{
"answer_id": 46573009,
"author": "Charlie",
"author_id": 145976,
"author_profile": "https://Stackoverflow.com/users/145976",
"pm_score": -1,
"selected": false,
"text": "<p>Bootstrap modals from before 4.0 have a basically undocumented behavior that they will load <code>href</code>s from <code>a</code> elements using AJAX unless they are exactly <code>#</code>. If you are using Bootstrap 3, <code>javascript:void(0);</code> hrefs will cause javascript errors:</p>\n\n<p><code>AJAX Error: error GET javascript:void(0);</code></p>\n\n<p>In these cases you would need to upgrade to bootstrap 4 or change the href.</p>\n"
},
{
"answer_id": 54009205,
"author": "L Y E S - C H I O U K H",
"author_id": 9317830,
"author_profile": "https://Stackoverflow.com/users/9317830",
"pm_score": 3,
"selected": false,
"text": "<h1>Edited on 2019 January</h1>\n\n<p>In <strong>HTML5</strong>, using an a element without an href attribute is <strong>valid</strong>. It is considered to be a <strong>\"placeholder hyperlink\"</strong></p>\n\n<blockquote>\n <p>If the a element has no href attribute, then the element represents a placeholder for where a link might otherwise have been placed, if it had been relevant, consisting of just the element's contents.</p>\n</blockquote>\n\n<p>Example:</p>\n\n<pre><code><a>previous</a>\n</code></pre>\n\n<p>If after that you want to do otherwise :</p>\n\n<p>1 - If your link doesn't go anywhere, don't use an <code><a></code> element. Use a <code><span></code> or something else appropriate and add CSS <code>:hover</code> to style it as you wish.</p>\n\n<p>2 - Use the <code>javascript:void(0)</code> OR <code>javascript:undefined</code> OR <code>javascript:;</code> if you want to be raw, precise and fast.</p>\n"
},
{
"answer_id": 56131904,
"author": "SchoolforDesign",
"author_id": 3527054,
"author_profile": "https://Stackoverflow.com/users/3527054",
"pm_score": 2,
"selected": false,
"text": "<p>• <code>Javascript: void(0);</code> is void to null value <strong>[Not assigned]</strong>, which that mean your browser is going to <code>NULL</code> click to <strong>DOM</strong>, and window return to false.<br />\n• The <code>'#'</code> is not follow the DOM or Window in javascript. which that mean the '#' sign inside anchor href is a <strong>LINK</strong>. Link to the same current direction.</p>\n"
},
{
"answer_id": 56353294,
"author": "Javed Khan",
"author_id": 9704900,
"author_profile": "https://Stackoverflow.com/users/9704900",
"pm_score": 2,
"selected": false,
"text": "<p>You can use javascript:void(0) here instead of using # to stop anchor tag redirect to header section.</p>\n\n<pre><code>function helloFunction() {\n alert(\"hello world\");\n}\n<a href=\"javascript:void(0)\" onclick=\"helloFunction();\">Call Hello Function</a>\n</code></pre>\n"
},
{
"answer_id": 56597389,
"author": "Dev pokhariya",
"author_id": 7179457,
"author_profile": "https://Stackoverflow.com/users/7179457",
"pm_score": 3,
"selected": false,
"text": "<p>The most simple and used by everyone mostly is <strong>javascript:void(0)</strong> You can use it instead of using <strong>#</strong> to stop <strong> tag redirect to header section</strong>.</p>\n\n<pre><code><a href=\"javascript:void(0)\" onclick=\"testFunction();\">Click To check Function</a>\n\nfunction testFunction() {\n alert(\"hello world\");\n}\n</code></pre>\n"
},
{
"answer_id": 66427870,
"author": "Stokely",
"author_id": 5555938,
"author_profile": "https://Stackoverflow.com/users/5555938",
"pm_score": 2,
"selected": false,
"text": "<p>There are actually <strong>four options</strong> here.</p>\n<p>Using <code>return false;</code> allows you to keep the anchor version in cases where you want a safe "fallback" in browsers that have <strong>JavaScript <em>disabled</em> or it is not supported in the user agent</strong> (1-5% of user's now). You can use the anchor "#" sign, an empty string, or a special URL for the <code>href</code> <strong>should your script fail</strong>. Note that you must use an <code>href</code> so screen readers know it is a hyperlink. (Note: I am not going to get into arguments about removing the <code>href</code> attribute as that point is moot here. Without an <code>href</code> on an anchor means the anchor is no longer a hyperlink and just an html tag with a click event on it that is captured.)</p>\n<pre><code><a href="" onclick="alert('hello world!');return false;">My Link</a>\n<a href="#" onclick="alert('hello world!');return false;">My Link</a>\n<a href="MyFallbackURL.html" onclick="alert('hello world!');return false;">My Link</a>\n</code></pre>\n<p>Below is the more popular design today using <code>javascript:void(0)</code> inside the <code>href</code> attribute. If a browser doesn't support scripting it should post again back to its page again, as an empty string is returned for the <code>href</code> hyperlink path. Use this if you don't care who supports JavaScript.</p>\n<pre><code><a href="javascript:void(0);" onclick="alert('hello world!');">My Link</a>\n</code></pre>\n"
},
{
"answer_id": 68150105,
"author": "Nedim AKAR",
"author_id": 11943388,
"author_profile": "https://Stackoverflow.com/users/11943388",
"pm_score": 1,
"selected": false,
"text": "<p><code>javascript:void(0)</code> will deprecate in future, therefore you should use <code>#</code>.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8018/"
]
| The following are two methods of building a link that has the sole purpose of running JavaScript code. Which is better, in terms of functionality, page load speed, validation purposes, etc.?
```js
function myJsFunc() {
alert("myJsFunc");
}
```
```html
<a href="#" onclick="myJsFunc();">Run JavaScript Code</a>
```
or
```js
function myJsFunc() {
alert("myJsFunc");
}
```
```html
<a href="javascript:void(0)" onclick="myJsFunc();">Run JavaScript Code</a>
``` | I use `javascript:void(0)`.
Three reasons. Encouraging the use of `#` amongst a team of developers inevitably leads to some using the return value of the function called like this:
```
function doSomething() {
//Some code
return false;
}
```
But then they forget to use `return doSomething()` in the onclick and just use `doSomething()`.
A second reason for avoiding `#` is that the final `return false;` will not execute if the called function throws an error. Hence the developers have to also remember to handle any error appropriately in the called function.
A third reason is that there are cases where the `onclick` event property is assigned dynamically. I prefer to be able to call a function or assign it dynamically without having to code the function specifically for one method of attachment or another. Hence my `onclick` (or on anything) in HTML markup look like this:
```
onclick="someFunc.call(this)"
```
OR
```
onclick="someFunc.apply(this, arguments)"
```
Using `javascript:void(0)` avoids all of the above headaches, and I haven't found any examples of a downside.
So if you're a lone developer then you can clearly make your own choice, but if you work as a team you have to either state:
Use `href="#"`, make sure `onclick` always contains `return false;` at the end, that any called function does not throw an error and if you attach a function dynamically to the `onclick` property make sure that as well as not throwing an error it returns `false`.
OR
Use `href="javascript:void(0)"`
The second is clearly much easier to communicate. |
134,858 | <p>I have some code I've written in PHP for consuming our simple webservice, which I'd also like to provide in Perl for users who may prefer that language. What's the simplest method of making a HTTP request to do that? In PHP I can do it in one line with <code>file_get_contents()</code>.</p>
<p>Here's the entire code I want to port to Perl:</p>
<pre class="lang-php prettyprint-override"><code>/**
* Makes a remote call to the our API, and returns the response
* @param cmd {string} - command string ID
* @param argsArray {array} - associative array of argument names and argument values
* @return {array} - array of responses
*/
function callAPI( $cmd, $argsArray=array() )
{
$apikey="MY_API_KEY";
$secret="MY_SECRET";
$apiurl="https://foobar.com/api";
// timestamp this API was submitted (for security reasons)
$epoch_time=time();
//--- assemble argument array into string
$query = "cmd=" .$cmd;
foreach ($argsArray as $argName => $argValue) {
$query .= "&" . $argName . "=" . urlencode($argValue);
}
$query .= "&key=". $apikey . "&time=" . $epoch_time;
//--- make md5 hash of the query + secret string
$md5 = md5($query . $secret);
$url = $apiurl . "?" . $query . "&md5=" . $md5;
//--- make simple HTTP GET request, put the server response into $response
$response = file_get_contents($url);
//--- convert "|" (pipe) delimited string to array
$responseArray = explode("|", $response);
return $responseArray;
}
</code></pre>
| [
{
"answer_id": 134884,
"author": "bmdhacks",
"author_id": 14032,
"author_profile": "https://Stackoverflow.com/users/14032",
"pm_score": 3,
"selected": false,
"text": "<p>Take a look at <a href=\"http://search.cpan.org/perldoc?LWP::Simple\" rel=\"noreferrer\">LWP::Simple</a>.\nFor more involved queries, there's even <a href=\"http://oreilly.com/catalog/9780596001780/\" rel=\"noreferrer\">a book about it</a>.</p>\n"
},
{
"answer_id": 134889,
"author": "Kevin Crumley",
"author_id": 1818,
"author_profile": "https://Stackoverflow.com/users/1818",
"pm_score": 7,
"selected": true,
"text": "<p>LWP::Simple:</p>\n\n<pre><code>use LWP::Simple;\n$contents = get(\"http://YOUR_URL_HERE\");\n</code></pre>\n"
},
{
"answer_id": 134891,
"author": "AndrewJFord",
"author_id": 6154,
"author_profile": "https://Stackoverflow.com/users/6154",
"pm_score": 3,
"selected": false,
"text": "<p>I would use the <a href=\"http://metacpan.org/pod/LWP::Simple\" rel=\"nofollow noreferrer\">LWP::Simple</a> module.</p>\n"
},
{
"answer_id": 134901,
"author": "coppro",
"author_id": 16855,
"author_profile": "https://Stackoverflow.com/users/16855",
"pm_score": 2,
"selected": false,
"text": "<p>Try the <a href=\"https://metacpan.org/pod/HTTP::Request\" rel=\"nofollow noreferrer\">HTTP::Request</a> module. \nInstances of this class are usually passed to the request() method of an LWP::UserAgent object.</p>\n"
},
{
"answer_id": 134911,
"author": "Barry Brown",
"author_id": 17312,
"author_profile": "https://Stackoverflow.com/users/17312",
"pm_score": 4,
"selected": false,
"text": "<p>LWP::Simple has the function you're looking for.</p>\n\n<pre><code>use LWP::Simple;\n$content = get($url);\ndie \"Can't GET $url\" if (! defined $content);\n</code></pre>\n"
},
{
"answer_id": 18908775,
"author": "Dave Horner",
"author_id": 1937339,
"author_profile": "https://Stackoverflow.com/users/1937339",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://search.cpan.org/perldoc?Mojo%3a%3aUserAgent\" rel=\"nofollow\">Mojo::UserAgent</a> is a great option too!</p>\n\n<pre><code> use Mojo::UserAgent;\n my $ua = Mojo::UserAgent->new;\n\n # Say hello to the Unicode snowman with \"Do Not Track\" header\n say $ua->get('www.☃.net?hello=there' => {DNT => 1})->res->body;\n\n # Form POST with exception handling\n my $tx = $ua->post('https://metacpan.org/search' => form => {q => 'mojo'});\n if (my $res = $tx->success) { say $res->body }\n else {\n my ($err, $code) = $tx->error;\n say $code ? \"$code response: $err\" : \"Connection error: $err\";\n }\n\n # Quick JSON API request with Basic authentication\n say $ua->get('https://sri:[email protected]/search.json?q=perl')\n ->res->json('/results/0/title');\n\n # Extract data from HTML and XML resources\n say $ua->get('www.perl.org')->res->dom->html->head->title->text;`\n</code></pre>\n\n<p>Samples direct from CPAN page. I used this when I couldn 't get LWP::Simple to work on my machine.</p>\n"
},
{
"answer_id": 29163199,
"author": "Srihari Karanth",
"author_id": 1447507,
"author_profile": "https://Stackoverflow.com/users/1447507",
"pm_score": 1,
"selected": false,
"text": "<p>If it's in Unix and if LWP::Simple isn't installed, you can try:</p>\n\n<pre><code>my $content = `GET \"http://trackMyPhones.com/\"`;\n</code></pre>\n"
},
{
"answer_id": 35093522,
"author": "tboz203",
"author_id": 1445042,
"author_profile": "https://Stackoverflow.com/users/1445042",
"pm_score": 1,
"selected": false,
"text": "<p>I think <a href=\"https://stackoverflow.com/questions/134858/whats-the-simplest-way-to-make-a-http-get-request-in-perl/29163199#29163199\">what Srihari might be referencing</a> is <a href=\"https://www.gnu.org/software/wget/\" rel=\"nofollow noreferrer\">Wget</a>, but I would actually recommend (again, on *nix without LWP::Simple) to use <a href=\"http://curl.haxx.se/\" rel=\"nofollow noreferrer\">cURL</a>:</p>\n\n<pre><code>$ my $content = `curl -s \"http://google.com\"`;\n<HTML><HEAD><meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\">\n<TITLE>301 Moved</TITLE></HEAD><BODY>\n<H1>301 Moved</H1>\nThe document has moved\n<A HREF=\"http://www.google.com/\">here</A>.\n</BODY></HTML>\n</code></pre>\n\n<p>The <code>-s</code> flag tells curl to be silent. Otherwise, you get curl's progress bar output on standard error every time.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14569/"
]
| I have some code I've written in PHP for consuming our simple webservice, which I'd also like to provide in Perl for users who may prefer that language. What's the simplest method of making a HTTP request to do that? In PHP I can do it in one line with `file_get_contents()`.
Here's the entire code I want to port to Perl:
```php
/**
* Makes a remote call to the our API, and returns the response
* @param cmd {string} - command string ID
* @param argsArray {array} - associative array of argument names and argument values
* @return {array} - array of responses
*/
function callAPI( $cmd, $argsArray=array() )
{
$apikey="MY_API_KEY";
$secret="MY_SECRET";
$apiurl="https://foobar.com/api";
// timestamp this API was submitted (for security reasons)
$epoch_time=time();
//--- assemble argument array into string
$query = "cmd=" .$cmd;
foreach ($argsArray as $argName => $argValue) {
$query .= "&" . $argName . "=" . urlencode($argValue);
}
$query .= "&key=". $apikey . "&time=" . $epoch_time;
//--- make md5 hash of the query + secret string
$md5 = md5($query . $secret);
$url = $apiurl . "?" . $query . "&md5=" . $md5;
//--- make simple HTTP GET request, put the server response into $response
$response = file_get_contents($url);
//--- convert "|" (pipe) delimited string to array
$responseArray = explode("|", $response);
return $responseArray;
}
``` | LWP::Simple:
```
use LWP::Simple;
$contents = get("http://YOUR_URL_HERE");
``` |
134,866 | <p>I have a mindmp file from a target's application crash. Is it possible for me to rebuild the dll/pdb files for a version of software and have windbg load symbols correctly? </p>
<p>My problem is that our pdb files are only kept for major releases (unfortunately). This is a daily build, which I can rebuild myself, but I'm getting tripped up on errors.</p>
<p>With !sym noisy on:
"image header does not match memory image header."</p>
<pre><code>DBGENG: C:\...\XXX.dll image header does not match memory image header.
DBGENG: XXX.dll - Partial symbol image load missing image info
DBGHELP: Module is not fully loaded into memory.
DBGHELP: Searching for symbols using debugger-provided data.
DBGHELP: C:\...\XXX.pdb - mismatched pdb
</code></pre>
<p>Note I've build the pdb with the dll, they are from the same RELEASE directory (should I be building debug?)</p>
<p>Theses are release builds (as release builds are installed on the target and crashing) should I be somehow using the debug build dlls to get more symbol information?</p>
| [
{
"answer_id": 134928,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 4,
"selected": true,
"text": "<p>In my experience probably not.</p>\n\n<p>If you have the exact build directory and build with the <strong>exact same</strong> compiler settings then this might work. You definitely will not be able to load symbols from a debug build against a release crash dump.</p>\n\n<p>You will need to turn on the 'load anything' options: .symopt+0x40 to get windbg to ignore the timestamp differences.</p>\n"
},
{
"answer_id": 160818,
"author": "SteveMan",
"author_id": 5994,
"author_profile": "https://Stackoverflow.com/users/5994",
"pm_score": 4,
"selected": false,
"text": "<p>The <a href=\"http://www.debuginfo.com/tools/chkmatch.html\" rel=\"noreferrer\" title=\"ChkMatch\">ChkMatch</a> utility is designed for this exact scenario.\nAs long as you have the original .EXE, you can recompile the sources (with the same compiler and compiler settings) and patch the new .PDB to match the old .EXE.</p>\n\n<p>In this example, <em>OriginalExecutable.exe</em> is the executable that no longer has a .PDB file, and <em>RebuiltPDB.pdb</em> is one that has been produced by rebuilding the original source.</p>\n\n<pre><code>chkmatch -m OriginalExecutable.exe RebuiltPDB.pdb\n</code></pre>\n\n<p>Now, as long as the two files have their original names, The debugger should accept them as a matching pair.</p>\n"
},
{
"answer_id": 201821,
"author": "Roger Lipscombe",
"author_id": 8446,
"author_profile": "https://Stackoverflow.com/users/8446",
"pm_score": 1,
"selected": false,
"text": "<p>PDB files are tied to their EXE files by a GUID and an \"age\" (it's a sequence number). These are embedded in the EXE, and into the PDB. The GUID is regenerated on each complete build, and the \"age\" is changed on each incremental build.</p>\n\n<p>The debugger uses these to ensure that it's looking at the correct PDB for the EXE file.</p>\n\n<p>I didn't know about the \"chkmatch\" tool mentioned by SteveMan, but I suspect that it works by patching up the GUID/age so that they match.</p>\n"
},
{
"answer_id": 233306,
"author": "mikhailitsky",
"author_id": 26114,
"author_profile": "https://Stackoverflow.com/users/26114",
"pm_score": 2,
"selected": false,
"text": "<p>if you still have the exact source code the image was compiled from, then rebuild it producing a new pdb file and then instruct WinDbg to forcibly load this pdb when you open the crash dump - it worked once in my practice.</p>\n"
},
{
"answer_id": 21099781,
"author": "Dan K",
"author_id": 328285,
"author_profile": "https://Stackoverflow.com/users/328285",
"pm_score": 0,
"selected": false,
"text": "<p>This is too late to help Doug, but for the sake of anyone who comes across this question, another thread (<a href=\"https://stackoverflow.com/questions/3660084/is-it-possible-to-load-mismatched-symbols-in-visual-studio\">Is it possible to load mismatched symbols in Visual Studio?</a>) pointed out a way to get WinDbg to accept mismatched .PDB files</p>\n\n<pre><code>.symopt_0x40\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8123/"
]
| I have a mindmp file from a target's application crash. Is it possible for me to rebuild the dll/pdb files for a version of software and have windbg load symbols correctly?
My problem is that our pdb files are only kept for major releases (unfortunately). This is a daily build, which I can rebuild myself, but I'm getting tripped up on errors.
With !sym noisy on:
"image header does not match memory image header."
```
DBGENG: C:\...\XXX.dll image header does not match memory image header.
DBGENG: XXX.dll - Partial symbol image load missing image info
DBGHELP: Module is not fully loaded into memory.
DBGHELP: Searching for symbols using debugger-provided data.
DBGHELP: C:\...\XXX.pdb - mismatched pdb
```
Note I've build the pdb with the dll, they are from the same RELEASE directory (should I be building debug?)
Theses are release builds (as release builds are installed on the target and crashing) should I be somehow using the debug build dlls to get more symbol information? | In my experience probably not.
If you have the exact build directory and build with the **exact same** compiler settings then this might work. You definitely will not be able to load symbols from a debug build against a release crash dump.
You will need to turn on the 'load anything' options: .symopt+0x40 to get windbg to ignore the timestamp differences. |
134,882 | <p>How do I easily undo a git rebase? A lengthy manual method is:</p>
<ol>
<li>checkout the commit parent to both of the branches</li>
<li>create and checkout a temporary branch</li>
<li>cherry-pick all commits by hand</li>
<li>reset the faulty rebased branch to point to the temporary branch</li>
</ol>
<p>In my current situation, this works because I can easily spot commits from both branches (one was my stuff, the other was my colleague's stuff). However, my approach strikes me as suboptimal and error-prone (let's say I had just rebased with two of my own branches).</p>
<p>Clarification: I am talking about a rebase during which <em>multiple</em> commits were replayed, not only one.</p>
| [
{
"answer_id": 135614,
"author": "CB Bailey",
"author_id": 19563,
"author_profile": "https://Stackoverflow.com/users/19563",
"pm_score": 13,
"selected": true,
"text": "<p>The easiest way would be to find the head commit of the branch as it was immediately before the rebase started in the <a href=\"https://git-scm.com/docs/git-reflog\" rel=\"noreferrer\">reflog</a>...</p>\n<pre><code>git reflog\n</code></pre>\n<p>and to reset the current branch to it (with the usual caveats about being absolutely sure before reseting with the <code>--hard</code> option).</p>\n<p>Suppose the old commit was <code>HEAD@{2}</code> in the ref log:</p>\n<pre><code>git reset --hard HEAD@{2}\n</code></pre>\n<p><em>In Windows, you may need to quote the reference:</em></p>\n<pre><code>git reset --hard "HEAD@{2}"\n</code></pre>\n<p>You can check the history of the candidate old head by just doing a <code>git log HEAD@{2}</code> (<em>Windows:</em> <code>git log "HEAD@{2}"</code>).</p>\n<p>If you've not disabled per branch reflogs you should be able to simply do <code>git reflog branchname@{1}</code> as a rebase detaches the branch head before reattaching to the final head. I would double check this, though as I haven't verified this recently.</p>\n<p>Per default, all reflogs are activated for non-bare repositories:</p>\n<pre><code>[core]\n logAllRefUpdates = true\n</code></pre>\n"
},
{
"answer_id": 136332,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": false,
"text": "<p>For multiple commits, remember that any commit references all the history leading up to that commit. So in Charles' answer, read \"the old commit\" as \"the newest of the old commits\". If you reset to that commit, then all the history leading up to that commit will reappear. This should do what you want.</p>\n"
},
{
"answer_id": 137363,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 7,
"selected": false,
"text": "<p>Resetting the branch to the dangling commit object of its old tip is of course the best solution, because it restores the previous state without expending any effort. But if you happen to have lost those commits (f.ex. because you garbage-collected your repository in the meantime, or this is a fresh clone), you can always rebase the branch again. The key to this is the <code>--onto</code> switch.</p>\n\n<p>Let’s say you had a topic branch imaginatively called <code>topic</code>, that you branched off <code>master</code> when the tip of <code>master</code> was the <code>0deadbeef</code> commit. At some point while on the <code>topic</code> branch, you did <code>git rebase master</code>. Now you want to undo this. Here’s how:</p>\n\n<pre><code>git rebase --onto 0deadbeef master topic\n</code></pre>\n\n<p>This will take all commits on <code>topic</code> that aren’t on <code>master</code> and replay them on top of <code>0deadbeef</code>.</p>\n\n<p>With <code>--onto</code>, you can rearrange your history into pretty much <em>any shape whatsoever</em>.</p>\n\n<p>Have fun. :-)</p>\n"
},
{
"answer_id": 692763,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": 11,
"selected": false,
"text": "<p>Actually, rebase saves your starting point to <code>ORIG_HEAD</code> so this is usually as simple as:</p>\n\n<pre><code>git reset --hard ORIG_HEAD\n</code></pre>\n\n<p>However, the <code>reset</code>, <code>rebase</code> and <code>merge</code> all save your original <code>HEAD</code> pointer into <code>ORIG_HEAD</code> so, if you've done any of those commands since the rebase you're trying to undo then you'll have to use the reflog.</p>\n"
},
{
"answer_id": 854840,
"author": "Alex Gontmakher",
"author_id": 98510,
"author_profile": "https://Stackoverflow.com/users/98510",
"pm_score": 6,
"selected": false,
"text": "<p>I actually put a backup tag on the branch before I do any nontrivial operation (most rebases are trivial, but I'd do that if it looks anywhere complex).</p>\n\n<p>Then, restoring is as easy as <code>git reset --hard BACKUP</code>.</p>\n"
},
{
"answer_id": 1189779,
"author": "Allan",
"author_id": 139035,
"author_profile": "https://Stackoverflow.com/users/139035",
"pm_score": 9,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/a/135614/259206\">Charles's answer</a> works, but you may want to do this:</p>\n<pre><code>git rebase --abort\n</code></pre>\n<p>to clean up after the <code>reset</code>.</p>\n<p>Otherwise, you may get the message “<code>Interactive rebase already started</code>”.</p>\n"
},
{
"answer_id": 9362339,
"author": "Kris",
"author_id": 22237,
"author_profile": "https://Stackoverflow.com/users/22237",
"pm_score": 5,
"selected": false,
"text": "<p>Using <code>reflog</code> didn't work for me.</p>\n\n<p>What worked for me was similar to as described <a href=\"http://www.bluemangolearning.com/blog/2009/03/recovering-from-a-disastrous-git-rebase-mistake/\" rel=\"noreferrer\">here</a>. Open the file in .git/logs/refs named after the branch that was rebased and find the line that contains \"rebase finsihed\", something like:</p>\n\n<pre><code>5fce6b51 88552c8f Kris Leech <[email protected]> 1329744625 +0000 rebase finished: refs/heads/integrate onto 9e460878\n</code></pre>\n\n<p>Checkout the second commit listed on the line.</p>\n\n<pre><code>git checkout 88552c8f\n</code></pre>\n\n<p>Once confirmed this contained my lost changes I branched and let out a sigh of relief.</p>\n\n<pre><code>git log\ngit checkout -b lost_changes\n</code></pre>\n"
},
{
"answer_id": 28997687,
"author": "Matheus Felipe",
"author_id": 2044035,
"author_profile": "https://Stackoverflow.com/users/2044035",
"pm_score": 4,
"selected": false,
"text": "<p>Following the solution of @Allan and @Zearin, I wish I could simply do a comment though but I don't enough reputation, so I have used the following command:</p>\n\n<p>Instead of doing <code>git rebase -i --abort</code> (note the <strong>-i</strong>) I had to simply do <code>git rebase --abort</code> (<strong>without</strong> the <strong>-i</strong>).</p>\n\n<p>Using both <code>-i</code> and <code>--abort</code> at the same time causes Git to show me a list of usage/options.</p>\n\n<p>So my previous and current branch status with this solution is:</p>\n\n<pre><code>matbhz@myPc /my/project/environment (branch-123|REBASE-i)\n$ git rebase --abort\n\nmatbhz@myPc /my/project/environment (branch-123)\n$\n</code></pre>\n"
},
{
"answer_id": 32823323,
"author": "Maksym",
"author_id": 3502543,
"author_profile": "https://Stackoverflow.com/users/3502543",
"pm_score": 7,
"selected": false,
"text": "<p>In case <strong>you had pushed your branch to remote repository</strong> (usually it's origin) and then you've done a succesfull rebase (without merge) (<code>git rebase --abort</code> gives \"No rebase in progress\") you can easily <strong>reset branch</strong> using \ncommand:</p>\n\n<blockquote>\n <p>git reset --hard origin/{branchName}</p>\n</blockquote>\n\n<p>Example:</p>\n\n<pre><code>$ ~/work/projects/{ProjectName} $ git status\nOn branch {branchName}\nYour branch is ahead of 'origin/{branchName}' by 135 commits.\n (use \"git push\" to publish your local commits)\n\nnothing to commit, working directory clean\n\n$ ~/work/projects/{ProjectName} $ git reset --hard origin/{branchName}\nHEAD is now at 6df5719 \"Commit message\".\n\n$ ~/work/projects/{ProjectName} $ git status\nOn branch {branchName}\nYour branch is up-to-date with 'origin/{branchName}.\n\nnothing to commit, working directory clean\n</code></pre>\n"
},
{
"answer_id": 35887419,
"author": "stevek-pro",
"author_id": 356759,
"author_profile": "https://Stackoverflow.com/users/356759",
"pm_score": -1,
"selected": false,
"text": "<p>If you mess something up within a git rebase, e.g. <code>git rebase --abort</code>, while you have uncommitted files, they will be lost and <code>git reflog</code> will not help. This happened to me and you will need to think outside the box here. If you are lucky like me and use IntelliJ Webstorm then you can <code>right-click->local history</code> and can revert to a previous state of your file/folders no matter what mistakes you have done with versioning software. It is always good to have another failsafe running.</p>\n"
},
{
"answer_id": 37987428,
"author": "Sergey P. aka azure",
"author_id": 1075459,
"author_profile": "https://Stackoverflow.com/users/1075459",
"pm_score": 4,
"selected": false,
"text": "<p>If you successfully rebased against a remote branch and can not <code>git rebase --abort</code> you still can do some tricks to save your work and don't have forced pushes.\nSuppose your current branch that was rebased by mistake is called <code>your-branch</code> and is tracking <code>origin/your-branch</code></p>\n<ul>\n<li><code>git branch -m your-branch-rebased</code> # rename current branch</li>\n<li><code>git checkout origin/your-branch</code> # checkout to latest state that is known to the origin</li>\n<li><code>git checkout -b your-branch</code></li>\n<li>check <code>git log your-branch-rebased</code>, compare to <code>git log your-branch</code>, and define commits that are missing from <code>your-branch</code></li>\n<li><code>git cherry-pick COMMIT_HASH</code> for every commit in <code>your-branch-rebased</code></li>\n<li>push your changes. Please be aware that two local branches are associated with <code>remote/your-branch</code> and you should push only <code>your-branch</code></li>\n</ul>\n"
},
{
"answer_id": 42136684,
"author": "Hardev",
"author_id": 1299948,
"author_profile": "https://Stackoverflow.com/users/1299948",
"pm_score": 2,
"selected": false,
"text": "<p>Let's say I rebase master to my feature branch and I get 30 new commits which break something. I've found that often it's easiest to just remove the bad commits.</p>\n\n<pre><code>git rebase -i HEAD~31\n</code></pre>\n\n<p>Interactive rebase for the last 31 commits (it doesn't hurt if you pick way too many).</p>\n\n<p>Simply take the commits that you want to get rid of and mark them with \"d\" instead of \"pick\". Now the commits are deleted effectively undoing the rebase (if you remove only the commits you just got when rebasing).</p>\n"
},
{
"answer_id": 54128623,
"author": "devconsole",
"author_id": 773189,
"author_profile": "https://Stackoverflow.com/users/773189",
"pm_score": 2,
"selected": false,
"text": "<p>If you are on a branch you can use:</p>\n\n<pre><code>git reset --hard @{1}\n</code></pre>\n\n<p>There is not only a reference log for HEAD (obtained by <code>git reflog</code>), there are also reflogs for each branch (obtained by <code>git reflog <branch></code>). So, if you are on <code>master</code> then <code>git reflog master</code> will list all changes to that branch. You can refer to that changes by <code>master@{1}</code>, <code>master@{2}</code>, etc.</p>\n\n<p><code>git rebase</code> will usually change HEAD multiple times but the current branch will be updated only once.</p>\n\n<p><code>@{1}</code> is simply a <a href=\"https://git-scm.com/docs/gitrevisions#gitrevisions-emltngtemegem1em\" rel=\"nofollow noreferrer\">shortcut for the current branch</a>, so it's equal to <code>master@{1}</code> if you are on <code>master</code>.</p>\n\n<p><code>git reset --hard ORIG_HEAD</code> will not work if you used <code>git reset</code> during an interactive <code>rebase</code>.</p>\n"
},
{
"answer_id": 56001129,
"author": "Damodar P",
"author_id": 11008980,
"author_profile": "https://Stackoverflow.com/users/11008980",
"pm_score": 6,
"selected": false,
"text": "<pre><code>git reset --hard origin/{branchName}\n</code></pre>\n<p>is the correct solution to reset all your local changes done by rebase.</p>\n"
},
{
"answer_id": 56366149,
"author": "Andrew",
"author_id": 3093731,
"author_profile": "https://Stackoverflow.com/users/3093731",
"pm_score": 4,
"selected": false,
"text": "<p><strong>If you don't want to do a hard reset</strong>...</p>\n<p>You can checkout the commit from the reflog, and then save it as a new branch:</p>\n<pre><code>git reflog\n</code></pre>\n<p>Find the commit just before you started rebasing. You may need to scroll further down to find it (press Enter or PageDown). Take note of the HEAD number and replace 57:</p>\n<pre><code>git checkout HEAD@{57}\n</code></pre>\n<p>Review the branch/commits, and if it's correct then create a new branch using this HEAD:</p>\n<pre><code>git checkout -b new_branch_name\n</code></pre>\n"
},
{
"answer_id": 56670315,
"author": "mrigendra",
"author_id": 2270386,
"author_profile": "https://Stackoverflow.com/users/2270386",
"pm_score": 2,
"selected": false,
"text": "<p>What I usually do is \n<code>git reset #commit_hash</code></p>\n\n<p>to the last commit where I think rebase had no effect.</p>\n\n<p>then <code>git pull</code></p>\n\n<p>Now your branch should match exactly like master and rebased commits should not be in it.</p>\n\n<p>Now one can just cherry-pick the commits on this branch.</p>\n"
},
{
"answer_id": 60252160,
"author": "user3638751",
"author_id": 3638751,
"author_profile": "https://Stackoverflow.com/users/3638751",
"pm_score": 1,
"selected": false,
"text": "<p>I tried all suggestions with reset and reflog without any success. Restoring local history of IntelliJ resolved the problem of lost files</p>\n"
},
{
"answer_id": 62986490,
"author": "DylanYoung",
"author_id": 3124256,
"author_profile": "https://Stackoverflow.com/users/3124256",
"pm_score": 2,
"selected": false,
"text": "<p>It annoys me to no end that none of these answers is fully automatic, despite the fact that it should be automatable (at least mostly). I created a set of aliases to try to remedy this:</p>\n<pre><code># Useful commands\n#################\n\n# Undo the last rebase\nundo-rebase = "! f() { : git reset ; PREV_COMMIT=`git x-rev-before-rebase` && git reset --merge \\"$PREV_COMMIT\\" \\"$@\\";}; f"\n\n# See what changed since the last rebase\nrdiff = "!f() { : git diff ; git diff `git x-rev-before-rebase` "$@";}; f"\n\n# Helpers\n########\n# Get the revision before the last rebase started\nx-rev-before-rebase = !git reflog --skip=1 -1 \\"`git x-start-of-rebase`\\" --format=\\"%gD\\"\n\n# Get the revision that started the rebase\nx-start-of-rebase = reflog --grep-reflog '^rebase (start)' -1 --format="%gD"\n</code></pre>\n<p>You should be able to tweak this to allow going back an arbitrary number of rebases pretty easily (juggling the args is the trickiest part), which can be useful if you do a number of rebases in quick succession and mess something up along the way.</p>\n<h2>Caveats</h2>\n<p>It will get confused if any commit messages begin with "rebase (start)" (please don't do this). You could make the regex more resilient to improve the situation by matching something like this for your regex:</p>\n<pre><code>--grep-reflog "^rebase (start): checkout " \n</code></pre>\n<p>WARNING: not tested (regex may need adjustments)</p>\n<p>The reason I haven't done this is because I'm not 100% that a rebase <em>always</em> begins with a checkout. Can anyone confirm this?</p>\n<p>[If you're curious about the null (<code>:</code>) commands at the beginning of the function, that's a way of setting up bash completions for the aliases]</p>\n"
},
{
"answer_id": 68217712,
"author": "GuyStalks",
"author_id": 4966536,
"author_profile": "https://Stackoverflow.com/users/4966536",
"pm_score": 3,
"selected": false,
"text": "<p>Another way <strong>that doesn't require doing a hard reset</strong> is to create a new branch with your desired starting point.</p>\n<p>As with the other solutions, you use the reflog to find the correct starting point.</p>\n<pre><code>git reflog\n</code></pre>\n<p>(you can also use <code>git log -g</code> here for more detail)</p>\n<p>Then you note the reference to the commit SHA (ex: <code>e86a52b851e</code>).</p>\n<p>Finally, you use the git branch command.</p>\n<pre><code>git branch recover-branch e86a52b851e\n</code></pre>\n<p>Reference: <a href=\"https://git-scm.com/book/en/v2/Git-Internals-Maintenance-and-Data-Recovery#_data_recovery\" rel=\"noreferrer\">https://git-scm.com/book/en/v2/Git-Internals-Maintenance-and-Data-Recovery#_data_recovery</a></p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6349/"
]
| How do I easily undo a git rebase? A lengthy manual method is:
1. checkout the commit parent to both of the branches
2. create and checkout a temporary branch
3. cherry-pick all commits by hand
4. reset the faulty rebased branch to point to the temporary branch
In my current situation, this works because I can easily spot commits from both branches (one was my stuff, the other was my colleague's stuff). However, my approach strikes me as suboptimal and error-prone (let's say I had just rebased with two of my own branches).
Clarification: I am talking about a rebase during which *multiple* commits were replayed, not only one. | The easiest way would be to find the head commit of the branch as it was immediately before the rebase started in the [reflog](https://git-scm.com/docs/git-reflog)...
```
git reflog
```
and to reset the current branch to it (with the usual caveats about being absolutely sure before reseting with the `--hard` option).
Suppose the old commit was `HEAD@{2}` in the ref log:
```
git reset --hard HEAD@{2}
```
*In Windows, you may need to quote the reference:*
```
git reset --hard "HEAD@{2}"
```
You can check the history of the candidate old head by just doing a `git log HEAD@{2}` (*Windows:* `git log "HEAD@{2}"`).
If you've not disabled per branch reflogs you should be able to simply do `git reflog branchname@{1}` as a rebase detaches the branch head before reattaching to the final head. I would double check this, though as I haven't verified this recently.
Per default, all reflogs are activated for non-bare repositories:
```
[core]
logAllRefUpdates = true
``` |
134,885 | <p>I'm looking to use a VBScript variable within a reference to a DOM element for a web-app I'm building. Here's a brief excerpt of the affected area of code:</p>
<pre><code>dim num
num = CInt(document.myform.i.value)
dim x
x = 0
dim orders(num)
For x = 0 To num
orders(x) = document.getElementById("order" & x).value
objFile.writeLine(orders(x))
Next
</code></pre>
<p>This is my first venture into VBScript, and I've not been able to find any methods of performing this type of action online. As you can see in the above code, I'm trying to create an array (orders). This array can have any number of values, but that number will be specified in <code>document.myform.i.value</code>. So the For loop cycles through all text inputs with an ID of order+x (ie, order0, order1, order2, order3, order4, etc. up to num)</p>
<p>It seems to be a problem with my orders(x) line, I don't think it recognizes what I mean by <code>getElementById("order" & x)</code>, and I'm not sure exactly how to do such a thing. Anyone have any suggestions? It would be much appreciated!</p>
| [
{
"answer_id": 134927,
"author": "Dan Williams",
"author_id": 4230,
"author_profile": "https://Stackoverflow.com/users/4230",
"pm_score": 0,
"selected": false,
"text": "<p>I can only assume that this is client side VBScript as document.getElementById() isn't accessible from the server.</p>\n\n<p>try objFile.writeLine(\"order\" & x), then check the source to make sure all the elements are in the document.</p>\n\n<p>[As I can't put code in comments...]\nThat is strange. It looks to me like everything should be working.</p>\n\n<p>Only other thing I can think of is: change</p>\n\n<pre><code>orders(x) = document.getElementById(\"order\" & x).value\nobjFile.writeLine(orders(x))\n</code></pre>\n\n<p>to</p>\n\n<pre><code>orders(x) = document.getElementById(\"order\" & x)\nobjFile.writeLine(orders(x).value)\n</code></pre>\n"
},
{
"answer_id": 136030,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 0,
"selected": false,
"text": "<p>It looks as if you're mixing client vs server-side code.</p>\n\n<pre><code>objFile.writeLine(orders(x))\n</code></pre>\n\n<p>That is VBScript to write to a file, which you can only do on the server.</p>\n\n<pre><code>document.getElementById\n</code></pre>\n\n<p>This is client-size code that is usually executed in JavaScript. You can use VBScript on IE on the client, but rarely does anyone do this.</p>\n\n<p>On the server you'd usually refer to form fields that were part of a form tag, not DOM elements, (assuming you're using classic ASP) using request(\"formFieldName\").</p>\n\n<p>To make server-side stuff appear on the client (when you build a page) you'd embed it in your HTML like this:</p>\n\n<pre><code><% = myVariable %>\n</code></pre>\n\n<p>or like this (as part of a code block):</p>\n\n<pre><code>document.write myVariable\n</code></pre>\n"
},
{
"answer_id": 139471,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I was able to get this working. Thanks to both of you for your time and input. Here is what solved it for me:</p>\n\n<p>Rather than using</p>\n\n<pre><code>document.getElementById(\"order\" & x).value\n</code></pre>\n\n<p>I set the entire ID as a variable:</p>\n\n<pre><code>temp = \"order\" & x\ndocument.getElementById(temp).value\n</code></pre>\n\n<p>It seems to be working as expected. Again, many thanks for the time and effort on this!</p>\n"
},
{
"answer_id": 208485,
"author": "Magnus Smith",
"author_id": 11461,
"author_profile": "https://Stackoverflow.com/users/11461",
"pm_score": 0,
"selected": false,
"text": "<p>Don't you need to change your loop slightly?</p>\n\n<pre><code>For x = 0 To num - 1\n</code></pre>\n\n<p>E.G. With 4 items you need to iterate from 0 to 3.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I'm looking to use a VBScript variable within a reference to a DOM element for a web-app I'm building. Here's a brief excerpt of the affected area of code:
```
dim num
num = CInt(document.myform.i.value)
dim x
x = 0
dim orders(num)
For x = 0 To num
orders(x) = document.getElementById("order" & x).value
objFile.writeLine(orders(x))
Next
```
This is my first venture into VBScript, and I've not been able to find any methods of performing this type of action online. As you can see in the above code, I'm trying to create an array (orders). This array can have any number of values, but that number will be specified in `document.myform.i.value`. So the For loop cycles through all text inputs with an ID of order+x (ie, order0, order1, order2, order3, order4, etc. up to num)
It seems to be a problem with my orders(x) line, I don't think it recognizes what I mean by `getElementById("order" & x)`, and I'm not sure exactly how to do such a thing. Anyone have any suggestions? It would be much appreciated! | I was able to get this working. Thanks to both of you for your time and input. Here is what solved it for me:
Rather than using
```
document.getElementById("order" & x).value
```
I set the entire ID as a variable:
```
temp = "order" & x
document.getElementById(temp).value
```
It seems to be working as expected. Again, many thanks for the time and effort on this! |
134,887 | <p>After making it through the major parts of an introductory Lisp book, I still couldn't understand what the special operator <code>(quote)</code> (or equivalent <code>'</code>) function does, yet this has been all over Lisp code that I've seen. </p>
<p>What does it do?</p>
| [
{
"answer_id": 134908,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 6,
"selected": false,
"text": "<p>It says \"don't evaluate me\". For example, if you wanted to use a list as data, and not as code, you'd put a quote in front of it. For example,</p>\n\n<p><code>(print '(+ 3 4))</code> prints \"(+ 3 4)\", whereas\n<code>(print (+ 3 4))</code> prints \"7\"</p>\n"
},
{
"answer_id": 134924,
"author": "Kyle Burton",
"author_id": 19784,
"author_profile": "https://Stackoverflow.com/users/19784",
"pm_score": 4,
"selected": false,
"text": "<p>The quote prevents execution or evaluation of a form, turning it instead into data. In general you can execute the data by then eval'ing it.</p>\n\n<p>quote creates list data structures, for example, the following are equivalent:</p>\n\n<pre><code>(quote a)\n'a\n</code></pre>\n\n<p>It can also be used to create lists (or trees):</p>\n\n<pre><code>(quote (1 2 3))\n'(1 2 3)\n</code></pre>\n\n<p>You're probably best off getting an introductary book on lisp, such as <a href=\"http://gigamonkeys.com/book/\" rel=\"noreferrer\">Practical Common Lisp</a> (which is available to read on-line).</p>\n"
},
{
"answer_id": 136200,
"author": "Matthias Benkard",
"author_id": 15517,
"author_profile": "https://Stackoverflow.com/users/15517",
"pm_score": 4,
"selected": false,
"text": "<p>One answer to this question says that QUOTE “creates list data structures”. This isn't quite right. QUOTE is more fundamental than this. In fact, QUOTE is a trivial operator: Its purpose is to <em>prevent</em> anything from happening at all. In particular, it doesn't create anything.</p>\n\n<p>What (QUOTE X) says is basically “don't do anything, just give me X.” X needn't be a list as in (QUOTE (A B C)) or a symbol as in (QUOTE FOO). It can be any object whatever. Indeed, the result of evaluating the list that is produced by (LIST 'QUOTE SOME-OBJECT) will always just return SOME-OBJECT, whatever it is.</p>\n\n<p>Now, the reason that (QUOTE (A B C)) seems as if it created a list whose elements are A, B, and C is that such a list really is what it returns; but at the time the QUOTE form is evaluated, the list has generally already been in existence for a while (as a component of the QUOTE form!), created either by the loader or the reader prior to execution of the code.</p>\n\n<p>One implication of this that tends to trip up newbies fairly often is that it's very unwise to modify a list returned by a QUOTE form. Data returned by QUOTE is, for all intents and purposes, to be considered as part of the <em>code</em> being executed and should therefore be treated as read-only!</p>\n"
},
{
"answer_id": 137774,
"author": "Mikael Jansson",
"author_id": 18753,
"author_profile": "https://Stackoverflow.com/users/18753",
"pm_score": 9,
"selected": true,
"text": "<p><strong>Short answer</strong>\nBypass the default evaluation rules and do <em>not</em> evaluate the expression (symbol or s-exp), passing it along to the function exactly as typed.</p>\n\n<p><strong>Long Answer: The Default Evaluation Rule</strong></p>\n\n<p>When a regular (I'll come to that later) function is invoked, all arguments passed to it are evaluated. This means you can write this:</p>\n\n<pre><code>(* (+ a 2)\n 3)\n</code></pre>\n\n<p>Which in turn evaluates <code>(+ a 2)</code>, by evaluating <code>a</code> and 2. The value of the symbol <code>a</code> is looked up in the current variable binding set, and then replaced. Say <code>a</code> is currently bound to the value 3:</p>\n\n<pre><code>(let ((a 3))\n (* (+ a 2)\n 3))\n</code></pre>\n\n<p>We'd get <code>(+ 3 2)</code>, + is then invoked on 3 and 2 yielding 5. Our original form is now <code>(* 5 3)</code> yielding 15.</p>\n\n<p><strong>Explain <code>quote</code> Already!</strong></p>\n\n<p>Alright. As seen above, all arguments to a function are evaluated, so if you would like to pass the <em>symbol</em> <code>a</code> and not its value, you don't want to evaluate it. Lisp symbols can double both as their values, and markers where you in other languages would have used strings, such as keys to hash tables.</p>\n\n<p>This is where <code>quote</code> comes in. Say you want to plot resource allocations from a Python application, but rather do the plotting in Lisp. Have your Python app do something like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(\"'(\")\nwhile allocating:\n if random.random() > 0.5:\n print(f\"(allocate {random.randint(0, 20)})\")\n else:\n print(f\"(free {random.randint(0, 20)})\")\n ...\nprint(\")\")\n</code></pre>\n\n<p>Giving you output looking like this (slightly prettyfied):</p>\n\n<pre><code>'((allocate 3)\n (allocate 7)\n (free 14)\n (allocate 19)\n ...)\n</code></pre>\n\n<p>Remember what I said about <code>quote</code> (\"tick\") causing the default rule not to apply? Good. What would otherwise happen is that the values of <code>allocate</code> and <code>free</code> are looked up, and we don't want that. In our Lisp, we wish to do:</p>\n\n<pre><code>(dolist (entry allocation-log)\n (case (first entry)\n (allocate (plot-allocation (second entry)))\n (free (plot-free (second entry)))))\n</code></pre>\n\n<p>For the data given above, the following sequence of function calls would have been made:</p>\n\n<pre><code>(plot-allocation 3)\n(plot-allocation 7)\n(plot-free 14)\n(plot-allocation 19)\n</code></pre>\n\n<p><strong>But What About <code>list</code>?</strong></p>\n\n<p>Well, sometimes you <em>do</em> want to evaluate the arguments. Say you have a nifty function manipulating a number and a string and returning a list of the resulting ... things. Let's make a false start:</p>\n\n<pre><code>(defun mess-with (number string)\n '(value-of-number (1+ number) something-with-string (length string)))\n\nLisp> (mess-with 20 \"foo\")\n(VALUE-OF-NUMBER (1+ NUMBER) SOMETHING-WITH-STRING (LENGTH STRING))\n</code></pre>\n\n<p>Hey! That's not what we wanted. We want to <em>selectively</em> evaluate some arguments, and leave the others as symbols. Try #2!</p>\n\n<pre><code>(defun mess-with (number string)\n (list 'value-of-number (1+ number) 'something-with-string (length string)))\n\nLisp> (mess-with 20 \"foo\")\n(VALUE-OF-NUMBER 21 SOMETHING-WITH-STRING 3)\n</code></pre>\n\n<p><strong>Not Just <code>quote</code>, But <code>backquote</code></strong></p>\n\n<p>Much better! Incidently, this pattern is so common in (mostly) macros, that there is special syntax for doing just that. The backquote:</p>\n\n<pre><code>(defun mess-with (number string)\n `(value-of-number ,(1+ number) something-with-string ,(length string)))\n</code></pre>\n\n<p>It's like using <code>quote</code>, but with the option to explicitly evaluate some arguments by prefixing them with comma. The result is equivalent to using <code>list</code>, but if you're generating code from a macro you often only want to evaluate small parts of the code returned, so the backquote is more suited. For shorter lists, <code>list</code> can be more readable.</p>\n\n<p><strong>Hey, You Forgot About <code>quote</code>!</strong></p>\n\n<p>So, where does this leave us? Oh right, what does <code>quote</code> actually do? It simply returns its argument(s) unevaluated! Remember what I said in the beginning about regular functions? Turns out that some operators/functions need to <em>not</em> evaluate their arguments. Such as IF -- you wouldn't want the else branch to be evaluated if it wasn't taken, right? So-called <em>special operators</em>, together with macros, work like that. Special operators are also the \"axiom\" of the language -- minimal set of rules -- upon which you can implement the rest of Lisp by combining them together in different ways. </p>\n\n<p>Back to <code>quote</code>, though:</p>\n\n<pre><code>Lisp> (quote spiffy-symbol)\nSPIFFY-SYMBOL\n\nLisp> 'spiffy-symbol ; ' is just a shorthand (\"reader macro\"), as shown above\nSPIFFY-SYMBOL\n</code></pre>\n\n<p>Compare to (on Steel-Bank Common Lisp):</p>\n\n<pre><code>Lisp> spiffy-symbol\ndebugger invoked on a UNBOUND-VARIABLE in thread #<THREAD \"initial thread\" RUNNING {A69F6A9}>:\n The variable SPIFFY-SYMBOL is unbound.\n\nType HELP for debugger help, or (SB-EXT:QUIT) to exit from SBCL.\n\nrestarts (invokable by number or by possibly-abbreviated name):\n 0: [ABORT] Exit debugger, returning to top level.\n\n(SB-INT:SIMPLE-EVAL-IN-LEXENV SPIFFY-SYMBOL #<NULL-LEXENV>)\n0] \n</code></pre>\n\n<p>Because there is no <code>spiffy-symbol</code> in the current scope!</p>\n\n<p><strong>Summing Up</strong></p>\n\n<p><code>quote</code>, <code>backquote</code> (with comma), and <code>list</code> are some of the tools you use to create lists, that are not only lists of values, but as you seen can be used as lightweight (no need to define a <code>struct</code>) data structures!</p>\n\n<p>If you wish to learn more, I recommend Peter Seibel's book <a href=\"http://gigamonkeys.com/book\" rel=\"noreferrer\">Practical Common Lisp</a> for a practical approach to learning Lisp, if you're already into programming at large. Eventually on your Lisp journey, you'll start using packages too. Ron Garret's <a href=\"http://www.flownet.com/ron/packages.pdf\" rel=\"noreferrer\">The Idiot's Guide to Common Lisp Packages</a> will give you good explanation of those.</p>\n\n<p>Happy hacking!</p>\n"
},
{
"answer_id": 578365,
"author": "Xanthir",
"author_id": 58347,
"author_profile": "https://Stackoverflow.com/users/58347",
"pm_score": 4,
"selected": false,
"text": "<p>Other people have answered this question admirably, and Matthias Benkard brings up an excellent warning.</p>\n\n<p>DO NOT USE QUOTE TO CREATE LISTS THAT YOU WILL LATER MODIFY. The spec allows the compiler to treat quoted lists as constants. Often, a compiler will optimize constants by creating a single value for them in memory and then referencing that single value from all locations where the constant appears. In other words, it may treat the constant like an anonymous global variable.</p>\n\n<p>This can cause obvious problems. If you modify a constant, it may very well modify other uses of the same constant in completely unrelated code. For example, you may compare some variable to '(1 1) in some function, and in a completely different function, start a list with '(1 1) and then add more stuff to it. Upon running these functions, you may find that the first function doesn't match things properly anymore, because it's now trying to compare the variable to '(1 1 2 3 5 8 13), which is what the second function returned. These two functions are completely unrelated, but they have an effect on each other because of the use of constants. Even crazier bad effects can happen, like a perfectly normal list iteration suddenly infinite looping.</p>\n\n<p>Use quote when you need a constant list, such as for comparison. Use list when you will be modifying the result.</p>\n"
},
{
"answer_id": 24093979,
"author": "unknownerror",
"author_id": 2960555,
"author_profile": "https://Stackoverflow.com/users/2960555",
"pm_score": 2,
"selected": false,
"text": "<p>When we want to pass an argument itself instead of passing the value of the argument then we use quote. It is mostly related to the procedure passing during using lists, pairs and atoms\nwhich are not available in C programming Language ( most people start programming using C programming, Hence we get confused) \nThis is code in Scheme programming language which is a dialect of lisp and I guess you can understand this code.</p>\n\n<pre><code>(define atom? ; defining a procedure atom?\n (lambda (x) ; which as one argument x\n(and (not (null? x)) (not(pair? x) )))) ; checks if the argument is atom or not\n(atom? '(a b c)) ; since it is a list it is false #f\n</code></pre>\n\n<p>The last line (atom? 'abc) is passing abc as it is to the procedure to check if abc is an atom or not, but when you pass(atom? abc) then it checks for the value of abc and passses the value to it. Since, we haven't provided any value to it </p>\n"
},
{
"answer_id": 30179668,
"author": "Steve",
"author_id": 4889380,
"author_profile": "https://Stackoverflow.com/users/4889380",
"pm_score": 1,
"selected": false,
"text": "<p>Quote returns the internal representation of its arguments. After plowing through way too many explanations of what quote <em>doesn't</em> do, that's when the light-bulb went on. If the REPL didn't convert function names to UPPER-CASE when I quoted them, it might not have dawned on me.</p>\n\n<p>So. Ordinary Lisp functions convert their arguments into an internal representation, evaluate the arguments, and apply the function. Quote converts its arguments to an internal representation, and just returns that. Technically it's correct to say that quote says, \"don't evaluate\", but when I was trying to understand what it did, telling me what it doesn't do was frustrating. My toaster doesn't evaluate Lisp functions either; but that's not how you explain what a toaster does.</p>\n"
},
{
"answer_id": 35542683,
"author": "Andrew_1510",
"author_id": 451718,
"author_profile": "https://Stackoverflow.com/users/451718",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Anoter short answer:</strong></p>\n\n<p><code>quote</code> means without evaluating it, and <em>backquote</em> is quote but leave <em>back doors</em>.</p>\n\n<p><strong>A good referrence:</strong></p>\n\n<p>Emacs Lisp Reference Manual make it very clear</p>\n\n<p>9.3 Quoting</p>\n\n<p>The special form quote returns its single argument, as written, without evaluating it. This provides a way to include constant symbols and lists, which are not self-evaluating objects, in a program. (It is not necessary to quote self-evaluating objects such as numbers, strings, and vectors.)</p>\n\n<p>Special Form: quote object</p>\n\n<pre><code>This special form returns object, without evaluating it. \n</code></pre>\n\n<p>Because quote is used so often in programs, Lisp provides a convenient read syntax for it. An apostrophe character (‘'’) followed by a Lisp object (in read syntax) expands to a list whose first element is quote, and whose second element is the object. Thus, the read syntax 'x is an abbreviation for (quote x).</p>\n\n<p>Here are some examples of expressions that use quote:</p>\n\n<pre><code>(quote (+ 1 2))\n ⇒ (+ 1 2)\n\n(quote foo)\n ⇒ foo\n\n'foo\n ⇒ foo\n\n''foo\n ⇒ (quote foo)\n\n'(quote foo)\n ⇒ (quote foo)\n</code></pre>\n\n<p>9.4 Backquote</p>\n\n<p>Backquote constructs allow you to quote a list, but selectively evaluate elements of that list. In the simplest case, it is identical to the special form quote (described in the previous section; see Quoting). For example, these two forms yield identical results: </p>\n\n<pre><code>`(a list of (+ 2 3) elements)\n ⇒ (a list of (+ 2 3) elements)\n\n'(a list of (+ 2 3) elements)\n ⇒ (a list of (+ 2 3) elements)\n</code></pre>\n\n<p>The special marker ‘,’ inside of the argument to backquote indicates a value that isn’t constant. The Emacs Lisp evaluator evaluates the argument of ‘,’, and puts the value in the list structure:</p>\n\n<pre><code>`(a list of ,(+ 2 3) elements)\n ⇒ (a list of 5 elements)\n</code></pre>\n\n<p>Substitution with ‘,’ is allowed at deeper levels of the list structure also. For example:</p>\n\n<pre><code>`(1 2 (3 ,(+ 4 5)))\n ⇒ (1 2 (3 9))\n</code></pre>\n\n<p>You can also splice an evaluated value into the resulting list, using the special marker ‘,@’. The elements of the spliced list become elements at the same level as the other elements of the resulting list. The equivalent code without using ‘`’ is often unreadable. Here are some examples:</p>\n\n<pre><code>(setq some-list '(2 3))\n ⇒ (2 3)\n\n(cons 1 (append some-list '(4) some-list))\n ⇒ (1 2 3 4 2 3)\n\n`(1 ,@some-list 4 ,@some-list)\n ⇒ (1 2 3 4 2 3)\n</code></pre>\n"
},
{
"answer_id": 35682547,
"author": "jhegedus",
"author_id": 1198559,
"author_profile": "https://Stackoverflow.com/users/1198559",
"pm_score": 2,
"selected": false,
"text": "<p><strong>In Emacs Lisp:</strong></p>\n\n<p><strong>What can be quoted ?</strong> </p>\n\n<p>Lists and symbols.</p>\n\n<p>Quoting a number evaluates to the number itself:\n<code>'5</code> is the same as <code>5</code>.</p>\n\n<p><strong>What happens when you quote lists ?</strong></p>\n\n<p>For example:</p>\n\n<p><code>'(one two)</code> evaluates to </p>\n\n<p><code>(list 'one 'two)</code> which evaluates to </p>\n\n<p><code>(list (intern \"one\") (intern (\"two\")))</code>.</p>\n\n<p><code>(intern \"one\")</code> creates a symbol named \"one\" and stores it in a \"central\" hash-map, so anytime you say <code>'one</code> then the symbol named <code>\"one\"</code> will be looked up in that central hash-map.</p>\n\n<p><strong>But what is a symbol ?</strong></p>\n\n<p>For example, in OO-languages (Java/Javascript/Python) a symbol could be represented as an object that has a <code>name</code> field, which is the symbol's name like <code>\"one\"</code> above, and data and/or code can be associated with it this object.</p>\n\n<p>So an symbol in Python could be implemented as:</p>\n\n<pre><code>class Symbol:\n def __init__(self,name,code,value):\n self.name=name\n self.code=code\n self.value=value\n</code></pre>\n\n<p>In Emacs Lisp for example a symbol can have 1) data associated with it AND (at the same time - for the same symbol) 2) code associated with it - depending on the context, either the data or the code gets called.</p>\n\n<p>For example, in Elisp:</p>\n\n<pre><code>(progn\n (fset 'add '+ )\n (set 'add 2)\n (add add add)\n)\n</code></pre>\n\n<p>evaluates to <code>4</code>. </p>\n\n<p>Because <code>(add add add)</code> evaluates as:</p>\n\n<pre><code>(add add add)\n(+ add add)\n(+ 2 add)\n(+ 2 2)\n4\n</code></pre>\n\n<p>So, for example, using the <code>Symbol</code> class we defined in Python above, this <code>add</code> ELisp-Symbol could be written in Python as <code>Symbol(\"add\",(lambda x,y: x+y),2)</code>.</p>\n\n<p>Many thanks for folks on IRC #emacs for explaining symbols and quotes to me.</p>\n"
},
{
"answer_id": 56653324,
"author": "alinsoar",
"author_id": 1419272,
"author_profile": "https://Stackoverflow.com/users/1419272",
"pm_score": 2,
"selected": false,
"text": "<pre><code>Code is data and data is code. There is no clear distinction between them.\n</code></pre>\n\n<p>This is a classical statement any lisp programmer knows.</p>\n\n<p>When you quote a code, that code will be data.</p>\n\n<pre><code>1 ]=> '(+ 2 3 4)\n;Value: (+ 2 3 4)\n\n1 ]=> (+ 2 3 4)\n;Value: 9\n</code></pre>\n\n<p>When you quote a code, the result will be data that represent that code. So, when you want to work with data that represents a program you quote that program. This is also valid for atomic expressions, not only for lists:</p>\n\n<pre><code>1 ]=> 'code\n;Value: code\n\n1 ]=> '10\n;Value: 10\n\n1 ]=> '\"ok\"\n;Value: \"ok\"\n\n1 ]=> code\n;Unbound variable: code\n</code></pre>\n\n<p>Supposing you want to create a programming language embedded in lisp -- you will work with programs that are quoted in scheme (like <code>'(+ 2 3)</code>) and that are interpreted as code in the language you create, by giving programs a semantic interpretation. In this case you need to use quote to keep the data, otherwise it will be evaluated in external language.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1256/"
]
| After making it through the major parts of an introductory Lisp book, I still couldn't understand what the special operator `(quote)` (or equivalent `'`) function does, yet this has been all over Lisp code that I've seen.
What does it do? | **Short answer**
Bypass the default evaluation rules and do *not* evaluate the expression (symbol or s-exp), passing it along to the function exactly as typed.
**Long Answer: The Default Evaluation Rule**
When a regular (I'll come to that later) function is invoked, all arguments passed to it are evaluated. This means you can write this:
```
(* (+ a 2)
3)
```
Which in turn evaluates `(+ a 2)`, by evaluating `a` and 2. The value of the symbol `a` is looked up in the current variable binding set, and then replaced. Say `a` is currently bound to the value 3:
```
(let ((a 3))
(* (+ a 2)
3))
```
We'd get `(+ 3 2)`, + is then invoked on 3 and 2 yielding 5. Our original form is now `(* 5 3)` yielding 15.
**Explain `quote` Already!**
Alright. As seen above, all arguments to a function are evaluated, so if you would like to pass the *symbol* `a` and not its value, you don't want to evaluate it. Lisp symbols can double both as their values, and markers where you in other languages would have used strings, such as keys to hash tables.
This is where `quote` comes in. Say you want to plot resource allocations from a Python application, but rather do the plotting in Lisp. Have your Python app do something like this:
```py
print("'(")
while allocating:
if random.random() > 0.5:
print(f"(allocate {random.randint(0, 20)})")
else:
print(f"(free {random.randint(0, 20)})")
...
print(")")
```
Giving you output looking like this (slightly prettyfied):
```
'((allocate 3)
(allocate 7)
(free 14)
(allocate 19)
...)
```
Remember what I said about `quote` ("tick") causing the default rule not to apply? Good. What would otherwise happen is that the values of `allocate` and `free` are looked up, and we don't want that. In our Lisp, we wish to do:
```
(dolist (entry allocation-log)
(case (first entry)
(allocate (plot-allocation (second entry)))
(free (plot-free (second entry)))))
```
For the data given above, the following sequence of function calls would have been made:
```
(plot-allocation 3)
(plot-allocation 7)
(plot-free 14)
(plot-allocation 19)
```
**But What About `list`?**
Well, sometimes you *do* want to evaluate the arguments. Say you have a nifty function manipulating a number and a string and returning a list of the resulting ... things. Let's make a false start:
```
(defun mess-with (number string)
'(value-of-number (1+ number) something-with-string (length string)))
Lisp> (mess-with 20 "foo")
(VALUE-OF-NUMBER (1+ NUMBER) SOMETHING-WITH-STRING (LENGTH STRING))
```
Hey! That's not what we wanted. We want to *selectively* evaluate some arguments, and leave the others as symbols. Try #2!
```
(defun mess-with (number string)
(list 'value-of-number (1+ number) 'something-with-string (length string)))
Lisp> (mess-with 20 "foo")
(VALUE-OF-NUMBER 21 SOMETHING-WITH-STRING 3)
```
**Not Just `quote`, But `backquote`**
Much better! Incidently, this pattern is so common in (mostly) macros, that there is special syntax for doing just that. The backquote:
```
(defun mess-with (number string)
`(value-of-number ,(1+ number) something-with-string ,(length string)))
```
It's like using `quote`, but with the option to explicitly evaluate some arguments by prefixing them with comma. The result is equivalent to using `list`, but if you're generating code from a macro you often only want to evaluate small parts of the code returned, so the backquote is more suited. For shorter lists, `list` can be more readable.
**Hey, You Forgot About `quote`!**
So, where does this leave us? Oh right, what does `quote` actually do? It simply returns its argument(s) unevaluated! Remember what I said in the beginning about regular functions? Turns out that some operators/functions need to *not* evaluate their arguments. Such as IF -- you wouldn't want the else branch to be evaluated if it wasn't taken, right? So-called *special operators*, together with macros, work like that. Special operators are also the "axiom" of the language -- minimal set of rules -- upon which you can implement the rest of Lisp by combining them together in different ways.
Back to `quote`, though:
```
Lisp> (quote spiffy-symbol)
SPIFFY-SYMBOL
Lisp> 'spiffy-symbol ; ' is just a shorthand ("reader macro"), as shown above
SPIFFY-SYMBOL
```
Compare to (on Steel-Bank Common Lisp):
```
Lisp> spiffy-symbol
debugger invoked on a UNBOUND-VARIABLE in thread #<THREAD "initial thread" RUNNING {A69F6A9}>:
The variable SPIFFY-SYMBOL is unbound.
Type HELP for debugger help, or (SB-EXT:QUIT) to exit from SBCL.
restarts (invokable by number or by possibly-abbreviated name):
0: [ABORT] Exit debugger, returning to top level.
(SB-INT:SIMPLE-EVAL-IN-LEXENV SPIFFY-SYMBOL #<NULL-LEXENV>)
0]
```
Because there is no `spiffy-symbol` in the current scope!
**Summing Up**
`quote`, `backquote` (with comma), and `list` are some of the tools you use to create lists, that are not only lists of values, but as you seen can be used as lightweight (no need to define a `struct`) data structures!
If you wish to learn more, I recommend Peter Seibel's book [Practical Common Lisp](http://gigamonkeys.com/book) for a practical approach to learning Lisp, if you're already into programming at large. Eventually on your Lisp journey, you'll start using packages too. Ron Garret's [The Idiot's Guide to Common Lisp Packages](http://www.flownet.com/ron/packages.pdf) will give you good explanation of those.
Happy hacking! |
134,905 | <p>What is the best way to return XML from a controller's action in ASP.NET MVC? There is a nice way to return JSON, but not for XML. Do I really need to route the XML through a View, or should I do the not-best-practice way of Response.Write-ing it?</p>
| [
{
"answer_id": 134982,
"author": "Luke Smith",
"author_id": 5556,
"author_profile": "https://Stackoverflow.com/users/5556",
"pm_score": 8,
"selected": true,
"text": "<p>Use <a href=\"http://www.codeplex.com/MVCContrib\" rel=\"noreferrer\">MVCContrib</a>'s XmlResult Action.</p>\n\n<p>For reference here is their code:</p>\n\n<blockquote>\n<pre><code>public class XmlResult : ActionResult\n{\n private object objectToSerialize;\n\n /// <summary>\n /// Initializes a new instance of the <see cref=\"XmlResult\"/> class.\n /// </summary>\n /// <param name=\"objectToSerialize\">The object to serialize to XML.</param>\n public XmlResult(object objectToSerialize)\n {\n this.objectToSerialize = objectToSerialize;\n }\n\n /// <summary>\n /// Gets the object to be serialized to XML.\n /// </summary>\n public object ObjectToSerialize\n {\n get { return this.objectToSerialize; }\n }\n\n /// <summary>\n /// Serialises the object that was passed into the constructor to XML and writes the corresponding XML to the result stream.\n /// </summary>\n /// <param name=\"context\">The controller context for the current request.</param>\n public override void ExecuteResult(ControllerContext context)\n {\n if (this.objectToSerialize != null)\n {\n context.HttpContext.Response.Clear();\n var xs = new System.Xml.Serialization.XmlSerializer(this.objectToSerialize.GetType());\n context.HttpContext.Response.ContentType = \"text/xml\";\n xs.Serialize(context.HttpContext.Response.Output, this.objectToSerialize);\n }\n }\n}\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 248160,
"author": "Mahdi Taghizadeh",
"author_id": 27946,
"author_profile": "https://Stackoverflow.com/users/27946",
"pm_score": 4,
"selected": false,
"text": "<p>There is a XmlResult (and much more) in MVC Contrib. Take a look at <a href=\"http://www.codeplex.com/MVCContrib\" rel=\"noreferrer\">http://www.codeplex.com/MVCContrib</a></p>\n"
},
{
"answer_id": 1578296,
"author": "Erik",
"author_id": 191231,
"author_profile": "https://Stackoverflow.com/users/191231",
"pm_score": 5,
"selected": false,
"text": "<p>If you are only interested to return xml through a request, and you have your xml \"chunk\", you can just do (as an action in your controller): </p>\n\n<pre><code>public string Xml()\n{\n Response.ContentType = \"text/xml\";\n return yourXmlChunk;\n}\n</code></pre>\n"
},
{
"answer_id": 4325941,
"author": "Petr",
"author_id": 526770,
"author_profile": "https://Stackoverflow.com/users/526770",
"pm_score": 7,
"selected": false,
"text": "<pre class=\"lang-cs prettyprint-override\"><code>return this.Content(xmlString, \"text/xml\");\n</code></pre>\n"
},
{
"answer_id": 12718046,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 5,
"selected": false,
"text": "<p>If you're building the XML using the excellent Linq-to-XML framework, then this approach will be helpful.</p>\n\n<p>I create an <code>XDocument</code> in the action method.</p>\n\n\n\n<pre class=\"lang-cs prettyprint-override\"><code>public ActionResult MyXmlAction()\n{\n // Create your own XDocument according to your requirements\n var xml = new XDocument(\n new XElement(\"root\",\n new XAttribute(\"version\", \"2.0\"),\n new XElement(\"child\", \"Hello World!\")));\n\n return new XmlActionResult(xml);\n}\n</code></pre>\n\n<p>This reusable, custom <code>ActionResult</code> serialises the XML for you.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public sealed class XmlActionResult : ActionResult\n{\n private readonly XDocument _document;\n\n public Formatting Formatting { get; set; }\n public string MimeType { get; set; }\n\n public XmlActionResult(XDocument document)\n {\n if (document == null)\n throw new ArgumentNullException(\"document\");\n\n _document = document;\n\n // Default values\n MimeType = \"text/xml\";\n Formatting = Formatting.None;\n }\n\n public override void ExecuteResult(ControllerContext context)\n {\n context.HttpContext.Response.Clear();\n context.HttpContext.Response.ContentType = MimeType;\n\n using (var writer = new XmlTextWriter(context.HttpContext.Response.OutputStream, Encoding.UTF8) { Formatting = Formatting })\n _document.WriteTo(writer);\n }\n}\n</code></pre>\n\n<p>You can specify a MIME type (such as <code>application/rss+xml</code>) and whether the output should be indented if you need to. Both properties have sensible defaults.</p>\n\n<p>If you need an encoding other than UTF8, then it's simple to add a property for that too.</p>\n"
},
{
"answer_id": 19036811,
"author": "sheir",
"author_id": 245884,
"author_profile": "https://Stackoverflow.com/users/245884",
"pm_score": 2,
"selected": false,
"text": "<p>Finally manage to get this work and thought I would document how here in the hopes of saving others the pain. </p>\n\n<p>Environment</p>\n\n<ul>\n<li>VS2012</li>\n<li>SQL Server 2008R2</li>\n<li>.NET 4.5</li>\n<li>ASP.NET MVC4 (Razor)</li>\n<li>Windows 7</li>\n</ul>\n\n<p>Supported Web Browsers</p>\n\n<ul>\n<li>FireFox 23</li>\n<li>IE 10</li>\n<li>Chrome 29</li>\n<li>Opera 16</li>\n<li>Safari 5.1.7 (last one for Windows?)</li>\n</ul>\n\n<p>My task was on a ui button click, call a method on my Controller (with some params) and then have it return an MS-Excel XML via an xslt transform. The returned MS-Excel XML would then cause the browser to popup the Open/Save dialog. This had to work in all the browsers (listed above).</p>\n\n<p>At first I tried with Ajax and to create a dynamic Anchor with the \"download\" attribute for the filename, \nbut that only worked for about 3 of the 5 browsers(FF, Chrome, Opera) and not for IE or Safari.\nAnd there were issues with trying to programmatically fire the Click event of the anchor to cause the actual \"download\".</p>\n\n<p>What I ended up doing was using an \"invisible\" IFRAME and it worked for all 5 browsers!</p>\n\n<p>So here is what I came up with:\n[please note that I am by no means an html/javascript guru and have only included the relevant code]</p>\n\n<p>HTML (snippet of relevant bits)\n</p>\n\n<pre><code><div id=\"docxOutput\">\n<iframe id=\"ifOffice\" name=\"ifOffice\" width=\"0\" height=\"0\"\n hidden=\"hidden\" seamless='seamless' frameBorder=\"0\" scrolling=\"no\"></iframe></div>\n</code></pre>\n\n<p>JAVASCRIPT\n</p>\n\n<pre><code>//url to call in the controller to get MS-Excel xml\nvar _lnkToControllerExcel = '@Url.Action(\"ExportToExcel\", \"Home\")';\n$(\"#btExportToExcel\").on(\"click\", function (event) {\n event.preventDefault();\n\n $(\"#ProgressDialog\").show();//like an ajax loader gif\n\n //grab the basket as xml \n var keys = GetMyKeys();//returns delimited list of keys (for selected items from UI) \n\n //potential problem - the querystring might be too long??\n //2K in IE8\n //4096 characters in ASP.Net\n //parameter key names must match signature of Controller method\n var qsParams = [\n 'keys=' + keys,\n 'locale=' + '@locale' \n ].join('&');\n\n //The element with id=\"ifOffice\"\n var officeFrame = $(\"#ifOffice\")[0];\n\n //construct the url for the iframe\n var srcUrl = _lnkToControllerExcel + '?' + qsParams;\n\n try {\n if (officeFrame != null) {\n //Controller method can take up to 4 seconds to return\n officeFrame.setAttribute(\"src\", srcUrl);\n }\n else {\n alert('ExportToExcel - failed to get reference to the office iframe!');\n }\n } catch (ex) {\n var errMsg = \"ExportToExcel Button Click Handler Error: \";\n HandleException(ex, errMsg);\n }\n finally {\n //Need a small 3 second ( delay for the generated MS-Excel XML to come down from server)\n setTimeout(function () {\n //after the timeout then hide the loader graphic\n $(\"#ProgressDialog\").hide();\n }, 3000);\n\n //clean up\n officeFrame = null;\n srcUrl = null;\n qsParams = null;\n keys = null;\n }\n});\n</code></pre>\n\n<p>C# SERVER-SIDE (code snippet)\n@Drew created a custom ActionResult called XmlActionResult which I modified for my purpose.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/134905/what-is-the-best-way-to-return-xml-from-a-controllers-action-in-asp-net-mvc/12718046#12718046\">Return XML from a controller's action in as an ActionResult?</a></p>\n\n<p>My Controller method (returns ActionResult) </p>\n\n<ul>\n<li>passes the keys parameter to a SQL Server stored proc that generates an XML</li>\n<li>that XML is then transformed via xslt into an MS-Excel xml (XmlDocument)</li>\n<li><p>creates instance of the modified XmlActionResult and returns it\n</p>\n\n<p>XmlActionResult result = new XmlActionResult(excelXML, \"application/vnd.ms-excel\");\nstring version = DateTime.Now.ToString(\"dd_MMM_yyyy_hhmmsstt\");\nstring fileMask = \"LabelExport_{0}.xml\";<br>\nresult.DownloadFilename = string.Format(fileMask, version);\nreturn result;</p></li>\n</ul>\n\n<p>The main modification to the XmlActionResult class that @Drew created.\n</p>\n\n<pre><code>public override void ExecuteResult(ControllerContext context)\n{\n string lastModDate = DateTime.Now.ToString(\"R\");\n\n //Content-Disposition: attachment; filename=\"<file name.xml>\" \n // must set the Content-Disposition so that the web browser will pop the open/save dialog\n string disposition = \"attachment; \" +\n \"filename=\\\"\" + this.DownloadFilename + \"\\\"; \";\n\n context.HttpContext.Response.Clear();\n context.HttpContext.Response.ClearContent();\n context.HttpContext.Response.ClearHeaders();\n context.HttpContext.Response.Cookies.Clear();\n context.HttpContext.Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);// Stop Caching in IE\n context.HttpContext.Response.Cache.SetNoStore();// Stop Caching in Firefox\n context.HttpContext.Response.Cache.SetMaxAge(TimeSpan.Zero);\n context.HttpContext.Response.CacheControl = \"private\";\n context.HttpContext.Response.Cache.SetLastModified(DateTime.Now.ToUniversalTime());\n context.HttpContext.Response.ContentType = this.MimeType;\n context.HttpContext.Response.Charset = System.Text.UTF8Encoding.UTF8.WebName;\n\n //context.HttpContext.Response.Headers.Add(\"name\", \"value\");\n context.HttpContext.Response.Headers.Add(\"Last-Modified\", lastModDate);\n context.HttpContext.Response.Headers.Add(\"Pragma\", \"no-cache\"); // HTTP 1.0.\n context.HttpContext.Response.Headers.Add(\"Expires\", \"0\"); // Proxies.\n\n context.HttpContext.Response.AppendHeader(\"Content-Disposition\", disposition);\n\n using (var writer = new XmlTextWriter(context.HttpContext.Response.OutputStream, this.Encoding)\n { Formatting = this.Formatting })\n this.Document.WriteTo(writer);\n}\n</code></pre>\n\n<p>That was basically it.\nHope it helps others.</p>\n"
},
{
"answer_id": 21687683,
"author": "Casey",
"author_id": 2056448,
"author_profile": "https://Stackoverflow.com/users/2056448",
"pm_score": 1,
"selected": false,
"text": "<p>A simple option that will let you use streams and all that is <code>return File(stream, \"text/xml\");</code>.</p>\n"
},
{
"answer_id": 22024105,
"author": "user2670714",
"author_id": 2670714,
"author_profile": "https://Stackoverflow.com/users/2670714",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a simple way of doing it:</p>\n\n<pre><code> var xml = new XDocument(\n new XElement(\"root\",\n new XAttribute(\"version\", \"2.0\"),\n new XElement(\"child\", \"Hello World!\")));\n MemoryStream ms = new MemoryStream();\n xml.Save(ms);\n return File(new MemoryStream(ms.ToArray()), \"text/xml\", \"HelloWorld.xml\");\n</code></pre>\n"
},
{
"answer_id": 38594073,
"author": "Matthew Price",
"author_id": 6640631,
"author_profile": "https://Stackoverflow.com/users/6640631",
"pm_score": 3,
"selected": false,
"text": "<p>I've had to do this recently for a Sitecore project which uses a method to create an XmlDocument from a Sitecore Item and its children and returns it from the controller ActionResult as a File. My solution:</p>\n\n<pre><code>public virtual ActionResult ReturnXml()\n{\n return File(Encoding.UTF8.GetBytes(GenerateXmlFeed().OuterXml), \"text/xml\");\n}\n</code></pre>\n"
},
{
"answer_id": 38855421,
"author": "Nelson Lopez Centeno",
"author_id": 4473736,
"author_profile": "https://Stackoverflow.com/users/4473736",
"pm_score": 0,
"selected": false,
"text": "<p>A small variation of the <a href=\"https://stackoverflow.com/a/12718046/4473736\">answer from Drew Noakes</a> that use the method Save() of XDocument.</p>\n\n<pre><code>public sealed class XmlActionResult : ActionResult\n{\n private readonly XDocument _document;\n public string MimeType { get; set; }\n\n public XmlActionResult(XDocument document)\n {\n if (document == null)\n throw new ArgumentNullException(\"document\");\n\n _document = document;\n\n // Default values\n MimeType = \"text/xml\";\n }\n\n public override void ExecuteResult(ControllerContext context)\n {\n context.HttpContext.Response.Clear();\n context.HttpContext.Response.ContentType = MimeType;\n _document.Save(context.HttpContext.Response.OutputStream)\n }\n}\n</code></pre>\n"
},
{
"answer_id": 65161290,
"author": "Hamid Jolany",
"author_id": 555078,
"author_profile": "https://Stackoverflow.com/users/555078",
"pm_score": 2,
"selected": false,
"text": "<p>use one of these methods</p>\n<pre><code> public ContentResult GetXml()\n {\n string xmlString = "your xml data";\n return Content(xmlString, "text/xml");\n }\n</code></pre>\n<p>or</p>\n<pre><code> public string GetXml()\n {\n string xmlString = "your xml data";\n Response.ContentType = "text/xml";\n return xmlString;\n }\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22299/"
]
| What is the best way to return XML from a controller's action in ASP.NET MVC? There is a nice way to return JSON, but not for XML. Do I really need to route the XML through a View, or should I do the not-best-practice way of Response.Write-ing it? | Use [MVCContrib](http://www.codeplex.com/MVCContrib)'s XmlResult Action.
For reference here is their code:
>
>
> ```
> public class XmlResult : ActionResult
> {
> private object objectToSerialize;
>
> /// <summary>
> /// Initializes a new instance of the <see cref="XmlResult"/> class.
> /// </summary>
> /// <param name="objectToSerialize">The object to serialize to XML.</param>
> public XmlResult(object objectToSerialize)
> {
> this.objectToSerialize = objectToSerialize;
> }
>
> /// <summary>
> /// Gets the object to be serialized to XML.
> /// </summary>
> public object ObjectToSerialize
> {
> get { return this.objectToSerialize; }
> }
>
> /// <summary>
> /// Serialises the object that was passed into the constructor to XML and writes the corresponding XML to the result stream.
> /// </summary>
> /// <param name="context">The controller context for the current request.</param>
> public override void ExecuteResult(ControllerContext context)
> {
> if (this.objectToSerialize != null)
> {
> context.HttpContext.Response.Clear();
> var xs = new System.Xml.Serialization.XmlSerializer(this.objectToSerialize.GetType());
> context.HttpContext.Response.ContentType = "text/xml";
> xs.Serialize(context.HttpContext.Response.Output, this.objectToSerialize);
> }
> }
> }
>
> ```
>
> |
134,906 | <p>Is there a command or an existing script that will let me view all of a *NIX system's scheduled cron jobs at once? I'd like it to include all of the user crontabs, as well as <code>/etc/crontab</code>, and whatever's in <code>/etc/cron.d</code>. It would also be nice to see the specific commands run by <code>run-parts</code> in <code>/etc/crontab</code>.</p>
<p>Ideally, I'd like the output in a nice column form and ordered in some meaningful way.</p>
<p>I could then merge these listings from multiple servers to view the overall "schedule of events."</p>
<p>I was about to write such a script myself, but if someone's already gone to the trouble...</p>
| [
{
"answer_id": 134944,
"author": "Kyle Burton",
"author_id": 19784,
"author_profile": "https://Stackoverflow.com/users/19784",
"pm_score": 10,
"selected": false,
"text": "<p>You would have to run this as root, but:</p>\n\n<pre><code>for user in $(cut -f1 -d: /etc/passwd); do crontab -u $user -l; done\n</code></pre>\n\n<p>will loop over each user name listing out their crontab. The crontabs are owned by the respective users so you won't be able to see another user's crontab w/o being them or root.</p>\n\n<hr>\n\n<p><strong>Edit</strong>\nif you want to know which user a crontab belongs to, use <code>echo $user</code></p>\n\n<pre><code>for user in $(cut -f1 -d: /etc/passwd); do echo $user; crontab -u $user -l; done\n</code></pre>\n"
},
{
"answer_id": 134947,
"author": "Daniel Papasian",
"author_id": 7548,
"author_profile": "https://Stackoverflow.com/users/7548",
"pm_score": 3,
"selected": false,
"text": "<p>Depends on your version of cron. Using Vixie cron on FreeBSD, I can do something like this:</p>\n\n<pre><code>(cd /var/cron/tabs && grep -vH ^# *) \n</code></pre>\n\n<p>if I want it more tab deliminated, I might do something like this:</p>\n\n<pre><code>(cd /var/cron/tabs && grep -vH ^# * | sed \"s/:/ /\")\n</code></pre>\n\n<p>Where that's a literal tab in the sed replacement portion.</p>\n\n<p>It may be more system independent to loop through the users in <code>/etc/passwd</code> and do <code>crontab -l -u $user</code> for each of them.</p>\n"
},
{
"answer_id": 137173,
"author": "yukondude",
"author_id": 726,
"author_profile": "https://Stackoverflow.com/users/726",
"pm_score": 9,
"selected": true,
"text": "<p>I ended up writing a script (I'm trying to teach myself the finer points of bash scripting, so that's why you don't see something like Perl here). It's not exactly a simple affair, but it does most of what I need. It uses Kyle's suggestion for looking up individual users' crontabs, but also deals with <code>/etc/crontab</code> (including the scripts launched by <code>run-parts</code> in <code>/etc/cron.hourly</code>, <code>/etc/cron.daily</code>, etc.) and the jobs in the <code>/etc/cron.d</code> directory. It takes all of those and merges them into a display something like the following:</p>\n\n<pre><code>mi h d m w user command\n09,39 * * * * root [ -d /var/lib/php5 ] && find /var/lib/php5/ -type f -cmin +$(/usr/lib/php5/maxlifetime) -print0 | xargs -r -0 rm\n47 */8 * * * root rsync -axE --delete --ignore-errors / /mirror/ >/dev/null\n17 1 * * * root /etc/cron.daily/apt\n17 1 * * * root /etc/cron.daily/aptitude\n17 1 * * * root /etc/cron.daily/find\n17 1 * * * root /etc/cron.daily/logrotate\n17 1 * * * root /etc/cron.daily/man-db\n17 1 * * * root /etc/cron.daily/ntp\n17 1 * * * root /etc/cron.daily/standard\n17 1 * * * root /etc/cron.daily/sysklogd\n27 2 * * 7 root /etc/cron.weekly/man-db\n27 2 * * 7 root /etc/cron.weekly/sysklogd\n13 3 * * * archiver /usr/local/bin/offsite-backup 2>&1\n32 3 1 * * root /etc/cron.monthly/standard\n36 4 * * * yukon /home/yukon/bin/do-daily-stuff\n5 5 * * * archiver /usr/local/bin/update-logs >/dev/null\n</code></pre>\n\n<p>Note that it shows the user, and more-or-less sorts by hour and minute so that I can see the daily schedule.</p>\n\n<p>So far, I've tested it on Ubuntu, Debian, and Red Hat AS.</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/bash\n\n# System-wide crontab file and cron job directory. Change these for your system.\nCRONTAB='/etc/crontab'\nCRONDIR='/etc/cron.d'\n\n# Single tab character. Annoyingly necessary.\ntab=$(echo -en \"\\t\")\n\n# Given a stream of crontab lines, exclude non-cron job lines, replace\n# whitespace characters with a single space, and remove any spaces from the\n# beginning of each line.\nfunction clean_cron_lines() {\n while read line ; do\n echo \"${line}\" |\n egrep --invert-match '^($|\\s*#|\\s*[[:alnum:]_]+=)' |\n sed --regexp-extended \"s/\\s+/ /g\" |\n sed --regexp-extended \"s/^ //\"\n done;\n}\n\n# Given a stream of cleaned crontab lines, echo any that don't include the\n# run-parts command, and for those that do, show each job file in the run-parts\n# directory as if it were scheduled explicitly.\nfunction lookup_run_parts() {\n while read line ; do\n match=$(echo \"${line}\" | egrep -o 'run-parts (-{1,2}\\S+ )*\\S+')\n\n if [[ -z \"${match}\" ]] ; then\n echo \"${line}\"\n else\n cron_fields=$(echo \"${line}\" | cut -f1-6 -d' ')\n cron_job_dir=$(echo \"${match}\" | awk '{print $NF}')\n\n if [[ -d \"${cron_job_dir}\" ]] ; then\n for cron_job_file in \"${cron_job_dir}\"/* ; do # */ <not a comment>\n [[ -f \"${cron_job_file}\" ]] && echo \"${cron_fields} ${cron_job_file}\"\n done\n fi\n fi\n done;\n}\n\n# Temporary file for crontab lines.\ntemp=$(mktemp) || exit 1\n\n# Add all of the jobs from the system-wide crontab file.\ncat \"${CRONTAB}\" | clean_cron_lines | lookup_run_parts >\"${temp}\" \n\n# Add all of the jobs from the system-wide cron directory.\ncat \"${CRONDIR}\"/* | clean_cron_lines >>\"${temp}\" # */ <not a comment>\n\n# Add each user's crontab (if it exists). Insert the user's name between the\n# five time fields and the command.\nwhile read user ; do\n crontab -l -u \"${user}\" 2>/dev/null |\n clean_cron_lines |\n sed --regexp-extended \"s/^((\\S+ +){5})(.+)$/\\1${user} \\3/\" >>\"${temp}\"\ndone < <(cut --fields=1 --delimiter=: /etc/passwd)\n\n# Output the collected crontab lines. Replace the single spaces between the\n# fields with tab characters, sort the lines by hour and minute, insert the\n# header line, and format the results as a table.\ncat \"${temp}\" |\n sed --regexp-extended \"s/^(\\S+) +(\\S+) +(\\S+) +(\\S+) +(\\S+) +(\\S+) +(.*)$/\\1\\t\\2\\t\\3\\t\\4\\t\\5\\t\\6\\t\\7/\" |\n sort --numeric-sort --field-separator=\"${tab}\" --key=2,1 |\n sed \"1i\\mi\\th\\td\\tm\\tw\\tuser\\tcommand\" |\n column -s\"${tab}\" -t\n\nrm --force \"${temp}\"\n</code></pre>\n"
},
{
"answer_id": 361851,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": false,
"text": "<p>Under Ubuntu or debian, you can view crontab by <code>/var/spool/cron/crontabs/</code> and then a file for each user is in there. That's only for user-specific crontab's of course.</p>\n\n<p>For Redhat 6/7 and Centos, the crontab is under <code>/var/spool/cron/</code>.</p>\n"
},
{
"answer_id": 1243501,
"author": "jbbarth",
"author_id": 278757,
"author_profile": "https://Stackoverflow.com/users/278757",
"pm_score": 3,
"selected": false,
"text": "<p>Thanks for this very useful script. I had some tiny problems running it on old systems (Red Hat Enterprise 3, which handle differently egrep and tabs in strings), and other systems with nothing in /etc/cron.d/ (the script then ended with an error). So here is a patch to make it work in such cases :</p>\n\n<pre><code>2a3,4\n> #See: http://stackoverflow.com/questions/134906/how-do-i-list-all-cron-jobs-for-all-users\n>\n27c29,30\n< match=$(echo \"${line}\" | egrep -o 'run-parts (-{1,2}\\S+ )*\\S+')\n---\n> #match=$(echo \"${line}\" | egrep -o 'run-parts (-{1,2}\\S+ )*\\S+')\n> match=$(echo \"${line}\" | egrep -o 'run-parts.*')\n51c54,57\n< cat \"${CRONDIR}\"/* | clean_cron_lines >>\"${temp}\" # */ <not a comment>\n---\n> sys_cron_num=$(ls /etc/cron.d | wc -l | awk '{print $1}')\n> if [ \"$sys_cron_num\" != 0 ]; then\n> cat \"${CRONDIR}\"/* | clean_cron_lines >>\"${temp}\" # */ <not a comment>\n> fi\n67c73\n< sed \"1i\\mi\\th\\td\\tm\\tw\\tuser\\tcommand\" |\n---\n> sed \"1i\\mi${tab}h${tab}d${tab}m${tab}w${tab}user${tab}command\" |\n</code></pre>\n\n<p>I'm not really sure the changes in the first egrep are a good idea, but well, this script has been tested on RHEL3,4,5 and Debian5 without any problem. Hope this helps!</p>\n"
},
{
"answer_id": 2759975,
"author": "squarism",
"author_id": 88406,
"author_profile": "https://Stackoverflow.com/users/88406",
"pm_score": 3,
"selected": false,
"text": "<p>I like the simple one-liner answer above:</p>\n\n<blockquote>\n <p>for user in $(cut -f1 -d: /etc/passwd); do crontab -u $user -l; done</p>\n</blockquote>\n\n<p>But Solaris which does not have the -u flag and does not print the user it's checking, you can modify it like so:</p>\n\n<pre><code>for user in $(cut -f1 -d: /etc/passwd); do echo User:$user; crontab -l $user 2>&1 | grep -v crontab; done\n</code></pre>\n\n<p>You will get a list of users without the errors thrown by crontab when an account is not allowed to use cron etc. Be aware that in Solaris, roles can be in /etc/passwd too (see /etc/user_attr).</p>\n"
},
{
"answer_id": 2862180,
"author": "Mithaldu",
"author_id": 145119,
"author_profile": "https://Stackoverflow.com/users/145119",
"pm_score": 4,
"selected": false,
"text": "<pre><code>getent passwd | cut -d: -f1 | perl -e'while(<>){chomp;$l = `crontab -u $_ -l 2>/dev/null`;print \"$_\\n$l\\n\" if $l}'\n</code></pre>\n\n<p>This avoids messing with passwd directly, skips users that have no cron entries and for those who have them it prints out the username as well as their crontab.</p>\n\n<p>Mostly dropping this here though so i can find it later in case i ever need to search for it again.</p>\n"
},
{
"answer_id": 3185772,
"author": "sum",
"author_id": 384480,
"author_profile": "https://Stackoverflow.com/users/384480",
"pm_score": 4,
"selected": false,
"text": "<p>A small refinement of Kyle Burton's answer with improved output formatting:</p>\n\n<pre><code>#!/bin/bash\nfor user in $(cut -f1 -d: /etc/passwd)\ndo echo $user && crontab -u $user -l\necho \" \"\ndone\n</code></pre>\n"
},
{
"answer_id": 7160866,
"author": "Doris",
"author_id": 907686,
"author_profile": "https://Stackoverflow.com/users/907686",
"pm_score": 4,
"selected": false,
"text": "<p>If you check a cluster using NIS, the only way to see if a user has a crontab entry ist according to Matt's answer /var/spool/cron/tabs.</p>\n\n<pre><code>grep -v \"#\" -R /var/spool/cron/tabs\n</code></pre>\n"
},
{
"answer_id": 11454635,
"author": "indra bhushan kumar",
"author_id": 1521170,
"author_profile": "https://Stackoverflow.com/users/1521170",
"pm_score": 3,
"selected": false,
"text": "<pre><code>for user in $(cut -f1 -d: /etc/passwd); \ndo \n echo $user; crontab -u $user -l; \ndone\n</code></pre>\n"
},
{
"answer_id": 18028103,
"author": "Jørgen",
"author_id": 638488,
"author_profile": "https://Stackoverflow.com/users/638488",
"pm_score": 5,
"selected": false,
"text": "<p>Depends on your linux version but I use: </p>\n\n<pre><code>tail -n 1000 /var/spool/cron/*\n</code></pre>\n\n<p>as root. Very simple and very short.</p>\n\n<p>Gives me output like:</p>\n\n<pre><code>==> /var/spool/cron/root <==\n15 2 * * * /bla\n\n==> /var/spool/cron/my_user <==\n*/10 1 * * * /path/to/script\n</code></pre>\n"
},
{
"answer_id": 22665036,
"author": "Ali",
"author_id": 487855,
"author_profile": "https://Stackoverflow.com/users/487855",
"pm_score": 2,
"selected": false,
"text": "<p>Building on top of @Kyle </p>\n\n<pre><code>for user in $(tail -n +11 /etc/passwd | cut -f1 -d:); do echo $user; crontab -u $user -l; done\n</code></pre>\n\n<p>to avoid the comments usually at the top of /etc/passwd,</p>\n\n<p>And on macosx </p>\n\n<pre><code>for user in $(dscl . -list /users | cut -f1 -d:); do echo $user; crontab -u $user -l; done \n</code></pre>\n"
},
{
"answer_id": 27991385,
"author": "Rob Frost",
"author_id": 4462960,
"author_profile": "https://Stackoverflow.com/users/4462960",
"pm_score": -1,
"selected": false,
"text": "<p>This script outputs the Crontab to a file and also lists all users confirming those which have no crontab entry:</p>\n\n<pre><code>for user in $(cut -f1 -d: /etc/passwd); do \n echo $user >> crontab.bak\n echo \"\" >> crontab.bak\n crontab -u $user -l >> crontab.bak 2>> > crontab.bak\ndone\n</code></pre>\n"
},
{
"answer_id": 31873590,
"author": "idranoels",
"author_id": 5201295,
"author_profile": "https://Stackoverflow.com/users/5201295",
"pm_score": 6,
"selected": false,
"text": "<p>This will show all crontab entries from all users.</p>\n<pre><code>sed 's/^\\([^:]*\\):.*$/crontab -u \\1 -l 2>\\&1/' /etc/passwd | sh | grep -v "no crontab for"\n</code></pre>\n"
},
{
"answer_id": 37328076,
"author": "Monte",
"author_id": 6357058,
"author_profile": "https://Stackoverflow.com/users/6357058",
"pm_score": 2,
"selected": false,
"text": "<p>I think a better one liner would be below. For example if you have users in NIS or LDAP they wouldnt be in /etc/passwd. This will give you the crontabs of every user that has logged in.</p>\n\n<pre><code>for I in `lastlog | grep -v Never | cut -f1 -d' '`; do echo $I ; crontab -l -u $I ; done\n</code></pre>\n"
},
{
"answer_id": 38631252,
"author": "fedorqui",
"author_id": 1983854,
"author_profile": "https://Stackoverflow.com/users/1983854",
"pm_score": 2,
"selected": false,
"text": "<p>Since it is a matter of looping through a file (<code>/etc/passwd</code>) and performing an action, I am missing the proper approach on <a href=\"http://mywiki.wooledge.org/BashFAQ/001\" rel=\"nofollow\">How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?</a>:</p>\n\n<pre><code>while IFS=\":\" read -r user _\ndo\n echo \"crontab for user ${user}:\"\n crontab -u \"$user\" -l\ndone < /etc/passwd\n</code></pre>\n\n<p>This reads <code>/etc/passwd</code> line by line using <code>:</code> as field delimiter. By saying <code>read -r user _</code>, we make <code>$user</code> hold the first field and <code>_</code> the rest (it is just a junk variable to ignore fields).</p>\n\n<p>This way, we can then call <code>crontab -u</code> using the variable <code>$user</code>, which we quote for safety (what if it contains spaces? It is unlikely in such file, but you can never know).</p>\n"
},
{
"answer_id": 39385151,
"author": "rkoots",
"author_id": 6771480,
"author_profile": "https://Stackoverflow.com/users/6771480",
"pm_score": 3,
"selected": false,
"text": "<p>you can write for all user list :</p>\n\n<pre><code>sudo crontab -u userName -l\n\n,\n</code></pre>\n\n<p>You can also go to </p>\n\n<pre><code>cd /etc/cron.daily/\nls -l\ncat filename\n</code></pre>\n\n<p>this file will list the schedules</p>\n\n<pre><code>cd /etc/cron.d/\nls -l\ncat filename\n</code></pre>\n"
},
{
"answer_id": 41233535,
"author": "Dale C. Anderson",
"author_id": 267455,
"author_profile": "https://Stackoverflow.com/users/267455",
"pm_score": 3,
"selected": false,
"text": "<p>The following strips away comments, empty lines, and errors from users with no crontab. All you're left with is a clear list of users and their jobs. </p>\n\n<p>Note the use of <code>sudo</code> in the 2nd line. If you're already root, remove that.</p>\n\n<pre><code>for USER in $(cut -f1 -d: /etc/passwd); do \\\nUSERTAB=\"$(sudo crontab -u \"$USER\" -l 2>&1)\"; \\\nFILTERED=\"$(echo \"$USERTAB\"| grep -vE '^#|^$|no crontab for|cannot use this program')\"; \\\nif ! test -z \"$FILTERED\"; then \\\necho \"# ------ $(tput bold)$USER$(tput sgr0) ------\"; \\\necho \"$FILTERED\"; \\\necho \"\"; \\\nfi; \\\ndone\n</code></pre>\n\n<p>Example output: </p>\n\n<pre><code># ------ root ------\n0 */6 * * * /usr/local/bin/disk-space-notify.sh\n45 3 * * * /opt/mysql-backups/mysql-backups.sh\n5 7 * * * /usr/local/bin/certbot-auto renew --quiet --no-self-upgrade\n\n# ------ sammy ------\n55 * * * * wget -O - -q -t 1 https://www.example.com/cron.php > /dev/null\n</code></pre>\n\n<p>I use this on Ubuntu (12 thru 16) and Red Hat (5 thru 7).</p>\n"
},
{
"answer_id": 44714620,
"author": "Sam Arul Raj T",
"author_id": 493662,
"author_profile": "https://Stackoverflow.com/users/493662",
"pm_score": 4,
"selected": false,
"text": "<p>This script worked for me in CentOS to list all crons in the environment:</p>\n\n<pre><code>sudo cat /etc/passwd | sed 's/^\\([^:]*\\):.*$/sudo crontab -u \\1 -l 2>\\&1/' | grep -v \"no crontab for\" | sh\n</code></pre>\n"
},
{
"answer_id": 48003490,
"author": "Sheikh Abdul Wahid",
"author_id": 3590283,
"author_profile": "https://Stackoverflow.com/users/3590283",
"pm_score": 4,
"selected": false,
"text": "<p>To get list from ROOT user.</p>\n\n<pre><code>for user in $(cut -f1 -d: /etc/passwd); do echo $user; sudo crontab -u $user -l; done\n</code></pre>\n"
},
{
"answer_id": 48194538,
"author": "armagedescu",
"author_id": 4582948,
"author_profile": "https://Stackoverflow.com/users/4582948",
"pm_score": 3,
"selected": false,
"text": "<p>On Solaris, for a particular known user name:</p>\n<pre><code>crontab -l username\n</code></pre>\n<p>To get all user's jobs at once on Solaris, much like other posts above:</p>\n<pre><code>for user in $(cut -f1 -d: /etc/passwd); do crontab -l $user 2>/dev/null; done\n</code></pre>\n<p>Update:\nPlease stop suggesting edits that are wrong on Solaris:\n<a href=\"https://i.stack.imgur.com/1PT7z.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1PT7z.png\" alt=\"enter image description here\" /></a></p>\n"
},
{
"answer_id": 53892185,
"author": "david collier",
"author_id": 5631477,
"author_profile": "https://Stackoverflow.com/users/5631477",
"pm_score": 2,
"selected": false,
"text": "<p>With apologies and thanks to yukondude.</p>\n\n<p>I've tried to summarise the timing settings for easy reading, though it's not a perfect job, and I don't touch 'every Friday' or 'only on Mondays' stuff.</p>\n\n<p>This is version 10 - it now:</p>\n\n<ul>\n<li>runs much much faster</li>\n<li>has optional progress characters so you could improve the speed further.</li>\n<li>uses a divider line to separate header and output.</li>\n<li>outputs in a compact format when all timing intervals uencountered can be summarised.</li>\n<li>Accepts Jan...Dec descriptors for months-of-the-year</li>\n<li>Accepts Mon...Sun descriptors for days-of-the-week</li>\n<li>tries to handle debian-style dummying-up of anacron when it is missing </li>\n<li>tries to deal with crontab lines which run a file after pre-testing executability using \"[ -x ... ]\"</li>\n<li>tries to deal with crontab lines which run a file after pre-testing executability using \"command -v\"</li>\n<li>allows the use of interval spans and lists.</li>\n<li>supports run-parts usage in user-specific /var/spool crontab files.</li>\n</ul>\n\n<p>I am now publishing the script in full here. </p>\n\n<p><a href=\"https://gist.github.com/myshkin-uk/d667116d3e2d689f23f18f6cd3c71107\" rel=\"nofollow noreferrer\">https://gist.github.com/myshkin-uk/d667116d3e2d689f23f18f6cd3c71107</a></p>\n"
},
{
"answer_id": 64662148,
"author": "Ярослав Рахматуллин",
"author_id": 657703,
"author_profile": "https://Stackoverflow.com/users/657703",
"pm_score": 3,
"selected": false,
"text": "<p>While many of the answers produce useful results, I think the hustle of maintaining a complex script for this task is not worth it. This is mainly because most distros use different cron daemons.</p>\n<h1>Watch and learn, kids & elders.</h1>\n<pre><code>$ \\cat ~jaroslav/bin/ls-crons \n#!/bin/bash\ngetent passwd | awk -F: '{ print $1 }' | xargs -I% sh -c 'crontab -l -u % | sed "/^$/d; /^#/d; s/^/% /"' 2>/dev/null\necho\ncat /etc/crontab /etc/anacrontab 2>/dev/null | sed '/^$/d; /^#/d;'\necho\nrun-parts --list /etc/cron.hourly;\nrun-parts --list /etc/cron.daily;\nrun-parts --list /etc/cron.weekly;\nrun-parts --list /etc/cron.monthly;\n</code></pre>\n<h3>Run like this</h3>\n<pre><code>$ sudo ls-cron\n</code></pre>\n<h3>Sample output (Gentoo)</h3>\n<pre><code>$ sudo ~jaroslav/bin/ls-crons \njaroslav */5 * * * * mv ~/java_error_in_PHPSTORM* ~/tmp 2>/dev/null\njaroslav 5 */24 * * * ~/bin/Find-home-files\njaroslav * 7 * * * cp /T/fortrabbit/ssh-config/fapps.tsv /home/jaroslav/reference/fortrabbit/fapps\njaroslav */8 1 * * * make -C /T/fortrabbit/ssh-config discover-apps # >/dev/null\njaroslav */7 * * * * getmail -r jazzoslav -r fortrabbit 2>/dev/null\njaroslav */1 * * * * /home/jaroslav/bin/checkmail\njaroslav * 9-18 * * * getmail -r fortrabbit 2>/dev/null\n\nSHELL=/bin/bash\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\nMAILTO=root\nHOME=/\nSHELL=/bin/sh\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\nMAILTO=root\nRANDOM_DELAY=45\nSTART_HOURS_RANGE=3-22\n1 5 cron.daily nice run-parts /etc/cron.daily\n7 25 cron.weekly nice run-parts /etc/cron.weekly\n@monthly 45 cron.monthly nice run-parts /etc/cron.monthly\n\n/etc/cron.hourly/0anacron\n/etc/cron.daily/logrotate\n/etc/cron.daily/man-db\n/etc/cron.daily/mlocate\n/etc/cron.weekly/mdadm\n/etc/cron.weekly/pfl\n</code></pre>\n<h3>Sample output (Ubuntu)</h3>\n<pre><code>SHELL=/bin/sh\nPATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin\n17 * * * * root cd / && run-parts --report /etc/cron.hourly\n25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )\n47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )\n52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )\n\n/etc/cron.hourly/btrfs-quota-cleanup\n/etc/cron.hourly/ntpdate-debian\n/etc/cron.daily/apport\n/etc/cron.daily/apt-compat\n/etc/cron.daily/apt-show-versions\n/etc/cron.daily/aptitude\n/etc/cron.daily/bsdmainutils\n/etc/cron.daily/dpkg\n/etc/cron.daily/logrotate\n/etc/cron.daily/man-db\n/etc/cron.daily/mlocate\n/etc/cron.daily/passwd\n/etc/cron.daily/popularity-contest\n/etc/cron.daily/ubuntu-advantage-tools\n/etc/cron.daily/update-notifier-common\n/etc/cron.daily/upstart\n/etc/cron.weekly/apt-xapian-index\n/etc/cron.weekly/man-db\n/etc/cron.weekly/update-notifier-common\n\n</code></pre>\n<h3>Pics</h3>\n<p>Ubuntu:</p>\n<p><a href=\"https://i.stack.imgur.com/fyNiH.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/fyNiH.png\" alt=\"ubuntu\" /></a></p>\n<p>Gentoo:</p>\n<p><a href=\"https://i.stack.imgur.com/vETIY.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/vETIY.png\" alt=\"gentoo\" /></a></p>\n"
},
{
"answer_id": 68988468,
"author": "Manifest Man",
"author_id": 5667103,
"author_profile": "https://Stackoverflow.com/users/5667103",
"pm_score": 1,
"selected": false,
"text": "<p>I tend to use following small commands to list all jobs for single user and all users on Unix based operating systems with a modern bash console:</p>\n<p><strong>1. Single user</strong></p>\n<pre><code> echo "Jobs owned by $USER" && crontab -l -u $USER\n</code></pre>\n<p><strong>2. All users</strong></p>\n<pre><code>for wellknownUser in $(cut -f1 -d: /etc/passwd);\n do\n echo "Jobs owned by $wellknownUser";\n crontab -l -u $wellknownUser;\n echo -e "\\n";\n sleep 2; # (optional sleep 2 seconds) while drinking a coffee\n done\n</code></pre>\n"
},
{
"answer_id": 69394204,
"author": "linux.cnf",
"author_id": 10000566,
"author_profile": "https://Stackoverflow.com/users/10000566",
"pm_score": 3,
"selected": false,
"text": "<p>i made below one liner script and it worked for me to list all cron jobs for all users.</p>\n<pre><code>cat /etc/passwd |awk -F ':' '{print $1}'|while read a;do crontab -l -u ${a} ; done\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/726/"
]
| Is there a command or an existing script that will let me view all of a \*NIX system's scheduled cron jobs at once? I'd like it to include all of the user crontabs, as well as `/etc/crontab`, and whatever's in `/etc/cron.d`. It would also be nice to see the specific commands run by `run-parts` in `/etc/crontab`.
Ideally, I'd like the output in a nice column form and ordered in some meaningful way.
I could then merge these listings from multiple servers to view the overall "schedule of events."
I was about to write such a script myself, but if someone's already gone to the trouble... | I ended up writing a script (I'm trying to teach myself the finer points of bash scripting, so that's why you don't see something like Perl here). It's not exactly a simple affair, but it does most of what I need. It uses Kyle's suggestion for looking up individual users' crontabs, but also deals with `/etc/crontab` (including the scripts launched by `run-parts` in `/etc/cron.hourly`, `/etc/cron.daily`, etc.) and the jobs in the `/etc/cron.d` directory. It takes all of those and merges them into a display something like the following:
```
mi h d m w user command
09,39 * * * * root [ -d /var/lib/php5 ] && find /var/lib/php5/ -type f -cmin +$(/usr/lib/php5/maxlifetime) -print0 | xargs -r -0 rm
47 */8 * * * root rsync -axE --delete --ignore-errors / /mirror/ >/dev/null
17 1 * * * root /etc/cron.daily/apt
17 1 * * * root /etc/cron.daily/aptitude
17 1 * * * root /etc/cron.daily/find
17 1 * * * root /etc/cron.daily/logrotate
17 1 * * * root /etc/cron.daily/man-db
17 1 * * * root /etc/cron.daily/ntp
17 1 * * * root /etc/cron.daily/standard
17 1 * * * root /etc/cron.daily/sysklogd
27 2 * * 7 root /etc/cron.weekly/man-db
27 2 * * 7 root /etc/cron.weekly/sysklogd
13 3 * * * archiver /usr/local/bin/offsite-backup 2>&1
32 3 1 * * root /etc/cron.monthly/standard
36 4 * * * yukon /home/yukon/bin/do-daily-stuff
5 5 * * * archiver /usr/local/bin/update-logs >/dev/null
```
Note that it shows the user, and more-or-less sorts by hour and minute so that I can see the daily schedule.
So far, I've tested it on Ubuntu, Debian, and Red Hat AS.
```sh
#!/bin/bash
# System-wide crontab file and cron job directory. Change these for your system.
CRONTAB='/etc/crontab'
CRONDIR='/etc/cron.d'
# Single tab character. Annoyingly necessary.
tab=$(echo -en "\t")
# Given a stream of crontab lines, exclude non-cron job lines, replace
# whitespace characters with a single space, and remove any spaces from the
# beginning of each line.
function clean_cron_lines() {
while read line ; do
echo "${line}" |
egrep --invert-match '^($|\s*#|\s*[[:alnum:]_]+=)' |
sed --regexp-extended "s/\s+/ /g" |
sed --regexp-extended "s/^ //"
done;
}
# Given a stream of cleaned crontab lines, echo any that don't include the
# run-parts command, and for those that do, show each job file in the run-parts
# directory as if it were scheduled explicitly.
function lookup_run_parts() {
while read line ; do
match=$(echo "${line}" | egrep -o 'run-parts (-{1,2}\S+ )*\S+')
if [[ -z "${match}" ]] ; then
echo "${line}"
else
cron_fields=$(echo "${line}" | cut -f1-6 -d' ')
cron_job_dir=$(echo "${match}" | awk '{print $NF}')
if [[ -d "${cron_job_dir}" ]] ; then
for cron_job_file in "${cron_job_dir}"/* ; do # */ <not a comment>
[[ -f "${cron_job_file}" ]] && echo "${cron_fields} ${cron_job_file}"
done
fi
fi
done;
}
# Temporary file for crontab lines.
temp=$(mktemp) || exit 1
# Add all of the jobs from the system-wide crontab file.
cat "${CRONTAB}" | clean_cron_lines | lookup_run_parts >"${temp}"
# Add all of the jobs from the system-wide cron directory.
cat "${CRONDIR}"/* | clean_cron_lines >>"${temp}" # */ <not a comment>
# Add each user's crontab (if it exists). Insert the user's name between the
# five time fields and the command.
while read user ; do
crontab -l -u "${user}" 2>/dev/null |
clean_cron_lines |
sed --regexp-extended "s/^((\S+ +){5})(.+)$/\1${user} \3/" >>"${temp}"
done < <(cut --fields=1 --delimiter=: /etc/passwd)
# Output the collected crontab lines. Replace the single spaces between the
# fields with tab characters, sort the lines by hour and minute, insert the
# header line, and format the results as a table.
cat "${temp}" |
sed --regexp-extended "s/^(\S+) +(\S+) +(\S+) +(\S+) +(\S+) +(\S+) +(.*)$/\1\t\2\t\3\t\4\t\5\t\6\t\7/" |
sort --numeric-sort --field-separator="${tab}" --key=2,1 |
sed "1i\mi\th\td\tm\tw\tuser\tcommand" |
column -s"${tab}" -t
rm --force "${temp}"
``` |
134,917 | <p>We will need to call out to a 3rd party to retrieve a value using REST, however if we do not receive a response within 10ms, I want to use a default value and continue processing.</p>
<p>I'm leaning towards using an asynchronous WebRequest do to this, but I was wondering if there was a trick to doing it using a synchronous request.</p>
<p>Any advice?</p>
| [
{
"answer_id": 135004,
"author": "Philip Rieck",
"author_id": 12643,
"author_profile": "https://Stackoverflow.com/users/12643",
"pm_score": 2,
"selected": false,
"text": "<p>If you are doing a request and waiting on it to return I'd say stay synchronous - there's no reason to do an async request if you're not going to do anything or stay responsive while waiting.</p>\n\n<p>For a sync call:</p>\n\n<pre><code>WebRequest request = WebRequest.Create(\"http://something.somewhere/url\");\nWebResponse response = null;\nrequest.Timeout = 10000; // 10 second timeout\ntry\n{\n response = request.GetResponse();\n}\ncatch(WebException e)\n{\n if( e.Status == WebExceptionStatus.Timeout)\n {\n //something\n }\n}\n</code></pre>\n\n<p>If doing async:</p>\n\n<p>You will have to call Abort() on the request object - you'll need to check the timeout yourself, there's no built-in way to enforce a hard timeout.</p>\n"
},
{
"answer_id": 135147,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 0,
"selected": false,
"text": "<p>You could encapsulate your call to the 3rd party in a WebService. You could then call this WebService synchronously from your application - the web service reference has a simple timeout property that you can set to 10 seconds or whatever.</p>\n\n<p>Your call to get the 3rd party data from your WebService will throw a WebException after the timeout period has elapsed. You catch it and use a default value instead.</p>\n\n<p>EDIT: Philip's response above is better. RIF.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
]
| We will need to call out to a 3rd party to retrieve a value using REST, however if we do not receive a response within 10ms, I want to use a default value and continue processing.
I'm leaning towards using an asynchronous WebRequest do to this, but I was wondering if there was a trick to doing it using a synchronous request.
Any advice? | If you are doing a request and waiting on it to return I'd say stay synchronous - there's no reason to do an async request if you're not going to do anything or stay responsive while waiting.
For a sync call:
```
WebRequest request = WebRequest.Create("http://something.somewhere/url");
WebResponse response = null;
request.Timeout = 10000; // 10 second timeout
try
{
response = request.GetResponse();
}
catch(WebException e)
{
if( e.Status == WebExceptionStatus.Timeout)
{
//something
}
}
```
If doing async:
You will have to call Abort() on the request object - you'll need to check the timeout yourself, there's no built-in way to enforce a hard timeout. |
134,934 | <p>How do I display a leading zero for all numbers with less than two digits?</p>
<pre class="lang-none prettyprint-override"><code>1 → 01
10 → 10
100 → 100
</code></pre>
| [
{
"answer_id": 134942,
"author": "nosklo",
"author_id": 17160,
"author_profile": "https://Stackoverflow.com/users/17160",
"pm_score": 6,
"selected": false,
"text": "<pre><code>x = [1, 10, 100]\nfor i in x:\n print '%02d' % i\n</code></pre>\n<p>results in:</p>\n<pre class=\"lang-none prettyprint-override\"><code>01\n10\n100\n</code></pre>\n<p>Read <a href=\"https://pyformat.info/\" rel=\"noreferrer\">more information about string formatting using %</a> in the documentation.</p>\n"
},
{
"answer_id": 134951,
"author": "Jack M.",
"author_id": 3421,
"author_profile": "https://Stackoverflow.com/users/3421",
"pm_score": 12,
"selected": true,
"text": "<p>In Python 2 (and Python 3) you can do:</p>\n<pre><code>number = 1\nprint("%02d" % (number,))\n</code></pre>\n<p>Basically <strong>%</strong> is like <code>printf</code> or <code>sprintf</code> (see <a href=\"https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting\" rel=\"noreferrer\">docs</a>).</p>\n<hr />\n<p>For Python 3.+, the same behavior can also be achieved with <a href=\"https://docs.python.org/3/library/stdtypes.html#str.format\" rel=\"noreferrer\"><code>format</code></a>:</p>\n<pre><code>number = 1\nprint("{:02d}".format(number))\n</code></pre>\n<hr />\n<p>For Python 3.6+ the same behavior can be achieved with <a href=\"https://docs.python.org/3/reference/lexical_analysis.html#f-strings\" rel=\"noreferrer\">f-strings</a>:</p>\n<pre><code>number = 1\nprint(f"{number:02d}")\n</code></pre>\n"
},
{
"answer_id": 134961,
"author": "Airsource Ltd",
"author_id": 18017,
"author_profile": "https://Stackoverflow.com/users/18017",
"pm_score": 3,
"selected": false,
"text": "<p>Use a format string - <a href=\"http://docs.python.org/lib/typesseq-strings.html\" rel=\"noreferrer\">http://docs.python.org/lib/typesseq-strings.html</a></p>\n\n<p>For example:</p>\n\n<pre><code>python -c 'print \"%(num)02d\" % {\"num\":5}'\n</code></pre>\n"
},
{
"answer_id": 135157,
"author": "Ber",
"author_id": 11527,
"author_profile": "https://Stackoverflow.com/users/11527",
"pm_score": 9,
"selected": false,
"text": "<p>In Python 2.6+ and 3.0+, you would use the <a href=\"https://docs.python.org/library/stdtypes.html#str.format\" rel=\"noreferrer\"><code>format()</code></a> string method:</p>\n\n<pre><code>for i in (1, 10, 100):\n print('{num:02d}'.format(num=i))\n</code></pre>\n\n<p>or using the built-in (for a single number):</p>\n\n<pre><code>print(format(i, '02d'))\n</code></pre>\n\n<p>See the <a href=\"http://www.python.org/dev/peps/pep-3101\" rel=\"noreferrer\">PEP-3101</a> documentation for the new formatting functions.</p>\n"
},
{
"answer_id": 3371180,
"author": "Datageek",
"author_id": 328989,
"author_profile": "https://Stackoverflow.com/users/328989",
"pm_score": 10,
"selected": false,
"text": "<p>You can use <a href=\"https://docs.python.org/2/library/stdtypes.html#str.zfill\" rel=\"noreferrer\"><code>str.zfill</code></a>:</p>\n<pre><code>print(str(1).zfill(2))\nprint(str(10).zfill(2))\nprint(str(100).zfill(2))\n</code></pre>\n<p>prints:</p>\n<pre class=\"lang-none prettyprint-override\"><code>01\n10\n100\n</code></pre>\n"
},
{
"answer_id": 4143246,
"author": "ajd",
"author_id": 503017,
"author_profile": "https://Stackoverflow.com/users/503017",
"pm_score": 7,
"selected": false,
"text": "<p>Or this:</p>\n\n<p><code>print '{0:02d}'.format(1)</code></p>\n"
},
{
"answer_id": 10358441,
"author": "ZuLu",
"author_id": 1100233,
"author_profile": "https://Stackoverflow.com/users/1100233",
"pm_score": 6,
"selected": false,
"text": "<p>The Pythonic way to do this:</p>\n<pre><code>str(number).rjust(string_width, fill_char)\n</code></pre>\n<p>This way, the original string is returned unchanged if its length is greater than string_width. Example:</p>\n<pre><code>a = [1, 10, 100]\nfor num in a:\n print str(num).rjust(2, '0')\n</code></pre>\n<p>Results:</p>\n<pre class=\"lang-none prettyprint-override\"><code>01\n10\n100\n</code></pre>\n"
},
{
"answer_id": 19962689,
"author": "Kresimir",
"author_id": 1127700,
"author_profile": "https://Stackoverflow.com/users/1127700",
"pm_score": 7,
"selected": false,
"text": "<pre><code>print('{:02}'.format(1))\nprint('{:02}'.format(10))\nprint('{:02}'.format(100))\n</code></pre>\n<p>prints:</p>\n<pre class=\"lang-none prettyprint-override\"><code>01\n10\n100\n</code></pre>\n"
},
{
"answer_id": 20005921,
"author": "nvd",
"author_id": 1943525,
"author_profile": "https://Stackoverflow.com/users/1943525",
"pm_score": 2,
"selected": false,
"text": "<pre><code>width = 5\nnum = 3\nformatted = (width - len(str(num))) * \"0\" + str(num)\nprint formatted\n</code></pre>\n"
},
{
"answer_id": 33860138,
"author": "WinterChilly",
"author_id": 4527839,
"author_profile": "https://Stackoverflow.com/users/4527839",
"pm_score": 5,
"selected": false,
"text": "<p>Or another solution. </p>\n\n<pre><code>\"{:0>2}\".format(number)\n</code></pre>\n"
},
{
"answer_id": 35497237,
"author": "Knowbody",
"author_id": 4526483,
"author_profile": "https://Stackoverflow.com/users/4526483",
"pm_score": -1,
"selected": false,
"text": "<p>If dealing with numbers that are either one or two digits:</p>\n\n<p><code>'0'+str(number)[-2:]</code> or <code>'0{0}'.format(number)[-2:]</code></p>\n"
},
{
"answer_id": 47534472,
"author": "Dimitris Fasarakis Hilliard",
"author_id": 4952130,
"author_profile": "https://Stackoverflow.com/users/4952130",
"pm_score": 7,
"selected": false,
"text": "<p>In <strong>Python >= 3.6</strong>, you can do this succinctly with the new f-strings that were introduced by using:</p>\n<pre><code>f'{val:02}'\n</code></pre>\n<p>which prints the variable with name <code>val</code> with a <a href=\"https://docs.python.org/3/library/string.html#grammar-token-fill\" rel=\"noreferrer\"><code>fill</code></a> value of <code>0</code> and a <a href=\"https://docs.python.org/3/library/string.html#grammar-token-width\" rel=\"noreferrer\"><code>width</code></a> of <code>2</code>.</p>\n<p>For your specific example you can do this nicely in a loop:</p>\n<pre><code>a, b, c = 1, 10, 100\nfor val in [a, b, c]:\n print(f'{val:02}')\n</code></pre>\n<p>which prints:</p>\n<pre class=\"lang-none prettyprint-override\"><code>01 \n10\n100\n</code></pre>\n<hr />\n<p>For more information on f-strings, take a look at <a href=\"https://www.python.org/dev/peps/pep-0498/\" rel=\"noreferrer\">PEP 498</a> where they were introduced.</p>\n"
},
{
"answer_id": 49942659,
"author": "Linekio",
"author_id": 9675003,
"author_profile": "https://Stackoverflow.com/users/9675003",
"pm_score": 2,
"selected": false,
"text": "<p>Use:</p>\n\n<pre><code>'00'[len(str(i)):] + str(i)\n</code></pre>\n\n<p>Or with the <code>math</code> module:</p>\n\n<pre><code>import math\n'00'[math.ceil(math.log(i, 10)):] + str(i)\n</code></pre>\n"
},
{
"answer_id": 50958859,
"author": "Roberto",
"author_id": 183713,
"author_profile": "https://Stackoverflow.com/users/183713",
"pm_score": 3,
"selected": false,
"text": "<p>This is how I do it:</p>\n\n<pre><code>str(1).zfill(len(str(total)))\n</code></pre>\n\n<p>Basically zfill takes the number of leading zeros you want to add, so it's easy to take the biggest number, turn it into a string and get the length, like this:</p>\n\n<pre>\nPython 3.6.5 (default, May 11 2018, 04:00:52) \n[GCC 8.1.0] on linux\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> total = 100\n>>> print(str(1).zfill(len(str(total))))\n001\n>>> total = 1000\n>>> print(str(1).zfill(len(str(total))))\n0001\n>>> total = 10000\n>>> print(str(1).zfill(len(str(total))))\n00001\n>>> \n</pre>\n"
},
{
"answer_id": 60642717,
"author": "Nicolas Gervais",
"author_id": 10908375,
"author_profile": "https://Stackoverflow.com/users/10908375",
"pm_score": 3,
"selected": false,
"text": "<p>You can do this with <em>f strings</em>.</p>\n\n<pre><code>import numpy as np\n\nprint(f'{np.random.choice([1, 124, 13566]):0>8}')\n</code></pre>\n\n<p>This will print constant length of 8, and pad the rest with leading <code>0</code>.</p>\n\n<pre><code>00000001\n00000124\n00013566\n</code></pre>\n"
},
{
"answer_id": 66553049,
"author": "handle",
"author_id": 1619432,
"author_profile": "https://Stackoverflow.com/users/1619432",
"pm_score": 2,
"selected": false,
"text": "<p>All of these create the string "01":</p>\n<pre><code>>python -m timeit "'{:02d}'.format(1)"\n1000000 loops, best of 5: 357 nsec per loop\n\n>python -m timeit "'{0:0{1}d}'.format(1,2)"\n500000 loops, best of 5: 607 nsec per loop\n\n>python -m timeit "f'{1:02d}'"\n1000000 loops, best of 5: 281 nsec per loop\n\n>python -m timeit "f'{1:0{2}d}'"\n500000 loops, best of 5: 423 nsec per loop\n\n>python -m timeit "str(1).zfill(2)"\n1000000 loops, best of 5: 271 nsec per loop\n\n>python\nPython 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32\n</code></pre>\n"
},
{
"answer_id": 69416441,
"author": "Zahid Riaz",
"author_id": 16918593,
"author_profile": "https://Stackoverflow.com/users/16918593",
"pm_score": 1,
"selected": false,
"text": "<p>This would be the Python way, although I would include the parameter for clarity - "{0:0>2}".format(number), if someone will wants nLeadingZeros they should note they can also do:"{0:0>{1}}".format(number, nLeadingZeros + 1)</p>\n"
},
{
"answer_id": 72264376,
"author": "Stuart Demmer",
"author_id": 19106782,
"author_profile": "https://Stackoverflow.com/users/19106782",
"pm_score": 1,
"selected": false,
"text": "<p>You could also do:</p>\n<pre><code>'{:0>2}'.format(1)\n</code></pre>\n<p>which will return a string.</p>\n"
},
{
"answer_id": 74377641,
"author": "thosbrown",
"author_id": 20460618,
"author_profile": "https://Stackoverflow.com/users/20460618",
"pm_score": -1,
"selected": false,
"text": "<p>Its built into python with string formatting</p>\n<pre><code>f'{number:02d}'\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22306/"
]
| How do I display a leading zero for all numbers with less than two digits?
```none
1 → 01
10 → 10
100 → 100
``` | In Python 2 (and Python 3) you can do:
```
number = 1
print("%02d" % (number,))
```
Basically **%** is like `printf` or `sprintf` (see [docs](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting)).
---
For Python 3.+, the same behavior can also be achieved with [`format`](https://docs.python.org/3/library/stdtypes.html#str.format):
```
number = 1
print("{:02d}".format(number))
```
---
For Python 3.6+ the same behavior can be achieved with [f-strings](https://docs.python.org/3/reference/lexical_analysis.html#f-strings):
```
number = 1
print(f"{number:02d}")
``` |
134,958 | <p>How would I be able to get N results for several groups in
an oracle query.</p>
<p>For example, given the following table:</p>
<pre><code>|--------+------------+------------|
| emp_id | name | occupation |
|--------+------------+------------|
| 1 | John Smith | Accountant |
| 2 | Jane Doe | Engineer |
| 3 | Jack Black | Funnyman |
|--------+------------+------------|
</code></pre>
<p>There are many more rows with more occupations. I would like to get
three employees (lets say) from each occupation.</p>
<p>Is there a way to do this without using a subquery?</p>
| [
{
"answer_id": 135046,
"author": "billjamesdev",
"author_id": 13824,
"author_profile": "https://Stackoverflow.com/users/13824",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure this is very efficient, but maybe a starting place?</p>\n\n<pre><code>select *\nfrom people p1\n join people p2\n on p1.occupation = p2.occupation\n join people p3\n on p1.occupation = p3.occupation\n and p2.occupation = p3.occupation\nwhere p1.emp_id != p2.emp_id\n and p1.emp_id != p3.emp_id\n</code></pre>\n\n<p>This should give you rows that contain 3 distinct employees all in the same occupation. Unfortunately, it will give you ALL combinations of those.</p>\n\n<p>Can anyone pare this down please?</p>\n"
},
{
"answer_id": 135064,
"author": "jop",
"author_id": 11830,
"author_profile": "https://Stackoverflow.com/users/11830",
"pm_score": 5,
"selected": false,
"text": "<p>I don't have an oracle instance handy right now so I have not tested this:</p>\n\n<pre><code>select *\nfrom (select emp_id, name, occupation,\n rank() over ( partition by occupation order by emp_id) rank\n from employee)\nwhere rank <= 3\n</code></pre>\n\n<p>Here is a link on how rank works: <a href=\"http://www.psoug.org/reference/rank.html\" rel=\"noreferrer\">http://www.psoug.org/reference/rank.html</a></p>\n"
},
{
"answer_id": 135101,
"author": "Leon Tayson",
"author_id": 18413,
"author_profile": "https://Stackoverflow.com/users/18413",
"pm_score": 1,
"selected": false,
"text": "<p>tested this in SQL Server (and it uses subquery)</p>\n\n<pre><code>select emp_id, name, occupation\nfrom employees t1\nwhere emp_id IN (select top 3 emp_id from employees t2 where t2.occupation = t1.occupation)\n</code></pre>\n\n<p>just do an ORDER by in the subquery to suit your needs</p>\n"
},
{
"answer_id": 135977,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 5,
"selected": true,
"text": "<p>This produces what you want, and it uses no vendor-specific SQL features like TOP N or RANK(). </p>\n\n<pre><code>SELECT MAX(e.name) AS name, MAX(e.occupation) AS occupation \nFROM emp e \n LEFT OUTER JOIN emp e2 \n ON (e.occupation = e2.occupation AND e.emp_id <= e2.emp_id) \nGROUP BY e.emp_id \nHAVING COUNT(*) <= 3 \nORDER BY occupation;\n</code></pre>\n\n<p>In this example it gives the three employees with the lowest emp_id values per occupation. You can change the attribute used in the inequality comparison, to make it give the top employees by name, or whatever.</p>\n"
},
{
"answer_id": 6263662,
"author": "trung",
"author_id": 787235,
"author_profile": "https://Stackoverflow.com/users/787235",
"pm_score": 2,
"selected": false,
"text": "<p>Add RowNum to rank :</p>\n\n<pre><code>select * from \n (select emp_id, name, occupation,rank() over ( partition by occupation order by emp_id,RowNum) rank \n from employee) \n where rank <= 3 \n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/134958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9435/"
]
| How would I be able to get N results for several groups in
an oracle query.
For example, given the following table:
```
|--------+------------+------------|
| emp_id | name | occupation |
|--------+------------+------------|
| 1 | John Smith | Accountant |
| 2 | Jane Doe | Engineer |
| 3 | Jack Black | Funnyman |
|--------+------------+------------|
```
There are many more rows with more occupations. I would like to get
three employees (lets say) from each occupation.
Is there a way to do this without using a subquery? | This produces what you want, and it uses no vendor-specific SQL features like TOP N or RANK().
```
SELECT MAX(e.name) AS name, MAX(e.occupation) AS occupation
FROM emp e
LEFT OUTER JOIN emp e2
ON (e.occupation = e2.occupation AND e.emp_id <= e2.emp_id)
GROUP BY e.emp_id
HAVING COUNT(*) <= 3
ORDER BY occupation;
```
In this example it gives the three employees with the lowest emp\_id values per occupation. You can change the attribute used in the inequality comparison, to make it give the top employees by name, or whatever. |
135,000 | <p>When generating XML from XmlDocument in .NET, a blank <code>xmlns</code> attribute appears the first time an element <em>without</em> an associated namespace is inserted; how can this be prevented?</p>
<p>Example:</p>
<pre><code>XmlDocument xml = new XmlDocument();
xml.AppendChild(xml.CreateElement("root",
"whatever:name-space-1.0"));
xml.DocumentElement.AppendChild(xml.CreateElement("loner"));
Console.WriteLine(xml.OuterXml);
</code></pre>
<p>Output:</p>
<pre><code><root xmlns="whatever:name-space-1.0"><loner xmlns="" /></root>
</code></pre>
<p><em>Desired</em> Output:</p>
<pre><code><root xmlns="whatever:name-space-1.0"><loner /></root>
</code></pre>
<p>Is there a solution applicable to the <code>XmlDocument</code> code, not something that occurs <em>after</em> converting the document to a string with <code>OuterXml</code>?</p>
<p>My reasoning for doing this is to see if I can match the standard XML of a particular protocol using XmlDocument-generated XML. The blank <code>xmlns</code> attribute <em>may</em> not break or confuse a parser, but it's also not present in any usage that I've seen of this protocol.</p>
| [
{
"answer_id": 135027,
"author": "JeniT",
"author_id": 6739,
"author_profile": "https://Stackoverflow.com/users/6739",
"pm_score": 4,
"selected": false,
"text": "<p>If the <code><loner></code> element in your sample XML didn't have the <code>xmlns</code> default namespace declaration on it, then it would be in the <code>whatever:name-space-1.0</code> namespace rather than being in no namespace. If that's what you want, you need to create the element in that namespace:</p>\n\n<pre><code>xml.CreateElement(\"loner\", \"whatever:name-space-1.0\")\n</code></pre>\n\n<p>If you want the <code><loner></code> element to be in no namespace, then the XML that's been produced is exactly what you need, and you shouldn't worry about the <code>xmlns</code> attribute that's been added automatically for you.</p>\n"
},
{
"answer_id": 135066,
"author": "jlew",
"author_id": 7450,
"author_profile": "https://Stackoverflow.com/users/7450",
"pm_score": 3,
"selected": false,
"text": "<p>Since root is in an unprefixed namespace, any child of root that wants to be un-namespaced has to be output like your example. The solution would be to prefix the root element like so:</p>\n\n<pre><code><w:root xmlns:w=\"whatever:name-space-1.0\">\n <loner/>\n</w:root>\n</code></pre>\n\n<p>code:</p>\n\n<pre><code>XmlDocument doc = new XmlDocument();\nXmlElement root = doc.CreateElement( \"w\", \"root\", \"whatever:name-space-1.0\" );\ndoc.AppendChild( root );\nroot.AppendChild( doc.CreateElement( \"loner\" ) );\nConsole.WriteLine(doc.OuterXml);\n</code></pre>\n"
},
{
"answer_id": 135525,
"author": "ilitirit",
"author_id": 9825,
"author_profile": "https://Stackoverflow.com/users/9825",
"pm_score": 0,
"selected": false,
"text": "<p>If possible, create a serialization class then do:</p>\n\n<pre><code>XmlSerializerNamespaces ns = new XmlSerializerNamespaces();\nns.Add(\"\", \"\");\nXmlSerializer serializer = new XmlSerializer(yourType);\nserializer.Serialize(xmlTextWriter, someObject, ns);\n</code></pre>\n\n<p>It's safer, and you can control the namespaces with attributes if you really need more control.</p>\n"
},
{
"answer_id": 135982,
"author": "Neil C. Obremski",
"author_id": 9642,
"author_profile": "https://Stackoverflow.com/users/9642",
"pm_score": 8,
"selected": true,
"text": "<p>Thanks to Jeremy Lew's answer and a bit more playing around, I figured out how to remove blank <code>xmlns</code> attributes: pass in the root node's namespace when creating any child node you want <em>not</em> to have a prefix on. Using a namespace without a prefix at the root means that you need to use that same namespace on child elements for them to <em>also</em> not have prefixes.</p>\n\n<p>Fixed Code:</p>\n\n<pre><code>XmlDocument xml = new XmlDocument();\nxml.AppendChild(xml.CreateElement(\"root\", \"whatever:name-space-1.0\"));\nxml.DocumentElement.AppendChild(xml.CreateElement(\"loner\", \"whatever:name-space-1.0\")); \nConsole.WriteLine(xml.OuterXml);\n</code></pre>\n\n<p>Thanks everyone to all your answers which led me in the right direction!</p>\n"
},
{
"answer_id": 5093771,
"author": "brinke",
"author_id": 630565,
"author_profile": "https://Stackoverflow.com/users/630565",
"pm_score": 0,
"selected": false,
"text": "<p>I've solved the problem by using the Factory Pattern. I created a factory for XElement objects. As parameter for the instantiation of the factory I've specified a XNamespace object. So, everytime a XElement is created by the factory the namespace will be added automatically. Here is the code of the factory:</p>\n\n<pre><code>internal class XElementFactory\n{\n private readonly XNamespace currentNs;\n\n public XElementFactory(XNamespace ns)\n {\n this.currentNs = ns;\n }\n\n internal XElement CreateXElement(String name, params object[] content)\n {\n return new XElement(currentNs + name, content);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 8676037,
"author": "C.J.",
"author_id": 321866,
"author_profile": "https://Stackoverflow.com/users/321866",
"pm_score": 7,
"selected": false,
"text": "<p>This is a variant of JeniT's answer (Thank you very very much btw!)</p>\n\n<pre><code>XmlElement new_element = doc.CreateElement(\"Foo\", doc.DocumentElement.NamespaceURI);\n</code></pre>\n\n<p>This eliminates having to copy or repeat the namespace everywhere.</p>\n"
},
{
"answer_id": 30685927,
"author": "Debabrata Ghosh",
"author_id": 4981856,
"author_profile": "https://Stackoverflow.com/users/4981856",
"pm_score": 0,
"selected": false,
"text": "<p>Yes you can prevent the XMLNS from the XmlElement .\nFirst Creating time it is coming : like that</p>\n\n<pre><code><trkpt lat=\"30.53597\" lon=\"-97.753324\" xmlns=\"\">\n <ele>249.118774</ele>\n <time>2006-05-05T14:34:44Z</time>\n</trkpt>\n</code></pre>\n\n<p>Change the code : And pass xml namespace\nlike this</p>\n\n<p>C# code:</p>\n\n<pre><code>XmlElement bookElement = xdoc.CreateElement(\"trkpt\", \"http://www.topografix.com/GPX/1/1\");\nbookElement.SetAttribute(\"lat\", \"30.53597\");\nbookElement.SetAttribute(\"lon\", \"97.753324\");\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9642/"
]
| When generating XML from XmlDocument in .NET, a blank `xmlns` attribute appears the first time an element *without* an associated namespace is inserted; how can this be prevented?
Example:
```
XmlDocument xml = new XmlDocument();
xml.AppendChild(xml.CreateElement("root",
"whatever:name-space-1.0"));
xml.DocumentElement.AppendChild(xml.CreateElement("loner"));
Console.WriteLine(xml.OuterXml);
```
Output:
```
<root xmlns="whatever:name-space-1.0"><loner xmlns="" /></root>
```
*Desired* Output:
```
<root xmlns="whatever:name-space-1.0"><loner /></root>
```
Is there a solution applicable to the `XmlDocument` code, not something that occurs *after* converting the document to a string with `OuterXml`?
My reasoning for doing this is to see if I can match the standard XML of a particular protocol using XmlDocument-generated XML. The blank `xmlns` attribute *may* not break or confuse a parser, but it's also not present in any usage that I've seen of this protocol. | Thanks to Jeremy Lew's answer and a bit more playing around, I figured out how to remove blank `xmlns` attributes: pass in the root node's namespace when creating any child node you want *not* to have a prefix on. Using a namespace without a prefix at the root means that you need to use that same namespace on child elements for them to *also* not have prefixes.
Fixed Code:
```
XmlDocument xml = new XmlDocument();
xml.AppendChild(xml.CreateElement("root", "whatever:name-space-1.0"));
xml.DocumentElement.AppendChild(xml.CreateElement("loner", "whatever:name-space-1.0"));
Console.WriteLine(xml.OuterXml);
```
Thanks everyone to all your answers which led me in the right direction! |
135,010 | <p>I have a problem with stopping a service and starting it again and want to be notified when the process runs and let me know what the result is. </p>
<p>Here's the scenario,
I have a text file output of an "sc" command. I want to send that file but not as an attachment. Also, I want to see the initial status quickly in the subject of the email.</p>
<p>Here's the 'servstop.txt' file contents:</p>
<blockquote>
<p>[SC] StartService FAILED 1058:</p>
<p>The service cannot be started, either
because it is disabled or because it
has no enabled devices associated with
it.</p>
</blockquote>
<p>I want the subject of the email to be "Alert Service Start: [SC] StartService FAILED 1058"
and the body to contain the entire error message above.</p>
<p>I will put my current method in an answer below using a program called blat to send me the result.</p>
| [
{
"answer_id": 135027,
"author": "JeniT",
"author_id": 6739,
"author_profile": "https://Stackoverflow.com/users/6739",
"pm_score": 4,
"selected": false,
"text": "<p>If the <code><loner></code> element in your sample XML didn't have the <code>xmlns</code> default namespace declaration on it, then it would be in the <code>whatever:name-space-1.0</code> namespace rather than being in no namespace. If that's what you want, you need to create the element in that namespace:</p>\n\n<pre><code>xml.CreateElement(\"loner\", \"whatever:name-space-1.0\")\n</code></pre>\n\n<p>If you want the <code><loner></code> element to be in no namespace, then the XML that's been produced is exactly what you need, and you shouldn't worry about the <code>xmlns</code> attribute that's been added automatically for you.</p>\n"
},
{
"answer_id": 135066,
"author": "jlew",
"author_id": 7450,
"author_profile": "https://Stackoverflow.com/users/7450",
"pm_score": 3,
"selected": false,
"text": "<p>Since root is in an unprefixed namespace, any child of root that wants to be un-namespaced has to be output like your example. The solution would be to prefix the root element like so:</p>\n\n<pre><code><w:root xmlns:w=\"whatever:name-space-1.0\">\n <loner/>\n</w:root>\n</code></pre>\n\n<p>code:</p>\n\n<pre><code>XmlDocument doc = new XmlDocument();\nXmlElement root = doc.CreateElement( \"w\", \"root\", \"whatever:name-space-1.0\" );\ndoc.AppendChild( root );\nroot.AppendChild( doc.CreateElement( \"loner\" ) );\nConsole.WriteLine(doc.OuterXml);\n</code></pre>\n"
},
{
"answer_id": 135525,
"author": "ilitirit",
"author_id": 9825,
"author_profile": "https://Stackoverflow.com/users/9825",
"pm_score": 0,
"selected": false,
"text": "<p>If possible, create a serialization class then do:</p>\n\n<pre><code>XmlSerializerNamespaces ns = new XmlSerializerNamespaces();\nns.Add(\"\", \"\");\nXmlSerializer serializer = new XmlSerializer(yourType);\nserializer.Serialize(xmlTextWriter, someObject, ns);\n</code></pre>\n\n<p>It's safer, and you can control the namespaces with attributes if you really need more control.</p>\n"
},
{
"answer_id": 135982,
"author": "Neil C. Obremski",
"author_id": 9642,
"author_profile": "https://Stackoverflow.com/users/9642",
"pm_score": 8,
"selected": true,
"text": "<p>Thanks to Jeremy Lew's answer and a bit more playing around, I figured out how to remove blank <code>xmlns</code> attributes: pass in the root node's namespace when creating any child node you want <em>not</em> to have a prefix on. Using a namespace without a prefix at the root means that you need to use that same namespace on child elements for them to <em>also</em> not have prefixes.</p>\n\n<p>Fixed Code:</p>\n\n<pre><code>XmlDocument xml = new XmlDocument();\nxml.AppendChild(xml.CreateElement(\"root\", \"whatever:name-space-1.0\"));\nxml.DocumentElement.AppendChild(xml.CreateElement(\"loner\", \"whatever:name-space-1.0\")); \nConsole.WriteLine(xml.OuterXml);\n</code></pre>\n\n<p>Thanks everyone to all your answers which led me in the right direction!</p>\n"
},
{
"answer_id": 5093771,
"author": "brinke",
"author_id": 630565,
"author_profile": "https://Stackoverflow.com/users/630565",
"pm_score": 0,
"selected": false,
"text": "<p>I've solved the problem by using the Factory Pattern. I created a factory for XElement objects. As parameter for the instantiation of the factory I've specified a XNamespace object. So, everytime a XElement is created by the factory the namespace will be added automatically. Here is the code of the factory:</p>\n\n<pre><code>internal class XElementFactory\n{\n private readonly XNamespace currentNs;\n\n public XElementFactory(XNamespace ns)\n {\n this.currentNs = ns;\n }\n\n internal XElement CreateXElement(String name, params object[] content)\n {\n return new XElement(currentNs + name, content);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 8676037,
"author": "C.J.",
"author_id": 321866,
"author_profile": "https://Stackoverflow.com/users/321866",
"pm_score": 7,
"selected": false,
"text": "<p>This is a variant of JeniT's answer (Thank you very very much btw!)</p>\n\n<pre><code>XmlElement new_element = doc.CreateElement(\"Foo\", doc.DocumentElement.NamespaceURI);\n</code></pre>\n\n<p>This eliminates having to copy or repeat the namespace everywhere.</p>\n"
},
{
"answer_id": 30685927,
"author": "Debabrata Ghosh",
"author_id": 4981856,
"author_profile": "https://Stackoverflow.com/users/4981856",
"pm_score": 0,
"selected": false,
"text": "<p>Yes you can prevent the XMLNS from the XmlElement .\nFirst Creating time it is coming : like that</p>\n\n<pre><code><trkpt lat=\"30.53597\" lon=\"-97.753324\" xmlns=\"\">\n <ele>249.118774</ele>\n <time>2006-05-05T14:34:44Z</time>\n</trkpt>\n</code></pre>\n\n<p>Change the code : And pass xml namespace\nlike this</p>\n\n<p>C# code:</p>\n\n<pre><code>XmlElement bookElement = xdoc.CreateElement(\"trkpt\", \"http://www.topografix.com/GPX/1/1\");\nbookElement.SetAttribute(\"lat\", \"30.53597\");\nbookElement.SetAttribute(\"lon\", \"97.753324\");\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/730/"
]
| I have a problem with stopping a service and starting it again and want to be notified when the process runs and let me know what the result is.
Here's the scenario,
I have a text file output of an "sc" command. I want to send that file but not as an attachment. Also, I want to see the initial status quickly in the subject of the email.
Here's the 'servstop.txt' file contents:
>
> [SC] StartService FAILED 1058:
>
>
> The service cannot be started, either
> because it is disabled or because it
> has no enabled devices associated with
> it.
>
>
>
I want the subject of the email to be "Alert Service Start: [SC] StartService FAILED 1058"
and the body to contain the entire error message above.
I will put my current method in an answer below using a program called blat to send me the result. | Thanks to Jeremy Lew's answer and a bit more playing around, I figured out how to remove blank `xmlns` attributes: pass in the root node's namespace when creating any child node you want *not* to have a prefix on. Using a namespace without a prefix at the root means that you need to use that same namespace on child elements for them to *also* not have prefixes.
Fixed Code:
```
XmlDocument xml = new XmlDocument();
xml.AppendChild(xml.CreateElement("root", "whatever:name-space-1.0"));
xml.DocumentElement.AppendChild(xml.CreateElement("loner", "whatever:name-space-1.0"));
Console.WriteLine(xml.OuterXml);
```
Thanks everyone to all your answers which led me in the right direction! |
135,020 | <p>When creating a class that has internal private methods, usually to reduce code duplication, that don't require the use of any instance fields, are there performance or memory advantages to declaring the method as static?</p>
<p>Example:</p>
<pre><code>foreach (XmlElement element in xmlDoc.DocumentElement.SelectNodes("sample"))
{
string first = GetInnerXml(element, ".//first");
string second = GetInnerXml(element, ".//second");
string third = GetInnerXml(element, ".//third");
}
</code></pre>
<p>...</p>
<pre><code>private static string GetInnerXml(XmlElement element, string nodeName)
{
return GetInnerXml(element, nodeName, null);
}
private static string GetInnerXml(XmlElement element, string nodeName, string defaultValue)
{
XmlNode node = element.SelectSingleNode(nodeName);
return node == null ? defaultValue : node.InnerXml;
}
</code></pre>
<p>Is there any advantage to declaring the GetInnerXml() methods as static? No opinion responses please, I have an opinion.</p>
| [
{
"answer_id": 135023,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 4,
"selected": false,
"text": "<p>Yes, the compiler does not need to pass the implicit <code>this</code> pointer to <code>static</code> methods. Even if you don't use it in your instance method, it is still being passed.</p>\n"
},
{
"answer_id": 135028,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>This forces you to remember to also declare any class-scoped members the function uses as static as well, which should save the memory of creating those items for each instance.</p>\n"
},
{
"answer_id": 135033,
"author": "Free Wildebeest",
"author_id": 1849,
"author_profile": "https://Stackoverflow.com/users/1849",
"pm_score": 3,
"selected": false,
"text": "<p>It'll be slightly quicker as there is no this parameter passed (although the performance cost of calling the method is probably considerably more than this saving).</p>\n\n<p>I'd say the best reason I can think of for private static methods is that it means you can't accidentally change the object (as there's no this pointer).</p>\n"
},
{
"answer_id": 135038,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 9,
"selected": true,
"text": "<p>From the <a href=\"http://msdn.microsoft.com/en-us/library/ms245046.aspx\" rel=\"noreferrer\">FxCop rule page</a> on this:</p>\n\n<blockquote>\n <p>After you mark the methods as static, the compiler will emit non-virtual call sites to these members. Emitting non-virtual call sites will prevent a check at runtime for each call that ensures that the current object pointer is non-null. This can result in a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue.</p>\n</blockquote>\n"
},
{
"answer_id": 272841,
"author": "Neil",
"author_id": 24315,
"author_profile": "https://Stackoverflow.com/users/24315",
"pm_score": 7,
"selected": false,
"text": "<p>When I'm writing a class, most methods fall into two categories:</p>\n\n<ul>\n<li>Methods that use/change the current instance's state.</li>\n<li>Helper methods that don't use/change the current object's state, but help me compute values I need elsewhere.</li>\n</ul>\n\n<p>Static methods are useful, because just by looking at its signature, you know that the calling it doesn't use or modify the current instance's state.</p>\n\n<p>Take this example:</p>\n\n<pre>public class Library\n{\n private static Book findBook(List<Book> books, string title)\n {\n // code goes here\n }\n}</pre>\n\n<p>If an instance of library's state ever gets screwed up, and I'm trying to figure out why, I can rule out findBook as the culprit, just from its signature.</p>\n\n<p>I try to communicate as much as I can with a method or function's signature, and this is an excellent way to do that.</p>\n"
},
{
"answer_id": 12261577,
"author": "Marek Takac",
"author_id": 1157076,
"author_profile": "https://Stackoverflow.com/users/1157076",
"pm_score": 6,
"selected": false,
"text": "<blockquote>\n<p>A call to a static method generates a call instruction in Microsoft intermediate language (MSIL), whereas a call to an instance method generates a callvirt instruction, which also checks for a null object references. <strong>However, most of the time the performance difference between the two is not significant.</strong></p>\n</blockquote>\n<p>Source: MSDN - <a href=\"https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2012/79b3xss3(v=vs.110)\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2012/79b3xss3(v=vs.110)</a></p>\n"
},
{
"answer_id": 36888316,
"author": "sara",
"author_id": 2622234,
"author_profile": "https://Stackoverflow.com/users/2622234",
"pm_score": 2,
"selected": false,
"text": "<p>I very much prefer all private methods to be static unless they really can't be. I would much prefer the following:</p>\n\n<pre><code>public class MyClass\n{\n private readonly MyDependency _dependency;\n\n public MyClass(MyDependency dependency)\n {\n _dependency = dependency;\n }\n\n public int CalculateHardStuff()\n {\n var intermediate = StepOne(_dependency);\n return StepTwo(intermediate);\n }\n\n private static int StepOne(MyDependency dependency)\n {\n return dependency.GetFirst3Primes().Sum();\n }\n\n private static int StepTwo(int intermediate)\n {\n return (intermediate + 5)/4;\n }\n}\n\npublic class MyDependency\n{\n public IEnumerable<int> GetFirst3Primes()\n {\n yield return 2;\n yield return 3;\n yield return 5;\n }\n}\n</code></pre>\n\n<p>over every method accessing the instance field. Why is this? Because as this process of calculating becomes more complex and the class ends up with 15 private helper methods, then I REALLY want to be able to pull them out into a new class that encapsulates a subset of the steps in a semantically meaningful way.</p>\n\n<p>When <code>MyClass</code> gets more dependencies because we need logging and also need to notify a web service (please excuse the cliche examples), then it's really helpful to easily see what methods have which dependencies.</p>\n\n<p>Tools like R# lets you extract a class from a set of private static methods in a few keystrokes. Try doing it when all private helper methods are tightly coupled to the instance field and you'll see it can be quite a headache.</p>\n"
},
{
"answer_id": 40002114,
"author": "James Haumann",
"author_id": 6858125,
"author_profile": "https://Stackoverflow.com/users/6858125",
"pm_score": -1,
"selected": false,
"text": "<p>As has already been stated, there are many advantages to static methods. However; keep in mind that they will live on the heap for the life of the application. I recently spent a day tracking down a memory leak in a Windows Service... the leak was caused by private static methods inside a class that implemented IDisposable and was consistently called from a using statement. Each time this class was created, memory was reserved on the heap for the static methods within the class, unfortunately, when the class was disposed of, the memory for the static methods was not released. This caused the memory footprint of this service to consume the available memory of the server within a couple of days with predictable results.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6146/"
]
| When creating a class that has internal private methods, usually to reduce code duplication, that don't require the use of any instance fields, are there performance or memory advantages to declaring the method as static?
Example:
```
foreach (XmlElement element in xmlDoc.DocumentElement.SelectNodes("sample"))
{
string first = GetInnerXml(element, ".//first");
string second = GetInnerXml(element, ".//second");
string third = GetInnerXml(element, ".//third");
}
```
...
```
private static string GetInnerXml(XmlElement element, string nodeName)
{
return GetInnerXml(element, nodeName, null);
}
private static string GetInnerXml(XmlElement element, string nodeName, string defaultValue)
{
XmlNode node = element.SelectSingleNode(nodeName);
return node == null ? defaultValue : node.InnerXml;
}
```
Is there any advantage to declaring the GetInnerXml() methods as static? No opinion responses please, I have an opinion. | From the [FxCop rule page](http://msdn.microsoft.com/en-us/library/ms245046.aspx) on this:
>
> After you mark the methods as static, the compiler will emit non-virtual call sites to these members. Emitting non-virtual call sites will prevent a check at runtime for each call that ensures that the current object pointer is non-null. This can result in a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue.
>
>
> |
135,035 | <p>In ruby the library path is provided in <code>$:</code>, in perl it's in <code>@INC</code> - how do you get the list of paths that Python searches for modules when you do an import?</p>
| [
{
"answer_id": 135050,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "<pre><code>import sys\nsys.path\n</code></pre>\n"
},
{
"answer_id": 135051,
"author": "Jack M.",
"author_id": 3421,
"author_profile": "https://Stackoverflow.com/users/3421",
"pm_score": 8,
"selected": true,
"text": "<p>I think you're looking for <a href=\"https://docs.python.org/3/library/sys.html#sys.path\" rel=\"noreferrer\">sys.path</a></p>\n\n<pre><code>import sys\nprint (sys.path)\n</code></pre>\n"
},
{
"answer_id": 135273,
"author": "apg",
"author_id": 22277,
"author_profile": "https://Stackoverflow.com/users/22277",
"pm_score": 7,
"selected": false,
"text": "<p>You can also make additions to this path with the PYTHONPATH environment variable at runtime, in addition to:</p>\n\n<pre><code>import sys\nsys.path.append('/home/user/python-libs')\n</code></pre>\n"
},
{
"answer_id": 71260812,
"author": "CodeFarmer",
"author_id": 479008,
"author_profile": "https://Stackoverflow.com/users/479008",
"pm_score": 2,
"selected": false,
"text": "<pre><code>python -c "import sys; print('\\n'.join(sys.path))"\n\n\n/usr/local/Cellar/[email protected]/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python39.zip\n/usr/local/Cellar/[email protected]/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9\n/usr/local/Cellar/[email protected]/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload\n/usr/local/lib/python3.9/site-packages\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19784/"
]
| In ruby the library path is provided in `$:`, in perl it's in `@INC` - how do you get the list of paths that Python searches for modules when you do an import? | I think you're looking for [sys.path](https://docs.python.org/3/library/sys.html#sys.path)
```
import sys
print (sys.path)
``` |
135,041 | <p>Why or why not?</p>
| [
{
"answer_id": 135070,
"author": "Dan Udey",
"author_id": 21450,
"author_profile": "https://Stackoverflow.com/users/21450",
"pm_score": 4,
"selected": false,
"text": "<p><code>xrange()</code> is more efficient because instead of generating a list of objects, it just generates one object at a time. Instead of 100 integers, and all of their overhead, and the list to put them in, you just have one integer at a time. Faster generation, better memory use, more efficient code.</p>\n\n<p>Unless I specifically need a list for something, I always favor <code>xrange()</code></p>\n"
},
{
"answer_id": 135074,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 5,
"selected": false,
"text": "<p>You should favour <code>range()</code> over <code>xrange()</code> only when you need an actual list. For instance, when you want to modify the list returned by <code>range()</code>, or when you wish to slice it. For iteration or even just normal indexing, <code>xrange()</code> will work fine (and usually much more efficiently). There is a point where <code>range()</code> is a bit faster than <code>xrange()</code> for very small lists, but depending on your hardware and various other details, the break-even can be at a result of length 1 or 2; not something to worry about. Prefer <code>xrange()</code>.</p>\n"
},
{
"answer_id": 135081,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 2,
"selected": false,
"text": "<p>Go with range for these reasons:</p>\n\n<p>1) xrange will be going away in newer Python versions. This gives you easy future compatibility.</p>\n\n<p>2) range will take on the efficiencies associated with xrange.</p>\n"
},
{
"answer_id": 135114,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 10,
"selected": true,
"text": "<p>For performance, especially when you're iterating over a large range, <code>xrange()</code> is usually better. However, there are still a few cases why you might prefer <code>range()</code>:</p>\n\n<ul>\n<li><p>In python 3, <code>range()</code> does what <code>xrange()</code> used to do and <code>xrange()</code> does not exist. If you want to write code that will run on both Python 2 and Python 3, you can't use <code>xrange()</code>.</p></li>\n<li><p><code>range()</code> can actually be faster in some cases - eg. if iterating over the same sequence multiple times. <code>xrange()</code> has to reconstruct the integer object every time, but <code>range()</code> will have real integer objects. (It will always perform worse in terms of memory however)</p></li>\n<li><p><code>xrange()</code> isn't usable in all cases where a real list is needed. For instance, it doesn't support slices, or any list methods.</p></li>\n</ul>\n\n<p>[Edit] There are a couple of posts mentioning how <code>range()</code> will be upgraded by the 2to3 tool. For the record, here's the output of running the tool on some sample usages of <code>range()</code> and <code>xrange()</code></p>\n\n<pre><code>RefactoringTool: Skipping implicit fixer: buffer\nRefactoringTool: Skipping implicit fixer: idioms\nRefactoringTool: Skipping implicit fixer: ws_comma\n--- range_test.py (original)\n+++ range_test.py (refactored)\n@@ -1,7 +1,7 @@\n\n for x in range(20):\n- a=range(20)\n+ a=list(range(20))\n b=list(range(20))\n c=[x for x in range(20)]\n d=(x for x in range(20))\n- e=xrange(20)\n+ e=range(20)\n</code></pre>\n\n<p>As you can see, when used in a for loop or comprehension, or where already wrapped with list(), range is left unchanged.</p>\n"
},
{
"answer_id": 135228,
"author": "jschultz",
"author_id": 16490,
"author_profile": "https://Stackoverflow.com/users/16490",
"pm_score": 3,
"selected": false,
"text": "<p>range() returns a list, xrange() returns an xrange object.</p>\n\n<p>xrange() is a bit faster, and a bit more memory efficient. But the gain is not very large.</p>\n\n<p>The extra memory used by a list is of course not just wasted, lists have more functionality (slice, repeat, insert, ...). Exact differences can be found in the <a href=\"http://docs.python.org/typesseq.html\" rel=\"noreferrer\">documentation</a>. There is no bonehard rule, use what is needed.</p>\n\n<p>Python 3.0 is still in development, but IIRC range() will very similar to xrange() of 2.X and list(range()) can be used to generate lists.</p>\n"
},
{
"answer_id": 135531,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 2,
"selected": false,
"text": "<p>Okay, everyone here as a different opinion as to the tradeoffs and advantages of xrange versus range. They're mostly correct, xrange is an iterator, and range fleshes out and creates an actual list. For the majority of cases, you won't really notice a difference between the two. (You can use map with range but not with xrange, but it uses up more memory.)</p>\n\n<p>What I think you rally want to hear, however, is that the preferred choice is xrange. Since range in Python 3 is an iterator, the code conversion tool 2to3 will correctly convert all uses of xrange to range, and will throw out an error or warning for uses of range. If you want to be sure to easily convert your code in the future, you'll use xrange only, and list(xrange) when you're sure that you want a list. I learned this during the CPython sprint at PyCon this year (2008) in Chicago.</p>\n"
},
{
"answer_id": 135669,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 7,
"selected": false,
"text": "<p>No, they both have their uses:</p>\n\n<p>Use <code>xrange()</code> when iterating, as it saves memory. Say:</p>\n\n<pre><code>for x in xrange(1, one_zillion):\n</code></pre>\n\n<p>rather than:</p>\n\n<pre><code>for x in range(1, one_zillion):\n</code></pre>\n\n<p>On the other hand, use <code>range()</code> if you actually want a list of numbers.</p>\n\n<pre><code>multiples_of_seven = range(7,100,7)\nprint \"Multiples of seven < 100: \", multiples_of_seven\n</code></pre>\n"
},
{
"answer_id": 9641194,
"author": "Garrett Berg",
"author_id": 674076,
"author_profile": "https://Stackoverflow.com/users/674076",
"pm_score": 3,
"selected": false,
"text": "<p>I would just like to say that it REALLY isn't that difficult to get an xrange object with slice and indexing functionality. I have written some code that works pretty dang well and is just as fast as xrange for when it counts (iterations).</p>\n\n<pre><code>from __future__ import division\n\ndef read_xrange(xrange_object):\n # returns the xrange object's start, stop, and step\n start = xrange_object[0]\n if len(xrange_object) > 1:\n step = xrange_object[1] - xrange_object[0]\n else:\n step = 1\n stop = xrange_object[-1] + step\n return start, stop, step\n\nclass Xrange(object):\n ''' creates an xrange-like object that supports slicing and indexing.\n ex: a = Xrange(20)\n a.index(10)\n will work\n\n Also a[:5]\n will return another Xrange object with the specified attributes\n\n Also allows for the conversion from an existing xrange object\n '''\n def __init__(self, *inputs):\n # allow inputs of xrange objects\n if len(inputs) == 1:\n test, = inputs\n if type(test) == xrange:\n self.xrange = test\n self.start, self.stop, self.step = read_xrange(test)\n return\n\n # or create one from start, stop, step\n self.start, self.step = 0, None\n if len(inputs) == 1:\n self.stop, = inputs\n elif len(inputs) == 2:\n self.start, self.stop = inputs\n elif len(inputs) == 3:\n self.start, self.stop, self.step = inputs\n else:\n raise ValueError(inputs)\n\n self.xrange = xrange(self.start, self.stop, self.step)\n\n def __iter__(self):\n return iter(self.xrange)\n\n def __getitem__(self, item):\n if type(item) is int:\n if item < 0:\n item += len(self)\n\n return self.xrange[item]\n\n if type(item) is slice:\n # get the indexes, and then convert to the number\n start, stop, step = item.start, item.stop, item.step\n start = start if start != None else 0 # convert start = None to start = 0\n if start < 0:\n start += start\n start = self[start]\n if start < 0: raise IndexError(item)\n step = (self.step if self.step != None else 1) * (step if step != None else 1)\n stop = stop if stop is not None else self.xrange[-1]\n if stop < 0:\n stop += stop\n\n stop = self[stop]\n stop = stop\n\n if stop > self.stop:\n raise IndexError\n if start < self.start:\n raise IndexError\n return Xrange(start, stop, step)\n\n def index(self, value):\n error = ValueError('object.index({0}): {0} not in object'.format(value))\n index = (value - self.start)/self.step\n if index % 1 != 0:\n raise error\n index = int(index)\n\n\n try:\n self.xrange[index]\n except (IndexError, TypeError):\n raise error\n return index\n\n def __len__(self):\n return len(self.xrange)\n</code></pre>\n\n<p>Honestly, I think the whole issue is kind of silly and xrange should do all of this anyway...</p>\n"
},
{
"answer_id": 11795908,
"author": "Brian Minton",
"author_id": 752695,
"author_profile": "https://Stackoverflow.com/users/752695",
"pm_score": 5,
"selected": false,
"text": "<p>One other difference is that Python 2 implementation of <code>xrange()</code> can't support numbers bigger than C ints, so if you want to have a range using Python's built in large number support, you have to use <code>range()</code>.</p>\n<pre><code>Python 2.7.3 (default, Jul 13 2012, 22:29:01) \n[GCC 4.7.1] on linux2\nType "help", "copyright", "credits" or "license" for more information.\n>>> range(123456787676676767676676,123456787676676767676679)\n[123456787676676767676676L, 123456787676676767676677L, 123456787676676767676678L]\n>>> xrange(123456787676676767676676,123456787676676767676679)\nTraceback (most recent call last):\n File "<stdin>", line 1, in <module>\nOverflowError: Python int too large to convert to C long\n</code></pre>\n<p>Python 3 does not have this problem:</p>\n<pre><code>Python 3.2.3 (default, Jul 14 2012, 01:01:48) \n[GCC 4.7.1] on linux2\nType "help", "copyright", "credits" or "license" for more information.\n>>> range(123456787676676767676676,123456787676676767676679)\nrange(123456787676676767676676, 123456787676676767676679)\n</code></pre>\n"
},
{
"answer_id": 18288537,
"author": "Grijesh Chauhan",
"author_id": 1673391,
"author_profile": "https://Stackoverflow.com/users/1673391",
"pm_score": 2,
"selected": false,
"text": "<p>A good example given in book: <a href=\"http://books.google.co.in/books?id=KmKoNJ2OoOYC&pg=PA114&lpg=PA114&dq=zip%28range%285%29,%20xrange%28100000000%29%29&source=bl&ots=-BxWZinKHq&sig=O9G4mskHmYDljCCQv8v7alVUy_M&hl=en&sa=X&ei=0mMPUoa9LsXJrAe7p4DABA&ved=0CD0Q6AEwAw#v=onepage&q=zip%28range%285%29,%20xrange%28100000000%29%29&f=false\" rel=\"nofollow\">Practical Python</a> By Magnus Lie Hetland </p>\n\n<pre><code>>>> zip(range(5), xrange(100000000))\n[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]\n</code></pre>\n\n<p>I wouldn’t recommend using range instead of xrange in the preceding example—although\nonly the first five numbers are needed, range calculates all the numbers, and that may take a lot\nof time. With xrange, this isn’t a problem because it calculates only those numbers needed.</p>\n\n<p>Yes I read @Brian's answer: In python 3, range() is a generator anyway and xrange() does not exist.</p>\n"
},
{
"answer_id": 39428467,
"author": "Tushar Patil",
"author_id": 2013238,
"author_profile": "https://Stackoverflow.com/users/2013238",
"pm_score": 2,
"selected": false,
"text": "<ul>\n<li><code>range()</code>: <code>range(1, 10)</code> returns a list from 1 to 10 numbers & hold whole list in memory.</li>\n<li><code>xrange()</code>: Like <code>range()</code>, but instead of returning a list, returns an object that generates the numbers in the range on demand. For looping, this is lightly faster than <code>range()</code> and more memory efficient. <code>xrange()</code> object like an iterator and generates the numbers on demand (Lazy Evaluation).</li>\n</ul>\n\n\n\n<pre><code>In [1]: range(1,10)\nOut[1]: [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\nIn [2]: xrange(10)\nOut[2]: xrange(10)\n\nIn [3]: print xrange.__doc__\nOut[3]: xrange([start,] stop[, step]) -> xrange object\n</code></pre>\n\n<p><code>range()</code> does the same thing as <code>xrange()</code> used to do in Python 3 and there is not term <code>xrange()</code> exist in Python 3.\n<code>range()</code> can actually be faster in some scenario if you iterating over the same sequence multiple times. <code>xrange()</code> has to reconstruct the integer object every time, but <code>range()</code> will have real integer objects.</p>\n"
},
{
"answer_id": 41726540,
"author": "speedplane",
"author_id": 234270,
"author_profile": "https://Stackoverflow.com/users/234270",
"pm_score": 2,
"selected": false,
"text": "<p>While <code>xrange</code> is faster than <code>range</code> in most circumstances, the difference in performance is pretty minimal. The little program below compares iterating over a <code>range</code> and an <code>xrange</code>:</p>\n\n<pre><code>import timeit\n# Try various list sizes.\nfor list_len in [1, 10, 100, 1000, 10000, 100000, 1000000]:\n # Time doing a range and an xrange.\n rtime = timeit.timeit('a=0;\\nfor n in range(%d): a += n'%list_len, number=1000)\n xrtime = timeit.timeit('a=0;\\nfor n in xrange(%d): a += n'%list_len, number=1000)\n # Print the result\n print \"Loop list of len %d: range=%.4f, xrange=%.4f\"%(list_len, rtime, xrtime)\n</code></pre>\n\n<p>The results below shows that <code>xrange</code> is indeed faster, but not enough to sweat over.</p>\n\n<pre><code>Loop list of len 1: range=0.0003, xrange=0.0003\nLoop list of len 10: range=0.0013, xrange=0.0011\nLoop list of len 100: range=0.0068, xrange=0.0034\nLoop list of len 1000: range=0.0609, xrange=0.0438\nLoop list of len 10000: range=0.5527, xrange=0.5266\nLoop list of len 100000: range=10.1666, xrange=7.8481\nLoop list of len 1000000: range=168.3425, xrange=155.8719\n</code></pre>\n\n<p>So by all means use <code>xrange</code>, but unless you're on a constrained hardware, don't worry too much about it.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18446/"
]
| Why or why not? | For performance, especially when you're iterating over a large range, `xrange()` is usually better. However, there are still a few cases why you might prefer `range()`:
* In python 3, `range()` does what `xrange()` used to do and `xrange()` does not exist. If you want to write code that will run on both Python 2 and Python 3, you can't use `xrange()`.
* `range()` can actually be faster in some cases - eg. if iterating over the same sequence multiple times. `xrange()` has to reconstruct the integer object every time, but `range()` will have real integer objects. (It will always perform worse in terms of memory however)
* `xrange()` isn't usable in all cases where a real list is needed. For instance, it doesn't support slices, or any list methods.
[Edit] There are a couple of posts mentioning how `range()` will be upgraded by the 2to3 tool. For the record, here's the output of running the tool on some sample usages of `range()` and `xrange()`
```
RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: ws_comma
--- range_test.py (original)
+++ range_test.py (refactored)
@@ -1,7 +1,7 @@
for x in range(20):
- a=range(20)
+ a=list(range(20))
b=list(range(20))
c=[x for x in range(20)]
d=(x for x in range(20))
- e=xrange(20)
+ e=range(20)
```
As you can see, when used in a for loop or comprehension, or where already wrapped with list(), range is left unchanged. |
135,069 | <p>This may be a matter of style, but there's a bit of a divide in our dev team and I wondered if anyone else had any ideas on the matter...</p>
<p>Basically, we have some debug print statements which we turn off during normal development. Personally I prefer to do the following:</p>
<pre><code>//---- SomeSourceFile.cpp ----
#define DEBUG_ENABLED (0)
...
SomeFunction()
{
int someVariable = 5;
#if(DEBUG_ENABLED)
printf("Debugging: someVariable == %d", someVariable);
#endif
}
</code></pre>
<p>Some of the team prefer the following though:</p>
<pre><code>// #define DEBUG_ENABLED
...
SomeFunction()
{
int someVariable = 5;
#ifdef DEBUG_ENABLED
printf("Debugging: someVariable == %d", someVariable);
#endif
}
</code></pre>
<p>...which of those methods sounds better to you and why? My feeling is that the first is safer because there is always something defined and there's no danger it could destroy other defines elsewhere.</p>
| [
{
"answer_id": 135077,
"author": "Martin Beckett",
"author_id": 10897,
"author_profile": "https://Stackoverflow.com/users/10897",
"pm_score": 3,
"selected": false,
"text": "<p><code>#if</code> gives you the option of setting it to 0 to turn off the functionality, while still detecting that the switch is there.<br>\nPersonally I always <code>#define DEBUG 1</code> so I can catch it with either an #if or #ifdef</p>\n"
},
{
"answer_id": 135089,
"author": "Jim Buck",
"author_id": 2666,
"author_profile": "https://Stackoverflow.com/users/2666",
"pm_score": 3,
"selected": false,
"text": "<p>I myself prefer:</p>\n\n<pre><code>#if defined(DEBUG_ENABLED)\n</code></pre>\n\n<p>Since it makes it easier to create code that looks for the opposite condition much easier to spot:</p>\n\n<pre><code>#if !defined(DEBUG_ENABLED)\n</code></pre>\n\n<p>vs.</p>\n\n<pre><code>#ifndef(DEBUG_ENABLED)\n</code></pre>\n"
},
{
"answer_id": 135094,
"author": "axblount",
"author_id": 1729005,
"author_profile": "https://Stackoverflow.com/users/1729005",
"pm_score": 2,
"selected": false,
"text": "<p>The first seems clearer to me. It seems more natural make it a flag as compared to defined/not defined.</p>\n"
},
{
"answer_id": 135104,
"author": "Dima",
"author_id": 13313,
"author_profile": "https://Stackoverflow.com/users/13313",
"pm_score": 0,
"selected": false,
"text": "<p>Alternatively, you can declare a global constant, and use the C++ if, instead of the preprocessor #if. The compiler should optimize the unused branches away for you, and your code will be cleaner.</p>\n\n<p>Here is what <a href=\"http://books.google.com/books?id=L5ZbzVnpkXAC&pg=PA69&lpg=PA69&dq=C%2B%2B+gotchas+%23ifdef&source=web&ots=Rl36PkXigd&sig=bFPFNrvlXU-g0I9HQ0OpvcBEC0M&hl=en&sa=X&oi=book_result&resnum=1&ct=result#PPA69,M1\" rel=\"nofollow noreferrer\">C++ Gotchas</a> by Stephen C. Dewhurst says about using #if's.</p>\n"
},
{
"answer_id": 135111,
"author": "tloach",
"author_id": 14092,
"author_profile": "https://Stackoverflow.com/users/14092",
"pm_score": 0,
"selected": false,
"text": "<p>I've always used #ifdef and compiler flags to define it...</p>\n"
},
{
"answer_id": 135113,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 4,
"selected": false,
"text": "<p>I think it's entirely a question of style. Neither really has an obvious advantage over the other.</p>\n\n<p>Consistency is more important than either particular choice, so I'd recommend that you get together with your team and pick one style, and stick to it.</p>\n"
},
{
"answer_id": 135134,
"author": "zvrba",
"author_id": 2583,
"author_profile": "https://Stackoverflow.com/users/2583",
"pm_score": 2,
"selected": false,
"text": "<p>Both are exactly equivalent. In idiomatic use, #ifdef is used just to check for definedness (and what I'd use in your example), whereas #if is used in more complex expressions, such as #if defined(A) && !defined(B).</p>\n"
},
{
"answer_id": 135253,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 2,
"selected": false,
"text": "<h2>#if and #define MY_MACRO (0)</h2>\n<p>Using #if means that you created a "define" macro, i.e., something that will be searched in the code to be replaced by "(0)". This is the "macro hell" I hate to see in C++, because it pollutes the code with potential code modifications.</p>\n<p>For example:</p>\n<pre><code>#define MY_MACRO (0)\n\nint doSomething(int p_iValue)\n{\n return p_iValue + 1 ;\n}\n\nint main(int argc, char **argv)\n{\n int MY_MACRO = 25 ;\n doSomething(MY_MACRO) ;\n\n return 0;\n}\n</code></pre>\n<p>gives the following error on g++:</p>\n<pre><code>main.cpp|408|error: lvalue required as left operand of assignment|\n||=== Build finished: 1 errors, 0 warnings ===|\n</code></pre>\n<p>Only <strong>one</strong> error.</p>\n<p>Which means that your macro successfully interacted with your C++ code: The call to the function was successful. In this simple case, it is amusing. But my own experience with macros playing silently with my code is not full of joy and fullfilment, so...</p>\n<h2>#ifdef and #define MY_MACRO</h2>\n<p>Using #ifdef means you "define" something. Not that you give it a value. It is still polluting, but at least, it will be "replaced by nothing", and not seen by C++ code as lagitimate code statement. The same code above, with a simple define, it:</p>\n<pre><code>#define MY_MACRO\n\nint doSomething(int p_iValue)\n{\n return p_iValue + 1 ;\n}\n\nint main(int argc, char **argv)\n{\n int MY_MACRO = 25 ;\n doSomething(MY_MACRO) ;\n\n return 0;\n}\n</code></pre>\n<p>Gives the following warnings:</p>\n<pre><code>main.cpp||In function ‘int main(int, char**)’:|\nmain.cpp|406|error: expected unqualified-id before ‘=’ token|\nmain.cpp|399|error: too few arguments to function ‘int doSomething(int)’|\nmain.cpp|407|error: at this point in file|\n||=== Build finished: 3 errors, 0 warnings ===|\n</code></pre>\n<p>So...</p>\n<h2>Conclusion</h2>\n<p>I'd rather live without macros in my code, but for multiple reasons (defining header guards, or debug macros), I can't.</p>\n<p>But at least, I like to make them the least interactive possible with my legitimate C++ code. Which means using #define without value, using #ifdef and #ifndef (or even #if defined as suggested by Jim Buck), and most of all, giving them names so long and so alien no one in his/her right mind will use it "by chance", and that in no way it will affect legitimate C++ code.</p>\n<h2>Post Scriptum</h2>\n<p>Now, as I'm re-reading my post, I wonder if I should not try to find some value that won't ever ever be correct C++ to add to my define. Something like</p>\n<pre><code>#define MY_MACRO @@@@@@@@@@@@@@@@@@\n</code></pre>\n<p>that could be used with #ifdef and #ifndef, but not let code compile if used inside a function... I tried this successfully on g++, and it gave the error:</p>\n<pre><code>main.cpp|410|error: stray ‘@’ in program|\n</code></pre>\n<p>Interesting.\n:-)</p>\n"
},
{
"answer_id": 135286,
"author": "David Nehme",
"author_id": 14167,
"author_profile": "https://Stackoverflow.com/users/14167",
"pm_score": 1,
"selected": false,
"text": "<p>A little OT, but turning on/off logging with the preprocessor is definitely sub-optimal in C++. There are nice logging tools like Apache's <a href=\"http://logging.apache.org/log4cxx/index.html\" rel=\"nofollow noreferrer\">log4cxx</a> which are open-source and don't restrict how you distribute your application. They also allow you to change logging levels without recompilation, have very low overhead if you turn logging off, and give you the chance to turn logging off completely in production.</p>\n"
},
{
"answer_id": 135454,
"author": "Roddy",
"author_id": 1737,
"author_profile": "https://Stackoverflow.com/users/1737",
"pm_score": 8,
"selected": true,
"text": "<p>My initial reaction was <em><code>#ifdef</code>, of course</em>, but I think <code>#if</code> actually has some significant advantages for this - here's why:</p>\n\n<p>First, you can use <code>DEBUG_ENABLED</code> in preprocessor <em>and</em> compiled tests. Example - Often, I want longer timeouts when debug is enabled, so using <code>#if</code>, I can write this</p>\n\n<pre><code> DoSomethingSlowWithTimeout(DEBUG_ENABLED? 5000 : 1000);\n</code></pre>\n\n<p>... instead of ...</p>\n\n<pre><code>#ifdef DEBUG_MODE\n DoSomethingSlowWithTimeout(5000);\n#else\n DoSomethingSlowWithTimeout(1000);\n#endif\n</code></pre>\n\n<p>Second, you're in a better position if you want to migrate from a <code>#define</code> to a global constant. <code>#define</code>s are usually frowned on by most C++ programmers.</p>\n\n<p>And, Third, you say you've a divide in your team. My guess is this means different members have already adopted different approaches, and you need to standardise. Ruling that <code>#if</code> is the preferred choice means that code using <code>#ifdef</code> will compile -and run- even when <code>DEBUG_ENABLED</code> is false. And it's <em>much</em> easier to track down and remove debug output that is produced when it shouldn't be than vice-versa.</p>\n\n<p>Oh, and a minor readability point. You should be able to use true/false rather than 0/1 in your <code>#define</code>, and because the value is a single lexical token, it's the one time you don't need parentheses around it. </p>\n\n<pre><code>#define DEBUG_ENABLED true\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>#define DEBUG_ENABLED (1)\n</code></pre>\n"
},
{
"answer_id": 135611,
"author": "Lev",
"author_id": 7224,
"author_profile": "https://Stackoverflow.com/users/7224",
"pm_score": 3,
"selected": false,
"text": "<p>It's a matter of style. But I recommend a more concise way of doing this:</p>\n\n<pre><code>#ifdef USE_DEBUG\n#define debug_print printf\n#else\n#define debug_print\n#endif\n\ndebug_print(\"i=%d\\n\", i);\n</code></pre>\n\n<p>You do this once, then always use debug_print() to either print or do nothing. (Yes, this will compile in both cases.) This way, your code won't be garbled with preprocessor directives.</p>\n\n<p>If you get the warning \"expression has no effect\" and want to get rid of it, here's an alternative:</p>\n\n<pre><code>void dummy(const char*, ...)\n{}\n\n#ifdef USE_DEBUG\n#define debug_print printf\n#else\n#define debug_print dummy\n#endif\n\ndebug_print(\"i=%d\\n\", i);\n</code></pre>\n"
},
{
"answer_id": 135981,
"author": "Mike Thompson",
"author_id": 2754,
"author_profile": "https://Stackoverflow.com/users/2754",
"pm_score": 4,
"selected": false,
"text": "<p>For the purposes of performing conditional compilation, #if and #ifdef are <em>almost</em> the same, but not quite. If your conditional compilation depends on two symbols then #ifdef will not work as well. For example, suppose you have two conditional compilation symbols, PRO_VERSION and TRIAL_VERSION, you might have something like this:</p>\n\n<pre><code>#if defined(PRO_VERSION) && !defined(TRIAL_VERSION)\n...\n#else\n...\n#endif\n</code></pre>\n\n<p>Using #ifdef the above becomes much more complicated, especially getting the #else part to work. </p>\n\n<p>I work on code that uses conditional compilation extensively and we have a mixture of #if & #ifdef. We tend to use #ifdef/#ifndef for the simple case and #if whenever two or more symbols are being evaluation. </p>\n"
},
{
"answer_id": 136080,
"author": "Terence Simpson",
"author_id": 22395,
"author_profile": "https://Stackoverflow.com/users/22395",
"pm_score": 5,
"selected": false,
"text": "<p><code>#ifdef</code> just checks if a token is defined, given</p>\n\n<pre><code>#define FOO 0\n</code></pre>\n\n<p>then</p>\n\n<pre><code>#ifdef FOO // is true\n#if FOO // is false, because it evaluates to \"#if 0\"\n</code></pre>\n"
},
{
"answer_id": 3160643,
"author": "Brent Priddy",
"author_id": 351211,
"author_profile": "https://Stackoverflow.com/users/351211",
"pm_score": 5,
"selected": false,
"text": "<p>We have had this same problem across multiple files and there is always the problem with people forgetting to include a \"features flag\" file (With a codebase of > 41,000 files it is easy to do).</p>\n\n<p>If you had feature.h:</p>\n\n<pre><code>#ifndef FEATURE_H\n#define FEATURE_H\n\n// turn on cool new feature\n#define COOL_FEATURE 1\n\n#endif // FEATURE_H\n</code></pre>\n\n<p>But then You forgot to include the header file in file.cpp:</p>\n\n<pre><code>#if COOL_FEATURE\n // definitely awesome stuff here...\n#endif\n</code></pre>\n\n<p>Then you have a problem, the compiler interprets COOL_FEATURE being undefined as a \"false\" in this case and fails to include the code. Yes gcc does support a flag that causes a error for undefined macros... but most 3rd party code either defines or does not define features so this would not be that portable.</p>\n\n<p>We have adopted a portable way of correcting for this case as well as testing for a feature's state: function macros.</p>\n\n<p>if you changed the above feature.h to:</p>\n\n<pre><code>#ifndef FEATURE_H\n#define FEATURE_H\n\n// turn on cool new feature\n#define COOL_FEATURE() 1\n\n#endif // FEATURE_H\n</code></pre>\n\n<p>But then you again forgot to include the header file in file.cpp:</p>\n\n<pre><code>#if COOL_FEATURE()\n // definitely awseome stuff here...\n#endif\n</code></pre>\n\n<p>The preprocessor would have errored out because of the use of an undefined function macro. </p>\n"
},
{
"answer_id": 3172334,
"author": "R.. GitHub STOP HELPING ICE",
"author_id": 379897,
"author_profile": "https://Stackoverflow.com/users/379897",
"pm_score": 6,
"selected": false,
"text": "<p>They're both hideous. Instead, do this:</p>\n\n<pre><code>#ifdef DEBUG\n#define D(x) do { x } while(0)\n#else\n#define D(x) do { } while(0)\n#endif\n</code></pre>\n\n<p>Then whenever you need debug code, put it inside <code>D();</code>. And your program isn't polluted with hideous mazes of <code>#ifdef</code>.</p>\n"
},
{
"answer_id": 17032843,
"author": "tmanthey",
"author_id": 837119,
"author_profile": "https://Stackoverflow.com/users/837119",
"pm_score": 2,
"selected": false,
"text": "<p>That is not a matter of style at all. Also the question is unfortunately wrong. You cannot compare these preprocessor directives in the sense of better or safer.</p>\n\n<pre><code>#ifdef macro\n</code></pre>\n\n<p>means \"if macro is defined\" or \"if macro exists\". The value of macro does not matter here. It can be whatever.</p>\n\n<pre><code>#if macro\n</code></pre>\n\n<p>if always compare to a value. In the above example it is the standard implicit comparison:</p>\n\n<pre><code>#if macro !=0\n</code></pre>\n\n<p>example for the usage of #if</p>\n\n<pre><code>#if CFLAG_EDITION == 0\n return EDITION_FREE;\n#elif CFLAG_EDITION == 1\n return EDITION_BASIC;\n#else\n return EDITION_PRO;\n#endif\n</code></pre>\n\n<p>you now can either put the definition of CFLAG_EDITION either in your code</p>\n\n<pre><code>#define CFLAG_EDITION 1 \n</code></pre>\n\n<p>or you can set the macro as compiler flag. Also <a href=\"http://gcc.gnu.org/onlinedocs/gcc-3.0.1/cpp_4.html\" rel=\"nofollow\">see here</a>.</p>\n"
},
{
"answer_id": 45511381,
"author": "StefanB",
"author_id": 5895733,
"author_profile": "https://Stackoverflow.com/users/5895733",
"pm_score": 1,
"selected": false,
"text": "<p>I used to use <code>#ifdef</code>, but when I switched to Doxygen for documentation, I found that commented-out macros cannot be documented (or, at least, Doxygen produces a warning). This means I cannot document the feature-switch macros that are not currently enabled.</p>\n\n<p>Although it is possible to define the macros only for Doxygen, this means that the macros in the non-active portions of the code will be documented, too. I personally want to show the feature switches and otherwise only document what is currently selected. Furthermore, it makes the code quite messy if there are many macros that have to be defined only when Doxygen processes the file.</p>\n\n<p>Therefore, in this case, it is better to always define the macros and use <code>#if</code>.</p>\n"
},
{
"answer_id": 48298164,
"author": "Tomilov Anatoliy",
"author_id": 1430927,
"author_profile": "https://Stackoverflow.com/users/1430927",
"pm_score": 2,
"selected": false,
"text": "<p>There is a difference in case of different way to specify a conditional define to the driver:</p>\n\n<pre><code>diff <( echo | g++ -DA= -dM -E - ) <( echo | g++ -DA -dM -E - )\n</code></pre>\n\n<p>output:</p>\n\n<pre><code>344c344\n< #define A \n---\n> #define A 1\n</code></pre>\n\n<p>This means, that <code>-DA</code> is synonym for <code>-DA=1</code> and if value is omitted, then it may lead to problems in case of <code>#if A</code> usage.</p>\n"
},
{
"answer_id": 57519378,
"author": "memtha",
"author_id": 11529348,
"author_profile": "https://Stackoverflow.com/users/11529348",
"pm_score": 0,
"selected": false,
"text": "<p>I like <code>#define DEBUG_ENABLED (0)</code> when you might want multiple levels of debug. For example:</p>\n\n<pre><code>#define DEBUG_RELEASE (0)\n#define DEBUG_ERROR (1)\n#define DEBUG_WARN (2)\n#define DEBUG_MEM (3)\n#ifndef DEBUG_LEVEL\n#define DEBUG_LEVEL (DEBUG_RELEASE)\n#endif\n//...\n\n//now not only\n#if (DEBUG_LEVEL)\n//...\n#endif\n\n//but also\n#if (DEBUG_LEVEL >= DEBUG_MEM)\nLOG(\"malloc'd %d bytes at %s:%d\\n\", size, __FILE__, __LINE__);\n#endif\n</code></pre>\n\n<p>Makes it easier to debug memory leaks, without having all those log lines in your way of debugging other things.</p>\n\n<p>Also the <code>#ifndef</code> around the define makes it easier to pick a specific debug level at the commandline:</p>\n\n<pre><code>make -DDEBUG_LEVEL=2\ncmake -DDEBUG_LEVEL=2\netc\n</code></pre>\n\n<p>If not for this, I would give advantage to <code>#ifdef</code> because the compiler/make flag would be overridden by the one in the file. So you don't have to worry about changing back the header before doing the commit.</p>\n"
},
{
"answer_id": 68450723,
"author": "iheanyi",
"author_id": 2250588,
"author_profile": "https://Stackoverflow.com/users/2250588",
"pm_score": 0,
"selected": false,
"text": "<p>As with many things, the answer depends. <code>#ifdef</code> is great for things that are guaranteed to be defined or not defined in a particular unit. Include guards for example. If the include file is present at least once, the symbol is guaranteed to be defined, otherwise not.</p>\n<p>However, some things don't have that guarantee. Think about the symbol <code>HAS_FEATURE_X</code>. How many states exist?</p>\n<ol>\n<li>Undefined</li>\n<li>Defined</li>\n<li>Defined with a value (say 0 or 1).</li>\n</ol>\n<p>So, if you're writing code, especially shared code, where some may <code>#define HAS_FEATURE_X 0</code> to mean feature X isn't present and others may just not define it, you need to handle all those cases.</p>\n<p><code>#if !defined(HAS_FEATURE_X) || HAS_FEATURE_X == 1</code></p>\n<p>Using just an <code>#ifdef</code> could allow for a subtle error where something is switched in (or out) unexpectedly because someone or some team has a convention of defining unused things to 0. In some ways, I like this <code>#if</code> approach because it means the programmer <strong>actively</strong> made a decision. Leaving something undefined is passive and from an external point of view, it can sometimes be unclear whether that was intentional or an oversight.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15369/"
]
| This may be a matter of style, but there's a bit of a divide in our dev team and I wondered if anyone else had any ideas on the matter...
Basically, we have some debug print statements which we turn off during normal development. Personally I prefer to do the following:
```
//---- SomeSourceFile.cpp ----
#define DEBUG_ENABLED (0)
...
SomeFunction()
{
int someVariable = 5;
#if(DEBUG_ENABLED)
printf("Debugging: someVariable == %d", someVariable);
#endif
}
```
Some of the team prefer the following though:
```
// #define DEBUG_ENABLED
...
SomeFunction()
{
int someVariable = 5;
#ifdef DEBUG_ENABLED
printf("Debugging: someVariable == %d", someVariable);
#endif
}
```
...which of those methods sounds better to you and why? My feeling is that the first is safer because there is always something defined and there's no danger it could destroy other defines elsewhere. | My initial reaction was *`#ifdef`, of course*, but I think `#if` actually has some significant advantages for this - here's why:
First, you can use `DEBUG_ENABLED` in preprocessor *and* compiled tests. Example - Often, I want longer timeouts when debug is enabled, so using `#if`, I can write this
```
DoSomethingSlowWithTimeout(DEBUG_ENABLED? 5000 : 1000);
```
... instead of ...
```
#ifdef DEBUG_MODE
DoSomethingSlowWithTimeout(5000);
#else
DoSomethingSlowWithTimeout(1000);
#endif
```
Second, you're in a better position if you want to migrate from a `#define` to a global constant. `#define`s are usually frowned on by most C++ programmers.
And, Third, you say you've a divide in your team. My guess is this means different members have already adopted different approaches, and you need to standardise. Ruling that `#if` is the preferred choice means that code using `#ifdef` will compile -and run- even when `DEBUG_ENABLED` is false. And it's *much* easier to track down and remove debug output that is produced when it shouldn't be than vice-versa.
Oh, and a minor readability point. You should be able to use true/false rather than 0/1 in your `#define`, and because the value is a single lexical token, it's the one time you don't need parentheses around it.
```
#define DEBUG_ENABLED true
```
instead of
```
#define DEBUG_ENABLED (1)
``` |
135,076 | <p>I am <strong>losing hair</strong> on this one ... it seems that when I fix width an HTML SELECT control it renders its width differently depending on the browser. </p>
<p>Any idea how to to standardize this without having to turn to multiple style sheets?</p>
<p>Here is what I am working with:</p>
<pre><code>.combo
{
padding: 2px;
width: 200px;
}
.text
{
padding: 2px;
width: 200px;
}
</code></pre>
<p>This is my document type for the page:</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
</code></pre>
| [
{
"answer_id": 135083,
"author": "Steve Paulo",
"author_id": 9414,
"author_profile": "https://Stackoverflow.com/users/9414",
"pm_score": 1,
"selected": false,
"text": "<p>Make sure you remove all default margins and padding, and define them explicitly. Make sure you're using a proper DOCTYPE and therefore rendering IE in Standards Mode.</p>\n"
},
{
"answer_id": 135085,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 2,
"selected": false,
"text": "<p>Try setting <code>font-size</code> on the selects as well, that can affect how they are rendered. Also consider the <code>min-width</code> and <code>max-width</code> properties.</p>\n"
},
{
"answer_id": 135099,
"author": "Daniel Silveira",
"author_id": 1100,
"author_profile": "https://Stackoverflow.com/users/1100",
"pm_score": 1,
"selected": false,
"text": "<p>You may use faked dropdown widget and replace the SELECT.</p>\n"
},
{
"answer_id": 135118,
"author": "Ryan",
"author_id": 17917,
"author_profile": "https://Stackoverflow.com/users/17917",
"pm_score": 0,
"selected": false,
"text": "<p>Try using <a href=\"https://addons.mozilla.org/en-US/firefox/addon/1843\" rel=\"nofollow noreferrer\">Firebug</a> or Chrome's \"Inspect Element\" feature (right click on the select control, click \"inspect element\") to see exactly what style properties are being inherited/rendered for that specific object. That should lead you in the right direction. </p>\n"
},
{
"answer_id": 135764,
"author": "mattruma",
"author_id": 1768,
"author_profile": "https://Stackoverflow.com/users/1768",
"pm_score": 0,
"selected": false,
"text": "<p>I've tried all these suggestions ... and I finally have it so it looks good in IE and Firefox. Looks like there is something wrong with the padding on the SELECT control. If I increase the width of the SELECT by 2 pixels the now size correctly. </p>\n\n<pre><code> .combo\n {\n padding: 2px;\n width: 206px;\n }\n\n.text\n{\n padding: 2px;\n width: 200px;\n}\n</code></pre>\n\n<p>However, Chrome still does not show them the same size.</p>\n"
},
{
"answer_id": 141587,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>Form controls will always be less obedient to styling attempts,in particular selects and file inputs, so the only way to reliably style them cross-browser and with future-proofing in mind, is to replace them with JavaScript or Flash and mimic their functionality</p>\n"
},
{
"answer_id": 318290,
"author": "Paul D. Waite",
"author_id": 20578,
"author_profile": "https://Stackoverflow.com/users/20578",
"pm_score": 1,
"selected": false,
"text": "<p>Browsers tend to limit the amount you can style form controls with CSS, because form controls have a lot of complicated styling that varies between operating systems. CSS can’t describe that fully, so browsers put some of it off limits.</p>\n\n<p>Eric Meyer wrote a good article on the subject:</p>\n\n<p><a href=\"http://meyerweb.com/eric/thoughts/2007/05/15/formal-weirdness/\" rel=\"nofollow noreferrer\">http://meyerweb.com/eric/thoughts/2007/05/15/formal-weirdness/</a></p>\n\n<p>The best you can do is accept you don’t have complete control over the look of form fields, and experiment with whatever styling is really important.</p>\n"
},
{
"answer_id": 5069836,
"author": "Martinator",
"author_id": 627125,
"author_profile": "https://Stackoverflow.com/users/627125",
"pm_score": 2,
"selected": false,
"text": "<p>input[type=text],\nselect {\n border: solid 1px #c2c1c1;\n width: 150px;\n padding: 2px;\n }</p>\n\n<p>// then </p>\n\n<p>select {\n width: 156px; //needs to be input[type=text] width + (border and padding)\n }</p>\n\n<p>/*\nThe input[type=text] width = width + padding + border</p>\n\n<p>The select width just equals width. The padding and border get rendered inside that width constraint. That's just the way SELECT rolls...</p>\n\n<p>*/</p>\n"
},
{
"answer_id": 10325061,
"author": "cheekybastard",
"author_id": 1357413,
"author_profile": "https://Stackoverflow.com/users/1357413",
"pm_score": 0,
"selected": false,
"text": "<p>Martinator is correct. </p>\n\n<p>Sounds like you're trying to control the width of various types of inputs or menus across bowsers. You can directly select the object and specify the width. For example:</p>\n\n<pre><code>select {\n width:350px;\n}\n</code></pre>\n\n<p>Or you can do this with text area:</p>\n\n<pre><code>select {\n width:350px;\n}\n</code></pre>\n\n<p>Other types of inputs require the syntax Martinator mentions. So, for a text, input, or even file type input, you'd do this for each one:</p>\n\n<pre><code>input[type=text] {\n width:350px;\n}\n\ninput[type=input] {\n width:350px;\n}\n\ninput[type=file] {\n width:350px;\n}\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768/"
]
| I am **losing hair** on this one ... it seems that when I fix width an HTML SELECT control it renders its width differently depending on the browser.
Any idea how to to standardize this without having to turn to multiple style sheets?
Here is what I am working with:
```
.combo
{
padding: 2px;
width: 200px;
}
.text
{
padding: 2px;
width: 200px;
}
```
This is my document type for the page:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
``` | Form controls will always be less obedient to styling attempts,in particular selects and file inputs, so the only way to reliably style them cross-browser and with future-proofing in mind, is to replace them with JavaScript or Flash and mimic their functionality |
135,105 | <p>We'd like to override DataGridView's default behavior when using a mouse wheel with this control. By default, the DataGridView scrolls a number of rows equal the SystemInformation.MouseWheelScrollLines setting. What we'd like to do is scroll just one item at a time. </p>
<p>(We display images in the DataGridView, which are somewhat large. Because of this scroll three rows (a typical system setting) is too much, often causing the user to scroll to items they can't even see.)</p>
<p>I've tried a couple things already and haven't had much success so far. Here are some issues I've run into:</p>
<ol>
<li><p>You can subscribe to MouseWheel events but there's no way to mark the event as handled and do my own thing.</p></li>
<li><p>You can override OnMouseWheel but this never appears to be called.</p></li>
<li><p>You might be able to correct this in the base scrolling code but it sounds like a messy job since other types of scrolling (e.g. using the keyboard) come through the same pipeline.</p></li>
</ol>
<p>Anyone have a good suggestion?</p>
<p>Here's the final code, using the wonderful answer given:</p>
<pre><code> /// <summary>
/// Handle the mouse wheel manually due to the fact that we display
/// images, which don't work well when you scroll by more than one
/// item at a time.
/// </summary>
///
/// <param name="sender">
/// sender
/// </param>
/// <param name="e">
/// the mouse event
/// </param>
private void mImageDataGrid_MouseWheel(object sender, MouseEventArgs e)
{
// Hack alert! Through reflection, we know that the passed
// in event argument is actually a handled mouse event argument,
// allowing us to handle this event ourselves.
// See http://tinyurl.com/54o7lc for more info.
HandledMouseEventArgs handledE = (HandledMouseEventArgs) e;
handledE.Handled = true;
// Do the scrolling manually. Move just one row at a time.
int rowIndex = mImageDataGrid.FirstDisplayedScrollingRowIndex;
mImageDataGrid.FirstDisplayedScrollingRowIndex =
e.Delta < 0 ?
Math.Min(rowIndex + 1, mImageDataGrid.RowCount - 1):
Math.Max(rowIndex - 1, 0);
}
</code></pre>
| [
{
"answer_id": 135516,
"author": "ZeroBugBounce",
"author_id": 11314,
"author_profile": "https://Stackoverflow.com/users/11314",
"pm_score": 1,
"selected": false,
"text": "<p>I would subclass the DataGridView into my own custom control (you know, add a new Windows Forms --> Custom Control file and change the base class from Control to DataGridView).</p>\n\n<pre><code>public partial class MyDataGridView : DataGridView\n</code></pre>\n\n<p>Then override the WndProc method and substitute something like so:</p>\n\n<pre><code>protected override void WndProc(ref Message m)\n{\n if (m.Msg == 0x20a)\n {\n int wheelDelta = ((int)m.WParam) >> 16;\n\n // 120 = UP 1 tick\n // -120 = DOWN 1 tick\n\n this.FirstDisplayedScrollingRowIndex -= (wheelDelta / 120);\n }\n else\n {\n base.WndProc(ref m);\n }\n}\n</code></pre>\n\n<p>Of course, you'll have the check that you don't set FirstDisplayedScrollingRowIndex to a number outside of the range of your grid etc. But this works quite well!</p>\n\n<p>Richard</p>\n"
},
{
"answer_id": 135529,
"author": "Nikki9696",
"author_id": 456669,
"author_profile": "https://Stackoverflow.com/users/456669",
"pm_score": 1,
"selected": false,
"text": "<p>Overriding OnMouseWheel and not calling base.OnMouseWheel should work. Some wheel mice have special settings that you may need to set yourself for it to work properly. See this post <a href=\"http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=126295&SiteID=1\" rel=\"nofollow noreferrer\">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=126295&SiteID=1</a></p>\n"
},
{
"answer_id": 135562,
"author": "Joel B Fant",
"author_id": 22211,
"author_profile": "https://Stackoverflow.com/users/22211",
"pm_score": 3,
"selected": true,
"text": "<p>I just did a little scrounging and testing of my own. I used <a href=\"http://www.red-gate.com/products/reflector/\" rel=\"nofollow noreferrer\">Reflector</a> to investigate and discovered a couple things. The <code>MouseWheel</code> event provides a <code>MouseEventArgs</code> parameter, but the <code>OnMouseWheel()</code> override in <code>DataGridView</code> casts it to <strong><code>Handled</code></strong><code>MouseEventArgs</code>. This also works when handling the <code>MouseWheel</code> event. <code>OnMouseWheel()</code> does indeed get called, and it is in <code>DataGridView</code>'s override that it uses <code>SystemInformation.MouseWheelScrollLines</code>.</p>\n\n<p>So:</p>\n\n<ol>\n<li><p>You could indeed handle the <code>MouseWheel</code> event, casting <code>MouseEventArgs</code> to <code>HandledMouseEventArgs</code> and set <code>Handled = true</code>, then do what you want.</p></li>\n<li><p>Subclass <code>DataGridView</code>, override <code>OnMouseWheel()</code> yourself, and try to recreate all the code I read here in <a href=\"http://www.red-gate.com/products/reflector/\" rel=\"nofollow noreferrer\">Reflector</a> except for replacing <code>SystemInformation.MouseWheelScrollLines</code> with <code>1</code>.</p></li>\n</ol>\n\n<p>The latter would be a huge pain because it uses a number of private variables (including references to the <code>ScrollBar</code>s) and you'd have replace some with your own and get/set others using Reflection.</p>\n"
},
{
"answer_id": 135997,
"author": "Christoffer Lette",
"author_id": 11808,
"author_profile": "https://Stackoverflow.com/users/11808",
"pm_score": 1,
"selected": false,
"text": "<p><strong>UPDATE:</strong> Since I've now learned that the <code>DataGridView</code> has a <code>MouseWheel</code> event, I've added a second, simpler override.</p>\n\n<p>One way to accomplish this is to subclass the <code>DataGridView</code> and override the <code>WndProc</code> to add special handling of the <code>WM_MOUSEWHEEL</code> message.</p>\n\n<p>This example catches the mouse wheel movement and replaces it with a call to <code>SendKeys.Send</code>.</p>\n\n<p><em>(This is a little different than just scrolling, since it also selects the next/previous row of the <code>DataGridView</code>. But it works.)</em></p>\n\n<pre><code>public class MyDataGridView : DataGridView\n{\n private const uint WM_MOUSEWHEEL = 0x20a;\n\n protected override void WndProc(ref Message m)\n {\n if (m.Msg == WM_MOUSEWHEEL)\n {\n var wheelDelta = ((int)m.WParam) >> 16;\n\n if (wheelDelta < 0)\n {\n SendKeys.Send(\"{DOWN}\");\n }\n\n if (wheelDelta > 0)\n {\n SendKeys.Send(\"{UP}\");\n }\n\n return;\n }\n\n base.WndProc(ref m);\n }\n}\n</code></pre>\n\n<p>2nd take (with the same caveats as mentioned above):</p>\n\n<pre><code>public class MyDataGridView : DataGridView\n{\n protected override void OnMouseWheel(MouseEventArgs e)\n {\n if (e.Delta < 0)\n SendKeys.Send(\"{DOWN}\");\n else\n SendKeys.Send(\"{UP}\");\n }\n}\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7357/"
]
| We'd like to override DataGridView's default behavior when using a mouse wheel with this control. By default, the DataGridView scrolls a number of rows equal the SystemInformation.MouseWheelScrollLines setting. What we'd like to do is scroll just one item at a time.
(We display images in the DataGridView, which are somewhat large. Because of this scroll three rows (a typical system setting) is too much, often causing the user to scroll to items they can't even see.)
I've tried a couple things already and haven't had much success so far. Here are some issues I've run into:
1. You can subscribe to MouseWheel events but there's no way to mark the event as handled and do my own thing.
2. You can override OnMouseWheel but this never appears to be called.
3. You might be able to correct this in the base scrolling code but it sounds like a messy job since other types of scrolling (e.g. using the keyboard) come through the same pipeline.
Anyone have a good suggestion?
Here's the final code, using the wonderful answer given:
```
/// <summary>
/// Handle the mouse wheel manually due to the fact that we display
/// images, which don't work well when you scroll by more than one
/// item at a time.
/// </summary>
///
/// <param name="sender">
/// sender
/// </param>
/// <param name="e">
/// the mouse event
/// </param>
private void mImageDataGrid_MouseWheel(object sender, MouseEventArgs e)
{
// Hack alert! Through reflection, we know that the passed
// in event argument is actually a handled mouse event argument,
// allowing us to handle this event ourselves.
// See http://tinyurl.com/54o7lc for more info.
HandledMouseEventArgs handledE = (HandledMouseEventArgs) e;
handledE.Handled = true;
// Do the scrolling manually. Move just one row at a time.
int rowIndex = mImageDataGrid.FirstDisplayedScrollingRowIndex;
mImageDataGrid.FirstDisplayedScrollingRowIndex =
e.Delta < 0 ?
Math.Min(rowIndex + 1, mImageDataGrid.RowCount - 1):
Math.Max(rowIndex - 1, 0);
}
``` | I just did a little scrounging and testing of my own. I used [Reflector](http://www.red-gate.com/products/reflector/) to investigate and discovered a couple things. The `MouseWheel` event provides a `MouseEventArgs` parameter, but the `OnMouseWheel()` override in `DataGridView` casts it to **`Handled`**`MouseEventArgs`. This also works when handling the `MouseWheel` event. `OnMouseWheel()` does indeed get called, and it is in `DataGridView`'s override that it uses `SystemInformation.MouseWheelScrollLines`.
So:
1. You could indeed handle the `MouseWheel` event, casting `MouseEventArgs` to `HandledMouseEventArgs` and set `Handled = true`, then do what you want.
2. Subclass `DataGridView`, override `OnMouseWheel()` yourself, and try to recreate all the code I read here in [Reflector](http://www.red-gate.com/products/reflector/) except for replacing `SystemInformation.MouseWheelScrollLines` with `1`.
The latter would be a huge pain because it uses a number of private variables (including references to the `ScrollBar`s) and you'd have replace some with your own and get/set others using Reflection. |
135,121 | <p>So in my documentation it says:</p>
<blockquote>
<p>public event TreeViewPlusNodeCheckedEventHandler NodeChecked()</p>
<p>You can use this event to run cause a method to run whenever the
check-box for a node is checked on the tree.</p>
</blockquote>
<p>So how do I add a method to my code behind file that will run when a node is checked? The method I want to run is:</p>
<pre><code>protected void TOCNodeCheckedServer(object sender, TreeViewPlusNodeEventArgs args)
{
TreeViewPlusNode aNode = args.Node;
if (!aNode.Checked)
return;
List<string> BaseLayers = new List<string>();
_arcTOCConfig.BaseDataLayers.CopyTo(BaseLayers);
List<MapResourceItem> mapResources = new List<MapResourceItem>();
if (BaseLayers.Contains(aNode.Text))
{
foreach (BaseDataLayerElement anEl in _arcTOCConfig.BaseDataLayers)
{
if (!aNode.Text.Equals(anEl.Name))
{
if (aNode.TreeViewPlus.Nodes.FindByValue(anEl.Name).Checked)
{
aNode.TreeViewPlus.Nodes.FindByValue(anEl.Name).Checked = false;
aNode.TreeViewPlus.Nodes.FindByValue(anEl.Name).Refresh();
MapResourceItem aMapResource = this.Map1.MapResourceManagerInstance.ResourceItems.Find(anEl.Name);
aMapResource.DisplaySettings.Visible = false;
this.Map1.RefreshResource(anEl.Name);
mapResources.Add(aMapResource);
this.Map1.MapResourceManagerInstance.ResourceItems.Remove(aMapResource);
}
else
{
MapResourceItem aMapResource = this.Map1.MapResourceManagerInstance.ResourceItems.Find(anEl.Name);
mapResources.Add(aMapResource);
this.Map1.MapResourceManagerInstance.ResourceItems.Remove(aMapResource);
}
}
}
foreach (MapResourceItem aMapResource in mapResources)
{
int count = this.Map1.MapResourceManagerInstance.ResourceItems.Count - 1;
this.Map1.MapResourceManagerInstance.ResourceItems.Insert(count, aMapResource);
this.Map1.MapResourceManagerInstance.CreateResource(aMapResource);
}
this.Map1.InitializeFunctionalities();
this.Map1.Refresh();
}
}
</code></pre>
<p>vs 2008
c#
.net 3.5</p>
| [
{
"answer_id": 135137,
"author": "DaveK",
"author_id": 4244,
"author_profile": "https://Stackoverflow.com/users/4244",
"pm_score": 4,
"selected": true,
"text": "<p>You need to assign a delegate to the event and have it run the method you want. Something like :</p>\n\n<p>TreeViewControl.NodeChecked += new TreeViewPlusNodeCheckedEventHandler(TOCNodeCheckedServer)</p>\n"
},
{
"answer_id": 135138,
"author": "Max Schmeling",
"author_id": 3226,
"author_profile": "https://Stackoverflow.com/users/3226",
"pm_score": 2,
"selected": false,
"text": "<p>Just add a handler to the event.</p>\n\n<pre><code>myTreeView.NodeChecked += new TreeViewPlusNodeCheckedEventHandler(TOCNodeCheckedServer);\n</code></pre>\n\n<p>or (because instantiating the TreeViewPlusNodeCheckedEventHandler isn't actually necessary)</p>\n\n<pre><code>myTreeView.NodeChecked += TOCNodeCheckedServer;\n</code></pre>\n"
},
{
"answer_id": 135141,
"author": "Jonathan Rupp",
"author_id": 12502,
"author_profile": "https://Stackoverflow.com/users/12502",
"pm_score": 2,
"selected": false,
"text": "<p>This is a standard case of registering a handler for an event</p>\n\n<pre><code>treeView.NodeChecked += TOCNodeCheckedServer;\n</code></pre>\n"
},
{
"answer_id": 135166,
"author": "SecretDeveloper",
"author_id": 2720,
"author_profile": "https://Stackoverflow.com/users/2720",
"pm_score": 0,
"selected": false,
"text": "<p>On your initialise method for the form add</p>\n\n<pre><code>TOCTree.NodeChecked += new TreeViewPlusNodeCheckedEventHandler (TOCNodeCheckedServer);\n</code></pre>\n\n<p>This will tell your app to run TOCNodeCheckedServer when the TOCNode Fires the NodeChecked Event.</p>\n\n<p>There are loads of resources on the web explaining how this works. Check out <a href=\"http://www.csharphelp.com/archives/archive253.html\" rel=\"nofollow noreferrer\">http://www.csharphelp.com/archives/archive253.html</a>\n as an example.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5234/"
]
| So in my documentation it says:
>
> public event TreeViewPlusNodeCheckedEventHandler NodeChecked()
>
>
> You can use this event to run cause a method to run whenever the
> check-box for a node is checked on the tree.
>
>
>
So how do I add a method to my code behind file that will run when a node is checked? The method I want to run is:
```
protected void TOCNodeCheckedServer(object sender, TreeViewPlusNodeEventArgs args)
{
TreeViewPlusNode aNode = args.Node;
if (!aNode.Checked)
return;
List<string> BaseLayers = new List<string>();
_arcTOCConfig.BaseDataLayers.CopyTo(BaseLayers);
List<MapResourceItem> mapResources = new List<MapResourceItem>();
if (BaseLayers.Contains(aNode.Text))
{
foreach (BaseDataLayerElement anEl in _arcTOCConfig.BaseDataLayers)
{
if (!aNode.Text.Equals(anEl.Name))
{
if (aNode.TreeViewPlus.Nodes.FindByValue(anEl.Name).Checked)
{
aNode.TreeViewPlus.Nodes.FindByValue(anEl.Name).Checked = false;
aNode.TreeViewPlus.Nodes.FindByValue(anEl.Name).Refresh();
MapResourceItem aMapResource = this.Map1.MapResourceManagerInstance.ResourceItems.Find(anEl.Name);
aMapResource.DisplaySettings.Visible = false;
this.Map1.RefreshResource(anEl.Name);
mapResources.Add(aMapResource);
this.Map1.MapResourceManagerInstance.ResourceItems.Remove(aMapResource);
}
else
{
MapResourceItem aMapResource = this.Map1.MapResourceManagerInstance.ResourceItems.Find(anEl.Name);
mapResources.Add(aMapResource);
this.Map1.MapResourceManagerInstance.ResourceItems.Remove(aMapResource);
}
}
}
foreach (MapResourceItem aMapResource in mapResources)
{
int count = this.Map1.MapResourceManagerInstance.ResourceItems.Count - 1;
this.Map1.MapResourceManagerInstance.ResourceItems.Insert(count, aMapResource);
this.Map1.MapResourceManagerInstance.CreateResource(aMapResource);
}
this.Map1.InitializeFunctionalities();
this.Map1.Refresh();
}
}
```
vs 2008
c#
.net 3.5 | You need to assign a delegate to the event and have it run the method you want. Something like :
TreeViewControl.NodeChecked += new TreeViewPlusNodeCheckedEventHandler(TOCNodeCheckedServer) |
135,132 | <p>I'm really baffled by this - I know how to do this in VB, unmanaged C++ and C# but for some reason I can't accept a ref variable of a managed type in C++. I'm sure there's a simple answer, really - but here's the C# equivalent:</p>
<pre><code>myClass.myFunction(ref variableChangedByfunction);
</code></pre>
<p>I've tried C++ pointers - no dice. I've tried ref keywords. No dice. I tried the <code>[out]</code> keyword. Didn't work.</p>
<p>I can't find any documentation that clearly explains my problem, either.</p>
| [
{
"answer_id": 135135,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>Use a ^ instead of a *</p>\n"
},
{
"answer_id": 135404,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Turns out in the function declaration you need to use a % after the parameter name:</p>\n\n<p>bool Importer::GetBodyChunk(String^% BodyText, String^% ChunkText)</p>\n\n<p>And then you pass in the variable per usual.</p>\n"
},
{
"answer_id": 2280477,
"author": "rotti2",
"author_id": 207620,
"author_profile": "https://Stackoverflow.com/users/207620",
"pm_score": 1,
"selected": false,
"text": "<p>Just to make it a little clearer:</p>\n\n<p>Parameters of reference types (e.g. System::String) have to be denoted with <code>^</code> in the newer C++/CLI syntax. This tells the compiler that the parameter is a handle to a GC object. </p>\n\n<p>If you need a tracking reference (like with <code>ref</code> or <code>out</code> in C#) you need to add <code>%</code> as well. </p>\n\n<p>And here comes a tip: I often find it helpful to use the <a href=\"http://www.red-gate.com/products/reflector/\" rel=\"nofollow noreferrer\">.NET Reflector</a> to look at existing assemblies and switch to C++ code style. This gives good insight into usage of attributes for interoperability between different .net languages.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I'm really baffled by this - I know how to do this in VB, unmanaged C++ and C# but for some reason I can't accept a ref variable of a managed type in C++. I'm sure there's a simple answer, really - but here's the C# equivalent:
```
myClass.myFunction(ref variableChangedByfunction);
```
I've tried C++ pointers - no dice. I've tried ref keywords. No dice. I tried the `[out]` keyword. Didn't work.
I can't find any documentation that clearly explains my problem, either. | Turns out in the function declaration you need to use a % after the parameter name:
bool Importer::GetBodyChunk(String^% BodyText, String^% ChunkText)
And then you pass in the variable per usual. |
135,151 | <p>The .NET web system I'm working on allows the end user to input HTML formatted text in some situations. In some of those places, we want to leave all the tags, but strip off any trailing break tags (but leave any breaks inside the body of the text.)</p>
<p>What's the best way to do this? (I can think of ways to do this, but I'm sure they're not the best.)</p>
| [
{
"answer_id": 135161,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 2,
"selected": false,
"text": "<p>You can use a regex to find and remove the text with the regex match set to anchor at the end of the string.</p>\n"
},
{
"answer_id": 135165,
"author": "Max Schmeling",
"author_id": 3226,
"author_profile": "https://Stackoverflow.com/users/3226",
"pm_score": 2,
"selected": false,
"text": "<p>I'm sure this isn't the best way either, but it should work unless you have trailing spaces or something.</p>\n\n<pre><code>while (myHtmlString.EndsWith(\"<br>\"))\n{\n myHtmlString = myHtmlString.SubString(0, myHtmlString.Length - 4);\n}\n</code></pre>\n"
},
{
"answer_id": 135174,
"author": "Leon Tayson",
"author_id": 18413,
"author_profile": "https://Stackoverflow.com/users/18413",
"pm_score": 0,
"selected": false,
"text": "<p>you can use RegEx or check if the trailing string is a break and remove it</p>\n"
},
{
"answer_id": 135216,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 5,
"selected": true,
"text": "<p>As @<a href=\"https://stackoverflow.com/questions/135151#135161\">Mitch</a> said, </p>\n\n<pre><code>// using System.Text.RegularExpressions;\n\n/// <summary>\n/// Regular expression built for C# on: Thu, Sep 25, 2008, 02:01:36 PM\n/// Using Expresso Version: 2.1.2150, http://www.ultrapico.com\n/// \n/// A description of the regular expression:\n/// \n/// Match expression but don't capture it. [\\<br\\s*/?\\>], any number of repetitions\n/// \\<br\\s*/?\\>\n/// <\n/// br\n/// Whitespace, any number of repetitions\n/// /, zero or one repetitions\n/// >\n/// End of line or string\n/// \n/// \n/// </summary>\npublic static Regex regex = new Regex(\n @\"(?:\\<br\\s*/?\\>)*$\",\n RegexOptions.IgnoreCase\n | RegexOptions.CultureInvariant\n | RegexOptions.IgnorePatternWhitespace\n | RegexOptions.Compiled\n );\nregex.Replace(text, string.Empty);\n</code></pre>\n"
},
{
"answer_id": 135239,
"author": "Rob",
"author_id": 7872,
"author_profile": "https://Stackoverflow.com/users/7872",
"pm_score": 1,
"selected": false,
"text": "<p>You could also try (if the markup is likely to be a valid tree) something similar to:</p>\n\n<pre><code>string s = \"<markup><div>Text</div><br /><br /></markup>\";\n\nXmlDocument doc = new XmlDocument();\ndoc.LoadXml(s);\n\nConsole.WriteLine(doc.InnerXml);\n\nXmlElement markup = doc[\"markup\"];\nint childCount = markup.ChildNodes.Count;\nfor (int i = childCount -1; i >= 0; i--)\n{\n if (markup.ChildNodes[i].Name.ToLower() == \"br\")\n {\n markup.RemoveChild(markup.ChildNodes[i]);\n }\n else\n {\n break;\n }\n}\nConsole.WriteLine(\"---\");\nConsole.WriteLine(markup.InnerXml); \nConsole.ReadKey();\n</code></pre>\n\n<p>The code above is a bit \"scratch-pad\" but if you cut and paste it into a Console application and run it, it does work :=)</p>\n"
},
{
"answer_id": 135260,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 2,
"selected": false,
"text": "<p>I'm trying to ignore the ambiguity in your original question, and read it literally. Here is an extension method that overloads TrimEnd to take a string.</p>\n\n<pre><code>static class StringExtensions\n{\n public static string TrimEnd(this string s, string remove)\n {\n if (s.EndsWith(remove))\n {\n return s.Substring(0, s.Length - remove.Length);\n }\n return s;\n }\n}\n</code></pre>\n\n<p>Here are some tests to show that it works:</p>\n\n<pre><code> Debug.Assert(\"abc\".TrimEnd(\"<br>\") == \"abc\");\n Debug.Assert(\"abc<br>\".TrimEnd(\"<br>\") == \"abc\");\n Debug.Assert(\"<br>abc\".TrimEnd(\"<br>\") == \"<br>abc\");\n</code></pre>\n\n<p>I want to point out that this solution is easier to read than regex, probably faster than regex (you should use a profiler, not speculation, if you're concerned about performance), and useful for removing other things from the ends of strings.</p>\n\n<p>regex becomes more appropriate if your problem is more general than you stated (e.g., if you want to remove <code><BR></code> and <code></BR></code> and deal with trailing spaces or whatever.</p>\n"
},
{
"answer_id": 135340,
"author": "Ray Hayes",
"author_id": 7093,
"author_profile": "https://Stackoverflow.com/users/7093",
"pm_score": 2,
"selected": false,
"text": "<p>Small change to <a href=\"https://stackoverflow.com/questions/135151/whats-the-best-way-to-remove-br-tags-from-the-end-of-a-string#135216\">bdukes</a> code, which should be faster as it doesn't backtrack.</p>\n\n<pre><code>public static Regex regex = new Regex(\n @\"(?:\\<br[^>]*\\>)*$\",\n RegexOptions.IgnoreCase\n | RegexOptions.CultureInvariant\n | RegexOptions.IgnorePatternWhitespace\n | RegexOptions.Compiled\n);\nregex.Replace(text, string.Empty);\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19074/"
]
| The .NET web system I'm working on allows the end user to input HTML formatted text in some situations. In some of those places, we want to leave all the tags, but strip off any trailing break tags (but leave any breaks inside the body of the text.)
What's the best way to do this? (I can think of ways to do this, but I'm sure they're not the best.) | As @[Mitch](https://stackoverflow.com/questions/135151#135161) said,
```
// using System.Text.RegularExpressions;
/// <summary>
/// Regular expression built for C# on: Thu, Sep 25, 2008, 02:01:36 PM
/// Using Expresso Version: 2.1.2150, http://www.ultrapico.com
///
/// A description of the regular expression:
///
/// Match expression but don't capture it. [\<br\s*/?\>], any number of repetitions
/// \<br\s*/?\>
/// <
/// br
/// Whitespace, any number of repetitions
/// /, zero or one repetitions
/// >
/// End of line or string
///
///
/// </summary>
public static Regex regex = new Regex(
@"(?:\<br\s*/?\>)*$",
RegexOptions.IgnoreCase
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
regex.Replace(text, string.Empty);
``` |
135,173 | <p>I have a table that holds only two columns - a ListID and PersonID. When a person is merged with another in the system, I was to update all references from the "source" person to be references to the "destination" person.</p>
<p>Ideally, I would like to call something simple like</p>
<pre><code>UPDATE MailingListSubscription
SET PersonID = @DestPerson
WHERE PersonID = @SourcePerson
</code></pre>
<p>However, if the destination person already exists in this table with the same ListID as the source person, a duplicate entry will be made. How can I perform this action without creating duplicated entries? (ListID, PersonID is the primary key)</p>
<p>EDIT: Multiple ListIDs are used. If SourcePerson is assigned to ListIDs 1, 2, and 3, and DestinationPerson is assigned to ListIDs 3 and 4, then the end result needs to have four rows - DestinationPerson assigned to ListID 1, 2, 3, and 4.</p>
| [
{
"answer_id": 135252,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 3,
"selected": true,
"text": "<pre><code>--out with the bad\nDELETE\nFROM MailingListSubscription\nWHERE PersonId = @SourcePerson\n and ListID in (SELECT ListID FROM MailingListSubscription WHERE PersonID = @DestPerson)\n\n--update the rest (good)\nUPDATE MailingListSubscription\nSET PersonId = @DestPerson\nWHERE PersonId = @SourcePerson\n</code></pre>\n"
},
{
"answer_id": 135320,
"author": "SecretDeveloper",
"author_id": 2720,
"author_profile": "https://Stackoverflow.com/users/2720",
"pm_score": 0,
"selected": false,
"text": "<p>I have to agree with David B here. Remove all the older stuff that shouldn't be there and then do your update.</p>\n"
},
{
"answer_id": 135350,
"author": "Cruachan",
"author_id": 7315,
"author_profile": "https://Stackoverflow.com/users/7315",
"pm_score": 0,
"selected": false,
"text": "<p>Actually, I think you should go back and reconsider your database design as you really shouldn't be in circumstances where you're changing the primary key for a record as you're proposing to do - it implies that the PersonID column is not actually a suitable primary key in the first place. </p>\n\n<p>My guess is your PersonID is exposed to your users, they've renumbered their database for some reason and you're syncing the change back in. This is generally a poor idea as it breaks audit trails and temporal consistency. In these circumstances, it's generally better to use your own non-changing primary key - usually an identity - and set up the PersonID that the users see as an attribute of that. It's extra work but will give you additional consistency and robustness in the long run.</p>\n\n<p>A good rule of thumb is the primary key of a record should not be exposed to the users where possible and you should only do so after careful consideration. OK, I confess to breaking this myself on numerous occasions but it's worth striving for where you can :-) </p>\n"
},
{
"answer_id": 135590,
"author": "Aheho",
"author_id": 21155,
"author_profile": "https://Stackoverflow.com/users/21155",
"pm_score": 0,
"selected": false,
"text": "<p>First you should subscribe destperson to all lists that SourcePerson is subscribed to that Destperson isn't already subscibed. Then delete all the SourcePersons subscriptions.\nThis will work with multiple ListIDs.</p>\n\n<pre><code>Insert into MailingListSubscription\n(\n ListID,\n PersonID\n)\nSelect\n ListID,\n @DestPerson\nFrom\n MailingListSubscription as t1\nWhere\n PersonID = @SourcePerson and\n Not Exists\n (\n Select *\n From MailingListSubscription as t2\n Where\n PersonID = @DestPerson and\n t1.ListID = t2.ListID\n )\n\n\n\nDelete From MailingListSubscription\nWhere\n PersonID = @SourcePerson\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3259/"
]
| I have a table that holds only two columns - a ListID and PersonID. When a person is merged with another in the system, I was to update all references from the "source" person to be references to the "destination" person.
Ideally, I would like to call something simple like
```
UPDATE MailingListSubscription
SET PersonID = @DestPerson
WHERE PersonID = @SourcePerson
```
However, if the destination person already exists in this table with the same ListID as the source person, a duplicate entry will be made. How can I perform this action without creating duplicated entries? (ListID, PersonID is the primary key)
EDIT: Multiple ListIDs are used. If SourcePerson is assigned to ListIDs 1, 2, and 3, and DestinationPerson is assigned to ListIDs 3 and 4, then the end result needs to have four rows - DestinationPerson assigned to ListID 1, 2, 3, and 4. | ```
--out with the bad
DELETE
FROM MailingListSubscription
WHERE PersonId = @SourcePerson
and ListID in (SELECT ListID FROM MailingListSubscription WHERE PersonID = @DestPerson)
--update the rest (good)
UPDATE MailingListSubscription
SET PersonId = @DestPerson
WHERE PersonId = @SourcePerson
``` |
135,186 | <p>I have a project at work the requires me to be able to enter information into a web page, read the next page I get redirected to and then take further action. A simplified real-world example would be something like going to google.com, entering "Coding tricks" as search criteria, and reading the resulting page.</p>
<p>Small coding examples like the ones linked to at <a href="http://www.csharp-station.com/HowTo/HttpWebFetch.aspx" rel="nofollow noreferrer">http://www.csharp-station.com/HowTo/HttpWebFetch.aspx</a> tell how to read a web page, but not how to interact with it by submitting information into a form and continuing on to the next page.</p>
<p>For the record, I'm not building a malicious and/or spam related product.</p>
<p>So how do I go read web pages that require a few steps of normal browsing to reach first?</p>
| [
{
"answer_id": 135231,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>What you need to do is keep retrieving and analyzing the html source for each page in the chain. For each page, you need to figure out what the form submission will look like and send a request that will match that to get the next page in the chain.</p>\n\n<p>What I do is build a custom class the wraps System.Net.HttpWebRequest/HttpWebResponse, so retrieving pages is as simple as using System.Net.WebClient. However, my custom class also keeps the same cookie container across requests and makes it a little easier to send post data, customize the user agent, etc. </p>\n"
},
{
"answer_id": 135235,
"author": "SecretDeveloper",
"author_id": 2720,
"author_profile": "https://Stackoverflow.com/users/2720",
"pm_score": 0,
"selected": false,
"text": "<p>Depending on how the website works you can either manipulate the url to perform what you want. e.g to search for the word \"beatles\" you could just open a request to google.com?q=beetles and then just read the results. </p>\n\n<p>Alternatively if the website does not use querystring values (url) to process page actions then you will need to work on a webrequest which posts the required values to the website instead. Search in Google for working with WebRequest and webresponse. </p>\n"
},
{
"answer_id": 135460,
"author": "Chris Lawlor",
"author_id": 21245,
"author_profile": "https://Stackoverflow.com/users/21245",
"pm_score": 3,
"selected": false,
"text": "<p>You can programmatically create an Http request and retrieve the response:</p>\n\n<pre><code> string uri = \"http://www.google.com/search\";\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);\n request.Method = \"POST\";\n request.ContentType = \"application/x-www-form-urlencoded\";\n\n // encode the data to POST:\n string postData = \"q=searchterm&hl=en\";\n byte[] encodedData = new ASCIIEncoding().GetBytes(postData);\n request.ContentLength = encodedData.Length;\n\n Stream requestStream = request.GetRequestStream();\n requestStream.Write(encodedData, 0, encodedData.Length);\n\n // send the request and get the response\n using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())\n {\n\n // Do something with the response stream. As an example, we'll\n // stream the response to the console via a 256 character buffer\n using (StreamReader reader = new StreamReader(response.GetResponseStream()))\n {\n Char[] buffer = new Char[256];\n int count = reader.Read(buffer, 0, 256);\n while (count > 0)\n {\n Console.WriteLine(new String(buffer, 0, count));\n count = reader.Read(buffer, 0, 256);\n }\n } // reader is disposed here\n } // response is disposed here\n</code></pre>\n\n<p>Of course, this code will return an error since Google uses GET, not POST, for search queries.</p>\n\n<p>This method will work if you are dealing with specific web pages, as the URLs and POST data are all basically hard-coded. If you needed something that was a little more dynamic, you'd have to:</p>\n\n<ol>\n<li>Capture the page</li>\n<li>Strip out the form</li>\n<li>Create a POST string based on the form fields</li>\n</ol>\n\n<p>FWIW, I think something like Perl or Python might be better suited to that sort of task.</p>\n\n<p>edit: x-www-form-urlencoded</p>\n"
},
{
"answer_id": 136276,
"author": "Axl",
"author_id": 16605,
"author_profile": "https://Stackoverflow.com/users/16605",
"pm_score": 2,
"selected": false,
"text": "<p>You might try <a href=\"http://selenium.openqa.org/\" rel=\"nofollow noreferrer\">Selenium</a>. Record the actions in Firefox using Selenium IDE, save the script in C# format, then play them back using the Selenium RC C# wrapper. As others have mentioned you could also use <a href=\"http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx\" rel=\"nofollow noreferrer\">System.Net.HttpWebRequest</a> or <a href=\"http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx\" rel=\"nofollow noreferrer\">System.Net.WebClient</a>. If this is a desktop application see also <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.aspx\" rel=\"nofollow noreferrer\">System.Windows.Forms.WebBrowser</a>.</p>\n\n<p>Addendum: Similar to Selenium IDE and Selenium RC, which are Java-based, <a href=\"http://watintestrecord.sourceforge.net/\" rel=\"nofollow noreferrer\">WatiN Test Recorder</a> and <a href=\"http://watin.sourceforge.net/\" rel=\"nofollow noreferrer\">WatiN</a> are .NET-based.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have a project at work the requires me to be able to enter information into a web page, read the next page I get redirected to and then take further action. A simplified real-world example would be something like going to google.com, entering "Coding tricks" as search criteria, and reading the resulting page.
Small coding examples like the ones linked to at <http://www.csharp-station.com/HowTo/HttpWebFetch.aspx> tell how to read a web page, but not how to interact with it by submitting information into a form and continuing on to the next page.
For the record, I'm not building a malicious and/or spam related product.
So how do I go read web pages that require a few steps of normal browsing to reach first? | You can programmatically create an Http request and retrieve the response:
```
string uri = "http://www.google.com/search";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// encode the data to POST:
string postData = "q=searchterm&hl=en";
byte[] encodedData = new ASCIIEncoding().GetBytes(postData);
request.ContentLength = encodedData.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(encodedData, 0, encodedData.Length);
// send the request and get the response
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// Do something with the response stream. As an example, we'll
// stream the response to the console via a 256 character buffer
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Char[] buffer = new Char[256];
int count = reader.Read(buffer, 0, 256);
while (count > 0)
{
Console.WriteLine(new String(buffer, 0, count));
count = reader.Read(buffer, 0, 256);
}
} // reader is disposed here
} // response is disposed here
```
Of course, this code will return an error since Google uses GET, not POST, for search queries.
This method will work if you are dealing with specific web pages, as the URLs and POST data are all basically hard-coded. If you needed something that was a little more dynamic, you'd have to:
1. Capture the page
2. Strip out the form
3. Create a POST string based on the form fields
FWIW, I think something like Perl or Python might be better suited to that sort of task.
edit: x-www-form-urlencoded |
135,234 | <p>What is the difference between <code>ref</code> and <code>out</code> parameters in .NET? What are the situations where one can be more useful than the other? What would be a code snippet where one can be used and another can't?</p>
| [
{
"answer_id": 135241,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>ref will probably choke on null since it presumably expects to be modifying an existing object. out expects null, since it's returning a new object.</p>\n"
},
{
"answer_id": 135244,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 2,
"selected": false,
"text": "<p>Ref parameters aren't required to be set in the function, whereas out parameters must be bound to a value before exiting the function. Variables passed as out may also be passed to a function without being initialized.</p>\n"
},
{
"answer_id": 135255,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 1,
"selected": false,
"text": "<p><code>out</code> parameters are initialized by the method called, <code>ref</code> parameters are initialized before calling the method. Therefore, <code>out</code> parameters are used when you just need to get a secondary return value, <code>ref</code> parameters are used to get a value <em>and</em> potentially return a change to that value (secondarily to the main return value).</p>\n"
},
{
"answer_id": 135257,
"author": "Khoth",
"author_id": 20686,
"author_profile": "https://Stackoverflow.com/users/20686",
"pm_score": 10,
"selected": true,
"text": "<p>They're pretty much the same - the only difference is that a variable you pass as an <code>out</code> parameter doesn't need to be initialized but passing it as a <code>ref</code> parameter it has to be set to something.</p>\n\n<pre><code>int x;\nFoo(out x); // OK\n\nint y;\nFoo(ref y); // Error: y should be initialized before calling the method\n</code></pre>\n\n<p><code>Ref</code> parameters are for data that might be modified, <code>out</code> parameters are for data that's an additional output for the function (eg <code>int.TryParse</code>) that are already using the return value for something.</p>\n"
},
{
"answer_id": 135263,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 7,
"selected": false,
"text": "<p><a href=\"http://evacion.wordpress.com/2009/08/12/why-does-c-have-both-ref-and-out/\" rel=\"noreferrer\">Why does C# have both 'ref' and 'out'?</a></p>\n\n<p>The caller of a method which takes an out parameter is not required to assign to the variable passed as the out parameter prior to the call; however, the callee is required to assign to the out parameter before returning.</p>\n\n<p>In contrast ref parameters are considered initially assigned by the caller. As such, the callee is not required to assign to the ref parameter before use. Ref parameters are passed both into and out of a method.</p>\n\n<p>So, <code>out</code> means out, while <code>ref</code> is for in and out. </p>\n\n<p>These correspond closely to the <code>[out]</code> and <code>[in,out]</code> parameters of COM interfaces, the advantages of <code>out</code> parameters being that callers need not pass a pre-allocated object in cases where it is not needed by the method being called - this avoids both the cost of allocation, and any cost that might be associated with marshaling (more likely with COM, but not uncommon in .NET).</p>\n"
},
{
"answer_id": 135270,
"author": "BlackWasp",
"author_id": 21862,
"author_profile": "https://Stackoverflow.com/users/21862",
"pm_score": 1,
"selected": false,
"text": "<p>The ref keyword is used to pass values by reference. (This does not preclude the passed values being value-types or reference types). Output parameters specified with the out keyword are for returning values from a method.</p>\n\n<p>One key difference in the code is that you must set the value of an output parameter within the method. This is not the case for ref parameters.</p>\n\n<p>For more details look at <a href=\"http://www.blackwasp.co.uk/CSharpMethodParameters.aspx\" rel=\"nofollow noreferrer\">http://www.blackwasp.co.uk/CSharpMethodParameters.aspx</a></p>\n"
},
{
"answer_id": 135275,
"author": "casademora",
"author_id": 5619,
"author_profile": "https://Stackoverflow.com/users/5619",
"pm_score": 0,
"selected": false,
"text": "<p>This <em><a href=\"http://www.c-sharpcorner.com/UploadFile/mahesh/out_and_ref11112005002102AM/out_and_ref.aspx\" rel=\"nofollow noreferrer\">The out and ref Paramerter in C#</a></em> has some good examples.</p>\n\n<p>The basic difference outlined is that <code>out</code> parameters don't need to be initialized when passed in, while ref parameters do.</p>\n"
},
{
"answer_id": 135292,
"author": "Jacob Proffitt",
"author_id": 1336,
"author_profile": "https://Stackoverflow.com/users/1336",
"pm_score": 0,
"selected": false,
"text": "<p>out and ref are exactly the same with the exception that out variables don't have to be initialized before sending it into the abyss. I'm not that smart, I cribbed that from the MSDN library :).</p>\n\n<p>To be more explicit about their use, however, the meaning of the modifier is that if you change the reference of that variable in your code, out and ref will cause your calling variable to change reference as well. In the code below, the ceo variable will be a reference to the newGuy once it returns from the call to doStuff. If it weren't for ref (or out) the reference wouldn't be changed.</p>\n\n<pre><code>private void newEmployee()\n{\n Person ceo = Person.FindCEO();\n doStuff(ref ceo);\n}\n\nprivate void doStuff(ref Person employee)\n{\n Person newGuy = new Person();\n employee = newGuy;\n}\n</code></pre>\n"
},
{
"answer_id": 135403,
"author": "Euro Micelli",
"author_id": 2230,
"author_profile": "https://Stackoverflow.com/users/2230",
"pm_score": 6,
"selected": false,
"text": "<p><code>ref</code> and <code>out</code> both allow the called method to modify a parameter. The difference between them is what happens <em>before</em> you make the call.</p>\n<ul>\n<li><p><code>ref</code> means that the parameter has a value on it <strong>before</strong> going into the function. The called function can read and or change the value any time. <em>The parameter goes in, then comes out</em></p>\n</li>\n<li><p><code>out</code> means that the parameter has no official value before going into the function. The called function must initialize it. <em>The parameter only goes out</em></p>\n</li>\n</ul>\n<p>Here's my favorite way to look at it: <code>ref</code> is to pass variables by reference. <code>out</code> is to declare a secondary <strong>return value</strong> for the function. It's like if you could write this:</p>\n<pre><code>// This is not C#\npublic (bool, string) GetWebThing(string name, ref Buffer paramBuffer);\n\n// This is C#\npublic bool GetWebThing(string name, ref Buffer paramBuffer, out string actualUrl);\n</code></pre>\n<p>Here's a more detailed list of the effects of each alternative:</p>\n<h3>Before calling the method:</h3>\n<p><code>ref</code>: The caller must set the value of the parameter before passing it to the called method.</p>\n<p><code>out</code>: The caller method is not required to set the value of the argument before calling the method. Most likely, you shouldn't. In fact, any current value is discarded.</p>\n<h3>During the call:</h3>\n<p><code>ref</code>: The called method can read the argument at any time.</p>\n<p><code>out</code>: The called method must initialize the parameter before reading it.</p>\n<h3>Remoted calls:</h3>\n<p><code>ref</code>: The current value is marshalled to the remote call. Extra performance cost.</p>\n<p><code>out</code>: Nothing is passed to the remote call. Faster.</p>\n<p>Technically speaking, you could use always <code>ref</code> in place of <code>out</code>, but <code>out</code> allows you to be more precise about the meaning of the argument, and sometimes it can be a lot more efficient.</p>\n"
},
{
"answer_id": 286170,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Example for OUT : Variable gets value initialized after going into the method. Later the same value is returned to the main method.</p>\n\n<pre><code>namespace outreftry\n{\n class outref\n {\n static void Main(string[] args)\n {\n yyy a = new yyy(); ;\n\n // u can try giving int i=100 but is useless as that value is not passed into\n // the method. Only variable goes into the method and gets changed its\n // value and comes out. \n int i; \n\n a.abc(out i);\n\n System.Console.WriteLine(i);\n }\n }\n class yyy\n {\n\n public void abc(out int i)\n {\n\n i = 10;\n\n }\n\n }\n}\n</code></pre>\n\n<blockquote>\n <p>Output: </p>\n \n <p>10</p>\n</blockquote>\n\n<p>===============================================</p>\n\n<p>Example for Ref : Variable should be initialized before going into the method. Later same value or modified value will be returned to the main method.</p>\n\n<pre><code>namespace outreftry\n{\n class outref\n {\n static void Main(string[] args)\n {\n yyy a = new yyy(); ;\n\n int i = 0;\n\n a.abc(ref i);\n\n System.Console.WriteLine(i);\n }\n }\n class yyy\n {\n\n public void abc(ref int i)\n {\n System.Console.WriteLine(i);\n i = 10;\n\n }\n\n }\n}\n</code></pre>\n\n<blockquote>\n <p>Output: </p>\n\n<pre><code> 0\n 10\n</code></pre>\n</blockquote>\n\n<p>=================================</p>\n\n<p>Hope its clear now.</p>\n"
},
{
"answer_id": 3000832,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 3,
"selected": false,
"text": "<ul>\n<li>A <code>ref</code> variable needs to be initialized before passing it in.</li>\n<li>An <code>out</code> variable needs to be set in your function implementation</li>\n<li><code>out</code> parameters can be thought of as additional return variables (not input)</li>\n<li><code>ref</code> parameters can be thought of as both input and output variables. </li>\n</ul>\n"
},
{
"answer_id": 3000840,
"author": "Alan",
"author_id": 37843,
"author_profile": "https://Stackoverflow.com/users/37843",
"pm_score": 2,
"selected": false,
"text": "<p><code>out</code> specifies that the parameter is an output parameters, i.e. it has no value until it is explicitly set by the method.</p>\n\n<p><code>ref</code> specifies that the value is a reference that has a value, and whose value you can change inside the method.</p>\n"
},
{
"answer_id": 12914635,
"author": "Krishna Thota",
"author_id": 1113226,
"author_profile": "https://Stackoverflow.com/users/1113226",
"pm_score": 3,
"selected": false,
"text": "<h2>Ref and Out Parameters:</h2>\n\n<p>The <code>out</code> and the <code>ref</code> parameters are used to return values in the same variable, that you pass as an argument of a method. These both parameters are very useful when your method needs to return more than one value.</p>\n\n<p>You must assigned value to out parameter in calee method body, otherwise the method won't get compiled.</p>\n\n<hr>\n\n<blockquote>\n <p><strong>Ref Parameter :</strong> It has to be initialized before passing to the Method. \n The <code>ref</code> keyword on a method parameter causes a method to refer to the same variable that was passed as an input parameter for the same method. If you do any changes to the variable, they will be reflected in the variable. </p>\n\n<pre><code>int sampleData = 0; \nsampleMethod(ref sampleData);\n</code></pre>\n</blockquote>\n\n<p><strong><em>Ex of Ref Parameter</em></strong></p>\n\n<pre><code>public static void Main() \n{ \n int i = 3; // Variable need to be initialized \n sampleMethod(ref i ); \n}\n\npublic static void sampleMethod(ref int sampleData) \n{ \n sampleData++; \n} \n</code></pre>\n\n<hr>\n\n<blockquote>\n <p><strong>Out Parameter :</strong> It is not necessary to be initialized before passing to Method. \n The <code>out</code> parameter can be used to return the values in the same variable passed as a parameter of the method. Any changes made to the parameter will be reflected in the variable.</p>\n\n<pre><code> int sampleData; \n sampleMethod(out sampleData);\n</code></pre>\n</blockquote>\n\n<p><em><strong>Ex of Out Parameter</em></strong></p>\n\n<pre><code>public static void Main() \n{ \n int i, j; // Variable need not be initialized \n sampleMethod(out i, out j); \n} \npublic static int sampleMethod(out int sampleData1, out int sampleData2) \n{ \n sampleData1 = 10; \n sampleData2 = 20; \n return 0; \n} \n</code></pre>\n\n<hr>\n"
},
{
"answer_id": 14656920,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 1,
"selected": false,
"text": "<p>An <code>out</code> parameter is a <code>ref</code> parameter with a special <code>Out()</code> attribute added. If a parameter to a C# method is declared as <code>out</code>, the compiler will require that the parameter be written before it can be read and before the method can return. If C# calls a method whose parameter includes an <code>Out()</code> attribute, the compiler will, for purposes of deciding whether to report \"undefined variable\" errors, pretend that the variable is written immediately before calling the method. Note that because other .net languages do not attach the same meaning to the <code>Out()</code> attribute, it is possible that calling a routine with an <code>out</code> parameter will leave the variable in question unaffected. If a variable is used as an <code>out</code> parameter before it is definitely assigned, the C# compiler will generate code to ensure that it gets cleared at some point before it is used, but if such a variable leaves and re-enters scope, there's no guarantee that it will be cleared again.</p>\n"
},
{
"answer_id": 36363561,
"author": "Nazmul Hasan",
"author_id": 4415445,
"author_profile": "https://Stackoverflow.com/users/4415445",
"pm_score": 3,
"selected": false,
"text": "<h2>out:</h2>\n\n<p>In C#, a method can return only one value. If you would like to return more than one value, you can use the out keyword. The out modifier returns as return-by-reference. The simplest answer is that the keyword “out” is used to get the value from the method.</p>\n\n<ul>\n<li>You don't need to initialize the value in the calling function.</li>\n<li>You must assign the value in the called function, otherwise the compiler will report an error.</li>\n</ul>\n\n<h2>ref:</h2>\n\n<p>In C#, when you pass a value type such as int, float, double etc. as an argument to the method parameter, it is passed by value. Therefore, if you modify the parameter value, it does not affect argument in the method call. But if you mark the parameter with “ref” keyword, it will reflect in the actual variable.</p>\n\n<ul>\n<li>You need to initialize the variable before you call the function.</li>\n<li>It’s not mandatory to assign any value to the ref parameter in the method. If you don’t change the value, what is the need to mark it as “ref”?</li>\n</ul>\n"
},
{
"answer_id": 43721946,
"author": "jpaugh",
"author_id": 712526,
"author_profile": "https://Stackoverflow.com/users/712526",
"pm_score": 0,
"selected": false,
"text": "<p>They are subtly different. </p>\n\n<p>An <code>out</code> parameter does not need to be initialized by the callee before being passed to the method. Therefore, any method with an <code>out</code> parameter</p>\n\n<ul>\n<li>Cannot read the parameter before assigning a value to it</li>\n<li>Must assign a value to it before returning</li>\n</ul>\n\n<p>This is used for a method which needs to overwrite its argument regardless of its previous value.</p>\n\n<hr>\n\n<p>A <code>ref</code> parameter must be initialized by the callee before passing it to the method. Therefore, any method with a <code>ref</code> parameter</p>\n\n<ul>\n<li>Can inspect the value before assigning it</li>\n<li>Can return the original value, untouched</li>\n</ul>\n\n<p>This is used for a method which must (e.g.) inspect its value and validate it or normalize it.</p>\n"
},
{
"answer_id": 44029981,
"author": "Marc Ziss",
"author_id": 555061,
"author_profile": "https://Stackoverflow.com/users/555061",
"pm_score": 0,
"selected": false,
"text": "<p>out has gotten a new more succint syntax in C#7\n<a href=\"https://learn.microsoft.com/en-us/dotnet/articles/csharp/whats-new/csharp-7#more-expression-bodied-members\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/articles/csharp/whats-new/csharp-7#more-expression-bodied-members</a>\nand even more exciting is the C#7 tuple enhancements that are a more elegant choice than using ref and out IMHO.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1909/"
]
| What is the difference between `ref` and `out` parameters in .NET? What are the situations where one can be more useful than the other? What would be a code snippet where one can be used and another can't? | They're pretty much the same - the only difference is that a variable you pass as an `out` parameter doesn't need to be initialized but passing it as a `ref` parameter it has to be set to something.
```
int x;
Foo(out x); // OK
int y;
Foo(ref y); // Error: y should be initialized before calling the method
```
`Ref` parameters are for data that might be modified, `out` parameters are for data that's an additional output for the function (eg `int.TryParse`) that are already using the return value for something. |
135,246 | <p>I'm attempting to write a Python C extension that reads packed binary data (it is stored as structs of structs) and then parses it out into Python objects. Everything works as expected on a 32 bit machine (the binary files are always written on 32bit architecture), but not on a 64 bit box. Is there a "preferred" way of doing this?</p>
<hr>
<p>It would be a lot of code to post but as an example:</p>
<pre><code>struct
{
WORD version;
BOOL upgrade;
time_t time1;
time_t time2;
} apparms;
File *fp;
fp = fopen(filePath, "r+b");
fread(&apparms, sizeof(apparms), 1, fp);
return Py_BuildValue("{s:i,s:l,s:l}",
"sysVersion",apparms.version,
"powerFailTime", apparms.time1,
"normKitExpDate", apparms.time2
);
</code></pre>
<p>Now on a 32 bit system this works great, but on a 64 bit my time_t sizes are different (32bit vs 64 bit longs).</p>
<hr>
<p>Damn, you people are fast. </p>
<p>Patrick, I originally started using the struct package but found it just way to slow for my needs. Plus I was looking for an excuse to write a Python Extension.</p>
<p>I know this is a stupid question but what types do I need to watch out for?</p>
<p>Thanks.</p>
| [
{
"answer_id": 135267,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 1,
"selected": false,
"text": "<p>What's your code for reading the binary data? Make sure you're copying the data into properly-sized types like <code>int32_t</code> instead of just <code>int</code>.</p>\n"
},
{
"answer_id": 135271,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 0,
"selected": false,
"text": "<p>Why aren't you using the <a href=\"http://docs.python.org/lib/module-struct.html\" rel=\"nofollow noreferrer\">struct</a> package?</p>\n"
},
{
"answer_id": 135276,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 2,
"selected": false,
"text": "<p>The 'struct' module should be able to do this, although alignment of structs in the middle of the data is always an issue. It's not very hard to get it right, however: find out (once) what boundary the structs-in-structs align to, then pad (manually, with the 'x' specifier) to that boundary. You can doublecheck your padding by comparing struct.calcsize() with your actual data. It's certainly easier than writing a C extension for it.</p>\n\n<p>In order to keep using Py_BuildValue() like that, you have two options. You can determine the size of time_t at compiletime (in terms of fundamental types, so 'an int' or 'a long' or 'an ssize_t') and then use the right format character to Py_BuildValue -- 'i' for an int, 'l' for a long, 'n' for an ssize_t. Or you can use PyInt_FromSsize_t() manually, in which case the compiler does the upcasting for you, and then use the 'O' format characters to pass the result to Py_BuildValue.</p>\n"
},
{
"answer_id": 135311,
"author": "Dan Udey",
"author_id": 21450,
"author_profile": "https://Stackoverflow.com/users/21450",
"pm_score": 3,
"selected": true,
"text": "<p>Explicitly specify that your data types (e.g. integers) are 32-bit. Otherwise if you have two integers next to each other when you read them they will be read as one 64-bit integer.</p>\n\n<p>When you are dealing with cross-platform issues, the two main things to watch out for are:</p>\n\n<ol>\n<li>Bitness. If your packed data is written with 32-bit ints, then all of your code must explicitly specify 32-bit ints when reading <em>and</em> writing.</li>\n<li>Byte order. If you move your code from Intel chips to PPC or SPARC, your byte order will be wrong. You will have to import your data and then byte-flip it so that it matches up with the current architecture. Otherwise 12 (<code>0x0000000C</code>) will be read as 201326592 (<code>0x0C000000</code>).</li>\n</ol>\n\n<p>Hopefully this helps.</p>\n"
},
{
"answer_id": 135360,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 2,
"selected": false,
"text": "<p>You need to make sure you're using architecture independent members for your struct. For instance an int may be 32 bits on one architecture and 64 bits on another. As others have suggested, use the <code>int32_t</code> style types instead. If your struct contains unaligned members, you may need to deal with padding added by the compiler too.</p>\n\n<p>Another common problem with cross architecture data is endianness. Intel i386 architecture is little-endian, but if you're reading on a completely different machine (e.g. an Alpha or Sparc), you'll have to worry about this too.</p>\n\n<p>The Python struct module deals with both these situations, using the prefix passed as part of the format string.</p>\n\n<ul>\n<li>@ - Use native size, endianness and alignment. i= sizeof(int), l= sizeof(long)</li>\n<li>= - Use native endianness, but standard sizes and alignment (i=32 bits, l=64 bits)</li>\n<li>< - Little-endian standard sizes/alignment</li>\n<li><blockquote>\n <ul>\n <li>Big-endian standard sizes/alignment</li>\n </ul>\n</blockquote></li>\n</ul>\n\n<p>In general, if the data passes off your machine, you should nail down the endianness and the size / padding format to something specific — ie. use \"<\" or \">\" as your format. If you want to handle this in your C extension, you may need to add some code to handle it.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16363/"
]
| I'm attempting to write a Python C extension that reads packed binary data (it is stored as structs of structs) and then parses it out into Python objects. Everything works as expected on a 32 bit machine (the binary files are always written on 32bit architecture), but not on a 64 bit box. Is there a "preferred" way of doing this?
---
It would be a lot of code to post but as an example:
```
struct
{
WORD version;
BOOL upgrade;
time_t time1;
time_t time2;
} apparms;
File *fp;
fp = fopen(filePath, "r+b");
fread(&apparms, sizeof(apparms), 1, fp);
return Py_BuildValue("{s:i,s:l,s:l}",
"sysVersion",apparms.version,
"powerFailTime", apparms.time1,
"normKitExpDate", apparms.time2
);
```
Now on a 32 bit system this works great, but on a 64 bit my time\_t sizes are different (32bit vs 64 bit longs).
---
Damn, you people are fast.
Patrick, I originally started using the struct package but found it just way to slow for my needs. Plus I was looking for an excuse to write a Python Extension.
I know this is a stupid question but what types do I need to watch out for?
Thanks. | Explicitly specify that your data types (e.g. integers) are 32-bit. Otherwise if you have two integers next to each other when you read them they will be read as one 64-bit integer.
When you are dealing with cross-platform issues, the two main things to watch out for are:
1. Bitness. If your packed data is written with 32-bit ints, then all of your code must explicitly specify 32-bit ints when reading *and* writing.
2. Byte order. If you move your code from Intel chips to PPC or SPARC, your byte order will be wrong. You will have to import your data and then byte-flip it so that it matches up with the current architecture. Otherwise 12 (`0x0000000C`) will be read as 201326592 (`0x0C000000`).
Hopefully this helps. |
135,254 | <p>I have a number of panels in a single window in C# application and I created 2 scrollbars, one for horizontal and one vertical. This is what I currently have:</p>
<p><a href="http://www.simnet.is/elinnils52/scrollbar.jpg" rel="nofollow noreferrer">picture with 2 scroolbars http://www.simnet.is/elinnils52/scrollbar.jpg</a></p>
<p>I have 1 variable and that is the total height all the items take & need.
Here is my code on scroll change:</p>
<pre><code>for (int i = 0; i < this._splitMainView.Panel2.Controls.Count; i++)
{
this._splitMainView.Panel2.Controls[i].Location = new Point(
3 - _scrollBarX.Value,
3 + (132 + 6) * (i - 2) - _scrollBarY.Value);
this._splitMainView.Panel2.Controls[i].Refresh();
}
</code></pre>
<p>The scrollbar maximum is the total amount of all the containers height, the space in between and a few pixels extra.</p>
<p>As you can see from the picture, it doesn't look good. Even if the maximum in this case is a little around 50 - 100 pixels it still looks like it's a thousand pages long. When I change the SmallChange and LargeChange, the scrollbar bar itself lengthens but then it wont reach the maximum pixels. It will be able to get almost at the end (depening on the SmallChange and LargeChange value) and leave around 5 - 29 px left. And as everyone knows, seeing half is not good.</p>
<p>Does anyone know how to overcome this obstacle or a better way to implement it?</p>
| [
{
"answer_id": 193350,
"author": "Robert C. Barth",
"author_id": 9209,
"author_profile": "https://Stackoverflow.com/users/9209",
"pm_score": 1,
"selected": false,
"text": "<p>Why not just make the maximum value of the scrollbar the overflow (visible area height - panel height)? Then just set the top of the panel to the value of the scrollbar * -1.</p>\n"
},
{
"answer_id": 783552,
"author": "Fredrik Mörk",
"author_id": 93623,
"author_profile": "https://Stackoverflow.com/users/93623",
"pm_score": 0,
"selected": false,
"text": "<p>Is there a reason not to use the AutoScroll property?</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have a number of panels in a single window in C# application and I created 2 scrollbars, one for horizontal and one vertical. This is what I currently have:
[picture with 2 scroolbars http://www.simnet.is/elinnils52/scrollbar.jpg](http://www.simnet.is/elinnils52/scrollbar.jpg)
I have 1 variable and that is the total height all the items take & need.
Here is my code on scroll change:
```
for (int i = 0; i < this._splitMainView.Panel2.Controls.Count; i++)
{
this._splitMainView.Panel2.Controls[i].Location = new Point(
3 - _scrollBarX.Value,
3 + (132 + 6) * (i - 2) - _scrollBarY.Value);
this._splitMainView.Panel2.Controls[i].Refresh();
}
```
The scrollbar maximum is the total amount of all the containers height, the space in between and a few pixels extra.
As you can see from the picture, it doesn't look good. Even if the maximum in this case is a little around 50 - 100 pixels it still looks like it's a thousand pages long. When I change the SmallChange and LargeChange, the scrollbar bar itself lengthens but then it wont reach the maximum pixels. It will be able to get almost at the end (depening on the SmallChange and LargeChange value) and leave around 5 - 29 px left. And as everyone knows, seeing half is not good.
Does anyone know how to overcome this obstacle or a better way to implement it? | Why not just make the maximum value of the scrollbar the overflow (visible area height - panel height)? Then just set the top of the panel to the value of the scrollbar \* -1. |
135,303 | <p>In C# I could easily write the following:</p>
<pre><code>string stringValue = string.IsNullOrEmpty( otherString ) ? defaultString : otherString;
</code></pre>
<p>Is there a quick way of doing the same thing in Python or am I stuck with an 'if' statement?</p>
| [
{
"answer_id": 135318,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 6,
"selected": true,
"text": "<p>In Python 2.5, there is</p>\n\n<pre><code>A if C else B\n</code></pre>\n\n<p>which behaves a lot like ?: in C. However, it's frowned upon for two reasons: readability, and the fact that there's usually a simpler way to approach the problem. For instance, in your case:</p>\n\n<pre><code>stringValue = otherString or defaultString\n</code></pre>\n"
},
{
"answer_id": 135342,
"author": "Dan Udey",
"author_id": 21450,
"author_profile": "https://Stackoverflow.com/users/21450",
"pm_score": 1,
"selected": false,
"text": "<p>It's never a bad thing to write readable, expressive code.</p>\n\n<pre><code>if otherString:\n stringValue = otherString\nelse:\n stringValue = defaultString\n</code></pre>\n\n<p>This type of code is longer and more expressive, but also more readable and less likely to get tripped over or mis-edited down the road. Don't be afraid to write expressively - readable code should be a goal, not a byproduct.</p>\n"
},
{
"answer_id": 135354,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": -1,
"selected": false,
"text": "<p>You can take advantage of the fact that logical expressions return their value, and not just true or false status. For example, you can always use:</p>\n\n<pre><code>result = question and firstanswer or secondanswer\n</code></pre>\n\n<p>With the caveat that it doesn't work like the ternary operator if firstanswer is false. This is because question is evaluated first, assuming it's true firstanswer is returned unless firstanswer is false, so this usage fails to act like the ternary operator. If you know the values, however, there is usually no problem. An example would be:</p>\n\n<pre><code>result = choice == 7 and \"Seven\" or \"Another Choice\"\n</code></pre>\n"
},
{
"answer_id": 135450,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "<p>@Dan</p>\n\n<blockquote>\n<pre><code>if otherString:\n stringValue = otherString\nelse:\n stringValue = defaultString\n</code></pre>\n \n <p>This type of code is longer and more expressive, but also more readable</p>\n</blockquote>\n\n<p>Well yes, it's longer. Not so sure about “more expressive” and “more readable”. At the very least, your claim is disputable. I would even go as far as saying it's downright wrong, for two reasons.</p>\n\n<p>First, your code emphasizes the decision-making (rather extremely). Onthe other hand, the conditional operator emphasizes something else, namely the value (resp. the assignment of said value). And this is <em>exactly</em> what the writer of this code wants. The decision-making is really rather a by-product of the code. The important part here is the assignment operation. Your code hides this assignment in a lot of syntactic noise: the branching.</p>\n\n<p>Your code is less expressive because it shifts the emphasis from the important part.</p>\n\n<p>Even then your code would probably trump some obscure ASCII art like <code>?:</code>. An inline-<code>if</code> would be preferable. Personally, I don't like the variant introduced with Python 2.5 because it's backwards. I would prefer something that reads in the same flow (direction) as the C ternary operator but uses words instead of ASCII characters:</p>\n\n<pre><code>C = if cond then A else B\n</code></pre>\n\n<p>This wins hands down.</p>\n\n<p>C and C# unfortunately don't have such an expressive statement. But (and this is the second argument), the ternary conditional operator of C languages is so long established that it has become an idiom in itself. The ternary operator is as much part of the language as the “conventional” <code>if</code> statement. Because it's an idiom, anybody who knows the language immediately reads this code right. Furthermore, it's an extremely short, concise way of expressing these semantics. In fact, it's the shortest imaginable way. It's extremely expressive because it doesn't obscure the essence with needless noise.</p>\n\n<p>Finally, Jeff Atwood has written the perfect conclusion to this: <a href=\"http://www.codinghorror.com/blog/archives/000878.html\" rel=\"noreferrer\"><strong>The best code is no code at all</strong></a>.</p>\n"
},
{
"answer_id": 135471,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p>By the way, j0rd4n, you don't (<em>please</em> don't!) write code like this in C#. Apart from the fact that the <code>IsDefaultOrNull</code> is actually called <code>IsNullOrEmpty</code>, this is pure code bloat. C# offers the coalesce operator for situations like these:</p>\n\n<pre><code>string stringValue = otherString ?? defaultString;\n</code></pre>\n\n<p>It's true that this only works if <code>otherString</code> is <code>null</code> (rather than empty) but if this can be ensured beforehand (and often it can) it makes the code much more readable.</p>\n"
},
{
"answer_id": 135889,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": -1,
"selected": false,
"text": "<p>If you used ruby, you could write</p>\n\n<pre><code>stringValue = otherString.blank? ? defaultString : otherString;\n</code></pre>\n\n<p>the built in <code>blank?</code> method means null or empty.<br>\nCome over to the dark side...</p>\n"
},
{
"answer_id": 135907,
"author": "Jordan Parmer",
"author_id": 20133,
"author_profile": "https://Stackoverflow.com/users/20133",
"pm_score": 0,
"selected": false,
"text": "<p>I also discovered that just using the \"or\" operator does pretty well. For instance:</p>\n\n<pre><code>finalString = get_override() or defaultString\n</code></pre>\n\n<p>If <em>get_override()</em> returns \"\" or None, it will always use <em>defaultString</em>.</p>\n"
},
{
"answer_id": 812425,
"author": "Joo Park",
"author_id": 99234,
"author_profile": "https://Stackoverflow.com/users/99234",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.diveintopython.net/power_of_introspection/and_or.html#d0e9975\" rel=\"nofollow noreferrer\">Chapter 4 of diveintopython.net</a> has the answer. It's called the and-or trick in Python.</p>\n"
},
{
"answer_id": 1601685,
"author": "ThomasH",
"author_id": 127465,
"author_profile": "https://Stackoverflow.com/users/127465",
"pm_score": 1,
"selected": false,
"text": "<p>There are a few duplicates of this question, e.g.</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/394809/python-ternary-operator\">Does Python have a ternary conditional operator?</a></li>\n<li><a href=\"https://stackoverflow.com/questions/643983/whats-the-best-way-to-replace-the-ternary-operator-in-python\">What's the best way to replace the ternary operator in Python?</a></li>\n</ul>\n\n<p>In essence, in a general setting pre-2.5 code should use this:</p>\n\n<pre><code> (condExp and [thenExp] or [elseExp])[0]\n</code></pre>\n\n<p>(given condExp, thenExp and elseExp are arbitrary expressions), as it avoids wrong results if thenExp evaluates to boolean False, while maintaining short-circuit evaluation.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20133/"
]
| In C# I could easily write the following:
```
string stringValue = string.IsNullOrEmpty( otherString ) ? defaultString : otherString;
```
Is there a quick way of doing the same thing in Python or am I stuck with an 'if' statement? | In Python 2.5, there is
```
A if C else B
```
which behaves a lot like ?: in C. However, it's frowned upon for two reasons: readability, and the fact that there's usually a simpler way to approach the problem. For instance, in your case:
```
stringValue = otherString or defaultString
``` |
135,317 | <p>When running a CherryPy app it will send server name tag something like CherryPy/version.
Is it possible to rename/overwrite that from the app without modifying CherryPy so it will show something else? </p>
<p>Maybe something like MyAppName/version (CherryPy/version) </p>
| [
{
"answer_id": 135644,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 2,
"selected": false,
"text": "<p>This string appears to be being set in the CherrPy <a href=\"http://www.cherrypy.org/browser/trunk/cherrypy/_cprequest.py\" rel=\"nofollow noreferrer\">Response</a> class:</p>\n\n<pre><code>def __init__(self):\n self.status = None\n self.header_list = None\n self._body = []\n self.time = time.time()\n\n self.headers = http.HeaderMap()\n # Since we know all our keys are titled strings, we can\n # bypass HeaderMap.update and get a big speed boost.\n dict.update(self.headers, {\n \"Content-Type\": 'text/html',\n \"Server\": \"CherryPy/\" + cherrypy.__version__,\n \"Date\": http.HTTPDate(self.time),\n })\n</code></pre>\n\n<p>So when you're creating your Response object, you can update the \"Server\" header to display your desired string. From the CherrPy <a href=\"http://www.cherrypy.org/wiki/ResponseObject\" rel=\"nofollow noreferrer\">Response Object documentation</a>: </p>\n\n<blockquote>\n <h3>headers</h3>\n \n <p><em>A dictionary containing the headers of the response. You may set values in \n this dict anytime before the finalize phase, after which CherryPy switches \n to using header_list ...</em></p>\n</blockquote>\n\n<p><strong>EDIT</strong>: To avoid needing to make this change with every response object you create, one simple way to get around this is to wrap the Response object. For example, you can create your own Response object that inherits from CherryPy's Response and updates the headers key after initializing: </p>\n\n<pre><code>class MyResponse(Response):\n\n def __init__(self):\n Response.__init__(self)\n dict.update(self.headers, {\n \"Server\": \"MyServer/1.0\",\n })\n\nRespObject = MyResponse()\nprint RespObject.headers[\"Server\"]\n</code></pre>\n\n<p>Then you can can call your object for uses where you need to create a Response object, and it will always have the Server header set to your desired string.</p>\n"
},
{
"answer_id": 208792,
"author": "daniels",
"author_id": 9789,
"author_profile": "https://Stackoverflow.com/users/9789",
"pm_score": 4,
"selected": true,
"text": "<p>Actually asking on IRC on their official channel fumanchu gived me a more clean way to do this (using latest svn):</p>\n\n<pre><code>import cherrypy\nfrom cherrypy import _cpwsgi_server \nclass HelloWorld(object):\n def index(self):\n return \"Hello World!\"\n index.exposed = True\n\nserverTag = \"MyApp/%s (CherryPy/%s)\" % (\"1.2.3\", cherrypy.__version__)\n_cpwsgi_server.CPWSGIServer.environ['SERVER_SOFTWARE'] = serverTag\ncherrypy.config.update({'tools.response_headers.on': True,\n 'tools.response_headers.headers': [('Server', serverTag)]})\ncherrypy.quickstart(HelloWorld())\n</code></pre>\n"
},
{
"answer_id": 15035521,
"author": "Baxter",
"author_id": 184822,
"author_profile": "https://Stackoverflow.com/users/184822",
"pm_score": 3,
"selected": false,
"text": "<p>This can now be set on a per application basis in the config file/dict</p>\n\n<pre><code>[/] \nresponse.headers.server = \"CherryPy Dev01\"\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9789/"
]
| When running a CherryPy app it will send server name tag something like CherryPy/version.
Is it possible to rename/overwrite that from the app without modifying CherryPy so it will show something else?
Maybe something like MyAppName/version (CherryPy/version) | Actually asking on IRC on their official channel fumanchu gived me a more clean way to do this (using latest svn):
```
import cherrypy
from cherrypy import _cpwsgi_server
class HelloWorld(object):
def index(self):
return "Hello World!"
index.exposed = True
serverTag = "MyApp/%s (CherryPy/%s)" % ("1.2.3", cherrypy.__version__)
_cpwsgi_server.CPWSGIServer.environ['SERVER_SOFTWARE'] = serverTag
cherrypy.config.update({'tools.response_headers.on': True,
'tools.response_headers.headers': [('Server', serverTag)]})
cherrypy.quickstart(HelloWorld())
``` |
135,330 | <p>Does anybody know if there is a built-in function in Mathematica for getting the lhs of downvalue rules (without any holding)? I know how to write the code to do it, but it seems basic enough for a built-in</p>
<p>For example:</p>
<pre><code>a[1]=2;
a[2]=3;
</code></pre>
<p><code>BuiltInIDoNotKnowOf[a]</code> returns <code>{1,2}</code></p>
| [
{
"answer_id": 138033,
"author": "Will Robertson",
"author_id": 4161,
"author_profile": "https://Stackoverflow.com/users/4161",
"pm_score": 4,
"selected": true,
"text": "<p>This seems to work; not sure how useful it is, though:</p>\n\n<pre><code>a[1] = 2\na[2] = 3\na[3] = 5\na[6] = 8\nPart[DownValues[a], All, 1, 1, 1]\n</code></pre>\n"
},
{
"answer_id": 154704,
"author": "dreeves",
"author_id": 4234,
"author_profile": "https://Stackoverflow.com/users/4234",
"pm_score": 5,
"selected": false,
"text": "<p>This is like <code>keys()</code> in Perl and Python and other languages that have built in support for hashes (aka dictionaries). As your example illustrates, Mathematica supports hashes without any special syntax. Just say <code>a[1] = 2</code> and you have a hash. [1]\nTo get the keys of a hash, I recommend adding this to your init.m or your personal utilities library:</p>\n\n<pre><code>keys[f_] := DownValues[f][[All,1,1,1]] (* Keys of a hash/dictionary. *)\n</code></pre>\n\n<p>(Or the following pure function version is supposedly slightly faster:</p>\n\n<pre><code>keys = DownValues[#][[All,1,1,1]]&; (* Keys of a hash/dictionary. *)\n</code></pre>\n\n<p>)</p>\n\n<p>Either way, <code>keys[a]</code> now returns what you want. (You can get the values of the hash with <code>a /@ keys[a]</code>.) If you want to allow for higher arity hashes, like <code>a[1,2]=5; a[3,4]=6</code> then you can use this:</p>\n\n<pre><code>SetAttributes[removeHead, {HoldAll}];\nremoveHead[h_[args___]] := {args}\nkeys[f_] := removeHead @@@ DownValues[f][[All,1]]\n</code></pre>\n\n<p>Which returns <code>{{1,2}, {3,4}}</code>. (In that case you can get the hash values with <code>a @@@ keys[a]</code>.)</p>\n\n<p>Note that <code>DownValues</code> by default sorts the keys, which is probably not a good idea since at best it takes extra time. If you want the keys sorted you can just do <code>Sort@keys[f]</code>. So I would actually recommend this version:</p>\n\n<pre><code>keys = DownValues[#,Sort->False][[All,1,1,1]]&;\n</code></pre>\n\n<p>Interestingly, there is no mention of the <code>Sort</code> option in the <code>DownValues</code> documention. I found out about it from an old post from Daniel Lichtblau of Wolfram Research. (I confirmed that it still works in the current version (7.0) of Mathematica.)</p>\n\n<hr/>\n\n<p>Footnotes:</p>\n\n<p>[1] What's really handy is that you can mix and match that with function definitions. Like:</p>\n\n<pre><code>fib[0] = 1;\nfib[1] = 1;\nfib[n_] := fib[n-1] + fib[n-2]\n</code></pre>\n\n<p>You can then add memoization by changing that last line to</p>\n\n<pre><code>fib[n_] := fib[n] = fib[n-1] + fib[n-2]\n</code></pre>\n\n<p>which says to cache the answer for all subsequent calls.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/279/"
]
| Does anybody know if there is a built-in function in Mathematica for getting the lhs of downvalue rules (without any holding)? I know how to write the code to do it, but it seems basic enough for a built-in
For example:
```
a[1]=2;
a[2]=3;
```
`BuiltInIDoNotKnowOf[a]` returns `{1,2}` | This seems to work; not sure how useful it is, though:
```
a[1] = 2
a[2] = 3
a[3] = 5
a[6] = 8
Part[DownValues[a], All, 1, 1, 1]
``` |
135,339 | <p>Within an n-tier app that makes use of a WCF service to interact with the database, what is the best practice way of making use of LinqToSql classes throughout the app?</p>
<p>I've seen it done a couple of different ways but they seemed like they burned a lot of hours creating extra interfaces, message classes, and the like which reduces the benefit you get from not having to write your data access code.</p>
<p>Is there a good way to do it currently? Are we stuck waiting for the Entity Framework?</p>
| [
{
"answer_id": 138033,
"author": "Will Robertson",
"author_id": 4161,
"author_profile": "https://Stackoverflow.com/users/4161",
"pm_score": 4,
"selected": true,
"text": "<p>This seems to work; not sure how useful it is, though:</p>\n\n<pre><code>a[1] = 2\na[2] = 3\na[3] = 5\na[6] = 8\nPart[DownValues[a], All, 1, 1, 1]\n</code></pre>\n"
},
{
"answer_id": 154704,
"author": "dreeves",
"author_id": 4234,
"author_profile": "https://Stackoverflow.com/users/4234",
"pm_score": 5,
"selected": false,
"text": "<p>This is like <code>keys()</code> in Perl and Python and other languages that have built in support for hashes (aka dictionaries). As your example illustrates, Mathematica supports hashes without any special syntax. Just say <code>a[1] = 2</code> and you have a hash. [1]\nTo get the keys of a hash, I recommend adding this to your init.m or your personal utilities library:</p>\n\n<pre><code>keys[f_] := DownValues[f][[All,1,1,1]] (* Keys of a hash/dictionary. *)\n</code></pre>\n\n<p>(Or the following pure function version is supposedly slightly faster:</p>\n\n<pre><code>keys = DownValues[#][[All,1,1,1]]&; (* Keys of a hash/dictionary. *)\n</code></pre>\n\n<p>)</p>\n\n<p>Either way, <code>keys[a]</code> now returns what you want. (You can get the values of the hash with <code>a /@ keys[a]</code>.) If you want to allow for higher arity hashes, like <code>a[1,2]=5; a[3,4]=6</code> then you can use this:</p>\n\n<pre><code>SetAttributes[removeHead, {HoldAll}];\nremoveHead[h_[args___]] := {args}\nkeys[f_] := removeHead @@@ DownValues[f][[All,1]]\n</code></pre>\n\n<p>Which returns <code>{{1,2}, {3,4}}</code>. (In that case you can get the hash values with <code>a @@@ keys[a]</code>.)</p>\n\n<p>Note that <code>DownValues</code> by default sorts the keys, which is probably not a good idea since at best it takes extra time. If you want the keys sorted you can just do <code>Sort@keys[f]</code>. So I would actually recommend this version:</p>\n\n<pre><code>keys = DownValues[#,Sort->False][[All,1,1,1]]&;\n</code></pre>\n\n<p>Interestingly, there is no mention of the <code>Sort</code> option in the <code>DownValues</code> documention. I found out about it from an old post from Daniel Lichtblau of Wolfram Research. (I confirmed that it still works in the current version (7.0) of Mathematica.)</p>\n\n<hr/>\n\n<p>Footnotes:</p>\n\n<p>[1] What's really handy is that you can mix and match that with function definitions. Like:</p>\n\n<pre><code>fib[0] = 1;\nfib[1] = 1;\nfib[n_] := fib[n-1] + fib[n-2]\n</code></pre>\n\n<p>You can then add memoization by changing that last line to</p>\n\n<pre><code>fib[n_] := fib[n] = fib[n-1] + fib[n-2]\n</code></pre>\n\n<p>which says to cache the answer for all subsequent calls.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1860358/"
]
| Within an n-tier app that makes use of a WCF service to interact with the database, what is the best practice way of making use of LinqToSql classes throughout the app?
I've seen it done a couple of different ways but they seemed like they burned a lot of hours creating extra interfaces, message classes, and the like which reduces the benefit you get from not having to write your data access code.
Is there a good way to do it currently? Are we stuck waiting for the Entity Framework? | This seems to work; not sure how useful it is, though:
```
a[1] = 2
a[2] = 3
a[3] = 5
a[6] = 8
Part[DownValues[a], All, 1, 1, 1]
``` |
135,375 | <p>I have a <code>ListBox</code> <code>DataTemplate</code> in WPF. I want one item to be tight against the left side of the <code>ListBox</code> and another item to be tight against the right side, but I can't figure out how to do this.</p>
<p>So far I have a <code>Grid</code> with three columns, the left and right ones have content and the center is a placeholder with it's width set to "*". Where am I going wrong?</p>
<p>Here is the code:</p>
<pre><code><DataTemplate x:Key="SmallCustomerListItem">
<Grid HorizontalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="*"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<WrapPanel HorizontalAlignment="Stretch" Margin="0">
<!--Some content here-->
<TextBlock Text="{Binding Path=LastName}" TextWrapping="Wrap" FontSize="24"/>
<TextBlock Text=", " TextWrapping="Wrap" FontSize="24"/>
<TextBlock Text="{Binding Path=FirstName}" TextWrapping="Wrap" FontSize="24"/>
</WrapPanel>
<ListBox ItemsSource="{Binding Path=PhoneNumbers}" Grid.Column="2" d:DesignWidth="100" d:DesignHeight="50"
Margin="8,0" Background="Transparent" BorderBrush="Transparent" IsHitTestVisible="False" HorizontalAlignment="Stretch"/>
</Grid>
</DataTemplate>
</code></pre>
| [
{
"answer_id": 135741,
"author": "Joel B Fant",
"author_id": 22211,
"author_profile": "https://Stackoverflow.com/users/22211",
"pm_score": 1,
"selected": false,
"text": "<p>The <code>Grid</code> should by default take up the whole width of the <code>ListBox</code> because the default <code>ItemsPanel</code> for it is a <code>VirtualizingStackPanel</code>. I'm assuming that you have <strong>not</strong> changed <code>ListBox.ItemsPanel</code>.</p>\n\n<p>Perhaps if you got rid of the middle <code>ColumnDefinition</code> (the others are default <code>\"*\"</code>), and put <code>HorizontalAlignment=\"Left\"</code> on your <code>WrapPanel</code> and <code>HorizontalAlignment=\"Right\"</code> on the <code>ListBox</code> for phone numbers. You may have to alter that <code>ListBox</code> a bit to get the phone numbers even more right-aligned, such as creating a <code>DataTemplate</code> for them.</p>\n"
},
{
"answer_id": 135750,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 2,
"selected": false,
"text": "<p>Ok, here's what you have:</p>\n\n<p>Column 0: <code>WrapPanel</code><br>\nColumn 1: Nothing<br>\nColumn 2: <code>ListBox</code></p>\n\n<p>It sounds like you want <code>WrapPanel</code> on the left edge, <code>ListBox</code> on the right edge, and space to take up what's left in the middle.</p>\n\n<p>Easiest way to do this is actually to use a <code>DockPanel</code>, not a <code>Grid</code>.</p>\n\n<pre><code><DockPanel>\n <WrapPanel DockPanel.Dock=\"Left\"></WrapPanel>\n <ListBox DockPanel.Dock=\"Right\"></ListBox>\n</DockPanel>\n</code></pre>\n\n<p>This should leave empty space between the <code>WrapPanel</code> and the <code>ListBox</code>.</p>\n"
},
{
"answer_id": 135848,
"author": "Phobis",
"author_id": 19854,
"author_profile": "https://Stackoverflow.com/users/19854",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to use a <code>Grid</code>, then you need to change your <code>ColumnDefinition</code>s to be:</p>\n\n<pre><code> <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"Auto\"/>\n <ColumnDefinition Width=\"*\"/>\n <ColumnDefinition Width=\"Auto\"/>\n </Grid.ColumnDefinitions>\n</code></pre>\n\n<p>If you don't need to use a <code>Grid</code>, then you could use a <code>DockPanel</code>:</p>\n\n<pre><code> <DockPanel>\n <WrapPanel DockPanel.Dock=\"Left\">\n <!--Some content here-->\n <TextBlock Text=\"{Binding Path=LastName}\" TextWrapping=\"Wrap\" FontSize=\"24\"/>\n <TextBlock Text=\", \" TextWrapping=\"Wrap\" FontSize=\"24\"/>\n <TextBlock Text=\"{Binding Path=FirstName}\" TextWrapping=\"Wrap\" FontSize=\"24\"/>\n </WrapPanel>\n <ListBox DockPanel.Dock=\"Right\" ItemsSource=\"{Binding Path=PhoneNumbers}\" \n Margin=\"8,0\" Background=\"Transparent\" BorderBrush=\"Transparent\" IsHitTestVisible=\"False\"/>\n <TextBlock />\n </DockPanel>\n</code></pre>\n\n<p>Notice the <code>TextBlock</code> at the end. Any control with no <code>\"DockPanel.Dock\"</code> defined will fill the remaining space.</p>\n"
},
{
"answer_id": 135951,
"author": "Eric Haskins",
"author_id": 100,
"author_profile": "https://Stackoverflow.com/users/100",
"pm_score": 8,
"selected": true,
"text": "<p>I also had to set:</p>\n\n<pre><code>HorizontalContentAlignment=\"Stretch\"\n</code></pre>\n\n<p>on the containing <code>ListBox</code>.</p>\n"
},
{
"answer_id": 4699138,
"author": "Taeke",
"author_id": 576650,
"author_profile": "https://Stackoverflow.com/users/576650",
"pm_score": 5,
"selected": false,
"text": "<pre><code><Grid.Width>\n <Binding Path=\"ActualWidth\" \n RelativeSource=\"{RelativeSource Mode=FindAncestor, AncestorType={x:Type ScrollContentPresenter}}\" />\n</Grid.Width>\n</code></pre>\n"
},
{
"answer_id": 12820912,
"author": "vancutterromney",
"author_id": 912207,
"author_profile": "https://Stackoverflow.com/users/912207",
"pm_score": 2,
"selected": false,
"text": "<p>Extending Taeke's answer, setting the <code>ScrollViewer.HorizontalScrollBarVisibility=\"Hidden\"</code> for a <code>ListBox</code> allows the child control to take the parent's width and not have the scroll bar show up.</p>\n\n<pre><code><ListBox Width=\"100\" ScrollViewer.HorizontalScrollBarVisibility=\"Hidden\"> \n <Label Content=\"{Binding Path=., Mode=OneWay}\" HorizontalContentAlignment=\"Stretch\" Height=\"30\" Margin=\"-4,0,0,0\" BorderThickness=\"0.5\" BorderBrush=\"Black\" FontFamily=\"Calibri\" >\n <Label.Width>\n <Binding Path=\"Width\" RelativeSource=\"{RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBox}}\" />\n </Label.Width>\n </Label>\n</ListBox >\n</code></pre>\n"
},
{
"answer_id": 40697569,
"author": "BCA",
"author_id": 1628429,
"author_profile": "https://Stackoverflow.com/users/1628429",
"pm_score": 0,
"selected": false,
"text": "<p>Taeke's answer works well, and as per vancutterromney's answer you can disable the horizontal scrollbar to get rid of the annoying size mismatch. However, if you do want the best of both worlds--to remove the scrollbar when it is not needed, but have it automatically enabled when the ListBox becomes too small, you can use the following converter:</p>\n\n<pre><code>/// <summary>\n/// Value converter that adjusts the value of a double according to min and max limiting values, as well as an offset. These values are set by object configuration, handled in XAML resource definition.\n/// </summary>\n[ValueConversion(typeof(double), typeof(double))]\npublic sealed class DoubleLimiterConverter : IValueConverter\n{\n /// <summary>\n /// Minimum value, if set. If not set, there is no minimum limit.\n /// </summary>\n public double? Min { get; set; }\n\n /// <summary>\n /// Maximum value, if set. If not set, there is no minimum limit.\n /// </summary>\n public double? Max { get; set; }\n\n /// <summary>\n /// Offset value to be applied after the limiting is done.\n /// </summary>\n public double Offset { get; set; }\n\n public static double _defaultFailureValue = 0;\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value == null || !(value is double))\n return _defaultFailureValue;\n\n double dValue = (double)value;\n double minimum = Min.HasValue ? Min.Value : double.NegativeInfinity;\n double maximum = Max.HasValue ? Max.Value : double.PositiveInfinity;\n double retVal = dValue.LimitToRange(minimum, maximum) + Offset;\n return retVal;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n}\n</code></pre>\n\n<p>Then define it in XAML according to the desired max/min values, as well an offset to deal with that annoying 2-pixel size mismatch as mentioned in the other answers:</p>\n\n<pre><code><ListBox.Resources>\n <con:DoubleLimiterConverter x:Key=\"conDoubleLimiter\" Min=\"450\" Offset=\"-2\"/>\n</ListBox.Resources>\n</code></pre>\n\n<p>Then use the converter in the Width binding:</p>\n\n<pre><code><Grid.Width>\n <Binding Path=\"ActualWidth\" RelativeSource=\"{RelativeSource Mode=FindAncestor, AncestorType={x:Type ScrollContentPresenter}}\" Converter=\"{StaticResource conDoubleLimiter}\" />\n</Grid.Width>\n</code></pre>\n"
},
{
"answer_id": 44710028,
"author": "Kevin Hilt",
"author_id": 5178913,
"author_profile": "https://Stackoverflow.com/users/5178913",
"pm_score": 0,
"selected": false,
"text": "<p>The method in Taeke's answer forces a horizontal scroll bar. This can be fixed by adding a converter to reduce the grid's width by the width of the vertical scrollbar control.</p>\n\n<pre><code>using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\nusing System.Windows.Markup;\n\nnamespace Converters\n{\n public class ListBoxItemWidthConverter : MarkupExtension, IValueConverter\n {\n private static ListBoxItemWidthConverter _instance;\n\n #region IValueConverter Members\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return System.Convert.ToInt32(value) - SystemParameters.VerticalScrollBarWidth;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n\n #endregion\n\n public override object ProvideValue(IServiceProvider serviceProvider)\n {\n return _instance ?? (_instance = new ListBoxItemWidthConverter());\n }\n }\n}\n</code></pre>\n\n<p>Add a namespace to the root node of your XAML.</p>\n\n<pre><code>xmlns:converters=\"clr-namespace:Converters\"\n</code></pre>\n\n<p>And update the Grid width to use the converter.</p>\n\n<pre><code><Grid.Width>\n <Binding Path=\"ActualWidth\" RelativeSource=\"{RelativeSource Mode=FindAncestor, AncestorType={x:Type ScrollContentPresenter}}\" Converter=\"{converters:ListBoxItemWidthConverter}\"/>\n</Grid.Width>\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/100/"
]
| I have a `ListBox` `DataTemplate` in WPF. I want one item to be tight against the left side of the `ListBox` and another item to be tight against the right side, but I can't figure out how to do this.
So far I have a `Grid` with three columns, the left and right ones have content and the center is a placeholder with it's width set to "\*". Where am I going wrong?
Here is the code:
```
<DataTemplate x:Key="SmallCustomerListItem">
<Grid HorizontalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="*"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<WrapPanel HorizontalAlignment="Stretch" Margin="0">
<!--Some content here-->
<TextBlock Text="{Binding Path=LastName}" TextWrapping="Wrap" FontSize="24"/>
<TextBlock Text=", " TextWrapping="Wrap" FontSize="24"/>
<TextBlock Text="{Binding Path=FirstName}" TextWrapping="Wrap" FontSize="24"/>
</WrapPanel>
<ListBox ItemsSource="{Binding Path=PhoneNumbers}" Grid.Column="2" d:DesignWidth="100" d:DesignHeight="50"
Margin="8,0" Background="Transparent" BorderBrush="Transparent" IsHitTestVisible="False" HorizontalAlignment="Stretch"/>
</Grid>
</DataTemplate>
``` | I also had to set:
```
HorizontalContentAlignment="Stretch"
```
on the containing `ListBox`. |
135,443 | <p>There are a group of private methods in my class, and I need to call one dynamically based on an input value. Both the invoking code and the target methods are in the same instance. The code looks like this:</p>
<pre><code>MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType);
dynMethod.Invoke(this, new object[] { methodParams });
</code></pre>
<p>In this case, <code>GetMethod()</code> will not return private methods. What <code>BindingFlags</code> do I need to supply to <code>GetMethod()</code> so that it can locate private methods?</p>
| [
{
"answer_id": 135455,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 2,
"selected": false,
"text": "<p>I think you can pass it <code>BindingFlags.NonPublic</code> where <em>it</em> is the <code>GetMethod</code> method.</p>\n"
},
{
"answer_id": 135461,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 3,
"selected": false,
"text": "<p>Are you absolutely sure this can't be done through inheritance? Reflection is the very last thing you should look at when solving a problem, it makes refactoring, understanding your code, and any automated analysis more difficult.</p>\n\n<p>It looks like you should just have a DrawItem1, DrawItem2, etc class that override your dynMethod.</p>\n"
},
{
"answer_id": 135482,
"author": "wprl",
"author_id": 17847,
"author_profile": "https://Stackoverflow.com/users/17847",
"pm_score": 10,
"selected": true,
"text": "<p>Simply change your code to use the overloaded <a href=\"http://msdn.microsoft.com/en-us/library/system.type.getmethod.aspx\" rel=\"noreferrer\">version of <code>GetMethod</code></a> that accepts BindingFlags:</p>\n\n<pre><code>MethodInfo dynMethod = this.GetType().GetMethod(\"Draw_\" + itemType, \n BindingFlags.NonPublic | BindingFlags.Instance);\ndynMethod.Invoke(this, new object[] { methodParams });\n</code></pre>\n\n<p>Here's the <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags.aspx\" rel=\"noreferrer\">BindingFlags enumeration documentation</a>.</p>\n"
},
{
"answer_id": 135555,
"author": "Jeromy Irvine",
"author_id": 8223,
"author_profile": "https://Stackoverflow.com/users/8223",
"pm_score": 6,
"selected": false,
"text": "<p><code>BindingFlags.NonPublic</code> will not return any results by itself. As it turns out, combining it with <code>BindingFlags.Instance</code> does the trick.</p>\n\n<pre><code>MethodInfo dynMethod = this.GetType().GetMethod(\"Draw_\" + itemType, \n BindingFlags.NonPublic | BindingFlags.Instance);\n</code></pre>\n"
},
{
"answer_id": 143434,
"author": "Peter Hession",
"author_id": 441,
"author_profile": "https://Stackoverflow.com/users/441",
"pm_score": 2,
"selected": false,
"text": "<p>Could you not just have a different Draw method for each type that you want to Draw? Then call the overloaded Draw method passing in the object of type itemType to be drawn.</p>\n\n<p>Your question does not make it clear whether itemType genuinely refers to objects of differing types.</p>\n"
},
{
"answer_id": 25415496,
"author": "cod3monk3y",
"author_id": 1174169,
"author_profile": "https://Stackoverflow.com/users/1174169",
"pm_score": 6,
"selected": false,
"text": "<p>And if you <em>really</em> want to get yourself in trouble, make it easier to execute by writing an extension method:</p>\n\n<pre><code>static class AccessExtensions\n{\n public static object call(this object o, string methodName, params object[] args)\n {\n var mi = o.GetType ().GetMethod (methodName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance );\n if (mi != null) {\n return mi.Invoke (o, args);\n }\n return null;\n }\n}\n</code></pre>\n\n<p>And usage:</p>\n\n<pre><code> class Counter\n {\n public int count { get; private set; }\n void incr(int value) { count += value; }\n }\n\n [Test]\n public void making_questionable_life_choices()\n {\n Counter c = new Counter ();\n c.call (\"incr\", 2); // \"incr\" is private !\n c.call (\"incr\", 3);\n Assert.AreEqual (5, c.count);\n }\n</code></pre>\n"
},
{
"answer_id": 41529500,
"author": "Owen James",
"author_id": 2736798,
"author_profile": "https://Stackoverflow.com/users/2736798",
"pm_score": 5,
"selected": false,
"text": "<p>Microsoft recently <a href=\"https://blogs.msdn.microsoft.com/dotnet/2012/08/28/evolving-the-reflection-api/\" rel=\"noreferrer\">modified the reflection API</a> rendering most of these answers obsolete. The following should work on modern platforms (including Xamarin.Forms and UWP):</p>\n\n<pre><code>obj.GetType().GetTypeInfo().GetDeclaredMethod(\"MethodName\").Invoke(obj, yourArgsHere);\n</code></pre>\n\n<p>Or as an extension method:</p>\n\n<pre><code>public static object InvokeMethod<T>(this T obj, string methodName, params object[] args)\n{\n var type = typeof(T);\n var method = type.GetTypeInfo().GetDeclaredMethod(methodName);\n return method.Invoke(obj, args);\n}\n</code></pre>\n\n<p>Note:</p>\n\n<ul>\n<li><p>If the desired method is in a superclass of <code>obj</code> the <code>T</code> generic must be explicitly set to the type of the superclass. </p></li>\n<li><p>If the method is asynchronous you can use <code>await (Task) obj.InvokeMethod(…)</code>.</p></li>\n</ul>\n"
},
{
"answer_id": 43509885,
"author": "Fab",
"author_id": 5328150,
"author_profile": "https://Stackoverflow.com/users/5328150",
"pm_score": 4,
"selected": false,
"text": "<h3>Reflection especially on private members is wrong</h3>\n\n<ul>\n<li><strong>Reflection breaks type safety.</strong> You can try to invoke a method that doesn't exists (anymore), or with the wrong parameters, or with too much parameters, or not enough... or even in the wrong order (this one my favourite :) ). By the way return type could change as well.</li>\n<li><strong>Reflection is slow.</strong></li>\n</ul>\n\n<p><strong>Private members reflection breaks <a href=\"https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)\" rel=\"noreferrer\">encapsulation</a> principle</strong> and thus exposing your code to the following :</p>\n\n<ul>\n<li><strong>Increase complexity</strong> of your code because it has to handle the inner behavior of the classes. What is hidden should remain hidden.</li>\n<li><strong>Makes your code easy to break</strong> as it will compile but won't run if the method changed its name.</li>\n<li><strong>Makes the private code easy to break</strong> because if it is private it is not intended to be called that way. Maybe the private method expects some inner state before being called.</li>\n</ul>\n\n<h3>What if I must do it anyway ?</h3>\n\n<p>There are so cases, when you depend on a third party or you need some api not exposed, you have to do some reflection. Some also use it to test some classes they own but that they don't want to change the interface to give access to the inner members just for tests.</p>\n\n<h3>If you do it, do it right</h3>\n\n<ul>\n<li>Mitigate the easy to break:</li>\n</ul>\n\n<p>To mitigate the easy to break issue, the best is to detect any potential break by testing in unit tests that would run in a continuous integration build or such. Of course, it means you always use the same assembly (which contains the private members). If you use a dynamic load and reflection, you like play with fire, but you can always catch the Exception that the call may produce.</p>\n\n<ul>\n<li>Mitigate the slowness of reflection:</li>\n</ul>\n\n<p>In the recent versions of .Net Framework, CreateDelegate beat by a factor 50 the MethodInfo invoke: </p>\n\n<pre><code>// The following should be done once since this does some reflection\nvar method = this.GetType().GetMethod(\"Draw_\" + itemType, \n BindingFlags.NonPublic | BindingFlags.Instance);\n\n// Here we create a Func that targets the instance of type which has the \n// Draw_ItemType method\nvar draw = (Func<TInput, Output[]>)_method.CreateDelegate(\n typeof(Func<TInput, TOutput[]>), this);\n</code></pre>\n\n<p><code>draw</code> calls will be around 50x faster than <code>MethodInfo.Invoke</code>\nuse <code>draw</code> as a standard <code>Func</code> like that:</p>\n\n<pre><code>var res = draw(methodParams);\n</code></pre>\n\n<p>Check this <a href=\"https://stackoverflow.com/questions/31859016/is-the-use-of-dynamic-considered-a-bad-practice/32817143#32817143\">post of mine</a> to see benchmark on different method invocations</p>\n"
},
{
"answer_id": 48680544,
"author": "Maksim Shamihulau",
"author_id": 836723,
"author_profile": "https://Stackoverflow.com/users/836723",
"pm_score": 2,
"selected": false,
"text": "<p>Invokes any method despite its protection level on object instance. Enjoy!</p>\n\n<pre><code>public static object InvokeMethod(object obj, string methodName, params object[] methodParams)\n{\n var methodParamTypes = methodParams?.Select(p => p.GetType()).ToArray() ?? new Type[] { };\n var bindingFlags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static;\n MethodInfo method = null;\n var type = obj.GetType();\n while (method == null && type != null)\n {\n method = type.GetMethod(methodName, bindingFlags, Type.DefaultBinder, methodParamTypes, null);\n type = type.BaseType;\n }\n\n return method?.Invoke(obj, methodParams);\n}\n</code></pre>\n"
},
{
"answer_id": 50480209,
"author": "T.S.",
"author_id": 1704458,
"author_profile": "https://Stackoverflow.com/users/1704458",
"pm_score": 0,
"selected": false,
"text": "<p>Read this (supplementary) answer (that is sometimes the answer) to understand where this is going and <strong>why</strong> some people in this thread complain that <em>\"it is still not working\"</em></p>\n\n<p><a href=\"https://stackoverflow.com/a/25415496/1704458\">I wrote exactly same code as one of the answers here</a>. But I still had an issue. I placed break point on </p>\n\n<pre><code>var mi = o.GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance );\n</code></pre>\n\n<p>It executed but <code>mi == null</code></p>\n\n<p>And it continued behavior like this until I did \"re-build\" on all projects involved. I was unit testing one assembly while the reflection method was sitting in third assembly. It was totally confusing but I used Immediate Window to discover methods and I found that a private method I tried to unit test had old name (I renamed it). This told me that old assembly or PDB is still out there even if unit test project builds - for some reason project it tests didn't built. \"rebuild\" worked</p>\n"
},
{
"answer_id": 67282411,
"author": "urglas",
"author_id": 15775993,
"author_profile": "https://Stackoverflow.com/users/15775993",
"pm_score": 1,
"selected": false,
"text": "<p>It should be noted that calling from a derived class can be problematic.</p>\n<p>Error prone:</p>\n<pre><code>this.GetType().GetMethod("PrivateTestMethod", BindingFlags.Instance | BindingFlags.NonPublic)\n</code></pre>\n<p>Correct:</p>\n<pre><code>typeof(CurrentClass).GetMethod("PrivateTestMethod", BindingFlags.Instance | BindingFlags.NonPublic)\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8223/"
]
| There are a group of private methods in my class, and I need to call one dynamically based on an input value. Both the invoking code and the target methods are in the same instance. The code looks like this:
```
MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType);
dynMethod.Invoke(this, new object[] { methodParams });
```
In this case, `GetMethod()` will not return private methods. What `BindingFlags` do I need to supply to `GetMethod()` so that it can locate private methods? | Simply change your code to use the overloaded [version of `GetMethod`](http://msdn.microsoft.com/en-us/library/system.type.getmethod.aspx) that accepts BindingFlags:
```
MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType,
BindingFlags.NonPublic | BindingFlags.Instance);
dynMethod.Invoke(this, new object[] { methodParams });
```
Here's the [BindingFlags enumeration documentation](http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags.aspx). |
135,445 | <p>I tried to use DriveInfo.IsReady, but it returns false if an unformatted floppy is in the drive.</p>
| [
{
"answer_id": 135479,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 1,
"selected": false,
"text": "<p>Simply speaking: you can't. Floppy drives don't support that.</p>\n"
},
{
"answer_id": 135597,
"author": "bhinks",
"author_id": 5877,
"author_profile": "https://Stackoverflow.com/users/5877",
"pm_score": 0,
"selected": false,
"text": "<p>what about <a href=\"http://msdn.microsoft.com/en-us/library/system.io.drivenotfoundexception.aspx\" rel=\"nofollow noreferrer\">DriveNotFoundException</a>?</p>\n\n<p>I don't have a floppy drive in the computer I'm on currently, so I can't test it. This exception is thrown when the drive is unavailable, which is a condition that I believe would be met when the floppy drive is empty.</p>\n"
},
{
"answer_id": 135714,
"author": "Kevin Fairchild",
"author_id": 3743,
"author_profile": "https://Stackoverflow.com/users/3743",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps you can look at the disk management APIs... That should be able to tell you the capacity of the disk (whether formatted or not)...</p>\n\n<p>And if there's no capacity, there's no floppy inserted...</p>\n"
},
{
"answer_id": 135756,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<p>Trap both DiscNotReady (For no disk in the drive), and write Exceptions (For invalid file system/not formatted).</p>\n"
},
{
"answer_id": 135763,
"author": "Jonas Engström",
"author_id": 7634,
"author_profile": "https://Stackoverflow.com/users/7634",
"pm_score": 3,
"selected": true,
"text": "<p>You can always try to read a sector from the floppy and see if it succeeds or not.</p>\n\n<p>I have no clue how to do it in .NET, but here is the C/C++ equivalent.</p>\n\n<pre><code>SetLastError(0);\nHANDLE h = CreateFile(\"\\\\\\\\.\\\\A:\", ...);\nif (!ReadFile(h, buf, 512, &bytes_read, 0))\n{\n DWORD err = GetLastError();\n}\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx\" rel=\"nofollow noreferrer\">CreateFile</a>, <a href=\"http://msdn.microsoft.com/en-us/library/aa365467(VS.85).aspx\" rel=\"nofollow noreferrer\">ReadFile</a></p>\n"
},
{
"answer_id": 136211,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Jonas stuff worked:</p>\n\n<pre><code>bool MyDll::Class1::HasFloppy( wchar_t driveLetter ) {\nwchar_t path[] = L\"\\\\\\\\.\\\\A:\";\npath[ 4 ] = driveLetter;\n\nSetLastError( 0 );\nHANDLE drive = CreateFile( path, //__in LPCTSTR lpFileName,\n GENERIC_READ, //__in DWORD dwDesiredAccess,\n 0, //__in DWORD dwShareMode,\n 0, //__in_opt LPSECURITY_ATTRIBUTES lpSecurityAttributes,\n OPEN_EXISTING, //__in DWORD dwCreationDisposition,\n 0, //__in DWORD dwFlagsAndAttributes,\n 0 //__in_opt HANDLE hTemplateFile\n);\n\nDWORD bytes_read;\nchar buf[ 512 ];\nDWORD err( 0 );\nif( !ReadFile( drive, buf, 512, &bytes_read, 0 ) )\n err = GetLastError();\n\nCloseHandle( drive );\nreturn err != ERROR_NOT_READY;\n</code></pre>\n\n<p>}</p>\n"
},
{
"answer_id": 1225906,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If you insert an unformatted floppy disk in your floppy drive, the purpose would normally be to use that floppy drive with that floppy disk. The first step is then logically to format that floppy disk.</p>\n\n<p>So, if you detect a non-ready floppy drive, you could try to format the disk, and if that succeeds, your floppy drive should become ready with a newly formatted floppy in it.\nIf the format of the unready floppy drive fails, then there is no floppy disk in it, or the floppy disk in it is faulty. Then you can show a message to insert a floppy disk in the drive.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I tried to use DriveInfo.IsReady, but it returns false if an unformatted floppy is in the drive. | You can always try to read a sector from the floppy and see if it succeeds or not.
I have no clue how to do it in .NET, but here is the C/C++ equivalent.
```
SetLastError(0);
HANDLE h = CreateFile("\\\\.\\A:", ...);
if (!ReadFile(h, buf, 512, &bytes_read, 0))
{
DWORD err = GetLastError();
}
```
[CreateFile](http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx), [ReadFile](http://msdn.microsoft.com/en-us/library/aa365467(VS.85).aspx) |
135,448 | <p>How do I check if an object has a specific property in JavaScript?</p>
<p>Consider:</p>
<pre><code>x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
</code></pre>
<p>Is that the best way to do it?</p>
| [
{
"answer_id": 135466,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 4,
"selected": false,
"text": "<p>Yes it is :) I think you can also do <code>Object.prototype.hasOwnProperty.call(x, 'key')</code> which should also work if <code>x</code> has a property called <code>hasOwnProperty</code> :)</p>\n\n<p>But that tests for own properties. If you want to check if it has an property that may also be inhered you can use <code>typeof x.foo != 'undefined'</code>.</p>\n"
},
{
"answer_id": 135475,
"author": "enobrev",
"author_id": 14651,
"author_profile": "https://Stackoverflow.com/users/14651",
"pm_score": 6,
"selected": false,
"text": "<pre><code>if (x.key !== undefined)\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/users/19990/armin-ronacher\">Armin Ronacher</a> seems to have already <a href=\"https://stackoverflow.com/questions/135448/how-do-i-check-to-see-if-an-object-has-an-attribute-in-javascript#135466\">beat me to it</a>, but:</p>\n\n<pre><code>Object.prototype.hasOwnProperty = function(property) {\n return this[property] !== undefined;\n};\n\nx = {'key': 1};\n\nif (x.hasOwnProperty('key')) {\n alert('have key!');\n}\n\nif (!x.hasOwnProperty('bar')) {\n alert('no bar!');\n}\n</code></pre>\n\n<p>A safer, but slower solution, <a href=\"https://stackoverflow.com/questions/135448/how-do-i-check-to-see-if-an-object-has-an-attribute-in-javascript#135568\">as pointed out</a> by <a href=\"https://stackoverflow.com/users/1968/konrad-rudolph\">Konrad Rudolph</a> and <a href=\"https://stackoverflow.com/users/19990/armin-ronacher\">Armin Ronacher</a> would be:</p>\n\n<pre><code>Object.prototype.hasOwnProperty = function(property) {\n return typeof this[property] !== 'undefined';\n};\n</code></pre>\n"
},
{
"answer_id": 135514,
"author": "sheats",
"author_id": 4915,
"author_profile": "https://Stackoverflow.com/users/4915",
"pm_score": 4,
"selected": false,
"text": "<p>OK, it looks like I had the right answer unless if you don't want inherited properties:</p>\n\n<pre><code>if (x.hasOwnProperty('key'))\n</code></pre>\n\n<p>Here are some other options to include inherited properties:</p>\n\n<pre><code>if (x.key) // Quick and dirty, but it does the same thing as below.\n\nif (x.key !== undefined)\n</code></pre>\n"
},
{
"answer_id": 135517,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<pre class=\"lang-js prettyprint-override\"><code>if(x.hasOwnProperty("key")){\n // …\n}\n</code></pre>\n<p>because</p>\n<pre class=\"lang-js prettyprint-override\"><code>if(x.key){\n // …\n}\n</code></pre>\n<p>fails if <code>x.key</code> is falsy (for example, <code>x.key === ""</code>).</p>\n"
},
{
"answer_id": 135568,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 7,
"selected": false,
"text": "<p><strong>Note</strong>: the following is nowadays largely obsolete thanks to strict mode, and <code>hasOwnProperty</code>. The correct solution is to use strict mode and to check for the presence of a property using <code>obj.hasOwnProperty</code>. This answer <em>predates</em> both these things, at least as widely implemented (yes, it is that old). Take the following as a historical note.</p>\n\n<hr>\n\n<p>Bear in mind that <code>undefined</code> is (unfortunately) <em>not</em> a reserved word in JavaScript if you’re not using strict mode. Therefore, someone (someone else, obviously) could have the grand idea of redefining it, breaking your code.</p>\n\n<p>A more robust method is therefore the following:</p>\n\n<pre><code>if (typeof(x.attribute) !== 'undefined')\n</code></pre>\n\n<p>On the flip side, this method is much more verbose and also slower. :-/</p>\n\n<p>A common alternative is to ensure that <code>undefined</code> is <em>actually</em> undefined, e.g. by putting the code into a function which accepts an additional parameter, called <code>undefined</code>, that isn’t passed a value. To ensure that it’s not passed a value, you could just call it yourself immediately, e.g.:</p>\n\n<pre><code>(function (undefined) {\n … your code …\n if (x.attribute !== undefined)\n … mode code …\n})();\n</code></pre>\n"
},
{
"answer_id": 136411,
"author": "John Resig",
"author_id": 6524,
"author_profile": "https://Stackoverflow.com/users/6524",
"pm_score": 12,
"selected": true,
"text": "<h2>2022 UPDATE</h2>\n<h2><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn\" rel=\"noreferrer\"><code>Object.hasOwn()</code></a></h2>\n<blockquote>\n<p><code>Object.hasOwn()</code> is recommended over <code>Object.hasOwnProperty()</code> because it works for objects created using <code>Object.create(null)</code> and with objects that have overridden the inherited <code>hasOwnProperty()</code> method. While it is possible to workaround these problems by calling <code>Object.prototype.hasOwnProperty()</code> on an external object, <code>Object.hasOwn()</code> is more intuitive.</p>\n</blockquote>\n<h4>Example</h4>\n<pre class=\"lang-js prettyprint-override\"><code>const object1 = {\n prop: 'exists'\n};\n\nconsole.log(Object.hasOwn(object1, 'prop'));\n// expected output: true\n</code></pre>\n<hr />\n<h2>Original answer</h2>\n<p>I'm really confused by the answers that have been given - most of them are just outright incorrect. Of course you can have object properties that have undefined, null, or false values. So simply reducing the property check to <code>typeof this[property]</code> or, even worse, <code>x.key</code> will give you completely misleading results.</p>\n<p>It depends on what you're looking for. If you want to know if an object physically contains a property (and it is not coming from somewhere up on the prototype chain) then <code>object.hasOwnProperty</code> is the way to go. All modern browsers support it. (It was missing in older versions of Safari - 2.0.1 and older - but those versions of the browser are rarely used any more.)</p>\n<p>If what you're looking for is if an object has a property on it that is iterable (when you iterate over the properties of the object, it will appear) then doing: <code>prop in object</code> will give you your desired effect.</p>\n<p>Since using <code>hasOwnProperty</code> is probably what you want, and considering that you may want a fallback method, I present to you the following solution:</p>\n<pre><code>var obj = {\n a: undefined,\n b: null,\n c: false\n};\n\n// a, b, c all found\nfor ( var prop in obj ) {\n document.writeln( "Object1: " + prop );\n}\n\nfunction Class(){\n this.a = undefined;\n this.b = null;\n this.c = false;\n}\n\nClass.prototype = {\n a: undefined,\n b: true,\n c: true,\n d: true,\n e: true\n};\n\nvar obj2 = new Class();\n\n// a, b, c, d, e found\nfor ( var prop in obj2 ) {\n document.writeln( "Object2: " + prop );\n}\n\nfunction hasOwnProperty(obj, prop) {\n var proto = obj.__proto__ || obj.constructor.prototype;\n return (prop in obj) &&\n (!(prop in proto) || proto[prop] !== obj[prop]);\n}\n\nif ( Object.prototype.hasOwnProperty ) {\n var hasOwnProperty = function(obj, prop) {\n return obj.hasOwnProperty(prop);\n }\n}\n\n// a, b, c found in modern browsers\n// b, c found in Safari 2.0.1 and older\nfor ( var prop in obj2 ) {\n if ( hasOwnProperty(obj2, prop) ) {\n document.writeln( "Object2 w/ hasOwn: " + prop );\n }\n}\n</code></pre>\n<p>The above is a working, cross-browser, solution to <code>hasOwnProperty()</code>, with one caveat: It is unable to distinguish between cases where an identical property is on the prototype and on the instance - it just assumes that it's coming from the prototype. You could shift it to be more lenient or strict, based upon your situation, but at the very least this should be more helpful.</p>\n"
},
{
"answer_id": 138428,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 5,
"selected": false,
"text": "<p>Let's cut through some confusion here. First, let's simplify by assuming <code>hasOwnProperty</code> already exists; this is true of the vast majority of current browsers in use.</p>\n\n<p><code>hasOwnProperty</code> returns true if the attribute name that is passed to it has been added to the object. It is entirely independent of the actual value assigned to it which may be exactly <code>undefined</code>.</p>\n\n<p><strong>Hence:</strong></p>\n\n<pre><code>var o = {}\no.x = undefined\n\nvar a = o.hasOwnProperty('x') // a is true\nvar b = o.x === undefined // b is also true\n</code></pre>\n\n<p><strong>However:</strong></p>\n\n<pre><code>var o = {}\n\nvar a = o.hasOwnProperty('x') // a is now false\nvar b = o.x === undefined // b is still true\n</code></pre>\n\n<p>The problem is what happens when an object in the prototype chain has an attribute with the value of undefined? <code>hasOwnProperty</code> will be false for it, and so will <code>!== undefined</code>. Yet, <code>for..in</code> will still list it in the enumeration.</p>\n\n<p>The bottom line is there is no cross-browser way (since Internet Explorer doesn't expose <code>__prototype__</code>) to determine that a specific identifier has not been attached to an object or anything in its prototype chain.</p>\n"
},
{
"answer_id": 11315692,
"author": "Brian M. Hunt",
"author_id": 19212,
"author_profile": "https://Stackoverflow.com/users/19212",
"pm_score": 8,
"selected": false,
"text": "<p>With <a href=\"http://underscorejs.org/\" rel=\"noreferrer\">Underscore.js</a> or (<a href=\"https://stackoverflow.com/questions/13789618/differences-between-lodash-and-underscore-js\">even better</a>) <a href=\"http://lodash.com/\" rel=\"noreferrer\">Lodash</a>:</p>\n<pre><code>_.has(x, 'key');\n</code></pre>\n<p>Which calls <code>Object.prototype.hasOwnProperty</code>, but (a) is shorter to type, and (b) uses "a safe reference to <code>hasOwnProperty</code>" (i.e. it works even if <code>hasOwnProperty</code> is overwritten).</p>\n<p>In particular, Lodash defines <code>_.has</code> as:</p>\n<pre><code>function has(object, key) {\n return object ? hasOwnProperty.call(object, key) : false;\n}\n// hasOwnProperty = Object.prototype.hasOwnProperty\n</code></pre>\n"
},
{
"answer_id": 14664748,
"author": "Whisher",
"author_id": 356380,
"author_profile": "https://Stackoverflow.com/users/356380",
"pm_score": 8,
"selected": false,
"text": "<p>Use:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var x = {\n 'key': 1\n};\n\nif ('key' in x) {\n console.log('has');\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 16674373,
"author": "Gerard ONeill",
"author_id": 1331672,
"author_profile": "https://Stackoverflow.com/users/1331672",
"pm_score": 5,
"selected": false,
"text": "<p>If you are searching for a property, then <em>"no"</em>. You want:</p>\n<pre><code>if ('prop' in obj) { }\n</code></pre>\n<p>In general, you should not care whether or not the property comes from the prototype or the object.</p>\n<p>However, because you used 'key' in your sample code, it looks like you are treating the object as a hash, in which case your answer would make sense. All of the hashes keys would be properties in the object, and you avoid the extra properties contributed by the prototype.</p>\n<p><a href=\"https://stackoverflow.com/questions/135448/how-do-i-check-if-an-object-has-a-specific-property-in-javascript/136411#136411\">John Resig's answer</a> was very comprehensive, but I thought it wasn't clear. Especially with when to use "'prop' in obj".</p>\n"
},
{
"answer_id": 22740939,
"author": "goonerify",
"author_id": 1445318,
"author_profile": "https://Stackoverflow.com/users/1445318",
"pm_score": 5,
"selected": false,
"text": "<p>Considering the following object in Javascript</p>\n<pre><code>const x = {key: 1};\n</code></pre>\n<p>You can use the <code>in</code> operator to check if the property exists on an object:</p>\n<pre><code>console.log("key" in x);\n</code></pre>\n<p>You can also loop through all the properties of the object using a <code>for - in</code> loop, and then check for the specific property:</p>\n<pre><code>for (const prop in x) {\n if (prop === "key") {\n //Do something\n }\n}\n</code></pre>\n<p>You must consider if this object property is enumerable or not, because non-enumerable properties will not show up in a <code>for-in</code> loop. Also, if the enumerable property is shadowing a non-enumerable property of the prototype, it will not show up in <a href=\"http://en.wikipedia.org/wiki/Internet_Explorer_8\" rel=\"noreferrer\">Internet Explorer 8</a> and earlier.</p>\n<p>If you’d like a list of all instance properties, whether enumerable or not, you can use</p>\n<pre><code>Object.getOwnPropertyNames(x);\n</code></pre>\n<p>This will return an array of names of all properties that exist on an object.</p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect\" rel=\"noreferrer\">Reflections</a> provide methods that can be used to interact with Javascript objects. The static <code>Reflect.has()</code> method works like the in operator as a function.</p>\n<pre><code>console.log(Reflect.has(x, 'key'));\n// expected output: true\n\nconsole.log(Reflect.has(x, 'key2'));\n// expected output: false\n\nconsole.log(Reflect.has(object1, 'toString'));\n// expected output: true\n</code></pre>\n<p>Finally, you can use the typeof operator to directly check the data type of the object property:</p>\n<pre><code>if (typeof x.key === "undefined") {\n console.log("undefined");\n}\n</code></pre>\n<p>If the property does not exist on the object, it will return the string undefined. Else it will return the appropriate property type. However, note that this is not always a valid way of checking if an object has a property or not, because you could have a property that is set to undefined, in which case, using <code>typeof x.key</code> would still return true (even though the key is still in the object).</p>\n<p>Similarly, you can check if a property exists by comparing directly to the <code>undefined</code> Javascript property</p>\n<pre><code>if (x.key === undefined) {\n console.log("undefined");\n}\n</code></pre>\n<p>This should work unless key was specifically set to <code>undefined</code> on the x object</p>\n"
},
{
"answer_id": 30533729,
"author": "Jamie Hutber",
"author_id": 240363,
"author_profile": "https://Stackoverflow.com/users/240363",
"pm_score": 3,
"selected": false,
"text": "<p>Another relatively simple way is using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys\" rel=\"nofollow noreferrer\"><code>Object.keys</code></a>. This returns an <code>array</code> which means you get all of the features of an array.</p>\n<pre><code>var noInfo = {};\nvar info = {something: 'data'};\n\nObject.keys(noInfo).length //returns 0 or false\nObject.keys(info).length //returns 1 or true\n</code></pre>\n<p>Although we are in a world with great browser support. Because this question is so old I thought I'd add this:\nThis is safe to use as of <a href=\"http://kangax.github.io/compat-table/es5/#Object.keys\" rel=\"nofollow noreferrer\">JavaScript v1.8.5</a>.</p>\n"
},
{
"answer_id": 32767522,
"author": "rogopag",
"author_id": 355760,
"author_profile": "https://Stackoverflow.com/users/355760",
"pm_score": 3,
"selected": false,
"text": "<p>hasOwnProperty <em>"can be used to determine whether an object has the specified property as a direct property of that object; <strong>unlike the in operator</strong>, this method does not check down the object's prototype chain."</em></p>\n<p>So most probably, for what seems by your question, you don't want to use hasOwnProperty, which determines if the property exists as attached <strong>directly to the object itself</strong>,.</p>\n<p>If you want to determine if the property exists in the prototype chain, you may want to use it like:</p>\n<pre><code>if (prop in object) { // Do something }\n</code></pre>\n"
},
{
"answer_id": 38332171,
"author": "arkod",
"author_id": 1506301,
"author_profile": "https://Stackoverflow.com/users/1506301",
"pm_score": 2,
"selected": false,
"text": "<p>Here is another option for a specific case. :)</p>\n<p>If you want to test for a member on an object and want to know if it has been set to something other than:</p>\n<ul>\n<li>''</li>\n<li>false</li>\n<li>null</li>\n<li>undefined</li>\n<li>0\n...</li>\n</ul>\n<p>then you can use:</p>\n<pre><code>var foo = {};\nfoo.bar = "Yes, this is a proper value!";\nif (!!foo.bar) {\n // member is set, do something\n}\n</code></pre>\n"
},
{
"answer_id": 40266120,
"author": "Wilt",
"author_id": 1697459,
"author_profile": "https://Stackoverflow.com/users/1697459",
"pm_score": 4,
"selected": false,
"text": "<p>You can also use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect\" rel=\"noreferrer\">the ES6 <code>Reflect</code> object</a>:</p>\n\n<pre><code>x = {'key': 1};\nReflect.has( x, 'key'); // returns true\n</code></pre>\n\n<p>Documentation on MDN for <code>Reflect.has</code> can be found <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/has\" rel=\"noreferrer\"><strong>here</strong></a>.</p>\n\n<blockquote>\n <p>The static <code>Reflect.has()</code> method works like the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in\" rel=\"noreferrer\">in operator</a> as a function.</p>\n</blockquote>\n"
},
{
"answer_id": 41184688,
"author": "davidhadas",
"author_id": 1931538,
"author_profile": "https://Stackoverflow.com/users/1931538",
"pm_score": 5,
"selected": false,
"text": "<p>For testing simple objects, use:</p>\n<pre><code>if (obj[x] !== undefined)\n</code></pre>\n<p>If you don't know what object type it is, use:</p>\n<pre><code>if (obj.hasOwnProperty(x))\n</code></pre>\n<p>All other options are slower...</p>\n<h3>Details</h3>\n<p>A performance evaluation of 100,000,000 cycles under Node.js to the five options suggested by others here:</p>\n<pre><code>function hasKey1(k,o) { return (x in obj); }\nfunction hasKey2(k,o) { return (obj[x]); }\nfunction hasKey3(k,o) { return (obj[x] !== undefined); }\nfunction hasKey4(k,o) { return (typeof(obj[x]) !== 'undefined'); }\nfunction hasKey5(k,o) { return (obj.hasOwnProperty(x)); }\n</code></pre>\n<p>The evaluation tells us that unless we specifically want to check the object's prototype chain as well as the object itself, <strong>we should not use the common form</strong>:</p>\n<pre><code>if (X in Obj)...\n</code></pre>\n<p><strong>It is between 2 to 6 times slower depending on the use case</strong></p>\n<pre><code>hasKey1 execution time: 4.51 s\nhasKey2 execution time: 0.90 s\nhasKey3 execution time: 0.76 s\nhasKey4 execution time: 0.93 s\nhasKey5 execution time: 2.15 s\n</code></pre>\n<p>Bottom line, if your Obj is not necessarily a simple object and you wish to avoid checking the object's prototype chain and to ensure x is owned by Obj directly, use <code>if (obj.hasOwnProperty(x))...</code>.</p>\n<p>Otherwise, when using a simple object and not being worried about the object's prototype chain, using <code>if (typeof(obj[x]) !== 'undefined')...</code> is the safest and fastest way.</p>\n<p>If you use a simple object as a hash table and never do anything kinky, I would use <code>if (obj[x])...</code> as I find it much more readable.</p>\n"
},
{
"answer_id": 41220962,
"author": "Harm",
"author_id": 882899,
"author_profile": "https://Stackoverflow.com/users/882899",
"pm_score": 2,
"selected": false,
"text": "<p>An ECMAScript 6 solution with reflection. Create a wrapper like:</p>\n<pre><code>/**\nGets an argument from array or object.\nThe possible outcome:\n- If the key exists the value is returned.\n- If no key exists the default value is returned.\n- If no default value is specified an empty string is returned.\n@param obj The object or array to be searched.\n@param key The name of the property or key.\n@param defVal Optional default version of the command-line parameter [default ""]\n@return The default value in case of an error else the found parameter.\n*/\nfunction getSafeReflectArg( obj, key, defVal) {\n "use strict";\n var retVal = (typeof defVal === 'undefined' ? "" : defVal);\n if ( Reflect.has( obj, key) ) {\n return Reflect.get( obj, key);\n }\n return retVal;\n} // getSafeReflectArg\n</code></pre>\n"
},
{
"answer_id": 46221139,
"author": "John Anisere",
"author_id": 8581214,
"author_profile": "https://Stackoverflow.com/users/8581214",
"pm_score": 1,
"selected": false,
"text": "<p>You need to use the method <code>object.hasOwnProperty(property)</code>. It returns true if the object has the property and false if the object doesn't.</p>\n"
},
{
"answer_id": 47175373,
"author": "vikram jeet singh",
"author_id": 4119501,
"author_profile": "https://Stackoverflow.com/users/4119501",
"pm_score": 2,
"selected": false,
"text": "<p>There is a method, "hasOwnProperty", that exists on an object, but it's not recommended to call this method directly, because it might be sometimes that the object is null or some property exist on the object like: <code>{ hasOwnProperty: false }</code></p>\n<p>So a better way would be:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// Good\nvar obj = {\"bar\": \"here bar desc\"}\nconsole.log(Object.prototype.hasOwnProperty.call(obj, \"bar\"));\n\n// Best\nconst has = Object.prototype.hasOwnProperty; // Cache the lookup once, in module scope.\nconsole.log(has.call(obj, \"bar\"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 49899370,
"author": "Abdullah Danyal",
"author_id": 7909857,
"author_profile": "https://Stackoverflow.com/users/7909857",
"pm_score": 4,
"selected": false,
"text": "<p>Do not do this <code>object.hasOwnProperty(key))</code>. It's really bad because these methods may be shadowed by properties on the object in question - consider <code>{ hasOwnProperty: false }</code> - or, the object may be a null object <code>(Object.create(null))</code>.</p>\n<p>The best way is to do <code>Object.prototype.hasOwnProperty.call(object, key)</code> or:</p>\n<pre><code>const has = Object.prototype.hasOwnProperty; // Cache the lookup once, in module scope.\nconsole.log(has.call(object, key));\n/* Or */\nimport has from 'has'; // https://www.npmjs.com/package/has\nconsole.log(has(object, key));\n</code></pre>\n"
},
{
"answer_id": 52170045,
"author": "Alex",
"author_id": 2732012,
"author_profile": "https://Stackoverflow.com/users/2732012",
"pm_score": 0,
"selected": false,
"text": "<p>Don't over-complicate things when you can do:</p>\n<pre><code>var isProperty = (objectname.keyname || "") ? true : false;\n</code></pre>\n<p>It Is simple and clear for most cases...</p>\n"
},
{
"answer_id": 54196605,
"author": "Komal Bansal",
"author_id": 10150695,
"author_profile": "https://Stackoverflow.com/users/10150695",
"pm_score": 3,
"selected": false,
"text": "<p>You can use the following approaches-</p>\n<pre><code>var obj = {a:1}\nconsole.log('a' in obj) // 1\nconsole.log(obj.hasOwnProperty('a')) // 2\nconsole.log(Boolean(obj.a)) // 3\n</code></pre>\n<p>The difference between the following approaches are as follows-</p>\n<ol>\n<li>In the first and third approach we are not just searching in object but its prototypal chain too. If the object does not have the property, but the property is present in its prototype chain it is going to give true.</li>\n</ol>\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 obj = {\n a: 2,\n __proto__ : {b: 2}\n}\n\nconsole.log('b' in obj)\nconsole.log(Boolean(obj.b))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<ol start=\"2\">\n<li>The second approach will check only for its own properties. Example -</li>\n</ol>\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 obj = {\n a: 2,\n __proto__ : {b: 2}\n}\n\nconsole.log(obj.hasOwnProperty('b'))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<ol start=\"3\">\n<li>The difference between the first and the third is if there is a property which has value undefined the third approach is going to give false while first will give true.</li>\n</ol>\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 obj = {\n b : undefined\n}\n\nconsole.log(Boolean(obj.b))\nconsole.log('b' in obj);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 62774235,
"author": "Ntwari Clarance Liberiste",
"author_id": 11698819,
"author_profile": "https://Stackoverflow.com/users/11698819",
"pm_score": 3,
"selected": false,
"text": "<p>JavaScript is now evolving and growing as it now has good and even efficient ways to check it.</p>\n<p>Here are some easy ways to check if <strong>object has a particular property</strong>:</p>\n<ol>\n<li><strong>Using <code>hasOwnProperty()</code></strong></li>\n</ol>\n<pre class=\"lang-js prettyprint-override\"><code>const hero = {\n name: 'Batman'\n};\n\nhero.hasOwnProperty('name'); // => true\nhero.hasOwnProperty('realName'); // => false\n</code></pre>\n<ol start=\"2\">\n<li><strong>Using keyword/operator <code>in</code></strong></li>\n</ol>\n<pre class=\"lang-js prettyprint-override\"><code>const hero = {\n name: 'Batman'\n};\n\n'name' in hero; // => true\n'realName' in hero; // => false\n</code></pre>\n<ol start=\"3\">\n<li><strong>Comparing with <code>undefined</code> keyword</strong></li>\n</ol>\n<pre class=\"lang-js prettyprint-override\"><code>const hero = {\n name: 'Batman'\n};\n\nhero.name; // => 'Batman'\nhero.realName; // => undefined\n\n// So consider this\nhero.realName == undefined // => true (which means property does not exists in object)\nhero.name == undefined // => false (which means that property exists in object)\n</code></pre>\n<p>For more information, check <a href=\"https://dmitripavlutin.com/check-if-object-has-property-javascript/#:%7E:text=The%20first%20way%20is%20to,own%20properties%20of%20the%20object.\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 65343749,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 2,
"selected": false,
"text": "<h1>Performance</h1>\n<p>Today 2020.12.17 I perform tests on MacOs HighSierra 10.13.6 on Chrome v87, Safari v13.1.2 and Firefox v83 for chosen solutions.</p>\n<h2>Results</h2>\n<p>I compare only solutions A-F because they give valid result for all cased used in snippet in details section. For all browsers</p>\n<ul>\n<li>solution based on <code>in</code> (A) is fast or fastest</li>\n<li>solution (E) is fastest for chrome for big objects and fastest for firefox for small arrays if key not exists</li>\n<li>solution (F) is fastest (~ >10x than other solutions) for small arrays</li>\n<li>solutions (D,E) are quite fast</li>\n<li>solution based on losash <code>has</code> (B) is slowest</li>\n</ul>\n<p><a href=\"https://i.stack.imgur.com/dmfF0.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dmfF0.png\" alt=\"enter image description here\" /></a></p>\n<h2>Details</h2>\n<p>I perform 4 tests cases:</p>\n<ul>\n<li>when object has 10 fields and searched key exists - you can run it <a href=\"https://jsbench.me/0skirxvkqa/1\" rel=\"nofollow noreferrer\">HERE</a></li>\n<li>when object has 10 fields and searched key not exists - you can run it <a href=\"https://jsbench.me/1akis0ltq7/1\" rel=\"nofollow noreferrer\">HERE</a></li>\n<li>when object has 10000 fields and searched key exists - you can run it <a href=\"https://jsbench.me/69kirynokp/1\" rel=\"nofollow noreferrer\">HERE</a></li>\n<li>when object has 10000 fields and searched key exists - you can run it <a href=\"https://jsbench.me/nakis0mx5m/1\" rel=\"nofollow noreferrer\">HERE</a></li>\n</ul>\n<p>Below snippet presents differences between solutions\n<a href=\"https://stackoverflow.com/a/14664748/860099\">A</a>\n<a href=\"https://stackoverflow.com/a/11315692/860099\">B</a>\n<a href=\"https://stackoverflow.com/a/40266120/860099\">C</a>\n<a href=\"https://stackoverflow.com/q/135448/860099\">D</a>\n<a href=\"https://stackoverflow.com/a/11315692/860099\">E</a>\n<a href=\"https://stackoverflow.com/a/136411/860099\">F</a>\n<a href=\"https://stackoverflow.com/a/135568/860099\">G</a>\n<a href=\"https://stackoverflow.com/a/22740939/860099\">H</a>\n<a href=\"https://stackoverflow.com/a/38332171/860099\">I</a>\n<a href=\"https://stackoverflow.com/a/41184688/860099\">J</a>\n<a href=\"https://stackoverflow.com/a/54196605/860099\">K</a></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// SO https://stackoverflow.com/q/135448/860099\n\n\n// src: https://stackoverflow.com/a/14664748/860099\nfunction A(x) {\n return 'key' in x\n}\n\n// src: https://stackoverflow.com/a/11315692/860099\nfunction B(x) {\n return _.has(x, 'key')\n}\n\n// src: https://stackoverflow.com/a/40266120/860099\nfunction C(x) {\n return Reflect.has( x, 'key')\n}\n\n// src: https://stackoverflow.com/q/135448/860099\nfunction D(x) {\n return x.hasOwnProperty('key')\n}\n\n// src: https://stackoverflow.com/a/11315692/860099\nfunction E(x) {\n return Object.prototype.hasOwnProperty.call(x, 'key')\n}\n\n// src: https://stackoverflow.com/a/136411/860099\nfunction F(x) {\n function hasOwnProperty(obj, prop) {\n var proto = obj.__proto__ || obj.constructor.prototype;\n return (prop in obj) &&\n (!(prop in proto) || proto[prop] !== obj[prop]);\n }\n return hasOwnProperty(x,'key')\n}\n\n// src: https://stackoverflow.com/a/135568/860099\nfunction G(x) {\n return typeof(x.key) !== 'undefined'\n}\n\n// src: https://stackoverflow.com/a/22740939/860099\nfunction H(x) {\n return x.key !== undefined\n}\n\n// src: https://stackoverflow.com/a/38332171/860099\nfunction I(x) {\n return !!x.key\n}\n\n// src: https://stackoverflow.com/a/41184688/860099\nfunction J(x) {\n return !!x['key']\n}\n\n// src: https://stackoverflow.com/a/54196605/860099\nfunction K(x) {\n return Boolean(x.key)\n}\n\n\n// --------------------\n// TEST\n// --------------------\n\nlet x1 = {'key': 1};\nlet x2 = {'key': \"1\"};\nlet x3 = {'key': true};\nlet x4 = {'key': []};\nlet x5 = {'key': {}};\nlet x6 = {'key': ()=>{}};\nlet x7 = {'key': ''};\nlet x8 = {'key': 0};\nlet x9 = {'key': false};\nlet x10= {'key': undefined};\nlet x11= {'nokey': 1};\n\n\n\nlet b= x=> x ? 1:0;\n\nconsole.log(' 1 2 3 4 5 6 7 8 9 10 11');\n\n[A,B,C,D,E,F,G,H,I,J,K ].map(f=> { \n console.log(\n `${f.name} ${b(f(x1))} ${b(f(x2))} ${b(f(x3))} ${b(f(x4))} ${b(f(x5))} ${b(f(x6))} ${b(f(x7))} ${b(f(x8))} ${b(f(x9))} ${b(f(x10))} ${b(f(x11))} `\n )})\n \nconsole.log('\\nLegend: Columns (cases)');\nconsole.log('1. key = 1 ');\nconsole.log('2. key = \"1\" ');\nconsole.log('3. key = true ');\nconsole.log('4. key = [] ');\nconsole.log('5. key = {} ');\nconsole.log('6. key = ()=>{} ');\nconsole.log('7. key = \"\" ');\nconsole.log('8. key = 0 ');\nconsole.log('9. key = false ');\nconsole.log('10. key = undefined ');\nconsole.log('11. no-key ');</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js\" integrity=\"sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==\" crossorigin=\"anonymous\"> </script>\n \nThis shippet only presents functions used in performance tests - it not perform tests itself!</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>And here are example results for chrome</p>\n<p><a href=\"https://i.stack.imgur.com/w18ak.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/w18ak.png\" alt=\"enter image description here\" /></a></p>\n"
},
{
"answer_id": 66039801,
"author": "Nitin Jadhav",
"author_id": 741251,
"author_profile": "https://Stackoverflow.com/users/741251",
"pm_score": 0,
"selected": false,
"text": "<h2>A Better approach for iterating on object's own properties:</h2>\n<p>If you want to iterate on object's properties without using <code>hasOwnProperty()</code> check,\nuse <code>for(let key of Object.keys(stud)){}</code> method:</p>\n<pre><code>for(let key of Object.keys(stud)){\n console.log(key); // will only log object's Own properties\n}\n</code></pre>\n<p>full Example and comparison with <code>for-in with hasOwnProperty()</code></p>\n<pre><code>function Student() {\n this.name = "nitin";\n}\n\nStudent.prototype = {\n grade: 'A'\n}\n\nlet stud = new Student();\n\n// for-in approach\nfor(let key in stud){\n if(stud.hasOwnProperty(key)){\n console.log(key); // only outputs "name"\n }\n} \n\n//Object.keys() approach\nfor(let key of Object.keys(stud)){\n console.log(key);\n}\n</code></pre>\n"
},
{
"answer_id": 66332561,
"author": "majurageerthan",
"author_id": 7765316,
"author_profile": "https://Stackoverflow.com/users/7765316",
"pm_score": 2,
"selected": false,
"text": "<p>Showing how to use <a href=\"https://stackoverflow.com/a/30533729/7765316\">this answer</a></p>\n<pre><code>const object= {key1: 'data', key2: 'data2'};\n\nObject.keys(object).includes('key1') //returns true\n</code></pre>\n<p>We can use <code>indexOf</code> as well, I prefer <a href=\"https://stackoverflow.com/a/45264728/7765316\">includes</a></p>\n"
},
{
"answer_id": 67120164,
"author": "MD SHAYON",
"author_id": 8725395,
"author_profile": "https://Stackoverflow.com/users/8725395",
"pm_score": 1,
"selected": false,
"text": "<p>The <strong>hasOwnProperty()</strong> method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).</p>\n<pre><code>const object1 = {};\nobject1.property1 = 42;\n\nconsole.log(object1.hasOwnProperty('property1'));\n// expected output: true\n\nconsole.log(object1.hasOwnProperty('toString'));\n// expected output: false\n\nconsole.log(object1.hasOwnProperty('hasOwnProperty'));\n// expected output: false\n</code></pre>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty\" rel=\"nofollow noreferrer\">Know more</a></p>\n"
},
{
"answer_id": 67810564,
"author": "Marco Balestra",
"author_id": 7592319,
"author_profile": "https://Stackoverflow.com/users/7592319",
"pm_score": 3,
"selected": false,
"text": "<p>Given <em>myObject</em> object and <em>“myKey”</em> as key name:</p>\n<pre><code>Object.keys(myObject).includes('myKey')\n</code></pre>\n<p>or</p>\n<pre><code>myObject.hasOwnProperty('myKey')\n</code></pre>\n<p>or</p>\n<pre><code>typeof myObject.myKey !== 'undefined'\n</code></pre>\n<p>The last was widely used, but (as pointed out in other answers and comments) it could also match on keys deriving from Object prototype.</p>\n"
},
{
"answer_id": 68203057,
"author": "bristweb",
"author_id": 4481226,
"author_profile": "https://Stackoverflow.com/users/4481226",
"pm_score": 2,
"selected": false,
"text": "<p><strong>some easier and short options depending on the specific use case:</strong></p>\n<ol>\n<li>to check if the property exists, regardless of value, use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in\" rel=\"nofollow noreferrer\">in operator ("a" in b)</a></li>\n<li>to check a property value from a variable, use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#bracket_notation\" rel=\"nofollow noreferrer\">bracket notation (obj[v])</a></li>\n<li>to check a property value as truthy, use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining\" rel=\"nofollow noreferrer\">optional\nchaining (?.) </a></li>\n<li>to check a property value boolean, use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT#double_not_!!\" rel=\"nofollow noreferrer\">double-not / bang-bang / (!!)</a></li>\n<li>to set a default value for null / undefined check, use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator\" rel=\"nofollow noreferrer\">nullish coalescing operator (??)</a></li>\n<li>to set a default value for falsey value check, use short-circuit <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator\" rel=\"nofollow noreferrer\">logical OR operator (||)</a></li>\n</ol>\n<p>run the code snippet to see results:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let obj1 = {prop:undefined};\nconsole.log(1,\"prop\" in obj1);\nconsole.log(1,obj1?.prop);\n\nlet obj2 = undefined;\n//console.log(2,\"prop\" in obj2); would throw because obj2 undefined\nconsole.log(2,\"prop\" in (obj2 ?? {}))\nconsole.log(2,obj2?.prop);\n\nlet obj3 = {prop:false};\nconsole.log(3,\"prop\" in obj3);\nconsole.log(3,!!obj3?.prop);\n\nlet obj4 = {prop:null};\nlet look = \"prop\"\nconsole.log(4,\"prop\" in obj4);\nconsole.log(4,obj4?.[look]);\n\nlet obj5 = {prop:true};\nconsole.log(5,\"prop\" in obj5);\nconsole.log(5,obj5?.prop === true);\n\nlet obj6 = {otherProp:true};\nlook = \"otherProp\"\nconsole.log(6,\"prop\" in obj6);\nconsole.log(6,obj6.look); //should have used bracket notation\n\nlet obj7 = {prop:\"\"};\nconsole.log(7,\"prop\" in obj7);\nconsole.log(7,obj7?.prop || \"empty\"); </code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>I see very few instances where <code>hasOwn</code> is used properly, especially given its <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty#direct_vs._inherited_properties\" rel=\"nofollow noreferrer\">inheritance issues</a></p>\n"
},
{
"answer_id": 71533572,
"author": "nassim miled",
"author_id": 8945943,
"author_profile": "https://Stackoverflow.com/users/8945943",
"pm_score": 2,
"selected": false,
"text": "<p>Now with <strong>ECMAScript22</strong> we can use <a href=\"https://exploringjs.com/impatient-js/ch_objects.html#Object.hasOwn\" rel=\"nofollow noreferrer\">hasOwn</a> instead of <code>hasOwnProperty</code> (Because this feature has pitfalls )</p>\n<pre><code>Object.hasOwn(obj, propKey)\n</code></pre>\n"
},
{
"answer_id": 72124802,
"author": "Miroslav Hinkov",
"author_id": 14099540,
"author_profile": "https://Stackoverflow.com/users/14099540",
"pm_score": 0,
"selected": false,
"text": "<p>x?.key returns 1 if x.key exists, otherwise undefined</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4915/"
]
| How do I check if an object has a specific property in JavaScript?
Consider:
```
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
```
Is that the best way to do it? | 2022 UPDATE
-----------
[`Object.hasOwn()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn)
-------------------------------------------------------------------------------------------------------------------
>
> `Object.hasOwn()` is recommended over `Object.hasOwnProperty()` because it works for objects created using `Object.create(null)` and with objects that have overridden the inherited `hasOwnProperty()` method. While it is possible to workaround these problems by calling `Object.prototype.hasOwnProperty()` on an external object, `Object.hasOwn()` is more intuitive.
>
>
>
#### Example
```js
const object1 = {
prop: 'exists'
};
console.log(Object.hasOwn(object1, 'prop'));
// expected output: true
```
---
Original answer
---------------
I'm really confused by the answers that have been given - most of them are just outright incorrect. Of course you can have object properties that have undefined, null, or false values. So simply reducing the property check to `typeof this[property]` or, even worse, `x.key` will give you completely misleading results.
It depends on what you're looking for. If you want to know if an object physically contains a property (and it is not coming from somewhere up on the prototype chain) then `object.hasOwnProperty` is the way to go. All modern browsers support it. (It was missing in older versions of Safari - 2.0.1 and older - but those versions of the browser are rarely used any more.)
If what you're looking for is if an object has a property on it that is iterable (when you iterate over the properties of the object, it will appear) then doing: `prop in object` will give you your desired effect.
Since using `hasOwnProperty` is probably what you want, and considering that you may want a fallback method, I present to you the following solution:
```
var obj = {
a: undefined,
b: null,
c: false
};
// a, b, c all found
for ( var prop in obj ) {
document.writeln( "Object1: " + prop );
}
function Class(){
this.a = undefined;
this.b = null;
this.c = false;
}
Class.prototype = {
a: undefined,
b: true,
c: true,
d: true,
e: true
};
var obj2 = new Class();
// a, b, c, d, e found
for ( var prop in obj2 ) {
document.writeln( "Object2: " + prop );
}
function hasOwnProperty(obj, prop) {
var proto = obj.__proto__ || obj.constructor.prototype;
return (prop in obj) &&
(!(prop in proto) || proto[prop] !== obj[prop]);
}
if ( Object.prototype.hasOwnProperty ) {
var hasOwnProperty = function(obj, prop) {
return obj.hasOwnProperty(prop);
}
}
// a, b, c found in modern browsers
// b, c found in Safari 2.0.1 and older
for ( var prop in obj2 ) {
if ( hasOwnProperty(obj2, prop) ) {
document.writeln( "Object2 w/ hasOwn: " + prop );
}
}
```
The above is a working, cross-browser, solution to `hasOwnProperty()`, with one caveat: It is unable to distinguish between cases where an identical property is on the prototype and on the instance - it just assumes that it's coming from the prototype. You could shift it to be more lenient or strict, based upon your situation, but at the very least this should be more helpful. |
135,451 | <p>I want to create a list of methods to execute. Each method has the same signature.
I thought about putting delegates in a generic collection, but I keep getting this error:</p>
<blockquote>
<p>'method' is a 'variable' but is used like a 'method'</p>
</blockquote>
<p>In theory, here is what I would like to do:</p>
<pre><code>List<object> methodsToExecute;
int Add(int x, int y)
{ return x+y; }
int Subtract(int x, int y)
{ return x-y; }
delegate int BinaryOp(int x, int y);
methodsToExecute.add(new BinaryOp(add));
methodsToExecute.add(new BinaryOp(subtract));
foreach(object method in methodsToExecute)
{
method(1,2);
}
</code></pre>
<p>Any ideas on how to accomplish this?
Thanks!</p>
| [
{
"answer_id": 135453,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>Have them all implement of common interface, say IExecuteable, and then have a List<IExecutable></p>\n\n<p>Also, using delegates:</p>\n\n<pre><code>class Example\n{\n public delegate int AddDelegate(int x, int y);\n\n public List<AddDelegate> methods = new List<AddDelegate>();\n\n int Execute()\n {\n int sum = 0;\n foreach(AddDelegate method in methods)\n {\n sum+=method.Invoke(1, 2);\n }\n return sum;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 135463,
"author": "Maurice",
"author_id": 19676,
"author_profile": "https://Stackoverflow.com/users/19676",
"pm_score": 0,
"selected": false,
"text": "<p>Haven't tried it but using an List< Action< t>> type should be able to do it.</p>\n"
},
{
"answer_id": 135464,
"author": "Khoth",
"author_id": 20686,
"author_profile": "https://Stackoverflow.com/users/20686",
"pm_score": 5,
"selected": true,
"text": "<p>You need to cast the <code>object</code> in the list to a <code>BinaryOp</code>, or, better, use a more specific type parameter for the list:</p>\n\n<pre><code>delegate int BinaryOp(int x, int y);\n\nList<BinaryOp> methodsToExecute = new List<BinaryOp>();\n\nmethodsToExecute.add(Add);\nmethodsToExecute.add(Subtract);\n\nforeach(BinaryOp method in methodsToExecute)\n{\n method(1,2);\n}\n</code></pre>\n"
},
{
"answer_id": 135476,
"author": "David Alpert",
"author_id": 8997,
"author_profile": "https://Stackoverflow.com/users/8997",
"pm_score": 2,
"selected": false,
"text": "<p>Using .NET 3.0 (or 3.5?) you have generic delegates.</p>\n\n<p>Try this:</p>\n\n<pre><code>List<Func<int, int, int>> methodsToExecute = new List<Func<int, int, int>>();\n\nmethodsToExecute.Add(Subtract);\n\nmethodsToExecute.Add[0](1,2); // equivalent to Subtract(1,2)\n</code></pre>\n"
},
{
"answer_id": 135491,
"author": "brock.holum",
"author_id": 15860,
"author_profile": "https://Stackoverflow.com/users/15860",
"pm_score": 2,
"selected": false,
"text": "<pre><code>List<Func<int, int, int>> n = new List<Func<int, int, int>>();\n n.Add((x, y) => x + y);\n n.Add((x, y) => x - y);\n n.ForEach(f => f.Invoke(1, 2));\n</code></pre>\n"
},
{
"answer_id": 135506,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 1,
"selected": false,
"text": "<p>I like Khoth's implementation better but I think what is causing your compiler error is that you don't cast method to a BinaryOp before you try to invoke it. In your foreach loop it is merely an \"object\". Change your foreach to look like Khoth's and I think it would work.</p>\n"
},
{
"answer_id": 135936,
"author": "aceinthehole",
"author_id": 520,
"author_profile": "https://Stackoverflow.com/users/520",
"pm_score": 1,
"selected": false,
"text": "<p>Whenever I have been tempted to do something like this, I have found that it is generally better to refactor your design to use the command pattern, especially since all of your methods have the same parameters. This way allows for far more flexibility.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8797/"
]
| I want to create a list of methods to execute. Each method has the same signature.
I thought about putting delegates in a generic collection, but I keep getting this error:
>
> 'method' is a 'variable' but is used like a 'method'
>
>
>
In theory, here is what I would like to do:
```
List<object> methodsToExecute;
int Add(int x, int y)
{ return x+y; }
int Subtract(int x, int y)
{ return x-y; }
delegate int BinaryOp(int x, int y);
methodsToExecute.add(new BinaryOp(add));
methodsToExecute.add(new BinaryOp(subtract));
foreach(object method in methodsToExecute)
{
method(1,2);
}
```
Any ideas on how to accomplish this?
Thanks! | You need to cast the `object` in the list to a `BinaryOp`, or, better, use a more specific type parameter for the list:
```
delegate int BinaryOp(int x, int y);
List<BinaryOp> methodsToExecute = new List<BinaryOp>();
methodsToExecute.add(Add);
methodsToExecute.add(Subtract);
foreach(BinaryOp method in methodsToExecute)
{
method(1,2);
}
``` |
135,458 | <p>Suppose I have the following code:</p>
<pre><code>while(TRUE) {
pthread_t *thread = (pthread_t *) malloc(sizeof(pthread_t));
pthread_create(thread, NULL, someFunction, someArgument);
pthread_detach(*thread);
sleep(10);
}
</code></pre>
<p>Will the detached thread free the memory allocated by malloc, or is that something I now have to do?</p>
| [
{
"answer_id": 135922,
"author": "Commodore Jaeger",
"author_id": 4659,
"author_profile": "https://Stackoverflow.com/users/4659",
"pm_score": 4,
"selected": true,
"text": "<p>No. <strong>pthread_create()</strong> has no way of knowing that the <strong>thread</strong> pointer passed to it was dynamically allocated. pthreads doesn't use this value internally; it simply returns the new thread id to the caller. You don't need to dynamically allocate that value; you can pass the address of a local variable instead:</p>\n\n<pre><code>pthread_t thread;\npthread_create(&thread, NULL, someFunction, someArgument);\n</code></pre>\n"
},
{
"answer_id": 136073,
"author": "An̲̳̳drew",
"author_id": 17035,
"author_profile": "https://Stackoverflow.com/users/17035",
"pm_score": 1,
"selected": false,
"text": "<p>You need to free the memory yourself. It would be preferable to simply allocate the pthread_t variable on the stack as opposed to the heap.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/542226/"
]
| Suppose I have the following code:
```
while(TRUE) {
pthread_t *thread = (pthread_t *) malloc(sizeof(pthread_t));
pthread_create(thread, NULL, someFunction, someArgument);
pthread_detach(*thread);
sleep(10);
}
```
Will the detached thread free the memory allocated by malloc, or is that something I now have to do? | No. **pthread\_create()** has no way of knowing that the **thread** pointer passed to it was dynamically allocated. pthreads doesn't use this value internally; it simply returns the new thread id to the caller. You don't need to dynamically allocate that value; you can pass the address of a local variable instead:
```
pthread_t thread;
pthread_create(&thread, NULL, someFunction, someArgument);
``` |
135,474 | <p>For example:</p>
<pre><code>char * myString = malloc(sizeof(char)*STRING_BUFFER_SIZE);
free(myString);
free(myString);
</code></pre>
<p>Are there any adverse side effects of doing this? </p>
| [
{
"answer_id": 135483,
"author": "jbleners",
"author_id": 542226,
"author_profile": "https://Stackoverflow.com/users/542226",
"pm_score": 4,
"selected": false,
"text": "<p>Yes, you can get a double free error that causes your program to crash. It has to do with malloc's internal data structures to keep track of allocated memory.</p>\n"
},
{
"answer_id": 135484,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "<p>Depending on which system you run it on, nothing will happen, the program will crash, memory will be corrupted, or any other number of interesting effects.</p>\n"
},
{
"answer_id": 135486,
"author": "Khoth",
"author_id": 20686,
"author_profile": "https://Stackoverflow.com/users/20686",
"pm_score": 2,
"selected": false,
"text": "<p>Don't do that. If the memory that got freed is re-allocated to something else between the calls to <code>free</code>, then things will get messed up.</p>\n"
},
{
"answer_id": 135487,
"author": "mbac32768",
"author_id": 18446,
"author_profile": "https://Stackoverflow.com/users/18446",
"pm_score": 4,
"selected": false,
"text": "<p>One of nothing, silent memory corruption, or segmentation fault.</p>\n"
},
{
"answer_id": 135492,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 3,
"selected": false,
"text": "<p>Not so clever. Google for double free vulnerabilities. Set your pointer to <code>NULL</code> after freeing to avoid such bugs.</p>\n"
},
{
"answer_id": 135504,
"author": "Martin Beckett",
"author_id": 10897,
"author_profile": "https://Stackoverflow.com/users/10897",
"pm_score": 2,
"selected": false,
"text": "<p>Always set a pointer to NULL after freeing it.\nIt is safe to attempt to free a null pointer.</p>\n\n<p>It's worth writing your own free wrapper to do this automatically.</p>\n"
},
{
"answer_id": 135511,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 2,
"selected": false,
"text": "<p><em>Bad Things</em> (TM)</p>\n\n<p>Really, I think it's undefined so anything at all including playing \"Global Thermonuclear War\" with NORAD's mainframe</p>\n"
},
{
"answer_id": 135532,
"author": "luke",
"author_id": 16434,
"author_profile": "https://Stackoverflow.com/users/16434",
"pm_score": 1,
"selected": false,
"text": "<p>It may crash your program, corrupt memory, or have other more subtle negative effects. After you delete memory, it is a good idea to set it to NULL (0). Trying to free a null pointer does nothing, and is guaranteed to be safe. The same holds true for delete in c++.</p>\n"
},
{
"answer_id": 135547,
"author": "lillq",
"author_id": 2064,
"author_profile": "https://Stackoverflow.com/users/2064",
"pm_score": 3,
"selected": false,
"text": "<p>Answer summary:</p>\n\n<p>Yes, bad things can and probably will happen.</p>\n\n<p>To prevent this do:</p>\n\n<pre><code>free(myString);\nmyString = NULL;\n</code></pre>\n\n<p>Note that all references to the memory must be set to <code>NULL</code> if others were created.</p>\n\n<p>Also, calling <code>free()</code> with a <code>NULL</code> results in no action. For more info see: <a href=\"http://linux.die.net/man/3/free\" rel=\"noreferrer\">man free</a></p>\n"
},
{
"answer_id": 137814,
"author": "Christian.K",
"author_id": 21567,
"author_profile": "https://Stackoverflow.com/users/21567",
"pm_score": 1,
"selected": false,
"text": "<p>In short: \"Undefined Behavior\".</p>\n\n<p>(Now, what that can include and why that is the case the others have already said. I just though it was worth mentioning the term here as it is quite common).</p>\n"
},
{
"answer_id": 137850,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 6,
"selected": true,
"text": "<p>Here's the chapter and verse.</p>\n\n<blockquote>\n <p>If the argument [to the <code>free</code> function] does not match a pointer earlier returned by the <code>calloc</code>, <code>malloc</code>, or\n <code>realloc</code> function, or if the space has been deallocated by a call to <code>free</code> or <code>realloc</code>,\n the behavior is undefined. (<a href=\"http://www.open-std.org/jtc1/sc22/wg14/www/standards\" rel=\"noreferrer\">ISO 9899:1999 - <em>Programming languages — C</em></a>, Section 7.20.3.2)</p>\n</blockquote>\n"
},
{
"answer_id": 145150,
"author": "mbac32768",
"author_id": 18446,
"author_profile": "https://Stackoverflow.com/users/18446",
"pm_score": 1,
"selected": false,
"text": "<p>The admittedly strange macro below is a useful drop-in replacement for wiping out a few classes of security vulnerabilities as well as aid debugging since accesses to free()'d regions are more likely to segfault instead of silently corrupting memory.</p>\n\n<pre><code>#define my_free(x) do { free(x); x = NULL; } while (0)\n</code></pre>\n\n<p>The do-while loop is to help surrounding code more easily digest the multiple-statements. e.g. if (done) my_free(x);</p>\n"
},
{
"answer_id": 3575324,
"author": "pinpinokio",
"author_id": 431858,
"author_profile": "https://Stackoverflow.com/users/431858",
"pm_score": -1,
"selected": false,
"text": "<p><strong>Another interesting situation:</strong></p>\n\n<pre><code>char * myString = malloc(sizeof(char)*STRING_BUFFER_SIZE);\nchar * yourString = myString;\n\nif (myString)\n{\n free(myString);\n myString = NULL;\n}\n// Now this one is safe, because we keep to the rule for \n// setting pointers to NULL after deletion ...\nif (myString)\n{\n free(myString);\n myString = NULL;\n}\n\n// But what about this one:\nif (yourString)\n{\n free(yourString);\n yourString = NULL;\n}\n\n//?!? :)\n</code></pre>\n"
},
{
"answer_id": 7223384,
"author": "Jens",
"author_id": 648658,
"author_profile": "https://Stackoverflow.com/users/648658",
"pm_score": 3,
"selected": false,
"text": "<p>It (potentially) makes <a href=\"http://www.urbandictionary.com/define.php?term=nasal%20demons\" rel=\"noreferrer\">demons fly out of your nose</a>.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2064/"
]
| For example:
```
char * myString = malloc(sizeof(char)*STRING_BUFFER_SIZE);
free(myString);
free(myString);
```
Are there any adverse side effects of doing this? | Here's the chapter and verse.
>
> If the argument [to the `free` function] does not match a pointer earlier returned by the `calloc`, `malloc`, or
> `realloc` function, or if the space has been deallocated by a call to `free` or `realloc`,
> the behavior is undefined. ([ISO 9899:1999 - *Programming languages — C*](http://www.open-std.org/jtc1/sc22/wg14/www/standards), Section 7.20.3.2)
>
>
> |
135,518 | <p>In WPF, we are creating custom controls that inherit from button with completely drawn-from-scratch xaml graphics. We have a border around the entire button xaml and we'd like to use that as the location for updating the background when MouseOver=True in a trigger. What we need to know is how do we update the background of the border in this button with a gradient when the mouse hovers over it?</p>
| [
{
"answer_id": 135638,
"author": "Joel B Fant",
"author_id": 22211,
"author_profile": "https://Stackoverflow.com/users/22211",
"pm_score": 3,
"selected": true,
"text": "<p>In your <code>ControlTemplate</code>, give the <code>Border</code> a <code>Name</code> and you can then reference that part of its visual tree in the triggers. Here's a very brief example of restyling a normal <code>Button</code>:</p>\n\n<pre><code><Style\n TargetType=\"{x:Type Button}\">\n <Setter\n Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type Button}\">\n <Border Name=\"customBorder\"\n CornerRadius=\"5\"\n BorderThickness=\"1\"\n BorderBrush=\"Black\"\n Background=\"{StaticResource normalButtonBG}\">\n <ContentPresenter\n HorizontalAlignment=\"Center\"\n VerticalAlignment=\"Center\" />\n </Border>\n <ControlTemplate.Triggers>\n <Trigger\n Property=\"IsMouseOver\"\n Value=\"True\">\n <Setter\n TargetName=\"customBorder\"\n Property=\"Background\"\n Value=\"{StaticResource hoverButtonBG}\" />\n </Trigger>\n </ControlTemplate.Triggers>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n</Style>\n</code></pre>\n\n<p>If that doesn't help, we'll need to know more, probably seeing your own XAML. Your description doesn't make it very clear to me what your actual visual tree is.</p>\n"
},
{
"answer_id": 135796,
"author": "Phobis",
"author_id": 19854,
"author_profile": "https://Stackoverflow.com/users/19854",
"pm_score": 0,
"selected": false,
"text": "<p>You would want to add a trigger like this...</p>\n\n<p>Make a style like this:</p>\n\n<pre><code><Style x:Key=\"ButtonTemplate\"\n TargetType=\"{x:Type Button}\">\n <Setter Property=\"Foreground\"\n Value=\"{StaticResource ButtonForeground}\" />\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate\n TargetType=\"{x:Type Button}\">\n <Grid\n SnapsToDevicePixels=\"True\"\n Margin=\"0,0,0,0\">\n <Border Height=\"20\"\n x:Name=\"ButtonBorder\"\n BorderBrush=\"{DynamicResource BlackBorderBrush}\">\n <TextBlock x:Name=\"button\"\n TextWrapping=\"Wrap\"\n Text=\"{Binding Path=Content, RelativeSource={RelativeSource TemplatedParent}}\"\n SnapsToDevicePixels=\"True\"\n Foreground=\"#FFFFFFFF\"\n Margin=\"6,0,0,0\"\n VerticalAlignment=\"Center\"/>\n </Border>\n </Grid>\n <ControlTemplate.Triggers>\n <!-- Disabled -->\n <Trigger Property=\"IsMouseOver\"\n Value=\"True\">\n <Setter TargetName=\"ButtonBorder\"\n Property=\"Background\"\n Value=\"{DynamicResource ButtonBackgroundMouseOver}\" />\n <Setter TargetName=\"ButtonBorder\"\n Property=\"BorderBrush\"\n Value=\"{DynamicResource ButtonBorderMouseOver}\" />\n </Trigger>\n </ControlTemplate.Triggers>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n</Style>\n</code></pre>\n\n<p>Then add some resources for the gradients, like this:</p>\n\n<pre><code><LinearGradientBrush x:Key=\"ButtonBackgroundMouseOver\"\n EndPoint=\"0.5,1\"\n StartPoint=\"0.5,0\">\n <GradientStop Color=\"#FF000000\"\n Offset=\"0.432\"/>\n <GradientStop Color=\"#FF808080\"\n Offset=\"0.9\"/>\n <GradientStop Color=\"#FF848484\"\n Offset=\"0.044\"/>\n <GradientStop Color=\"#FF787878\"\n Offset=\"0.308\"/>\n <GradientStop Color=\"#FF212121\"\n Offset=\"0.676\"/>\n</LinearGradientBrush>\n</code></pre>\n\n<p>Please let me know if you need more help with this.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21096/"
]
| In WPF, we are creating custom controls that inherit from button with completely drawn-from-scratch xaml graphics. We have a border around the entire button xaml and we'd like to use that as the location for updating the background when MouseOver=True in a trigger. What we need to know is how do we update the background of the border in this button with a gradient when the mouse hovers over it? | In your `ControlTemplate`, give the `Border` a `Name` and you can then reference that part of its visual tree in the triggers. Here's a very brief example of restyling a normal `Button`:
```
<Style
TargetType="{x:Type Button}">
<Setter
Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border Name="customBorder"
CornerRadius="5"
BorderThickness="1"
BorderBrush="Black"
Background="{StaticResource normalButtonBG}">
<ContentPresenter
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger
Property="IsMouseOver"
Value="True">
<Setter
TargetName="customBorder"
Property="Background"
Value="{StaticResource hoverButtonBG}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
```
If that doesn't help, we'll need to know more, probably seeing your own XAML. Your description doesn't make it very clear to me what your actual visual tree is. |
135,534 | <p>I need to validate this simple pick list:</p>
<pre><code><select name="<%= key %>">
<option value="ETC" SELECTED>Select an option...</option>
<option value="ONE">Lorem ipsum</option>
<option value="TWO">dolor sit amet</option>
</select>
</code></pre>
<p>So the user would never submit the form with the, excuse the repetition, "Select an option..." option selected. In principle I'm allowed to use JavaScript but It'd be interesting to learn how to solve it within JSP too.</p>
| [
{
"answer_id": 135795,
"author": "Peter",
"author_id": 17123,
"author_profile": "https://Stackoverflow.com/users/17123",
"pm_score": 3,
"selected": true,
"text": "<p>You can never really satisfy the condition 'never submit a given value' because you don't have control over the client side. The user can always manipulate HTML to submit whatever they want.</p>\n\n<p>It is a good approach is to use JavaScript to do client-side validation and give the user quick feedback and catch 99%+ of the cases, then do a server-side validation of the submitted parameters to catch the minority that don't have JS enabled or who manipulate the HTML to submit non-expected values.</p>\n\n<p>Just remember that the client-side validation is optional, and is good for those 'common mistakes' input validation, but the server-side validation is mandatory for all input whether or not any client-side checks have been done on the given input.</p>\n"
},
{
"answer_id": 135973,
"author": "Olaf Kock",
"author_id": 13447,
"author_profile": "https://Stackoverflow.com/users/13447",
"pm_score": 1,
"selected": false,
"text": "<p>Nowadays you usually don't validate in JSPs, because they only visualize whatever was processed earlier. So the only validation that you do \"in jsps\" is usually Javascript. For the rest (the real validation) I second what Pete answered: You have to do it serverside in whatever technique you are using there. When it's displayed in the JSP again, validation has hopefully long been done.</p>\n\n<p>As I said \"nowadays\": When JSP was a shiny new concept, a lot more was done inside the boundaries of a JSP and sometimes even Forms were posted to JSPs. <em>How</em> to validate was even more nonstandard at that time.</p>\n"
},
{
"answer_id": 138738,
"author": "Sandman",
"author_id": 19911,
"author_profile": "https://Stackoverflow.com/users/19911",
"pm_score": 1,
"selected": false,
"text": "<p>JSP is a \"view\" in MVC pattern, and should therefore only be used to present the data to the user. Any application logic, including validation logic, should be done server-side.\nIf this JSP is intended to be a part of a large app, I would recommend using Spring MVC to set up your app, and writing a validator to validate the input.\nBut even if we're not talking about some large application here, the validation should still be done server-side, as others before me have already noted.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6992/"
]
| I need to validate this simple pick list:
```
<select name="<%= key %>">
<option value="ETC" SELECTED>Select an option...</option>
<option value="ONE">Lorem ipsum</option>
<option value="TWO">dolor sit amet</option>
</select>
```
So the user would never submit the form with the, excuse the repetition, "Select an option..." option selected. In principle I'm allowed to use JavaScript but It'd be interesting to learn how to solve it within JSP too. | You can never really satisfy the condition 'never submit a given value' because you don't have control over the client side. The user can always manipulate HTML to submit whatever they want.
It is a good approach is to use JavaScript to do client-side validation and give the user quick feedback and catch 99%+ of the cases, then do a server-side validation of the submitted parameters to catch the minority that don't have JS enabled or who manipulate the HTML to submit non-expected values.
Just remember that the client-side validation is optional, and is good for those 'common mistakes' input validation, but the server-side validation is mandatory for all input whether or not any client-side checks have been done on the given input. |
135,591 | <p>I've seen several products that will track the sales rank of an item on Amazon. Does Amazon have any web-services published that I can use to get the sales rank of a particular item? </p>
<p>I've looked through the AWS and didn't see anything of that nature.</p>
| [
{
"answer_id": 135627,
"author": "Adam Hughes",
"author_id": 3863,
"author_profile": "https://Stackoverflow.com/users/3863",
"pm_score": 4,
"selected": true,
"text": "<p>You should be able to determine the Sales Rank by querying for the SalesRank response group when doing an ItemLookup with the Amazon Associates Web Service.</p>\n\n<p>Example query:</p>\n\n<pre><code>http://ecs.amazonaws.com/onca/xml?\nService=AWSECommerceService&\nAWSAccessKeyId=[AWS Access Key ID]&\nOperation=ItemLookup&\nItemId=0976925524&\nResponseGroup=SalesRank&\nVersion=2008-08-19\n</code></pre>\n\n<p>Response:</p>\n\n<pre><code><Item>\n <ASIN>0976925524</ASIN> \n <SalesRank>68</SalesRank> \n</Item>\n</code></pre>\n\n<p>See the documentation here: <a href=\"http://docs.amazonwebservices.com/AWSECommerceService/2008-08-19/DG/index.html?RG_SalesRank.html\" rel=\"noreferrer\">http://docs.amazonwebservices.com/AWSECommerceService/2008-08-19/DG/index.html?RG_SalesRank.html</a></p>\n"
},
{
"answer_id": 1516131,
"author": "ade",
"author_id": 97238,
"author_profile": "https://Stackoverflow.com/users/97238",
"pm_score": 2,
"selected": false,
"text": "<p>Amazon have changed their API so it now requires a signature: <a href=\"http://developer.amazonwebservices.com/connect/ann.jspa?annID=483\" rel=\"nofollow noreferrer\">http://developer.amazonwebservices.com/connect/ann.jspa?annID=483</a> so the above example no longer works from August 2009 onwards.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4244/"
]
| I've seen several products that will track the sales rank of an item on Amazon. Does Amazon have any web-services published that I can use to get the sales rank of a particular item?
I've looked through the AWS and didn't see anything of that nature. | You should be able to determine the Sales Rank by querying for the SalesRank response group when doing an ItemLookup with the Amazon Associates Web Service.
Example query:
```
http://ecs.amazonaws.com/onca/xml?
Service=AWSECommerceService&
AWSAccessKeyId=[AWS Access Key ID]&
Operation=ItemLookup&
ItemId=0976925524&
ResponseGroup=SalesRank&
Version=2008-08-19
```
Response:
```
<Item>
<ASIN>0976925524</ASIN>
<SalesRank>68</SalesRank>
</Item>
```
See the documentation here: <http://docs.amazonwebservices.com/AWSECommerceService/2008-08-19/DG/index.html?RG_SalesRank.html> |
135,600 | <p>When I download my program from my website to my windows 2003 machine, it has a block on it and you have to right click on the exe, then properties, then select the button "Unblock".</p>
<p>I would like to add detection in my installer for when the file is blocked and hence doesn't have enough permissions. </p>
<p>But I can't eaisly reproduce getting my exe in this state where it needs to be unblocked.</p>
<p>How can I get the unblock to appear on my exe so I can test this functionality?</p>
| [
{
"answer_id": 135924,
"author": "HitScan",
"author_id": 9490,
"author_profile": "https://Stackoverflow.com/users/9490",
"pm_score": 5,
"selected": true,
"text": "<p>This is done using NTFS File Streams. There is a stream named \"Zone.Identifier\" added to downloaded files. When IE7 downloads certain types of file that stream contains:</p>\n\n<pre><code>[ZoneTransfer]\nZoneId=3\n</code></pre>\n\n<p>The simplest way to set it is to create a text file with those contents in it, and use more to add it to the alternate stream.</p>\n\n<p>Zone.Identifier.txt:</p>\n\n<pre><code>[ZoneTransfer]\nZoneId=3\n</code></pre>\n\n<p>Command:</p>\n\n<pre><code>more Zone.Identifier.txt > file.exe:Zone.Identifier\n</code></pre>\n\n<p>Then, the way for you to check it would be to try to open the Zone.Identifier stream and look for ZoneId=3, or simply assume that if the stream exists at all that your user will receive that warning.</p>\n\n<p>It's also important to note that this has nothing to do with permissions. Administrators see the same warning; it's to do entirely with the source and type of file. The entire stream goes away when users uncheck the \"Always ask before opening this file\" box and then click Run.</p>\n"
},
{
"answer_id": 267495,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>There is a supported API for this, documented on MSDN. Search on MSDN for \"Persistent Zone Identifier Object\". Basically you <code>CoCreateInstance</code> with <code>CLSID_PersistentZoneIdentifier</code> and request an <code>IPersistFile</code> interface. You then call <code>IPersistFile::Load</code> with the name of the file in question. Next, QI for an <code>IZoneIdentifier</code> interface and use <code>IZoneIdentifier::GetId</code> to obtain the zone of the file. If there was no \"mark of the web\", you should get <code>URLZONE_LOCAL_MACHINE</code>. The ZoneId of 3 mentioned in the other reply is <code>URLZONE_INTERNET</code>. (The enumeration is called <code>URLZONE</code> and is also documented on MSDN, or see <code>sdk\\inc\\urlmon.h</code>.) You can remove or change the \"mark of the web\" by calling <code>IZoneIdentifier::Remove</code> or <code>IZoneIdentifier::SetId</code> and then call <code>IPersistFile::Save</code>. There are more details about all of this on MSDN. Good luck!</p>\n"
},
{
"answer_id": 11018484,
"author": "alrutherford",
"author_id": 669504,
"author_profile": "https://Stackoverflow.com/users/669504",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks for this it helped me a lot.</p>\n\n<p>You can make the process even easier if you create a batch file with the contents.</p>\n\n<pre><code>echo [ZoneTransfer] > Zone.Identifier\necho ZoneId=3 >> Zone.Identifier\nmore Zone.Identifier > %1:Zone.Identifier\n</code></pre>\n\n<p>This will generate the Zone.Identifier for you and mark the file accordingly.</p>\n\n<p>To run it just supply the file name e.g. if the file is called mark.bat</p>\n\n<pre><code>mark.bat myfile.txt\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
]
| When I download my program from my website to my windows 2003 machine, it has a block on it and you have to right click on the exe, then properties, then select the button "Unblock".
I would like to add detection in my installer for when the file is blocked and hence doesn't have enough permissions.
But I can't eaisly reproduce getting my exe in this state where it needs to be unblocked.
How can I get the unblock to appear on my exe so I can test this functionality? | This is done using NTFS File Streams. There is a stream named "Zone.Identifier" added to downloaded files. When IE7 downloads certain types of file that stream contains:
```
[ZoneTransfer]
ZoneId=3
```
The simplest way to set it is to create a text file with those contents in it, and use more to add it to the alternate stream.
Zone.Identifier.txt:
```
[ZoneTransfer]
ZoneId=3
```
Command:
```
more Zone.Identifier.txt > file.exe:Zone.Identifier
```
Then, the way for you to check it would be to try to open the Zone.Identifier stream and look for ZoneId=3, or simply assume that if the stream exists at all that your user will receive that warning.
It's also important to note that this has nothing to do with permissions. Administrators see the same warning; it's to do entirely with the source and type of file. The entire stream goes away when users uncheck the "Always ask before opening this file" box and then click Run. |
135,664 | <p>For example, how much memory is required to store a list of one million (32-bit) integers?</p>
<pre><code>alist = range(1000000) # or list(range(1000000)) in Python 3.0
</code></pre>
| [
{
"answer_id": 135718,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 5,
"selected": false,
"text": "<p>\"It depends.\" Python allocates space for lists in such a way as to achieve <a href=\"http://effbot.org/zone/python-list.htm\" rel=\"noreferrer\">amortized constant time</a> for appending elements to the list.</p>\n\n<p>In practice, what this means with the current implementation is... the list always has space allocated for a power-of-two number of elements. So range(1000000) will actually allocate a list big enough to hold 2^20 elements (~ 1.045 million).</p>\n\n<p>This is only the space required to store the list structure itself (which is an array of pointers to the Python objects for each element). A 32-bit system will require 4 bytes per element, a 64-bit system will use 8 bytes per element.</p>\n\n<p>Furthermore, you need space to store the actual elements. This varies widely. For small integers (-5 to 256 currently), no additional space is needed, but for larger numbers Python allocates a new object for each integer, which takes 10-100 bytes and tends to fragment memory.</p>\n\n<p>Bottom line: <b>it's complicated</b> and Python lists are <b>not</b> a good way to store large homogeneous data structures. For that, use the <code>array</code> module or, if you need to do vectorized math, use NumPy.</p>\n\n<p>PS- Tuples, unlike lists, are <i>not designed</i> to have elements progressively appended to them. I don't know how the allocator works, but don't even think about using it for large data structures :-)</p>\n"
},
{
"answer_id": 135748,
"author": "HenryR",
"author_id": 2827,
"author_profile": "https://Stackoverflow.com/users/2827",
"pm_score": 2,
"selected": false,
"text": "<p>This is implementation specific, I'm pretty sure. Certainly it depends on the internal representation of integers - you can't assume they'll be stored as 32-bit since Python gives you arbitrarily large integers so perhaps small ints are stored more compactly. </p>\n\n<p>On my Python (2.5.1 on Fedora 9 on core 2 duo) the VmSize before allocation is 6896kB, after is 22684kB. After one more million element assignment, VmSize goes to 38340kB. This very grossly indicates around 16000kB for 1000000 integers, which is around 16 bytes per integer. That suggests a <em>lot</em> of overhead for the list. I'd take these numbers with a large pinch of salt.</p>\n"
},
{
"answer_id": 136083,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 5,
"selected": true,
"text": "<p>Useful links:</p>\n\n<p><a href=\"http://bytes.com/forum/thread757255.html\" rel=\"noreferrer\">How to get memory size/usage of python object</a></p>\n\n<p><a href=\"http://mail.python.org/pipermail/python-list/2002-March/135223.html\" rel=\"noreferrer\">Memory sizes of python objects?</a></p>\n\n<p><a href=\"http://groups.google.com/group/comp.lang.python/msg/b9afcfc2e1de5b05\" rel=\"noreferrer\">if you put data into dictionary, how do we calculate the data size?</a> </p>\n\n<p>However they don't give a definitive answer. The way to go:</p>\n\n<ol>\n<li><p>Measure memory consumed by Python interpreter with/without the list (use OS tools).</p></li>\n<li><p>Use a third-party extension module which defines some sort of sizeof(PyObject).</p></li>\n</ol>\n\n<p><strong>Update</strong>:</p>\n\n<p><a href=\"http://code.activestate.com/recipes/546530/\" rel=\"noreferrer\">Recipe 546530: Size of Python objects (revised)</a></p>\n\n<pre><code>import asizeof\n\nN = 1000000\nprint asizeof.asizeof(range(N)) / N\n# -> 20 (python 2.5, WinXP, 32-bit Linux)\n# -> 33 (64-bit Linux)\n</code></pre>\n"
},
{
"answer_id": 139393,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Addressing \"tuple\" part of the question</strong></p>\n\n<p>Declaration of CPython's PyTuple in a typical build configuration boils down to this:</p>\n\n<pre><code>struct PyTuple {\n size_t refcount; // tuple's reference count\n typeobject *type; // tuple type object\n size_t n_items; // number of items in tuple\n PyObject *items[1]; // contains space for n_items elements\n};\n</code></pre>\n\n<p>Size of PyTuple instance is fixed during it's construction and cannot be changed afterwards. The number of bytes occupied by PyTuple can be calculated as</p>\n\n<blockquote>\n <p><code>sizeof(size_t) x 2 + sizeof(void*) x (n_items + 1)</code>.</p>\n</blockquote>\n\n<p>This gives <em>shallow</em> size of tuple. To get <em>full</em> size you also need to add total number of bytes consumed by object graph rooted in <code>PyTuple::items[]</code> array. </p>\n\n<p>It's worth noting that tuple construction routines make sure that only single instance of empty tuple is ever created (singleton).</p>\n\n<p>References:\n<a href=\"http://svn.python.org/view/python/tags/r252/Include/Python.h?rev=60915&view=markup\" rel=\"noreferrer\">Python.h</a>,\n<a href=\"http://svn.python.org/view/python/tags/r252/Include/object.h?rev=60915&view=markup\" rel=\"noreferrer\">object.h</a>,\n<a href=\"http://svn.python.org/view/python/tags/r252/Include/tupleobject.h?rev=60915&view=markup\" rel=\"noreferrer\">tupleobject.h</a>,\n<a href=\"http://svn.python.org/view/python/tags/r252/Objects/tupleobject.c?rev=60915&view=markup\" rel=\"noreferrer\">tupleobject.c</a></p>\n"
},
{
"answer_id": 159844,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>A new function, <code>getsizeof()</code>, takes a\n Python object and returns the amount\n of memory used by the object, measured\n in bytes. Built-in objects return\n correct results; third-party\n extensions may not, but can define a\n <code>__sizeof__()</code> method to return the object’s size.</p>\n</blockquote>\n\n<pre><code>kveretennicov@nosignal:~/py/r26rc2$ ./python\nPython 2.6rc2 (r26rc2:66712, Sep 2 2008, 13:11:55) \n[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2\n>>> import sys\n>>> sys.getsizeof(range(1000000))\n4000032\n>>> sys.getsizeof(tuple(range(1000000)))\n4000024\n</code></pre>\n\n<p>Obviously returned numbers don't include memory consumed by contained objects (sys.getsizeof(1) == 12).</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4279/"
]
| For example, how much memory is required to store a list of one million (32-bit) integers?
```
alist = range(1000000) # or list(range(1000000)) in Python 3.0
``` | Useful links:
[How to get memory size/usage of python object](http://bytes.com/forum/thread757255.html)
[Memory sizes of python objects?](http://mail.python.org/pipermail/python-list/2002-March/135223.html)
[if you put data into dictionary, how do we calculate the data size?](http://groups.google.com/group/comp.lang.python/msg/b9afcfc2e1de5b05)
However they don't give a definitive answer. The way to go:
1. Measure memory consumed by Python interpreter with/without the list (use OS tools).
2. Use a third-party extension module which defines some sort of sizeof(PyObject).
**Update**:
[Recipe 546530: Size of Python objects (revised)](http://code.activestate.com/recipes/546530/)
```
import asizeof
N = 1000000
print asizeof.asizeof(range(N)) / N
# -> 20 (python 2.5, WinXP, 32-bit Linux)
# -> 33 (64-bit Linux)
``` |
135,670 | <p>This post is similar to <a href="https://stackoverflow.com/questions/16829/structure-of-projects-in-version-control">this previously asked question.</a> I really want to set up my SVN repository in TTB format, but when creating a project in Visual Studio 2008 (ASP.NET/VB.NET), the structure created tends to be incompatible when considering the solution file, project files, folders for projects, multiple projects within solutions, etc. Does anyone have a script or procedure to take a newly created ASP.NET project and move it to a TTB format as painlessly as possible?</p>
<hr>
<p>Let me be more specific. Suppose I have a project that I'm creating called StackOverflowIsAwesome. I can put that into my local folder structure (let's say that it's c:\working). When I create it, VS creates c:\working\StackOverflowIsAwesome and a whole bunch of subfolders (bin, app_data, etc.). But I want my repository structure to look like...</p>
<pre>
StackOverflowIsAwesome
/trunk
/bin
/app_data
/tags
/branches
</pre>
<p>So, is there a clean way to do this consistently or do I need to resort to constantly moving/modifying files and folders to make this work?</p>
| [
{
"answer_id": 135719,
"author": "Lev",
"author_id": 7224,
"author_profile": "https://Stackoverflow.com/users/7224",
"pm_score": 0,
"selected": false,
"text": "<p>If your TTB are common rather than per project, there is no problem with it. Or am I missing something?</p>\n"
},
{
"answer_id": 135735,
"author": "brock.holum",
"author_id": 15860,
"author_profile": "https://Stackoverflow.com/users/15860",
"pm_score": 1,
"selected": false,
"text": "<p>We went with a very simplistic approach:</p>\n\n<p><strong>File Structure:</strong></p>\n\n<ul>\n<li>Solution Folder (contains solution file, build scripts, maybe more?)\n\n<ul>\n<li>Project Folder</li>\n<li>Project Folder 2</li>\n<li>References (contains shared assemblies for the solution).</li>\n</ul></li>\n</ul>\n\n<p>Then we just check the entire solution folder's contents into our repository. We use one repository for each solution. I'm not sure if this is the optimal way to organize the solution, but it works for us.</p>\n\n<p>Also, we branch at the highest level, not per project.</p>\n"
},
{
"answer_id": 135778,
"author": "Fossmo",
"author_id": 4093,
"author_profile": "https://Stackoverflow.com/users/4093",
"pm_score": 0,
"selected": false,
"text": "<p>You can look at this <a href=\"https://stackoverflow.com/questions/71608/how-do-you-set-up-your-net-development-tree\">previous post</a> or this <a href=\"http://code.google.com/p/treefrog/\" rel=\"nofollow noreferrer\">project</a>. The project creates a .NET development tree structure (requires .NET 3.5). </p>\n"
},
{
"answer_id": 135806,
"author": "RS Conley",
"author_id": 7890,
"author_profile": "https://Stackoverflow.com/users/7890",
"pm_score": 0,
"selected": false,
"text": "<p>When dealing with multiple projects that makes up a Visual Studio Solution it is difficult to decide how to structure things properly. </p>\n\n<p>One critical aspect that you will need to do with your structure is make it easy to retrieve all the files for a particular release. It is important to make this as easy as possible. In subversion copying a root folder over to the tag branches is easier then remembering to repeat the same operation for X projects. </p>\n\n<p>Being able to work for extended periods outside of the main trunk is also important. You will have to consider that as well.</p>\n\n<p>You may find that your software has a number of components that naturally group together. You could do something like this</p>\n\n<pre><code>/tag\n\n/core_library\n /branch\n /main\n\n/business_logic\n /branch\n /main\n\n/report_library\n /branch\n /main\n\n/my_ui\n /branch\n /main\n</code></pre>\n\n<p>There is no easy answer. What you do really depends on your specific project. If everything is still coming out a snarled mess then perhaps you need to look at how your project is designed and see if that can be changed to improve understanding.</p>\n"
},
{
"answer_id": 135959,
"author": "Chris Lawlor",
"author_id": 21245,
"author_profile": "https://Stackoverflow.com/users/21245",
"pm_score": -1,
"selected": false,
"text": "<p>I do it this way:</p>\n\n<ol>\n<li>Create the project in VS</li>\n<li>Import everything in the project folder to repos/projectname/trunk</li>\n<li>Add the repos/branches and repos/tags folders</li>\n</ol>\n\n<p>That gives me a repository structure like:</p>\n\n<pre><code>projectname\n / trunk\n /bin\n /obj\n /Properties\n projectname.sln\n /tags\n /branches\n</code></pre>\n\n<p>And I can just leave all of the files in their default places in the file system.</p>\n"
},
{
"answer_id": 136626,
"author": "JKueck",
"author_id": 6354,
"author_profile": "https://Stackoverflow.com/users/6354",
"pm_score": 1,
"selected": false,
"text": "<p>Another way:</p>\n\n<pre><code>StackOverflowIsAwesome\n /trunk\n /database\n /datafiles\n /documents\n /build\n /installer\n /lib \n /External_DAL (external that points to shared library)\n /utilities\n /vendor\n /src\n /StackOverFlowIsAwesome\n /StackOverFlowIsAwesome.csprj\n /bin\n /...\n /StackOverFlowIsAwesomeTests\n /StackOverFlowIsAwesomeTests.csprj\n /bin\n /...\n /branches\n /tags\n</code></pre>\n\n<p>This would be for each project. Since we are using a build script, we don't need store our solution file in SVN.</p>\n"
},
{
"answer_id": 138885,
"author": "Bert Huijben",
"author_id": 2094,
"author_profile": "https://Stackoverflow.com/users/2094",
"pm_score": 0,
"selected": false,
"text": "<p>For bigger projects we usually use this format here:</p>\n\n<pre><code>/Project\n /trunk\n /lib/ # Binary imports here (not in svn)\n\n /src # Solution file here\n /Libraries # Library assemblies here\n /StackOverflowIsAwesome.Common\n\n /Products # Delivered products here\n /StackOverflowIsAwesome.Site\n\n /Projects # internal assemblies here\n /StackOverflowIsAwesome.Tests\n /branches\n /1.x\n /tags\n /StackOverflowIsAwesome-1.0\n</code></pre>\n\n<p>Depending on the actual project non source files (documents, etc.) have a \ndirectory under the trunk root and extra development resources are under src.</p>\n\n<p>Independent projects under are under their own /Project root, but in the same repository.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18009/"
]
| This post is similar to [this previously asked question.](https://stackoverflow.com/questions/16829/structure-of-projects-in-version-control) I really want to set up my SVN repository in TTB format, but when creating a project in Visual Studio 2008 (ASP.NET/VB.NET), the structure created tends to be incompatible when considering the solution file, project files, folders for projects, multiple projects within solutions, etc. Does anyone have a script or procedure to take a newly created ASP.NET project and move it to a TTB format as painlessly as possible?
---
Let me be more specific. Suppose I have a project that I'm creating called StackOverflowIsAwesome. I can put that into my local folder structure (let's say that it's c:\working). When I create it, VS creates c:\working\StackOverflowIsAwesome and a whole bunch of subfolders (bin, app\_data, etc.). But I want my repository structure to look like...
```
StackOverflowIsAwesome
/trunk
/bin
/app_data
/tags
/branches
```
So, is there a clean way to do this consistently or do I need to resort to constantly moving/modifying files and folders to make this work? | We went with a very simplistic approach:
**File Structure:**
* Solution Folder (contains solution file, build scripts, maybe more?)
+ Project Folder
+ Project Folder 2
+ References (contains shared assemblies for the solution).
Then we just check the entire solution folder's contents into our repository. We use one repository for each solution. I'm not sure if this is the optimal way to organize the solution, but it works for us.
Also, we branch at the highest level, not per project. |
135,688 | <p>What is the proper way to modify environment variables like PATH in OS X?</p>
<p>I've looked on Google a little bit and found three different files to edit:</p>
<ul>
<li>/etc/paths</li>
<li>~/.profile</li>
<li>~/.tcshrc</li>
</ul>
<p>I don't even have some of these files, and I'm pretty sure that <em>.tcshrc</em> is wrong, since OS X uses bash now. Where are these variables, especially PATH, defined?</p>
<p>I'm running <a href="http://en.wikipedia.org/wiki/Mac_OS_X_Leopard" rel="noreferrer">OS X v10.5</a> (Leopard).</p>
| [
{
"answer_id": 135697,
"author": "tim_yates",
"author_id": 6509,
"author_profile": "https://Stackoverflow.com/users/6509",
"pm_score": 7,
"selected": false,
"text": "<p><strong><em>Up to and including <a href=\"http://en.wikipedia.org/wiki/Mac_OS_X_Lion\" rel=\"noreferrer\">OS X v10.7</a> (Lion)</em></strong> you can set them in:</p>\n\n<pre><code>~/.MacOSX/environment.plist\n</code></pre>\n\n<p>See:</p>\n\n<ul>\n<li><a href=\"https://developer.apple.com/legacy/library/qa/qa1067/_index.html\" rel=\"noreferrer\">https://developer.apple.com/legacy/library/qa/qa1067/_index.html</a></li>\n<li><a href=\"https://developer.apple.com/library/content/documentation/MacOSX/Conceptual/BPRuntimeConfig/Articles/EnvironmentVars.html\" rel=\"noreferrer\">https://developer.apple.com/library/content/documentation/MacOSX/Conceptual/BPRuntimeConfig/Articles/EnvironmentVars.html</a></li>\n</ul>\n\n<p>For PATH in the Terminal, you should be able to set in <code>.bash_profile</code> or <code>.profile</code> (you'll probably have to create it though)</p>\n\n<p><strong><em>For <a href=\"http://en.wikipedia.org/wiki/OS_X_Mountain_Lion\" rel=\"noreferrer\">OS X v10.8</a> (Mountain Lion) and beyond</em></strong> <a href=\"http://www.dowdandassociates.com/blog/content/howto-set-an-environment-variable-in-mac-os-x-slash-etc-slash-launchd-dot-conf/\" rel=\"noreferrer\">you need to use <code>launchd</code> and <code>launchctl</code></a>.</p>\n"
},
{
"answer_id": 135702,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 4,
"selected": false,
"text": "<p>Any of the Bash startup files -- <code>~/.bashrc</code>, <code>~/.bash_profile</code>, <code>~/.profile</code>. There's also some sort of weird file named <code>~/.MacOSX/environment.plist</code> for environment variables in GUI applications.</p>\n"
},
{
"answer_id": 135705,
"author": "mmaibaum",
"author_id": 12213,
"author_profile": "https://Stackoverflow.com/users/12213",
"pm_score": 2,
"selected": false,
"text": "<p>For a single user modification, use <code>~/.profile</code> of the ones you listed. The following link explains when the different files are read by Bash.</p>\n\n<p><a href=\"http://telin.ugent.be/~slippens/drupal/bashrc_and_others\" rel=\"nofollow noreferrer\">http://telin.ugent.be/~slippens/drupal/bashrc_and_others</a></p>\n\n<p>If you want to set the environment variable for gui applications you need the ~/.MacOSX/environment.plist file</p>\n"
},
{
"answer_id": 136182,
"author": "mike511",
"author_id": 9593,
"author_profile": "https://Stackoverflow.com/users/9593",
"pm_score": 2,
"selected": false,
"text": "<p>Well, I'm unsure about the <code>/etc/paths</code> and <code>~/.MacOSX/environment.plist</code> files. Those are new.</p>\n\n<p>But with Bash, you should know that <code>.bashrc</code> is executed with every new shell invocation\nand <code>.bash_profile</code> is only executed once at startup.</p>\n\n<p>I don't know how often this is with Mac OS X. I think the distinction has broken down with the window system launching everything.</p>\n\n<p>Personally, I eliminate the confusion by creating a <code>.bashrc</code> file with everything I need and then do:</p>\n\n<pre><code>ln -s .bashrc .bash_profile\n</code></pre>\n"
},
{
"answer_id": 450246,
"author": "Bruno Ranschaert",
"author_id": 4900,
"author_profile": "https://Stackoverflow.com/users/4900",
"pm_score": 4,
"selected": false,
"text": "<p>Sometimes all of the previous answers simply don't work. If you want to have access to a system variable (like <code>M2_HOME</code>) in Eclipse or in IntelliJ IDEA the only thing that works for me in this case is:</p>\n\n<p>First (step 1) edit <code>/etc/launchd.conf</code> to contain a line like this: \"setenv VAR value\" and then (step 2) reboot.</p>\n\n<p>Simply modifying .bash_profile won't work because in OS X the applications are not started as in other Unix'es; they don't inherit the parent's shell variables. All the other modifications won't work for a reason that is unknown to me. Maybe someone else can clarify about this.</p>\n"
},
{
"answer_id": 588442,
"author": "Matthew McCullough",
"author_id": 56039,
"author_profile": "https://Stackoverflow.com/users/56039",
"pm_score": 9,
"selected": false,
"text": "<p>Bruno is right on track. I've done extensive research and if you want to set variables that are available in all GUI applications, your only option is <code>/etc/launchd.conf</code>.</p>\n\n<p>Please note that <a href=\"https://web.archive.org/web/20100212232552/https://www.digitaledgesw.com/node/31\" rel=\"noreferrer\">environment.plist does not work for applications launched via Spotlight. This is documented by Steve Sexton here</a>.</p>\n\n<ol>\n<li><p>Open a terminal prompt</p></li>\n<li><p>Type <code>sudo vi /etc/launchd.conf</code> (note: this file might not yet exist)</p></li>\n<li><p>Put contents like the following into the file</p>\n\n<pre class=\"lang-none prettyprint-override\"><code># Set environment variables here so they are available globally to all apps\n# (and Terminal), including those launched via Spotlight.\n#\n# After editing this file run the following command from the terminal to update\n# environment variables globally without needing to reboot.\n# NOTE: You will still need to restart the relevant application (including\n# Terminal) to pick up the changes!\n# grep -E \"^setenv\" /etc/launchd.conf | xargs -t -L 1 launchctl\n#\n# See http://www.digitaledgesw.com/node/31\n# and http://stackoverflow.com/questions/135688/setting-environment-variables-in-os-x/\n#\n# Note that you must hardcode the paths below, don't use environment variables.\n# You also need to surround multiple values in quotes, see MAVEN_OPTS example below.\n#\nsetenv JAVA_VERSION 1.6\nsetenv JAVA_HOME /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home\nsetenv GROOVY_HOME /Applications/Dev/groovy\nsetenv GRAILS_HOME /Applications/Dev/grails\nsetenv NEXUS_HOME /Applications/Dev/nexus/nexus-webapp\nsetenv JRUBY_HOME /Applications/Dev/jruby\n\nsetenv ANT_HOME /Applications/Dev/apache-ant\nsetenv ANT_OPTS -Xmx512M\n\nsetenv MAVEN_OPTS \"-Xmx1024M -XX:MaxPermSize=512m\"\nsetenv M2_HOME /Applications/Dev/apache-maven\n\nsetenv JMETER_HOME /Applications/Dev/jakarta-jmeter\n</code></pre></li>\n<li><p>Save your changes in vi and reboot your Mac. Or use the <a href=\"http://linux.die.net/man/1/grep\" rel=\"noreferrer\"><code>grep</code></a>/<a href=\"https://linux.die.net/man/1/xargs\" rel=\"noreferrer\"><code>xargs</code></a> command which is shown in the code comment above.</p></li>\n<li><p>Prove that your variables are working by opening a Terminal window and typing <code>export</code> and you should see your new variables. These will also be available in IntelliJ IDEA and other GUI applications you launch via Spotlight.</p></li>\n</ol>\n"
},
{
"answer_id": 3756686,
"author": "Matt Curtis",
"author_id": 17221,
"author_profile": "https://Stackoverflow.com/users/17221",
"pm_score": 8,
"selected": false,
"text": "<h1>Don't expect ~/.launchd.conf to work</h1>\n<p>The man page for launchctl says that it never worked:</p>\n<blockquote>\n<p>DEPRECATED AND REMOVED FUNCTIONALITY</p>\n<p>launchctl no longer has an interactive mode, nor does it accept commands from stdin. The /etc/launchd.conf file is no longer consulted for subcommands to run during early boot time; this functionality was removed for security considerations. While it was documented that $HOME/.launchd.conf would be consulted prior to setting up a user's session, this functionality was never implemented.</p>\n</blockquote>\n<h1>How to set the environment for new processes started by Spotlight (without needing to reboot)</h1>\n<p>You can set the environment used by launchd (and, by extension, anything started from Spotlight) with <code>launchctl setenv</code>. For example to set the path:</p>\n<pre><code>launchctl setenv PATH /opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin\n</code></pre>\n<p>Or if you want to set up your path in <code>.bashrc</code> or similar, then have it mirrored in launchd:</p>\n<pre><code>PATH=/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin\nlaunchctl setenv PATH $PATH\n</code></pre>\n<p><strong>There's no need to reboot</strong> though you will need to restart an app if you want it to pick up the changed environment.</p>\n<p>This includes any shells already running under Terminal.app, although if you're there you can set the environment more directly, e.g. with <code>export PATH=/opt/local/bin:/opt/local/sbin:$PATH</code> for bash or zsh.</p>\n<h1>How to keeping changes after a reboot</h1>\n<h2>New method (since 10.10 Yosemite)</h2>\n<p>Use <code>launchctl config user path /bin:/usr/bin:/mystuff</code>. See <code>man launchctl</code> for more information.</p>\n<h2>Previous method</h2>\n<p>The launchctl man page quote at the top of this answer says the feature described here (reading <code>/etc/launchd.conf</code> at boot) was removed for security reasons, so ymmv.</p>\n<p>To <strong>keep changes after a reboot</strong> you can set the environment variables from <code>/etc/launchd.conf</code>, like so:</p>\n<pre><code>setenv PATH /opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin\n</code></pre>\n<p><code>launchd.conf</code> is executed automatically when you reboot.</p>\n<p>If you want these changes to take effect now, you should use this command to reprocess <code>launchd.conf</code> (thanks @mklement for the tip!)</p>\n<pre><code>egrep -v '^\\s*#' /etc/launchd.conf | launchctl\n</code></pre>\n<p>You can find out more about <code>launchctl</code> and how it loads <code>launchd.conf</code> with the command <code>man launchctl</code>.</p>\n"
},
{
"answer_id": 4336134,
"author": "Tom Teman",
"author_id": 458311,
"author_profile": "https://Stackoverflow.com/users/458311",
"pm_score": 3,
"selected": false,
"text": "<p>I think the OP is looking for a simple, Windows-like solution.</p>\n\n<p>Here you go:</p>\n\n<p><a href=\"http://www.apple.com/downloads/macosx/system_disk_utilities/environmentvariablepreferencepane.html\" rel=\"nofollow noreferrer\">http://www.apple.com/downloads/macosx/system_disk_utilities/environmentvariablepreferencepane.html</a></p>\n"
},
{
"answer_id": 4917147,
"author": "MiB",
"author_id": 427009,
"author_profile": "https://Stackoverflow.com/users/427009",
"pm_score": 2,
"selected": false,
"text": "<p>One thing to note in addition to the approaches suggested is that, in <a href=\"http://en.wikipedia.org/wiki/Mac_OS_X_Leopard\" rel=\"nofollow noreferrer\">OS X 10.5</a> (Leopard) at least, the variables set in <code>launchd.conf</code> will be merged with the settings made in <code>.profile</code>. I suppose this is likely to be valid for the settings in <code>~/.MacOSX/environment.plist</code> too, but I haven't verified.</p>\n"
},
{
"answer_id": 5444960,
"author": "pajato0",
"author_id": 91443,
"author_profile": "https://Stackoverflow.com/users/91443",
"pm_score": 5,
"selected": false,
"text": "<p>There are essentially two problems to solve when dealing with\nenvironment variables in OS X. The first is when invoking programs\nfrom Spotlight (the magnifying glass icon on the right side of the Mac\nmenu/status bar) and the second when invoking programs from the Dock.\nInvoking programs from a Terminal application/utility is trivial\nbecause it reads the environment from the standard shell locations\n(<code>~/.profile</code>, <code>~/.bash_profile</code>, <code>~/.bashrc</code>, etc.)</p>\n\n<p>When invoking programs from the Dock, use <code>~/.MacOSX/environment.plist</code>\nwhere the <code><dict></code> element contains a sequence of\n<code><key>KEY</key><string>theValue</string></code> elements.</p>\n\n<p>When invoking programs from Spotlight, ensure that launchd has been\nsetup with all the key/value settings you require.</p>\n\n<p>To solve both problems simultaneously, I use a login item (set via the\nSystem Preferences tool) on my User account. The login item is a bash script that\ninvokes an Emacs lisp function although one can of course use their\nfavorite scripting tool to accomplish the same thing. This approach\nhas the added benefit that it works at any time and does not require a\nreboot, i.e. one can edit <code>~/.profile</code>, run the login item in some shell and have the changes visible for newly invoked programs, from either the Dock or Spotlight.</p>\n\n<p>Details:</p>\n\n<p>Login item: <code>~/bin/macosx-startup</code></p>\n\n<pre><code>#!/bin/bash\nbash -l -c \"/Applications/Emacs.app/Contents/MacOS/Emacs --batch -l ~/lib/emacs/elisp/macosx/environment-support.el -f generate-environment\"\n</code></pre>\n\n<p>Emacs lisp function: <code>~/lib/emacs/elisp/macosx/envionment-support.el</code></p>\n\n<pre><code>;;; Provide support for the environment on Mac OS X\n\n(defun generate-environment ()\n \"Dump the current environment into the ~/.MacOSX/environment.plist file.\"\n ;; The system environment is found in the global variable:\n ;; 'initial-environment' as a list of \"KEY=VALUE\" pairs.\n (let ((list initial-environment)\n pair start command key value)\n ;; clear out the current environment settings\n (find-file \"~/.MacOSX/environment.plist\")\n (goto-char (point-min))\n (setq start (search-forward \"<dict>\\n\"))\n (search-forward \"</dict>\")\n (beginning-of-line)\n (delete-region start (point))\n (while list\n (setq pair (split-string (car list) \"=\")\n list (cdr list))\n (setq key (nth 0 pair)\n value (nth 1 pair))\n (insert \" <key>\" key \"</key>\\n\")\n (insert \" <string>\" value \"</string>\\n\")\n\n ;; Enable this variable in launchd\n (setq command (format \"launchctl setenv %s \\\"%s\\\"\" key value))\n (shell-command command))\n ;; Save the buffer.\n (save-buffer)))\n</code></pre>\n\n<p>NOTE: This solution is an amalgam of those coming before I added mine, particularly that offered by Matt Curtis, but I have deliberately tried to keep my <code>~/.bash_profile</code> content platform independent and put the setting of the <code>launchd</code> environment (a Mac only facility) into a separate script.</p>\n"
},
{
"answer_id": 6604397,
"author": "Russell B",
"author_id": 832593,
"author_profile": "https://Stackoverflow.com/users/832593",
"pm_score": 4,
"selected": false,
"text": "<p>After chasing the <a href=\"http://www.apple.com/downloads/macosx/system_disk_utilities/environmentvariablepreferencepane.html\" rel=\"nofollow\">Environment Variables preference pane</a> and discovering that the link is broken and a search on Apple's site seems to indicate they've forgotten about it... I started back onto the trail of the elusive launchd process.</p>\n\n<p>On my system (Mac OS X 10.6.8) it appears that variables defined in environment.plist <em>are</em> being reliably exported to apps launched from Spotlight (via launchd). My trouble is that those vars are not being exported to new bash sessions in Terminal. I.e. I have the opposite problem as portrayed here.</p>\n\n<p>NOTE: environment.plist looks like JSON, not XML, as described previously</p>\n\n<p>I was able to get Spotlight apps to see the vars by <a href=\"http://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPRuntimeConfig/Articles/EnvironmentVars.html%23//apple_ref/doc/uid/20002093-BCIJIJBH\" rel=\"nofollow\">editing ~/MacOSX/environment.plist</a> <strong>and</strong>\nI was able to force the same vars into a new Terminal session by adding the following to my .profile file:</p>\n\n<pre><code>eval $(launchctl export)\n</code></pre>\n"
},
{
"answer_id": 6640813,
"author": "Rabi",
"author_id": 438466,
"author_profile": "https://Stackoverflow.com/users/438466",
"pm_score": 0,
"selected": false,
"text": "<p>For Bash, try adding your environment variables to the file <code>/etc/profile</code> to make them available for all users. No need to reboot, just start a new Terminal session.</p>\n"
},
{
"answer_id": 8264813,
"author": "WoooHaaaa",
"author_id": 802585,
"author_profile": "https://Stackoverflow.com/users/802585",
"pm_score": 6,
"selected": false,
"text": "<ol>\n<li><p>Do:</p>\n\n<pre><code>vim ~/.bash_profile\n</code></pre>\n\n<p>The file may not exist (if not, you can just create it).</p></li>\n<li><p>Type in this and save the file:</p>\n\n<pre><code>export PATH=$PATH:YOUR_PATH_HERE\n</code></pre></li>\n<li><p>Run</p>\n\n<pre><code>source ~/.bash_profile\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 9821213,
"author": "Nicolas Wu",
"author_id": 72224,
"author_profile": "https://Stackoverflow.com/users/72224",
"pm_score": 3,
"selected": false,
"text": "<p>The <code>$PATH</code> variable is also subject to <code>path_helper</code>, which in turn makes use of the <code>/etc/paths</code> file and files in <code>/etc/paths.d</code>. </p>\n\n<p>A more thorough description can be found in <em><a href=\"http://hea-www.harvard.edu/~fine/OSX/path_helper.html\" rel=\"nofollow noreferrer\">PATH and other environment issues in Leopard</a></em> (2008-11)</p>\n"
},
{
"answer_id": 11514989,
"author": "Jason T. Miller",
"author_id": 933626,
"author_profile": "https://Stackoverflow.com/users/933626",
"pm_score": 4,
"selected": false,
"text": "<p>While the answers here aren't \"wrong\", I'll add another: never make environment variable changes in OS X that affect \"all processes\", or even, outside the shell, for all processes run interactively by a given user.</p>\n\n<p>In my experience, global changes to environment variables like PATH for all processes are even more likely to break things on OS X than on Windows. Reason being, lots of OS X applications and other software (including, perhaps especially, components of the OS itself) rely on UNIX command-line tools under the hood, and assume the behavior of the versions of these tools provided with the system, and don't necessarily use absolute paths when doing so (similar comments apply to dynamically-loaded libraries and DYLD_* environment variables). Consider, for instance, that the highest-rated answers to various Stack Overflow questions about replacing OS X-supplied versions of interpreters like Python and Ruby generally say \"don't do this.\"</p>\n\n<p>OS X is really no different than other UNIX-like operating systems (e.g., Linux, FreeBSD, and Solaris) in this respect; the most likely reason Apple doesn't provide an easy way to do this is because it <em>breaks things</em>. To the extent Windows isn't as prone to these problems, it's due to two things: (1) Windows software doesn't tend to rely on command-line tools to the extent that UNIX software does, and (2) Microsoft has had such an extensive history of both \"DLL hell\" and security problems caused by changes that affect all processes that they've changed the behavior of dynamic loading in newer Windows versions to limit the impact of \"global\" configuration options like PATH.</p>\n\n<p>\"Lame\" or not, you'll have a far more stable system if you restrict such changes to smaller scopes.</p>\n"
},
{
"answer_id": 14339426,
"author": "Big Rich",
"author_id": 304330,
"author_profile": "https://Stackoverflow.com/users/304330",
"pm_score": 5,
"selected": false,
"text": "<p>Another, free, opensource, Mac OS X v10.8 (Mountain Lion) Preference pane/environment.plist solution is <a href=\"http://diaryproducts.net/EnvPane\" rel=\"nofollow noreferrer\">EnvPane</a>.</p>\n\n<p>EnvPane's <a href=\"https://github.com/hschmidt/EnvPane\" rel=\"nofollow noreferrer\">source code</a> available on <a href=\"https://github.com/hschmidt/EnvPane\" rel=\"nofollow noreferrer\">GitHub</a>. EnvPane looks like it has comparable features to <a href=\"http://www.rubicode.com/Software/RCEnvironment\" rel=\"nofollow noreferrer\">RCEnvironment</a>, however, it seems it can update its stored variables instantly, i.e. <em>without</em> the need for a restart or login, which is welcome.</p>\n\n<p>As stated by the developer:</p>\n\n<blockquote>\n <p>EnvPane is a preference pane for Mac OS X 10.8 (Mountain Lion) that\n lets you set environment variables for all programs in both graphical\n and terminal sessions. Not only does it restore support for\n ~/.MacOSX/environment.plist in Mountain Lion, it also publishes your\n changes to the environment immediately, without the need to log out\n and back in.\n <SNIP>\n EnvPane includes (and automatically installs) a\n launchd agent that runs 1) early after login and 2) whenever the\n ~/.MacOSX/environment.plist changes. The agent reads\n ~/.MacOSX/environment.plist and exports the environment variables from\n that file to the current user's launchd instance via the same API that\n is used by launchctl setenv and launchctl unsetenv.</p>\n</blockquote>\n\n<p>Disclaimer: I am in no way related to the developer or his/her project.</p>\n\n<p>P.S. I like the name (sounds like 'Ends Pain').</p>\n"
},
{
"answer_id": 14501421,
"author": "Flori",
"author_id": 202151,
"author_profile": "https://Stackoverflow.com/users/202151",
"pm_score": 4,
"selected": false,
"text": "<p>On Mountain Lion all the <code>/etc/paths</code> and <code>/etc/launchd.conf</code> editing doesn't make any effect!</p>\n\n<p>Apple's Developer Forums say:</p>\n\n<blockquote>\n <p>\"Change the Info.plist of the .app itself to contain an \"LSEnvironment\"\n dictionary with the environment variables you want.</p>\n \n <p>~/.MacOSX/environment.plist is no longer supported.\"</p>\n</blockquote>\n\n<p>So I directly edited the application's <code>Info.plist</code> (right click on \"AppName.app\" (in this case SourceTree) and then \"<code>Show package contents</code>\").</p>\n\n<p><img src=\"https://i.stack.imgur.com/Z6ZHP.png\" alt=\"Show Package Contents\"></p>\n\n<p>And I added a new key/dict pair called:</p>\n\n<pre><code><key>LSEnvironment</key>\n<dict>\n <key>PATH</key>\n <string>/Users/flori/.rvm/gems/ruby-1.9.3-p362/bin:/Users/flori/.rvm/gems/ruby-1.9.3-p362@global/bin:/Users/flori/.rvm/rubies/ruby-1.9.3-p326/bin:/Users/flori/.rvm/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:</string>\n</dict>\n</code></pre>\n\n<p>(see: <a href=\"http://developer.apple.com/library/ios/#documentation/general/Reference/InfoPlistKeyReference/Articles/LaunchServicesKeys.html\" rel=\"nofollow noreferrer\">LaunchServicesKeys Documentation at Apple</a>)</p>\n\n<p><img src=\"https://i.stack.imgur.com/oiwcE.png\" alt=\"Enter image description here\"></p>\n\n<p>Now the application (in my case Sourcetree) uses the given path and works with Git 1.9.3 :-)</p>\n\n<p>PS: Of course you have to adjust the Path entry to your specific path needs.</p>\n"
},
{
"answer_id": 18972464,
"author": "wired00",
"author_id": 629222,
"author_profile": "https://Stackoverflow.com/users/629222",
"pm_score": 4,
"selected": false,
"text": "<p>Here is a very simple way to do what you want. In my case, it was getting Gradle to work (for Android Studio).</p>\n\n<ul>\n<li>Open up Terminal.</li>\n<li><p>Run the following command:</p>\n\n<p><code>sudo nano /etc/paths</code> or <code>sudo vim /etc/paths</code></p></li>\n<li><p>Enter your password, when prompted.</p></li>\n<li>Go to the bottom of the file, and enter the path you wish to add.</li>\n<li>Hit <kbd>Control</kbd> + <kbd>X</kbd> to quit.</li>\n<li>Enter 'Y' to save the modified buffer.</li>\n<li><p>Open a new terminal window then type:</p>\n\n<p><code>echo $PATH</code></p></li>\n</ul>\n\n<p>You should see the new path appended to the end of the PATH.</p>\n\n<p>I got these details from this post:</p>\n\n<p><em><a href=\"http://architectryan.com/2012/10/02/add-to-the-path-on-mac-os-x-mountain-lion/#.UkED3rxPp3Q\" rel=\"nofollow noreferrer\">Add to the PATH on Mac OS X 10.8 Mountain Lion and up</a></em></p>\n"
},
{
"answer_id": 20681139,
"author": "Charaf JRA",
"author_id": 1618189,
"author_profile": "https://Stackoverflow.com/users/1618189",
"pm_score": 2,
"selected": false,
"text": "<h2>Set up your PATH environment variable on Mac OS</h2>\n\n<p>Open the Terminal program (this is in your Applications/Utilities folder by default). Run the following command</p>\n\n<pre><code>touch ~/.bash_profile; open ~/.bash_profile\n</code></pre>\n\n<p>This will open the file in the your default text editor.</p>\n\n<p><strong>For Android SDK as example:</strong></p>\n\n<p>You need to add the path to your Android SDK platform-tools and tools directory. In my example I will use \"/Development/android-sdk-macosx\" as the directory the SDK is installed in. Add the following line:</p>\n\n<pre><code>export PATH=${PATH}:/Development/android-sdk-macosx/platform-tools:/Development/android-sdk-macosx/tools\n</code></pre>\n\n<p>Save the file and quit the text editor. Execute your .bash_profile to update your PATH:</p>\n\n<pre><code>source ~/.bash_profile\n</code></pre>\n\n<p>Now every time you open the Terminal program your PATH will include the Android SDK.</p>\n"
},
{
"answer_id": 21345598,
"author": "Fernando Martínez",
"author_id": 2115173,
"author_profile": "https://Stackoverflow.com/users/2115173",
"pm_score": 2,
"selected": false,
"text": "<p>It's simple:</p>\n\n<p>Edit ~/.profile and put your variables as follow</p>\n\n<blockquote>\n <p>$ vim ~/.profile</p>\n</blockquote>\n\n<p>In file put:</p>\n\n<blockquote>\n <p>MY_ENV_VAR=value</p>\n</blockquote>\n\n<ol>\n<li><p>Save ( :wq )</p></li>\n<li><p>Restart the terminal (Quit and open it again)</p></li>\n<li><p>Make sure that`s all be fine:</p></li>\n</ol>\n\n<blockquote>\n <p>$ echo $MY_ENV_VAR</p>\n \n <p>$ value</p>\n</blockquote>\n\n<hr>\n"
},
{
"answer_id": 21834243,
"author": "francois.robert",
"author_id": 1184693,
"author_profile": "https://Stackoverflow.com/users/1184693",
"pm_score": 2,
"selected": false,
"text": "<p>It's quite simple. Edit file <code>.profile</code> (vi, <a href=\"https://en.wikipedia.org/wiki/GNU_nano\" rel=\"nofollow noreferrer\">nano</a>, <a href=\"http://en.wikipedia.org/wiki/Sublime_Text\" rel=\"nofollow noreferrer\">Sublime Text</a> or other text editor) file. You can found it at the <code>~/</code> directory (user directory) and set like this:</p>\n\n<pre><code>export MY_VAR=[your value here]\n</code></pre>\n\n<p>Example with Java home:</p>\n\n<pre><code>export JAVA_HOME=/Library/Java/JavaVirtualMachines/current\n</code></pre>\n\n<p>Save it and return to the terminal.</p>\n\n<p>You can reload it with:</p>\n\n<pre><code>source .profile\n</code></pre>\n\n<p>Or close and open your terminal window.</p>\n"
},
{
"answer_id": 22075073,
"author": "courtlandj",
"author_id": 3201683,
"author_profile": "https://Stackoverflow.com/users/3201683",
"pm_score": 3,
"selected": false,
"text": "<p>Much like the answer Matt Curtis gave, I set environment variables via launchctl, but I wrap it in a function called export, so that whenever I export a variable like normal in my .bash_profile, it is also set by launchctl. Here is what I do:</p>\n\n<ol>\n<li><p>My .bash_profile consists solely of one line, (This is just personal preference.)</p>\n\n<pre><code>source .bashrc\n</code></pre></li>\n<li><p>My .bashrc has this:</p>\n\n<pre><code>function export()\n{\n builtin export \"$@\"\n if [[ ${#@} -eq 1 && \"${@//[^=]/}\" ]]\n then\n launchctl setenv \"${@%%=*}\" \"${@#*=}\"\n elif [[ ! \"${@//[^ ]/}\" ]]\n then\n launchctl setenv \"${@}\" \"${!@}\"\n fi\n}\n\nexport -f export\n</code></pre></li>\n<li><p>The above will overload the Bash builtin \"export\" and will export everything normally (you'll notice I export \"export\" with it!), then properly set them for OS X app environments via launchctl, whether you use any of the following:</p>\n\n<pre><code>export LC_CTYPE=en_US.UTF-8\n# ~$ launchctl getenv LC_CTYPE\n# en_US.UTF-8\nPATH=\"/usr/local/bin:${PATH}\"\nPATH=\"/usr/local/opt/coreutils/libexec/gnubin:${PATH}\"\nexport PATH\n# ~$ launchctl getenv PATH\n# /usr/local/opt/coreutils/libexec/gnubin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin\nexport CXX_FLAGS=\"-mmacosx-version-min=10.9\"\n# ~$ launchctl getenv CXX_FLAGS\n# -mmacosx-version-min=10.9\n</code></pre></li>\n<li><p>This way I don't have to send every variable to launchctl every time, and I can just have my .bash_profile / .bashrc set up the way I want. Open a terminal window, check out your environment variables you're interested in with <code>launchctl getenv myVar</code>, change something in your .bash_profile/.bashrc, close the terminal window and re-open it, check the variable again with launchctl, and voilá, it's changed.</p></li>\n<li><p>Again, like the other solutions for the post-Mountain Lion world, for any new environment variables to be available for apps, you need to launch or re-launch them after the change.</p></li>\n</ol>\n"
},
{
"answer_id": 26264377,
"author": "CodeOverRide",
"author_id": 1394838,
"author_profile": "https://Stackoverflow.com/users/1394838",
"pm_score": 3,
"selected": false,
"text": "<p>Just did this really easy and quick. First create a <strong>~/.bash_profile</strong> from terminal:</p>\n\n<pre><code>touch .bash_profile\n</code></pre>\n\n<p>then</p>\n\n<pre><code>open -a TextEdit.app .bash_profile\n</code></pre>\n\n<p>add</p>\n\n<pre><code>export TOMCAT_HOME=/Library/Tomcat/Home\n</code></pre>\n\n<p>save documement and you are done.</p>\n"
},
{
"answer_id": 26829886,
"author": "Claudio Floreani",
"author_id": 985792,
"author_profile": "https://Stackoverflow.com/users/985792",
"pm_score": 3,
"selected": false,
"text": "<p>To be concise and clear about what each file is intended for</p>\n\n<ul>\n<li><code>~/.profile</code> is sourced every time Terminal.app is launched</li>\n<li><code>~/.bashrc</code> is where \"traditionally\" all the export statements for Bash environment are set</li>\n<li><code>/etc/paths</code> is the main file in Mac OS that contains the list of default paths for building the PATH environment variable for all users</li>\n<li><code>/etc/paths.d/</code> contains files that hold additional search paths</li>\n</ul>\n\n<p>Non-terminal programs don't inherit the system wide PATH and MANPATH variables that your terminal does! To set environment for all processes launched by a specific user, thus making environment variables available to Mac OS X GUI applications, those variables must be defined in your <code>~/.MacOSX/environment.plist</code> (Apple Technical Q&A QA1067)</p>\n\n<p>Use the following command line to synchronize your <code>environment.plist</code> with <code>/etc/paths</code>:</p>\n\n<pre><code>defaults write $HOME/.MacOSX/environment PATH \"$(tr '\\n' ':' </etc/paths)\"\n</code></pre>\n"
},
{
"answer_id": 28078294,
"author": "ZOXIS",
"author_id": 1150275,
"author_profile": "https://Stackoverflow.com/users/1150275",
"pm_score": 2,
"selected": false,
"text": "<p>There are two type of shells at play here.</p>\n\n<ul>\n<li>Non-login: .bashrc is reloaded every time you start a new copy of Bash</li>\n<li>Login: The .profile is loaded only when you either login, or explicitly tell Bash to load it and use it as a login shell.</li>\n</ul>\n\n<p>It's important to understand here that with Bash, file <code>.bashrc</code> is only read by a shell that's both interactive and non-login, and you will find that people often load <code>.bashrc</code> in <code>.bash_profile</code> to overcome this limitation.</p>\n\n<p>Now that you have the basic understanding, let’s move on to how I would advice you to set it up.</p>\n\n<ul>\n<li>.profile: create it non-existing. Put your PATH setup in there.</li>\n<li>.bashrc: create if non-existing. Put all your aliases and custom methods in there.</li>\n<li>.bash_profile: create if non-existing. Put the following in there.</li>\n</ul>\n\n<p>.bash_file:</p>\n\n<pre><code>#!/bin/bash\nsource ~/.profile # Get the PATH settings\nsource ~/.bashrc # Get Aliases and Functions\n#\n</code></pre>\n"
},
{
"answer_id": 29905744,
"author": "Koray Tugay",
"author_id": 1173112,
"author_profile": "https://Stackoverflow.com/users/1173112",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Login Shells</strong></p>\n\n<pre><code>/etc/profile\n</code></pre>\n\n<p>The shell first executes the commands in file <code>/etc/profile</code>. A user working with root privileges can set up this file to establish systemwide default characteristics for users running Bash.</p>\n\n<pre><code>.bash_profile\n.bash_login\n.profile\n</code></pre>\n\n<p>Next the shell looks for <code>~/.bash_profile</code>, <code>~/.bash_login</code>, and <code>~/.profile</code> (~/ is short- hand for your home directory), in that order, executing the commands in the first of these files it finds. You can put commands in one of these files to override the defaults set in <code>/etc/profile</code>. A shell running on a virtual terminal does not execute commands in these files.</p>\n\n<pre><code>.bash_logout\n</code></pre>\n\n<p>When you log out, bash executes commands in the <code>~/.bash_logout</code> file. This file often holds commands that clean up after a session, such as those that remove temporary files.</p>\n\n<p><strong>Interactive Nonlogin Shells</strong></p>\n\n<pre><code>/etc/bashrc\n</code></pre>\n\n<p>Although not called by bash directly, many <code>~/.bashrc</code> files call <code>/etc/bashrc</code>. This setup allows a user working with root privileges to establish systemwide default characteristics for nonlogin bash shells.</p>\n\n<pre><code>.bashrc\n</code></pre>\n\n<p>An interactive nonlogin shell executes commands in the <code>~/.bashrc</code> file. Typically a startup file for a login shell, such as <code>.bash_profile</code>, runs this file, so both login and nonlogin shells run the commands in <code>.bashrc</code>.</p>\n\n<p><strong>Because commands in <code>.bashrc</code> may be executed many times, and because subshells inherit exported variables, it is a good idea to put commands that add to existing variables in the <code>.bash_profile</code> file.</strong></p>\n"
},
{
"answer_id": 32405815,
"author": "Ersin Er",
"author_id": 258474,
"author_profile": "https://Stackoverflow.com/users/258474",
"pm_score": 6,
"selected": false,
"text": "<h1>Solution for both command line and GUI applications from a single source (works with <a href=\"https://en.wikipedia.org/wiki/OS_X_Yosemite\" rel=\"noreferrer\">Mac OS X v10.10</a> (Yosemite) and <a href=\"https://en.wikipedia.org/wiki/OS_X_El_Capitan\" rel=\"noreferrer\">Mac OS X v10.11</a> (El Capitan))</h1>\n<p>Let's assume you have environment variable definitions in your <code>~/.bash_profile</code> like in the following snippet:</p>\n<pre><code>export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)"\nexport GOPATH="$HOME/go"\nexport PATH="$PATH:/usr/local/opt/go/libexec/bin:$GOPATH/bin"\nexport PATH="/usr/local/opt/coreutils/libexec/gnubin:$PATH"\nexport MANPATH="/usr/local/opt/coreutils/libexec/gnuman:$MANPATH"\n</code></pre>\n<p>We need a <em>Launch Agent</em> which will run on each login and anytime on demand which is going to load these variables to the user session. We'll also need a shell script to parse these definitions and build necessary commands to be executed by the agent.</p>\n<p>Create a file with <code>plist</code> suffix (e.g. named <code>osx-env-sync.plist</code>) in <code>~/Library/LaunchAgents/</code> directory with the following contents:</p>\n<pre><code><?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0">\n<dict>\n <key>Label</key>\n <string>osx-env-sync</string>\n <key>ProgramArguments</key>\n <array>\n <string>bash</string>\n <string>-l</string>\n <string>-c</string>\n <string>\n $HOME/.osx-env-sync.sh\n </string>\n </array>\n <key>RunAtLoad</key>\n <true/>\n</dict>\n</plist>\n</code></pre>\n<p><code>-l</code> parameter is critical here; it's necessary for executing the shell script with a <strong>login shell</strong> so that <code>~/.bash_profile</code> is sourced in the first place before this script is executed.</p>\n<p>Now, the shell script. Create it at <code>~/.osx-env-sync.sh</code> with the following contents:</p>\n<pre><code>grep export $HOME/.bash_profile | while IFS=' =' read ignoreexport envvar ignorevalue; do\n launchctl setenv "${envvar}" "${!envvar}"\ndone\n</code></pre>\n<p>Make sure the shell script is executable:</p>\n<pre><code>chmod +x ~/.osx-env-sync.sh\n</code></pre>\n<p>Now, load the launch agent for current session:</p>\n<pre><code>launchctl load ~/Library/LaunchAgents/osx-env-sync.plist\n</code></pre>\n<p>(Re)Launch a GUI application and verify that it can read the environment variables.</p>\n<p><em>The setup is persistent. It will survive restarts and relogins.</em></p>\n<p>After the initial setup (that you just did), if you want to reflect any changes in your <code>~/.bash_profile</code> to your whole environment again, rerunning the <code>launchctl load ...</code> command won't perform what you want; instead you'll get a warning like the following:</p>\n<p><code><$HOME>/Library/LaunchAgents/osx-env-sync.plist: Operation already in progress</code></p>\n<p>In order to reload your environment variables without going through the logout/login process do the following:</p>\n<pre><code>launchctl unload ~/Library/LaunchAgents/osx-env-sync.plist\nlaunchctl load ~/Library/LaunchAgents/osx-env-sync.plist\n</code></pre>\n<p>Finally make sure that you relaunch your already running applications (including Terminal.app) to make them aware of the changes.</p>\n<p>I've also pushed the code and explanations here to a GitHub project: <a href=\"https://github.com/ersiner/osx-env-sync\" rel=\"noreferrer\">osx-env-sync</a>.</p>\n<p>I hope this is going to be the ultimate solution, at least for the latest versions of OS X (Yosemite & El Capitan).</p>\n"
},
{
"answer_id": 32902449,
"author": "Max Leske",
"author_id": 219324,
"author_profile": "https://Stackoverflow.com/users/219324",
"pm_score": 4,
"selected": false,
"text": "<h3>Update (2017-08-04)</h3>\n\n<p>As of (at least) macOS 10.12.6 (Sierra) this method seems to have stopped working for Apache httpd (for both the <code>system</code> and the <code>user</code> option of <code>launchctl config</code>). Other programs do not seem to be affected. It is conceivable that this is a bug in httpd.</p>\n\n<h2>Original answer</h2>\n\n<p>This concerns OS X 10.10+ (10.11+ specifically due to rootless mode where <code>/usr/bin</code> is no longer writeable).</p>\n\n<p>I've read in multiple places that using <code>launchctl setenv PATH <new path></code> to set the <code>PATH</code> variable does not work due to a bug in OS X (which seems true from personal experience). I found that there's another way the <code>PATH</code> can be set for <em>applications not launched from the shell</em>:</p>\n\n<pre><code>sudo launchctl config user path <new path>\n</code></pre>\n\n<p>This option is documented in the launchctl man page:</p>\n\n<blockquote>\n <p>config system | user parameter value</p>\n \n <blockquote>\n <p>Sets persistent configuration information for launchd(8) domains. Only the system domain and user domains may be configured. The location of the persistent storage is an\n implementation detail, and changes to that storage should only be made through this subcommand. A reboot is required for changes made through this subcommand to take effect.</p>\n \n <p>[...]</p>\n \n <p>path</p>\n \n <blockquote>\n <p>Sets the PATH environment variable for all services within the target domain to the string value. The string value should conform to the format outlined for the\n PATH environment variable in environ(7). Note that if a service specifies its own PATH, the service-specific environment variable will take precedence.</p>\n \n <p>NOTE: This facility cannot be used to set general environment variables for all services within the domain. It is intentionally scoped to the PATH environment vari-\n able and nothing else for security reasons.</p>\n </blockquote>\n </blockquote>\n</blockquote>\n\n<p>I have confirmed this to work with a GUI application started from Finder (which uses <code>getenv</code> to get PATH).\nNote that you only have to do this once and the change will be persistent through reboots.</p>\n"
},
{
"answer_id": 48139773,
"author": "David",
"author_id": 7360,
"author_profile": "https://Stackoverflow.com/users/7360",
"pm_score": 3,
"selected": false,
"text": "<p>/etc/launchd.conf is not used in OS X v10.10 (Yosemite), OS X v10.11 (El Capitan), macOS v10.12 (Sierra), or macOS v10.13 (High Sierra).</p>\n\n<hr>\n\n<p>From the <code>launchctl</code> man page:</p>\n\n<pre><code>/etc/launchd.conf file is no longer consulted for subcommands to run during early boot time;\nthis functionality was removed for security considerations.\n</code></pre>\n\n<p>The method described in this <a href=\"https://apple.stackexchange.com/questions/106355/setting-the-system-wide-path-environment-variable-in-mavericks\"><em>Ask Different</em> answer</a> works for me (after a reboot): applications launched from the Dock or from Spotlight inherit environment variables that I set in <code>~/Library/LaunchAgents/my.startup.plist</code>. (In my case, I needed to set <code>LANG</code>, to <code>en_US.UTF-8</code>, for a Sublime Text plugin.)</p>\n"
},
{
"answer_id": 52823938,
"author": "suther",
"author_id": 1256697,
"author_profile": "https://Stackoverflow.com/users/1256697",
"pm_score": 2,
"selected": false,
"text": "<p>All the magic on iOS only goes with using <code>source</code> with the file, where you export your environment variables.</p>\n\n<p><strong>For example:</strong></p>\n\n<p>You can create an file like this:</p>\n\n<pre><code>export bim=fooo\nexport bom=bar\n</code></pre>\n\n<p>Save this file as <code>bimbom.env</code>, and do <code>source ./bimbom.ev</code>.\nVoilá, you got your environment variables.</p>\n\n<p>Check them with:</p>\n\n<pre><code>echo $bim\n</code></pre>\n"
},
{
"answer_id": 58517844,
"author": "Thushara Buddhika",
"author_id": 12162813,
"author_profile": "https://Stackoverflow.com/users/12162813",
"pm_score": 0,
"selected": false,
"text": "<p>My personal practice is <code>.bash_profile</code>. I'm adding paths there and append to Path variable,</p>\n\n<pre><code>GOPATH=/usr/local/go/bin/\nMYSQLPATH=/usr/local/opt/[email protected]/bin\n\nPATH=$PATH:$GOPATH:$MYSQLPATH\n</code></pre>\n\n<p>After then I can have individual Path by <code>echo $GOPATH</code>, <code>echo$MYSQLPATH</code> or all by <code>echo $PATH</code>.</p>\n"
},
{
"answer_id": 70959181,
"author": "Ben Carp",
"author_id": 7224430,
"author_profile": "https://Stackoverflow.com/users/7224430",
"pm_score": 3,
"selected": false,
"text": "<h1>Feb 2022 (MacOs 12+)</h1>\n<p>Solutions here should work after reboot or application restart.</p>\n<h2>CLI</h2>\n<p>Open your CLI of choice config file.</p>\n<ul>\n<li>For bash open <code>~/.bash_profile</code></li>\n<li>For zsh open <code>~/.zshrc</code></li>\n</ul>\n<p>add (or replace)</p>\n<pre><code>export varName=varValue \n</code></pre>\n<p>(if <code>varValue</code> has spaces in it - wrap it in <code>"</code>)</p>\n<p>Make sure to restart command line app.</p>\n<h2>GUI</h2>\n<p>Complete the CLI step.\nMake sure GUI app is closed.\nOpen GUI app from the command line. For example:</p>\n<pre><code>open /Applications/Sourcetree.app\n</code></pre>\n<p>(you can also alias this command in the <code>.zshrc</code>)</p>\n<h3>Principles</h3>\n<ul>\n<li>Mac does not have a configuration options that sets environment variable for all contexts.</li>\n<li>Avoid changing anything outside your user profile.</li>\n</ul>\n<h3>Doesn't work anymore</h3>\n<ul>\n<li><code>launchctl config user varName varVal</code> (MacOS 12.1+)</li>\n<li>Editing <code>/etc/launchd.conf</code></li>\n<li>xml file with <code>plist</code> suffix</li>\n</ul>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85/"
]
| What is the proper way to modify environment variables like PATH in OS X?
I've looked on Google a little bit and found three different files to edit:
* /etc/paths
* ~/.profile
* ~/.tcshrc
I don't even have some of these files, and I'm pretty sure that *.tcshrc* is wrong, since OS X uses bash now. Where are these variables, especially PATH, defined?
I'm running [OS X v10.5](http://en.wikipedia.org/wiki/Mac_OS_X_Leopard) (Leopard). | Bruno is right on track. I've done extensive research and if you want to set variables that are available in all GUI applications, your only option is `/etc/launchd.conf`.
Please note that [environment.plist does not work for applications launched via Spotlight. This is documented by Steve Sexton here](https://web.archive.org/web/20100212232552/https://www.digitaledgesw.com/node/31).
1. Open a terminal prompt
2. Type `sudo vi /etc/launchd.conf` (note: this file might not yet exist)
3. Put contents like the following into the file
```none
# Set environment variables here so they are available globally to all apps
# (and Terminal), including those launched via Spotlight.
#
# After editing this file run the following command from the terminal to update
# environment variables globally without needing to reboot.
# NOTE: You will still need to restart the relevant application (including
# Terminal) to pick up the changes!
# grep -E "^setenv" /etc/launchd.conf | xargs -t -L 1 launchctl
#
# See http://www.digitaledgesw.com/node/31
# and http://stackoverflow.com/questions/135688/setting-environment-variables-in-os-x/
#
# Note that you must hardcode the paths below, don't use environment variables.
# You also need to surround multiple values in quotes, see MAVEN_OPTS example below.
#
setenv JAVA_VERSION 1.6
setenv JAVA_HOME /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home
setenv GROOVY_HOME /Applications/Dev/groovy
setenv GRAILS_HOME /Applications/Dev/grails
setenv NEXUS_HOME /Applications/Dev/nexus/nexus-webapp
setenv JRUBY_HOME /Applications/Dev/jruby
setenv ANT_HOME /Applications/Dev/apache-ant
setenv ANT_OPTS -Xmx512M
setenv MAVEN_OPTS "-Xmx1024M -XX:MaxPermSize=512m"
setenv M2_HOME /Applications/Dev/apache-maven
setenv JMETER_HOME /Applications/Dev/jakarta-jmeter
```
4. Save your changes in vi and reboot your Mac. Or use the [`grep`](http://linux.die.net/man/1/grep)/[`xargs`](https://linux.die.net/man/1/xargs) command which is shown in the code comment above.
5. Prove that your variables are working by opening a Terminal window and typing `export` and you should see your new variables. These will also be available in IntelliJ IDEA and other GUI applications you launch via Spotlight. |
135,734 | <p>I am trying to learn Emacs and trying to find best keyboard layout for me. One thing is really annoying me. I have added following lines to .emacs</p>
<pre class="lang-lisp prettyprint-override"><code>(global-set-key "\C-y" 'scroll-up)
(global-set-key "\M-y" 'scroll-down)
</code></pre>
<p>When I hold <kbd>Control</kbd> and press <kbd>y</kbd> a few times, it will page down on every press of <kbd>y</kbd>.</p>
<p><strong>However</strong>, when I hold the <kbd>Windows</kbd> key (mapped as <kbd>Meta</kbd>) and press <kbd>y</kbd> a few times it will only page up on the <strong>first</strong> press of <kbd>y</kbd> and all subsequent presses of <kbd>y</kbd> I get the ‘y’ character inserted in the buffer.</p>
<p>Can the page up behave like page down? I want to hold <kbd>Meta</kbd> and keep pressing <kbd>y</kbd> to scroll multiple pages up.</p>
<p>I am using GNU Emacs 23.0.60.1 (i386-mingw-nt5.1.2600) of 2008-05-12 on LENNART-69DE564 (patched). It is Emacs with EmacsW32 patch. Is this problem with this Emacs? Problem with Meta key?</p>
<p>I tried original GNU Emacs (not patched) and it works OK with <kbd>Alt</kbd>. But my problem is not that I want to scroll without releasing any key. I release key <kbd>y</kbd> and press it multiple times but don't want to have to release <kbd>Meta</kbd> key. Same problem is described here:</p>
<p><a href="http://groups.google.com/group/gnu.emacs.help/browse_thread/thread/f30f4b75a8b75b10" rel="nofollow noreferrer">http://groups.google.com/group/gnu.emacs.help/browse_thread/thread/f30f4b75a8b75b10</a></p>
<p>Problem is not in that I have changed key mapping. It looks like it is a bug in EmacsW32 version. Here is another description of the problem:
<a href="http://www.nabble.com/23.0.60--Unreleased-Meta-Win-modifier-td19213327.html" rel="nofollow noreferrer">Unreleased Meta/Win modifier</a></p>
| [
{
"answer_id": 136427,
"author": "Andy",
"author_id": 3857,
"author_profile": "https://Stackoverflow.com/users/3857",
"pm_score": 3,
"selected": true,
"text": "<p>Could this be a side affect of using the Windows key as Meta? I'm thinking this because in a non-Emacs situation if you press and hold the Windows key and another key for a short cut (Win+E for Explorer, Win+R for Run dialog, etc.) the desired action only triggers once, not multiple times if you keep holding it down.</p>\n\n<p>I'd try reassigning Meta to Alt and see if the problem persists. If it doesn't, then I'm not sure what other option you have, since likely it's the OS only sending the Windows key press once to the app in focus.</p>\n"
},
{
"answer_id": 293829,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 3,
"selected": false,
"text": "<ol>\n<li>Use <code>C-v</code> and <code>M-v</code>.</li>\n<li>Don't change <code>C-y</code>, <code>M-y</code> default bindings.</li>\n</ol>\n"
},
{
"answer_id": 293865,
"author": "ahoka",
"author_id": 36399,
"author_profile": "https://Stackoverflow.com/users/36399",
"pm_score": 0,
"selected": false,
"text": "<p>You should use the patched EmacsW32 version, if you want the Windows key as Meta.</p>\n\n<p>From the site about the patches:</p>\n\n<p>\"Changes that makes it possible to use the window keyboard keys as META in Emacs. Without this patch key sequences like E will always do what they by default does in windows, ie in this case open up Windows Explorer. (This patched is not used by default, you have to turn it on.)\"</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/438025/"
]
| I am trying to learn Emacs and trying to find best keyboard layout for me. One thing is really annoying me. I have added following lines to .emacs
```lisp
(global-set-key "\C-y" 'scroll-up)
(global-set-key "\M-y" 'scroll-down)
```
When I hold `Control` and press `y` a few times, it will page down on every press of `y`.
**However**, when I hold the `Windows` key (mapped as `Meta`) and press `y` a few times it will only page up on the **first** press of `y` and all subsequent presses of `y` I get the ‘y’ character inserted in the buffer.
Can the page up behave like page down? I want to hold `Meta` and keep pressing `y` to scroll multiple pages up.
I am using GNU Emacs 23.0.60.1 (i386-mingw-nt5.1.2600) of 2008-05-12 on LENNART-69DE564 (patched). It is Emacs with EmacsW32 patch. Is this problem with this Emacs? Problem with Meta key?
I tried original GNU Emacs (not patched) and it works OK with `Alt`. But my problem is not that I want to scroll without releasing any key. I release key `y` and press it multiple times but don't want to have to release `Meta` key. Same problem is described here:
<http://groups.google.com/group/gnu.emacs.help/browse_thread/thread/f30f4b75a8b75b10>
Problem is not in that I have changed key mapping. It looks like it is a bug in EmacsW32 version. Here is another description of the problem:
[Unreleased Meta/Win modifier](http://www.nabble.com/23.0.60--Unreleased-Meta-Win-modifier-td19213327.html) | Could this be a side affect of using the Windows key as Meta? I'm thinking this because in a non-Emacs situation if you press and hold the Windows key and another key for a short cut (Win+E for Explorer, Win+R for Run dialog, etc.) the desired action only triggers once, not multiple times if you keep holding it down.
I'd try reassigning Meta to Alt and see if the problem persists. If it doesn't, then I'm not sure what other option you have, since likely it's the OS only sending the Windows key press once to the app in focus. |
135,745 | <p>I have a simple web service, it takes 2 parameters one is a simple xml security token, the other is usually a long xml string. It works with short strings but longer strings give a 400 error message. maxMessageLength did nothing to allow for longer strings.</p>
| [
{
"answer_id": 135809,
"author": "Yuval Peled",
"author_id": 20257,
"author_profile": "https://Stackoverflow.com/users/20257",
"pm_score": 2,
"selected": false,
"text": "<p>You should remove the quotas limitations as well.\nHere is how you can do it in code with Tcp binding. \nI have added some code that shows removal of timeout problems because usually sending very big arguments causes timeout issues. So use the code wisely...\nOf course, you can set these parameters in the config file as well.</p>\n\n<pre><code> NetTcpBinding binding = new NetTcpBinding(SecurityMode.None, true);\n\n // Allow big arguments on messages. Allow ~500 MB message.\n binding.MaxReceivedMessageSize = 500 * 1024 * 1024;\n\n // Allow unlimited time to send/receive a message. \n // It also prevents closing idle sessions. \n // From MSDN: To prevent the service from aborting idle sessions prematurely increase the Receive timeout on the service endpoint's binding.’\n binding.ReceiveTimeout = TimeSpan.MaxValue;\n binding.SendTimeout = TimeSpan.MaxValue;\n\n XmlDictionaryReaderQuotas quotas = new XmlDictionaryReaderQuotas();\n\n // Remove quotas limitations\n quotas.MaxArrayLength = int.MaxValue;\n quotas.MaxBytesPerRead = int.MaxValue;\n quotas.MaxDepth = int.MaxValue;\n quotas.MaxNameTableCharCount = int.MaxValue;\n quotas.MaxStringContentLength = int.MaxValue;\n binding.ReaderQuotas = quotas;\n</code></pre>\n"
},
{
"answer_id": 139003,
"author": "user22367",
"author_id": 22367,
"author_profile": "https://Stackoverflow.com/users/22367",
"pm_score": 2,
"selected": false,
"text": "<p>After the answer on quotas I just did all that in the web.config</p>\n\n<pre><code><bindings>\n <wsHttpBinding>\n <binding name=\"WSHttpBinding_IPayroll\" maxReceivedMessageSize=\"6553600\">\n <security mode=\"None\"/>\n <readerQuotas maxDepth=\"32\" \n maxStringContentLength=\"6553600\" \n maxArrayLength=\"16384\"\n maxBytesPerRead=\"4096\" \n maxNameTableCharCount=\"16384\" />\n </binding>\n </wsHttpBinding>\n</bindings>\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22367/"
]
| I have a simple web service, it takes 2 parameters one is a simple xml security token, the other is usually a long xml string. It works with short strings but longer strings give a 400 error message. maxMessageLength did nothing to allow for longer strings. | You should remove the quotas limitations as well.
Here is how you can do it in code with Tcp binding.
I have added some code that shows removal of timeout problems because usually sending very big arguments causes timeout issues. So use the code wisely...
Of course, you can set these parameters in the config file as well.
```
NetTcpBinding binding = new NetTcpBinding(SecurityMode.None, true);
// Allow big arguments on messages. Allow ~500 MB message.
binding.MaxReceivedMessageSize = 500 * 1024 * 1024;
// Allow unlimited time to send/receive a message.
// It also prevents closing idle sessions.
// From MSDN: To prevent the service from aborting idle sessions prematurely increase the Receive timeout on the service endpoint's binding.’
binding.ReceiveTimeout = TimeSpan.MaxValue;
binding.SendTimeout = TimeSpan.MaxValue;
XmlDictionaryReaderQuotas quotas = new XmlDictionaryReaderQuotas();
// Remove quotas limitations
quotas.MaxArrayLength = int.MaxValue;
quotas.MaxBytesPerRead = int.MaxValue;
quotas.MaxDepth = int.MaxValue;
quotas.MaxNameTableCharCount = int.MaxValue;
quotas.MaxStringContentLength = int.MaxValue;
binding.ReaderQuotas = quotas;
``` |
135,754 | <p>It is typical to have something like this in your cshrc file for setting the path:</p>
<pre><code>set path = ( . $otherpath $path )
</code></pre>
<p>but, the path gets duplicated when you source your cshrc file multiple times, how do you prevent the duplication?</p>
<p>EDIT: This is one unclean way of doing it:</p>
<pre><code>set localpaths = ( . $otherpaths )
echo ${path} | egrep -i "$localpaths" >& /dev/null
if ($status != 0) then
set path = ( . $otherpaths $path )
endif
</code></pre>
| [
{
"answer_id": 135783,
"author": "Andrew Stein",
"author_id": 13029,
"author_profile": "https://Stackoverflow.com/users/13029",
"pm_score": 0,
"selected": false,
"text": "<p>I always set my path from scratch in .cshrc.\nThat is I start off with a basic path, something like:</p>\n\n<pre><code>set path = (. ~/bin /bin /usr/bin /usr/ucb /usr/bin/X11)\n</code></pre>\n\n<p>(depending on the system).</p>\n\n<p>And then do:</p>\n\n<pre><code>set path = ($otherPath $path)\n</code></pre>\n\n<p>to add more stuff</p>\n"
},
{
"answer_id": 135831,
"author": "ShoeLace",
"author_id": 3825,
"author_profile": "https://Stackoverflow.com/users/3825",
"pm_score": 3,
"selected": true,
"text": "<p>you can use the following Perl script to prune paths of duplicates.</p>\n\n<hr>\n\n<pre><code>#!/usr/bin/perl\n#\n# ^^ ensure this is pointing to the correct location.\n#\n# Title: SLimPath\n# Author: David \"Shoe Lace\" Pyke <[email protected] >\n# : Tim Nelson \n# Purpose: To create a slim version of my envirnoment path so as to eliminate\n# duplicate entries and ensure that the \".\" path was last.\n# Date Created: April 1st 1999\n# Revision History:\n# 01/04/99: initial tests.. didn't wok verywell at all\n# : retreived path throught '$ENV' call\n# 07/04/99: After an email from Tim Nelson <[email protected]> got it to\n# work.\n# : used 'push' to add to array\n# : used 'join' to create a delimited string from a list/array.\n# 16/02/00: fixed cmd-line options to look/work better\n# 25/02/00: made verbosity level-oriented\n#\n#\n\nuse Getopt::Std;\n\nsub printlevel;\n\n$initial_str = \"\";\n$debug_mode = \"\";\n$delim_chr = \":\";\n$opt_v = 1;\n\ngetopts(\"v:hd:l:e:s:\");\n\nOPTS: {\n $opt_h && do {\nprint \"\\n$0 [-v level] [-d level] [-l delim] ( -e varname | -s strname | -h )\";\nprint \"\\nWhere:\";\nprint \"\\n -h This help\";\nprint \"\\n -d Debug level\";\nprint \"\\n -l Delimiter (between path vars)\";\nprint \"\\n -e Specify environment variable (NB: don't include \\$ sign)\";\nprint \"\\n -s String (ie. $0 -s \\$PATH:/looser/bin/)\";\nprint \"\\n -v Verbosity (0 = quiet, 1 = normal, 2 = verbose)\";\nprint \"\\n\";\n exit;\n };\n $opt_d && do {\n printlevel 1, \"You selected debug level $opt_d\\n\";\n $debug_mode = $opt_d;\n };\n $opt_l && do {\n printlevel 1, \"You are going to delimit the string with \\\"$opt_l\\\"\\n\";\n $delim_chr = $opt_l;\n };\n $opt_e && do {\n if($opt_s) { die \"Cannot specify BOTH env var and string\\n\"; }\n printlevel 1, \"Using Environment variable \\\"$opt_e\\\"\\n\";\n $initial_str = $ENV{$opt_e};\n };\n $opt_s && do {\n printlevel 1, \"Using String \\\"$opt_s\\\"\\n\";\n $initial_str = $opt_s;\n };\n}\n\nif( ($#ARGV != 1) and !$opt_e and !$opt_s){\n die \"Nothing to work with -- try $0 -h\\n\";\n}\n\n$what = shift @ARGV;\n# Split path using the delimiter\n@dirs = split(/$delim_chr/, $initial_str);\n\n$dest;\n@newpath = ();\nLOOP: foreach (@dirs){\n # Ensure the directory exists and is a directory\n if(! -e ) { printlevel 1, \"$_ does not exist\\n\"; next; }\n # If the directory is ., set $dot and go around again\n if($_ eq '.') { $dot = 1; next; }\n\n# if ($_ ne `realpath $_`){\n# printlevel 2, \"$_ becomes \".`realpath $_`.\"\\n\";\n# }\n undef $dest;\n #$_=Stdlib::realpath($_,$dest);\n # Check for duplicates and dot path\n foreach $adir (@newpath) { if($_ eq $adir) { \n printlevel 2, \"Duplicate: $_\\n\";\n next LOOP; \n }}\n\n push @newpath, $_;\n}\n\n# Join creates a string from a list/array delimited by the first expression\nprint join($delim_chr, @newpath) . ($dot ? $delim_chr.\".\\n\" : \"\\n\");\n\nprintlevel 1, \"Thank you for using $0\\n\";\nexit;\n\nsub printlevel {\n my($level, $string) = @_;\n\n if($opt_v >= $level) {\n print STDERR $string;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>i hope thats useful.</p>\n"
},
{
"answer_id": 136153,
"author": "mike511",
"author_id": 9593,
"author_profile": "https://Stackoverflow.com/users/9593",
"pm_score": 2,
"selected": false,
"text": "<p>ok, <strong>not</strong> in csh, but this is how I append $HOME/bin to my path in bash...</p>\n\n<pre><code>case $PATH in\n *:$HOME/bin | *:$HOME/bin:* ) ;;\n *) export PATH=$PATH:$HOME/bin\nesac\n</code></pre>\n\n<p>season to taste...</p>\n"
},
{
"answer_id": 137981,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": false,
"text": "<p>I've been using the following (Bourne/Korn/POSIX/Bash) script for most of a decade:</p>\n\n<pre><code>: \"@(#)$Id: clnpath.sh,v 1.6 1999/06/08 23:34:07 jleffler Exp $\"\n#\n# Print minimal version of $PATH, possibly removing some items\n\ncase $# in\n0) chop=\"\"; path=${PATH:?};;\n1) chop=\"\"; path=$1;;\n2) chop=$2; path=$1;;\n*) echo \"Usage: `basename $0 .sh` [$PATH [remove:list]]\" >&2\n exit 1;;\nesac\n\n# Beware of the quotes in the assignment to chop!\necho \"$path\" |\n${AWK:-awk} -F: '#\nBEGIN { # Sort out which path components to omit\n chop=\"'\"$chop\"'\";\n if (chop != \"\") nr = split(chop, remove); else nr = 0;\n for (i = 1; i <= nr; i++)\n omit[remove[i]] = 1;\n }\n{\n for (i = 1; i <= NF; i++)\n {\n x=$i;\n if (x == \"\") x = \".\";\n if (omit[x] == 0 && path[x]++ == 0)\n {\n output = output pad x;\n pad = \":\";\n }\n }\n print output;\n}'\n</code></pre>\n\n<p>In Korn shell, I use:</p>\n\n<pre><code>export PATH=$(clnpath /new/bin:/other/bin:$PATH /old/bin:/extra/bin)\n</code></pre>\n\n<p>This leaves me with PATH containing the new and other bin directories at the front, plus one copy of each directory name in the main path value, except that the old and extra bin directories have bin removed.</p>\n\n<p>You would have to adapt this to C shell (sorry - but I'm a great believer in the truths enunciated at <a href=\"http://www.faqs.org/faqs/unix-faq/shell/csh-whynot/\" rel=\"nofollow noreferrer\">C Shell Programming Considered Harmful</a>). Primarily, you won't have to fiddle with the colon separator, so life is actually easier.</p>\n"
},
{
"answer_id": 148702,
"author": "Steve Baker",
"author_id": 13566,
"author_profile": "https://Stackoverflow.com/users/13566",
"pm_score": 2,
"selected": false,
"text": "<p>Well, if you don't care what order your paths are in, you could do something like:</p>\n\n<pre><code>set path=(`echo $path | tr ' ' '\\n' | sort | uniq | tr '\\n' ' '`)\n</code></pre>\n\n<p>That will sort your paths and remove any extra paths that are the same. If you have . in your path, you may want to remove it with a grep -v and re-add it at the end.</p>\n"
},
{
"answer_id": 154979,
"author": "dr_pepper",
"author_id": 18415,
"author_profile": "https://Stackoverflow.com/users/18415",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a long one-liner without sorting:<br/>\nset path = ( <code>echo $path | tr ' ' '\\n' | perl -e 'while (<>) { print $_ unless $s{$_}++; }' | tr '\\n' ' '</code>)</p>\n"
},
{
"answer_id": 1761074,
"author": "Madhur Kashyap",
"author_id": 214331,
"author_profile": "https://Stackoverflow.com/users/214331",
"pm_score": 2,
"selected": false,
"text": "<p>dr_peper,</p>\n\n<p>I usually prefer to stick to scripting capabilities of the shell I am living in. Makes it more portable. So, I liked your solution using csh scripting. I just extended it to work on per dir in the localdirs to make it work for myself.</p>\n\n<pre>\nforeach dir ( $localdirs )\n echo ${path} | egrep -i \"$dir\" >& /dev/null\n if ($status != 0) then\n set path = ( $dir $path )\n endif\nend\n</pre>\n"
},
{
"answer_id": 5048977,
"author": "MestreLion",
"author_id": 624066,
"author_profile": "https://Stackoverflow.com/users/624066",
"pm_score": 4,
"selected": false,
"text": "<p>Im surprised no one used the <code>tr \":\" \"\\n\" | grep -x</code> techique to search if a given folder already exists in $PATH. Any reason not to?</p>\n\n<p>In 1 line:</p>\n\n<pre><code>if ! $(echo \"$PATH\" | tr \":\" \"\\n\" | grep -qx \"$dir\") ; then PATH=$PATH:$dir ; fi\n</code></pre>\n\n<p>Here is a function ive made myself to add several folders at once to $PATH (use \"aaa:bbb:ccc\" notation as argument), checking each one for duplicates before adding:</p>\n\n<pre><code>append_path()\n{\n local SAVED_IFS=\"$IFS\"\n local dir\n IFS=:\n for dir in $1 ; do\n if ! $( echo \"$PATH\" | tr \":\" \"\\n\" | grep -qx \"$dir\" ) ; then\n PATH=$PATH:$dir\n fi\n done\n IFS=\"$SAVED_IFS\"\n}\n</code></pre>\n\n<p>It can be called in a script like this:</p>\n\n<pre><code>append_path \"/test:$HOME/bin:/example/my dir/space is not an issue\"\n</code></pre>\n\n<p>It has the following advantages:</p>\n\n<ul>\n<li>No bashisms or any shell-specific syntax. It run perfectly with <code>!#/bin/sh</code> (ive tested with dash)</li>\n<li>Multiple folders can be added at once</li>\n<li>No sorting, preserves folder order</li>\n<li>Deals perfectly with spaces in folder names</li>\n<li>A single test works no matter if $folder is at begginning, end, middle, or is the only folder in $PATH (thus avoiding testing x:*, *:x, <em>:x:</em>, x, as many of the solutions here implicitly do)</li>\n<li>Works (and preserve) if $PATH begins or ends with \":\", or has \"::\" in it (meaning current folder)</li>\n<li>No <code>awk</code> or <code>sed</code> needed.</li>\n<li>EPA friendly ;) Original IFS value is preserved, and all other variables are local to the function scope.</li>\n</ul>\n\n<p>Hope that helps!</p>\n"
},
{
"answer_id": 9044243,
"author": "bnjf",
"author_id": 1175002,
"author_profile": "https://Stackoverflow.com/users/1175002",
"pm_score": 2,
"selected": false,
"text": "<p>Using sed(1) to remove duplicates. </p>\n\n<pre><code>$ PATH=$(echo $PATH | sed -e 's/$/:/;s/^/:/;s/:/::/g;:a;s#\\(:[^:]\\{1,\\}:\\)\\(.*\\)\\1#\\1\\2#g;ta;s/::*/:/g;s/^://;s/:$//;')\n</code></pre>\n\n<p>This will remove the duplicates after the first instance, which may or may not be what you want, e.g.:</p>\n\n<pre><code>$ NEWPATH=/bin:/usr/bin:/bin:/usr/local/bin:/usr/local/bin:/bin\n$ echo $NEWPATH | sed -e 's/$/:/; s/^/:/; s/:/::/g; :a; s#\\(:[^:]\\{1,\\}:\\)\\(.*\\)\\1#\\1\\2#g; t a; s/::*/:/g; s/^://; s/:$//;'\n/bin:/usr/bin:/usr/local/bin\n$\n</code></pre>\n\n<p>Enjoy!</p>\n"
},
{
"answer_id": 21564464,
"author": "jpabel",
"author_id": 3257507,
"author_profile": "https://Stackoverflow.com/users/3257507",
"pm_score": 1,
"selected": false,
"text": "<p>Here's what I use - perhaps someone else will find it useful:</p>\n\n<pre><code>#!/bin/csh\n# ABSTRACT\n# /bin/csh function-like aliases for manipulating environment\n# variables containing paths.\n#\n# BUGS\n# - These *MUST* be single line aliases to avoid parsing problems apparently related\n# to if-then-else\n# - Aliases currently perform tests in inefficient in order to avoid parsing problems\n# - Extremely fragile - use bash instead!!\n#\n# AUTHOR\n# J. P. Abelanet - 11/11/10\n\n# Function-like alias to add a path to the front of an environment variable\n# containing colon (':') delimited paths, without path duplication\n#\n# Usage: prepend_path ENVVARIABLE /path/to/prepend\nalias prepend_path \\\n 'set arg2=\"\\!:2\"; if ($?\\!:1 == 0) setenv \\!:1 \"$arg2\"; if ($?\\!:1 && $\\!:1 !~ {,*:}\"$arg2\"{:*,}) setenv \\!:1 \"$arg2\":\"$\\!:1\";'\n\n# Function-like alias to add a path to the back of any environment variable \n# containing colon (':') delimited paths, without path duplication\n#\n# Usage: append_path ENVVARIABLE /path/to/append\nalias append_path \\\n 'set arg2=\"\\!:2\"; if ($?\\!:1 == 0) setenv \\!:1 \"$arg2\"; if ($?\\!:1 && $\\!:1 !~ {,*:}\"$arg2\"{:*,}) setenv \\!:1 \"$\\!:1\":\"$arg2\";'\n</code></pre>\n"
},
{
"answer_id": 28584356,
"author": "BOC",
"author_id": 2051109,
"author_profile": "https://Stackoverflow.com/users/2051109",
"pm_score": 0,
"selected": false,
"text": "<p>I have the same need as the original question.\nBuilding on your previous answers, I have used in Korn/POSIX/Bash:</p>\n\n<pre><code>export PATH=$(perl -e 'print join \":\", grep {!$h{$_}++} split \":\", \"'$otherpath:$PATH\\\")\n</code></pre>\n\n<p>I had difficulties to translate it directly in csh (csh escape rules are insane). I have used (as suggested by dr_pepper):</p>\n\n<pre><code>set path = ( `echo $otherpath $path | tr ' ' '\\n' | perl -ne 'print $_ unless $h{$_}++' | tr '\\n' ' '`)\n</code></pre>\n\n<p>Do you have ideas to simplify it more (reduce the number of pipes) ?</p>\n"
},
{
"answer_id": 58641778,
"author": "Dotan Dimet",
"author_id": 117896,
"author_profile": "https://Stackoverflow.com/users/117896",
"pm_score": 1,
"selected": false,
"text": "<p>When setting path (lowercase, the csh variable) rather than PATH (the environment variable) in csh, you can use set -f and set -l, which will only keep one occurrence of each list element (preferring to keep either the first or last, respectively).</p>\n\n<p><a href=\"https://nature.berkeley.edu/~casterln/tcsh/Builtin_commands.html#set\" rel=\"nofollow noreferrer\">https://nature.berkeley.edu/~casterln/tcsh/Builtin_commands.html#set</a></p>\n\n<p>So something like this</p>\n\n<p><code>cat foo.csh # or .tcshrc or whatever:\nset -f path = (/bin /usr/bin . ) # initial value\nset -f path = ($path /mycode /hercode /usr/bin ) # add things, both new and duplicates\n</code></p>\n\n<p>Will not keep extending PATH with duplicates every time you <code>source</code> it:</p>\n\n<p><code>% source foo.csh\n % echo $PATH\n % /bin:/usr/bin:.:/mycode:/hercode\n % source foo.csh\n % echo $PATH\n % /bin:/usr/bin:.:/mycode:/hercode\n</code> </p>\n\n<p>set -f there ensures that only the first occurrence of each PATH element is kept.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18415/"
]
| It is typical to have something like this in your cshrc file for setting the path:
```
set path = ( . $otherpath $path )
```
but, the path gets duplicated when you source your cshrc file multiple times, how do you prevent the duplication?
EDIT: This is one unclean way of doing it:
```
set localpaths = ( . $otherpaths )
echo ${path} | egrep -i "$localpaths" >& /dev/null
if ($status != 0) then
set path = ( . $otherpaths $path )
endif
``` | you can use the following Perl script to prune paths of duplicates.
---
```
#!/usr/bin/perl
#
# ^^ ensure this is pointing to the correct location.
#
# Title: SLimPath
# Author: David "Shoe Lace" Pyke <[email protected] >
# : Tim Nelson
# Purpose: To create a slim version of my envirnoment path so as to eliminate
# duplicate entries and ensure that the "." path was last.
# Date Created: April 1st 1999
# Revision History:
# 01/04/99: initial tests.. didn't wok verywell at all
# : retreived path throught '$ENV' call
# 07/04/99: After an email from Tim Nelson <[email protected]> got it to
# work.
# : used 'push' to add to array
# : used 'join' to create a delimited string from a list/array.
# 16/02/00: fixed cmd-line options to look/work better
# 25/02/00: made verbosity level-oriented
#
#
use Getopt::Std;
sub printlevel;
$initial_str = "";
$debug_mode = "";
$delim_chr = ":";
$opt_v = 1;
getopts("v:hd:l:e:s:");
OPTS: {
$opt_h && do {
print "\n$0 [-v level] [-d level] [-l delim] ( -e varname | -s strname | -h )";
print "\nWhere:";
print "\n -h This help";
print "\n -d Debug level";
print "\n -l Delimiter (between path vars)";
print "\n -e Specify environment variable (NB: don't include \$ sign)";
print "\n -s String (ie. $0 -s \$PATH:/looser/bin/)";
print "\n -v Verbosity (0 = quiet, 1 = normal, 2 = verbose)";
print "\n";
exit;
};
$opt_d && do {
printlevel 1, "You selected debug level $opt_d\n";
$debug_mode = $opt_d;
};
$opt_l && do {
printlevel 1, "You are going to delimit the string with \"$opt_l\"\n";
$delim_chr = $opt_l;
};
$opt_e && do {
if($opt_s) { die "Cannot specify BOTH env var and string\n"; }
printlevel 1, "Using Environment variable \"$opt_e\"\n";
$initial_str = $ENV{$opt_e};
};
$opt_s && do {
printlevel 1, "Using String \"$opt_s\"\n";
$initial_str = $opt_s;
};
}
if( ($#ARGV != 1) and !$opt_e and !$opt_s){
die "Nothing to work with -- try $0 -h\n";
}
$what = shift @ARGV;
# Split path using the delimiter
@dirs = split(/$delim_chr/, $initial_str);
$dest;
@newpath = ();
LOOP: foreach (@dirs){
# Ensure the directory exists and is a directory
if(! -e ) { printlevel 1, "$_ does not exist\n"; next; }
# If the directory is ., set $dot and go around again
if($_ eq '.') { $dot = 1; next; }
# if ($_ ne `realpath $_`){
# printlevel 2, "$_ becomes ".`realpath $_`."\n";
# }
undef $dest;
#$_=Stdlib::realpath($_,$dest);
# Check for duplicates and dot path
foreach $adir (@newpath) { if($_ eq $adir) {
printlevel 2, "Duplicate: $_\n";
next LOOP;
}}
push @newpath, $_;
}
# Join creates a string from a list/array delimited by the first expression
print join($delim_chr, @newpath) . ($dot ? $delim_chr.".\n" : "\n");
printlevel 1, "Thank you for using $0\n";
exit;
sub printlevel {
my($level, $string) = @_;
if($opt_v >= $level) {
print STDERR $string;
}
}
```
---
i hope thats useful. |
135,755 | <p>How do you find the version of an installed Perl module?</p>
<p>This is in an answer down at the bottom, but I figure it important enough to live up here. With these suggestions, I create a function in my <code>.bashrc</code></p>
<pre><code>function perlmodver {
perl -M$1 -e 'print "Version " . $ARGV[0]->VERSION . " of " . $ARGV[0] . \
" is installed.\n"' $1
}
</code></pre>
| [
{
"answer_id": 135760,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 6,
"selected": false,
"text": "<p>Most modules (especially ones from The CPAN) have a $VERSION variable:</p>\n\n<pre><code>perl -MSome::Module -le 'print $Some::Module::VERSION'\n</code></pre>\n"
},
{
"answer_id": 135773,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 3,
"selected": false,
"text": "<p>If you are lucky, the module will have a package variable named <strong>$VERSION</strong>:</p>\n\n<pre><code>$ perl -MCPAN -e 'print \"$CPAN::VERSION\\n\"'\n1.9205\n</code></pre>\n\n<p>This is needed for modules to be distributed on CPAN, but internally developed modules might follow a different convention or none at all.</p>\n"
},
{
"answer_id": 135863,
"author": "cjm",
"author_id": 8355,
"author_profile": "https://Stackoverflow.com/users/8355",
"pm_score": 2,
"selected": false,
"text": "<p>I wrote a small script to report that: <a href=\"http://www.cjmweb.net/utilities/#perlver\" rel=\"nofollow noreferrer\">perlver</a>.</p>\n\n<blockquote>\n <p>This is a simple little tool that\n tells you what version of a module you\n have installed, and where the .pm file\n is located. It also ensures the module\n can be loaded successfully. It\n automatically converts ‘-’, ‘/’, or\n ‘\\’ to ‘::’, so you can use a pathname\n or distribution name instead of the\n canonical module name.</p>\n</blockquote>\n\n<p>It assumes that the module defines a $VERSION. If the module doesn't define a $VERSION, it will still tell you where the <code>.pm</code> file is, so you can examine it manually. You can also check several modules at once:</p>\n\n<pre><code>$ perlver CPAN DBD-Pg Getopt::Long\nCPAN 1.7602 is\n /usr/lib/perl5/5.8.8/CPAN.pm\nDBD::Pg 1.49 is\n /usr/lib/perl5/vendor_perl/5.8.8/i686-linux/DBD/Pg.pm\nGetopt::Long 2.36 is\n /usr/lib/perl5/vendor_perl/5.8.8/Getopt/Long.pm\n</code></pre>\n"
},
{
"answer_id": 135928,
"author": "tye",
"author_id": 21496,
"author_profile": "https://Stackoverflow.com/users/21496",
"pm_score": 1,
"selected": false,
"text": "<p>In addition, for modules that use Exporter.pm, you can get this information with this trick:</p>\n\n<pre><code>perl -MSome::Module=99999 -ex\nSome::Module version 99999 required--this is only version 1.9205 at ...\n</code></pre>\n\n<p>For modules that don't use Exporter.pm, a slightly longer trick reports the same information:</p>\n\n<pre><code>perl -e'use Some::Module 99999'\nSome::Module version 99999 required--this is only version 1.9205 at ...\n</code></pre>\n"
},
{
"answer_id": 135978,
"author": "Penfold",
"author_id": 11952,
"author_profile": "https://Stackoverflow.com/users/11952",
"pm_score": 5,
"selected": false,
"text": "<p>There is a less-typing trick, that works provided your module doesn't have something insane like a Unix timestamp as a version number.</p>\n\n<pre><code>perl -MFoo::Bar\\ 9999\n</code></pre>\n\n<p>This works because what it translates to is</p>\n\n<pre><code>use Foo::Bar 9999;\n</code></pre>\n\n<p>i.e. a version of Foo::Bar that's at least version 9999 or newer.\nAnd what you get is</p>\n\n<pre><code>Foo::Bar version 9999 required--this is only version 1.1.\nBEGIN failed--compilation aborted.\n</code></pre>\n\n<p>(Neat trick I learned from Matt Trout.)</p>\n"
},
{
"answer_id": 136218,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 7,
"selected": true,
"text": "<p>Why are you trying to get the version of the module? Do you need this from within a program, do you just need the number to pass to another operation, or are you just trying to find out what you have?</p>\n\n<p>I have this built into the <code>cpan</code> (which comes with perl) with the <code>-D</code> switch so you can see the version that you have installed and the current version on CPAN:</p>\n\n<pre>\n$ cpan -D Text::CSV_XS\n\nText::CSV_XS\n-------------------------------------------------------------------------\n Fast 8bit clean version of Text::CSV\n H/HM/HMBRAND/Text-CSV_XS-0.54.tgz\n /usr/local/lib/perl5/site_perl/5.8.8/darwin-2level/Text/CSV_XS.pm\n Installed: 0.32\n CPAN: 0.54 Not up to date\n H.Merijn Brand (HMBRAND)\n [email protected]\n</pre>\n\n<p>If you want to see all of the out-of-date modules, use the <code>-O</code> (capital O) switch:</p>\n\n<pre>\n$ cpan -O\nModule Name Local CPAN\n-------------------------------------------------------------------------\nApache::DB 0.1300 0.1400\nApache::SOAP 0.0000 0.7100\nApache::Session 1.8300 1.8700\nApache::SizeLimit 0.0300 0.9100\nApache::XMLRPC::Lite 0.0000 0.7100\n... and so on\n</pre>\n\n<p>If you want to see this for all modules you have installed, try the <code>-a</code> switch to create an autobundle.</p>\n"
},
{
"answer_id": 136229,
"author": "jmcnamara",
"author_id": 10238,
"author_profile": "https://Stackoverflow.com/users/10238",
"pm_score": 5,
"selected": false,
"text": "<p>VERSION is a <a href=\"http://perldoc.perl.org/UNIVERSAL.html\" rel=\"noreferrer\">UNIVERSAL</a> method of all Perl classes. You can use it to get the module version (if it has been set which it usually has). </p>\n\n<p>Here is a one liner where you only have to add the module name once:</p>\n\n<pre><code>perl -le 'eval \"require $ARGV[0]\" and print $ARGV[0]->VERSION' Some::Module\n</code></pre>\n"
},
{
"answer_id": 136304,
"author": "Dave Rolsky",
"author_id": 9832,
"author_profile": "https://Stackoverflow.com/users/9832",
"pm_score": 2,
"selected": false,
"text": "<p>Check out the <a href=\"http://search.cpan.org/dist/pmtools/\" rel=\"nofollow noreferrer\">pmtools</a> scripts on CPAN. If you're using a Debian(-based) distro, there's also a handy <a href=\"https://packages.debian.org/unstable/pmtools\" rel=\"nofollow noreferrer\"><em>pmtools</em> package</a>. This includes a script \"pmvers\" that tells you a module's version. It's quite handy.</p>\n\n<p>It does something similar to the various one-liners folks posted, but it's a bit smarter about error handling, and can give you the version of more than one module at once.</p>\n"
},
{
"answer_id": 136356,
"author": "Drew Stephens",
"author_id": 17339,
"author_profile": "https://Stackoverflow.com/users/17339",
"pm_score": 3,
"selected": false,
"text": "<p>Thanks for the answers! I've created a function in my .bashrc to easily find the version of a Perl module:</p>\n\n<pre><code>function perlmodver {\n perl -M$1 -e 'print $ARGV[0]->VERSION . \"\\n\"' $1\n} \n</code></pre>\n"
},
{
"answer_id": 21977953,
"author": "BMW",
"author_id": 498256,
"author_profile": "https://Stackoverflow.com/users/498256",
"pm_score": 1,
"selected": false,
"text": "<p>We have the system perl (/usr/bin/perl) in Solaris 10, and above solutions are useless. Some of them report \"module.pm is not installed\", some of them have no output.</p>\n\n<p>Here is the code which is helpful, which can list all modules and their version.</p>\n\n<pre><code>#!/usr/bin/perl\n\nuse strict;\nuse ExtUtils::Installed;\n\nmy @modules;\nmy $installed = ExtUtils::Installed->new();\n\nif (scalar(@ARGV) > 0) {\n\n @modules = @ARGV;\n\n} else {\n\n @modules = $installed->modules();\n\n}\n\nprint \"Module\\tVersion\\n\";\n\nforeach (@modules) {\n\n print $_ . \"\\t\" . $installed->version($_) . \"\\n\";\n\n}\n</code></pre>\n"
},
{
"answer_id": 31879196,
"author": "smonff",
"author_id": 954777,
"author_profile": "https://Stackoverflow.com/users/954777",
"pm_score": 0,
"selected": false,
"text": "<p>You can also take a look at <a href=\"https://metacpan.org/pod/module-version\" rel=\"nofollow\">App::module::version</a></p>\n\n<pre><code>$ module-version\n\nThe version of App::module::version in /home/yourself/perl5/lib/perl5 is 1.004\n</code></pre>\n"
},
{
"answer_id": 47397132,
"author": "Jpsy",
"author_id": 430742,
"author_profile": "https://Stackoverflow.com/users/430742",
"pm_score": 2,
"selected": false,
"text": "<p>Easiest to remember and most robust version for me:</p>\n\n<pre><code>perl -e 'use Search::Elasticsearch; print $Search::Elasticsearch::VERSION;'\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17339/"
]
| How do you find the version of an installed Perl module?
This is in an answer down at the bottom, but I figure it important enough to live up here. With these suggestions, I create a function in my `.bashrc`
```
function perlmodver {
perl -M$1 -e 'print "Version " . $ARGV[0]->VERSION . " of " . $ARGV[0] . \
" is installed.\n"' $1
}
``` | Why are you trying to get the version of the module? Do you need this from within a program, do you just need the number to pass to another operation, or are you just trying to find out what you have?
I have this built into the `cpan` (which comes with perl) with the `-D` switch so you can see the version that you have installed and the current version on CPAN:
```
$ cpan -D Text::CSV_XS
Text::CSV_XS
-------------------------------------------------------------------------
Fast 8bit clean version of Text::CSV
H/HM/HMBRAND/Text-CSV_XS-0.54.tgz
/usr/local/lib/perl5/site_perl/5.8.8/darwin-2level/Text/CSV_XS.pm
Installed: 0.32
CPAN: 0.54 Not up to date
H.Merijn Brand (HMBRAND)
[email protected]
```
If you want to see all of the out-of-date modules, use the `-O` (capital O) switch:
```
$ cpan -O
Module Name Local CPAN
-------------------------------------------------------------------------
Apache::DB 0.1300 0.1400
Apache::SOAP 0.0000 0.7100
Apache::Session 1.8300 1.8700
Apache::SizeLimit 0.0300 0.9100
Apache::XMLRPC::Lite 0.0000 0.7100
... and so on
```
If you want to see this for all modules you have installed, try the `-a` switch to create an autobundle. |
135,759 | <p>Why can't I create a <code>class</code> in <code>VB.NET</code> that <code>inherits</code> <code>System.IO.Directory</code>? According to Lutz Roeder, it is <em>not</em> declared as <code>NotInheritable</code>!</p>
<p>I want to create a <code>utility class</code> that adds functionality to the <code>Directory class</code>. For instance, I want to add a <code>Directory.Move</code> function.</p>
<p>Please advise and I will send you a six pack. OK nevermind I'm not sending you anything but if you come to the bar tonight I will hook you up and then beat you in pool.</p>
| [
{
"answer_id": 135766,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 3,
"selected": false,
"text": "<p>Are you using <s>C# 3.0</s> VB.NET 2008 -- then you could add an <a href=\"http://msdn.microsoft.com/en-us/library/bb384936.aspx\" rel=\"noreferrer\">Extension Method</a></p>\n"
},
{
"answer_id": 135771,
"author": "Austin Salonen",
"author_id": 4068,
"author_profile": "https://Stackoverflow.com/users/4068",
"pm_score": 1,
"selected": false,
"text": "<p>If you use the DirectoryInfo class, you will have access to a MoveTo function.</p>\n\n<p>EDIT: I'll correct myself... The static Directory class already has a Move method.</p>\n"
},
{
"answer_id": 135772,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 5,
"selected": true,
"text": "<p>From the Meta Data of .NET</p>\n\n<pre><code>namespace System.IO\n{\n // Summary:\n // Exposes static methods for creating, moving, and enumerating through directories\n // and subdirectories. This class cannot be inherited.\n [ComVisible(true)]\n public static class Directory\n</code></pre>\n\n<p>You cannot inherit from a Static Class.</p>\n"
},
{
"answer_id": 136601,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I'd guess that Reflector isn't picking up the sealed attribute correctly for VB (or perhaps just not displaying it properly). If you look at the IL, it is sealed:</p>\n\n<p>class public abstract auto ansi <strong>sealed</strong> beforefieldinit Directory</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54420/"
]
| Why can't I create a `class` in `VB.NET` that `inherits` `System.IO.Directory`? According to Lutz Roeder, it is *not* declared as `NotInheritable`!
I want to create a `utility class` that adds functionality to the `Directory class`. For instance, I want to add a `Directory.Move` function.
Please advise and I will send you a six pack. OK nevermind I'm not sending you anything but if you come to the bar tonight I will hook you up and then beat you in pool. | From the Meta Data of .NET
```
namespace System.IO
{
// Summary:
// Exposes static methods for creating, moving, and enumerating through directories
// and subdirectories. This class cannot be inherited.
[ComVisible(true)]
public static class Directory
```
You cannot inherit from a Static Class. |
135,775 | <p>Any ideas on how i get MVP working with Silverlight? How Do I get around the fact there is no load event raised?</p>
<p>This the view I have:</p>
<pre><code> public partial class Person: IPersonView
{
public event RoutedEventHandler Loaded;
public Person()
{
new PersonPresenter(this);
InitializeComponent();
}
public Person Person
{
set { Person.ItemsSource = value; }
}
}
</code></pre>
<p>And my presenter:</p>
<pre><code> public class PersonPresenter
{
private readonly IPersonView _view;
private readonly ServiceContractClient _client;
public PersonPresenter(IPersonView view)
{
_client = new ServiceContractClient();
_view = view;
WireUpEvents();
}
private void WireUpEvents()
{
_view.Loaded += Load;
}
private void Load(object sender, EventArgs e)
{
_client.GetPersonCompleted += Client_GetPerson;
_client.GetPersonAsync();
}
private void Client_GetPerson(object sender, GetPersonCompletedEventArgs e)
{
_view.Person= e.Result;
}
}
</code></pre>
<p>Nothing happened for me as the Loaded event dont seem to get called, how do i get around this?</p>
| [
{
"answer_id": 135964,
"author": "Santiago Palladino",
"author_id": 12791,
"author_profile": "https://Stackoverflow.com/users/12791",
"pm_score": 1,
"selected": false,
"text": "<p>I believe the loaded event gets called when the control has been initialized, loaded, rendered and ready for use. This means that as long as you don't place it inside a visible container (so that it is rendered), the loaded event won't be risen.</p>\n"
},
{
"answer_id": 153018,
"author": "ANaimi",
"author_id": 2721,
"author_profile": "https://Stackoverflow.com/users/2721",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://timross.wordpress.com/2008/03/16/implementing-the-mvp-pattern-in-silverlight/\" rel=\"nofollow noreferrer\">Tim Ross</a> has a good introduction to Silverlight MVP implementation, with source code.</p>\n"
},
{
"answer_id": 267218,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<h2>You may consider using <a href=\"http://www.mvcsharp.org\" rel=\"nofollow noreferrer\">MVC#</a> - a Model View Presenter framework with Silverlight 2.0 support.</h2>\n\n<p>Oleg Zhukov</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230/"
]
| Any ideas on how i get MVP working with Silverlight? How Do I get around the fact there is no load event raised?
This the view I have:
```
public partial class Person: IPersonView
{
public event RoutedEventHandler Loaded;
public Person()
{
new PersonPresenter(this);
InitializeComponent();
}
public Person Person
{
set { Person.ItemsSource = value; }
}
}
```
And my presenter:
```
public class PersonPresenter
{
private readonly IPersonView _view;
private readonly ServiceContractClient _client;
public PersonPresenter(IPersonView view)
{
_client = new ServiceContractClient();
_view = view;
WireUpEvents();
}
private void WireUpEvents()
{
_view.Loaded += Load;
}
private void Load(object sender, EventArgs e)
{
_client.GetPersonCompleted += Client_GetPerson;
_client.GetPersonAsync();
}
private void Client_GetPerson(object sender, GetPersonCompletedEventArgs e)
{
_view.Person= e.Result;
}
}
```
Nothing happened for me as the Loaded event dont seem to get called, how do i get around this? | [Tim Ross](http://timross.wordpress.com/2008/03/16/implementing-the-mvp-pattern-in-silverlight/) has a good introduction to Silverlight MVP implementation, with source code. |
135,777 | <h2>Seeking a method to:</h2>
<h2>Take whitespace separated tokens in a String; return a suggested Word</h2>
<p><br>
<strong>ie:</strong><br>
Google Search can take <em>"fonetic wrd nterpreterr"</em>,<br>
and atop of the result page it shows <em>"Did you mean: phonetic word interpreter"</em></p>
<p><em>A solution in any of the C* languages or Java would be preferred.</em></p>
<p><br>
<strong>Are there any existing Open Libraries which perform such functionality?</strong></p>
<p><strong>Or is there a way to Utilise a Google API to request a suggested word?</strong></p>
| [
{
"answer_id": 135791,
"author": "jeannicolas",
"author_id": 14981,
"author_profile": "https://Stackoverflow.com/users/14981",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the yahoo web service here:\n<a href=\"http://developer.yahoo.com/search/web/V1/spellingSuggestion.html\" rel=\"nofollow noreferrer\">http://developer.yahoo.com/search/web/V1/spellingSuggestion.html</a></p>\n\n<p>However it's only a web service... (i.e. there are no APIs for other language etc..) but it outputs JSON or XML, so... pretty easy to adapt to any language...</p>\n"
},
{
"answer_id": 696948,
"author": "Ralph M. Rickenbach",
"author_id": 4549416,
"author_profile": "https://Stackoverflow.com/users/4549416",
"pm_score": 2,
"selected": false,
"text": "<p>You can also use the Google API's to spell check. There is an ASP implementation <a href=\"http://www.asp101.com/articles/jeremy/googlespell/default.asp\" rel=\"nofollow noreferrer\">here</a> (I'm not to credit for this, though).</p>\n"
},
{
"answer_id": 707323,
"author": "Jonathan C Dickinson",
"author_id": 24064,
"author_profile": "https://Stackoverflow.com/users/24064",
"pm_score": 2,
"selected": false,
"text": "<p>First off:</p>\n\n<ul>\n<li><a href=\"http://jazzy.sourceforge.net/\" rel=\"nofollow noreferrer\" title=\"Java Library\">Java</a></li>\n<li><a href=\"http://www.codeproject.com/KB/recipes/spellchecker_mg.aspx\" rel=\"nofollow noreferrer\" title=\"C++ Library\">C++</a></li>\n<li><a href=\"http://www.loresoft.com/projects/netspell/default.aspx\" rel=\"nofollow noreferrer\" title=\".Net Library\">C#</a></li>\n</ul>\n\n<p>Use the one of your choice. I suspect it runs the query against a spell-checking engine with a word limit of exactly one, it then does nothing if the entire query is valid, otherwise it replaces each word with that word's best match. In other words, the following algorithm (an empty return string means that the query had no problems):</p>\n\n<pre><code>startup()\n{\n set the spelling engines word suggestion limit to 1\n}\n\noption 1()\n{\n int currentPosition = engine.NextWord(start the search at word 0, querystring);\n\n if(currentPosition == -1)\n return empty string; // Query is a-ok.\n\n while(currentPosition != -1)\n {\n queryString = engine.ReplaceWord(engine.CurrentWord, queryString, the suggestion with index 0);\n currentPosition = engine.NextWord(currentPosition, querystring);\n }\n\n return queryString;\n}\n</code></pre>\n"
},
{
"answer_id": 707367,
"author": "Mike Dunlavey",
"author_id": 23771,
"author_profile": "https://Stackoverflow.com/users/23771",
"pm_score": 1,
"selected": false,
"text": "<p>If you have a dictionary stored as a trie, there is a fairly straightforward way to find best-matching entries, where characters can be inserted, deleted, or replaced.</p>\n\n<pre><code>void match(trie t, char* w, string s, int budget){\n if (budget < 0) return;\n if (*w=='\\0') print s;\n foreach (char c, subtrie t1 in t){\n /* try matching or replacing c */\n match(t1, w+1, s+c, (*w==c ? budget : budget-1));\n /* try deleting c */\n match(t1, w, s, budget-1);\n }\n /* try inserting *w */\n match(t, w+1, s + *w, budget-1);\n}\n</code></pre>\n\n<p>The idea is that first you call it with a budget of zero, and see if it prints anything out. Then try a budget of 1, and so on, until it prints out some matches. The bigger the budget the longer it takes. You might want to only go up to a budget of 2.</p>\n\n<p>Added: It's not too hard to extend this to handle common prefixes and suffixes. For example, English prefixes like \"un\", \"anti\" and \"dis\" can be in the dictionary, and can then link back to the top of the dictionary. For suffixes like \"ism\", \"'s\", and \"ed\" there can be a separate trie containing just the suffixes, and most words can link to that suffix trie. Then it can handle strange words like \"antinationalizationalization\".</p>\n"
},
{
"answer_id": 707502,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 5,
"selected": true,
"text": "<p>In his article <a href=\"http://norvig.com/spell-correct.html\" rel=\"nofollow noreferrer\">How to Write a Spelling Corrector</a>, Peter Norvig discusses how a Google-like spellchecker could be implemented. The article contains a 20-line implementation in Python, as well as links to several reimplementations in C, C++, C# and Java. Here is an excerpt:</p>\n\n<blockquote>\n <p>The full details of an\n industrial-strength spell corrector\n like Google's would be more confusing\n than enlightening, but I figured that\n on the plane flight home, in less than\n a page of code, I could write a toy\n spelling corrector that achieves 80 or\n 90% accuracy at a processing speed of\n at least 10 words per second.</p>\n</blockquote>\n\n<p>Using Norvig's code and <a href=\"http://www.phon.ucl.ac.uk/home/johnm/ptlc2005/pdf/ptlcp56.pdf\" rel=\"nofollow noreferrer\">this text</a> as training set, i get the following results:</p>\n\n<pre><code>>>> import spellch\n>>> [spellch.correct(w) for w in 'fonetic wrd nterpreterr'.split()]\n['phonetic', 'word', 'interpreters']\n</code></pre>\n"
},
{
"answer_id": 710960,
"author": "StaxMan",
"author_id": 59501,
"author_profile": "https://Stackoverflow.com/users/59501",
"pm_score": 2,
"selected": false,
"text": "<p>Since no one has yet mentioned it, I'll give one more phrase to search for: \"edit distance\" (for example, <a href=\"http://en.wikipedia.org/wiki/Levenshtein_distance\" rel=\"nofollow noreferrer\">link text</a>).\nThat can be used to find closest matches, assuming it's typos where letters are transposed, missing or added.</p>\n\n<p>But usually this is also coupled with some sort of relevancy information; either by simple popularity (to assume most commonly used close-enough match is most likely correct word), or by contextual likelihood (words that follow preceding correct word, or come before one). This gets into information retrieval; one way to start is to look at bigram and trigrams (sequences of words seen together). Google has very extensive freely available data sets for these.</p>\n\n<p>For simple initial solution though a dictionary couple with Levenshtein-based matchers works surprisingly well.</p>\n"
},
{
"answer_id": 716938,
"author": "friol",
"author_id": 23034,
"author_profile": "https://Stackoverflow.com/users/23034",
"pm_score": 1,
"selected": false,
"text": "<p>The <a href=\"http://code.google.com/intl/it/apis/soapsearch/reference.html#1_3\" rel=\"nofollow noreferrer\">Google SOAP Search APIs</a> do that.</p>\n"
},
{
"answer_id": 718607,
"author": "wentbackward",
"author_id": 87100,
"author_profile": "https://Stackoverflow.com/users/87100",
"pm_score": 2,
"selected": false,
"text": "<p>You could plug Lucene, which has a dictionary facility implementing the Levenshtein distance method.</p>\n\n<p>Here's an example from the Wiki, where 2 is the distance.</p>\n\n<pre><code>String[] l=spellChecker.suggestSimilar(\"sevanty\", 2);\n//l[0] = \"seventy\"\n</code></pre>\n\n<ul>\n<li><a href=\"http://wiki.apache.org/lucene-java/SpellChecker\" rel=\"nofollow noreferrer\">http://wiki.apache.org/lucene-java/SpellChecker</a></li>\n<li>An older link <a href=\"http://today.java.net/pub/a/today/2005/08/09/didyoumean.html\" rel=\"nofollow noreferrer\">http://today.java.net/pub/a/today/2005/08/09/didyoumean.html</a></li>\n</ul>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4857/"
]
| Seeking a method to:
--------------------
Take whitespace separated tokens in a String; return a suggested Word
---------------------------------------------------------------------
**ie:**
Google Search can take *"fonetic wrd nterpreterr"*,
and atop of the result page it shows *"Did you mean: phonetic word interpreter"*
*A solution in any of the C\* languages or Java would be preferred.*
**Are there any existing Open Libraries which perform such functionality?**
**Or is there a way to Utilise a Google API to request a suggested word?** | In his article [How to Write a Spelling Corrector](http://norvig.com/spell-correct.html), Peter Norvig discusses how a Google-like spellchecker could be implemented. The article contains a 20-line implementation in Python, as well as links to several reimplementations in C, C++, C# and Java. Here is an excerpt:
>
> The full details of an
> industrial-strength spell corrector
> like Google's would be more confusing
> than enlightening, but I figured that
> on the plane flight home, in less than
> a page of code, I could write a toy
> spelling corrector that achieves 80 or
> 90% accuracy at a processing speed of
> at least 10 words per second.
>
>
>
Using Norvig's code and [this text](http://www.phon.ucl.ac.uk/home/johnm/ptlc2005/pdf/ptlcp56.pdf) as training set, i get the following results:
```
>>> import spellch
>>> [spellch.correct(w) for w in 'fonetic wrd nterpreterr'.split()]
['phonetic', 'word', 'interpreters']
``` |
135,782 | <p>A lot of my C# code follows this pattern:</p>
<pre><code>void foo(string param1, string param2, string param3)
{
try
{
// do something...
}
catch(Exception ex)
{
LogError(String.Format("Error in foo(param1={0}, param2={1}, param3={2}), exception={3}", param1, param2, param3, ex.Message));
}
}
</code></pre>
<p>Is there a way in .NET to get a Key/Value list of the parameters to a function so that I can call another function to construct my error logging string?
OR
Do you have a more generic / better way of doing this?</p>
| [
{
"answer_id": 135813,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 1,
"selected": false,
"text": "<p>When I have done this I just created a generic dictionary for the logging.</p>\n\n<p>I have this LogArgs class. And logging in a base class that I call when I have an exception.</p>\n\n<pre><code>public class LogArgs\n{\n\n public string MethodName { get; set; }\n public string ClassName { get; set; }\n public Dictionary<string, object> Paramters { get; set; }\n\n\n public LogArgs()\n {\n this.Paramters = new Dictionary<string, object>();\n }\n\n}\n</code></pre>\n\n<p>Then at the start of every method I do </p>\n\n<pre><code>LogArgs args = new LogArgs { ClassName = \"ClassName\", MethodName = \"MethodName\" };\nargs.Paramters.Add(\"Param1\", param1);\nargs.Paramters.Add(\"Param2\", param2);\nargs.Paramters.Add(\"Param3\", param3);\n\nbase.Logger.MethodStartLog(args);\n</code></pre>\n\n<p>When I have an error I log it this way.</p>\n\n<pre><code>base.Logger.LogError(args, ex);\n</code></pre>\n"
},
{
"answer_id": 135827,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 3,
"selected": false,
"text": "<p>No there isn't a way to do this.</p>\n\n<p>The normal practice is to not catch exceptions unless you can handle them.</p>\n\n<p>I.e. you would normally only catch exceptions and log them in a top-level exception handler. You will then get a stack trace, but won't of course get details of all the parameters of all method calls in the stack.</p>\n\n<p>Obviously when debugging you want as much detail as possible. Other ways to achieve this are:</p>\n\n<ul>\n<li><p>Use Debug.Assert statements liberally to test assumptions you are making.</p></li>\n<li><p>Instrument your application with logging that can be activate selectively. I use Log4Net, but there are also other alternatives, including using the System.Diagnostics.Trace class.</p></li>\n</ul>\n\n<p>In any case, if you do catch exceptions only to log them (I'd do this at a tier boundary in an n-tier application, so that exceptions are logged on the server), then you should always rethrow them:</p>\n\n<pre><code>try\n{\n ...\n}\ncatch(Exception ex)\n{\n log(ex);\n throw;\n}\n</code></pre>\n"
},
{
"answer_id": 135838,
"author": "JoshL",
"author_id": 20625,
"author_profile": "https://Stackoverflow.com/users/20625",
"pm_score": 1,
"selected": false,
"text": "<p>You could use a similar style of constructing the message, but add the params keyword in your LogError method to handle the arguments. For example:</p>\n\n<pre><code> public void LogError(string message, params object[] parameters)\n {\n if (parameters.Length > 0)\n LogError(string.Format(message, parameters));\n else\n LogError(message);\n }\n</code></pre>\n"
},
{
"answer_id": 136041,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 6,
"selected": true,
"text": "<p>You could use Reflection and the convention that you must pass the parameters to the LogError with the right order:</p>\n\n<pre><code>private static void MyMethod(string s, int x, int y)\n{\n try\n {\n throw new NotImplementedException();\n }\n catch (Exception ex)\n {\n LogError(MethodBase.GetCurrentMethod(), ex, s, x, y);\n }\n}\n\nprivate static void LogError(MethodBase method, Exception ex, params object[] values)\n{\n ParameterInfo[] parms = method.GetParameters();\n object[] namevalues = new object[2 * parms.Length];\n\n string msg = \"Error in \" + method.Name + \"(\";\n for (int i = 0, j = 0; i < parms.Length; i++, j += 2)\n {\n msg += \"{\" + j + \"}={\" + (j + 1) + \"}, \";\n namevalues[j] = parms[i].Name;\n if (i < values.Length) namevalues[j + 1] = values[i];\n }\n msg += \"exception=\" + ex.Message + \")\";\n Console.WriteLine(string.Format(msg, namevalues));\n}\n</code></pre>\n"
},
{
"answer_id": 136167,
"author": "Jacob",
"author_id": 22107,
"author_profile": "https://Stackoverflow.com/users/22107",
"pm_score": 3,
"selected": false,
"text": "<p>You could use aspect oriented programming with PostSharp (have a look at <a href=\"http://www.postsharp.org\" rel=\"noreferrer\">http://www.postsharp.org</a>, and the tutorial at <a href=\"http://www.codeproject.com/KB/cs/ps-custom-attributes-1.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/cs/ps-custom-attributes-1.aspx</a>). Basically you could do something like this:</p>\n\n<pre><code>public class LogExceptionAttribute : OnExceptionAspect\n{\n public override void OnException(MethodExecutionEventArgs eventArgs)\n {\n log.error(\"Exception occurred in method {0}\", eventArgs); \n }\n}\n\n[LoggingOnExceptionAspect]\npublic foo(int number, string word, Person customer)\n{\n // ... something here throws an exception\n}\n</code></pre>\n\n<p>Perhaps not quite what you want, but I'm sure it can be adapted to suit your needs.</p>\n"
},
{
"answer_id": 15522925,
"author": "HydPhani",
"author_id": 852225,
"author_profile": "https://Stackoverflow.com/users/852225",
"pm_score": -1,
"selected": false,
"text": "<p>There are scenarios of a few parameters or Large number of parameters...</p>\n\n<ol>\n<li><p>Few parameters, without much ado, better write them as part of the logging/exception message.</p></li>\n<li><p>In large parameters, a multi-layer application would be using ENTITIES ( like customer, CustomerOrder...) to transfer data between layers. These entities should implement \noverride ToString() methods of class Object, there by, </p></li>\n</ol>\n\n<p>Logmessage(\" method started \" + paramObj.ToString()) would give the list of data in the object..\nAny opinions? :) </p>\n\n<p>thanks</p>\n"
},
{
"answer_id": 37281373,
"author": "joym8",
"author_id": 1541224,
"author_profile": "https://Stackoverflow.com/users/1541224",
"pm_score": 0,
"selected": false,
"text": "<p>This is little dated post but just in case someone comes across this like I did - I solved this issue by using <a href=\"https://www.postsharp.net/\" rel=\"nofollow\">PostSharp</a>.</p>\n\n<p>It's not practically free though. The Express license (downloadable via NuGet in VS) allows you to decorate your method with <code>[Log]</code> attribute and then choose your already configured mechanism for logging, like <a href=\"https://logging.apache.org/log4net/\" rel=\"nofollow\">log4net</a> <a href=\"http://nlog-project.org/\" rel=\"nofollow\">nLog</a> etc. Now you will start seeing Debug level entries in your log giving parameter details.</p>\n\n<p>With express license I could only decorate a maximum of 50 methods in my project. If it fits your needs you're good to go!</p>\n"
},
{
"answer_id": 71048965,
"author": "Aaron Gibson",
"author_id": 2357370,
"author_profile": "https://Stackoverflow.com/users/2357370",
"pm_score": 0,
"selected": false,
"text": "<p>Late to the party but I did something along these lines a year or so ago:\n<a href=\"https://github.com/Alchemy86/ModernLogging/tree/master/ModernLogging\" rel=\"nofollow noreferrer\">Github Repo</a></p>\n<p>The idea of this setup is much like what your after, but with the ability to hook it up globally, there is more code than I would like there but it works and once plugged in, works for what your after.</p>\n<p>If you take a quick look at the ProxyLogger.cs, consider this a wrapper, it will encapsulate any method it is given and execute it while handling the logging of the error as set here. This can then be setup with dependency injection for anything and everything you wish to log, e.g.:</p>\n<pre><code>public void ConfigureServices(HostBuilderContext hostBuilder, IServiceCollection services)\n {\n services.AddOptions();\n services.AddSingleton<IHostedService, HostedService>();\n\n services.AddSingleton<IMyClass, MyClass>();\n\n // Logging added for both the hosted service and the example class\n services.Decorate<IMyClass, ProxyLogger<IMyClass>>();\n services.Decorate<IHostedService, ProxyLogger<IHostedService>>();\n }\n</code></pre>\n<p>You register your services as normal, but on top of that, you can decorate them with the proxy logger to handle the execution and log the details before, after, on failure etc, with FULL params.\nI was obsessed with this for a while and this is as best as I could get it, but it works really well.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
]
| A lot of my C# code follows this pattern:
```
void foo(string param1, string param2, string param3)
{
try
{
// do something...
}
catch(Exception ex)
{
LogError(String.Format("Error in foo(param1={0}, param2={1}, param3={2}), exception={3}", param1, param2, param3, ex.Message));
}
}
```
Is there a way in .NET to get a Key/Value list of the parameters to a function so that I can call another function to construct my error logging string?
OR
Do you have a more generic / better way of doing this? | You could use Reflection and the convention that you must pass the parameters to the LogError with the right order:
```
private static void MyMethod(string s, int x, int y)
{
try
{
throw new NotImplementedException();
}
catch (Exception ex)
{
LogError(MethodBase.GetCurrentMethod(), ex, s, x, y);
}
}
private static void LogError(MethodBase method, Exception ex, params object[] values)
{
ParameterInfo[] parms = method.GetParameters();
object[] namevalues = new object[2 * parms.Length];
string msg = "Error in " + method.Name + "(";
for (int i = 0, j = 0; i < parms.Length; i++, j += 2)
{
msg += "{" + j + "}={" + (j + 1) + "}, ";
namevalues[j] = parms[i].Name;
if (i < values.Length) namevalues[j + 1] = values[i];
}
msg += "exception=" + ex.Message + ")";
Console.WriteLine(string.Format(msg, namevalues));
}
``` |
135,801 | <p>I am using prototype and I can't find any built in extensions to set or retrieve cookies. After googling for a little bit, I see a few different ways to go about it. I was wondering what you think is the best approach for getting a cookie in JavaScript?</p>
| [
{
"answer_id": 135855,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": -1,
"selected": false,
"text": "<p>I use this. It has been dependable:</p>\n\n<pre><code>function getCookie(c_name) {\nif (document.cookie.length>0)\n {\n c_start=document.cookie.indexOf(c_name + \"=\")\n if (c_start!=-1)\n { \n c_start=c_start + c_name.length+1 \n c_end=document.cookie.indexOf(\";\",c_start)\n if (c_end==-1) c_end=document.cookie.length\n return unescape(document.cookie.substring(c_start,c_end))\n } \n }\nreturn \"\"\n</code></pre>\n\n<p>}</p>\n"
},
{
"answer_id": 135858,
"author": "Pseudo Masochist",
"author_id": 8529,
"author_profile": "https://Stackoverflow.com/users/8529",
"pm_score": 2,
"selected": false,
"text": "<p>Anytime I need to access it, I use <a href=\"http://www.quirksmode.org/js/cookies.html\" rel=\"nofollow noreferrer\">document.cookie</a>, basically how it's outlined in that article. Caveat, I've never used prototype, so there may be easier methods there that you just haven't run across.</p>\n"
},
{
"answer_id": 180271,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 3,
"selected": false,
"text": "<p>I use this routine:</p>\n\n<pre><code>function ReadCookie(name)\n{\n name += '=';\n var parts = document.cookie.split(/;\\s*/);\n for (var i = 0; i < parts.length; i++)\n {\n var part = parts[i];\n if (part.indexOf(name) == 0)\n return part.substring(name.length)\n }\n return null;\n}\n</code></pre>\n\n<p>Works quite well.</p>\n"
},
{
"answer_id": 11109684,
"author": "TheZ",
"author_id": 1217408,
"author_profile": "https://Stackoverflow.com/users/1217408",
"pm_score": 2,
"selected": false,
"text": "<p>In case anyone else needs it, I've fixed up <a href=\"https://stackoverflow.com/a/135855/1217408\">Diodeus's code</a> to address <a href=\"https://stackoverflow.com/questions/135801/what-is-the-best-way-to-get-a-cookie-by-name-in-javascript/11109684#comment62923_135855\">PhiLho's concern</a> about partial matches when trying to fetch a cookie value.</p>\n\n<pre><code>function getCookie(c_name) {\n var nameEQ = c_name + '=';\n var c_start = 0;\n var c_end = 0;\n if (document.cookie.substr(0, nameEQ.length) === nameEQ) {\n return document.cookie.substring(nameEQ.length, document.cookie.indexOf(';', nameEQ.length));\n } else {\n c_start = document.cookie.indexOf('; ' + nameEQ);\n if(c_start !== -1){\n c_start += nameEQ.length + 2;\n c_end = document.cookie.indexOf(';', c_start);\n if (c_end === -1) {c_end = document.cookie.length;}\n return document.cookie.substring(c_start, c_end);\n }\n }\n return null;\n}\n</code></pre>\n\n<p>I've recently also built a much more compact RegExp that should work as well:</p>\n\n<pre><code>function getCookie(c_name){\n var ret = window.testCookie.match(new RegExp(\"(?:^|;)\\\\s*\"+c_name+\"=([^;]*)\"));\n return (ret !== null ? ret[1] : null);\n}\n</code></pre>\n\n<p>I did some speed tests that seem to indicate that out of PhiLo, QuirksMode, and these two implementations the non-RegExp version (using indexOf is very fast, not a huge surprise) above is the fastest. <a href=\"http://jsperf.com/cookie-fetcher\" rel=\"nofollow noreferrer\">http://jsperf.com/cookie-fetcher</a></p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6350/"
]
| I am using prototype and I can't find any built in extensions to set or retrieve cookies. After googling for a little bit, I see a few different ways to go about it. I was wondering what you think is the best approach for getting a cookie in JavaScript? | I use this routine:
```
function ReadCookie(name)
{
name += '=';
var parts = document.cookie.split(/;\s*/);
for (var i = 0; i < parts.length; i++)
{
var part = parts[i];
if (part.indexOf(name) == 0)
return part.substring(name.length)
}
return null;
}
```
Works quite well. |
135,802 | <p>I'm looking for the concept to <strong>spawn a process</strong> such that:</p>
<ul>
<li>it has only access to certain libraries/APIs</li>
<li>it cannot acess the file system or only specific parts</li>
<li>it can <strong>do least harm should malicious code run in it</strong></li>
</ul>
<p>This concept is known as sandbox or jail.</p>
<p>It is required to do this <strong>for each major Operating system (Windows, MacOSX and Linux)</strong> and the question is conceptual (as in what to do, <strong>which APIs to use and and what to observe</strong>) rather then language specific.</p>
<h2>answer requirements</h2>
<p>I <strong>really</strong> want to accept an answer and give you 20 points for that. I cannot accept my own answer, and I don't have it yet anyway. So if you <strong>really</strong> want your answer to be accepted, please observe:</p>
<ul>
<li>The answer has to be specific and complete</li>
<li>With specific I mean that it is more then a pointer to some resource on the internet. It has to summarize what the resource says about the topic at least.</li>
<li>It may or may not contain example code, but if it does please write it in C</li>
<li>I cannot accept an answer that is 2/3 complete even if the 2/3 that are there are perfect.</li>
</ul>
<h2>this question FAQ</h2>
<ul>
<li>Is this homework? No.</li>
<li>Why do you ask this like a homework question? If you ask a specific question and you want to get a specific answer, and you know how that answer should look like, even though you don't know <em>the</em> answer, that's the style of question you get.</li>
<li>If you know how it should look like, why do you ask? 1) because I don't know all the answer 2) because on the internet there's no single place that contains all the details to this question in one place. Please also read the stackoverflow FAQ</li>
<li>Why is the main part of your question how to answer this question? Because nobody reads the FAQ.</li>
</ul>
| [
{
"answer_id": 135836,
"author": "Dan Udey",
"author_id": 21450,
"author_profile": "https://Stackoverflow.com/users/21450",
"pm_score": 2,
"selected": false,
"text": "<p>FreeBSD has specific concepts of <a href=\"http://en.wikipedia.org/wiki/FreeBSD_jail\" rel=\"nofollow noreferrer\">jails</a>, and Solaris has <a href=\"http://en.wikipedia.org/wiki/Solaris_Containers\" rel=\"nofollow noreferrer\">containers</a>. Depending on what you're looking for, these may help.</p>\n\n<p>chroot jails can help to limit what an application can do (though any app with root privileges can escape a jail), and they're available on most UNIXen, including OS X.</p>\n\n<p>As for Windows, I'm not sure. If there was an easy way to sandbox a Windows app, most of them would be a lot more secure by now, I'm sure.</p>\n"
},
{
"answer_id": 138333,
"author": "Paweł Hajdan",
"author_id": 9403,
"author_profile": "https://Stackoverflow.com/users/9403",
"pm_score": 3,
"selected": false,
"text": "<p>For Windows there is a sandbox in Google Chrome. You may want to investigate it. It uses liberal BSD-like license.</p>\n\n<p>For Linux there would be good old chroot or more sophisticated <a href=\"http://plash.beasts.org/wiki/\" rel=\"noreferrer\">http://plash.beasts.org/wiki/</a>.</p>\n\n<p>OS X since Leopard has some SELinux-like protection available.</p>\n"
},
{
"answer_id": 138345,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 1,
"selected": false,
"text": "<p>For Linux, there is <a href=\"http://developer.novell.com/wiki/index.php/Apparmor_FAQ\" rel=\"nofollow noreferrer\">AppArmor</a>. Unfortunately, the project is somewhat on hiatus.<br>\nAnother sandboxing-alternative is <a href=\"http://linux-vserver.org/Welcome_to_Linux-VServer.org\" rel=\"nofollow noreferrer\">VServer</a>, which uses virtualization.</p>\n"
},
{
"answer_id": 142753,
"author": "Anders",
"author_id": 3501,
"author_profile": "https://Stackoverflow.com/users/3501",
"pm_score": 2,
"selected": false,
"text": "<p>On windows (2000 and later) you can use Job objects to restrict processes.</p>\n"
},
{
"answer_id": 153111,
"author": "Trance Diviner",
"author_id": 7365,
"author_profile": "https://Stackoverflow.com/users/7365",
"pm_score": 4,
"selected": false,
"text": "<p>Mac OS X has a sandbox facility code-named Seatbelt. The public API for it is documented in the sandbox(7), sandbox_init(3), and related manual pages. The public API is somewhat limited, but the facility itself is very powerful. While the public API only lets you choose from some pre-defined sandboxes (e.g. “All sockets-based networking is prohibited”), you can also use the more powerful underlying implementation which allows you to specify exactly what operating system resources are available via a Scheme-like language. For example, here is an excerpt of the sandbox used for portmap:</p>\n\n<pre><code>(allow process-exec (regex #\"^/usr/sbin/portmap$\"))\n(allow file-read-data file-read-metadata (regex\n #\"^/etc\"\n #\"^/usr/lib/.*\\.dylib$\"\n #\"^/var\"\n #\"^/private/var/db/dyld/\"\n #\"^/dev/urandom$\"))\n(allow file-write-data (regex\n #\"^/dev/dtracehelper$\"))\n</code></pre>\n\n<p>You can see many sandboxes used by the system in /usr/share/sandbox. It is easy to experiment with sandboxes by using the sandbox-exec(1) command.</p>\n\n<p>For Windows, you may want to have a look at <a href=\"http://media.blackhat.com/bh-usa-07/video/2007_BlackHat_Vegas-V11-LeBlanc-Practical_Sandboxing.mp4\" rel=\"noreferrer\">David LeBlanc’s “Practical Sandboxing” talk given at Black Hat USA 2007</a>. Windows has no built-in sandboxing technology per se, so the techniques described leverage an incomplete mechanism introduced with Windows 2000 called SAFER. By using restricted tokens, one can create a process that has limited access to operating system resources.</p>\n\n<p>For Linux, you might investigate the complicated SELinux mechanism:\n<a href=\"http://www.nsa.gov/selinux/\" rel=\"noreferrer\">SELinux home</a>,\n<a href=\"http://www.lurking-grue.org/gettingstarted_newselinuxHOWTO.html\" rel=\"noreferrer\">a HOWTO</a>. It is used by Red Hat, for example, to harden some system services in some of their products.</p>\n"
},
{
"answer_id": 394614,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 3,
"selected": false,
"text": "<p>The site <a href=\"http://codepad.org\" rel=\"noreferrer\">codepad.prg</a> has a good <a href=\"http://codepad.org/about\" rel=\"noreferrer\">\"About\"</a> page on how they safely allow the execution of any code snippets..</p>\n\n<blockquote>\n <p>Code execution is handled by a supervisor based on <a href=\"http://www.xs4all.nl/~weegen/eelis/geordi/\" rel=\"noreferrer\">geordi</a>. The strategy is to run everything under ptrace, with many system calls disallowed or ignored. Compilers and final executables are both executed in a chroot jail, with strict resource limits. The supervisor is written in Haskell.</p>\n \n <p>When your app is remote code execution, you have to expect security problems. Rather than rely on just the chroot and ptrace supervisor, I've taken some additional precautions:</p>\n \n <ul>\n <li><p>The supervisor processes run on virtual machines, which are firewalled such that they are incapable of making outgoing connections.</p></li>\n <li><p>The machines that run the virtual machines are also heavily firewalled, and restored from their source images periodically. </p></li>\n </ul>\n</blockquote>\n"
},
{
"answer_id": 394622,
"author": "TokenMacGuy",
"author_id": 49287,
"author_profile": "https://Stackoverflow.com/users/49287",
"pm_score": -1,
"selected": false,
"text": "<p>I'm not an expert on the topic, but i think the standard answer for linux is to define a SeLinux policy with the right capabilities for the process. </p>\n"
},
{
"answer_id": 394776,
"author": "dj_segfault",
"author_id": 14924,
"author_profile": "https://Stackoverflow.com/users/14924",
"pm_score": 2,
"selected": false,
"text": "<p>If you really want a technique that will work with all these platforms, as opposed to a separate solution for each platform, then I think your only answer is to set up a virtual machine for each testing environment. You can restore back to a snapshot at any time.</p>\n\n<p>Another big advantage of using virtualization is that you can have all of the testing environments with their guest operating systems all on the same box. </p>\n"
},
{
"answer_id": 8101328,
"author": "NothingLikeGuru",
"author_id": 1042611,
"author_profile": "https://Stackoverflow.com/users/1042611",
"pm_score": 0,
"selected": false,
"text": "<p>Generally any virtual private server will do:</p>\n\n<p>Linux VServer\n<a href=\"http://linux-vserver.org/Welcome_to_Linux-VServer.org\" rel=\"nofollow\">http://linux-vserver.org/Welcome_to_Linux-VServer.org</a></p>\n\n<p>Parallels Virtuozzo Containers\n<a href=\"http://www.parallels.com/products/pvc/\" rel=\"nofollow\">http://www.parallels.com/products/pvc/</a></p>\n\n<p>and as was mentioned FreeBSD and Solaris has own implementations.</p>\n\n<p>Oh. actually I've noticed you're asking it to work on ANY OS. Well, that might be complicated a bit as the I think less effort is just to reuse some VM that can support some level of sandboxing like:</p>\n\n<ul>\n<li>Java</li>\n<li>.NET</li>\n</ul>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19435/"
]
| I'm looking for the concept to **spawn a process** such that:
* it has only access to certain libraries/APIs
* it cannot acess the file system or only specific parts
* it can **do least harm should malicious code run in it**
This concept is known as sandbox or jail.
It is required to do this **for each major Operating system (Windows, MacOSX and Linux)** and the question is conceptual (as in what to do, **which APIs to use and and what to observe**) rather then language specific.
answer requirements
-------------------
I **really** want to accept an answer and give you 20 points for that. I cannot accept my own answer, and I don't have it yet anyway. So if you **really** want your answer to be accepted, please observe:
* The answer has to be specific and complete
* With specific I mean that it is more then a pointer to some resource on the internet. It has to summarize what the resource says about the topic at least.
* It may or may not contain example code, but if it does please write it in C
* I cannot accept an answer that is 2/3 complete even if the 2/3 that are there are perfect.
this question FAQ
-----------------
* Is this homework? No.
* Why do you ask this like a homework question? If you ask a specific question and you want to get a specific answer, and you know how that answer should look like, even though you don't know *the* answer, that's the style of question you get.
* If you know how it should look like, why do you ask? 1) because I don't know all the answer 2) because on the internet there's no single place that contains all the details to this question in one place. Please also read the stackoverflow FAQ
* Why is the main part of your question how to answer this question? Because nobody reads the FAQ. | Mac OS X has a sandbox facility code-named Seatbelt. The public API for it is documented in the sandbox(7), sandbox\_init(3), and related manual pages. The public API is somewhat limited, but the facility itself is very powerful. While the public API only lets you choose from some pre-defined sandboxes (e.g. “All sockets-based networking is prohibited”), you can also use the more powerful underlying implementation which allows you to specify exactly what operating system resources are available via a Scheme-like language. For example, here is an excerpt of the sandbox used for portmap:
```
(allow process-exec (regex #"^/usr/sbin/portmap$"))
(allow file-read-data file-read-metadata (regex
#"^/etc"
#"^/usr/lib/.*\.dylib$"
#"^/var"
#"^/private/var/db/dyld/"
#"^/dev/urandom$"))
(allow file-write-data (regex
#"^/dev/dtracehelper$"))
```
You can see many sandboxes used by the system in /usr/share/sandbox. It is easy to experiment with sandboxes by using the sandbox-exec(1) command.
For Windows, you may want to have a look at [David LeBlanc’s “Practical Sandboxing” talk given at Black Hat USA 2007](http://media.blackhat.com/bh-usa-07/video/2007_BlackHat_Vegas-V11-LeBlanc-Practical_Sandboxing.mp4). Windows has no built-in sandboxing technology per se, so the techniques described leverage an incomplete mechanism introduced with Windows 2000 called SAFER. By using restricted tokens, one can create a process that has limited access to operating system resources.
For Linux, you might investigate the complicated SELinux mechanism:
[SELinux home](http://www.nsa.gov/selinux/),
[a HOWTO](http://www.lurking-grue.org/gettingstarted_newselinuxHOWTO.html). It is used by Red Hat, for example, to harden some system services in some of their products. |
135,803 | <blockquote>
<p>System.InvalidOperationException: DragDrop registration did not
succeed. ---> System.Threading.ThreadStateException:</p>
</blockquote>
<p>What does this exception mean? I get it at this line trying to add a panel to a panel at runtime...</p>
<pre><code>splitReport.Panel1.Controls.Add(ChartPanel);
</code></pre>
<p>Working in VS2008 C#</p>
| [
{
"answer_id": 160867,
"author": "Charlie",
"author_id": 18529,
"author_profile": "https://Stackoverflow.com/users/18529",
"pm_score": 5,
"selected": false,
"text": "<p>This exception means that the thread that owns the Panel (the Panel being added) has been initialized using the MTA threading model. The drag/drop system requires that the calling thread use the STA thread model (particularly it requires that COM be initialized via OleInitialize). Threading models are an unfortunate vestige of COM, a predecessor of the .NET platform.</p>\n\n<p>If you have the <code>[STAThread]</code> attribute on your Main function, then the main program thread should already be STA. The most likely explanation, then, is that this exception is happening on a different thread. Look at the Threads window in Visual Studio (Debug | Windows | Threads) when the exception occurs and see if you are on a thread other than the main thread. If you are, the solution is probably as simple as setting the thread model for that new thread, which you can do as follows (add this code to the thread where the control is being created):</p>\n\n<p><code>Thread.CurrentThread.SetApartmentState( ApartmentState.STA )</code></p>\n\n<p>(<code>Thread</code> and <code>ApartmentState</code> are members of <code>System.Threading</code>)</p>\n\n<p>That code will need to happen before you actually start the new thread. As noted by @Tomer, you can also specify this declaratively using the <code>[STAThread]</code> attribute.</p>\n\n<p>If you find that the exception is happening on the main thread, post back and let us know, and maybe we can help more. A stack trace at the time of the exception may help track down the problem.</p>\n"
},
{
"answer_id": 2205399,
"author": "Graviton",
"author_id": 3834,
"author_profile": "https://Stackoverflow.com/users/3834",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not sure whether you have solved this problem or not. I just encountered this problem and I fixed it by <a href=\"http://www.chapleau.info/cs/blogs/fchapleau/archive/2006/12/01/233.aspx\" rel=\"nofollow noreferrer\">deleting my <code>bin</code> directory</a>.</p>\n"
},
{
"answer_id": 5897823,
"author": "T.K.",
"author_id": 391618,
"author_profile": "https://Stackoverflow.com/users/391618",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, I realize this question was asked 2 and a half years ago. I hit this exception and did some reading on it. I corrected it, but didn't see my solution anywhere, so I thought I'd post it somewhere someone else could read.</p>\n\n<p>One possibility for this happening with <code>[STAThread]</code> marked on the <code>Main()</code> is if you're running this on a thread other than the one you started on.</p>\n\n<p>I just ran into this exception when trying to create and show a new form in a <code>BackgroundWorker.DoWork</code> method. To fix it, I wrapped the creation and showing of my new form into a method, and then called <code>Invoke</code> on that method so that it fired on the UI thread. This worked because the UI thread started from the <code>Main()</code> method with <code>[STAThread]</code> marked, as other answers here explained.</p>\n"
},
{
"answer_id": 7227339,
"author": "Sai Sherlekar",
"author_id": 730593,
"author_profile": "https://Stackoverflow.com/users/730593",
"pm_score": 3,
"selected": false,
"text": "<pre><code>function abc\n{\n Thread t = new Thread(new ThreadStart(xyz));\n t.SetApartmentState(ApartmentState.STA);\n t.Start( ); \n}\nfunction xyz\n{\n the code of Windows form..or whatever which is causing the error\n}\n</code></pre>\n"
},
{
"answer_id": 18462689,
"author": "zionpi",
"author_id": 1066501,
"author_profile": "https://Stackoverflow.com/users/1066501",
"pm_score": 0,
"selected": false,
"text": "<p>I have encountered this situation recently,<code>[STAThreadAttribute]</code>is in my case,and i solved this problem by using <strong>Invoke</strong> method,it might be helpful for you guys,so I share with a little code snippet:</p>\n\n<pre><code>this.Invoke(new InvokeHandler(delegate() \n{\n//Your method here!\n}));\n</code></pre>\n\n<p>And InvokeHandler is a delegate like this:</p>\n\n<pre><code>private delegate void InvokeHandler();\n</code></pre>\n"
},
{
"answer_id": 24139839,
"author": "Conrad de Wet",
"author_id": 2542014,
"author_profile": "https://Stackoverflow.com/users/2542014",
"pm_score": 1,
"selected": false,
"text": "<p>By far the easiest way is:</p>\n\n<pre><code>private void DoSomethingOnGui()\n{\n if (this.InvokeRequired)\n {\n this.Invoke((MethodInvoker)delegate\n {\n Safe_DoSomethingOnGui();\n });\n }\n else\n {\n Safe_DoSomethingOnGui();\n }\n}\nprivate void Safe_DoSomethingOnGui()\n{\n // Do whatever you want with the GUI\n}\n</code></pre>\n\n<p>You can even pass things along no problem:</p>\n\n<pre><code>private void DoSomethingOnGui(object o)\n{\n if (this.InvokeRequired)\n {\n this.Invoke((MethodInvoker)delegate\n {\n Safe_DoSomethingOnGui(o);\n });\n }\n else\n {\n Safe_DoSomethingOnGui(o);\n }\n}\nprivate void Safe_DoSomethingOnGui(object o)\n{\n // Do whatever you want with the GUI and o\n}\n</code></pre>\n"
},
{
"answer_id": 28553467,
"author": "Kosmas",
"author_id": 2833737,
"author_profile": "https://Stackoverflow.com/users/2833737",
"pm_score": 1,
"selected": false,
"text": "<p>I found this error, and the one that makes the error shown was when we have another thread calling <code>MessageBox.Show(this, ...)</code>. However, <code>this</code> is not done initialized.</p>\n<p>We need to remove the owner of the message box to remove the error.</p>\n"
},
{
"answer_id": 32665641,
"author": "RAVI VAGHELA",
"author_id": 4255952,
"author_profile": "https://Stackoverflow.com/users/4255952",
"pm_score": 1,
"selected": false,
"text": "<p>I solved this error by using below code...I were using Background Worker and trying to access UI while background worker..that is why getting error - DragDrop registration did not succeed.\nWe cannot access UI from the code running in background worker or in thread.</p>\n\n<pre><code>BeginInvoke((MethodInvoker)delegate\n{\n//write your code here...\n\n});\n</code></pre>\n\n<p>Thanks Happy Coding... :</p>\n"
},
{
"answer_id": 37921700,
"author": "Ali Sadri",
"author_id": 5137413,
"author_profile": "https://Stackoverflow.com/users/5137413",
"pm_score": 2,
"selected": false,
"text": "<p>Add the STAThreadAttribute attribute on the Main method. This attribute is required if your program access OLE related functions, like Clipboard class does.</p>\n\n<p><strong>[STAThread]</strong></p>\n\n<p>static void Main(string[] args)</p>\n\n<p>{</p>\n\n<p>}</p>\n"
},
{
"answer_id": 69099195,
"author": "S0und",
"author_id": 1809169,
"author_profile": "https://Stackoverflow.com/users/1809169",
"pm_score": 1,
"selected": false,
"text": "<p>This error also can happen, if you have <code>async Task</code> signature on your <code>Main()</code></p>\n<pre><code> [STAThread]\n static async Task Main()\n {\n }\n</code></pre>\n<p>if it's feasible change it back to <code>void</code></p>\n<pre><code> [STAThread]\n static void Main()\n {\n }\n</code></pre>\n"
},
{
"answer_id": 70222944,
"author": "WiiLF",
"author_id": 2694720,
"author_profile": "https://Stackoverflow.com/users/2694720",
"pm_score": 0,
"selected": false,
"text": "<p>"Crypto Obfuscator For .NET" can also trigger this exception, in my case the DragDrop event was subscribed to (from designer), but contained no code as I commented it out much earlier on. It took a while to figure out what is was, and this was after changing every single Obfuscator config option 1 after the next.. it came down to exactly this. If you encounter this with a popular obfuscation tool, keep this in mind.</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| >
> System.InvalidOperationException: DragDrop registration did not
> succeed. ---> System.Threading.ThreadStateException:
>
>
>
What does this exception mean? I get it at this line trying to add a panel to a panel at runtime...
```
splitReport.Panel1.Controls.Add(ChartPanel);
```
Working in VS2008 C# | This exception means that the thread that owns the Panel (the Panel being added) has been initialized using the MTA threading model. The drag/drop system requires that the calling thread use the STA thread model (particularly it requires that COM be initialized via OleInitialize). Threading models are an unfortunate vestige of COM, a predecessor of the .NET platform.
If you have the `[STAThread]` attribute on your Main function, then the main program thread should already be STA. The most likely explanation, then, is that this exception is happening on a different thread. Look at the Threads window in Visual Studio (Debug | Windows | Threads) when the exception occurs and see if you are on a thread other than the main thread. If you are, the solution is probably as simple as setting the thread model for that new thread, which you can do as follows (add this code to the thread where the control is being created):
`Thread.CurrentThread.SetApartmentState( ApartmentState.STA )`
(`Thread` and `ApartmentState` are members of `System.Threading`)
That code will need to happen before you actually start the new thread. As noted by @Tomer, you can also specify this declaratively using the `[STAThread]` attribute.
If you find that the exception is happening on the main thread, post back and let us know, and maybe we can help more. A stack trace at the time of the exception may help track down the problem. |
135,835 | <p>I am trying to load a small sample of records from a large database into a test database.</p>
<p>How do you tell mysqldump to only give you n records out of 8 million?</p>
<p>Thanks</p>
| [
{
"answer_id": 135843,
"author": "skaffman",
"author_id": 21234,
"author_profile": "https://Stackoverflow.com/users/21234",
"pm_score": 3,
"selected": false,
"text": "<p>mysqldump can be given a SQL query to execute, from which it will take the data for the dump. You can then use the \"limit X\" clause in your query to restrict the number of rows.</p>\n"
},
{
"answer_id": 135900,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 8,
"selected": false,
"text": "<p>As skaffman says, use the <strong>--where</strong> option:</p>\n\n<pre><code>mysqldump --opt --where=\"1 limit 1000000\" database\n</code></pre>\n\n<p>Of course, that would give you the first million rows from every table.</p>\n"
},
{
"answer_id": 19830993,
"author": "Casper André Casse",
"author_id": 1665847,
"author_profile": "https://Stackoverflow.com/users/1665847",
"pm_score": 6,
"selected": false,
"text": "<p>If you want to get <code>n</code> records from a specific table you can do something like this:</p>\n\n<pre><code>mysqldump --opt --where=\"1 limit 1000000\" database table > dump.sql\n</code></pre>\n\n<p>This will dump the first <code>1000000</code> rows from the table named <code>table</code> into the file <code>dump.sql</code>.</p>\n"
},
{
"answer_id": 46113423,
"author": "Andreas Bergström",
"author_id": 1202214,
"author_profile": "https://Stackoverflow.com/users/1202214",
"pm_score": 4,
"selected": false,
"text": "<p>As the default order is ASC which is rarely what you want in this situation, you need to have a proper database design to make DESC work out of the box. If all your tables have ONE primary key column with the same name (natural or surrogate) you can easily dump the n latest records using:</p>\n\n<pre><code>mysqldump --opt --where=\"1 ORDER BY id DESC limit 1000000\" --all-databases > dump.sql\n</code></pre>\n\n<p>This is a perfect reason to why you should always name your PK's <em>id</em> and avoid composite PK's, even in association tables (use surrogate keys instead).</p>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I am trying to load a small sample of records from a large database into a test database.
How do you tell mysqldump to only give you n records out of 8 million?
Thanks | As skaffman says, use the **--where** option:
```
mysqldump --opt --where="1 limit 1000000" database
```
Of course, that would give you the first million rows from every table. |
135,845 | <p>A colleague of mine states that <strong>booleans as method arguments are not acceptable</strong>. They shall be replaced by enumerations. At first I did not see any benefit, but he gave me an example.</p>
<p>What's easier to understand?</p>
<pre><code>file.writeData( data, true );
</code></pre>
<p>Or</p>
<pre><code>enum WriteMode {
Append,
Overwrite
};
file.writeData( data, Append );
</code></pre>
<p>Now I got it! ;-)<br>
This is definitely an example where an enumeration as second parameter makes the code much more readable.</p>
<p>So, what's your opinion on this topic?</p>
| [
{
"answer_id": 135865,
"author": "simon",
"author_id": 6040,
"author_profile": "https://Stackoverflow.com/users/6040",
"pm_score": 6,
"selected": false,
"text": "<p>Enums also allow for future modifications, where you now want a third choice (or more).</p>\n"
},
{
"answer_id": 135866,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 2,
"selected": false,
"text": "<p>A Boolean would only be acceptable if you do not intend to extend the functionality of the framework. The Enum is preferred because you can extend the enum and not break previous implementations of the function call. </p>\n\n<p>The other advantage of the Enum is that is easier to read.</p>\n"
},
{
"answer_id": 135871,
"author": "skaffman",
"author_id": 21234,
"author_profile": "https://Stackoverflow.com/users/21234",
"pm_score": 8,
"selected": true,
"text": "<p>Boolean's represent \"yes/no\" choices. If you want to represent a \"yes/no\", then use a boolean, it should be self-explanatory.</p>\n\n<p>But if it's a choice between two options, neither of which is clearly yes or no, then an enum can sometimes be more readable.</p>\n"
},
{
"answer_id": 135876,
"author": "Tim Jarvis",
"author_id": 10387,
"author_profile": "https://Stackoverflow.com/users/10387",
"pm_score": 4,
"selected": false,
"text": "<p>I think you almost answered this yourself, I think the end aim is to make the code more readable, and in this case the enum did that, IMO its always best to look at the end aim rather than blanket rules, maybe think of it more as a guideline i.e. enums are often more readable in code than generic bools, ints etc but there will always be exceptions to the rule.</p>\n"
},
{
"answer_id": 135878,
"author": "Borek Bernard",
"author_id": 21728,
"author_profile": "https://Stackoverflow.com/users/21728",
"pm_score": 3,
"selected": false,
"text": "<p>Enums are better but I wouldn't call boolean params as \"unacceptable\". Sometimes it's just easier to throw one little boolean in and move on (think private methods etc.)</p>\n"
},
{
"answer_id": 135882,
"author": "Jesse C. Slicer",
"author_id": 3312,
"author_profile": "https://Stackoverflow.com/users/3312",
"pm_score": 2,
"selected": false,
"text": "<p>If the method asks a question such as:</p>\n\n<pre><code>KeepWritingData (DataAvailable());\n</code></pre>\n\n<p>where</p>\n\n<pre><code>bool DataAvailable()\n{\n return true; //data is ALWAYS available!\n}\n\nvoid KeepWritingData (bool keepGoing)\n{\n if (keepGoing)\n {\n ...\n }\n}\n</code></pre>\n\n<p>boolean method arguments seem to make absolutely perfect sense.</p>\n"
},
{
"answer_id": 135891,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 2,
"selected": false,
"text": "<p>It depends on the method. If the method does something that is very obviously a true/false thing then it is fine, e.g. below [though not I am not saying this is the best design for this method, it's just an example of where the usage is obvious].</p>\n\n<pre><code>CommentService.SetApprovalStatus(commentId, false);\n</code></pre>\n\n<p>However in most cases, such as the example you mention, it is better to use an enumeration. There are many examples in the .NET Framework itself where this convention is not followed, but that is because they introduced this design guideline fairly late on in the cycle.</p>\n"
},
{
"answer_id": 135893,
"author": "Jurassic_C",
"author_id": 20572,
"author_profile": "https://Stackoverflow.com/users/20572",
"pm_score": 1,
"selected": false,
"text": "<p>IMHO it seems like an enum would be the obvious choice for any situation where more than two options are possible. But there definitely ARE situations where a boolean is all you need. In that case I would say that using an enum where a bool would work would be an example of using 7 words when 4 will do.</p>\n"
},
{
"answer_id": 135897,
"author": "Dan Udey",
"author_id": 21450,
"author_profile": "https://Stackoverflow.com/users/21450",
"pm_score": 0,
"selected": false,
"text": "<p>Booleans make sense when you have an obvious toggle which can only be one of two things (i.e. the state of a light bulb, on or off). Other than that, it's good to write it in such a way that it's obvious what you're passing - e.g. disk writes - unbuffered, line-buffered, or synchronous - should be passed as such. Even if you don't want to allow synchronous writes now (and so you're limited to two options), it's worth considering making them more verbose for the purposes of knowing what they do at first glance.</p>\n\n<p>That said, you can also use False and True (boolean 0 and 1) and then if you need more values later, expand the function out to support user-defined values (say, 2 and 3), and your old 0/1 values will port over nicely, so your code ought not to break.</p>\n"
},
{
"answer_id": 135901,
"author": "Jennifer",
"author_id": 22360,
"author_profile": "https://Stackoverflow.com/users/22360",
"pm_score": 2,
"selected": false,
"text": "<p>It does make things a bit more explicit, but does start to massively extend the complexity of your interfaces - in a sheer boolean choice such as appending/overwriting it seems like overkill. If you need to add a further option (which I can't think of in this case), you can always perform a refactor (depending on the language)</p>\n"
},
{
"answer_id": 135911,
"author": "csmba",
"author_id": 350,
"author_profile": "https://Stackoverflow.com/users/350",
"pm_score": 2,
"selected": false,
"text": "<p>I would not agree that it is a good <strong>rule</strong>. Obviously, Enum makes for a better explicit or verbose code at some instances, but as a rule it seems way over reaching. </p>\n\n<p>First let me take your example:\nThe programmers responsibility (and ability) to write good code is not really jeopardized by having a Boolean parameter. In your example the programmer could have written just as verbose code by writing:</p>\n\n<pre><code>dim append as boolean = true\nfile.writeData( data, append );\n</code></pre>\n\n<p>or I prefer more general</p>\n\n<pre><code>dim shouldAppend as boolean = true\nfile.writeData( data, shouldAppend );\n</code></pre>\n\n<p>Second:\nThe Enum example you gave is only \"better\" because you are passing a CONST. Most likely in most application at least some if not most of the time parameters that are passed to functions are VARIABLES. in which case my second example (giving variables with good names) is much better and Enum would have given you little benefits.</p>\n"
},
{
"answer_id": 135917,
"author": "Jeremy Bourque",
"author_id": 2192597,
"author_profile": "https://Stackoverflow.com/users/2192597",
"pm_score": 5,
"selected": false,
"text": "<p>Use the one that best models your problem. In the example you give, the enum is a better choice. However, there would be other times when a boolean is better. Which makes more sense to you:</p>\n\n<pre><code>lock.setIsLocked(True);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>enum LockState { Locked, Unlocked };\nlock.setLockState(Locked);\n</code></pre>\n\n<p>In this case, I might choose the boolean option since I think it's quite clear and unambiguous, and I'm pretty sure my lock is not going to have more than two states. Still, the second choice is valid, but unnecessarily complicated, IMHO.</p>\n"
},
{
"answer_id": 135955,
"author": "Thorsten79",
"author_id": 19734,
"author_profile": "https://Stackoverflow.com/users/19734",
"pm_score": 4,
"selected": false,
"text": "<p>Remember the question Adlai Stevenson posed to ambassador Zorin at the U.N. during the <a href=\"http://answers.google.com/answers/threadview/id/765433.html\" rel=\"noreferrer\">cuban missile crisis</a>?</p>\n\n<blockquote>\n <p>\"You are in the courtroom of world\n opinion right now, and you can answer\n <strong>yes or no</strong>. You have denied that [the missiles]\n exist, and I want to know whether I\n have understood you correctly.... I am\n prepared to wait for my answer until\n hell freezes over, if that's your\n decision.\"</p>\n</blockquote>\n\n<p>If the flag you have in your method is of such a nature that you can pin it down to a <strong>binary decision</strong>, and that decision will <strong>never</strong> turn into a three-way or n-way decision, go for boolean. Indications: your flag is called <strong>isXXX</strong>. </p>\n\n<p>Don't make it boolean in case of something that is a <strong>mode switch</strong>. There is always <strong>one more mode</strong> than you thought of when writing the method in the first place. </p>\n\n<p>The one-more-mode dilemma has e.g. haunted Unix, where the possible permission modes a file or directory can have today result in weird double meanings of modes depending on file type, ownership etc.</p>\n"
},
{
"answer_id": 135987,
"author": "Chris Lundie",
"author_id": 20685,
"author_profile": "https://Stackoverflow.com/users/20685",
"pm_score": 3,
"selected": false,
"text": "<p>Booleans may be OK in languages that have named parameters, like Python and Objective-C, since the name can explain what the parameter does:</p>\n\n<pre><code>file.writeData(data, overwrite=true)\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>[file writeData:data overwrite:YES]\n</code></pre>\n"
},
{
"answer_id": 136107,
"author": "Sam Schutte",
"author_id": 146,
"author_profile": "https://Stackoverflow.com/users/146",
"pm_score": 4,
"selected": false,
"text": "<p>There are two reasons I've run into this being a bad thing:</p>\n\n<ol>\n<li><p>Because some people will write methods like:</p>\n\n<pre><code>ProcessBatch(true, false, false, true, false, false, true);\n</code></pre>\n\n<p>This is obviously bad because it's too easy to mix up parameters, and you have no idea by looking at it what you're specifying. Just one bool isn't too bad though.</p></li>\n<li><p>Because controlling program flow by a simple yes/no branch might mean you have two entirely different functions that are wrapped up into one in an awkard way. For instance:</p>\n\n<pre><code>public void Write(bool toOptical);\n</code></pre>\n\n<p>Really, this should be two methods</p>\n\n<pre><code>public void WriteOptical();\npublic void WriteMagnetic();\n</code></pre>\n\n<p>because the code in these might be entirely different; they might have to do all sorts of different error handling and validation, or maybe even have to format the outgoing data differently. You can't tell that just by using <code>Write()</code> or even <code>Write(Enum.Optical)</code> (though of course you could have either of those methods just call internal methods WriteOptical/Mag if you want).</p></li>\n</ol>\n\n<p>I guess it just depends. I wouldn't make too big of a deal about it except for #1.</p>\n"
},
{
"answer_id": 136112,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 3,
"selected": false,
"text": "<p>Enums have a definite benefit, but you should't just go replacing all your booleans with enums. There are many places where true/false is actually the best way to represent what is going on.</p>\n<p>However, using them as method arguments is a bit suspect, simply because you can't see without digging into things what they are supposed to do, as they let you see what the true/false <em>actually means</em></p>\n<hr />\n<p>[Edit for the current state in 2022]</p>\n<p>In modern C#, or other languages that support this, the nicest way to do it is with named arguments:</p>\n<pre><code>var worker = new BackgroundWorker(workerReportsProgress: true);\n</code></pre>\n<p>If your language doesn't allow for named arguments, then you may find properties to be a reasonable solution as well</p>\n<hr />\n<p>[Original Answer from 2008 left for posterity]</p>\n<p>Properties (especially with C#3 object initializers) or keyword arguments (a la ruby or python) are a much better way to go where you'd otherwise use a boolean argument.</p>\n<p>C# example:</p>\n<pre><code>var worker = new BackgroundWorker { WorkerReportsProgress = true };\n</code></pre>\n<p>Ruby example</p>\n<pre><code>validates_presence_of :name, :allow_nil => true\n</code></pre>\n<p>Python example</p>\n<pre><code>connect_to_database( persistent=true )\n</code></pre>\n<p>The only thing I can think of where a boolean method argument is the right thing to do is in java, where you don't have either properties or keyword arguments. This is one of the reasons I hate java :-(</p>\n"
},
{
"answer_id": 136259,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 2,
"selected": false,
"text": "<p>Enums can certainly make the code more readable. There are still a few things to watch out for (in .net at least)</p>\n\n<p>Because the underlying storage of an enum is an int, the default value will be zero, so you should make sure that 0 is a sensible default. (E.g. structs have all fields set to zero when created, so there's no way to specify a default other than 0. If you don't have a 0 value, you can't even test the enum without casting to int, which would be bad style.)</p>\n\n<p>If your enum's are private to your code (never exposed publicly) then you can stop reading here.</p>\n\n<p>If your enums are <em>published</em> in any way to external code and/or are saved outside of the program, consider numbering them explicitly. The compiler automatically numbers them from 0, but if you rearrange your enums without giving them values you can end up with defects.</p>\n\n<p>I can legally write</p>\n\n<pre><code>WriteMode illegalButWorks = (WriteMode)1000000;\nfile.Write( data, illegalButWorks );\n</code></pre>\n\n<p>To combat this, any code that consumes an enum that you can't be certain of (e.g. public API) needs to check if the enum is valid. You do this via</p>\n\n<pre><code>if (!Enum.IsDefined(typeof(WriteMode), userValue))\n throw new ArgumentException(\"userValue\");\n</code></pre>\n\n<p>The only caveat of <code>Enum.IsDefined</code> is that it uses reflection and is slower. It also suffers a versioning issue. If you need to check the enum value often, you would be better off the following:</p>\n\n<pre><code>public static bool CheckWriteModeEnumValue(WriteMode writeMode)\n{\n switch( writeMode )\n {\n case WriteMode.Append:\n case WriteMode.OverWrite:\n break;\n default:\n Debug.Assert(false, \"The WriteMode '\" + writeMode + \"' is not valid.\");\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>The versioning issue is that old code may only know how to handle the 2 enums you have. If you add a third value, Enum.IsDefined will be true, but the old code can't necessarily handle it. Whoops.</p>\n\n<p>There's even more fun you can do with <code>[Flags]</code> enums, and the validation code for that is slightly different.</p>\n\n<p>I'll also note that for portability, you should use call <code>ToString()</code> on the enum, and use <code>Enum.Parse()</code> when reading them back in. Both <code>ToString()</code> and <code>Enum.Parse()</code> can handle <code>[Flags]</code> enum's as well, so there's no reason not to use them. Mind you, it's yet another pitfall, because now you can't even change the name of the enum without possibly breaking code.</p>\n\n<p>So, sometimes you need to weigh all of the above in when you ask yourself <em>Can I get away with just an bool?</em></p>\n"
},
{
"answer_id": 136582,
"author": "CheeZe5",
"author_id": 22431,
"author_profile": "https://Stackoverflow.com/users/22431",
"pm_score": -1,
"selected": false,
"text": "<p>It really depends on the exact nature of the argument. If it is not a yes/no or true/false then a enum makes it more readable. But with an enum you need to check the argument or have acceptable default behaviour since undefined values of the underlying type can be passed.</p>\n"
},
{
"answer_id": 136637,
"author": "Anthony",
"author_id": 5599,
"author_profile": "https://Stackoverflow.com/users/5599",
"pm_score": 2,
"selected": false,
"text": "<p>While it is true that in many cases enums are more readable and more extensible than booleans, an absolute rule that \"booleans are not acceptable\" is daft. It is inflexible and counter-productive - it does not leave room for human judgement. They're a fundamental built in type in most languages because they're useful - consider applying it to other built-in-types: saying for instance \"never use an int as a parameter\" would just be crazy.</p>\n\n<p>This rule is just a question of style, not of potential for bugs or runtime performance. A better rule would be \"prefer enums to booleans for reasons of readability\".</p>\n\n<p>Look at the .Net framework. Booleans are used as parameters on quite a few methods. The .Net API is not perfect, but I don't think that the use of boolean as parameters is a big problem. The tooltip always gives you the name of the parameter, and you can build this kind of guidance too - fill in your XML comments on the method parameters, they will come up in the tooltip.</p>\n\n<p>I should also add that there is a case when you should clearly refactor booleans to an enumeration - when you have two or more booleans on your class, or in your method params, and not all states are valid (e.g. it's not valid to have them both set true).</p>\n\n<p>For instance, if your class has properties like</p>\n\n<pre><code>public bool IsFoo\npublic bool IsBar\n</code></pre>\n\n<p>And it's an error to have both of them true at the same time, what you've actually got is three valid states, better expressed as something like:</p>\n\n<pre><code>enum FooBarType { IsFoo, IsBar, IsNeither };\n</code></pre>\n"
},
{
"answer_id": 137290,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": -1,
"selected": false,
"text": "<p>The use of enums instead of booleans in your example does help make the method call more readable. However, this is a substitute for my favorite wish item in C#, named arguments in method calls. This syntax:</p>\n\n<pre><code>var v = CallMethod(pData = data, pFileMode = WriteMode, pIsDirty = true);\n</code></pre>\n\n<p>would be perfectly readable, and you could then do what a programmer should do, which is choose the most appropriate type for each parameter in the method without regard to how it looks in the IDE.</p>\n\n<p>C# 3.0 allows named arguments in constructors. I don't know why they can't do this with methods as well.</p>\n"
},
{
"answer_id": 193881,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 0,
"selected": false,
"text": "<p>Sometimes it's just simpler to model different behaviour with overloads. To continue from your example would be:</p>\n\n<pre><code>file.appendData( data ); \nfile.overwriteData( data );\n</code></pre>\n\n<p>This approach degrades if you have multiple parameters, each allowing a fixed set of options. For example, a method that opens a file might have several permutations of file mode (open/create), file access (read/write), sharing mode (none/read/write). The total number of configurations is equal to the Cartesian products of the individual options. Naturally in such cases multiple overloads are not appropriate. </p>\n\n<p>Enums can, in some cases make code more readable, although validating the exact enum value in some languages (C# for example) can be difficult.</p>\n\n<p>Often a boolean parameter is appended to the list of parameters as a new overload. One example in .NET is:</p>\n\n<pre><code>Enum.Parse(str); \nEnum.Parse(str, true); // ignore case\n</code></pre>\n\n<p>The latter overload became available in a later version of the .NET framework than the first.</p>\n\n<p>If you know that there will only ever be two choices, a boolean might be fine. Enums are extensible in a way that won't break old code, although old libraries might not support new enum values so versioning cannot be completely disregarded.</p>\n\n<hr>\n\n<p><strong>EDIT</strong></p>\n\n<p>In newer versions of C# it's possible to use named arguments which, IMO, can make calling code clearer in the same way that enums can. Using the same example as above:</p>\n\n<pre><code>Enum.Parse(str, ignoreCase: true);\n</code></pre>\n"
},
{
"answer_id": 1670946,
"author": "Pascal Thivent",
"author_id": 70604,
"author_profile": "https://Stackoverflow.com/users/70604",
"pm_score": 4,
"selected": false,
"text": "<p>To me, neither using boolean nor enumeration is a good approach. Robert C. Martin captures this very clearly in his <a href=\"http://www.informit.com/articles/article.aspx?p=1392524\" rel=\"noreferrer\">Clean Code Tip #12: Eliminate Boolean Arguments</a>:</p>\n\n<blockquote>\n <p>Boolean arguments loudly declare that the function does more than one thing. They are confusing and should be eliminated.</p>\n</blockquote>\n\n<p>If a method does more than one thing, you should rather write two different methods, for example in your case: <code>file.append(data)</code> and <code>file.overwrite(data)</code>.</p>\n\n<p>Using an enumeration doesn't make things clearer. It doesn't change anything, it's still a flag argument. </p>\n"
},
{
"answer_id": 2525719,
"author": "Alex Worden",
"author_id": 181551,
"author_profile": "https://Stackoverflow.com/users/181551",
"pm_score": 2,
"selected": false,
"text": "<p>Some rules that your colleague might be better adhering to are: </p>\n\n<ul>\n<li>Don't be dogmatic with your design. </li>\n<li>Choose what fits most appropriately for the users of your code.</li>\n<li>Don't try to bash star-shaped pegs into every hole just because you like the shape this month!</li>\n</ul>\n"
},
{
"answer_id": 2525810,
"author": "fastcodejava",
"author_id": 184730,
"author_profile": "https://Stackoverflow.com/users/184730",
"pm_score": -1,
"selected": false,
"text": "<p>Booleans values <code>true</code>/<code>false</code> only. So it is not clear what it represent. <code>Enum</code> can have meaningful name, e.g <code>OVERWRITE</code>, <code>APPEND</code>, etc. So enums are better.</p>\n"
},
{
"answer_id": 10653485,
"author": "Haris Krajina",
"author_id": 776301,
"author_profile": "https://Stackoverflow.com/users/776301",
"pm_score": 0,
"selected": false,
"text": "<p>Where I do agree that Enums are good way to go, in methods where you have 2 options (and just two options you can have readability without enum.)</p>\n\n<p>e.g.</p>\n\n<pre><code>public void writeData(Stream data, boolean is_overwrite)\n</code></pre>\n\n<p>Love the Enums, but boolean is useful too.</p>\n"
},
{
"answer_id": 16882897,
"author": "Robert Martin",
"author_id": 895795,
"author_profile": "https://Stackoverflow.com/users/895795",
"pm_score": 0,
"selected": false,
"text": "<p>This is a late entry on an old post, and it's so far down the page that nobody will ever read it, but since nobody has said it already....</p>\n\n<p>An inline comment goes a long way to solving the unexpected <code>bool</code> problem. The original example is particularly heinous: imagine trying to name the variable in the function declearation! It'd be something like</p>\n\n<pre><code>void writeData( DataObject data, bool use_append_mode );\n</code></pre>\n\n<p>But, for the sake of example, let's say that's the declaration. Then, for an otherwise unexplained boolean argument, I put the variable name in an inline comment. Compare</p>\n\n<pre><code>file.writeData( data, true );\n</code></pre>\n\n<p>with</p>\n\n<pre><code>file.writeData( data, true /* use_append_mode */);\n</code></pre>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2012356/"
]
| A colleague of mine states that **booleans as method arguments are not acceptable**. They shall be replaced by enumerations. At first I did not see any benefit, but he gave me an example.
What's easier to understand?
```
file.writeData( data, true );
```
Or
```
enum WriteMode {
Append,
Overwrite
};
file.writeData( data, Append );
```
Now I got it! ;-)
This is definitely an example where an enumeration as second parameter makes the code much more readable.
So, what's your opinion on this topic? | Boolean's represent "yes/no" choices. If you want to represent a "yes/no", then use a boolean, it should be self-explanatory.
But if it's a choice between two options, neither of which is clearly yes or no, then an enum can sometimes be more readable. |
135,849 | <p>I'm trying to host a python script using an apache web server, but the server tries to run the script instead of just offering it for download.</p>
<p>I do not have direct access to server, and adding the line</p>
<pre><code>AddType text/plain .py
</code></pre>
<p>to .htaccess in the root folder does not appear to work, though I could be doing something wrong.</p>
<p>How do I get the server to just send the file as text instead of trying to run it?</p>
<p>-Edit</p>
<p>Changing the name does not work. Script.py.safe still give a 500 Server error when you click it. </p>
<p>I should also mention that the .htaccess file does work, but for some reason that one addType line is not working. Either because it's not overriding something, or the line is wrong.</p>
| [
{
"answer_id": 135869,
"author": "Jeremy Bourque",
"author_id": 2192597,
"author_profile": "https://Stackoverflow.com/users/2192597",
"pm_score": 2,
"selected": false,
"text": "<p>If you can't change the Apache config and you can't override it with an htaccess file, then it seems to me that the easiest solutions would be either to change the file extension, or else to write a script that prints the contents of the target script.</p>\n\n<p>Both are hacks to some extent, but the correct solution is to change the Apache config.</p>\n"
},
{
"answer_id": 135872,
"author": "Tilendor",
"author_id": 1470,
"author_profile": "https://Stackoverflow.com/users/1470",
"pm_score": 0,
"selected": false,
"text": "<p>One option is to change the extention and make clear that it should be renamed. IE python.py.safe or python.py.dl. The user would then need to remove the extra bit.</p>\n\n<p>You could also Zip it up.</p>\n"
},
{
"answer_id": 135888,
"author": "Nathan Feger",
"author_id": 8563,
"author_profile": "https://Stackoverflow.com/users/8563",
"pm_score": 0,
"selected": false,
"text": "<p>I would write something that loads the python script up. This way you could even get energetic and include formatting and styling of the code. You could even write it in python since you will not have precluded that by file extension.</p>\n"
},
{
"answer_id": 135890,
"author": "Mez",
"author_id": 20010,
"author_profile": "https://Stackoverflow.com/users/20010",
"pm_score": 0,
"selected": false,
"text": "<pre><code><IfModule mime_module>\n <Files *.py>\n ForceType text/plain\n </Files>\n</IfModule>\n</code></pre>\n\n<p>in a .htaccess for the folder should work ;)</p>\n"
},
{
"answer_id": 135895,
"author": "djsadinoff",
"author_id": 22369,
"author_profile": "https://Stackoverflow.com/users/22369",
"pm_score": 3,
"selected": true,
"text": "<p>In your .htaccess:</p>\n\n<blockquote>\n <p>RemoveHandler .py </p>\n</blockquote>\n"
}
]
| 2008/09/25 | [
"https://Stackoverflow.com/questions/135849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30/"
]
| I'm trying to host a python script using an apache web server, but the server tries to run the script instead of just offering it for download.
I do not have direct access to server, and adding the line
```
AddType text/plain .py
```
to .htaccess in the root folder does not appear to work, though I could be doing something wrong.
How do I get the server to just send the file as text instead of trying to run it?
-Edit
Changing the name does not work. Script.py.safe still give a 500 Server error when you click it.
I should also mention that the .htaccess file does work, but for some reason that one addType line is not working. Either because it's not overriding something, or the line is wrong. | In your .htaccess:
>
> RemoveHandler .py
>
>
> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.