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
198,526
<p>How do I determine if the currency symbol is supposed to be on the left or right of a number using CFLocale / CFNumberFormatter in a Mac Carbon project?</p> <p>I need to interface with a spreadsheet application which requires me to pass a number, currency symbol, currency symbol location and padding instead of a CStringRef created with CFNumberFormatter.</p> <pre><code>CFLocaleRef currentLocale = CFLocaleCopyCurrent(); CFTypeRef currencySymbol = CFLocaleGetValue (currentLocale, kCFLocaleCurrencySymbol); </code></pre> <p>provides me with the currency symbol as a string. But I'm lost on how to determine the position of the currency symbol...</p>
[ { "answer_id": 200245, "author": "Hans Martin Kern", "author_id": 27559, "author_profile": "https://Stackoverflow.com/users/27559", "pm_score": 2, "selected": false, "text": "<p>As a workaround, I have started to create a string representing a currency value and determining the position of the currency symbol by searching the string, but this sure looks fishy to me.</p>\n\n<pre><code> CFNumberFormatterRef numberFormatter = CFNumberFormatterCreate(kCFAllocatorDefault, CFLocaleCopyCurrent(), kCFNumberFormatterCurrencyStyle);\n double someNumber = 0;\n CFStringRef asString = CFNumberFormatterCreateStringWithValue(kCFAllocatorDefault, numberFormatter, kCFNumberDoubleType, &amp;someNumber);\n</code></pre>\n\n<p>...</p>\n\n<p>Feel free to hit me with a rolled-up newspaper and tell me the real answer...</p>\n" }, { "answer_id": 237653, "author": "Colin Barrett", "author_id": 23106, "author_profile": "https://Stackoverflow.com/users/23106", "pm_score": 0, "selected": false, "text": "<p>You could try inspecting the format string returned from <code>CFNumberFormatterGetFormat</code>. It <a href=\"http://unicode.org/reports/tr35/tr35-6.html#Number_Format_Patterns\" rel=\"nofollow noreferrer\">looks like</a> you want to search for <code>¤</code> which is <code>\\u00A4</code>.</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27559/" ]
How do I determine if the currency symbol is supposed to be on the left or right of a number using CFLocale / CFNumberFormatter in a Mac Carbon project? I need to interface with a spreadsheet application which requires me to pass a number, currency symbol, currency symbol location and padding instead of a CStringRef created with CFNumberFormatter. ``` CFLocaleRef currentLocale = CFLocaleCopyCurrent(); CFTypeRef currencySymbol = CFLocaleGetValue (currentLocale, kCFLocaleCurrencySymbol); ``` provides me with the currency symbol as a string. But I'm lost on how to determine the position of the currency symbol...
As a workaround, I have started to create a string representing a currency value and determining the position of the currency symbol by searching the string, but this sure looks fishy to me. ``` CFNumberFormatterRef numberFormatter = CFNumberFormatterCreate(kCFAllocatorDefault, CFLocaleCopyCurrent(), kCFNumberFormatterCurrencyStyle); double someNumber = 0; CFStringRef asString = CFNumberFormatterCreateStringWithValue(kCFAllocatorDefault, numberFormatter, kCFNumberDoubleType, &someNumber); ``` ... Feel free to hit me with a rolled-up newspaper and tell me the real answer...
198,532
<p>In <code>.NET</code> (at least in the 2008 version, and maybe in 2005 as well), changing the <code>BackColor</code> property of a <code>DateTimePicker</code> has absolutely no affect on the appearance. How do I change the background color of the text area, not of the drop-down calendar?</p> <p><strong><em>Edit:</em></strong> I was talking about Windows forms, not ASP.</p>
[ { "answer_id": 199278, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 5, "selected": true, "text": "<p>According to <a href=\"http://msdn.microsoft.com/en-us/library/0625h0ta.aspx\" rel=\"nofollow noreferrer\">MSDN</a> : </p>\n\n<blockquote>\n <p>Setting the <code>BackColor</code> has no effect on\n the appearance of the <code>DateTimePicker</code>.</p>\n</blockquote>\n\n<p>You need to write a custom control that extends <code>DateTimePicker</code>. Override the <code>BackColor</code> property and the <code>WndProc</code> method. </p>\n\n<p>Whenever you change the <code>BackColor</code>, don't forget to call the <code>myDTPicker.Invalidate()</code> method. This will force the control to redrawn using the new color specified.</p>\n\n<pre><code>const int WM_ERASEBKGND = 0x14;\nprotected override void WndProc(ref System.Windows.Forms.Message m)\n{\n if(m.Msg == WM_ERASEBKGND)\n {\n using(var g = Graphics.FromHdc(m.WParam))\n {\n using(var b = new SolidBrush(_backColor))\n {\n g.FillRectangle(b, ClientRectangle);\n }\n }\n return;\n }\n\n base.WndProc(ref m);\n}\n</code></pre>\n" }, { "answer_id": 1202804, "author": "Gustavo", "author_id": 2015, "author_profile": "https://Stackoverflow.com/users/2015", "pm_score": 3, "selected": false, "text": "<p>There is a free implementation derived from <code>DateTimePicker</code> that allows you to change <code>BackColor</code> property on change.</p>\n\n<p>See the CodeProject website: <a href=\"http://www.codeproject.com/KB/selection/DateTimePicker_With_BackC.aspx\" rel=\"nofollow noreferrer\"><code>DateTimePicker</code> with working <code>BackColor</code></a></p>\n" }, { "answer_id": 46486746, "author": "Carlos Borau", "author_id": 4676223, "author_profile": "https://Stackoverflow.com/users/4676223", "pm_score": 3, "selected": false, "text": "<p>Based on this CodeProject: <a href=\"https://www.codeproject.com/Articles/30660/A-DateTimePicker-with-working-BackColor\" rel=\"nofollow noreferrer\">A DateTimePicker with working BackColor</a> (as posted above) I've rewritten a custom datepicker class (in VB.NET) which allows customizing the Background color, the TextColor and the small Image appearing next to the dropdown button. </p>\n\n<p>Eg.1:</p>\n\n<p><a href=\"https://i.stack.imgur.com/LSZ4x.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/LSZ4x.png\" alt=\"enter image description here\"></a></p>\n\n<p>Eg.2: </p>\n\n<p><a href=\"https://i.stack.imgur.com/ZoHfk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZoHfk.png\" alt=\"enter image description here\"></a></p>\n\n<p>To make it work just create a new class in your project with the following code and Rebuild the Solution.<br>\nA new control called <code>MyDateTimePicker</code> should now appear in the toolbox list:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Public Class MyDateTimePicker \n Inherits System.Windows.Forms.DateTimePicker\n Private _disabled_back_color As Color\n Private _image As Image\n Private _text_color As Color = Color.Black\n\n Public Sub New()\n MyBase.New()\n Me.SetStyle(ControlStyles.UserPaint, True)\n _disabled_back_color = Color.FromKnownColor(KnownColor.Control)\n End Sub\n\n ''' &lt;summary&gt;\n ''' Gets or sets the background color of the control\n ''' &lt;/summary&gt;\n &lt;Browsable(True)&gt;\n Public Overrides Property BackColor() As Color\n Get\n Return MyBase.BackColor\n End Get\n Set\n MyBase.BackColor = Value\n End Set\n End Property\n\n ''' &lt;summary&gt;\n ''' Gets or sets the background color of the control when disabled\n ''' &lt;/summary&gt;\n &lt;Category(\"Appearance\"), Description(\"The background color of the component when disabled\")&gt;\n &lt;Browsable(True)&gt;\n Public Property BackDisabledColor() As Color\n Get\n Return _disabled_back_color\n End Get\n Set\n _disabled_back_color = Value\n End Set\n End Property\n\n ''' &lt;summary&gt;\n ''' Gets or sets the Image next to the dropdownbutton\n ''' &lt;/summary&gt;\n &lt;Category(\"Appearance\"),\n Description(\"Get or Set the small Image next to the dropdownbutton\")&gt;\n Public Property Image() As Image\n Get\n Return _image\n End Get\n Set(ByVal Value As Image)\n _image = Value\n Invalidate()\n End Set\n End Property\n\n ''' &lt;summary&gt;\n ''' Gets or sets the text color when calendar is not visible\n ''' &lt;/summary&gt;\n &lt;Category(\"Appearance\")&gt;\n Public Property TextColor As Color\n Get\n Return _text_color\n End Get\n Set(value As Color)\n _text_color = value\n End Set\n End Property\n\n\n Protected Overrides Sub OnPaint(e As System.Windows.Forms.PaintEventArgs)\n Dim g As Graphics = Me.CreateGraphics()\n g.TextRenderingHint = Drawing.Text.TextRenderingHint.ClearTypeGridFit\n\n 'Dropdownbutton rectangle\n Dim ddb_rect As New Rectangle(ClientRectangle.Width - 17, 0, 17, ClientRectangle.Height)\n 'Background brush\n Dim bb As Brush\n\n Dim visual_state As ComboBoxState\n\n 'When enabled the brush is set to Backcolor, \n 'otherwise to color stored in _disabled_back_Color\n If Me.Enabled Then\n bb = New SolidBrush(Me.BackColor)\n visual_state = ComboBoxState.Normal\n Else\n bb = New SolidBrush(Me._disabled_back_color)\n visual_state = ComboBoxState.Disabled\n End If\n\n 'Filling the background\n g.FillRectangle(bb, 0, 0, ClientRectangle.Width, ClientRectangle.Height)\n\n 'Drawing the datetime text\n g.DrawString(Me.Text, Me.Font, New SolidBrush(TextColor), 5, 2)\n\n 'Drawing icon\n If Not _image Is Nothing Then\n Dim im_rect As New Rectangle(ClientRectangle.Width - 40, 4, ClientRectangle.Height - 8, ClientRectangle.Height - 8)\n g.DrawImage(_image, im_rect)\n End If\n\n 'Drawing the dropdownbutton using ComboBoxRenderer\n ComboBoxRenderer.DrawDropDownButton(g, ddb_rect, visual_state)\n\n g.Dispose()\n bb.Dispose()\n End Sub\nEnd Class\n</code></pre>\n\n<p>*Note that this class is simplified, so it has limited functionallity</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27302/" ]
In `.NET` (at least in the 2008 version, and maybe in 2005 as well), changing the `BackColor` property of a `DateTimePicker` has absolutely no affect on the appearance. How do I change the background color of the text area, not of the drop-down calendar? ***Edit:*** I was talking about Windows forms, not ASP.
According to [MSDN](http://msdn.microsoft.com/en-us/library/0625h0ta.aspx) : > > Setting the `BackColor` has no effect on > the appearance of the `DateTimePicker`. > > > You need to write a custom control that extends `DateTimePicker`. Override the `BackColor` property and the `WndProc` method. Whenever you change the `BackColor`, don't forget to call the `myDTPicker.Invalidate()` method. This will force the control to redrawn using the new color specified. ``` const int WM_ERASEBKGND = 0x14; protected override void WndProc(ref System.Windows.Forms.Message m) { if(m.Msg == WM_ERASEBKGND) { using(var g = Graphics.FromHdc(m.WParam)) { using(var b = new SolidBrush(_backColor)) { g.FillRectangle(b, ClientRectangle); } } return; } base.WndProc(ref m); } ```
198,535
<p>I have small page which has label, DropDownList and a submit button.</p> <pre><code>&lt;div&gt; &lt;asp:label id=&quot;Message&quot; runat=&quot;server&quot;/&gt; &lt;br /&gt; Which city do you wish to look at on hotels for?&lt;br /&gt;&lt;br /&gt; &lt;asp:dropdownlist id=&quot;Dropdownlist1&quot; runat=&quot;server&quot; EnableViewState=&quot;true&quot;&gt; &lt;/asp:dropdownlist&gt; &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt; &lt;input type=&quot;Submit&quot; /&gt; &lt;/div&gt; </code></pre> <p>On form load I am inserting items into the DropDownList and on the button click I am displaying the count of the items in the DropDownList. Here's the code for that.</p> <code> if (Page.IsPostBack) { Message.Text = "You have selected " + Dropdownlist1.Items.Count.ToString(); } else { Message.Text = "You have selected " + Dropdownlist1.Items.Count.ToString(); Dropdownlist1.Items.Add("Madrid"); Dropdownlist1.Items.Add("Chennai"); Dropdownlist1.Items.Add("New York"); } </code> <p>Here's the funny part. If I run it directly from the IDE, its working perfectly fine. I get the count as 0 the first time and 3 when I press submit button. I need to run this small code on an existing virtual directory. If I run the same aspx page within that virtual directory, I get count 0 for the for the first time it loads. When I click submit, I get count as 0 and I don't see any items in the DropDownList, it is getting cleared. I have set ViewState to true so that I remember what was inserted.</p> <p>I am not sure what difference is there when I run it from IDE and when I run it from another virtual directory. I am fairly new to Asp.Net so I have exhuasted all my options here so to find out how a DropDownList works. Is there a config I am missing here ?.</p> <p>BTW just FYI, I am facing the same issue when I put the DropDownList in a Wizard Control. When run from IDE it is working fine but when I run from the virtual directory its not getting the selected value neither is it remembering the items in the DropDownList.</p> <blockquote> <p>According to your code the list only gets populated when it is not a PostBack. Therefore when you click the button the list will be empty.If you dynamically populate the list, the items are not remembered. You must added in each Page_load. The view state will only remember which item was selected.</p> </blockquote> <p>How it does then remember the items when the page is executed directly from the IDE and not remember when I run from a virtual directory. Is there a view state that I might need to set to get it working. The cache setting also did not do much luck. I enabled Trace info, funny thing again :|, tracing is happening when executed directly from the IDE and not from the virual directory. Question again, the child directory's <code>web.config</code> should override the parent <code>web.config</code> right?</p>
[ { "answer_id": 198547, "author": "tpower", "author_id": 18107, "author_profile": "https://Stackoverflow.com/users/18107", "pm_score": 0, "selected": false, "text": "<p>Maybe the page is being cached when in a virtual directory.</p>\n\n<p>Try adding this to the Page_Load</p>\n\n<pre><code>Response.Cache.SetCacheability(HttpCacheability.NoCache)\n</code></pre>\n\n<p>I think caching can be applied to directories using a config file. So may be this is the difference.</p>\n" }, { "answer_id": 198675, "author": "Gordon Bell", "author_id": 16473, "author_profile": "https://Stackoverflow.com/users/16473", "pm_score": 3, "selected": true, "text": "<p>It sounds like you may have EnableViewState disabled at the page level. Contrary to the other responses, you don't need to repopulate your lists on PostBack if ViewState is enabled.</p>\n\n<p>Try adding the EnableViewState=\"true\" attribute in your page header.</p>\n\n<p>I think it is a bug. If EnableViewState=\"false\" at the page level, and EnableViewState=\"true\" at the control level, ViewState isn't retained for the control like it should be.</p>\n\n<p>If you only want to enable ViewState for certain controls, set EnableViewState=\"true\" at the page level, and then EnableViewState=\"false\" for the controls which you don't want to retain ViewState for. Backwards, I know, but it's the only workaround.</p>\n" }, { "answer_id": 13134015, "author": "Siddhesh Bondre", "author_id": 1784773, "author_profile": "https://Stackoverflow.com/users/1784773", "pm_score": 2, "selected": false, "text": "<p>This worked for me</p>\n\n<pre><code> protected void Page_Load(object sender, EventArgs e)\n{\n if(!IsPostBack)\n FillApplicationDropDown();\n}\n</code></pre>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2245/" ]
I have small page which has label, DropDownList and a submit button. ``` <div> <asp:label id="Message" runat="server"/> <br /> Which city do you wish to look at on hotels for?<br /><br /> <asp:dropdownlist id="Dropdownlist1" runat="server" EnableViewState="true"> </asp:dropdownlist> <br /><br /><br /><br /> <input type="Submit" /> </div> ``` On form load I am inserting items into the DropDownList and on the button click I am displaying the count of the items in the DropDownList. Here's the code for that. `if (Page.IsPostBack) { Message.Text = "You have selected " + Dropdownlist1.Items.Count.ToString(); } else { Message.Text = "You have selected " + Dropdownlist1.Items.Count.ToString(); Dropdownlist1.Items.Add("Madrid"); Dropdownlist1.Items.Add("Chennai"); Dropdownlist1.Items.Add("New York"); }` Here's the funny part. If I run it directly from the IDE, its working perfectly fine. I get the count as 0 the first time and 3 when I press submit button. I need to run this small code on an existing virtual directory. If I run the same aspx page within that virtual directory, I get count 0 for the for the first time it loads. When I click submit, I get count as 0 and I don't see any items in the DropDownList, it is getting cleared. I have set ViewState to true so that I remember what was inserted. I am not sure what difference is there when I run it from IDE and when I run it from another virtual directory. I am fairly new to Asp.Net so I have exhuasted all my options here so to find out how a DropDownList works. Is there a config I am missing here ?. BTW just FYI, I am facing the same issue when I put the DropDownList in a Wizard Control. When run from IDE it is working fine but when I run from the virtual directory its not getting the selected value neither is it remembering the items in the DropDownList. > > According to your code the list only gets populated when it is not a PostBack. Therefore when you click the button the list will be empty.If you dynamically populate the list, the items are not remembered. You must added in each Page\_load. The view state will only remember which item was selected. > > > How it does then remember the items when the page is executed directly from the IDE and not remember when I run from a virtual directory. Is there a view state that I might need to set to get it working. The cache setting also did not do much luck. I enabled Trace info, funny thing again :|, tracing is happening when executed directly from the IDE and not from the virual directory. Question again, the child directory's `web.config` should override the parent `web.config` right?
It sounds like you may have EnableViewState disabled at the page level. Contrary to the other responses, you don't need to repopulate your lists on PostBack if ViewState is enabled. Try adding the EnableViewState="true" attribute in your page header. I think it is a bug. If EnableViewState="false" at the page level, and EnableViewState="true" at the control level, ViewState isn't retained for the control like it should be. If you only want to enable ViewState for certain controls, set EnableViewState="true" at the page level, and then EnableViewState="false" for the controls which you don't want to retain ViewState for. Backwards, I know, but it's the only workaround.
198,543
<p>I have a third-party editor that basically comprises a textbox and a button (the DevExpress ButtonEdit control). I want to make a particular keystroke (<kbd>Alt</kbd> + <kbd>Down</kbd>) emulate clicking the button. In order to avoid writing this over and over, I want to make a generic KeyUp event handler that will raise the ButtonClick event. Unfortunately, there doesn't seem to be a method in the control that raises the ButtonClick event, so...</p> <p>How do I raise the event from an external function via reflection?</p>
[ { "answer_id": 198584, "author": "torial", "author_id": 13990, "author_profile": "https://Stackoverflow.com/users/13990", "pm_score": 3, "selected": false, "text": "<p>From <em><a href=\"http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/44b0d573-5c53-47b0-8e85-6056cbae95b0/\" rel=\"nofollow noreferrer\">Raising an event via reflection</a></em>, although I think the answer in <a href=\"http://en.wikipedia.org/wiki/Visual_Basic_.NET\" rel=\"nofollow noreferrer\">VB.NET</a>, that is, two posts ahead of this one will provide you with the generic approach (for example, I'd look to the VB.NET one for inspiration on referencing a type not in the same class):</p>\n\n<pre><code> public event EventHandler&lt;EventArgs&gt; MyEventToBeFired;\n\n public void FireEvent(Guid instanceId, string handler)\n {\n\n // Note: this is being fired from a method with in the same\n // class that defined the event (that is, \"this\").\n\n EventArgs e = new EventArgs(instanceId);\n\n MulticastDelegate eventDelagate =\n (MulticastDelegate)this.GetType().GetField(handler,\n System.Reflection.BindingFlags.Instance |\n System.Reflection.BindingFlags.NonPublic).GetValue(this);\n\n Delegate[] delegates = eventDelagate.GetInvocationList();\n\n foreach (Delegate dlg in delegates)\n {\n dlg.Method.Invoke(dlg.Target, new object[] { this, e });\n }\n }\n\n FireEvent(new Guid(), \"MyEventToBeFired\");\n</code></pre>\n" }, { "answer_id": 198587, "author": "MichaelGG", "author_id": 27012, "author_profile": "https://Stackoverflow.com/users/27012", "pm_score": 4, "selected": false, "text": "<p>You can't normally raise another classes events. Events are really stored as a private delegate field, plus two accessors (add_event and remove_event). </p>\n\n<p>To do it via reflection, you simply need to find the private delegate field, get it, then invoke it.</p>\n" }, { "answer_id": 198593, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "<p>In general, you can't. Think of events as basically pairs of <code>AddHandler</code>/<code>RemoveHandler</code> methods (as that's basically what what they are). How they're implemented is up to the class. Most WinForms controls use <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.eventhandlerlist.aspx\" rel=\"nofollow noreferrer\"><code>EventHandlerList</code></a> as their implementation, but your code will be very brittle if it starts fetching private fields and keys.</p>\n\n<p>Does the <code>ButtonEdit</code> control expose an <code>OnClick</code> method which you could call?</p>\n\n<p>Footnote: Actually, events <em>can</em> have \"raise\" members, hence <code>EventInfo.GetRaiseMethod</code>. However, this is never populated by C# and I don't believe it's in the framework in general, either.</p>\n" }, { "answer_id": 201444, "author": "Josh Kodroff", "author_id": 549, "author_profile": "https://Stackoverflow.com/users/549", "pm_score": 3, "selected": false, "text": "<p>As it turns out, I could do this and didn't realize it:</p>\n\n<pre><code>buttonEdit1.Properties.Buttons[0].Shortcut = new DevExpress.Utils.KeyShortcut(Keys.Alt | Keys.Down);\n</code></pre>\n\n<p>But if I couldn't I would've have to delve into the source code and find the method that raises the event.</p>\n\n<p>Thanks for the help, all.</p>\n" }, { "answer_id": 585846, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>If you know that the control is a button you can call its <code>PerformClick()</code> method. I have similar problem for other events like <code>OnEnter</code>, <code>OnExit</code>. I can't raise those events if I don't want to derive a new type for each control type.</p>\n" }, { "answer_id": 586156, "author": "Wiebe Cnossen", "author_id": 70868, "author_profile": "https://Stackoverflow.com/users/70868", "pm_score": 6, "selected": true, "text": "<p>Here's a demo using generics (error checks omitted):</p>\n\n<pre><code>using System;\nusing System.Reflection;\nstatic class Program {\n private class Sub {\n public event EventHandler&lt;EventArgs&gt; SomethingHappening;\n }\n internal static void Raise&lt;TEventArgs&gt;(this object source, string eventName, TEventArgs eventArgs) where TEventArgs : EventArgs\n {\n var eventDelegate = (MulticastDelegate)source.GetType().GetField(eventName, BindingFlags.Instance | BindingFlags.NonPublic).GetValue(source);\n if (eventDelegate != null)\n {\n foreach (var handler in eventDelegate.GetInvocationList())\n {\n handler.Method.Invoke(handler.Target, new object[] { source, eventArgs });\n }\n }\n }\n public static void Main()\n {\n var p = new Sub();\n p.Raise(\"SomethingHappening\", EventArgs.Empty);\n p.SomethingHappening += (o, e) =&gt; Console.WriteLine(\"Foo!\");\n p.Raise(\"SomethingHappening\", EventArgs.Empty);\n p.SomethingHappening += (o, e) =&gt; Console.WriteLine(\"Bar!\");\n p.Raise(\"SomethingHappening\", EventArgs.Empty);\n Console.ReadLine();\n }\n}\n</code></pre>\n" }, { "answer_id": 3312601, "author": "The Chris", "author_id": 399525, "author_profile": "https://Stackoverflow.com/users/399525", "pm_score": 3, "selected": false, "text": "<p>I wrote an extension to classes, which implements INotifyPropertyChanged to inject the RaisePropertyChange&lt;T> method, so I can use it like this:</p>\n\n<pre><code>this.RaisePropertyChanged(() =&gt; MyProperty);\n</code></pre>\n\n<p>without implementing the method in any base class. For my usage it was to slow, but maybe the source code can help someone.</p>\n\n<p>So here it is:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Linq.Expressions;\nusing System.Reflection;\nusing System.Globalization;\n\nnamespace Infrastructure\n{\n /// &lt;summary&gt;\n /// Adds a RaisePropertyChanged method to objects implementing INotifyPropertyChanged.\n /// &lt;/summary&gt;\n public static class NotifyPropertyChangeExtension\n {\n #region private fields\n\n private static readonly Dictionary&lt;string, PropertyChangedEventArgs&gt; eventArgCache = new Dictionary&lt;string, PropertyChangedEventArgs&gt;();\n private static readonly object syncLock = new object();\n\n #endregion\n\n #region the Extension's\n\n /// &lt;summary&gt;\n /// Verifies the name of the property for the specified instance.\n /// &lt;/summary&gt;\n /// &lt;param name=\"bindableObject\"&gt;The bindable object.&lt;/param&gt;\n /// &lt;param name=\"propertyName\"&gt;Name of the property.&lt;/param&gt;\n [Conditional(\"DEBUG\")]\n public static void VerifyPropertyName(this INotifyPropertyChanged bindableObject, string propertyName)\n {\n bool propertyExists = TypeDescriptor.GetProperties(bindableObject).Find(propertyName, false) != null;\n if (!propertyExists)\n throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture,\n \"{0} is not a public property of {1}\", propertyName, bindableObject.GetType().FullName));\n }\n\n /// &lt;summary&gt;\n /// Gets the property name from expression.\n /// &lt;/summary&gt;\n /// &lt;param name=\"notifyObject\"&gt;The notify object.&lt;/param&gt;\n /// &lt;param name=\"propertyExpression\"&gt;The property expression.&lt;/param&gt;\n /// &lt;returns&gt;a string containing the name of the property.&lt;/returns&gt;\n public static string GetPropertyNameFromExpression&lt;T&gt;(this INotifyPropertyChanged notifyObject, Expression&lt;Func&lt;T&gt;&gt; propertyExpression)\n {\n return GetPropertyNameFromExpression(propertyExpression);\n }\n\n /// &lt;summary&gt;\n /// Raises a property changed event.\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;&lt;/typeparam&gt;\n /// &lt;param name=\"bindableObject\"&gt;The bindable object.&lt;/param&gt;\n /// &lt;param name=\"propertyExpression\"&gt;The property expression.&lt;/param&gt;\n public static void RaisePropertyChanged&lt;T&gt;(this INotifyPropertyChanged bindableObject, Expression&lt;Func&lt;T&gt;&gt; propertyExpression)\n {\n RaisePropertyChanged(bindableObject, GetPropertyNameFromExpression(propertyExpression));\n }\n\n #endregion\n\n /// &lt;summary&gt;\n /// Raises the property changed on the specified bindable Object.\n /// &lt;/summary&gt;\n /// &lt;param name=\"bindableObject\"&gt;The bindable object.&lt;/param&gt;\n /// &lt;param name=\"propertyName\"&gt;Name of the property.&lt;/param&gt;\n private static void RaisePropertyChanged(INotifyPropertyChanged bindableObject, string propertyName)\n {\n bindableObject.VerifyPropertyName(propertyName);\n RaiseInternalPropertyChangedEvent(bindableObject, GetPropertyChangedEventArgs(propertyName));\n }\n\n /// &lt;summary&gt;\n /// Raises the internal property changed event.\n /// &lt;/summary&gt;\n /// &lt;param name=\"bindableObject\"&gt;The bindable object.&lt;/param&gt;\n /// &lt;param name=\"eventArgs\"&gt;The &lt;see cref=\"System.ComponentModel.PropertyChangedEventArgs\"/&gt; instance containing the event data.&lt;/param&gt;\n private static void RaiseInternalPropertyChangedEvent(INotifyPropertyChanged bindableObject, PropertyChangedEventArgs eventArgs)\n {\n // get the internal eventDelegate\n var bindableObjectType = bindableObject.GetType();\n\n // search the base type, which contains the PropertyChanged event field.\n FieldInfo propChangedFieldInfo = null;\n while (bindableObjectType != null)\n {\n propChangedFieldInfo = bindableObjectType.GetField(\"PropertyChanged\", BindingFlags.Instance | BindingFlags.NonPublic);\n if (propChangedFieldInfo != null)\n break;\n\n bindableObjectType = bindableObjectType.BaseType;\n }\n if (propChangedFieldInfo == null)\n return;\n\n // get prop changed event field value\n var fieldValue = propChangedFieldInfo.GetValue(bindableObject);\n if (fieldValue == null)\n return;\n\n MulticastDelegate eventDelegate = fieldValue as MulticastDelegate;\n if (eventDelegate == null)\n return;\n\n // get invocation list\n Delegate[] delegates = eventDelegate.GetInvocationList();\n\n // invoke each delegate\n foreach (Delegate propertyChangedDelegate in delegates)\n propertyChangedDelegate.Method.Invoke(propertyChangedDelegate.Target, new object[] { bindableObject, eventArgs });\n }\n\n /// &lt;summary&gt;\n /// Gets the property name from an expression.\n /// &lt;/summary&gt;\n /// &lt;param name=\"propertyExpression\"&gt;The property expression.&lt;/param&gt;\n /// &lt;returns&gt;The property name as string.&lt;/returns&gt;\n private static string GetPropertyNameFromExpression&lt;T&gt;(Expression&lt;Func&lt;T&gt;&gt; propertyExpression)\n {\n var lambda = (LambdaExpression)propertyExpression;\n\n MemberExpression memberExpression;\n\n if (lambda.Body is UnaryExpression)\n {\n var unaryExpression = (UnaryExpression)lambda.Body;\n memberExpression = (MemberExpression)unaryExpression.Operand;\n }\n else memberExpression = (MemberExpression)lambda.Body;\n\n return memberExpression.Member.Name;\n }\n\n /// &lt;summary&gt;\n /// Returns an instance of PropertyChangedEventArgs for the specified property name.\n /// &lt;/summary&gt;\n /// &lt;param name=\"propertyName\"&gt;\n /// The name of the property to create event args for.\n /// &lt;/param&gt;\n private static PropertyChangedEventArgs GetPropertyChangedEventArgs(string propertyName)\n {\n PropertyChangedEventArgs args;\n\n lock (NotifyPropertyChangeExtension.syncLock)\n {\n if (!eventArgCache.TryGetValue(propertyName, out args))\n eventArgCache.Add(propertyName, args = new PropertyChangedEventArgs(propertyName));\n }\n\n return args;\n }\n }\n}\n</code></pre>\n\n<p>I removed some parts of the original code, so the extension should work as is, without references to other parts of my library. But it's not really tested.</p>\n\n<p>P.S. Some parts of the code was borrowed from someone else. Shame on me, that I forgot from where I got it. :(</p>\n" }, { "answer_id": 37498170, "author": "bitbonk", "author_id": 4227, "author_profile": "https://Stackoverflow.com/users/4227", "pm_score": 3, "selected": false, "text": "<p>It seems that the code from the <a href=\"https://stackoverflow.com/a/586156/4227\">accepted answer</a> by Wiebe Cnossen could be simplified to this:</p>\n\n<pre><code>private void RaiseEventViaReflection(object source, string eventName)\n{\n ((Delegate)source\n .GetType()\n .GetField(eventName, BindingFlags.Instance | BindingFlags.NonPublic)\n .GetValue(source))\n .DynamicInvoke(source, EventArgs.Empty);\n}\n</code></pre>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/549/" ]
I have a third-party editor that basically comprises a textbox and a button (the DevExpress ButtonEdit control). I want to make a particular keystroke (`Alt` + `Down`) emulate clicking the button. In order to avoid writing this over and over, I want to make a generic KeyUp event handler that will raise the ButtonClick event. Unfortunately, there doesn't seem to be a method in the control that raises the ButtonClick event, so... How do I raise the event from an external function via reflection?
Here's a demo using generics (error checks omitted): ``` using System; using System.Reflection; static class Program { private class Sub { public event EventHandler<EventArgs> SomethingHappening; } internal static void Raise<TEventArgs>(this object source, string eventName, TEventArgs eventArgs) where TEventArgs : EventArgs { var eventDelegate = (MulticastDelegate)source.GetType().GetField(eventName, BindingFlags.Instance | BindingFlags.NonPublic).GetValue(source); if (eventDelegate != null) { foreach (var handler in eventDelegate.GetInvocationList()) { handler.Method.Invoke(handler.Target, new object[] { source, eventArgs }); } } } public static void Main() { var p = new Sub(); p.Raise("SomethingHappening", EventArgs.Empty); p.SomethingHappening += (o, e) => Console.WriteLine("Foo!"); p.Raise("SomethingHappening", EventArgs.Empty); p.SomethingHappening += (o, e) => Console.WriteLine("Bar!"); p.Raise("SomethingHappening", EventArgs.Empty); Console.ReadLine(); } } ```
198,564
<p>I have apache web server installed as frontend and I have j2ee SAP Netweaver Application Server installed in Intranet server. How can I configure apache to forward requests and response to/from j2ee app server. for example, external apache server's ip is 9.20.1.1:80. internal sap server's address is 192.168.0.1/sap/bc/gui/sap/its/webgui?sap_client=200 I want access to my sap app server for example 9.20.1.1/sapserver/sap/bc/gui/sap/its/webgui?sap_client=200</p>
[ { "answer_id": 198611, "author": "Mark Roddy", "author_id": 9940, "author_profile": "https://Stackoverflow.com/users/9940", "pm_score": 1, "selected": false, "text": "<p>Assuming you have mod_proxy enabled, add to you're sites-available:</p>\n\n<pre><code> ProxyRequests Off\n &lt;Location \"/sapserver\"&gt;\n ProxyPass http://192.168.0.1\n ProxyPassReverse http://192.168.0.1\n &lt;/Location&gt;\n</code></pre>\n\n<p>Be careful though as this does expose your internal site to the entire internet.</p>\n" }, { "answer_id": 198630, "author": "jrwren", "author_id": 16998, "author_profile": "https://Stackoverflow.com/users/16998", "pm_score": 2, "selected": false, "text": "<p>This is often mistakenly referred to as a reverse proxy. If you use a search engine to find \"reverse proxy apache\" you will get many good results.</p>\n\n<p>The quick answer is to add something like this to your apache.conf</p>\n\n<blockquote>\n <p>ProxyPass /sap/ 192.168.0.1/sap/</p>\n \n <p>&lt; Location /sap/ ></p>\n\n<pre><code> ProxyPassReverse /sap/ \n</code></pre>\n \n <p>&lt; /Location ></p>\n</blockquote>\n\n<p>See also the modrewrite rools and the [P] option.</p>\n" }, { "answer_id": 202111, "author": "MattMcKnight", "author_id": 8136, "author_profile": "https://Stackoverflow.com/users/8136", "pm_score": 3, "selected": true, "text": "<p>You mentioned load balancing- so presumably you want to be able to add more Application Servers that are served through a single address. I hope they are stateless or storing session information in a database. You can use Apache to serve as a reverse proxy load balancer with <code>mod_proxy_balancer</code>. Docs are <a href=\"http://httpd.apache.org/docs/2.2/mod/mod_proxy_balancer.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Here's an example of what to add to your httpd.conf from <a href=\"http://blog.innerewut.de/2006/4/21/scaling-rails-with-apache-2-2-mod_proxy_balancer-and-mongrel\" rel=\"nofollow noreferrer\">this link</a>.</p>\n\n<pre><code> &lt;Proxy balancer://myclustername&gt;\n # cluster member 1\n BalancerMember http://192.168.0.1:3000 \n BalancerMember http://192.168.0.1:3001\n\n # cluster member 2, the fastest machine so double the load\n BalancerMember http://192.168.0.11:3000 loadfactor=2\n BalancerMember http://192.168.0.11:3001 loadfactor=2\n\n # cluster member 3\n BalancerMember http://192.168.0.12:3000\n BalancerMember http://192.168.0.12:3001\n\n # cluster member 4\n BalancerMember http://192.168.0.13:3000\n BalancerMember http://192.168.0.13:3001\n&lt;/Proxy&gt;\n\n&lt;VirtualHost *:80&gt;\n ServerAdmin [email protected]\n ServerName www.meinprof.de\n ServerAlias meinprof.de\n ProxyPass / balancer://meinprofcluster/\n ProxyPassReverse / balancer://meinprofcluster/\n ErrorLog /var/log/www/www.meinprof.de/apache_error_log\n CustomLog /var/log/www/www.meinprof.de/apache_access_log combined\n&lt;/VirtualHost&gt;\n</code></pre>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27563/" ]
I have apache web server installed as frontend and I have j2ee SAP Netweaver Application Server installed in Intranet server. How can I configure apache to forward requests and response to/from j2ee app server. for example, external apache server's ip is 9.20.1.1:80. internal sap server's address is 192.168.0.1/sap/bc/gui/sap/its/webgui?sap\_client=200 I want access to my sap app server for example 9.20.1.1/sapserver/sap/bc/gui/sap/its/webgui?sap\_client=200
You mentioned load balancing- so presumably you want to be able to add more Application Servers that are served through a single address. I hope they are stateless or storing session information in a database. You can use Apache to serve as a reverse proxy load balancer with `mod_proxy_balancer`. Docs are [here](http://httpd.apache.org/docs/2.2/mod/mod_proxy_balancer.html). Here's an example of what to add to your httpd.conf from [this link](http://blog.innerewut.de/2006/4/21/scaling-rails-with-apache-2-2-mod_proxy_balancer-and-mongrel). ``` <Proxy balancer://myclustername> # cluster member 1 BalancerMember http://192.168.0.1:3000 BalancerMember http://192.168.0.1:3001 # cluster member 2, the fastest machine so double the load BalancerMember http://192.168.0.11:3000 loadfactor=2 BalancerMember http://192.168.0.11:3001 loadfactor=2 # cluster member 3 BalancerMember http://192.168.0.12:3000 BalancerMember http://192.168.0.12:3001 # cluster member 4 BalancerMember http://192.168.0.13:3000 BalancerMember http://192.168.0.13:3001 </Proxy> <VirtualHost *:80> ServerAdmin [email protected] ServerName www.meinprof.de ServerAlias meinprof.de ProxyPass / balancer://meinprofcluster/ ProxyPassReverse / balancer://meinprofcluster/ ErrorLog /var/log/www/www.meinprof.de/apache_error_log CustomLog /var/log/www/www.meinprof.de/apache_access_log combined </VirtualHost> ```
198,577
<p>Is there any real practical difference between "java -server" and "java -client"? </p> <p>All I can find on Sun's site is a vague </p> <blockquote> <p>"-server starts slower but should run faster". </p> </blockquote> <p>What are the real differences? (Using JDK 1.6.0_07 currently.)</p>
[ { "answer_id": 198598, "author": "Brian Knoblauch", "author_id": 15689, "author_profile": "https://Stackoverflow.com/users/15689", "pm_score": 2, "selected": false, "text": "<p>I've not noticed any difference in startup time between the 2, but clocked a very minimal improvement in application performance with \"-server\" (Solaris server, everyone using SunRays to run the app). That was under 1.5.</p>\n" }, { "answer_id": 198616, "author": "Mike Akers", "author_id": 17188, "author_profile": "https://Stackoverflow.com/users/17188", "pm_score": 4, "selected": false, "text": "<p>IIRC the server VM does more hotspot optimizations at startup so it runs faster but takes a little longer to start and uses more memory. The client VM defers most of the optimization to allow faster startup.</p>\n\n<p>Edit to add: <a href=\"http://java.sun.com/docs/hotspot/HotSpotFAQ.html#compiler_types\" rel=\"noreferrer\">Here's some info</a> from Sun, it's not very specific but will give you some ideas.</p>\n" }, { "answer_id": 198649, "author": "Michael Easter", "author_id": 12704, "author_profile": "https://Stackoverflow.com/users/12704", "pm_score": 3, "selected": false, "text": "<p>IIRC, it involves garbage collection strategies. The theory is that a client and server will be different in terms of short-lived objects, which is important for modern GC algorithms.</p>\n\n<p><a href=\"http://www.jivesoftware.com/community/docs/DOC-1486\" rel=\"noreferrer\">Here is a link</a> on server mode. Alas, they don't mention client mode.</p>\n\n<p><a href=\"http://www.artima.com/insidejvm/ed2/gc.html\" rel=\"noreferrer\">Here is a very thorough link</a> on GC in general; this is a <a href=\"http://chaoticjava.com/posts/how-does-garbage-collection-work/\" rel=\"noreferrer\">more basic article</a>. Not sure if either address -server vs -client but this is relevant material.</p>\n\n<p>At No Fluff Just Stuff, both Ken Sipe and Glenn Vandenburg do great talks on this kind of thing.</p>\n" }, { "answer_id": 198651, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 10, "selected": true, "text": "<p>This is really linked to <em>HotSpot</em> and the default <em>option values</em> (<a href=\"http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html\" rel=\"noreferrer\">Java HotSpot VM Options</a>) which differ between client and server configuration.</p>\n<p>From <a href=\"http://www.oracle.com/technetwork/java/whitepaper-135217.html#2\" rel=\"noreferrer\">Chapter 2</a> of the whitepaper (<a href=\"http://www.oracle.com/technetwork/java/whitepaper-135217.html\" rel=\"noreferrer\">The Java HotSpot Performance Engine Architecture</a>):</p>\n<blockquote>\n<p>The JDK includes two flavors of the VM -- a client-side offering, and a VM tuned for server applications. These two solutions share the Java HotSpot runtime environment code base, but use different compilers that are suited to the distinctly unique performance characteristics of clients and servers. These differences include the compilation inlining policy and heap defaults.</p>\n<p>Although the Server and the Client VMs are similar, the Server VM has been specially tuned to maximize peak operating speed. It is intended for executing long-running server applications, which need the fastest possible operating speed more than a fast start-up time or smaller runtime memory footprint.</p>\n<p>The Client VM compiler serves as an upgrade for both the Classic VM and the just-in-time (JIT) compilers used by previous versions of the JDK. The Client VM offers improved run time performance for applications and applets. The Java HotSpot Client VM has been specially tuned to reduce application start-up time and memory footprint, making it particularly well suited for client environments. In general, the client system is better for GUIs.</p>\n</blockquote>\n<p>So the real difference is also on the compiler level:</p>\n<blockquote>\n<p>The Client VM compiler does not try to execute many of the more complex optimizations performed by the compiler in the Server VM, but in exchange, it requires less time to analyze and compile a piece of code. This means the Client VM can start up faster and requires a smaller memory footprint.</p>\n<p>The Server VM contains an advanced adaptive compiler that supports many of the same types of optimizations performed by optimizing C++ compilers, as well as some optimizations that cannot be done by traditional compilers, such as aggressive inlining across virtual method invocations. This is a competitive and performance advantage over static compilers. Adaptive optimization technology is very flexible in its approach, and typically outperforms even advanced static analysis and compilation techniques.</p>\n</blockquote>\n<p>Note: The release of <em>jdk6 update 10</em> (see <a href=\"http://www.oracle.com/technetwork/java/javase/6u10-142936.html\" rel=\"noreferrer\">Update Release Notes:Changes in 1.6.0_10</a>) tried to improve startup time, but for a different reason than the hotspot options, being packaged differently with a much smaller kernel.</p>\n<hr />\n<p><a href=\"https://stackoverflow.com/users/1037316/g-demecki\">G. Demecki</a> points out <a href=\"https://stackoverflow.com/questions/198577/real-differences-between-java-server-and-java-client/198651?noredirect=1#comment59707599_198651\">in the comments</a> that in 64-bit versions of JDK, the <code>-client</code> option is ignored for many years.<br />\nSee <a href=\"https://docs.oracle.com/javase/7/docs/technotes/tools/windows/java.html\" rel=\"noreferrer\">Windows <code>java</code> command</a>:</p>\n<pre><code>-client\n</code></pre>\n<blockquote>\n<p>Selects the Java HotSpot Client VM.<br />\n<strong>A 64-bit capable JDK currently ignores this option and instead uses the Java Hotspot Server VM</strong>.</p>\n</blockquote>\n<hr />\n<p>2022: <a href=\"https://stackoverflow.com/users/2711488/holger\">Holger</a> references in <a href=\"https://stackoverflow.com/questions/198577/real-differences-between-java-server-and-java-client/198651?noredirect=1#comment124789844_198651\">the comments</a> the <a href=\"https://docs.oracle.com/javase/6/docs/technotes/guides/vm/server-class.html\" rel=\"noreferrer\">JavaSE6 / Server-Class Machine Detection</a>, adding:</p>\n<blockquote>\n<p>Only on 32 bit Windows systems, <code>-client</code> was ever chosen unconditionally.<br />\nOther systems checked whether the machine was “server class” which was fulfilled when having at least 2 cores and at least 2GiB of memory.</p>\n<p>Which explains why almost everything uses <code>-server</code> for quite some time now. Even the cheapest computers you can find, are “server class” machines. The Sun/Oracle 64 builds did not even ship with a client JVM.</p>\n</blockquote>\n" }, { "answer_id": 3775811, "author": "prule", "author_id": 20242, "author_profile": "https://Stackoverflow.com/users/20242", "pm_score": 5, "selected": false, "text": "<p>One difference I've just noticed is that in \"client\" mode, it seems the JVM actually gives some unused memory back to the operating system, whereas with \"server\" mode, once the JVM grabs the memory, it won't give it back. Thats how it appears on Solaris with Java6 anyway (using <code>prstat -Z</code> to see the amount of memory allocated to a process).</p>\n" }, { "answer_id": 12003938, "author": "Mark Booth", "author_id": 42473, "author_profile": "https://Stackoverflow.com/users/42473", "pm_score": 7, "selected": false, "text": "<p>The most visible immediate difference in older versions of Java would be the memory allocated to a <code>-client</code> as opposed to a <code>-server</code> application. For instance, on my Linux system, I get:</p>\n\n<pre><code>$ java -XX:+PrintFlagsFinal -version 2&gt;&amp;1 | grep -i -E 'heapsize|permsize|version'\nuintx AdaptivePermSizeWeight = 20 {product}\nuintx ErgoHeapSizeLimit = 0 {product}\nuintx InitialHeapSize := 66328448 {product}\nuintx LargePageHeapSizeThreshold = 134217728 {product}\nuintx MaxHeapSize := 1063256064 {product}\nuintx MaxPermSize = 67108864 {pd product}\nuintx PermSize = 16777216 {pd product}\njava version \"1.6.0_24\"\n</code></pre>\n\n<p>as it defaults to <code>-server</code>, but with the <code>-client</code> option I get:</p>\n\n<pre><code>$ java -client -XX:+PrintFlagsFinal -version 2&gt;&amp;1 | grep -i -E 'heapsize|permsize|version'\nuintx AdaptivePermSizeWeight = 20 {product}\nuintx ErgoHeapSizeLimit = 0 {product}\nuintx InitialHeapSize := 16777216 {product}\nuintx LargePageHeapSizeThreshold = 134217728 {product}\nuintx MaxHeapSize := 268435456 {product}\nuintx MaxPermSize = 67108864 {pd product}\nuintx PermSize = 12582912 {pd product}\njava version \"1.6.0_24\"\n</code></pre>\n\n<p>so with <code>-server</code> most of the memory limits and initial allocations are much higher for this <code>java</code> version.</p>\n\n<p>These values can change for different combinations of architecture, operating system and jvm version however. Recent versions of the jvm have removed flags and re-moved many of the distinctions between server and client.</p>\n\n<p>Remember too that you can see all the details of a running <code>jvm</code> using <code>jvisualvm</code>. This is useful if you have users who or modules which set <code>JAVA_OPTS</code> or use scripts which change command line options. This will also let you monitor, in real time, <em>heap</em> and <em>permgen</em> space usage along with lots of other stats.</p>\n" }, { "answer_id": 15471505, "author": "pharsicle", "author_id": 181506, "author_profile": "https://Stackoverflow.com/users/181506", "pm_score": 5, "selected": false, "text": "<p>Oracle’s online documentation provides some information for Java SE 7.</p>\n\n<p>On the <a href=\"http://docs.oracle.com/javase/7/docs/technotes/tools/windows/java.html\">java – the Java application launcher</a> page for Windows, the <code>-client</code> option is ignored in a 64-bit JDK:</p>\n\n<blockquote>\n <p>Select the Java HotSpot Client VM. A 64-bit capable jdk currently ignores this option and instead uses the Java HotSpot Server VM. </p>\n</blockquote>\n\n<p>However (to make things interesting), under <code>-server</code> it states:</p>\n\n<blockquote>\n <p>Select the Java HotSpot Server VM. On a 64-bit capable jdk only the Java HotSpot Server VM is supported so the -server option is implicit. This is subject to change in a future release. </p>\n</blockquote>\n\n<p>The <a href=\"http://docs.oracle.com/javase/7/docs/technotes/guides/vm/server-class.html\">Server-Class Machine Detection</a> page gives information on which VM is selected by OS and architecture.</p>\n\n<p>I don’t know how much of this applies to JDK 6.</p>\n" }, { "answer_id": 15573364, "author": "brice", "author_id": 140264, "author_profile": "https://Stackoverflow.com/users/140264", "pm_score": 2, "selected": false, "text": "<p>Last time I had a look at this, (and admittedly it was a while back) the biggest difference I noticed was in the garbage collection. </p>\n\n<p>IIRC:</p>\n\n<ul>\n<li>The server heap VM has a differnt number of generations than the Client VM, and a different garbage collection algorithm. <strong>This may not be true anymore</strong></li>\n<li>The server VM will allocate memory and not release it to the OS</li>\n<li>The server VM will use more sophisticated optimisation algorithms, and hence have bigger time and memory requirements for optimisation</li>\n</ul>\n\n<p><s>If you can compare two java VMs, one client, one server using the <a href=\"http://visualvm.java.net/\" rel=\"nofollow\">jvisualvm</a> tool, you should see a difference in the frequency and effect of the garbage collection, as well as in the number of generations. </p>\n\n<p>I had a pair of screenshots that showed the difference really well, but I can't reproduce as I have a 64 bit JVM which only implements the server VM. (And I can't be bothered to download and wrangle the 32 bit version on my system as well.)</s></p>\n\n<p>This doesn't seem to be the case anymore, having tried running some code on windows with both server and client VMs, I seem to get the same generation model for both...</p>\n" }, { "answer_id": 29192128, "author": "Nuwan Arambage", "author_id": 572675, "author_profile": "https://Stackoverflow.com/users/572675", "pm_score": 1, "selected": false, "text": "<p>When doing a migration from 1.4 to 1.7(\"1.7.0_55\") version.The thing that we observed here is, there is no such differences in default values assigned to heapsize|permsize|ThreadStackSize parameters in client &amp; server mode. </p>\n\n<p>By the way, (<a href=\"http://www.oracle.com/technetwork/java/ergo5-140223.html\" rel=\"nofollow noreferrer\">http://www.oracle.com/technetwork/java/ergo5-140223.html</a>). This is the snippet taken from above link.</p>\n\n<pre><code>initial heap size of 1/64 of physical memory up to 1Gbyte\nmaximum heap size of ¼ of physical memory up to 1Gbyte\n</code></pre>\n\n<p>ThreadStackSize is higher in 1.7, while going through Open JDK forum,there are discussions which stated frame size is somewhat higher in 1.7 version.\nIt is believed real difference could be possible to measure at run time based on your behavior of your application</p>\n" }, { "answer_id": 31877125, "author": "Premraj", "author_id": 1697099, "author_profile": "https://Stackoverflow.com/users/1697099", "pm_score": 5, "selected": false, "text": "<p>the -client and -server systems are different binaries. They are essentially two different compilers (JITs) interfacing to the same runtime system. The client system is optimal for applications which need fast startup times or small footprints, the server system is optimal for applications where the overall performance is most important. In general the client system is better suited for interactive applications such as GUIs </p>\n\n<p><a href=\"https://i.stack.imgur.com/zkWjn.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/zkWjn.gif\" alt=\"enter image description here\"></a></p>\n\n<p>We run the following code with both switches:</p>\n\n<pre><code>package com.blogspot.sdoulger;\n\npublic class LoopTest {\n public LoopTest() {\n super();\n }\n\n public static void main(String[] args) {\n long start = System.currentTimeMillis();\n spendTime();\n long end = System.currentTimeMillis();\n System.out.println(\"Time spent: \"+ (end-start));\n\n LoopTest loopTest = new LoopTest();\n }\n\n private static void spendTime() {\n for (int i =500000000;i&gt;0;i--) {\n }\n }\n}\n</code></pre>\n\n<p><strong>Note:</strong> The code is been compiled only once! The classes are the same in both runs!</p>\n\n<p><strong>With -client:</strong><br>\n java.exe -client -classpath C:\\mywork\\classes com.blogspot.sdoulger.LoopTest<br>\n Time spent: 766 </p>\n\n<p><strong>With -server:</strong><br>\n java.exe -server -classpath C:\\mywork\\classes com.blogspot.sdoulger.LoopTest<br>\n Time spent: 0 </p>\n\n<p>It seems that the more aggressive optimazation of the server system, remove the loop as it understands that it does not perform any action!</p>\n\n<p><a href=\"http://www.javacodegeeks.com/2011/07/jvm-options-client-vs-server.html\" rel=\"noreferrer\">Reference</a></p>\n" }, { "answer_id": 35913837, "author": "Adam", "author_id": 1385174, "author_profile": "https://Stackoverflow.com/users/1385174", "pm_score": 4, "selected": false, "text": "<p>From Goetz - Java Concurrency in Practice:</p>\n<blockquote>\n<ol start=\"6\">\n<li>Debugging tip: For server applications, be sure to always specify the <code>-server</code> JVM command line switch when invoking the JVM, <strong>even for\ndevelopment and testing</strong>. The server JVM performs more optimization\nthan the client JVM, such as hoisting variables out of a loop that are\nnot modified in the loop; code that might appear to work in the\ndevelopment environment (client JVM) can break in the deployment\nenvironment (server JVM). For example, had we “forgotten” to declare\nthe variable asleep as volatile in Listing 3.4, <strong>the server JVM could\nhoist the test out of the loop (turning it into an infinite loop), but\nthe client JVM would not</strong>. An infinite loop that shows up in\ndevelopment is far less costly than one that only shows up in\nproduction.</li>\n</ol>\n</blockquote>\n<blockquote>\n<p>Listing 3.4. Counting sheep.</p>\n<pre class=\"lang-java prettyprint-override\"><code>volatile boolean asleep;\n...\nwhile (!asleep)\n countSomeSheep();\n</code></pre>\n</blockquote>\n<p>My emphasis. YMMV</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3333/" ]
Is there any real practical difference between "java -server" and "java -client"? All I can find on Sun's site is a vague > > "-server starts slower but should run faster". > > > What are the real differences? (Using JDK 1.6.0\_07 currently.)
This is really linked to *HotSpot* and the default *option values* ([Java HotSpot VM Options](http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html)) which differ between client and server configuration. From [Chapter 2](http://www.oracle.com/technetwork/java/whitepaper-135217.html#2) of the whitepaper ([The Java HotSpot Performance Engine Architecture](http://www.oracle.com/technetwork/java/whitepaper-135217.html)): > > The JDK includes two flavors of the VM -- a client-side offering, and a VM tuned for server applications. These two solutions share the Java HotSpot runtime environment code base, but use different compilers that are suited to the distinctly unique performance characteristics of clients and servers. These differences include the compilation inlining policy and heap defaults. > > > Although the Server and the Client VMs are similar, the Server VM has been specially tuned to maximize peak operating speed. It is intended for executing long-running server applications, which need the fastest possible operating speed more than a fast start-up time or smaller runtime memory footprint. > > > The Client VM compiler serves as an upgrade for both the Classic VM and the just-in-time (JIT) compilers used by previous versions of the JDK. The Client VM offers improved run time performance for applications and applets. The Java HotSpot Client VM has been specially tuned to reduce application start-up time and memory footprint, making it particularly well suited for client environments. In general, the client system is better for GUIs. > > > So the real difference is also on the compiler level: > > The Client VM compiler does not try to execute many of the more complex optimizations performed by the compiler in the Server VM, but in exchange, it requires less time to analyze and compile a piece of code. This means the Client VM can start up faster and requires a smaller memory footprint. > > > The Server VM contains an advanced adaptive compiler that supports many of the same types of optimizations performed by optimizing C++ compilers, as well as some optimizations that cannot be done by traditional compilers, such as aggressive inlining across virtual method invocations. This is a competitive and performance advantage over static compilers. Adaptive optimization technology is very flexible in its approach, and typically outperforms even advanced static analysis and compilation techniques. > > > Note: The release of *jdk6 update 10* (see [Update Release Notes:Changes in 1.6.0\_10](http://www.oracle.com/technetwork/java/javase/6u10-142936.html)) tried to improve startup time, but for a different reason than the hotspot options, being packaged differently with a much smaller kernel. --- [G. Demecki](https://stackoverflow.com/users/1037316/g-demecki) points out [in the comments](https://stackoverflow.com/questions/198577/real-differences-between-java-server-and-java-client/198651?noredirect=1#comment59707599_198651) that in 64-bit versions of JDK, the `-client` option is ignored for many years. See [Windows `java` command](https://docs.oracle.com/javase/7/docs/technotes/tools/windows/java.html): ``` -client ``` > > Selects the Java HotSpot Client VM. > > **A 64-bit capable JDK currently ignores this option and instead uses the Java Hotspot Server VM**. > > > --- 2022: [Holger](https://stackoverflow.com/users/2711488/holger) references in [the comments](https://stackoverflow.com/questions/198577/real-differences-between-java-server-and-java-client/198651?noredirect=1#comment124789844_198651) the [JavaSE6 / Server-Class Machine Detection](https://docs.oracle.com/javase/6/docs/technotes/guides/vm/server-class.html), adding: > > Only on 32 bit Windows systems, `-client` was ever chosen unconditionally. > > Other systems checked whether the machine was “server class” which was fulfilled when having at least 2 cores and at least 2GiB of memory. > > > Which explains why almost everything uses `-server` for quite some time now. Even the cheapest computers you can find, are “server class” machines. The Sun/Oracle 64 builds did not even ship with a client JVM. > > >
198,580
<p>What are optimal settings for Recycling of Application Pools in IIS7 in a shared environment?</p> <p><img src="https://i.stack.imgur.com/RNQo8.png" alt="enter image description here"></p>
[ { "answer_id": 198586, "author": "Daniel Silveira", "author_id": 1100, "author_profile": "https://Stackoverflow.com/users/1100", "pm_score": 2, "selected": false, "text": "<p>Tip: When you recycle your app, all your session variables are destroyed... so caution on this!</p>\n\n<p>IMHO, keep the defaults.</p>\n" }, { "answer_id": 198640, "author": "Ricardo Villamil", "author_id": 19314, "author_profile": "https://Stackoverflow.com/users/19314", "pm_score": 2, "selected": false, "text": "<p>If you have a heavy traffic site, use long recycle schedule. If you have a low traffic site use shorter/default schedule to save memory.</p>\n\n<p>I learned this from Al Zabir's blog: <a href=\"http://msmvps.com/blogs/omar/archive/2008/10/04/best-practices-for-creating-websites-in-iis-6-0.aspx\" rel=\"nofollow noreferrer\">http://msmvps.com/blogs/omar/archive/2008/10/04/best-practices-for-creating-websites-in-iis-6-0.aspx</a></p>\n\n<p>Daniel S. is right, your session variables get destroyed on recycle, so make sure you test this well or have good error protection/recovery when getting your session objects.</p>\n" }, { "answer_id": 201812, "author": "Christopher G. Lewis", "author_id": 13532, "author_profile": "https://Stackoverflow.com/users/13532", "pm_score": 6, "selected": true, "text": "<p>As a Hoster, you definitely want to recycle on Memory &amp; Time, potentially Request limits and CPU. You want to be pretty aggressive about these limits, but make sure you publish them to your clients.</p>\n\n<p><a href=\"https://technet.microsoft.com/en-us/library/cc725749(v=ws.10).aspx\" rel=\"noreferrer\"><strong>Memory</strong></a> - 512 for an x86 box, maybe 768. For x64, you can set this much higher depending on the number of hosts per server. You just have to be careful and watch your app pool recycle events on memory issues.</p>\n\n<p><a href=\"https://technet.microsoft.com/en-us/library/cc754494(v=ws.10).aspx\" rel=\"noreferrer\"><strong>Time</strong></a> - We typically recycle at 1 am in the morning, plus or minus (first site 1:01, second 1:11, third 1:21, just so you don't have all recycling at the same time) </p>\n\n<p><a href=\"https://technet.microsoft.com/en-us/library/cc770469(v=ws.10).aspx\" rel=\"noreferrer\"><strong>Request limit</strong></a> - 35,000 was the default for IIS6, but this number is quite arbitrary, and very dependant on the site in question. For small usage sites, the nightly recycle will hit long before you get 35k requests.</p>\n\n<p><a href=\"http://www.iis.net/configreference/system.applicationhost/applicationpools/add/cpu\" rel=\"noreferrer\"><strong>CPU</strong></a> - 95%/1 minute limit/KillW3WP, but use this carefully. My understanding of this is that if the CPU hits 95%+ over the 1 minute limit for this worker process, the worker process gets killed and is unable to restart for the remainder of the limit when Action is set to KillW3WP. You might want to try NoAction initially and just watch your event logs carefully.</p>\n\n<p><a href=\"https://technet.microsoft.com/en-us/library/cc771318(v=ws.10).aspx\" rel=\"noreferrer\"><strong>Recycle Event Logs</strong></a> - You want to make sure you are logging app pool recycles for each event threshhold that you set - i.e. if you limit based off of requests limits, make sure that Request Limit logging is enabled.</p>\n\n<p>One thing to remember is that you <em>should</em> set <code>retail=\"true\"</code> in the <code>&lt;deployment&gt;</code> element in your <a href=\"http://www.iis.net/learn/get-started/planning-your-iis-architecture/the-configuration-system-in-iis-7\" rel=\"noreferrer\">machine.config</a>:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;system.web&gt;\n &lt;!--\n &lt;deployment\n retail = \"false\" [true|false]\n /&gt;\n --&gt;\n &lt;deployment retail=\"true\" /&gt;\n&lt;/system.web&gt;\n</code></pre>\n\n<p>Not setting this will allow a site to turn debugging on, which allows unlimited timeouts in requests - not exactly ideal for a hoster...</p>\n" }, { "answer_id": 8574875, "author": "Jamie Savin", "author_id": 1107739, "author_profile": "https://Stackoverflow.com/users/1107739", "pm_score": 1, "selected": false, "text": "<p>you need to cater the settings to your needs, take into account the amount of memory you have and the peak times of usage for your site/web application.</p>\n\n<p>Also take into account the memory usage of your site/web application as if there are memory leaks you might be recycling more often then you think.</p>\n\n<p>Weigh up any leaks against the cost of recycling, as stated above you will lose state variables.</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23280/" ]
What are optimal settings for Recycling of Application Pools in IIS7 in a shared environment? ![enter image description here](https://i.stack.imgur.com/RNQo8.png)
As a Hoster, you definitely want to recycle on Memory & Time, potentially Request limits and CPU. You want to be pretty aggressive about these limits, but make sure you publish them to your clients. [**Memory**](https://technet.microsoft.com/en-us/library/cc725749(v=ws.10).aspx) - 512 for an x86 box, maybe 768. For x64, you can set this much higher depending on the number of hosts per server. You just have to be careful and watch your app pool recycle events on memory issues. [**Time**](https://technet.microsoft.com/en-us/library/cc754494(v=ws.10).aspx) - We typically recycle at 1 am in the morning, plus or minus (first site 1:01, second 1:11, third 1:21, just so you don't have all recycling at the same time) [**Request limit**](https://technet.microsoft.com/en-us/library/cc770469(v=ws.10).aspx) - 35,000 was the default for IIS6, but this number is quite arbitrary, and very dependant on the site in question. For small usage sites, the nightly recycle will hit long before you get 35k requests. [**CPU**](http://www.iis.net/configreference/system.applicationhost/applicationpools/add/cpu) - 95%/1 minute limit/KillW3WP, but use this carefully. My understanding of this is that if the CPU hits 95%+ over the 1 minute limit for this worker process, the worker process gets killed and is unable to restart for the remainder of the limit when Action is set to KillW3WP. You might want to try NoAction initially and just watch your event logs carefully. [**Recycle Event Logs**](https://technet.microsoft.com/en-us/library/cc771318(v=ws.10).aspx) - You want to make sure you are logging app pool recycles for each event threshhold that you set - i.e. if you limit based off of requests limits, make sure that Request Limit logging is enabled. One thing to remember is that you *should* set `retail="true"` in the `<deployment>` element in your [machine.config](http://www.iis.net/learn/get-started/planning-your-iis-architecture/the-configuration-system-in-iis-7): ```xml <system.web> <!-- <deployment retail = "false" [true|false] /> --> <deployment retail="true" /> </system.web> ``` Not setting this will allow a site to turn debugging on, which allows unlimited timeouts in requests - not exactly ideal for a hoster...
198,606
<p>I typically use URL rewriting to pass content IDs to my website, so this</p> <pre><code> Foo.1.aspx </code></pre> <p>rewrites to</p> <pre><code> Foo.aspx?id=1 </code></pre> <p>For a specific application I need to pass in multiple IDs to a single page, so I've rewritten things to accept this:</p> <pre><code> Foo.1,2,3,4,5.aspx </code></pre> <p>This works fine in Cassini (the built-in ad hoc web server for Visual Studio) but gives me "Internet Explorer cannot display the webpage" when I try it on a live server running IIS. Is this an IIS limitation? Should I just use dashes or underscores instead of commas?</p>
[ { "answer_id": 198617, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "<p>The right way to <em>accept</em> multiple ids is like this:</p>\n\n<pre><code>Foo.aspx?id=1;id=2;id=3;id=4;id=5\n</code></pre>\n\n<p>Note that's just what the target is. When re-writing urls, you can set your own rules to a certain extent for what you want the source to look like.</p>\n\n<p>I had to learn this on StackOverflow, too. See this question:<br>\n<a href=\"https://stackoverflow.com/questions/63463/split-out-ints-from-string\">Split out ints from string</a></p>\n" }, { "answer_id": 198632, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 2, "selected": false, "text": "<p>The comma is allowed in the path, query string and fragment according to spec. It wouldn't surprise me if IE doesn't conform to the spec though. Try the entity as Claudiu suggests, but I don't know why that would be necessary.</p>\n" }, { "answer_id": 198850, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 6, "selected": false, "text": "<p>Commas are allowed in the filename part of a URL, but are reserved characters in the domain*, as far as I know.</p>\n\n<p>What version of IE are you using? I've come across the odd report of IE5.5 truncating URLs on a comma (<a href=\"http://kb.adobe.com/selfservice/viewContent.do?externalId=326072\" rel=\"noreferrer\">link here</a>, but have tested URLs with commas in IE7 and it seems to be OK, so if there was an IE bug, it doesn't seem to be there any more - could it be an IIS issue?</p>\n\n<p>I'm wondering if the page error is due to a rule failure with the <code>mod_rewrite</code> - can you post the rule which is matching multiple ids and passing them off to your <code>Foo.aspx</code>? Is there any chance that it's only matching <code>Foo.N,N</code>, and failing on more commas?</p>\n\n<p><hr>\n* From the <a href=\"http://www.ietf.org/rfc/rfc2396.txt\" rel=\"noreferrer\">URI RFC</a>:</p>\n\n<blockquote>\n <p>2.2. Reserved Characters</p>\n \n <p>Many URI include components consisting of or delimited by, certain\n special characters. These characters are called \"reserved\", since\n their usage within the URI component is limited to their reserved\n purpose. If the data for a URI component would conflict with the\n reserved purpose, then the conflicting data must be escaped before\n forming the URI.</p>\n\n<pre><code> reserved = \";\" | \"/\" | \"?\" | \":\" | \"@\" | \"&amp;\" | \"=\" | \"+\" |\n \"$\" | \",\"\n</code></pre>\n \n <p>The \"reserved\" syntax class above refers to those characters that are\n allowed within a URI, but which may not be allowed within a\n particular component of the generic URI syntax</p>\n</blockquote>\n" }, { "answer_id": 198891, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 1, "selected": false, "text": "<h3>Answer</h3>\n<p>The problem was the commas. I'm guessing that IIS was having an issue with it (not IE) since IE was able to display it fine on localhost.</p>\n<p>At any rate I just changed the URL format to this and it works fine:</p>\n<pre><code>Foo.1-2-3-4-5.aspx\n</code></pre>\n" }, { "answer_id": 199079, "author": "Luke", "author_id": 21406, "author_profile": "https://Stackoverflow.com/users/21406", "pm_score": 1, "selected": false, "text": "<p>If you'd put in place a front controller then you could do something like;</p>\n\n<pre><code>index.aspx?c=Foo/1/2/3/4\n</code></pre>\n\n<p>The Front Controller would pick up the method name and the parameters to pass to it. This is a pretty common technique nowadays.</p>\n" }, { "answer_id": 199286, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 6, "selected": true, "text": "<p>I recall that Url Routing by default first checks to see if the file exists, and commas are not legal in filenames, which is parhaps why you are getting errors. IIS may have legacy code that aborts the request before it can get to asp.net for processing. </p>\n\n<p>Scott Hanselman's <a href=\"http://www.hanselman.com/blog/PlugInHybridsASPNETWebFormsAndASPMVCAndASPNETDynamicDataSideBySide.aspx\" rel=\"noreferrer\">blog post</a> talks a bit about this and may be relevant for you.</p>\n\n<hr>\n\n<p>As general comment: Url rewriting is typically used to make a url friendly and easy to remember.</p>\n\n<p><code>~/page.aspx?id=1,2,3,4</code> is neither worse nor better than <code>~/page/1-2-3-4.aspx</code> : both are difficult to use so why go through the extra effort? Avoid creating new url forms just because you can. Users, help desk, and other developers will just be confused.</p>\n\n<p>Url rewriting is best utilized to transform</p>\n\n<pre><code>~/products/view.aspx?id=1\n~/products/category.aspx?type=beverage\n</code></pre>\n\n<p>into</p>\n\n<pre><code>~/products/view/1\n~/products/category/beverage\n</code></pre>\n" }, { "answer_id": 1948967, "author": "Gordon", "author_id": 237156, "author_profile": "https://Stackoverflow.com/users/237156", "pm_score": 4, "selected": false, "text": "<p>Try using <code>%2c</code> in the URL to replace the commas.</p>\n" }, { "answer_id": 17778857, "author": "speedplane", "author_id": 234270, "author_profile": "https://Stackoverflow.com/users/234270", "pm_score": 3, "selected": false, "text": "<p>In addition to the answer by ConroyP, below is another citation to the RFC. It notes a number of unsafe characters, but does not mention the comma (suggesting that the comma is safe):</p>\n\n<blockquote>\n <p>Characters can be unsafe for a number of reasons. The space\n character is unsafe because significant spaces may disappear and \n insignificant spaces may be introduced when URLs are transcribed or \n typeset or subjected to the treatment of word-processing programs. \n The characters \"&lt;\" and \">\" are unsafe because they are used as the \n delimiters around URLs in free text; the quote mark (\"\"\") is used to \n delimit URLs in some systems. The character \"#\" is unsafe and should \n always be encoded because it is used in World Wide Web and in other \n systems to delimit a URL from a fragment/anchor identifier that might \n follow it. The character \"%\" is unsafe because it is used for \n encodings of other characters. Other characters are unsafe because \n gateways and other transport agents are known to sometimes modify \n such characters. These characters are \"{\", \"}\", \"|\", \"\\\", \"^\", \"~\", \n \"[\", \"]\", and \"`\". </p>\n \n <p>All unsafe characters must always be encoded within a URL. For \n example, the character \"#\" must be encoded within URLs even in \n systems that do not normally deal with fragment or anchor \n identifiers, so that if the URL is copied into another system that \n does use them, it will not be necessary to change the URL encoding.</p>\n</blockquote>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
I typically use URL rewriting to pass content IDs to my website, so this ``` Foo.1.aspx ``` rewrites to ``` Foo.aspx?id=1 ``` For a specific application I need to pass in multiple IDs to a single page, so I've rewritten things to accept this: ``` Foo.1,2,3,4,5.aspx ``` This works fine in Cassini (the built-in ad hoc web server for Visual Studio) but gives me "Internet Explorer cannot display the webpage" when I try it on a live server running IIS. Is this an IIS limitation? Should I just use dashes or underscores instead of commas?
I recall that Url Routing by default first checks to see if the file exists, and commas are not legal in filenames, which is parhaps why you are getting errors. IIS may have legacy code that aborts the request before it can get to asp.net for processing. Scott Hanselman's [blog post](http://www.hanselman.com/blog/PlugInHybridsASPNETWebFormsAndASPMVCAndASPNETDynamicDataSideBySide.aspx) talks a bit about this and may be relevant for you. --- As general comment: Url rewriting is typically used to make a url friendly and easy to remember. `~/page.aspx?id=1,2,3,4` is neither worse nor better than `~/page/1-2-3-4.aspx` : both are difficult to use so why go through the extra effort? Avoid creating new url forms just because you can. Users, help desk, and other developers will just be confused. Url rewriting is best utilized to transform ``` ~/products/view.aspx?id=1 ~/products/category.aspx?type=beverage ``` into ``` ~/products/view/1 ~/products/category/beverage ```
198,623
<p>I haven't really done any Windows scripting at all, so I am at a loss on how to pull this one off. Anyway, basically what we want to do is have a script that will take an argument on which IIS AppPool to recycle. I have done some research on Google and haven't had much success on getting things to work.</p> <p>Here is what I am trying now:</p> <pre><code>$appPoolName = $args[0] $appPool = get-wmiobject -namespace "root\MicrosoftIISv2" -class "IIsApplicationPools" Where-Object {$_.Name -eq "W3SVC/APPPOOLS/$appPoolName"} $appPool.Recycle() </code></pre> <p>and the error I get:</p> <pre><code>Get-WmiObject : A parameter cannot be found that matches parameter name '$_.Name -eq "W3SVC/APPPOOLS/$appPoolName"'. </code></pre> <p>Anyway, it would be nice if I also knew how to debug things like this. I already fixed one bug with the original script by doing gwmi -namespace "root\MicrosoftIISv2" -list. Any other tips like that one would be great.</p> <p>Thanks!</p> <p><strong>Update</strong>: Here is some more info</p> <pre><code>$appPool = gwmi -namespace "root\MicrosoftIISv2" -class "IISApplicationPools" | Get-Member . TypeName: System.Management.ManagementObject#root\MicrosoftIISv2\IIsApplicationPools Name MemberType Definition ---- ---------- ---------- Caption Property System.String Caption {get;set;} Description Property System.String Description {get;set;} InstallDate Property System.String InstallDate {get;set;} Name Property System.String Name {get;set;} Status Property System.String Status {get;set;} __CLASS Property System.String __CLASS {get;set;} __DERIVATION Property System.String[] __DERIVATION {get;set;} __DYNASTY Property System.String __DYNASTY {get;set;} __GENUS Property System.Int32 __GENUS {get;set;} __NAMESPACE Property System.String __NAMESPACE {get;set;} __PATH Property System.String __PATH {get;set;} __PROPERTY_COUNT Property System.Int32 __PROPERTY_COUNT {get;set;} __RELPATH Property System.String __RELPATH {get;set;} __SERVER Property System.String __SERVER {get;set;} __SUPERCLASS Property System.String __SUPERCLASS {get;set;} ConvertFromDateTime ScriptMethod System.Object ConvertFromDateTime(); ConvertToDateTime ScriptMethod System.Object ConvertToDateTime(); Delete ScriptMethod System.Object Delete(); GetType ScriptMethod System.Object GetType(); Put ScriptMethod System.Object Put(); gwmi -namespace "root\MicrosoftIISv2" -class "IISApplicationPools" __GENUS : 2 __CLASS : IIsApplicationPools __SUPERCLASS : CIM_LogicalElement __DYNASTY : CIM_ManagedSystemElement __RELPATH : IIsApplicationPools.Name="W3SVC/AppPools" __PROPERTY_COUNT : 5 __DERIVATION : {CIM_LogicalElement, CIM_ManagedSystemElement} __SERVER : IRON __NAMESPACE : root\MicrosoftIISv2 __PATH : \\IRON\root\MicrosoftIISv2:IIsApplicationPools.Name="W3SVC/A ppPools" Caption : Description : InstallDate : Name : W3SVC/AppPools Status : </code></pre>
[ { "answer_id": 198760, "author": "Scott Saad", "author_id": 4916, "author_profile": "https://Stackoverflow.com/users/4916", "pm_score": 4, "selected": false, "text": "<p><strong>Where-Object</strong> is a filter that expects something as in input. There seems to be a missing <strong>pipe</strong>, before the <em>where filter</em>. </p>\n\n<p>Try:</p>\n\n<pre><code>$appPoolName = $args[0]\n$appPool = get-wmiobject -namespace \"root\\MicrosoftIISv2\" -class \"IIsApplicationPool\" | Where-Object {$_.Name -eq \"W3SVC/APPPOOLS/$appPoolName\"}\n$appPool.Recycle()\n</code></pre>\n\n<p><strong>Edit</strong>: I noticed that the WMI class was <em>IISApplicationPools</em>, which as you saw, did not show us the Recycle method when piped to <strong>Get-Member</strong>. This needs to be changed to <em>IISApplicationPool</em> (non-plural). With that change, you are able to use the Recycle method. The code above has been updated.</p>\n" }, { "answer_id": 198948, "author": "EdgeVB", "author_id": 24863, "author_profile": "https://Stackoverflow.com/users/24863", "pm_score": 2, "selected": false, "text": "<p>When using get-WMIObject you should probably use -filter instead of piping to Where-Object. the filter parameter uses WQL syntax language instead of PowerShell's, so don't let that trip you up.</p>\n\n<pre><code>$appPoolName = $args[0]\n$appPool = get-wmiobject -namespace \"root\\MicrosoftIISv2\" -class \"IIsApplicationPools\" -filter 'name=\"W3SVC/APPPOOLS/$appPoolName\"'\n</code></pre>\n\n<p>Having said that putting the pipe there should work, and certainly makes it easier to work with unless you already know WQL.</p>\n" }, { "answer_id": 251507, "author": "jwmiller5", "author_id": 7824, "author_profile": "https://Stackoverflow.com/users/7824", "pm_score": 2, "selected": false, "text": "<p>This isn't a Powershell-specific answer, but iisapp.vbs will list the running application pools, and there is a /r flag to recycle a specific app pool. </p>\n" }, { "answer_id": 5824109, "author": "Jason", "author_id": 136584, "author_profile": "https://Stackoverflow.com/users/136584", "pm_score": 3, "selected": false, "text": "<p>Using the data from this question I was able to create 2 very useful functions.</p>\n\n<ul>\n<li>Get-IisAppPools</li>\n<li>Recycle-IisAppPool</li>\n</ul>\n\n<p>The code:</p>\n\n<pre><code>function Get-IisAppPools {\n\n Get-WmiObject -Namespace \"root\\MicrosoftIISv2\" -Class \"IIsApplicationPool\" -Filter 'name like \"W3SVC/APPPOOLS/%\"' \n | ForEach-Object { $_.Name.ToString().SubString(15) } \n\n}\n\nfunction Recycle-IisAppPool([string]$appPoolName) { \n\n Invoke-WmiMethod -Name Recycle -Namespace \"root\\MicrosoftIISv2\" -Path \"IIsApplicationPool.Name='W3SVC/APPPOOLS/$appPoolName'\" \n\n}\n</code></pre>\n\n<p>You can use these functions like this</p>\n\n<pre><code>Recycle-IisAppPool DefaultAppPool\nGet-IisAppPools | ? { $_ -match \"v4.0$\" } | % { Recycle-IisAppPool $_ }\n</code></pre>\n" }, { "answer_id": 6600509, "author": "Thomas S. Trias", "author_id": 189048, "author_profile": "https://Stackoverflow.com/users/189048", "pm_score": 1, "selected": false, "text": "<p>You can also use a WQL query to get just the AppPool you want; this has the advantage of filtering the results on the WMI side, which is especially handy when getting objects from a remote machine.</p>\n\n<pre><code>(Get-WmiObject -Query \"SELECT * FROM IIsApplicationPool WHERE Name = 'W3SVC/AppPools/$appPoolName'\" -Namespace 'root\\MicrosoftIISv2').Recycle()\n</code></pre>\n" }, { "answer_id": 36120804, "author": "user4317867", "author_id": 4317867, "author_profile": "https://Stackoverflow.com/users/4317867", "pm_score": 0, "selected": false, "text": "<p>With IIS 8.0 I've found I had to use <code>-namespace root\\webadministration -class ApplicationPool</code></p>\n\n<p>For example, to recycle an Application Pool in IIS 8 remotely using PowerShell:</p>\n\n<p>As always, please test this first by listing the application pools. Just remove the <code>| where</code> and the first <code>(</code> from the command:</p>\n\n<pre><code>gwmi -comp WebServer01 -namespace root\\webadministration -class ApplicationPool\n\n#Recycle app pool by name.\n(gwmi -comp WebServer01 -namespace root\\webadministration -class ApplicationPool | `\nwhere {$_.Name -eq 'YourAppPool'}).recycle()\n</code></pre>\n\n<p>And on one line:</p>\n\n<pre><code>(gwmi -comp WebSserver01 -namespace root\\webadministration -class ApplicationPool | where {$_.Name -eq 'YourAppPool'}).recycle()\n</code></pre>\n" }, { "answer_id": 52865969, "author": "mvanle", "author_id": 1213722, "author_profile": "https://Stackoverflow.com/users/1213722", "pm_score": 2, "selected": false, "text": "<p>In Powershell:</p>\n\n<pre><code>$pool = Get-IISAppPool -Name &lt;name&gt;\n\n$pool.recycle()\n</code></pre>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12448/" ]
I haven't really done any Windows scripting at all, so I am at a loss on how to pull this one off. Anyway, basically what we want to do is have a script that will take an argument on which IIS AppPool to recycle. I have done some research on Google and haven't had much success on getting things to work. Here is what I am trying now: ``` $appPoolName = $args[0] $appPool = get-wmiobject -namespace "root\MicrosoftIISv2" -class "IIsApplicationPools" Where-Object {$_.Name -eq "W3SVC/APPPOOLS/$appPoolName"} $appPool.Recycle() ``` and the error I get: ``` Get-WmiObject : A parameter cannot be found that matches parameter name '$_.Name -eq "W3SVC/APPPOOLS/$appPoolName"'. ``` Anyway, it would be nice if I also knew how to debug things like this. I already fixed one bug with the original script by doing gwmi -namespace "root\MicrosoftIISv2" -list. Any other tips like that one would be great. Thanks! **Update**: Here is some more info ``` $appPool = gwmi -namespace "root\MicrosoftIISv2" -class "IISApplicationPools" | Get-Member . TypeName: System.Management.ManagementObject#root\MicrosoftIISv2\IIsApplicationPools Name MemberType Definition ---- ---------- ---------- Caption Property System.String Caption {get;set;} Description Property System.String Description {get;set;} InstallDate Property System.String InstallDate {get;set;} Name Property System.String Name {get;set;} Status Property System.String Status {get;set;} __CLASS Property System.String __CLASS {get;set;} __DERIVATION Property System.String[] __DERIVATION {get;set;} __DYNASTY Property System.String __DYNASTY {get;set;} __GENUS Property System.Int32 __GENUS {get;set;} __NAMESPACE Property System.String __NAMESPACE {get;set;} __PATH Property System.String __PATH {get;set;} __PROPERTY_COUNT Property System.Int32 __PROPERTY_COUNT {get;set;} __RELPATH Property System.String __RELPATH {get;set;} __SERVER Property System.String __SERVER {get;set;} __SUPERCLASS Property System.String __SUPERCLASS {get;set;} ConvertFromDateTime ScriptMethod System.Object ConvertFromDateTime(); ConvertToDateTime ScriptMethod System.Object ConvertToDateTime(); Delete ScriptMethod System.Object Delete(); GetType ScriptMethod System.Object GetType(); Put ScriptMethod System.Object Put(); gwmi -namespace "root\MicrosoftIISv2" -class "IISApplicationPools" __GENUS : 2 __CLASS : IIsApplicationPools __SUPERCLASS : CIM_LogicalElement __DYNASTY : CIM_ManagedSystemElement __RELPATH : IIsApplicationPools.Name="W3SVC/AppPools" __PROPERTY_COUNT : 5 __DERIVATION : {CIM_LogicalElement, CIM_ManagedSystemElement} __SERVER : IRON __NAMESPACE : root\MicrosoftIISv2 __PATH : \\IRON\root\MicrosoftIISv2:IIsApplicationPools.Name="W3SVC/A ppPools" Caption : Description : InstallDate : Name : W3SVC/AppPools Status : ```
**Where-Object** is a filter that expects something as in input. There seems to be a missing **pipe**, before the *where filter*. Try: ``` $appPoolName = $args[0] $appPool = get-wmiobject -namespace "root\MicrosoftIISv2" -class "IIsApplicationPool" | Where-Object {$_.Name -eq "W3SVC/APPPOOLS/$appPoolName"} $appPool.Recycle() ``` **Edit**: I noticed that the WMI class was *IISApplicationPools*, which as you saw, did not show us the Recycle method when piped to **Get-Member**. This needs to be changed to *IISApplicationPool* (non-plural). With that change, you are able to use the Recycle method. The code above has been updated.
198,625
<p>Does anyone know if it is possible to reliably determine (programattically C/C++...) whether or not a firewall or IP filtering software is installed on a Windows PC? I need to detect whether a certain server IP is being blocked in my client software by the host OS.</p> <p>I don't need to worry about external hardware firewals in this situation as I have full control of this. It is only software firewalls that I am concerned with. My hope was that I could iterate the windows network stack or NDIS interfaces and determine this</p>
[ { "answer_id": 198644, "author": "Mark Roddy", "author_id": 9940, "author_profile": "https://Stackoverflow.com/users/9940", "pm_score": 0, "selected": false, "text": "<p>You'd have to translate from C#, but this blog post explains how to check if the Windows firewall is enabled:\n<a href=\"http://www.shafqatahmed.com/2008/01/controlling-win.html\" rel=\"nofollow noreferrer\">http://www.shafqatahmed.com/2008/01/controlling-win.html</a></p>\n" }, { "answer_id": 198661, "author": "Kirk Strauser", "author_id": 32538, "author_profile": "https://Stackoverflow.com/users/32538", "pm_score": 1, "selected": false, "text": "<p>And if that IP is blocked on their external firewall hardware? It would be absolutely impossible to tell <em>why</em> a given host was unreachable.</p>\n" }, { "answer_id": 198687, "author": "David Arno", "author_id": 7122, "author_profile": "https://Stackoverflow.com/users/7122", "pm_score": 1, "selected": false, "text": "<p>One possible solution is to take advantage of the fact that firewalls don't tend to block access to port 80, but will block access to other ports. So you could try connecting to port 80, then if successful, connect via a commonly blocked port (<a href=\"http://www.chebucto.ns.ca/~rakerman/trojan-port-table.html#Trojan-News\" rel=\"nofollow noreferrer\">see here for an example list</a>)</p>\n" }, { "answer_id": 198690, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 1, "selected": false, "text": "<p>You can't really tell if an IP is being blocked, at least not without knowing what firewall software you're looking for and checking it specifically. Some thoughts: </p>\n\n<ul>\n<li>Check for specific firewalls (e.g. Windows firewall) being enabled or blocking your server</li>\n<li>Check the hosts file for an entry blocking your server IP</li>\n<li>connect through a proxy or proxies and see if they can access the IP in the event your client cannot.</li>\n<li>Test the server to see if it's reachable (after all, that's what you're really testing for, right? To see if the server can be communicated with?). It may make sense to test this multiple times/periodically in case of actual outages on your server side as well.</li>\n</ul>\n" }, { "answer_id": 198694, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": -1, "selected": false, "text": "<p>Try invoking Ping.</p>\n" }, { "answer_id": 198713, "author": "Tahir Akhtar", "author_id": 18027, "author_profile": "https://Stackoverflow.com/users/18027", "pm_score": 2, "selected": false, "text": "<p>There could be a hack if you can assume following:</p>\n\n<ol>\n<li><p>Outgoing HTTP connections are allowed</p></li>\n<li><p>You can run one of your own service on another server listening on port 80</p></li>\n</ol>\n\n<p>Code your service to accept an IP [and a port or maybe a url]. It must return whether it was able to connect to the IP. </p>\n\n<p>This way you can find out whether the actual server is up and running. If the server is not available directly you can conclude that it is being blocked by a firewall. </p>\n\n<p>If you do not want to code/run your own service, you might be able to use one of the network status web-service available on the internet.</p>\n" }, { "answer_id": 198963, "author": "oz10", "author_id": 14069, "author_profile": "https://Stackoverflow.com/users/14069", "pm_score": 0, "selected": false, "text": "<p>I was going to suggest doing some 'expect'-style programming on <a href=\"http://support.microsoft.com/kb/242468\" rel=\"nofollow noreferrer\">netsh</a>... but usually when there is a command line app like this there is a library behind it. </p>\n\n<p>Look at the <a href=\"http://msdn.microsoft.com/en-us/library/aa366452(VS.85).aspx\" rel=\"nofollow noreferrer\">Windows Firewall API</a>. I can't say that this will solve your specific problem, but it seems likely.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa366434(VS.85).aspx\" rel=\"nofollow noreferrer\">Sample code</a> for checking if a specific port is allowed... <a href=\"http://msdn.microsoft.com/en-us/library/aa364726(VS.85).aspx\" rel=\"nofollow noreferrer\">A good example</a> showing the headers needed. </p>\n" }, { "answer_id": 200260, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 3, "selected": true, "text": "<p>After reading some of your comments in reply to other answers, I think this might actually be closer to what you're looking for. It might not catch every type of firewall but any major firewall vendor should be registered with the Security Center and therefore detected with this method. You could also combine this with some of the other answers here to give yourself a second level of verification.</p>\n<h3><a href=\"http://www.experts-exchange.com/Programming/Languages/CPP/Q_21645145.html\" rel=\"nofollow noreferrer\">Detecting running firewalls in windows</a></h3>\n<p>It's an Expert's Exchange post so you may not be able to read the thread. Just in case, I've copied and pasted the relevant info. It's in VBScript but it should point you in the right direction as far as what WMI namespaces you can use.</p>\n<blockquote>\n<p><strong>KemalRouge</strong>: I've just solved this problem with some help from a\ncolleague. He pointed me in the direction of a knowledge base article,\nwhich pointed out that this information was stored in the WMI database</p>\n<p>Basically, it's possible to query the WMI in a few lines of code to\nfind out what firewalls/anti-virus software is being monitored by the\nSecurity Center, and the status of this software (i.e. enabled or not).</p>\n<p>Anyway, if you're interested, here's some VB code I used to test this out\n(you'll need a reference to &quot;Microsoft WMI Scripting V1.2 Library&quot;):</p>\n</blockquote>\n<pre><code>Private Sub DumpFirewallInfo()\n\nDim oLocator As WbemScripting.SWbemLocator\nDim oService As WbemScripting.SWbemServicesEx\nDim oFirewalls As WbemScripting.SWbemObjectSet\nDim oFirewall As WbemScripting.SWbemObjectEx\nDim oFwMgr As Variant\n \n \n Set oFwMgr = CreateObject(&quot;HNetCfg.FwMgr&quot;)\n \n Debug.Print &quot;Checking the Windows Firewall...&quot;\n Debug.Print &quot;Windows Firewal Enabled: &quot; &amp; oFwMgr.LocalPolicy.CurrentProfile.FirewallEnabled\n Debug.Print &quot;&quot;\n \n Set oFwMgr = Nothing\n \n \n Debug.Print &quot;Checking for other installed firewalls...&quot;\n \n Set oLocator = New WbemScripting.SWbemLocator\n Set oService = oLocator.ConnectServer(&quot;.&quot;, &quot;root\\SecurityCenter&quot;)\n oService.Security_.ImpersonationLevel = 3\n\n Set oFirewalls = oService.ExecQuery(&quot;SELECT * FROM FirewallProduct&quot;) ' This could also be &quot;AntivirusProduct&quot;\n \n For Each oFirewall In oFirewalls\n Debug.Print &quot;Company: &quot; &amp; vbTab &amp; oFirewall.CompanyName\n Debug.Print &quot;Firewall Name: &quot; &amp; vbTab &amp; oFirewall.DisplayName\n Debug.Print &quot;Enabled: &quot; &amp; vbTab &amp; Format$(oFirewall.Enabled)\n Debug.Print &quot;Version: &quot; &amp; vbTab &amp; oFirewall.versionNumber\n Debug.Print &quot;&quot;\n Next oFirewall\n \n Set oFirewall = Nothing\n Set oFirewalls = Nothing\n Set oService = Nothing\n Set oLocator = Nothing\n\nEnd Sub\n</code></pre>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10446/" ]
Does anyone know if it is possible to reliably determine (programattically C/C++...) whether or not a firewall or IP filtering software is installed on a Windows PC? I need to detect whether a certain server IP is being blocked in my client software by the host OS. I don't need to worry about external hardware firewals in this situation as I have full control of this. It is only software firewalls that I am concerned with. My hope was that I could iterate the windows network stack or NDIS interfaces and determine this
After reading some of your comments in reply to other answers, I think this might actually be closer to what you're looking for. It might not catch every type of firewall but any major firewall vendor should be registered with the Security Center and therefore detected with this method. You could also combine this with some of the other answers here to give yourself a second level of verification. ### [Detecting running firewalls in windows](http://www.experts-exchange.com/Programming/Languages/CPP/Q_21645145.html) It's an Expert's Exchange post so you may not be able to read the thread. Just in case, I've copied and pasted the relevant info. It's in VBScript but it should point you in the right direction as far as what WMI namespaces you can use. > > **KemalRouge**: I've just solved this problem with some help from a > colleague. He pointed me in the direction of a knowledge base article, > which pointed out that this information was stored in the WMI database > > > Basically, it's possible to query the WMI in a few lines of code to > find out what firewalls/anti-virus software is being monitored by the > Security Center, and the status of this software (i.e. enabled or not). > > > Anyway, if you're interested, here's some VB code I used to test this out > (you'll need a reference to "Microsoft WMI Scripting V1.2 Library"): > > > ``` Private Sub DumpFirewallInfo() Dim oLocator As WbemScripting.SWbemLocator Dim oService As WbemScripting.SWbemServicesEx Dim oFirewalls As WbemScripting.SWbemObjectSet Dim oFirewall As WbemScripting.SWbemObjectEx Dim oFwMgr As Variant Set oFwMgr = CreateObject("HNetCfg.FwMgr") Debug.Print "Checking the Windows Firewall..." Debug.Print "Windows Firewal Enabled: " & oFwMgr.LocalPolicy.CurrentProfile.FirewallEnabled Debug.Print "" Set oFwMgr = Nothing Debug.Print "Checking for other installed firewalls..." Set oLocator = New WbemScripting.SWbemLocator Set oService = oLocator.ConnectServer(".", "root\SecurityCenter") oService.Security_.ImpersonationLevel = 3 Set oFirewalls = oService.ExecQuery("SELECT * FROM FirewallProduct") ' This could also be "AntivirusProduct" For Each oFirewall In oFirewalls Debug.Print "Company: " & vbTab & oFirewall.CompanyName Debug.Print "Firewall Name: " & vbTab & oFirewall.DisplayName Debug.Print "Enabled: " & vbTab & Format$(oFirewall.Enabled) Debug.Print "Version: " & vbTab & oFirewall.versionNumber Debug.Print "" Next oFirewall Set oFirewall = Nothing Set oFirewalls = Nothing Set oService = Nothing Set oLocator = Nothing End Sub ```
198,650
<p>In asp.net, you can retrieve MULTIPLE datatables from a single call to the database. Can you do the same thing in php?</p> <p>Example:</p> <pre><code>$sql ="select * from t1; select * from t2;"; $result = SomeQueryFunc($sql); print_r($result[0]); // dump results for t1 print_r($result[1]); // dump results for t2 </code></pre> <p>Can you do something like this?</p>
[ { "answer_id": 198665, "author": "gnud", "author_id": 27204, "author_profile": "https://Stackoverflow.com/users/27204", "pm_score": 0, "selected": false, "text": "<p>This should be possible with newer MySQL and the mysqli (improved) php extension.\nI'm not sure if any DB abstraction layers support this.</p>\n\n<p>See relevant <a href=\"http://dev.mysql.com/doc/refman/5.0/en/c-api-multiple-queries.html\" rel=\"nofollow noreferrer\">MySQL docs</a> and \n<a href=\"http://php.net/manual/en/mysqli.multi-query.php\" rel=\"nofollow noreferrer\">PHP docs</a>.</p>\n" }, { "answer_id": 198686, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://us2.php.net/manual/en/pdostatement.nextrowset.php\" rel=\"nofollow noreferrer\"><code>PDOStatement::nextRowset()</code></a> seems to be what you're after.</p>\n" }, { "answer_id": 199070, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": true, "text": "<p>This is called \"multi-query.\" The mysql extension in PHP does not have any means to enable multi-query. The mysqli extension does allow you to use multi-query, but only through the multi_query() method. See <a href=\"http://php.net/manual/en/mysqli.multi-query.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/mysqli.multi-query.php</a></p>\n\n<p>Using multi-query is not recommended, because it can increase the potential damage caused by SQL injection attacks. If you use multi-query, you should use rigorous code inspection habits to avoid SQL injection vulnerability.</p>\n" }, { "answer_id": 8111427, "author": "genesis", "author_id": 764846, "author_profile": "https://Stackoverflow.com/users/764846", "pm_score": 0, "selected": false, "text": "<p>If you're using classic MySQL, you can't. You can create a function which will look like</p>\n\n<pre><code>function SomeQueryFunc($queries) {\n $queries = explode(';', $queries);\n $return = array();\n foreach($queries as $index =&gt; $query) {\n $result = mysql_query($query);\n $return[$index] = array();\n while($row = mysql_fetch_assoc($result)) {\n foreach($row as $column =&gt; $value) {\n $return[$index][$column] = $value;\n }\n }\n }\n return $return;\n}\n</code></pre>\n\n<p>which will work as expected</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27305/" ]
In asp.net, you can retrieve MULTIPLE datatables from a single call to the database. Can you do the same thing in php? Example: ``` $sql ="select * from t1; select * from t2;"; $result = SomeQueryFunc($sql); print_r($result[0]); // dump results for t1 print_r($result[1]); // dump results for t2 ``` Can you do something like this?
This is called "multi-query." The mysql extension in PHP does not have any means to enable multi-query. The mysqli extension does allow you to use multi-query, but only through the multi\_query() method. See <http://php.net/manual/en/mysqli.multi-query.php> Using multi-query is not recommended, because it can increase the potential damage caused by SQL injection attacks. If you use multi-query, you should use rigorous code inspection habits to avoid SQL injection vulnerability.
198,656
<p>I creating a control for WPF, and I have a question for you WPF gurus out there.</p> <p>I want my control to be able to expand to fit a resizable window. </p> <p>In my control, I have a list box that I want to expand with the window. I also have other controls around the list box (buttons, text, etc).</p> <p>I want to be able to set a minimum size on my control, but I want the window to be able to be sized smaller by creating scroll bars for viewing the control. </p> <p>This creates nested scroll areas: One for the list box and a ScrollViewer wrapping the whole control. </p> <p>Now, if the list box is set to auto size, it will never have a scroll bar because it is always drawn full size within the ScrollViewer. </p> <p>I only want the control to scroll if the content can't get any smaller, otherwise I don't want to scroll the control; instead I want to scroll the list box inside the control.</p> <p>How can I alter the default behavior of the ScrollViewer class? I tried inheriting from the ScrollViewer class and overriding the MeasureOverride and ArrangeOverride classes, but I couldn't figure out how to measure and arrange the child properly. It appears that the arrange has to affect the ScrollContentPresenter somehow, not the actual content child.</p> <p>Any help/suggestions would be much appreciated.</p>
[ { "answer_id": 198688, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 0, "selected": false, "text": "<p>While I wouldn't recommend creating a UI that requires outer scroll bars you can accomplish this pretty easily:</p>\n\n<pre><code>&lt;Window\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n &gt; \n &lt;ScrollViewer HorizontalScrollBarVisibility=\"Auto\" \n VerticalScrollBarVisibility=\"Auto\"&gt;\n &lt;Grid&gt;\n &lt;Grid.RowDefinitions&gt;\n &lt;RowDefinition Height=\"Auto\"/&gt;\n &lt;RowDefinition Height=\"Auto\"/&gt;\n &lt;RowDefinition Height=\"Auto\"/&gt;\n &lt;/Grid.RowDefinitions&gt;\n &lt;Grid.ColumnDefinitions&gt;\n &lt;ColumnDefinition Width=\"*\"/&gt;\n &lt;ColumnDefinition Width=\"Auto\"/&gt;\n &lt;/Grid.ColumnDefinitions&gt;\n &lt;ListBox Grid.Row=\"0\" Grid.RowSpan=\"3\" Grid.Column=\"0\" MinWidth=\"200\"/&gt;\n &lt;Button Grid.Row=\"0\" Grid.Column=\"1\" Content=\"Button1\"/&gt;\n &lt;Button Grid.Row=\"1\" Grid.Column=\"1\" Content=\"Button2\"/&gt;\n &lt;Button Grid.Row=\"2\" Grid.Column=\"1\" Content=\"Button3\"/&gt;\n &lt;/Grid&gt;\n &lt;/ScrollViewer&gt;\n&lt;/Window&gt;\n</code></pre>\n\n<p>I don't really recommend this. WPF provides exceptional layout systems, like Grid, and you should try to allow the app to resize itself as needed. Perhaps you can set a MinWidth/MinHeight on the window itself to prevent this resizing?</p>\n" }, { "answer_id": 218587, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 2, "selected": false, "text": "<p>You problem arises, because <code>Control</code>s within a <code>ScrollViewer</code> have virtually unlimited space available. Therefore your inner <code>ListBox</code> thinks it can avoid scrolling by taking up the complete height necessary to display all its elements. Of course in your case that behaviour has the unwanted side effect of exercising the outer <code>ScrollViewer</code> too much.</p>\n\n<p>The objective therefore is to get the <code>ListBox</code> to use the <strong>visible</strong> height within the <code>ScrollViewer</code> iff there is enough of it and a certain minimal height otherwise. To achieve this, the most direct way is to inherit from <code>ScrollViewer</code> and override <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.measureoverride.aspx\" rel=\"nofollow noreferrer\"><code>MeasureOverride()</code></a> to pass an appropriately sized <code>availableSize</code> (that is the given <code>availableSize</code> blown up to the minimal size instead of the \"usual\" infinity) to the <code>Visual</code>s found by using <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.visualchildrencount.aspx\" rel=\"nofollow noreferrer\"><code>VisualChildrenCount</code></a> and <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.getvisualchild.aspx\" rel=\"nofollow noreferrer\"><code>GetVisualChild(int)</code></a>.</p>\n" }, { "answer_id": 1571972, "author": "Daniel", "author_id": 141502, "author_profile": "https://Stackoverflow.com/users/141502", "pm_score": 4, "selected": false, "text": "<p>I've created a class to work around this problem:</p>\n\n<pre><code>public class RestrictDesiredSize : Decorator\n{\n Size lastArrangeSize = new Size(double.PositiveInfinity, double.PositiveInfinity);\n\n protected override Size MeasureOverride(Size constraint)\n {\n Debug.WriteLine(\"Measure: \" + constraint);\n base.MeasureOverride(new Size(Math.Min(lastArrangeSize.Width, constraint.Width),\n Math.Min(lastArrangeSize.Height, constraint.Height)));\n return new Size(0, 0);\n }\n\n protected override Size ArrangeOverride(Size arrangeSize)\n {\n Debug.WriteLine(\"Arrange: \" + arrangeSize);\n if (lastArrangeSize != arrangeSize) {\n lastArrangeSize = arrangeSize;\n base.MeasureOverride(arrangeSize);\n }\n return base.ArrangeOverride(arrangeSize);\n }\n}\n</code></pre>\n\n<p>It will always return a desired size of (0,0), even if the containing element wants to be bigger.\nUsage:</p>\n\n<pre><code>&lt;local:RestrictDesiredSize MinWidth=\"200\" MinHeight=\"200\"&gt;\n &lt;ListBox /&gt;\n&lt;/local&gt;\n</code></pre>\n" }, { "answer_id": 9988974, "author": "Heiner", "author_id": 495910, "author_profile": "https://Stackoverflow.com/users/495910", "pm_score": 2, "selected": false, "text": "<p>I used <a href=\"https://stackoverflow.com/users/141502/daniel\">Daniel</a>s solution. That works great. Thank you.</p>\n\n<p>Then I added two boolean dependency properties to the decorator class: <code>KeepWidth</code> and <code>KeepHeight</code>. So the new feature can be suppressed for one dimension.</p>\n\n<p>This requires a change in <code>MeasureOverride</code>:</p>\n\n<pre><code>protected override Size MeasureOverride(Size constraint)\n{\n var innerWidth = Math.Min(this._lastArrangeSize.Width, constraint.Width);\n var innerHeight = Math.Min(this._lastArrangeSize.Height, constraint.Height);\n base.MeasureOverride(new Size(innerWidth, innerHeight));\n\n var outerWidth = KeepWidth ? Child.DesiredSize.Width : 0;\n var outerHeight = KeepHeight ? Child.DesiredSize.Height : 0;\n return new Size(outerWidth, outerHeight);\n}\n</code></pre>\n" }, { "answer_id": 23748102, "author": "richarfen", "author_id": 3654438, "author_profile": "https://Stackoverflow.com/users/3654438", "pm_score": 0, "selected": false, "text": "<p>Create a method in the code-behind that sets the ListBox's MaxHeight to the height of whatever control is containing it and other controls. If the Listbox has any controls/margins/padding above or below it, subtract their heights from the container height assigned to MaxHeight. Call this method in the main windows \"loaded\" and \"window resize\" event handlers. </p>\n\n<p>This should give you the best of both worlds. You are giving the ListBox a \"fixed\" size that will cause it to scroll in spite of the fact that the main window has its own scrollbar. </p>\n" }, { "answer_id": 44592501, "author": "Dmitry", "author_id": 5475902, "author_profile": "https://Stackoverflow.com/users/5475902", "pm_score": 0, "selected": false, "text": "<p>for 2 ScrollViewer</p>\n\n<pre><code> public class ScrollExt: ScrollViewer\n{\n Size lastArrangeSize = new Size(double.PositiveInfinity, double.PositiveInfinity);\n\n public ScrollExt()\n {\n\n }\n protected override Size MeasureOverride(Size constraint)\n {\n base.MeasureOverride(new Size(Math.Min(lastArrangeSize.Width, constraint.Width),\n Math.Min(lastArrangeSize.Height, constraint.Height)));\n return new Size(0, 0);\n }\n\n protected override Size ArrangeOverride(Size arrangeSize)\n {\n if (lastArrangeSize != arrangeSize)\n {\n lastArrangeSize = arrangeSize;\n base.MeasureOverride(arrangeSize);\n }\n return base.ArrangeOverride(arrangeSize);\n }\n}\n</code></pre>\n\n<p>code:</p>\n\n<pre><code> &lt;ScrollViewer HorizontalScrollBarVisibility=\"Auto\" VerticalScrollBarVisibility=\"Auto\"&gt;\n &lt;Grid &gt;\n &lt;Grid.ColumnDefinitions&gt;\n &lt;ColumnDefinition Width=\"Auto\" /&gt;\n &lt;ColumnDefinition Width=\"*\" /&gt;\n &lt;/Grid.ColumnDefinitions&gt;\n &lt;TextBlock Background=\"Beige\" Width=\"600\" Text=\"Example\"/&gt;\n &lt;Grid Grid.Column=\"1\" x:Name=\"grid\"&gt;\n &lt;Grid Grid.Column=\"1\" Margin=\"25\" Background=\"Green\"&gt;\n &lt;local:ScrollExt HorizontalScrollBarVisibility=\"Auto\" VerticalScrollBarVisibility=\"Auto\"&gt;\n &lt;Grid Width=\"10000\" Margin=\"25\" Background=\"Red\" /&gt;\n &lt;/local:ScrollExt&gt;\n &lt;/Grid&gt;\n &lt;/Grid&gt;\n &lt;/Grid&gt;\n &lt;/ScrollViewer&gt;\n</code></pre>\n" }, { "answer_id": 53011021, "author": "Glaucus", "author_id": 1011688, "author_profile": "https://Stackoverflow.com/users/1011688", "pm_score": 0, "selected": false, "text": "<p>I ended up combining <a href=\"https://stackoverflow.com/a/1571972/1011688\">Daniels</a> answer and <a href=\"https://stackoverflow.com/a/9988974/1011688\">Heiner's</a> answer. I decided to post the entire solution to make it easier for people to adopt this if needed. Here's my decorator class:</p>\n\n<pre><code>public class RestrictDesiredSizeDecorator : Decorator\n{\n public static readonly DependencyProperty KeepWidth;\n public static readonly DependencyProperty KeepHeight;\n\n #region Dependency property setters and getters\n public static void SetKeepWidth(UIElement element, bool value)\n {\n element.SetValue(KeepWidth, value);\n }\n\n public static bool GetKeepWidth(UIElement element)\n {\n return (bool)element.GetValue(KeepWidth);\n }\n\n public static void SetKeepHeight(UIElement element, bool value)\n {\n element.SetValue(KeepHeight, value);\n }\n\n public static bool GetKeepHeight(UIElement element)\n {\n return (bool)element.GetValue(KeepHeight);\n }\n #endregion\n\n private Size _lastArrangeSize = new Size(double.PositiveInfinity, double.PositiveInfinity);\n\n static RestrictDesiredSizeDecorator()\n {\n KeepWidth = DependencyProperty.RegisterAttached(\n nameof(KeepWidth),\n typeof(bool),\n typeof(RestrictDesiredSizeDecorator));\n\n KeepHeight = DependencyProperty.RegisterAttached(\n nameof(KeepHeight),\n typeof(bool),\n typeof(RestrictDesiredSizeDecorator));\n }\n\n protected override Size MeasureOverride(Size constraint)\n {\n Debug.WriteLine(\"Measure: \" + constraint);\n\n var keepWidth = GetValue(KeepWidth) as bool? ?? false;\n var keepHeight = GetValue(KeepHeight) as bool? ?? false;\n\n var innerWidth = keepWidth ? constraint.Width : Math.Min(this._lastArrangeSize.Width, constraint.Width);\n var innerHeight = keepHeight ? constraint.Height : Math.Min(this._lastArrangeSize.Height, constraint.Height);\n base.MeasureOverride(new Size(innerWidth, innerHeight));\n\n var outerWidth = keepWidth ? Child.DesiredSize.Width : 0;\n var outerHeight = keepHeight ? Child.DesiredSize.Height : 0;\n\n return new Size(outerWidth, outerHeight);\n }\n\n protected override Size ArrangeOverride(Size arrangeSize)\n {\n Debug.WriteLine(\"Arrange: \" + arrangeSize);\n\n if (_lastArrangeSize != arrangeSize)\n {\n _lastArrangeSize = arrangeSize;\n base.MeasureOverride(arrangeSize);\n }\n\n return base.ArrangeOverride(arrangeSize);\n }\n}\n</code></pre>\n\n<p>and here's how I use it in the xaml:</p>\n\n<pre><code>&lt;ScrollViewer&gt;\n &lt;StackPanel Orientation=\"Vertical\"&gt;\n &lt;Whatever /&gt;\n\n &lt;decorators:RestrictDesiredSizeDecorator MinWidth=\"100\" KeepHeight=\"True\"&gt;\n &lt;TextBox\n Text=\"{Binding Comment, UpdateSourceTrigger=PropertyChanged}\"\n Height=\"Auto\"\n MaxHeight=\"360\"\n VerticalScrollBarVisibility=\"Auto\"\n HorizontalScrollBarVisibility=\"Auto\"\n AcceptsReturn=\"True\"\n AcceptsTab=\"True\"\n TextWrapping=\"WrapWithOverflow\"\n /&gt;\n &lt;/decorators:RestrictDesiredSizeDecorator&gt;\n\n &lt;Whatever /&gt;\n &lt;/StackPanel&gt;\n&lt;/ScrollViewer\n</code></pre>\n\n<p>The above creates a textbox that will grow vertically (until it hits MaxHeight) but will match the parent's width without growing the outer ScrollViewer. Resizing the window/ScrollViewer to less than 100 wide will force the outer ScrollViewer to show the horizontal scroll bars. Other controls with inner ScrollViewers can be used as well, including complex grids.</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I creating a control for WPF, and I have a question for you WPF gurus out there. I want my control to be able to expand to fit a resizable window. In my control, I have a list box that I want to expand with the window. I also have other controls around the list box (buttons, text, etc). I want to be able to set a minimum size on my control, but I want the window to be able to be sized smaller by creating scroll bars for viewing the control. This creates nested scroll areas: One for the list box and a ScrollViewer wrapping the whole control. Now, if the list box is set to auto size, it will never have a scroll bar because it is always drawn full size within the ScrollViewer. I only want the control to scroll if the content can't get any smaller, otherwise I don't want to scroll the control; instead I want to scroll the list box inside the control. How can I alter the default behavior of the ScrollViewer class? I tried inheriting from the ScrollViewer class and overriding the MeasureOverride and ArrangeOverride classes, but I couldn't figure out how to measure and arrange the child properly. It appears that the arrange has to affect the ScrollContentPresenter somehow, not the actual content child. Any help/suggestions would be much appreciated.
I've created a class to work around this problem: ``` public class RestrictDesiredSize : Decorator { Size lastArrangeSize = new Size(double.PositiveInfinity, double.PositiveInfinity); protected override Size MeasureOverride(Size constraint) { Debug.WriteLine("Measure: " + constraint); base.MeasureOverride(new Size(Math.Min(lastArrangeSize.Width, constraint.Width), Math.Min(lastArrangeSize.Height, constraint.Height))); return new Size(0, 0); } protected override Size ArrangeOverride(Size arrangeSize) { Debug.WriteLine("Arrange: " + arrangeSize); if (lastArrangeSize != arrangeSize) { lastArrangeSize = arrangeSize; base.MeasureOverride(arrangeSize); } return base.ArrangeOverride(arrangeSize); } } ``` It will always return a desired size of (0,0), even if the containing element wants to be bigger. Usage: ``` <local:RestrictDesiredSize MinWidth="200" MinHeight="200"> <ListBox /> </local> ```
198,668
<p>I have a situation where I need to be able to load assemblies in the GAC based on their partial names. In order to do this I have added the following to my app.config file:</p> <pre><code>&lt;runtime&gt; &lt;assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"&gt; &lt;qualifyAssembly partialName="MyAssembly" fullName= "MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0123456789abcdef"/&gt; &lt;/assemblyBinding&gt; &lt;/runtime&gt; </code></pre> <p>This works exactly the way I want it to. However, if I place the same element in my machine.config file, it seems to be ignored, and I get FileNotFoundExceptions when trying to load MyAssembly.</p> <p>The following is the assembly binding log when the element is in my app.config, and the bind succeeds:</p> <pre>LOG: This bind starts in default load context. LOG: Using application configuration file: C:\Documents and Settings\jon_scheiding\My Documents\Source\Testing\Test Projects 1\Cmd\bin\Debug\Testers.Cmd.vshost.exe.config LOG: Using machine configuration file from C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\config\machine.config. LOG: Partial reference qualified from config file. New reference: MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0123456789abcdef. LOG: Post-policy reference: MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0123456789abcdef LOG: Found assembly by looking in the GAC. LOG: Binding succeeds. Returns assembly from C:\WINDOWS\assembly\GAC_MSIL\MyAssembly\1.0.0.0__b20f4683c1030dbd\MyAssembly.dll. LOG: Assembly is loaded in default load context.</pre> <p>Contrast that with the log when my configuration is in machine.config, and the bind fails:</p> <pre>LOG: This bind starts in default load context. LOG: Using application configuration file: C:\Documents and Settings\jon_scheiding\My Documents\Source\Testing\Test Projects 1\Cmd\bin\Debug\Testers.Cmd.vshost.exe.config LOG: Using machine configuration file from C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\config\machine.config. LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind). LOG: Attempting download of new URL file:///C:/Documents and Settings/jon_scheiding/My Documents/Source/Testing/Test Projects 1/Cmd/bin/Debug/MyAssembly.DLL. LOG: Attempting download of new URL file:///C:/Documents and Settings/jon_scheiding/My Documents/Source/Testing/Test Projects 1/Cmd/bin/Debug/MyAssembly/MyAssembly.DLL. LOG: Attempting download of new URL file:///C:/Documents and Settings/jon_scheiding/My Documents/Source/Testing/Test Projects 1/Cmd/bin/Debug/MyAssembly.EXE. LOG: Attempting download of new URL file:///C:/Documents and Settings/jon_scheiding/My Documents/Source/Testing/Test Projects 1/Cmd/bin/Debug/MyAssembly/MyAssembly.EXE. LOG: All probing URLs attempted and failed.</pre> <p>The problem seems to be the fourth line, "Policy not being applied to reference at this time." However, I can find very little documentation on what this message means, or how to address it.</p> <p>How can I get the framework to recognize my &lt;runtime&gt; element?</p> <p>Thanks in advance!</p>
[ { "answer_id": 198688, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 0, "selected": false, "text": "<p>While I wouldn't recommend creating a UI that requires outer scroll bars you can accomplish this pretty easily:</p>\n\n<pre><code>&lt;Window\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n &gt; \n &lt;ScrollViewer HorizontalScrollBarVisibility=\"Auto\" \n VerticalScrollBarVisibility=\"Auto\"&gt;\n &lt;Grid&gt;\n &lt;Grid.RowDefinitions&gt;\n &lt;RowDefinition Height=\"Auto\"/&gt;\n &lt;RowDefinition Height=\"Auto\"/&gt;\n &lt;RowDefinition Height=\"Auto\"/&gt;\n &lt;/Grid.RowDefinitions&gt;\n &lt;Grid.ColumnDefinitions&gt;\n &lt;ColumnDefinition Width=\"*\"/&gt;\n &lt;ColumnDefinition Width=\"Auto\"/&gt;\n &lt;/Grid.ColumnDefinitions&gt;\n &lt;ListBox Grid.Row=\"0\" Grid.RowSpan=\"3\" Grid.Column=\"0\" MinWidth=\"200\"/&gt;\n &lt;Button Grid.Row=\"0\" Grid.Column=\"1\" Content=\"Button1\"/&gt;\n &lt;Button Grid.Row=\"1\" Grid.Column=\"1\" Content=\"Button2\"/&gt;\n &lt;Button Grid.Row=\"2\" Grid.Column=\"1\" Content=\"Button3\"/&gt;\n &lt;/Grid&gt;\n &lt;/ScrollViewer&gt;\n&lt;/Window&gt;\n</code></pre>\n\n<p>I don't really recommend this. WPF provides exceptional layout systems, like Grid, and you should try to allow the app to resize itself as needed. Perhaps you can set a MinWidth/MinHeight on the window itself to prevent this resizing?</p>\n" }, { "answer_id": 218587, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 2, "selected": false, "text": "<p>You problem arises, because <code>Control</code>s within a <code>ScrollViewer</code> have virtually unlimited space available. Therefore your inner <code>ListBox</code> thinks it can avoid scrolling by taking up the complete height necessary to display all its elements. Of course in your case that behaviour has the unwanted side effect of exercising the outer <code>ScrollViewer</code> too much.</p>\n\n<p>The objective therefore is to get the <code>ListBox</code> to use the <strong>visible</strong> height within the <code>ScrollViewer</code> iff there is enough of it and a certain minimal height otherwise. To achieve this, the most direct way is to inherit from <code>ScrollViewer</code> and override <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.measureoverride.aspx\" rel=\"nofollow noreferrer\"><code>MeasureOverride()</code></a> to pass an appropriately sized <code>availableSize</code> (that is the given <code>availableSize</code> blown up to the minimal size instead of the \"usual\" infinity) to the <code>Visual</code>s found by using <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.visualchildrencount.aspx\" rel=\"nofollow noreferrer\"><code>VisualChildrenCount</code></a> and <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.getvisualchild.aspx\" rel=\"nofollow noreferrer\"><code>GetVisualChild(int)</code></a>.</p>\n" }, { "answer_id": 1571972, "author": "Daniel", "author_id": 141502, "author_profile": "https://Stackoverflow.com/users/141502", "pm_score": 4, "selected": false, "text": "<p>I've created a class to work around this problem:</p>\n\n<pre><code>public class RestrictDesiredSize : Decorator\n{\n Size lastArrangeSize = new Size(double.PositiveInfinity, double.PositiveInfinity);\n\n protected override Size MeasureOverride(Size constraint)\n {\n Debug.WriteLine(\"Measure: \" + constraint);\n base.MeasureOverride(new Size(Math.Min(lastArrangeSize.Width, constraint.Width),\n Math.Min(lastArrangeSize.Height, constraint.Height)));\n return new Size(0, 0);\n }\n\n protected override Size ArrangeOverride(Size arrangeSize)\n {\n Debug.WriteLine(\"Arrange: \" + arrangeSize);\n if (lastArrangeSize != arrangeSize) {\n lastArrangeSize = arrangeSize;\n base.MeasureOverride(arrangeSize);\n }\n return base.ArrangeOverride(arrangeSize);\n }\n}\n</code></pre>\n\n<p>It will always return a desired size of (0,0), even if the containing element wants to be bigger.\nUsage:</p>\n\n<pre><code>&lt;local:RestrictDesiredSize MinWidth=\"200\" MinHeight=\"200\"&gt;\n &lt;ListBox /&gt;\n&lt;/local&gt;\n</code></pre>\n" }, { "answer_id": 9988974, "author": "Heiner", "author_id": 495910, "author_profile": "https://Stackoverflow.com/users/495910", "pm_score": 2, "selected": false, "text": "<p>I used <a href=\"https://stackoverflow.com/users/141502/daniel\">Daniel</a>s solution. That works great. Thank you.</p>\n\n<p>Then I added two boolean dependency properties to the decorator class: <code>KeepWidth</code> and <code>KeepHeight</code>. So the new feature can be suppressed for one dimension.</p>\n\n<p>This requires a change in <code>MeasureOverride</code>:</p>\n\n<pre><code>protected override Size MeasureOverride(Size constraint)\n{\n var innerWidth = Math.Min(this._lastArrangeSize.Width, constraint.Width);\n var innerHeight = Math.Min(this._lastArrangeSize.Height, constraint.Height);\n base.MeasureOverride(new Size(innerWidth, innerHeight));\n\n var outerWidth = KeepWidth ? Child.DesiredSize.Width : 0;\n var outerHeight = KeepHeight ? Child.DesiredSize.Height : 0;\n return new Size(outerWidth, outerHeight);\n}\n</code></pre>\n" }, { "answer_id": 23748102, "author": "richarfen", "author_id": 3654438, "author_profile": "https://Stackoverflow.com/users/3654438", "pm_score": 0, "selected": false, "text": "<p>Create a method in the code-behind that sets the ListBox's MaxHeight to the height of whatever control is containing it and other controls. If the Listbox has any controls/margins/padding above or below it, subtract their heights from the container height assigned to MaxHeight. Call this method in the main windows \"loaded\" and \"window resize\" event handlers. </p>\n\n<p>This should give you the best of both worlds. You are giving the ListBox a \"fixed\" size that will cause it to scroll in spite of the fact that the main window has its own scrollbar. </p>\n" }, { "answer_id": 44592501, "author": "Dmitry", "author_id": 5475902, "author_profile": "https://Stackoverflow.com/users/5475902", "pm_score": 0, "selected": false, "text": "<p>for 2 ScrollViewer</p>\n\n<pre><code> public class ScrollExt: ScrollViewer\n{\n Size lastArrangeSize = new Size(double.PositiveInfinity, double.PositiveInfinity);\n\n public ScrollExt()\n {\n\n }\n protected override Size MeasureOverride(Size constraint)\n {\n base.MeasureOverride(new Size(Math.Min(lastArrangeSize.Width, constraint.Width),\n Math.Min(lastArrangeSize.Height, constraint.Height)));\n return new Size(0, 0);\n }\n\n protected override Size ArrangeOverride(Size arrangeSize)\n {\n if (lastArrangeSize != arrangeSize)\n {\n lastArrangeSize = arrangeSize;\n base.MeasureOverride(arrangeSize);\n }\n return base.ArrangeOverride(arrangeSize);\n }\n}\n</code></pre>\n\n<p>code:</p>\n\n<pre><code> &lt;ScrollViewer HorizontalScrollBarVisibility=\"Auto\" VerticalScrollBarVisibility=\"Auto\"&gt;\n &lt;Grid &gt;\n &lt;Grid.ColumnDefinitions&gt;\n &lt;ColumnDefinition Width=\"Auto\" /&gt;\n &lt;ColumnDefinition Width=\"*\" /&gt;\n &lt;/Grid.ColumnDefinitions&gt;\n &lt;TextBlock Background=\"Beige\" Width=\"600\" Text=\"Example\"/&gt;\n &lt;Grid Grid.Column=\"1\" x:Name=\"grid\"&gt;\n &lt;Grid Grid.Column=\"1\" Margin=\"25\" Background=\"Green\"&gt;\n &lt;local:ScrollExt HorizontalScrollBarVisibility=\"Auto\" VerticalScrollBarVisibility=\"Auto\"&gt;\n &lt;Grid Width=\"10000\" Margin=\"25\" Background=\"Red\" /&gt;\n &lt;/local:ScrollExt&gt;\n &lt;/Grid&gt;\n &lt;/Grid&gt;\n &lt;/Grid&gt;\n &lt;/ScrollViewer&gt;\n</code></pre>\n" }, { "answer_id": 53011021, "author": "Glaucus", "author_id": 1011688, "author_profile": "https://Stackoverflow.com/users/1011688", "pm_score": 0, "selected": false, "text": "<p>I ended up combining <a href=\"https://stackoverflow.com/a/1571972/1011688\">Daniels</a> answer and <a href=\"https://stackoverflow.com/a/9988974/1011688\">Heiner's</a> answer. I decided to post the entire solution to make it easier for people to adopt this if needed. Here's my decorator class:</p>\n\n<pre><code>public class RestrictDesiredSizeDecorator : Decorator\n{\n public static readonly DependencyProperty KeepWidth;\n public static readonly DependencyProperty KeepHeight;\n\n #region Dependency property setters and getters\n public static void SetKeepWidth(UIElement element, bool value)\n {\n element.SetValue(KeepWidth, value);\n }\n\n public static bool GetKeepWidth(UIElement element)\n {\n return (bool)element.GetValue(KeepWidth);\n }\n\n public static void SetKeepHeight(UIElement element, bool value)\n {\n element.SetValue(KeepHeight, value);\n }\n\n public static bool GetKeepHeight(UIElement element)\n {\n return (bool)element.GetValue(KeepHeight);\n }\n #endregion\n\n private Size _lastArrangeSize = new Size(double.PositiveInfinity, double.PositiveInfinity);\n\n static RestrictDesiredSizeDecorator()\n {\n KeepWidth = DependencyProperty.RegisterAttached(\n nameof(KeepWidth),\n typeof(bool),\n typeof(RestrictDesiredSizeDecorator));\n\n KeepHeight = DependencyProperty.RegisterAttached(\n nameof(KeepHeight),\n typeof(bool),\n typeof(RestrictDesiredSizeDecorator));\n }\n\n protected override Size MeasureOverride(Size constraint)\n {\n Debug.WriteLine(\"Measure: \" + constraint);\n\n var keepWidth = GetValue(KeepWidth) as bool? ?? false;\n var keepHeight = GetValue(KeepHeight) as bool? ?? false;\n\n var innerWidth = keepWidth ? constraint.Width : Math.Min(this._lastArrangeSize.Width, constraint.Width);\n var innerHeight = keepHeight ? constraint.Height : Math.Min(this._lastArrangeSize.Height, constraint.Height);\n base.MeasureOverride(new Size(innerWidth, innerHeight));\n\n var outerWidth = keepWidth ? Child.DesiredSize.Width : 0;\n var outerHeight = keepHeight ? Child.DesiredSize.Height : 0;\n\n return new Size(outerWidth, outerHeight);\n }\n\n protected override Size ArrangeOverride(Size arrangeSize)\n {\n Debug.WriteLine(\"Arrange: \" + arrangeSize);\n\n if (_lastArrangeSize != arrangeSize)\n {\n _lastArrangeSize = arrangeSize;\n base.MeasureOverride(arrangeSize);\n }\n\n return base.ArrangeOverride(arrangeSize);\n }\n}\n</code></pre>\n\n<p>and here's how I use it in the xaml:</p>\n\n<pre><code>&lt;ScrollViewer&gt;\n &lt;StackPanel Orientation=\"Vertical\"&gt;\n &lt;Whatever /&gt;\n\n &lt;decorators:RestrictDesiredSizeDecorator MinWidth=\"100\" KeepHeight=\"True\"&gt;\n &lt;TextBox\n Text=\"{Binding Comment, UpdateSourceTrigger=PropertyChanged}\"\n Height=\"Auto\"\n MaxHeight=\"360\"\n VerticalScrollBarVisibility=\"Auto\"\n HorizontalScrollBarVisibility=\"Auto\"\n AcceptsReturn=\"True\"\n AcceptsTab=\"True\"\n TextWrapping=\"WrapWithOverflow\"\n /&gt;\n &lt;/decorators:RestrictDesiredSizeDecorator&gt;\n\n &lt;Whatever /&gt;\n &lt;/StackPanel&gt;\n&lt;/ScrollViewer\n</code></pre>\n\n<p>The above creates a textbox that will grow vertically (until it hits MaxHeight) but will match the parent's width without growing the outer ScrollViewer. Resizing the window/ScrollViewer to less than 100 wide will force the outer ScrollViewer to show the horizontal scroll bars. Other controls with inner ScrollViewers can be used as well, including complex grids.</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27578/" ]
I have a situation where I need to be able to load assemblies in the GAC based on their partial names. In order to do this I have added the following to my app.config file: ``` <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <qualifyAssembly partialName="MyAssembly" fullName= "MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0123456789abcdef"/> </assemblyBinding> </runtime> ``` This works exactly the way I want it to. However, if I place the same element in my machine.config file, it seems to be ignored, and I get FileNotFoundExceptions when trying to load MyAssembly. The following is the assembly binding log when the element is in my app.config, and the bind succeeds: ``` LOG: This bind starts in default load context. LOG: Using application configuration file: C:\Documents and Settings\jon_scheiding\My Documents\Source\Testing\Test Projects 1\Cmd\bin\Debug\Testers.Cmd.vshost.exe.config LOG: Using machine configuration file from C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\config\machine.config. LOG: Partial reference qualified from config file. New reference: MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0123456789abcdef. LOG: Post-policy reference: MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0123456789abcdef LOG: Found assembly by looking in the GAC. LOG: Binding succeeds. Returns assembly from C:\WINDOWS\assembly\GAC_MSIL\MyAssembly\1.0.0.0__b20f4683c1030dbd\MyAssembly.dll. LOG: Assembly is loaded in default load context. ``` Contrast that with the log when my configuration is in machine.config, and the bind fails: ``` LOG: This bind starts in default load context. LOG: Using application configuration file: C:\Documents and Settings\jon_scheiding\My Documents\Source\Testing\Test Projects 1\Cmd\bin\Debug\Testers.Cmd.vshost.exe.config LOG: Using machine configuration file from C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\config\machine.config. LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind). LOG: Attempting download of new URL file:///C:/Documents and Settings/jon_scheiding/My Documents/Source/Testing/Test Projects 1/Cmd/bin/Debug/MyAssembly.DLL. LOG: Attempting download of new URL file:///C:/Documents and Settings/jon_scheiding/My Documents/Source/Testing/Test Projects 1/Cmd/bin/Debug/MyAssembly/MyAssembly.DLL. LOG: Attempting download of new URL file:///C:/Documents and Settings/jon_scheiding/My Documents/Source/Testing/Test Projects 1/Cmd/bin/Debug/MyAssembly.EXE. LOG: Attempting download of new URL file:///C:/Documents and Settings/jon_scheiding/My Documents/Source/Testing/Test Projects 1/Cmd/bin/Debug/MyAssembly/MyAssembly.EXE. LOG: All probing URLs attempted and failed. ``` The problem seems to be the fourth line, "Policy not being applied to reference at this time." However, I can find very little documentation on what this message means, or how to address it. How can I get the framework to recognize my <runtime> element? Thanks in advance!
I've created a class to work around this problem: ``` public class RestrictDesiredSize : Decorator { Size lastArrangeSize = new Size(double.PositiveInfinity, double.PositiveInfinity); protected override Size MeasureOverride(Size constraint) { Debug.WriteLine("Measure: " + constraint); base.MeasureOverride(new Size(Math.Min(lastArrangeSize.Width, constraint.Width), Math.Min(lastArrangeSize.Height, constraint.Height))); return new Size(0, 0); } protected override Size ArrangeOverride(Size arrangeSize) { Debug.WriteLine("Arrange: " + arrangeSize); if (lastArrangeSize != arrangeSize) { lastArrangeSize = arrangeSize; base.MeasureOverride(arrangeSize); } return base.ArrangeOverride(arrangeSize); } } ``` It will always return a desired size of (0,0), even if the containing element wants to be bigger. Usage: ``` <local:RestrictDesiredSize MinWidth="200" MinHeight="200"> <ListBox /> </local> ```
198,670
<p>Thanks for reading. I'm a bit new to jQuery, and am trying to make a script I can include in all my websites to solve a problem that always drives me crazy...</p> <p>The problem: Select boxes with long options get cut off in Internet Explorer. For example, these select boxes: <a href="http://discoverfire.com/test/select.php" rel="noreferrer">http://discoverfire.com/test/select.php</a></p> <p>In Firefox they are fine, but in IE, the options are cut off to the width of the select when they drop down.</p> <p>The solution: What I am looking to do, is create a script that I can include in any page that will do the following:</p> <ol> <li><p>Loop through all the selects on the page.</p></li> <li><p>For each select: A. Loop through its options. B. Find the width of the longest option. C. Bind a function to expand the select to that width on focus (or maybe click...). D. Bind a function to shrink to it's original width on blur.</p></li> </ol> <p>I've managed to do most of step #2 for one select box.</p> <p>I found that getting the options width was a problem (especially in IE), so I looped through and copied the text of each option to a span, measured the span width, and used the longest one as the width the select will be expanded to. Perhaps somebody has a better idea.</p> <p>Here is the code</p> <pre><code>&lt;script type='text/javascript'&gt; $(function() { /* This function will: 1. Create a data store for the select called ResizeToWidth. 2. Populate it with the width of the longest option, as approximated by span width. The data store can then be used */ // Make a temporary span to hold the text of the options. $('body').append("&lt;span id='CurrentOptWidth'&gt;&lt;/span&gt;"); $("#TheSelect option").each(function(i){ // If this is the first time through, zero out ResizeToWidth (or it will end up NaN). if ( isNaN( $(this).parent().data('ResizeToWidth') ) ) { $(this).parent().data( 'OriginalWidth', $(this).parent().width() ); $(this).parent().data('ResizeToWidth', 0); $('CurrentOptWidth').css('font-family', $(this).css('font-family') ); $('CurrentOptWidth').css('font-size', $(this).css('font-size') ); $('CurrentOptWidth').css('font-weight', $(this).css('font-weight') ); } // Put the text of the current option into the span. $('#CurrentOptWidth').text( $(this).text() ); // Set ResizeToWidth to the longer of a) the current opt width, or b) itself. //So it will hold the width of the longest option when we are done ResizeToWidth = Math.max( $('#CurrentOptWidth').width() , $(this).parent().data('ResizeToWidth') ); // Update parent ResizeToWidth data. $(this).parent().data('ResizeToWidth', ResizeToWidth) }); // Remove the temporary span. $('#CurrentOptWidth').remove(); $('#TheSelect').focus(function(){ $(this).width( $(this).data('ResizeToWidth') ); }); $('#TheSelect').blur(function(){ $(this).width( $(this).data('OriginalWidth') ); }); alert( $('#TheSelect').data('OriginalWidth') ); alert( $('#TheSelect').data('ResizeToWidth') ); }); &lt;/script&gt; </code></pre> <p>and the select:</p> <pre><code>&lt;select id='TheSelect' style='width:50px;'&gt; &lt;option value='1'&gt;One&lt;/option&gt; &lt;option value='2'&gt;Two&lt;/option&gt; &lt;option value='3'&gt;Three&lt;/option&gt; &lt;option value='42,693,748,756'&gt;Forty-two billion, six-hundred and ninety-three million, seven-hundred-forty-some-odd..... &lt;/option&gt; &lt;option value='5'&gt;Five&lt;/option&gt; &lt;option value='6'&gt;Six&lt;/option&gt; &lt;option value='7'&gt;Seven...&lt;/option&gt; &lt;/select&gt; </code></pre> <p>Hopefully this will run for you if you want to run it, or you can see it in action here: <a href="http://discoverfire.com/test/select.php" rel="noreferrer">http://discoverfire.com/test/select.php</a>.</p> <p>What I need help with: This needs a bit of polish, but seems to work ok if you specify the select box.</p> <p>However, I don't seem to be able to figure out how to apply it to all select boxes on the page with a loop. So far, I have this:</p> <pre><code>$('select').each( function(i, select){ // Get the options for the select here... can I use select.each...? } ); </code></pre> <p>Also, is there a better way to get the length of the longest option for each select? The span is close, but not very exact. The problem is that IE returns zero for the option widths of the actual selects.</p> <p>Any ideas are very welcome, both for the questions asked, and any other improvements to my code.</p> <p>Thanks!!</p>
[ { "answer_id": 198901, "author": "msmithstubbs", "author_id": 27606, "author_profile": "https://Stackoverflow.com/users/27606", "pm_score": 5, "selected": true, "text": "<p>To modify each select, try this:</p>\n\n<pre><code>$('select').each(function(){\n\n $('option', this).each(function() {\n // your normalizing script here\n\n })\n\n});\n</code></pre>\n\n<p>The second parameter (this) on the second jQuery call scopes the selecter ('option'), so it is essentially 'all option elements within this select'. You can think of that second parameter defaulting to 'document' if it's not supplied.</p>\n" }, { "answer_id": 198950, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 3, "selected": false, "text": "<p>I was able to replicate your results for all selects on a page in IE7 using this code, which I find much simpler than the span method you are using, but you can replace the \"resize\" function with whatever code suits your needs.</p>\n\n<pre><code>function resize(selectId, size){\n var objSelect = document.getElementById(selectId);\n var maxlength = 0;\n if(objSelect){\n if(size){\n objSelect.style.width = size;\n } else {\n for (var i=0; i&lt; objSelect.options.length; i++){\n if (objSelect[i].text.length &gt; maxlength){\n maxlength = objSelect[i].text.length;\n }\n }\n objSelect.style.width = maxlength * 9;\n }\n } \n}\n\n$(document).ready(function(){\n $(\"select\").focus(function(){\n resize($(this).attr(\"id\"));\n });\n $(\"select\").blur(function(){\n resize($(this).attr(\"id\"), 40);\n });\n});\n</code></pre>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27580/" ]
Thanks for reading. I'm a bit new to jQuery, and am trying to make a script I can include in all my websites to solve a problem that always drives me crazy... The problem: Select boxes with long options get cut off in Internet Explorer. For example, these select boxes: <http://discoverfire.com/test/select.php> In Firefox they are fine, but in IE, the options are cut off to the width of the select when they drop down. The solution: What I am looking to do, is create a script that I can include in any page that will do the following: 1. Loop through all the selects on the page. 2. For each select: A. Loop through its options. B. Find the width of the longest option. C. Bind a function to expand the select to that width on focus (or maybe click...). D. Bind a function to shrink to it's original width on blur. I've managed to do most of step #2 for one select box. I found that getting the options width was a problem (especially in IE), so I looped through and copied the text of each option to a span, measured the span width, and used the longest one as the width the select will be expanded to. Perhaps somebody has a better idea. Here is the code ``` <script type='text/javascript'> $(function() { /* This function will: 1. Create a data store for the select called ResizeToWidth. 2. Populate it with the width of the longest option, as approximated by span width. The data store can then be used */ // Make a temporary span to hold the text of the options. $('body').append("<span id='CurrentOptWidth'></span>"); $("#TheSelect option").each(function(i){ // If this is the first time through, zero out ResizeToWidth (or it will end up NaN). if ( isNaN( $(this).parent().data('ResizeToWidth') ) ) { $(this).parent().data( 'OriginalWidth', $(this).parent().width() ); $(this).parent().data('ResizeToWidth', 0); $('CurrentOptWidth').css('font-family', $(this).css('font-family') ); $('CurrentOptWidth').css('font-size', $(this).css('font-size') ); $('CurrentOptWidth').css('font-weight', $(this).css('font-weight') ); } // Put the text of the current option into the span. $('#CurrentOptWidth').text( $(this).text() ); // Set ResizeToWidth to the longer of a) the current opt width, or b) itself. //So it will hold the width of the longest option when we are done ResizeToWidth = Math.max( $('#CurrentOptWidth').width() , $(this).parent().data('ResizeToWidth') ); // Update parent ResizeToWidth data. $(this).parent().data('ResizeToWidth', ResizeToWidth) }); // Remove the temporary span. $('#CurrentOptWidth').remove(); $('#TheSelect').focus(function(){ $(this).width( $(this).data('ResizeToWidth') ); }); $('#TheSelect').blur(function(){ $(this).width( $(this).data('OriginalWidth') ); }); alert( $('#TheSelect').data('OriginalWidth') ); alert( $('#TheSelect').data('ResizeToWidth') ); }); </script> ``` and the select: ``` <select id='TheSelect' style='width:50px;'> <option value='1'>One</option> <option value='2'>Two</option> <option value='3'>Three</option> <option value='42,693,748,756'>Forty-two billion, six-hundred and ninety-three million, seven-hundred-forty-some-odd..... </option> <option value='5'>Five</option> <option value='6'>Six</option> <option value='7'>Seven...</option> </select> ``` Hopefully this will run for you if you want to run it, or you can see it in action here: <http://discoverfire.com/test/select.php>. What I need help with: This needs a bit of polish, but seems to work ok if you specify the select box. However, I don't seem to be able to figure out how to apply it to all select boxes on the page with a loop. So far, I have this: ``` $('select').each( function(i, select){ // Get the options for the select here... can I use select.each...? } ); ``` Also, is there a better way to get the length of the longest option for each select? The span is close, but not very exact. The problem is that IE returns zero for the option widths of the actual selects. Any ideas are very welcome, both for the questions asked, and any other improvements to my code. Thanks!!
To modify each select, try this: ``` $('select').each(function(){ $('option', this).each(function() { // your normalizing script here }) }); ``` The second parameter (this) on the second jQuery call scopes the selecter ('option'), so it is essentially 'all option elements within this select'. You can think of that second parameter defaulting to 'document' if it's not supplied.
198,679
<p>Given an <code>InputStream</code> called <code>in</code> which contains audio data in a compressed format (such as MP3 or OGG), I wish to create a <code>byte</code> array containing a WAV conversion of the input data. Unfortunately, if you try to do this, JavaSound hands you the following error:</p> <pre><code>java.io.IOException: stream length not specified </code></pre> <p>I managed to get it to work by writing the wav to a temporary file, then reading it back in, as shown below:</p> <pre><code>AudioInputStream source = AudioSystem.getAudioInputStream(new BufferedInputStream(in, 1024)); AudioInputStream pcm = AudioSystem.getAudioInputStream(AudioFormat.Encoding.PCM_SIGNED, source); AudioInputStream ulaw = AudioSystem.getAudioInputStream(AudioFormat.Encoding.ULAW, pcm); File tempFile = File.createTempFile("wav", "tmp"); AudioSystem.write(ulaw, AudioFileFormat.Type.WAVE, tempFile); // The fileToByteArray() method reads the file // into a byte array; omitted for brevity byte[] bytes = fileToByteArray(tempFile); tempFile.delete(); return bytes; </code></pre> <p>This is obviously less desirable. Is there a better way?</p>
[ { "answer_id": 198807, "author": "Simon Lehmann", "author_id": 27011, "author_profile": "https://Stackoverflow.com/users/27011", "pm_score": 4, "selected": true, "text": "<p>The problem is that the most AudioFileWriters need to know the file size in advance if writing to an OutputStream. Because you can't provide this, it always fails. Unfortunatly, the default Java sound API implementation doesn't have any alternatives.</p>\n\n<p>But you can try using the AudioOutputStream architecture from the Tritonus plugins (Tritonus is an open source implementation of the Java sound API): <a href=\"http://tritonus.org/plugins.html\" rel=\"noreferrer\">http://tritonus.org/plugins.html</a></p>\n" }, { "answer_id": 6505115, "author": "Gábor Dikán", "author_id": 818978, "author_profile": "https://Stackoverflow.com/users/818978", "pm_score": -1, "selected": false, "text": "<p>This is very simple...</p>\n\n<pre><code>File f = new File(exportFileName+\".tmp\");\nFile f2 = new File(exportFileName);\nlong l = f.length();\nFileInputStream fi = new FileInputStream(f);\nAudioInputStream ai = new AudioInputStream(fi,mainFormat,l/4);\nAudioSystem.write(ai, Type.WAVE, f2);\nfi.close();\nf.delete();\n</code></pre>\n\n<p>The .tmp file is a RAW audio file, the result is a WAV file with header.</p>\n" }, { "answer_id": 24537533, "author": "Superziyi", "author_id": 1208309, "author_profile": "https://Stackoverflow.com/users/1208309", "pm_score": 2, "selected": false, "text": "<p>I notice this one was asked very long time ago. In case any new person (using Java 7 and above) found this thread, note there is a better new way doing it via Files.readAllBytes API. See:\n<a href=\"https://stackoverflow.com/questions/13802441/how-to-convert-wav-file-into-byte-array\">How to convert .wav file into byte array?</a></p>\n" }, { "answer_id": 28844417, "author": "HolloW", "author_id": 752900, "author_profile": "https://Stackoverflow.com/users/752900", "pm_score": 2, "selected": false, "text": "<p>Too late, I know, but I was needed this, so this is my two cents on the topic.</p>\n\n<pre><code>public void UploadFiles(String fileName, byte[] bFile)\n{\n String uploadedFileLocation = \"c:\\\\\";\n\n AudioInputStream source;\n AudioInputStream pcm;\n InputStream b_in = new ByteArrayInputStream(bFile);\n source = AudioSystem.getAudioInputStream(new BufferedInputStream(b_in));\n pcm = AudioSystem.getAudioInputStream(AudioFormat.Encoding.PCM_SIGNED, source);\n File newFile = new File(uploadedFileLocation + fileName);\n AudioSystem.write(pcm, Type.WAVE, newFile);\n\n source.close();\n pcm.close();\n}\n</code></pre>\n" }, { "answer_id": 39232513, "author": "Kanaris007", "author_id": 5685534, "author_profile": "https://Stackoverflow.com/users/5685534", "pm_score": -1, "selected": false, "text": "<p>The issue is easy to solve if you prepare class which will create correct header for you. In my example <a href=\"http://privateblog.info/kak-zapisat-zvuk-na-java-v-byte-massiv/\" rel=\"nofollow\">Example how to read audio input in wav buffer</a> data goes in some buffer, after that I create header and have wav file in the buffer. No need in additional libraries. Just copy the code from my example.</p>\n\n<p>Example how to use class which creates correct header in the buffer array:</p>\n\n<pre><code>public void run() { \n try { \n writer = new NewWaveWriter(44100); \n\n byte[]buffer = new byte[256]; \n int res = 0; \n while((res = m_audioInputStream.read(buffer)) &gt; 0) { \n writer.write(buffer, 0, res); \n } \n } catch (IOException e) { \n System.out.println(\"Error: \" + e.getMessage()); \n } \n} \n\npublic byte[]getResult() throws IOException { \n return writer.getByteBuffer(); \n} \n</code></pre>\n\n<p>And class NewWaveWriter you can find under my link.</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4287/" ]
Given an `InputStream` called `in` which contains audio data in a compressed format (such as MP3 or OGG), I wish to create a `byte` array containing a WAV conversion of the input data. Unfortunately, if you try to do this, JavaSound hands you the following error: ``` java.io.IOException: stream length not specified ``` I managed to get it to work by writing the wav to a temporary file, then reading it back in, as shown below: ``` AudioInputStream source = AudioSystem.getAudioInputStream(new BufferedInputStream(in, 1024)); AudioInputStream pcm = AudioSystem.getAudioInputStream(AudioFormat.Encoding.PCM_SIGNED, source); AudioInputStream ulaw = AudioSystem.getAudioInputStream(AudioFormat.Encoding.ULAW, pcm); File tempFile = File.createTempFile("wav", "tmp"); AudioSystem.write(ulaw, AudioFileFormat.Type.WAVE, tempFile); // The fileToByteArray() method reads the file // into a byte array; omitted for brevity byte[] bytes = fileToByteArray(tempFile); tempFile.delete(); return bytes; ``` This is obviously less desirable. Is there a better way?
The problem is that the most AudioFileWriters need to know the file size in advance if writing to an OutputStream. Because you can't provide this, it always fails. Unfortunatly, the default Java sound API implementation doesn't have any alternatives. But you can try using the AudioOutputStream architecture from the Tritonus plugins (Tritonus is an open source implementation of the Java sound API): <http://tritonus.org/plugins.html>
198,691
<p>I'm working on a solution that contains multiple projects targeting Windows Mobile 5 and standard Windows applications.</p> <p>Lately when opening up a form in designer the common UI controls (textbox, button, label, etc etc...) have vanished leaving only the controls defined within the project.</p> <p>Resetting the toolbox has no effect. A google search suggested deleting the toolbox temp files in the <code>Local Settings\Application Data\Microsoft\VisualStudio\9.0</code>, however this was only successful in bringing back the default controls for Windows Mobile 5. The WinForms controls are still mysteriously missing.</p> <p>Also, if I right-click and <em>Select All</em> on the toolbox, all of the WinForms controls do in fact come up, however they're all grayed out.</p> <p>Has anyone else experienced this?</p>
[ { "answer_id": 199273, "author": "justin.m.chase", "author_id": 12958, "author_profile": "https://Stackoverflow.com/users/12958", "pm_score": 1, "selected": false, "text": "<p>I've noticed this exact same thing for regular WinForms as well. I can't speak to mobile applications but in regular winforms this has a tendency to happen.</p>\n\n<p>I believe it's actually a bug in Visual Studio.</p>\n\n<p>There are some things you can do (again, for WinForms. I'm not sure about mobile) with adding attributes to your control. Such as:</p>\n\n<pre><code>[ToolboxBitmap(typeof(MyControl), \"MyControlBitmap\")]\n</code></pre>\n\n<p>There are some other useful related things on this site:</p>\n\n<p><a href=\"http://en.csharp-online.net/Design-Time_Integration-Attributes\" rel=\"nofollow noreferrer\">http://en.csharp-online.net/Design-Time_Integration-Attributes</a></p>\n" }, { "answer_id": 199281, "author": "justin.m.chase", "author_id": 12958, "author_profile": "https://Stackoverflow.com/users/12958", "pm_score": 0, "selected": false, "text": "<p>Actually you may be able to <a href=\"http://msdn.microsoft.com/en-us/library/9yxtkx75(VS.80).aspx\" rel=\"nofollow noreferrer\">add a registry key</a> to get this to work also.</p>\n" }, { "answer_id": 303245, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you are running Visual Studio 2008 under vista, try running it as an Administrator. Right click on the shortcut and select <em>Run as Administrator</em>.</p>\n" }, { "answer_id": 868765, "author": "Simon H.", "author_id": 72807, "author_profile": "https://Stackoverflow.com/users/72807", "pm_score": 2, "selected": false, "text": "<p>I just had a similiar problem. In a managed C++ project all the default toolbox items disappeared form the winforms designer. After playing around for a while I found that there was a problem in the .vcproj file.</p>\n\n<pre><code>&lt;VisualStudioProject\n ProjectType=\"Visual C++\"\n Version=\"9,00\"\n Name=\"COLLADA Import\"\n ProjectGUID=\"{0DEEF9B6-1929-44E3-92EC-13712839FB63}\"\n RootNamespace=\"COLLADAImport\"\n Keyword=\"ManagedCProj\"\n TargetFrameworkVersion=\"0\"\n &gt;\n</code></pre>\n\n<p>When you set TargetFrameworkVersion to a valid number, for example 131072 for .Net 2.0, the toolbox items will be back.</p>\n" }, { "answer_id": 888389, "author": "pro", "author_id": 352728, "author_profile": "https://Stackoverflow.com/users/352728", "pm_score": 2, "selected": false, "text": "<p>If you right click on the Toolbox and select 'Choose Items...' and then sort by the 'Namespace' column, you can then select the ones you need (for example System.Windows.Forms for WinForms).</p>\n\n<p>You can multiselect with Shift and then select/deselect the group.</p>\n\n<p>The controls then reappear in the Toolbox as enabled.</p>\n" }, { "answer_id": 1613473, "author": "Muneeb Fayyaz", "author_id": 195312, "author_profile": "https://Stackoverflow.com/users/195312", "pm_score": 0, "selected": false, "text": "<p>Well guess what install Service pack 1 for VS 2008 and it would go away and if you have wireless mouse and keyboard turn it off. Choose one of these two both work.</p>\n" }, { "answer_id": 3093960, "author": "ucupahmec", "author_id": 373265, "author_profile": "https://Stackoverflow.com/users/373265", "pm_score": 1, "selected": false, "text": "<p>Go to the Tools menu and choose import &amp; export settings, then choose the 'reset all' setting, then yes. Save your current settings, after that you'll have your toolbox reappear.</p>\n" }, { "answer_id": 7986883, "author": "Alex Addison", "author_id": 1026454, "author_profile": "https://Stackoverflow.com/users/1026454", "pm_score": 0, "selected": false, "text": "<p>Make sure you're not in Debug mode.</p>\n" }, { "answer_id": 10598825, "author": "bernhardrusch", "author_id": 3056, "author_profile": "https://Stackoverflow.com/users/3056", "pm_score": 1, "selected": false, "text": "<p>I had exactly the same problem (after installing Windows Mobile SDK all items in the toolbox were greyed out).</p>\n\n<p>I've startet the Visual Studio 2008 command line as administrator and started the following command (WARNING - all your settings are lost !!)</p>\n\n<pre><code>devenv /setup /resetuserdata /selfreg /resetskippkgs\n</code></pre>\n\n<p>After that the toolbox looked fine and worked like on the first day.\nThe idea came from this thread: <a href=\"http://connect.microsoft.com/VisualStudio/feedback/details/322223/no-usable-controls-in-toolbox-when-developing-for-compact-framework\" rel=\"nofollow\">connect.microsoft.com</a></p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm working on a solution that contains multiple projects targeting Windows Mobile 5 and standard Windows applications. Lately when opening up a form in designer the common UI controls (textbox, button, label, etc etc...) have vanished leaving only the controls defined within the project. Resetting the toolbox has no effect. A google search suggested deleting the toolbox temp files in the `Local Settings\Application Data\Microsoft\VisualStudio\9.0`, however this was only successful in bringing back the default controls for Windows Mobile 5. The WinForms controls are still mysteriously missing. Also, if I right-click and *Select All* on the toolbox, all of the WinForms controls do in fact come up, however they're all grayed out. Has anyone else experienced this?
I just had a similiar problem. In a managed C++ project all the default toolbox items disappeared form the winforms designer. After playing around for a while I found that there was a problem in the .vcproj file. ``` <VisualStudioProject ProjectType="Visual C++" Version="9,00" Name="COLLADA Import" ProjectGUID="{0DEEF9B6-1929-44E3-92EC-13712839FB63}" RootNamespace="COLLADAImport" Keyword="ManagedCProj" TargetFrameworkVersion="0" > ``` When you set TargetFrameworkVersion to a valid number, for example 131072 for .Net 2.0, the toolbox items will be back.
198,705
<p>In my <a href="http://www.codeplex.com/MEF" rel="nofollow noreferrer">MEF</a> usage, I have a bunch of imports that I want to make available in many other parts of my code. Something like:</p> <pre><code>[Export (typeof (IBarProvider))] class MyBarFactory : IBarPovider { [Import] public IFoo1Service IFoo1Service { get; set; } [Import] public IFoo2Service IFoo2Service { get; set; } [Import] public IFoo3Service IFoo3Service { get; set; } [Import] public IFoo4Service IFoo4Service { get; set; } [Import] public IFoo5Service IFoo5Service { get; set; } public IBar CreateBar() { return new BarImplementation(/* want to pass the imported services here */); } } class BarImplementation : IBar { readonly zib zib; public BarImplementation(/* ... */) { this.zib = new Zib(/* pass services here, too */); } } </code></pre> <p>I could pass each imported service as an individual parameter, but it's a lot of boring code. There's gotta be something better. Any ideas?</p>
[ { "answer_id": 198708, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 0, "selected": false, "text": "<p>I thought about making an interface to provide these services:</p>\n\n<pre><code>partial class BarImplementation\n{\n public IRequiredServices\n {\n\n public IFoo1Service IFoo1Service { get; set; }\n public IFoo2Service IFoo2Service { get; set; } \n public IFoo3Service IFoo3Service { get; set; } \n public IFoo4Service IFoo4Service { get; set; } \n public IFoo5Service IFoo5Service { get; set; }\n }\n}\n</code></pre>\n\n<p>Then <code>MyBarFactory</code> implements <code>BarImplementation : BarImplementation.IRequiredServices</code>. That's easy to write, but then, how do I pass them down to <code>Zib</code>? I don't want to couple <code>Zib</code> to its consumer that way.</p>\n" }, { "answer_id": 198715, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 0, "selected": false, "text": "<p>I could make <code>IImports</code> an interface that contains all the services I import, pass that around everywhere, and then classes can use or not use whichever they like. But that couples all the classes toegether.</p>\n" }, { "answer_id": 207547, "author": "Wes Haggard", "author_id": 12784, "author_profile": "https://Stackoverflow.com/users/12784", "pm_score": 1, "selected": false, "text": "<p>I'm not entirely sure this answers your question but have you considered using the constructor injection yet?</p>\n\n<pre><code>class BarImplementation : IBar\n{\n [ImportingConstructor]\n public BarImplementation(IFoo1Service foo1, IFoo2Service foo2, ...) { }\n}\n</code></pre>\n\n<p>By marking your constructor with the ImportingConstructor attribute it will essentially make all the parameters of that constructor required imports.</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5314/" ]
In my [MEF](http://www.codeplex.com/MEF) usage, I have a bunch of imports that I want to make available in many other parts of my code. Something like: ``` [Export (typeof (IBarProvider))] class MyBarFactory : IBarPovider { [Import] public IFoo1Service IFoo1Service { get; set; } [Import] public IFoo2Service IFoo2Service { get; set; } [Import] public IFoo3Service IFoo3Service { get; set; } [Import] public IFoo4Service IFoo4Service { get; set; } [Import] public IFoo5Service IFoo5Service { get; set; } public IBar CreateBar() { return new BarImplementation(/* want to pass the imported services here */); } } class BarImplementation : IBar { readonly zib zib; public BarImplementation(/* ... */) { this.zib = new Zib(/* pass services here, too */); } } ``` I could pass each imported service as an individual parameter, but it's a lot of boring code. There's gotta be something better. Any ideas?
I'm not entirely sure this answers your question but have you considered using the constructor injection yet? ``` class BarImplementation : IBar { [ImportingConstructor] public BarImplementation(IFoo1Service foo1, IFoo2Service foo2, ...) { } } ``` By marking your constructor with the ImportingConstructor attribute it will essentially make all the parameters of that constructor required imports.
198,707
<p>As a workaround for a problem, I think I have to handle KeyDown events to get the printable character the user actually typed.</p> <p>KeyDown supplies me with a KeyEventArgs object with the properities KeyCode, KeyData, KeyValue, Modifiers, Alt, Shift, Control.</p> <p>My first attempt was just to consider the KeyCode to be the ascii code, but KeyCode on my keyboard is 46, a period ("."), so I end up printing a period when the user types the delete key. So, I know my logic is inadequate.</p> <p>(For those who are curious, the problem is that I have my own combobox in a DataGridView's control collection and somehow SOME characters I type don't produce the KeyPress and TextChanged ComboBox events. These letters include Q, $, %....</p> <p>This code will reproduce the problem. Generate a Form App and replace the ctor with this code. Run it, and try typing the letter Q into the two comboxes.</p> <pre><code>public partial class Form1 : Form { ComboBox cmbInGrid; ComboBox cmbNotInGrid; DataGridView grid; public Form1() { InitializeComponent(); grid = new DataGridView(); cmbInGrid = new ComboBox(); cmbNotInGrid = new ComboBox(); cmbInGrid.Items.Add("a"); cmbInGrid.Items.Add("b"); cmbNotInGrid.Items.Add("c"); cmbNotInGrid.Items.Add("d"); this.Controls.Add(cmbNotInGrid); this.Controls.Add(grid); grid.Location = new Point(0, 100); this.grid.Controls.Add(cmbInGrid); } </code></pre>
[ { "answer_id": 198736, "author": "gnud", "author_id": 27204, "author_profile": "https://Stackoverflow.com/users/27204", "pm_score": 0, "selected": false, "text": "<p>Have a look at System.Text.Encoding.ASCII and System.Text.Encoding.Default</p>\n" }, { "answer_id": 198804, "author": "Aleris", "author_id": 20417, "author_profile": "https://Stackoverflow.com/users/20417", "pm_score": 0, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>KeysConverter converter = new KeysConverter();\nstring key = converter.ConvertTo(e.KeyCode, typeof(string));\n</code></pre>\n\n<p>But is very strange the behavior you are describing. You should get the KeyPress in those cases...\nTry to do a simple example (just a form with KeyPreview = true and KeyPress event handled) and see what you get. Also check in the language bar when the form is displayed, maybe there is an input method different than what you expect.</p>\n" }, { "answer_id": 201137, "author": "Jon Schneider", "author_id": 12484, "author_profile": "https://Stackoverflow.com/users/12484", "pm_score": 0, "selected": false, "text": "<p>Just as an idea to throw out there, if it looks like your <code>DataGridView</code> is intercepting keyboard events before they can reach your child control, can you provide your own handlers for the keyboard events you are interested in directly on the <code>DataGridView</code>, and in the handler method(s), (1) suppress the <code>DataGridView</code>'s normal handling of the event, and/or (2) manually pass the event along to your child control?</p>\n" }, { "answer_id": 1801116, "author": "Pedery", "author_id": 118211, "author_profile": "https://Stackoverflow.com/users/118211", "pm_score": 2, "selected": false, "text": "<p>Many controls override the default key input events. For instance, a Panel won't respond to them by default at all. As for the case of simple controls, you could try:</p>\n\n<pre><code>protected override bool IsInputKey(Keys keyData) {\n // This snippet informs .Net that arrow keys should be processed in the panel (which is strangely not standard).\n\n switch (keyData &amp; Keys.KeyCode) {\n case Keys.Left:\n return true;\n case Keys.Right:\n return true;\n case Keys.Up:\n return true;\n case Keys.Down:\n return true;\n }\n return base.IsInputKey(keyData);\n\n}\n</code></pre>\n\n<p>The IsInputKey function tells your program what keys to receive events from. There is a chance you'll get weird behaviour if you override keys that clearly have special functions, but experiment a little and see for yourself what works and what doesn't.</p>\n\n<p>Now, for more advanced controls like a DataGridView or ComboBox, keyhandling can be even more complicated. The following resource should give you a few pointers about how to go about your problem:</p>\n\n<p><a href=\"http://www.dotnet247.com/247reference/msgs/29/148332.aspx\" rel=\"nofollow noreferrer\">http://www.dotnet247.com/247reference/msgs/29/148332.aspx</a></p>\n\n<p>Or this resource might perhaps solve your problem:</p>\n\n<p><a href=\"http://dotnetperls.com/previewkeydown\" rel=\"nofollow noreferrer\">http://dotnetperls.com/previewkeydown</a></p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9328/" ]
As a workaround for a problem, I think I have to handle KeyDown events to get the printable character the user actually typed. KeyDown supplies me with a KeyEventArgs object with the properities KeyCode, KeyData, KeyValue, Modifiers, Alt, Shift, Control. My first attempt was just to consider the KeyCode to be the ascii code, but KeyCode on my keyboard is 46, a period ("."), so I end up printing a period when the user types the delete key. So, I know my logic is inadequate. (For those who are curious, the problem is that I have my own combobox in a DataGridView's control collection and somehow SOME characters I type don't produce the KeyPress and TextChanged ComboBox events. These letters include Q, $, %.... This code will reproduce the problem. Generate a Form App and replace the ctor with this code. Run it, and try typing the letter Q into the two comboxes. ``` public partial class Form1 : Form { ComboBox cmbInGrid; ComboBox cmbNotInGrid; DataGridView grid; public Form1() { InitializeComponent(); grid = new DataGridView(); cmbInGrid = new ComboBox(); cmbNotInGrid = new ComboBox(); cmbInGrid.Items.Add("a"); cmbInGrid.Items.Add("b"); cmbNotInGrid.Items.Add("c"); cmbNotInGrid.Items.Add("d"); this.Controls.Add(cmbNotInGrid); this.Controls.Add(grid); grid.Location = new Point(0, 100); this.grid.Controls.Add(cmbInGrid); } ```
Many controls override the default key input events. For instance, a Panel won't respond to them by default at all. As for the case of simple controls, you could try: ``` protected override bool IsInputKey(Keys keyData) { // This snippet informs .Net that arrow keys should be processed in the panel (which is strangely not standard). switch (keyData & Keys.KeyCode) { case Keys.Left: return true; case Keys.Right: return true; case Keys.Up: return true; case Keys.Down: return true; } return base.IsInputKey(keyData); } ``` The IsInputKey function tells your program what keys to receive events from. There is a chance you'll get weird behaviour if you override keys that clearly have special functions, but experiment a little and see for yourself what works and what doesn't. Now, for more advanced controls like a DataGridView or ComboBox, keyhandling can be even more complicated. The following resource should give you a few pointers about how to go about your problem: <http://www.dotnet247.com/247reference/msgs/29/148332.aspx> Or this resource might perhaps solve your problem: <http://dotnetperls.com/previewkeydown>
198,716
<p>I need to pivot one column (Numbers column). example need this data:</p> <pre><code>a 1 a 2 b 3 b 4 c 5 d 6 d 7 d 8 d 9 e 10 e 11 e 12 e 13 e 14 </code></pre> <p>Look like this</p> <pre><code>a 1 2 b 3 4 c 5 d 6 7 8 9 e 10 11 12 13 14 </code></pre> <p>any help would be greatly appreciated...</p>
[ { "answer_id": 198879, "author": "Booji Boy", "author_id": 1433, "author_profile": "https://Stackoverflow.com/users/1433", "pm_score": 1, "selected": false, "text": "<p>This related question should have the answer you need: <a href=\"https://stackoverflow.com/questions/24470/sql-server-pivot-examples\">SQL Server: Examples of PIVOTing String data</a></p>\n\n<p>A Matrix control in SSRS has dynamic columns, if this data is bound for a report anyways then you could use that. Otherwise you'll have to create a sql sproc that generates the sql like in the exaamples dynamicly and then executes it. </p>\n" }, { "answer_id": 198920, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 1, "selected": false, "text": "<p>Just because I wanted to get some more experience with CTEs, I came up with the following:</p>\n\n<pre><code>WITH CTE(CTEstring, CTEids, CTElast_id)\nAS\n(\n SELECT string, CAST(id AS VARCHAR(1000)), id\n FROM dbo.Test_Pivot TP1\n WHERE NOT EXISTS (SELECT * FROM dbo.Test_Pivot TP2 WHERE TP2.string = TP1.string AND TP2.id &lt; TP1.id)\n UNION ALL\n SELECT CTEstring, CAST(CTEids + ' ' + CAST(TP.id AS VARCHAR) AS VARCHAR(1000)), TP.id\n FROM dbo.Test_Pivot TP\n INNER JOIN CTE ON\n CTE.CTEstring = TP.string\n WHERE\n TP.id &gt; CTE.CTElast_id AND\n NOT EXISTS (SELECT * FROM dbo.Test_Pivot WHERE string = CTE.CTEstring AND id &gt; CTE.CTElast_id AND id &lt; TP.id)\n)\nSELECT\n t1.CTEstring, t1.CTEids\nFROM CTE t1\nINNER JOIN (SELECT CTEstring, MAX(LEN(CTEids)) AS max_len_ids FROM CTE GROUP BY CTEstring) SQ ON SQ.CTEstring = t1.CTEstring AND SQ.max_len_ids = LEN(t1.CTEids)\nORDER BY CTEstring\nGO\n</code></pre>\n\n<p>It might need some tweaking, but it worked with your example</p>\n" }, { "answer_id": 198972, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 1, "selected": false, "text": "<p>The coalesce function could also be used here, similar to other questions that have been asked about concatenating data. </p>\n\n<p><a href=\"https://stackoverflow.com/questions/6899/is-there-a-way-to-create-a-mssql-function-to-join-multiple-rows-from-a-subquery#6924\">How to create a SQL Server function to &quot;join&quot; multiple rows from a subquery into a single delimited field?</a></p>\n" }, { "answer_id": 199041, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 0, "selected": false, "text": "<p>I'm not sure that what you're doing is really possible (or at least practical) in SQL - I'm not sure, because I'm still not exactly sure what you want to do.</p>\n\n<p>You could build that pivot table in your client application, for example with:</p>\n\n<pre><code>select distinct Letter from MyTable\n</code></pre>\n\n<p>to get the list of letters, and then use a parameterized query inside a loop:</p>\n\n<pre><code>select Number from MyTable where Letter=:letter\n</code></pre>\n\n<p>to get the list of numbers for each letter.</p>\n" }, { "answer_id": 199763, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 4, "selected": false, "text": "<p>Using <code>ROW_NUMBER()</code>, <code>PIVOT</code> and some dynamic SQL (but no cursor necessary) :</p>\n\n<pre><code>CREATE TABLE [dbo].[stackoverflow_198716](\n [code] [varchar](1) NOT NULL,\n [number] [int] NOT NULL\n) ON [PRIMARY]\n\nDECLARE @sql AS varchar(max)\nDECLARE @pivot_list AS varchar(max) -- Leave NULL for COALESCE technique\nDECLARE @select_list AS varchar(max) -- Leave NULL for COALESCE technique\n\nSELECT @pivot_list = COALESCE(@pivot_list + ', ', '') + '[' + CONVERT(varchar, PIVOT_CODE) + ']'\n ,@select_list = COALESCE(@select_list + ', ', '') + '[' + CONVERT(varchar, PIVOT_CODE) + '] AS [col_' + CONVERT(varchar, PIVOT_CODE) + ']'\nFROM (\n SELECT DISTINCT PIVOT_CODE\n FROM (\n SELECT code, number, ROW_NUMBER() OVER (PARTITION BY code ORDER BY number) AS PIVOT_CODE\n FROM stackoverflow_198716\n ) AS rows\n) AS PIVOT_CODES\n\nSET @sql = '\n;WITH p AS (\n SELECT code, number, ROW_NUMBER() OVER (PARTITION BY code ORDER BY number) AS PIVOT_CODE\n FROM stackoverflow_198716\n)\nSELECT code, ' + @select_list + '\nFROM p\nPIVOT (\n MIN(number)\n FOR PIVOT_CODE IN (\n ' + @pivot_list + '\n )\n) AS pvt\n'\n\nPRINT @sql\n\nEXEC (@sql)\n</code></pre>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27585/" ]
I need to pivot one column (Numbers column). example need this data: ``` a 1 a 2 b 3 b 4 c 5 d 6 d 7 d 8 d 9 e 10 e 11 e 12 e 13 e 14 ``` Look like this ``` a 1 2 b 3 4 c 5 d 6 7 8 9 e 10 11 12 13 14 ``` any help would be greatly appreciated...
Using `ROW_NUMBER()`, `PIVOT` and some dynamic SQL (but no cursor necessary) : ``` CREATE TABLE [dbo].[stackoverflow_198716]( [code] [varchar](1) NOT NULL, [number] [int] NOT NULL ) ON [PRIMARY] DECLARE @sql AS varchar(max) DECLARE @pivot_list AS varchar(max) -- Leave NULL for COALESCE technique DECLARE @select_list AS varchar(max) -- Leave NULL for COALESCE technique SELECT @pivot_list = COALESCE(@pivot_list + ', ', '') + '[' + CONVERT(varchar, PIVOT_CODE) + ']' ,@select_list = COALESCE(@select_list + ', ', '') + '[' + CONVERT(varchar, PIVOT_CODE) + '] AS [col_' + CONVERT(varchar, PIVOT_CODE) + ']' FROM ( SELECT DISTINCT PIVOT_CODE FROM ( SELECT code, number, ROW_NUMBER() OVER (PARTITION BY code ORDER BY number) AS PIVOT_CODE FROM stackoverflow_198716 ) AS rows ) AS PIVOT_CODES SET @sql = ' ;WITH p AS ( SELECT code, number, ROW_NUMBER() OVER (PARTITION BY code ORDER BY number) AS PIVOT_CODE FROM stackoverflow_198716 ) SELECT code, ' + @select_list + ' FROM p PIVOT ( MIN(number) FOR PIVOT_CODE IN ( ' + @pivot_list + ' ) ) AS pvt ' PRINT @sql EXEC (@sql) ```
198,717
<p>Ok, so I'm building bread crumbs and depending on the value of the breadcrumb an image will be the seperator. So "HOME" will have one image and "SEARCH" will have another. </p> <p>I know I can do this programatically (at least I ASSUME) but is there an easier way to do this? Can I link an image to a node based on the value of the node? Can I do it with PathSeparatorTemplate? </p> <p>Thank you. </p>
[ { "answer_id": 198817, "author": "Aleris", "author_id": 20417, "author_profile": "https://Stackoverflow.com/users/20417", "pm_score": 2, "selected": false, "text": "<p>You can put an</p>\n\n<pre><code>&lt;asp:Image ... /&gt;\n</code></pre>\n\n<p>into the PathSerparatorTemplate but you still have to set the image url from code.</p>\n" }, { "answer_id": 199212, "author": "Alfred B. Thordarson", "author_id": 3379, "author_profile": "https://Stackoverflow.com/users/3379", "pm_score": 1, "selected": true, "text": "<p>I see you have already accepted an answer, but I thought some code would help, so here is some:</p>\n\n<h2>Site1.Master</h2>\n\n<hr>\n\n<pre><code> &lt;asp:SiteMapPath ID=\"SiteMapPath1\" Runat=\"server\" OnItemDataBound=\"Item_Bound\"&gt;\n &lt;PathSeparatorTemplate&gt;\n &lt;asp:Image ID=\"SepImage\" runat=\"server\" ImageUrl=\"/images\"/&gt;\n &lt;/PathSeparatorTemplate&gt;\n &lt;/asp:SiteMapPath&gt;\n</code></pre>\n\n<h2>Site1.Master.cs</h2>\n\n<hr>\n\n<pre><code> private string lastItemKey = \"\";\n public void Item_Bound(Object sender, SiteMapNodeItemEventArgs e)\n {\n if (e.Item.ItemType == SiteMapNodeItemType.PathSeparator)\n {\n string imageUrl = ((Image) e.Item.Controls[1]).ImageUrl;\n imageUrl += lastItemKey + \".png\";\n ((Image) e.Item.Controls[1]).ImageUrl = imageUrl;\n }\n else\n {\n lastItemKey = e.Item.SiteMapNode.Key;\n }\n }\n</code></pre>\n\n<p>Then I have an <code>/images</code> directory containing an image for each of the <code>Key</code>'s of the <code>SiteMapNode</code>s. In other terms: this code will result in the image being displayed, after each of the path nodes, to depend on the key of the node before it.</p>\n\n<p>Hope this helps someone.</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4140/" ]
Ok, so I'm building bread crumbs and depending on the value of the breadcrumb an image will be the seperator. So "HOME" will have one image and "SEARCH" will have another. I know I can do this programatically (at least I ASSUME) but is there an easier way to do this? Can I link an image to a node based on the value of the node? Can I do it with PathSeparatorTemplate? Thank you.
I see you have already accepted an answer, but I thought some code would help, so here is some: Site1.Master ------------ --- ``` <asp:SiteMapPath ID="SiteMapPath1" Runat="server" OnItemDataBound="Item_Bound"> <PathSeparatorTemplate> <asp:Image ID="SepImage" runat="server" ImageUrl="/images"/> </PathSeparatorTemplate> </asp:SiteMapPath> ``` Site1.Master.cs --------------- --- ``` private string lastItemKey = ""; public void Item_Bound(Object sender, SiteMapNodeItemEventArgs e) { if (e.Item.ItemType == SiteMapNodeItemType.PathSeparator) { string imageUrl = ((Image) e.Item.Controls[1]).ImageUrl; imageUrl += lastItemKey + ".png"; ((Image) e.Item.Controls[1]).ImageUrl = imageUrl; } else { lastItemKey = e.Item.SiteMapNode.Key; } } ``` Then I have an `/images` directory containing an image for each of the `Key`'s of the `SiteMapNode`s. In other terms: this code will result in the image being displayed, after each of the path nodes, to depend on the key of the node before it. Hope this helps someone.
198,726
<p>I'm responsible for several (rather small) programs, which share a lot of code via different libraries. I'm wondering what the best repository layout is to develop the different prorgrams (and libraries), and keep the libraries in sync across all the programs.</p> <p>For the sake of argument let's say there are two programs with two libraries:</p> <ul> <li>Program1 <ul> <li>Library1</li> <li>Library2</li> </ul></li> <li>Program2 <ul> <li>Library1</li> <li>Library2</li> </ul></li> </ul> <p>Naturally, bug fixes and enhancements for the libraries should (eventually) merge to all programs. Since the libraries are being worked on while working on the different programs, using <a href="http://svnbook.red-bean.com/en/1.5/svn.advanced.externals.html" rel="noreferrer">externals definitions</a> seems out of the question.</p> <p>So I thought to treat my libraries at all but one place as <a href="http://svnbook.red-bean.com/en/1.5/svn.advanced.vendorbr.html" rel="noreferrer">vendor branches</a> but I'm not sure what the best layout for this would be.</p> <p>I was thinking something along the lines of:</p> <ul> <li>Libraries <ul> <li>Library1 (ancestor)</li> <li>Library2 (ancestor)</li> </ul></li> <li>Program1 <ul> <li>Program1 code</li> <li>Library1 (vendor branch)</li> <li>Library2 (vendor branch)</li> </ul></li> <li>...</li> </ul> <p>Then say when developing Program1 some changes are made for Library2, I merge them back to the Libraries part of the repository, and merge them from there to all other programs when desired. </p> <p>Merging to the other programs can't always happen immediately, the people working on Program2 could be close to a release and rather finish that first, create a tag, and only then update all libraries.</p> <p>I'm a bit concerned this will result in many merges and a bit of a maintenance headache after a while but I don't really see a much better solution.</p> <p>Then again, this seems a rather common use case to me, so I thought I'd just ask the stackoverflow community, what's the best repository layout to achieve this?</p>
[ { "answer_id": 198784, "author": "Steve Moyer", "author_id": 17008, "author_profile": "https://Stackoverflow.com/users/17008", "pm_score": 1, "selected": false, "text": "<p>Why does the source for the library have to exist in the program tree. Compile your libraries separately and link them into your programs.</p>\n" }, { "answer_id": 198800, "author": "oz10", "author_id": 14069, "author_profile": "https://Stackoverflow.com/users/14069", "pm_score": 4, "selected": true, "text": "<p>Well, I guess I disagree that externals are out of the question. I've had a similar problem in the past. I solved it using the svn property externals.</p>\n\n<p>Create your library repositories:</p>\n\n<pre><code>svnadmin create /path/library1\nsvnadmin create /path/library2\n...\n</code></pre>\n\n<p>Create client repositories:</p>\n\n<pre><code>svnadmin create /path/program1\nsvnadmin create /path/program2\n...\n</code></pre>\n\n<p>Now declare the libraries as external within the program repositories:</p>\n\n<pre><code>cd /path/program1\nsvn propset svn:externals \"library1 svnpath://wherever/library1/trunk/\" .\nsvn propset svn:externals \"library2 svnpath://wherever2/library2/trunk/\" .\n</code></pre>\n\n<p>Now then you can make changes to programs 1 &amp; 2 and making commits at the root of those projects doesn't affect the libraries... but, if you needed to make changes to the libraries you can. Then if and only if you have write permissions to the library repositories you could commit those changes too - but only from the library's subdirectory. </p>\n\n<p>I.e. this doesn't make a commit to the libraries...</p>\n\n<pre><code>... make a change in /path/program1/library1 ... \ncd /path/program1\nsvn commit -m \"some change\"\n</code></pre>\n\n<p>This commits the change made in the library above:</p>\n\n<pre><code>cd /path/program1/library1\nsvn commit -m \"change to library code\"\n</code></pre>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5822/" ]
I'm responsible for several (rather small) programs, which share a lot of code via different libraries. I'm wondering what the best repository layout is to develop the different prorgrams (and libraries), and keep the libraries in sync across all the programs. For the sake of argument let's say there are two programs with two libraries: * Program1 + Library1 + Library2 * Program2 + Library1 + Library2 Naturally, bug fixes and enhancements for the libraries should (eventually) merge to all programs. Since the libraries are being worked on while working on the different programs, using [externals definitions](http://svnbook.red-bean.com/en/1.5/svn.advanced.externals.html) seems out of the question. So I thought to treat my libraries at all but one place as [vendor branches](http://svnbook.red-bean.com/en/1.5/svn.advanced.vendorbr.html) but I'm not sure what the best layout for this would be. I was thinking something along the lines of: * Libraries + Library1 (ancestor) + Library2 (ancestor) * Program1 + Program1 code + Library1 (vendor branch) + Library2 (vendor branch) * ... Then say when developing Program1 some changes are made for Library2, I merge them back to the Libraries part of the repository, and merge them from there to all other programs when desired. Merging to the other programs can't always happen immediately, the people working on Program2 could be close to a release and rather finish that first, create a tag, and only then update all libraries. I'm a bit concerned this will result in many merges and a bit of a maintenance headache after a while but I don't really see a much better solution. Then again, this seems a rather common use case to me, so I thought I'd just ask the stackoverflow community, what's the best repository layout to achieve this?
Well, I guess I disagree that externals are out of the question. I've had a similar problem in the past. I solved it using the svn property externals. Create your library repositories: ``` svnadmin create /path/library1 svnadmin create /path/library2 ... ``` Create client repositories: ``` svnadmin create /path/program1 svnadmin create /path/program2 ... ``` Now declare the libraries as external within the program repositories: ``` cd /path/program1 svn propset svn:externals "library1 svnpath://wherever/library1/trunk/" . svn propset svn:externals "library2 svnpath://wherever2/library2/trunk/" . ``` Now then you can make changes to programs 1 & 2 and making commits at the root of those projects doesn't affect the libraries... but, if you needed to make changes to the libraries you can. Then if and only if you have write permissions to the library repositories you could commit those changes too - but only from the library's subdirectory. I.e. this doesn't make a commit to the libraries... ``` ... make a change in /path/program1/library1 ... cd /path/program1 svn commit -m "some change" ``` This commits the change made in the library above: ``` cd /path/program1/library1 svn commit -m "change to library code" ```
198,743
<p>After many years of using make, I've just started using jam (actually ftjam) for my projects. </p> <p>In my project workspaces, I have two directories:</p> <ul> <li><code>src</code> where I build executables and libraries</li> <li><code>test</code> where my test programs are</li> </ul> <p>I'm trying to set up a dependency on test programs so that each time I compile them, the libraries will be recompiled as well (if they need to).</p> <p>Any suggestion on how to do it? </p>
[ { "answer_id": 201788, "author": "Remo.D", "author_id": 16827, "author_profile": "https://Stackoverflow.com/users/16827", "pm_score": 2, "selected": false, "text": "<p>Ok this seems to be not an as easy question as I thought so I worked out a solution on my own. It uses a script to achieve the end result so I still hope that a Jam guru will have a jam-only solution.</p>\n\n<ul>\n<li><p>Create a Jamrules in the root directory of the project with the common definitions.</p></li>\n<li><p>Create a Jamfile in the root directory of the project with the following content:</p></li>\n</ul>\n\n<pre>\n\n SubDir . ;\n SubInclude . src ;\n SubInclude . test ;\n\n</pre>\n\n<ul>\n<li>Create a Jamfile in the src directory</li>\n</ul>\n\n<pre>\n\n SubDir .. src ;\n Library mylib : mylib.c ; \n\n</pre>\n\n<ul>\n<li>Create a Jamfile in the test directory</li>\n</ul>\n\n<pre>\n\n SubDir .. test ;\n Main mytest : mytest.c ; \n Depends mytest : mylib$(SUFLIB) ;\n\n</pre>\n\n<p>With this setting, as long as I am in the root directory, whenever I try to build mytest the library will also be recompiled (if needed). I found an old message on the jammer mailing list describing it.</p>\n\n<p>Alas this doesn't work if I'm in the test subdirectory since jam can only look <em>down</em> into subdirectories.</p>\n\n<p>So, I created a simple script called <code>jmk</code> and put it together with the <code>jam</code> executable (so that both are in the path):</p>\n\n<pre><code>if [ \"$JMKROOT\" = \"\" ] ; then\n JMKROOT=`pwd`\n export JMKROOT\nfi\ncd $JMKROOT\njam $*\n</code></pre>\n\n<p>and I set the JMKROOT environment variable to the root of my project.</p>\n\n<p>For when I compile in a Windows shell (that's why I want to use Jam) I simply use this small <code>jmk.bat</code> batch file:</p>\n\n<pre><code>@echo off\nif \"%JMKROOT%\" EQU \"\" set JMKROOT=%CD%\n\nset OLDCD=%CD%\ncd %JMKROOT%\njam %1 %2 %3 %4 %5 %6 %7 %8 %9\n\ncd %OLDCD%\n</code></pre>\n" }, { "answer_id": 18434928, "author": "wjk", "author_id": 2059100, "author_profile": "https://Stackoverflow.com/users/2059100", "pm_score": 0, "selected": false, "text": "<p>I'm using Jam in <a href=\"http://github.com/Andromeda-OS/LLVM\" rel=\"nofollow\">one of my projects</a>, and I am encountering your very situation. I have my executable programs in the <code>bin</code> subdirectory, and my static libraries are kept in the <code>lib</code> subdirectory.</p>\n\n<p>In my top-level Jamfile, I type in <code>SubDir TOP ;</code>. This initializes the <code>$(TOP)</code> variable to point to the directory containing this Jamfile. I then add lines such as <code>SubInclude TOP bin llvm-tblgen</code> and <code>SubInclude TOP lib Support</code>, which adds the contents of the Jamfiles in <code>bin/llvm-tblgen</code> and <code>lib/Support</code> to the build.</p>\n\n<p>In the Jamfile in <code>bin/llvm-tblgen</code>, I type in <code>SubDir TOP bin llvm-tblgen ;</code>. I do the same in the Jamfile in <code>lib/Support</code>, but I use <code>SubDir TOP lib Support ;</code> instead. The key when entering <code>SubDir</code> rules is to type in the names of each subdirectory from the <code>TOP</code> to the directory containing this Jamfile.</p>\n\n<p>Then, when it is time to set the linkline of my executable target, I reference the support library like this: <code>$(TOP)/lib/Support/libLLVMSupport.a</code>. Jam expands this path into the location of <code>libLLVMSupport.a</code>, relative to where I run Jam, even if I cd into the <code>bin/llvm-tblgen</code> directory and run Jam manually from there.</p>\n\n<p>This makes it very easy to manage large projects that contain cross-directory dependencies. This solution, unlike your earlier one, lets you run Jam directly. Hope it helps you!</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16827/" ]
After many years of using make, I've just started using jam (actually ftjam) for my projects. In my project workspaces, I have two directories: * `src` where I build executables and libraries * `test` where my test programs are I'm trying to set up a dependency on test programs so that each time I compile them, the libraries will be recompiled as well (if they need to). Any suggestion on how to do it?
Ok this seems to be not an as easy question as I thought so I worked out a solution on my own. It uses a script to achieve the end result so I still hope that a Jam guru will have a jam-only solution. * Create a Jamrules in the root directory of the project with the common definitions. * Create a Jamfile in the root directory of the project with the following content: ``` SubDir . ; SubInclude . src ; SubInclude . test ; ``` * Create a Jamfile in the src directory ``` SubDir .. src ; Library mylib : mylib.c ; ``` * Create a Jamfile in the test directory ``` SubDir .. test ; Main mytest : mytest.c ; Depends mytest : mylib$(SUFLIB) ; ``` With this setting, as long as I am in the root directory, whenever I try to build mytest the library will also be recompiled (if needed). I found an old message on the jammer mailing list describing it. Alas this doesn't work if I'm in the test subdirectory since jam can only look *down* into subdirectories. So, I created a simple script called `jmk` and put it together with the `jam` executable (so that both are in the path): ``` if [ "$JMKROOT" = "" ] ; then JMKROOT=`pwd` export JMKROOT fi cd $JMKROOT jam $* ``` and I set the JMKROOT environment variable to the root of my project. For when I compile in a Windows shell (that's why I want to use Jam) I simply use this small `jmk.bat` batch file: ``` @echo off if "%JMKROOT%" EQU "" set JMKROOT=%CD% set OLDCD=%CD% cd %JMKROOT% jam %1 %2 %3 %4 %5 %6 %7 %8 %9 cd %OLDCD% ```
198,744
<p>Yeah, its a bit on this side of pointless, but I was wondering... I've got all these codebehind files cluttering my MVC app. The only reason why I need these files, as far as I can tell, is to tell ASP.NET that my page extends from ViewPage rather than Page. </p> <p>I've tried a couple different Page directives changes, but nothing I've found will allow me to identify the base class for the page AND let me delete the codebehind files.</p> <p>Is there a way to do it?</p> <p><strong>UPDATE</strong>: I'm trying to inherit from a strongly-typed ViewPage! Seems like its possible to inherit from a regular ViewPage...</p>
[ { "answer_id": 198794, "author": "Sumit", "author_id": 16123, "author_profile": "https://Stackoverflow.com/users/16123", "pm_score": 2, "selected": false, "text": "<p>Assuming you don't have any code in your codebehind, why don't you point them all to one codebehind file?</p>\n" }, { "answer_id": 198797, "author": "Chris Sutton", "author_id": 3289, "author_profile": "https://Stackoverflow.com/users/3289", "pm_score": 3, "selected": true, "text": "<p>Delete the codebehind and use a page directive like this:</p>\n\n<pre><code>&lt;%@ Page Title=\"Title\" Inherits=\"System.Web.Mvc.ViewPage\" Language=\"C#\" MasterPageFile=\"~/Views/Layouts/Site.Master\" %&gt;\n</code></pre>\n\n<p>Or, if you want to get rid of the codebehind but still want to use strongly typed view, then read this link: <a href=\"http://devlicio.us/blogs/tim_barcz/archive/2008/08/13/strongly-typed-viewdata-without-a-codebehind.aspx\" rel=\"nofollow noreferrer\">http://devlicio.us/blogs/tim_barcz/archive/2008/08/13/strongly-typed-viewdata-without-a-codebehind.aspx</a></p>\n\n<p>Here is a cut and paste of what this would look like:</p>\n\n<pre><code>&lt;%@ Page Inherits=\"System.Web.Mvc.ViewPage`1[[ABCCompany.MVC.Web.Models.LoginData, ABCCompany.MVC.Web]]\" Language=\"C#\" MasterPageFile=\"~/Views/Shared/Site.Master\" %&gt;\n</code></pre>\n" }, { "answer_id": 198818, "author": "Wyatt", "author_id": 26626, "author_profile": "https://Stackoverflow.com/users/26626", "pm_score": 0, "selected": false, "text": "<p>Straight out of the box you should be able to delete the .designer.cs and nothing will break. The other code behind can be useful, for instance if you'd like to strongly type your viewdata.</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Yeah, its a bit on this side of pointless, but I was wondering... I've got all these codebehind files cluttering my MVC app. The only reason why I need these files, as far as I can tell, is to tell ASP.NET that my page extends from ViewPage rather than Page. I've tried a couple different Page directives changes, but nothing I've found will allow me to identify the base class for the page AND let me delete the codebehind files. Is there a way to do it? **UPDATE**: I'm trying to inherit from a strongly-typed ViewPage! Seems like its possible to inherit from a regular ViewPage...
Delete the codebehind and use a page directive like this: ``` <%@ Page Title="Title" Inherits="System.Web.Mvc.ViewPage" Language="C#" MasterPageFile="~/Views/Layouts/Site.Master" %> ``` Or, if you want to get rid of the codebehind but still want to use strongly typed view, then read this link: <http://devlicio.us/blogs/tim_barcz/archive/2008/08/13/strongly-typed-viewdata-without-a-codebehind.aspx> Here is a cut and paste of what this would look like: ``` <%@ Page Inherits="System.Web.Mvc.ViewPage`1[[ABCCompany.MVC.Web.Models.LoginData, ABCCompany.MVC.Web]]" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" %> ```
198,754
<p>When using the unmanaged API for the .NET framework to profile a .NET process in-process, is it possible to look up the IL instruction pointer that correlates to the native instruction pointer provided to the StackSnapshotCallback function?</p> <p>As is probably obvious, I am taking a snapshot of the current stack, and would like to provide file and line number information in the stack dump. The <em>Managed Stack Explorer</em> does this by querying <code>ISymUnmanagedMethod::GetSequencePoints</code>. This is great, but the sequence points are associated to offsets, and I have so far assumed these are offsets from the beginning of the method ( in intermediate language ).</p> <p>In a follow-up comment to his blog post <a href="https://web.archive.org/web/20190114032244/https://blogs.msdn.microsoft.com/davbr/2005/10/06/profiler-stack-walking-basics-and-beyond" rel="nofollow noreferrer">Profiler stack walking: Basics and beyond</a>, David Broman indicates that this mapping can be achieved using <code>ICorDebugCode::GetILToNativeMapping</code>. However, this is not ideal as getting this interface requires attaching to my process from another, debugger process.</p> <p>I would like to avoid that step because I would like to continue to be able to run my application from within the visual studio debugger while I am taking these snapshots. It makes it easier to click on the line number in the output window and go to the code in question.</p> <p>The functionality is possible.... you can spit out a line-numbered stack trace at will inside of managed code, the only question, is it accessible. Also, I don't want to use the <code>System::Diagnostics::StackTrace</code> or <code>System::Environment::StackTrace</code> functionality because, for performance reasons, I need to delay the actual dump of the stack.... so saving the cost for resolution of method names and code location for later is desirable... along with the ability to intermix native and managed frames.</p>
[ { "answer_id": 214123, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>Console.WriteLine(\"StackTrace: '{0}'\", Environment.StackTrace);\n</code></pre>\n\n<p>Make sure your build generates symbols.</p>\n\n<p>Expanding on the discussion:</p>\n\n<blockquote>\n <blockquote>\n <p>As is probably obvious, I am taking a snapshot of the current stack, and would like to provide file and line number information in the stack dump.</p>\n </blockquote>\n</blockquote>\n\n<p>Given this - It looks like the only reason you're not attaching to process is so that you can debug your tool , or parts of it , easily, as you're developing it. That IMO is a poor excuse for not choosing a better design (ICorDebug or w/e ) when its available. The reason its poor design is because your code executes in the process space of (presumably) external binaries , causing nasty ('sometimes' rare) side effects (including corrupting somebody else data) in known (or worse - unknown) corrupt process states. That should be enough to begin with, but even otherwise, there are several edge cases with multi-threaded code, etc where the design needs to be worked around. </p>\n\n<p>Most people generally ask \"What are you really trying to do?\" as a reply to an overtly complex way of doing things. In <strong>most</strong> cases there is a simpler/easier way. Having written a stack tracer for native code, I know it can get messy. </p>\n\n<p>Now maybe you might end up making everything work , so - Just my $.02</p>\n" }, { "answer_id": 255795, "author": "Steven", "author_id": 27577, "author_profile": "https://Stackoverflow.com/users/27577", "pm_score": 4, "selected": true, "text": "<p>In order to translate from a native instruction pointer as provided by <code>ICorProfilerInfo2::DoStackSnapshot</code> to an intermediate language method offset, you must take two steps since <code>DoStackSnapshot</code> provides a <code>FunctionID</code> and native instruction pointer as a virtual memory address.</p>\n\n<p>Step 1, is to convert the instruction pointer to a native code method offset. ( an offset from the beginning of the JITed method). This can be done with <code>ICorProfilerInfo2::GetCodeInfo2</code></p>\n\n<pre><code>ULONG32 pcIL(0xffffffff);\nHRESULT hr(E_FAIL);\nCOR_PRF_CODE_INFO* codeInfo(NULL);\nCOR_DEBUG_IL_TO_NATIVE_MAP* map(NULL);\nULONG32 cItem(0);\n\nUINT_PTR nativePCOffset(0xffffffff);\nif (SUCCEEDED(hr = pInfo-&gt;GetCodeInfo2(functioId, 0, &amp;cItem, NULL)) &amp;&amp;\n (NULL != (codeInfo = new COR_PRF_CODE_INFO[cItem])))\n{\n if (SUCCEEDED(hr = pInfo-&gt;GetCodeInfo2(functionId, cItem, &amp;cItem, codeInfo)))\n {\n COR_PRF_CODE_INFO *pCur(codeInfo), *pEnd(codeInfo + cItem);\n nativePCOffset = 0;\n for (; pCur &lt; pEnd; pCur++)\n {\n // 'ip' is the UINT_PTR passed to the StackSnapshotCallback as named in\n // the docs I am looking at \n if ((ip &gt;= pCur-&gt;startAddress) &amp;&amp; (ip &lt; (pCur-&gt;startAddress + pCur-&gt;size)))\n {\n nativePCOffset += (instructionPtr - pCur-&gt;startAddress);\n break;\n }\n else\n {\n nativePCOffset += pCur-&gt;size;\n }\n\n }\n }\n delete[] codeInfo; codeInfo = NULL;\n}\n</code></pre>\n\n<p>Step 2. Once you have an offset from the begining of the natvie code method, you can use this to convert to an offset from the begining of the intermediate language method using <code>ICorProfilerInfo2::GetILToNativeMapping</code>.</p>\n\n<pre><code>if ((nativePCOffset != -1) &amp;&amp;\n SUCCEEDED(hr = pInfo-&gt;GetILToNativeMapping(functionId, 0, &amp;cItem, NULL)) &amp;&amp;\n (NULL != (map = new COR_DEBUG_IL_TO_NATIVE_MAP[cItem])))\n{\n if (SUCCEEDED(pInfo-&gt;GetILToNativeMapping(functionId, cItem, &amp;cItem, map)))\n {\n COR_DEBUG_IL_TO_NATIVE_MAP* mapCurrent = map + (cItem - 1);\n for (;mapCurrent &gt;= map; mapCurrent--)\n {\n if ((mapCurrent-&gt;nativeStartOffset &lt;= nativePCOffset) &amp;&amp; \n (mapCurrent-&gt;nativeEndOffset &gt; nativePCOffset))\n {\n pcIL = mapCurrent-&gt;ilOffset;\n break;\n }\n }\n }\n delete[] map; map = NULL;\n}\n</code></pre>\n\n<p>This can then be used to map the code location to a file and line number using the symbol APIs</p>\n\n<p>Thanks to <a href=\"http://social.msdn.microsoft.com/Forums/en-US/netfxtoolsdev/thread/ee47a207-5ee6-4e24-a89f-e2134a8eb7c8\" rel=\"noreferrer\">Mithun Shanbhag</a> for direction in finding the solution.</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27577/" ]
When using the unmanaged API for the .NET framework to profile a .NET process in-process, is it possible to look up the IL instruction pointer that correlates to the native instruction pointer provided to the StackSnapshotCallback function? As is probably obvious, I am taking a snapshot of the current stack, and would like to provide file and line number information in the stack dump. The *Managed Stack Explorer* does this by querying `ISymUnmanagedMethod::GetSequencePoints`. This is great, but the sequence points are associated to offsets, and I have so far assumed these are offsets from the beginning of the method ( in intermediate language ). In a follow-up comment to his blog post [Profiler stack walking: Basics and beyond](https://web.archive.org/web/20190114032244/https://blogs.msdn.microsoft.com/davbr/2005/10/06/profiler-stack-walking-basics-and-beyond), David Broman indicates that this mapping can be achieved using `ICorDebugCode::GetILToNativeMapping`. However, this is not ideal as getting this interface requires attaching to my process from another, debugger process. I would like to avoid that step because I would like to continue to be able to run my application from within the visual studio debugger while I am taking these snapshots. It makes it easier to click on the line number in the output window and go to the code in question. The functionality is possible.... you can spit out a line-numbered stack trace at will inside of managed code, the only question, is it accessible. Also, I don't want to use the `System::Diagnostics::StackTrace` or `System::Environment::StackTrace` functionality because, for performance reasons, I need to delay the actual dump of the stack.... so saving the cost for resolution of method names and code location for later is desirable... along with the ability to intermix native and managed frames.
In order to translate from a native instruction pointer as provided by `ICorProfilerInfo2::DoStackSnapshot` to an intermediate language method offset, you must take two steps since `DoStackSnapshot` provides a `FunctionID` and native instruction pointer as a virtual memory address. Step 1, is to convert the instruction pointer to a native code method offset. ( an offset from the beginning of the JITed method). This can be done with `ICorProfilerInfo2::GetCodeInfo2` ``` ULONG32 pcIL(0xffffffff); HRESULT hr(E_FAIL); COR_PRF_CODE_INFO* codeInfo(NULL); COR_DEBUG_IL_TO_NATIVE_MAP* map(NULL); ULONG32 cItem(0); UINT_PTR nativePCOffset(0xffffffff); if (SUCCEEDED(hr = pInfo->GetCodeInfo2(functioId, 0, &cItem, NULL)) && (NULL != (codeInfo = new COR_PRF_CODE_INFO[cItem]))) { if (SUCCEEDED(hr = pInfo->GetCodeInfo2(functionId, cItem, &cItem, codeInfo))) { COR_PRF_CODE_INFO *pCur(codeInfo), *pEnd(codeInfo + cItem); nativePCOffset = 0; for (; pCur < pEnd; pCur++) { // 'ip' is the UINT_PTR passed to the StackSnapshotCallback as named in // the docs I am looking at if ((ip >= pCur->startAddress) && (ip < (pCur->startAddress + pCur->size))) { nativePCOffset += (instructionPtr - pCur->startAddress); break; } else { nativePCOffset += pCur->size; } } } delete[] codeInfo; codeInfo = NULL; } ``` Step 2. Once you have an offset from the begining of the natvie code method, you can use this to convert to an offset from the begining of the intermediate language method using `ICorProfilerInfo2::GetILToNativeMapping`. ``` if ((nativePCOffset != -1) && SUCCEEDED(hr = pInfo->GetILToNativeMapping(functionId, 0, &cItem, NULL)) && (NULL != (map = new COR_DEBUG_IL_TO_NATIVE_MAP[cItem]))) { if (SUCCEEDED(pInfo->GetILToNativeMapping(functionId, cItem, &cItem, map))) { COR_DEBUG_IL_TO_NATIVE_MAP* mapCurrent = map + (cItem - 1); for (;mapCurrent >= map; mapCurrent--) { if ((mapCurrent->nativeStartOffset <= nativePCOffset) && (mapCurrent->nativeEndOffset > nativePCOffset)) { pcIL = mapCurrent->ilOffset; break; } } } delete[] map; map = NULL; } ``` This can then be used to map the code location to a file and line number using the symbol APIs Thanks to [Mithun Shanbhag](http://social.msdn.microsoft.com/Forums/en-US/netfxtoolsdev/thread/ee47a207-5ee6-4e24-a89f-e2134a8eb7c8) for direction in finding the solution.
198,777
<p>I'm trying to configure Windows Powershell to work with Visual Studio. Nothing fancy, just get things set so I can cl &amp; nmake. I think all I need to do is edit the path setting(but I don't know how to set that in WPSH).</p>
[ { "answer_id": 198822, "author": "jerhinesmith", "author_id": 1108, "author_profile": "https://Stackoverflow.com/users/1108", "pm_score": 1, "selected": false, "text": "<p>You might want to check out <a href=\"https://stackoverflow.com/questions/138144/whats-in-your-powershell-profileps1file#139997\">this post</a> -- it seems to address your question fairly well (it worked for what I wanted, anyway).</p>\n" }, { "answer_id": 199529, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 3, "selected": true, "text": "<p>After much digging around, I created a directory in My Documents named <strong>WindowsPowerShell</strong>, created a file named <strong>Microsoft.PowerShell_profile.ps1</strong>, and(after a few iterations), inserted the following code in it, and it works.</p>\n\n<pre><code>function Get-Batchfile($file) \n{\n $theCmd = \"`\"$file`\" &amp; set\" \n cmd /c $theCmd | Foreach-Object {\n $thePath, $theValue = $_.split('=')\n Set-Item -path env:$thePath -value $theValue\n }\n}\n\n\nGet-Batchfile(\"C:\\Program Files\\Microsoft Visual Studio 9.0\\VC\\vcvarsall.bat\")\n</code></pre>\n\n<p>Thanks everyone for their kind help. :-)</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26227/" ]
I'm trying to configure Windows Powershell to work with Visual Studio. Nothing fancy, just get things set so I can cl & nmake. I think all I need to do is edit the path setting(but I don't know how to set that in WPSH).
After much digging around, I created a directory in My Documents named **WindowsPowerShell**, created a file named **Microsoft.PowerShell\_profile.ps1**, and(after a few iterations), inserted the following code in it, and it works. ``` function Get-Batchfile($file) { $theCmd = "`"$file`" & set" cmd /c $theCmd | Foreach-Object { $thePath, $theValue = $_.split('=') Set-Item -path env:$thePath -value $theValue } } Get-Batchfile("C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat") ``` Thanks everyone for their kind help. :-)
198,781
<p>Easy question this time.</p> <p>I'm trying to test whether or not a string does not contain a character using regular expressions. I thought the expression was of the form "[^<em>x</em>]" where <em>x</em> is the character that you don't want to appear, but that doesn't seem to be working.</p> <p>For example,</p> <pre><code>Regex.IsMatch("103","[^0]") </code></pre> <p>and</p> <pre><code>Regex.IsMatch("103&amp;","[^&amp;]") </code></pre> <p>both return true (I would expect false).</p> <p>I started using <code>"[^&amp;]"</code> and thought maybe the &amp; needed to be escaped as \&amp;, but it didn't seem to make a difference.</p> <p>Ideas? I assume it's something small.</p> <p>Also, I'm using .NET, so keep that in mind.</p> <p>Edit1:</p> <p>I found <a href="https://stackoverflow.com/questions/42990/regex-to-match-against-something-that-is-not-a-specific-substring">this</a>, but it doesn't seem to answer the issue I'm having.</p> <p>Edit2:</p> <p>I wanted to respond to <a href="https://stackoverflow.com/questions/198781/regex-to-tell-if-a-string-does-not-contain-a-specific-character#198793">Kevin</a> and <a href="https://stackoverflow.com/questions/198781/regex-to-tell-if-a-string-does-not-contain-a-specific-character#198796">Joel</a>'s suggestions. These suggestions would indeed be faster, but they don't accomplish the flexibility I need in this case, so if you found this question through search, definitely look to see if their answers will fit your needs. In my case, the regular expression is getting passed in to a DataTable validation method that loops through each row and verifies that the contents of that row in a specific column matches the RegEx that is getting passed in. Since I'll be reusing this method for several other DataTables that are being validated, I wanted to:</p> <ol> <li>Use Regex to enable the widest range of validations, and</li> <li>Always look for a positive match (i.e. instead of using !Regex.IsMatch(cell, regexvariable), I wanted to rely on always being able to use Regex.IsMatch(cell, regexvariable) since the majority of DataTables invoking this method will be using the positive match instead of the negative.</li> </ol> <p>Hopefully that helps.</p>
[ { "answer_id": 198790, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 7, "selected": true, "text": "<p>Your solution is half right. The match you see is for the other characters. What you want to say is something like \"hey! I do not want to see this character in the entire string\".</p>\n\n<p>In that case you do:</p>\n\n<pre><code>Regex.IsMatch(\"103\",\"^[^0]*$\")\n</code></pre>\n" }, { "answer_id": 198792, "author": "stephenbayer", "author_id": 18893, "author_profile": "https://Stackoverflow.com/users/18893", "pm_score": 2, "selected": false, "text": "<p>The first character the parser reaches is \"1\", which is true for [^0] and also true for [^&amp;], so therefore it will return true in both of those examples. </p>\n" }, { "answer_id": 198793, "author": "Kevin", "author_id": 19038, "author_profile": "https://Stackoverflow.com/users/19038", "pm_score": 3, "selected": false, "text": "<p>if you are looking for a single character in a string, regex seems like a bit of an overkill. Why not just use .IndexOf or .Contains ?</p>\n" }, { "answer_id": 198796, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>You're putting your negation in the wrong place. <code>[^x]</code> will match anything that isn't x. If x is in the string, the string still matches the expression if there are any other characters as well. Instead, you want to match true if x is there, and then negate the result of the function:</p>\n\n<pre><code>Not Regex.IsMatch(\"103\", \"0\")\n\nNot Regex.IsMatch(\"103&amp;\", \"&amp;\")\n</code></pre>\n\n<p>Not that with these simple examples, the normal String.IndexOf() or String.Contains() would be a better choice.</p>\n" }, { "answer_id": 198810, "author": "Ken Paul", "author_id": 26671, "author_profile": "https://Stackoverflow.com/users/26671", "pm_score": 4, "selected": false, "text": "<p>The pattern [^0] will match any character that is not a zero. In both of your examples, the pattern will match the first character (\"1\"). To test whether the entire string contains no zeros, the pattern should be \"^[^0]*$\". This reads as follows: Start at the beginning of the string, match an arbitrary number of characters which are not zeros, followed immediately by the end of the string. Any string containing a zero will fail. Any string containing no zeros will pass.</p>\n" }, { "answer_id": 2503334, "author": "Brett", "author_id": 300284, "author_profile": "https://Stackoverflow.com/users/300284", "pm_score": 2, "selected": false, "text": "<p>I came across this question looking for the same thing but for JavaScript. The expression above did not work in my case, but I came across the below expression which did. (Just in case anybody else looking for a JavaScript solution ends up here too.)</p>\n\n<p><code>^((?!0).)*$</code></p>\n\n<p>This construct is called a <a href=\"https://www.regular-expressions.info/lookaround.html\" rel=\"nofollow noreferrer\">Negative Lookahead</a></p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1108/" ]
Easy question this time. I'm trying to test whether or not a string does not contain a character using regular expressions. I thought the expression was of the form "[^*x*]" where *x* is the character that you don't want to appear, but that doesn't seem to be working. For example, ``` Regex.IsMatch("103","[^0]") ``` and ``` Regex.IsMatch("103&","[^&]") ``` both return true (I would expect false). I started using `"[^&]"` and thought maybe the & needed to be escaped as \&, but it didn't seem to make a difference. Ideas? I assume it's something small. Also, I'm using .NET, so keep that in mind. Edit1: I found [this](https://stackoverflow.com/questions/42990/regex-to-match-against-something-that-is-not-a-specific-substring), but it doesn't seem to answer the issue I'm having. Edit2: I wanted to respond to [Kevin](https://stackoverflow.com/questions/198781/regex-to-tell-if-a-string-does-not-contain-a-specific-character#198793) and [Joel](https://stackoverflow.com/questions/198781/regex-to-tell-if-a-string-does-not-contain-a-specific-character#198796)'s suggestions. These suggestions would indeed be faster, but they don't accomplish the flexibility I need in this case, so if you found this question through search, definitely look to see if their answers will fit your needs. In my case, the regular expression is getting passed in to a DataTable validation method that loops through each row and verifies that the contents of that row in a specific column matches the RegEx that is getting passed in. Since I'll be reusing this method for several other DataTables that are being validated, I wanted to: 1. Use Regex to enable the widest range of validations, and 2. Always look for a positive match (i.e. instead of using !Regex.IsMatch(cell, regexvariable), I wanted to rely on always being able to use Regex.IsMatch(cell, regexvariable) since the majority of DataTables invoking this method will be using the positive match instead of the negative. Hopefully that helps.
Your solution is half right. The match you see is for the other characters. What you want to say is something like "hey! I do not want to see this character in the entire string". In that case you do: ``` Regex.IsMatch("103","^[^0]*$") ```
198,831
<p>I'm building an app in Ruby on Rails, and I'm including 3 of my models (and their migration scripts) to show what I'm trying to do, and what isn't working. Here's the rundown: I have users in my application that belong to teams, and each team can have multiple coaches. I want to be able to pull a list of the coaches that are applicable to a user. </p> <p>For instance, User A could belong to teams T1 and T2. Teams T1 and T2 could have four different coaches each, and one coach in common. I'd like to be able to pull the list of coaches by simply saying: </p> <pre><code>u = User.find(1) coaches = u.coaches </code></pre> <p>Here are my migration scripts, and the associations in my models. Am I doing something incorrectly in my design? Are my associations correct?</p> <pre><code>class CreateUsers &lt; ActiveRecord::Migration def self.up create_table :users do |t| t.column :login, :string, :default =&gt; nil t.column :firstname, :string, :default =&gt; nil t.column :lastname, :string, :default =&gt; nil t.column :password, :string, :default =&gt; nil t.column :security_token, :string, :default =&gt; nil t.column :token_expires, :datetime, :default =&gt; nil t.column :legacy_password, :string, :default =&gt; nil end end def self.down drop_table :users end end class CreateTeams &lt; ActiveRecord::Migration def self.up create_table :teams do |t| t.column :name, :string end end def self.down drop_table :teams end end class TeamsUsers &lt; ActiveRecord::Migration def self.up create_table :teams_users, :id =&gt; false do |t| t.column :team_id, :integer t.column :user_id, :integer t.column :joined_date, :datetime end end def self.down drop_table :teams_users end end </code></pre> <p>Here are the models (not the entire file):</p> <pre><code>class User &lt; ActiveRecord::Base has_and_belongs_to_many :teams has_many :coaches, :through =&gt; :teams class Team &lt; ActiveRecord::Base has_many :coaches has_and_belongs_to_many :users class Coach &lt; ActiveRecord::Base belongs_to :teams end </code></pre> <p>This is what happens when I try to pull the coaches:</p> <pre><code>u = User.find(1) =&gt; #&lt;User id: 1, firstname: "Dan", lastname: "Wolchonok"&gt; &gt;&gt; u.coaches ActiveRecord::StatementInvalid: Mysql::Error: #42S22Unknown column 'teams.user_id' in 'where clause': SELECT `coaches`.* FROM `coaches` INNER JOIN teams ON coaches.team_id = teams.id WHERE ((`teams`.user_id = 1)) </code></pre> <p>Here's the error in sql:</p> <p>Mysql::Error: #42S22Unknown column 'teams.user_id' in 'where clause': SELECT <code>coaches</code>.* FROM <code>coaches</code> INNER JOIN teams ON coaches.team_id = teams.id WHERE ((<code>teams</code>.user_id = 1)) </p> <p>Am I missing something in my :through clause? Is my design totally off? Can someone point me in the right direction?</p>
[ { "answer_id": 198956, "author": "Mike Deck", "author_id": 1247, "author_profile": "https://Stackoverflow.com/users/1247", "pm_score": 1, "selected": false, "text": "<p>I don't think ActiveRecord can handle doing a 2 step join in a has_many relationship. In order for this to work you'll have to join users to team_users to teams to coaches. The through option only allows for one extra join.</p>\n\n<p>Instead you'll have to use the :finder_sql option and write out the full join clause yourself. Not the prettiest thing in the world, but that's how it goes with ActiveRecord when you try to do something out of the ordinary.</p>\n" }, { "answer_id": 198971, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 2, "selected": false, "text": "<p>It's more of a many-to-many-to-even-more-relationship. I'd just write some sql:</p>\n\n<pre><code>has_many :coaches, :finder_sql =&gt; 'SELECT * from coaches, teams_users WHERE \n coaches.team_id=teams_users.team_id \n AND teams_users.user_id=#{id}'\n</code></pre>\n" }, { "answer_id": 199064, "author": "Steropes", "author_id": 21872, "author_profile": "https://Stackoverflow.com/users/21872", "pm_score": 3, "selected": true, "text": "<p>You can't do a has_many :through twice in a row. It'll tell you that its an invalid association. If you don't want to add finder_sql like above, you can add a method that mimics what you're trying to do.</p>\n\n<pre><code> def coaches\n self.teams.collect do |team|\n team.coaches\n end.flatten.uniq\n end\n</code></pre>\n" }, { "answer_id": 199109, "author": "Roy Pardee", "author_id": 64731, "author_profile": "https://Stackoverflow.com/users/64731", "pm_score": 1, "selected": false, "text": "<p>You could drop the \"has_many :coaches, :through => :teams\" line in users &amp; then hand-write a coaches method in your User model like so:</p>\n\n<pre><code>def coaches\n ret = []\n teams.each do |t|\n t.coaches.each do |c|\n ret &lt;&lt; c\n end\n end\n ret.uniq\nend\n</code></pre>\n" }, { "answer_id": 199830, "author": "Dan Wolchonok", "author_id": 168, "author_profile": "https://Stackoverflow.com/users/168", "pm_score": 0, "selected": false, "text": "<p>While I love to write SQL, I don't think it's the ideal solution in this instance. Here's what I ended up doing in the User model:</p>\n\n<pre><code> def coaches\n self.teams.collect do |team|\n team.coaches\n end.flatten.uniq\n end\n\n def canCoach(coachee)\n u = User.find(coachee)\n\n coaches = u.coaches\n c = []\n coaches.collect do |coach|\n c.push(coach.user_id)\n end\n\n return c.include?(self.id)\n end\n</code></pre>\n\n<p>I thought about just doing it all in one fell swoop, but I liked the ability to return an array of coach objects from within the user object. If there's a better way to do it, I'm very interested in seeing the improved code.</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/168/" ]
I'm building an app in Ruby on Rails, and I'm including 3 of my models (and their migration scripts) to show what I'm trying to do, and what isn't working. Here's the rundown: I have users in my application that belong to teams, and each team can have multiple coaches. I want to be able to pull a list of the coaches that are applicable to a user. For instance, User A could belong to teams T1 and T2. Teams T1 and T2 could have four different coaches each, and one coach in common. I'd like to be able to pull the list of coaches by simply saying: ``` u = User.find(1) coaches = u.coaches ``` Here are my migration scripts, and the associations in my models. Am I doing something incorrectly in my design? Are my associations correct? ``` class CreateUsers < ActiveRecord::Migration def self.up create_table :users do |t| t.column :login, :string, :default => nil t.column :firstname, :string, :default => nil t.column :lastname, :string, :default => nil t.column :password, :string, :default => nil t.column :security_token, :string, :default => nil t.column :token_expires, :datetime, :default => nil t.column :legacy_password, :string, :default => nil end end def self.down drop_table :users end end class CreateTeams < ActiveRecord::Migration def self.up create_table :teams do |t| t.column :name, :string end end def self.down drop_table :teams end end class TeamsUsers < ActiveRecord::Migration def self.up create_table :teams_users, :id => false do |t| t.column :team_id, :integer t.column :user_id, :integer t.column :joined_date, :datetime end end def self.down drop_table :teams_users end end ``` Here are the models (not the entire file): ``` class User < ActiveRecord::Base has_and_belongs_to_many :teams has_many :coaches, :through => :teams class Team < ActiveRecord::Base has_many :coaches has_and_belongs_to_many :users class Coach < ActiveRecord::Base belongs_to :teams end ``` This is what happens when I try to pull the coaches: ``` u = User.find(1) => #<User id: 1, firstname: "Dan", lastname: "Wolchonok"> >> u.coaches ActiveRecord::StatementInvalid: Mysql::Error: #42S22Unknown column 'teams.user_id' in 'where clause': SELECT `coaches`.* FROM `coaches` INNER JOIN teams ON coaches.team_id = teams.id WHERE ((`teams`.user_id = 1)) ``` Here's the error in sql: Mysql::Error: #42S22Unknown column 'teams.user\_id' in 'where clause': SELECT `coaches`.\* FROM `coaches` INNER JOIN teams ON coaches.team\_id = teams.id WHERE ((`teams`.user\_id = 1)) Am I missing something in my :through clause? Is my design totally off? Can someone point me in the right direction?
You can't do a has\_many :through twice in a row. It'll tell you that its an invalid association. If you don't want to add finder\_sql like above, you can add a method that mimics what you're trying to do. ``` def coaches self.teams.collect do |team| team.coaches end.flatten.uniq end ```
198,849
<p>I've just performed a new installation of the very latest (Fall, 2008) version of Fedora 9 Linux and am perplexed that it never set the default route properly and that even traveling the labyrinthine ways of this OS, there's no obvious way.</p> <p>Of course, it's clear that one can do it on a one-off basis like this:</p> <pre><code> route add default gw gw1 metric 0 eth0 </code></pre> <p>or like this:</p> <pre><code> ip route add to default via 192.168.2.1 protocol static </code></pre> <p>However, neither of these survives reboot. In reading through /etc/rc.d/init.d/network, it attempts to find data from a file in /etc/sysconfig/static-routes, but that file never existed. So, I tried to create it and populate it with data. The trouble with that is that the script places a dash (minus sign) in an odd spot that I'm not sure how to deal with.</p> <p>Of course, one can just edit /etc/rc.d/init.d/network, but that would be non-standard. As it is, my only other recourse seems to be editing rc.local, but that doesn't come early enough in the boot sequence to be there for things like, for example, the network time daemon.</p> <p>I've done my homework - I've read all the man pages, info entries, tried apropos, and I've even done a fair bit of web searching, all to no avail - my next step, sans answer here, will be to sign up to the Fedora mailing lists and ask there! Or, give up and edit the scripts.</p> <p>So, how is one supposed to do this?</p>
[ { "answer_id": 198859, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 1, "selected": false, "text": "<p>I have not used recent versions of Fedora, but it was often set as a GATEWAY variable in /etc/sysconfig/network.</p>\n\n<p>Of course, if you just wanted it to work, you could just put the commands in /etc/rc.local to be executed when the boot sequence completes.</p>\n" }, { "answer_id": 198899, "author": "John Nilsson", "author_id": 24243, "author_profile": "https://Stackoverflow.com/users/24243", "pm_score": 0, "selected": false, "text": "<p>Haven't seen Fedora. But shouldn't there be some GUI for this kind of thing? If you have Gnome try running <code>gnome-network-preferences</code></p>\n" }, { "answer_id": 198969, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 4, "selected": true, "text": "<p>The gateway is normally set in /etc/sysconfig/network-scripts/ifcfg-eth0, not in /etc/sysconfig/network. For example, on my current machine:</p>\n\n<blockquote>\n <p>/etc/sysconfig/network</p>\n</blockquote>\n\n<pre><code>NETWORKING=yes\nNETWORKING_IPV6=no\nHOSTNAME=flyboys\nNISDOMAIN=ekcineon\n</code></pre>\n\n<blockquote>\n <p>/etc/sysconfig/network-scripts/ifcfg-eth0</p>\n</blockquote>\n\n<pre><code>DEVICE=eth0\nONBOOT=yes\nHWADDR=00:1d:09:31:3a:cc\nNETMASK=255.255.255.0\nIPADDR=150.102.65.30\nGATEWAY=150.102.65.252\nTYPE=Ethernet\n</code></pre>\n\n<p>Note that I set HWADDR because I have two ethernet cards and I want to make sure the right one is assigned to eth0. The configuration for the second card is in /etc/sysconfig/network-scripts/ifcfg-eth1</p>\n" }, { "answer_id": 26589470, "author": "Dex", "author_id": 1463474, "author_profile": "https://Stackoverflow.com/users/1463474", "pm_score": 0, "selected": false, "text": "<p>Here it is for RHEL, as it is slightly different:</p>\n\n<p><ol>\n<li>Identify the interface by using ifconfig</li>\n<li>sudo vi /etc/sysconfig/network-scripts/route-ethXX</li>\n<li>add the routes as per syntax below, where /xx represents subnet mask</p>\n\n<blockquote>\n<pre><code>host: 172.30.xxx.xxx via 172.30.xxx.xxx\nnetwork: 172.30.xxx.xxx/xx via 172.30.xxx.xxx\nDefault gateway: 0.0.0.0 via xxx.xxx.xxx.xxx&lt;/li&gt;\n</code></pre>\n \n <p><li>Save the file.</li>\n <li>sudo /etc/init.d/network restart (Warning: if you forget to set\n correct routes for the management interface (if applicable) you may lose\n connectivity to the server)</li>\n </ol></p>\n</blockquote>\n" }, { "answer_id": 39559978, "author": "user6845878", "author_id": 6845878, "author_profile": "https://Stackoverflow.com/users/6845878", "pm_score": 2, "selected": false, "text": "<p>just edit the <code>/etc/sysconfig/network-scripts/route-ethXX</code></p>\n\n<p>and write inside: <strong>default via ip_address dev device</strong> , replace <strong>ip_address</strong> with <strong>your gateway ip</strong> and <strong>device</strong> with <strong>the name of the right eth device</strong>. but for the <strong>Device option</strong> its ... optional, set it in the case of multiple eth devices.\nWorks even in case of network restart, the route directive in rc.local works at boot only.</p>\n" }, { "answer_id": 67841807, "author": "Luc", "author_id": 9520099, "author_profile": "https://Stackoverflow.com/users/9520099", "pm_score": 1, "selected": false, "text": "<p>You can use nmcli if available, e.i.</p>\n<pre><code>\n# nmcli con show\nNAME UUID TYPE DEVICE\nSystem eth0 xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx ethernet eth0\nens33 xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx ethernet --\n\n# nmcli con edit &quot;System eth0&quot;\n\nnmcli&gt; goto ipv4\nYou may edit the following properties: method, dns, dns-search, dns-options, dns-priority, addresses, gateway, routes, route-metric, route-table, routing-rules, ignore-auto-routes, ignore-auto-dns, dhcp-client-id, dhcp-timeout, dhcp-send-hostname, dhcp-hostname, dhcp-fqdn, never-default, may-fail, dad-timeout\nnmcli ipv4&gt;\n\nnmcli ipv4&gt; print\n['ipv4' setting values]\nipv4.method: manual\nipv4.dns: --\nipv4.dns-search: --\nipv4.dns-options: --\nipv4.dns-priority: 0\nipv4.addresses: 10.10.10.1/26\nipv4.gateway: 10.10.10.129\nipv4.routes: --\nipv4.route-metric: -1\nipv4.route-table: 0 (unspec)\nipv4.routing-rules: --\nipv4.ignore-auto-routes: no\nipv4.ignore-auto-dns: no\nipv4.dhcp-client-id: --\nipv4.dhcp-timeout: 0 (default)\nipv4.dhcp-send-hostname: yes\nipv4.dhcp-hostname: --\nipv4.dhcp-fqdn: --\nipv4.never-default: no\nipv4.may-fail: yes\nipv4.dad-timeout: -1 (default)\nnmcli ipv4&gt;\n\n\nnmcli ipv4&gt; set routes 192.168.122.0/24 10.10.10.1\n\nnmcli ipv4&gt; verify\nVerify setting 'ipv4': OK\nnmcli ipv4&gt; save\nnmcli ipv4&gt; quit\n\n#nmcli con up &quot;System eth0&quot;\n</code></pre>\n<p>And it should create file /etc/sysconfig/network-scripts/routes- with proper parameters, e.g.</p>\n<pre><code>ADDRESS0=192.0.2.0\nNETMASK0=255.255.255.0\nGATEWAY0=198.51.100.1\n</code></pre>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26976/" ]
I've just performed a new installation of the very latest (Fall, 2008) version of Fedora 9 Linux and am perplexed that it never set the default route properly and that even traveling the labyrinthine ways of this OS, there's no obvious way. Of course, it's clear that one can do it on a one-off basis like this: ``` route add default gw gw1 metric 0 eth0 ``` or like this: ``` ip route add to default via 192.168.2.1 protocol static ``` However, neither of these survives reboot. In reading through /etc/rc.d/init.d/network, it attempts to find data from a file in /etc/sysconfig/static-routes, but that file never existed. So, I tried to create it and populate it with data. The trouble with that is that the script places a dash (minus sign) in an odd spot that I'm not sure how to deal with. Of course, one can just edit /etc/rc.d/init.d/network, but that would be non-standard. As it is, my only other recourse seems to be editing rc.local, but that doesn't come early enough in the boot sequence to be there for things like, for example, the network time daemon. I've done my homework - I've read all the man pages, info entries, tried apropos, and I've even done a fair bit of web searching, all to no avail - my next step, sans answer here, will be to sign up to the Fedora mailing lists and ask there! Or, give up and edit the scripts. So, how is one supposed to do this?
The gateway is normally set in /etc/sysconfig/network-scripts/ifcfg-eth0, not in /etc/sysconfig/network. For example, on my current machine: > > /etc/sysconfig/network > > > ``` NETWORKING=yes NETWORKING_IPV6=no HOSTNAME=flyboys NISDOMAIN=ekcineon ``` > > /etc/sysconfig/network-scripts/ifcfg-eth0 > > > ``` DEVICE=eth0 ONBOOT=yes HWADDR=00:1d:09:31:3a:cc NETMASK=255.255.255.0 IPADDR=150.102.65.30 GATEWAY=150.102.65.252 TYPE=Ethernet ``` Note that I set HWADDR because I have two ethernet cards and I want to make sure the right one is assigned to eth0. The configuration for the second card is in /etc/sysconfig/network-scripts/ifcfg-eth1
198,870
<p>I'm using the GGeoXml object to overlay KML on an embedded Google Map. I need to customize the popup balloon for placemarks, so I'm trying to use the <a href="http://code.google.com/apis/kml/documentation/kmlreference.html#balloonstyle" rel="nofollow noreferrer"><code>&lt;BalloonStyle&gt;</code></a> element:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;Document xmlns="http://earth.google.com/kml/2.0"&gt; &lt;name&gt;Concessions&lt;/name&gt; &lt;Style id="masterPolyStyle"&gt; ... &lt;BalloonStyle&gt; &lt;text&gt; &lt;![CDATA[ &lt;h6&gt;Concession&lt;/h6&gt; &lt;h4&gt;$[name]&lt;/h4&gt; &lt;p&gt;$[description]&lt;/p&gt; ]]&gt; &lt;/text&gt; &lt;displayMode&gt;default&lt;/displayMode&gt; &lt;bgColor&gt;DDA39B81&lt;/bgColor&gt; &lt;/BalloonStyle&gt; &lt;/Style&gt; ... &lt;/Document&gt; </code></pre> <p>This works as expected in Google Earth, but the embedded map API appears to ignore this altogether. I suppose I could just leave out the <code>&lt;name&gt;</code> element altogether and just put everything in HTML inside the <code>&lt;description&gt;</code> element, but I'd like to be able to take advantage of the <a href="http://code.google.com/apis/kml/documentation/kmlreference.html#extendeddata" rel="nofollow noreferrer"><code>&lt;ExtendedData&gt;</code></a> element to display custom data in a structured way. </p>
[ { "answer_id": 329240, "author": "Stepan Mazurov", "author_id": 40786, "author_profile": "https://Stackoverflow.com/users/40786", "pm_score": 2, "selected": true, "text": "<p>No, like you have mentioned, html in the description is the only way I know that you can control the style of balloons through kml/georss feed. </p>\n" }, { "answer_id": 787553, "author": "commonpike", "author_id": 95733, "author_profile": "https://Stackoverflow.com/users/95733", "pm_score": 2, "selected": false, "text": "<p>This is now documented here (2009/04):</p>\n\n<p><a href=\"http://code.google.com/apis/kml/documentation/kmlelementsinmaps.html\" rel=\"nofollow noreferrer\">http://code.google.com/apis/kml/documentation/kmlelementsinmaps.html</a></p>\n\n<ul>\n<li>&lt; BalloonStyle > no</li>\n</ul>\n\n<p>(When did you ask this ? This forum/service needs a big fat DATE on each question, with a year in it :-) )</p>\n\n<p>2$c,\n*pike</p>\n" }, { "answer_id": 3483703, "author": "Tom", "author_id": 420423, "author_profile": "https://Stackoverflow.com/users/420423", "pm_score": 1, "selected": false, "text": "<p>Actually, the document referenced above (<a href=\"http://code.google.com/apis/kml/documentation/kmlelementsinmaps.html\" rel=\"nofollow noreferrer\">http://code.google.com/apis/kml/documentation/kmlelementsinmaps.html</a>) must have changed, b/c now it says:</p>\n\n<blockquote>\n <p>&lt;BalloonStyle&gt; partially only &lt;text&gt;\n is supported</p>\n</blockquote>\n\n<p>My problem is that the &lt;text&gt; seems to work for one KML file, but not another. The one that works for has polygon placemarkers, the other has points represented by icons - I wonder if that is why...</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
I'm using the GGeoXml object to overlay KML on an embedded Google Map. I need to customize the popup balloon for placemarks, so I'm trying to use the [`<BalloonStyle>`](http://code.google.com/apis/kml/documentation/kmlreference.html#balloonstyle) element: ``` <?xml version="1.0" encoding="utf-8"?> <Document xmlns="http://earth.google.com/kml/2.0"> <name>Concessions</name> <Style id="masterPolyStyle"> ... <BalloonStyle> <text> <![CDATA[ <h6>Concession</h6> <h4>$[name]</h4> <p>$[description]</p> ]]> </text> <displayMode>default</displayMode> <bgColor>DDA39B81</bgColor> </BalloonStyle> </Style> ... </Document> ``` This works as expected in Google Earth, but the embedded map API appears to ignore this altogether. I suppose I could just leave out the `<name>` element altogether and just put everything in HTML inside the `<description>` element, but I'd like to be able to take advantage of the [`<ExtendedData>`](http://code.google.com/apis/kml/documentation/kmlreference.html#extendeddata) element to display custom data in a structured way.
No, like you have mentioned, html in the description is the only way I know that you can control the style of balloons through kml/georss feed.
198,892
<p>I have an img tag in my webapp that uses the onload handler to resize the image:</p> <pre><code>&lt;img onLoad="SizeImage(this);" src="foo" &gt; </code></pre> <p>This works fine in Firefox 3, but fails in IE7 because the image object being passed to the <code>SizeImage()</code> function has a width and height of 0 for some reason -- maybe IE calls the function before it finishes loading?. In researching this, I have discovered that other people have had this same problem with IE. I have also discovered that this isn't valid HTML 4. This is our doctype, so I don't know if it's valid or not:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; </code></pre> <p>Is there a reasonable solution for resizing an image as it is loaded, preferably one that is standards-compliant? The image is being used for the user to upload a photo of themselves, which can be nearly any size, and we want to display it at a maximum of 150x150. If your solution is to resize the image server-side on upload, I know that is the correct solution, but I am forbidden from implementing it :( It must be done client side, and it must be done on display.</p> <p>Thanks.</p> <p><strong>Edit</strong>: Due to the structure of our app, it is impractical (bordering on impossible) to run this script in the document's onload. I can only reasonably edit the image tag and the code near it (for instance I could add a <code>&lt;script&gt;</code> right below it). Also, we already have Prototype and EXT JS libraries... management would prefer to not have to add another (some answers have suggested jQuery). If this can be solved using those frameworks, that would be great.</p> <p><strong>Edit 2</strong>: Unfortunately, we must support Firefox 3, IE 6 and IE 7. It is desirable to support all Webkit-based browsers as well, but as our site doesn't currently support them, we can tolerate solutions that only work in the Big 3.</p>
[ { "answer_id": 198903, "author": "Steve Paulo", "author_id": 9414, "author_profile": "https://Stackoverflow.com/users/9414", "pm_score": 4, "selected": true, "text": "<p>IE7 is trying to resize the image before the DOM tree is fully rendered. You need to run it on document.onload... you'll just need to make sure your function can handle being passed a reference to the element that isn't \"this.\"</p>\n\n<p>Alternatively... and I hope this isn't a flameable offense... jQuery makes stuff like this really, really easy.</p>\n\n<p>EDIT in response to EDIT 1:</p>\n\n<p>You can put <code>document.onload(runFunction);</code> in any script tag, anywhere in the body. it will still wait until the document is loaded to run the function.</p>\n" }, { "answer_id": 198908, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 2, "selected": false, "text": "<p>The way I would do it is to use jQuery to do something like:</p>\n\n<pre><code>$(document).load(function(){\n // applies to all images, could be replaced \n //by img.resize to resize all images with class=\"resize\"\n $('img').each(function(){\n // sizing code here\n });\n});\n</code></pre>\n\n<p>But I'm no javascript expert ;)</p>\n" }, { "answer_id": 198934, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 3, "selected": false, "text": "<p>If you don't have to support IE 6, you can just use this CSS.</p>\n\n<pre><code>yourImageSelector {\n max-width: 150px;\n max-height: 150px;\n}\n</code></pre>\n" }, { "answer_id": 270070, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 1, "selected": false, "text": "<p>setTimeout() may be a workaround if you are really stuck. Just set it for 2 or 3 seconds - or after the page is expected to load. </p>\n\n<p>EDIT: You may want to have a look at <a href=\"http://www.jibbering.com/faq/faq_notes/closures.html#clMem\" rel=\"nofollow noreferrer\">this article</a> - all the way at the bottom about IE mem leaks...</p>\n" }, { "answer_id": 360563, "author": "Jeremy Wadhams", "author_id": 8995, "author_profile": "https://Stackoverflow.com/users/8995", "pm_score": 2, "selected": false, "text": "<p>I've noticed that Firefox and Safari both fire \"load\" events on new images no matter what, but IE 6&amp;7 only fire \"load\" if they actually have to get the image from the server -- they don't if the image is already in local cache. I played with two solutions:</p>\n\n<p>1) Give the image a unique http argument every time, that the web server ignores, like</p>\n\n<pre><code>&lt;img src=\"mypicture.jpg?keepfresh=12345\" /&gt;\n</code></pre>\n\n<p>This has the downside that it actually defeats caching, so you're wasting bandwidth. But it might solve the problem without having to screw with your JavaScript.</p>\n\n<p>2) In my app, the images that need load handlers are being inserted dynamically by JavaScript. Instead of just appending the image, then building a handler, I use this code, which is tested good in Safari, FF, and IE6 &amp; 7.</p>\n\n<pre><code>document.body.appendChild(newPicture);\nif(newPicture.complete){\n doStuff.apply(newPicture);\n}else{\n YAHOO.util.Event.addListener(newPicture, \"load\", doStuff);\n}\n</code></pre>\n\n<p>I'm using YUI (obviously) but you can attache the handler using whatever works in your framework. The function doStuff expects to run with <strong>this</strong> attached to the affected IMG element, that's why I call it in the <strong>.apply</strong> style, your mileage may vary. </p>\n" }, { "answer_id": 821729, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>Edit: Due to the structure of our app,\n it is impractical (bordering on\n impossible) to run this script in the\n document's onload.</p>\n</blockquote>\n\n<p>It is always possible to add handlers to <code>window.onload</code> (or any event really), even if other frameworks, library or code attaches handlers to that event.</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\nfunction addOnloadHandler(func) {\n if (window.onload) {\n var windowOnload = window.onload;\n window.onload = function(evt) {\n windowOnload(evt);\n func(evt);\n }\n } else {\n window.onload = function(evt) {\n func(evt);\n }\n }\n}\n\n// attach a handler to window.onload as you normally might\nwindow.onload = function() { alert('Watch'); };\n\n// demonstrate that you can now attach as many other handlers\n// to the onload event as you want\naddOnloadHandler(function() { alert('as'); });\naddOnloadHandler(function() { alert('window.onload'); });\naddOnloadHandler(function() { alert('runs'); });\naddOnloadHandler(function() { alert('as'); });\naddOnloadHandler(function() { alert('many'); });\naddOnloadHandler(function() { alert('handlers'); });\naddOnloadHandler(function() { alert('as'); });\naddOnloadHandler(function() { alert('you'); });\naddOnloadHandler(function() { alert('want.'); });\n&lt;/script&gt;\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/807878/javascript-that-executes-after-page-load/807997#807997\">This answer</a> has a slightly different version of my <code>addOnloadHandler()</code> code using <code>attachEvent</code>. But I discovered in testing that <code>attachEvent</code> doesn't seem to guarantee the handlers fire in the order you added them, which may be important. The function as presented guarantees handlers are fired in the order added.</p>\n\n<p>Note that I pass <code>evt</code> into the added event handlers. This is not strictly necessary and the code should work without it, but I work with a library that expects the event to be passed to the <code>onload</code> handler and that code fails unless I include it in my function.</p>\n" }, { "answer_id": 1580858, "author": "Maksym Klymyshyn", "author_id": 186734, "author_profile": "https://Stackoverflow.com/users/186734", "pm_score": 2, "selected": false, "text": "<p>Code for jQuery. But it's easy to make dial with other frameworks. Really helpful.</p>\n\n<pre><code>var onload = function(){ /** your awesome onload method **/ };\nvar img = new Image();\nimg.src = 'test.png';\n\n// IE 7 workarond\nif($.browser.version.substr(0,1) == 7){\n function testImg(){\n if(img.complete != null && img.complete == true){ \n onload();\n return;\n }\n setTimeout(testImg, 1000);\n }\n setTimeout(testImg, 1000);\n}else{\n img.onload = onload\n}\n</code></pre>\n" }, { "answer_id": 11029706, "author": "Sebastien", "author_id": 809953, "author_profile": "https://Stackoverflow.com/users/809953", "pm_score": 0, "selected": false, "text": "<p>You can do something like : </p>\n\n<pre><code>var img = new Image();\nimg.src = '/output/preview_image.jpg' + '?' + Math.random();\nimg.onload = function() {\n alert('pass')\n}\n</code></pre>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10861/" ]
I have an img tag in my webapp that uses the onload handler to resize the image: ``` <img onLoad="SizeImage(this);" src="foo" > ``` This works fine in Firefox 3, but fails in IE7 because the image object being passed to the `SizeImage()` function has a width and height of 0 for some reason -- maybe IE calls the function before it finishes loading?. In researching this, I have discovered that other people have had this same problem with IE. I have also discovered that this isn't valid HTML 4. This is our doctype, so I don't know if it's valid or not: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> ``` Is there a reasonable solution for resizing an image as it is loaded, preferably one that is standards-compliant? The image is being used for the user to upload a photo of themselves, which can be nearly any size, and we want to display it at a maximum of 150x150. If your solution is to resize the image server-side on upload, I know that is the correct solution, but I am forbidden from implementing it :( It must be done client side, and it must be done on display. Thanks. **Edit**: Due to the structure of our app, it is impractical (bordering on impossible) to run this script in the document's onload. I can only reasonably edit the image tag and the code near it (for instance I could add a `<script>` right below it). Also, we already have Prototype and EXT JS libraries... management would prefer to not have to add another (some answers have suggested jQuery). If this can be solved using those frameworks, that would be great. **Edit 2**: Unfortunately, we must support Firefox 3, IE 6 and IE 7. It is desirable to support all Webkit-based browsers as well, but as our site doesn't currently support them, we can tolerate solutions that only work in the Big 3.
IE7 is trying to resize the image before the DOM tree is fully rendered. You need to run it on document.onload... you'll just need to make sure your function can handle being passed a reference to the element that isn't "this." Alternatively... and I hope this isn't a flameable offense... jQuery makes stuff like this really, really easy. EDIT in response to EDIT 1: You can put `document.onload(runFunction);` in any script tag, anywhere in the body. it will still wait until the document is loaded to run the function.
198,910
<p>I wrote a small WPF app where I like to prepend text into a RichTextBox, so that the newest stuff is on top. I wrote this, and it works: </p> <pre><code> /// &lt;summary&gt; /// Prepends the text to the rich textbox /// &lt;/summary&gt; /// &lt;param name="textoutput"&gt;The text representing the character information.&lt;/param&gt; private void PrependSimpleText(string textoutput) { Run run = new Run(textoutput); Paragraph paragraph = new Paragraph(run); if (this.RichTextBoxOutput.Document.Blocks.Count == 0) { this.RichTextBoxOutput.Document.Blocks.Add(paragraph); } else { this.RichTextBoxOutput.Document.Blocks.InsertBefore(this.RichTextBoxOutput.Document.Blocks.FirstBlock, paragraph); } } </code></pre> <p>Now I would like to make a new version of that function which can add small images as well. I'm at a loss though - is it possible to add images? </p>
[ { "answer_id": 199409, "author": "Jan Bannister", "author_id": 460845, "author_profile": "https://Stackoverflow.com/users/460845", "pm_score": 1, "selected": false, "text": "<p>RickTextbox.Document is a FlowDocument to which you can add almost anything that implements ContentElement. That includes Image, Label, StackPanel and all your other WPF favourites.</p>\n\n<p>Check out the <a href=\"http://msdn.microsoft.com/en-us/library/aa970909.aspx\" rel=\"nofollow noreferrer\">FlowDocument Overview</a> for more details.</p>\n" }, { "answer_id": 200185, "author": "rudigrobler", "author_id": 5147, "author_profile": "https://Stackoverflow.com/users/5147", "pm_score": 5, "selected": true, "text": "<p>Try the following:</p>\n\n<pre><code>BitmapImage bi = new BitmapImage(new Uri(@\"C:\\SimpleImage.jpg\"));\nImage image = new Image();\nimage.Source = bi;\nInlineUIContainer container = new InlineUIContainer(image); \nParagraph paragraph = new Paragraph(container); \nRichTextBoxOutput.Document.Blocks.Add(paragraph);\n</code></pre>\n\n<p>The InlineUIContainer is the \"magic\" here... You can add any UIElement to it. If you want to add multiple items, use a panel to wrap the items (ie. StackPanel, etc)</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5948/" ]
I wrote a small WPF app where I like to prepend text into a RichTextBox, so that the newest stuff is on top. I wrote this, and it works: ``` /// <summary> /// Prepends the text to the rich textbox /// </summary> /// <param name="textoutput">The text representing the character information.</param> private void PrependSimpleText(string textoutput) { Run run = new Run(textoutput); Paragraph paragraph = new Paragraph(run); if (this.RichTextBoxOutput.Document.Blocks.Count == 0) { this.RichTextBoxOutput.Document.Blocks.Add(paragraph); } else { this.RichTextBoxOutput.Document.Blocks.InsertBefore(this.RichTextBoxOutput.Document.Blocks.FirstBlock, paragraph); } } ``` Now I would like to make a new version of that function which can add small images as well. I'm at a loss though - is it possible to add images?
Try the following: ``` BitmapImage bi = new BitmapImage(new Uri(@"C:\SimpleImage.jpg")); Image image = new Image(); image.Source = bi; InlineUIContainer container = new InlineUIContainer(image); Paragraph paragraph = new Paragraph(container); RichTextBoxOutput.Document.Blocks.Add(paragraph); ``` The InlineUIContainer is the "magic" here... You can add any UIElement to it. If you want to add multiple items, use a panel to wrap the items (ie. StackPanel, etc)
198,928
<p>Brief:</p> <pre><code>convert ( -size 585x128 gradient: ) NewImage.png </code></pre> <p>How do I change the above ImageMagick command so it takes the width and height from an existing image? I need it to remain a one line command.</p> <hr> <p>Details:</p> <p>I'm trying to programatically create an image reflection using ImageMagick. The effect I am looking for is similar to what you would see when looking at an object on the edge of a pool of water. There is a pretty good thread on what I am trying to do <a href="http://www.imagemagick.org/discourse-server/viewtopic.php?f=1&amp;t=11585" rel="nofollow noreferrer">here</a> but the solution isn't exactly what I am looking for. Since I will be calling ImageMagick from a C#.Net application I want to use one call without any temp files and return the image through stdout. So far I have this...</p> <pre><code>convert OriginalImage.png ( OriginalImage.png -flip -blur 3x5 \ -crop 100%%x30%%+0+0 -negate -evaluate multiply 0.3 \ -negate ( -size 585x128 gradient: ) +matte -compose copy_opacity -composite ) -append NewImage.png </code></pre> <p>This works ok but doesn't give me the exact fade I am looking for. Instead of a nice solid fade from top to bottom it is giving me a fade from top left to bottom right. I added the (-negate -evaluate multiply 0.3 -negate) section in to lighten it up a bit more since I wasn't getting the fade I wanted. I also don't want to have to hard code in the size of the image when creating the gradient ( -size 585x128 gradient: ) I'm also going to want to keep the original image's transparency if possible.</p> <p>To go to stdout I plan on replacing "NewImage.png" with "-"</p>
[ { "answer_id": 205401, "author": "korro", "author_id": 22650, "author_profile": "https://Stackoverflow.com/users/22650", "pm_score": 1, "selected": false, "text": "<p>If you are calling it from C#, perhaps you could get retrieve the image dimensions in C#.\nThen call the ImageMagick command with</p>\n\n<pre><code>command = String.Format(\"convert bar %1x%2\",img.Width,img.Height)\n</code></pre>\n" }, { "answer_id": 301022, "author": "Sparr", "author_id": 13675, "author_profile": "https://Stackoverflow.com/users/13675", "pm_score": 0, "selected": false, "text": "<p>You should take the existing image as an input, and create the gradient yourself using -fx instead of using the gradient pseudo-format.</p>\n" }, { "answer_id": 2701367, "author": "hacketiwack", "author_id": 324533, "author_profile": "https://Stackoverflow.com/users/324533", "pm_score": -1, "selected": false, "text": "<p>May be this can help:\n<a href=\"http://www.alleluia.ch/systeme-dexploitation/commande/107-reflexion-sous-une-image\" rel=\"nofollow noreferrer\">Reflection under an image</a></p>\n\n<pre><code>#!/bin/sh\n\ngamma=$1\nsource=$2\ndestination=$3\nsize=`identify -format \"%wx%h\" $source`\n\nconvert $source \\\n \\( -size $size xc:none \\\n \\( \\( -flip $source -crop $size+0+0 \\) \\\n -size $size gradient: -gamma $gamma \\\n -compose copy_opacity -composite \\) \\\n -compose blend -composite \\) \\\n -append $destination\n</code></pre>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Brief: ``` convert ( -size 585x128 gradient: ) NewImage.png ``` How do I change the above ImageMagick command so it takes the width and height from an existing image? I need it to remain a one line command. --- Details: I'm trying to programatically create an image reflection using ImageMagick. The effect I am looking for is similar to what you would see when looking at an object on the edge of a pool of water. There is a pretty good thread on what I am trying to do [here](http://www.imagemagick.org/discourse-server/viewtopic.php?f=1&t=11585) but the solution isn't exactly what I am looking for. Since I will be calling ImageMagick from a C#.Net application I want to use one call without any temp files and return the image through stdout. So far I have this... ``` convert OriginalImage.png ( OriginalImage.png -flip -blur 3x5 \ -crop 100%%x30%%+0+0 -negate -evaluate multiply 0.3 \ -negate ( -size 585x128 gradient: ) +matte -compose copy_opacity -composite ) -append NewImage.png ``` This works ok but doesn't give me the exact fade I am looking for. Instead of a nice solid fade from top to bottom it is giving me a fade from top left to bottom right. I added the (-negate -evaluate multiply 0.3 -negate) section in to lighten it up a bit more since I wasn't getting the fade I wanted. I also don't want to have to hard code in the size of the image when creating the gradient ( -size 585x128 gradient: ) I'm also going to want to keep the original image's transparency if possible. To go to stdout I plan on replacing "NewImage.png" with "-"
If you are calling it from C#, perhaps you could get retrieve the image dimensions in C#. Then call the ImageMagick command with ``` command = String.Format("convert bar %1x%2",img.Width,img.Height) ```
198,936
<p>What is the right way to populate the model for the index page in a grails app? There is no IndexController by default, is there some other mechanism for getting lists of this and that into the model?</p>
[ { "answer_id": 198953, "author": "Robert Fischer", "author_id": 27561, "author_profile": "https://Stackoverflow.com/users/27561", "pm_score": 2, "selected": false, "text": "<p><strong>The good answer:</strong> If you need to populate a model for the index page, it's time to change from using a straight index.gsp to an index controller.</p>\n\n<p><strong>The evil answer:</strong> If you create a filter whose controller is '*', it'll get executed even for static pages.</p>\n" }, { "answer_id": 204537, "author": "Ed.T", "author_id": 3014, "author_profile": "https://Stackoverflow.com/users/3014", "pm_score": 6, "selected": true, "text": "<p>I won't claim that this is the right way, but it is one way to start things off. It doesn't take much to have a controller be the default. Add a mapping to UrlMappings.groovy:</p>\n\n<pre><code>class UrlMappings {\n static mappings = {\n \"/$controller/$action?/$id?\"{\n constraints {\n // apply constraints here\n }\n }\n \"500\"(view:'/error')\n \"/\"\n {\n controller = \"quote\"\n }\n }\n}\n</code></pre>\n\n<p>Then add an index action to the now default controller:</p>\n\n<pre><code>class QuoteController {\n\n def index = {\n ...\n }\n}\n</code></pre>\n\n<p>If what you want to load is already part of another action simply redirect:</p>\n\n<pre><code>def index = {\n redirect(action: random)\n}\n</code></pre>\n\n<p>Or to really get some reuse going, put the logic in a service:</p>\n\n<pre><code>class QuoteController {\n\n def quoteService\n\n def index = {\n redirect(action: random)\n }\n\n def random = {\n def randomQuote = quoteService.getRandomQuote()\n [ quote : randomQuote ]\n }\n}\n</code></pre>\n" }, { "answer_id": 1085014, "author": "William Pietri", "author_id": 123248, "author_profile": "https://Stackoverflow.com/users/123248", "pm_score": 4, "selected": false, "text": "<p>I couldn't get Ed T's example above to work. Perhaps Grails has changed since then?</p>\n\n<p>After some experimentation and some rummaging on the net, I ended up with this in <code>UrlMappings.groovy</code>:</p>\n\n<pre><code> \"/\"(controller: 'home', action: 'index')\n</code></pre>\n\n<p>My HomeController looks like this:</p>\n\n<pre><code>class HomeController {\n\n def index = {\n def quotes = = latest(Quote.list(), 5)\n [\"quotes\": quotes, \"totalQuotes\": Quote.count()]\n }\n\n}\n</code></pre>\n\n<p>And in <code>views/home</code>, I have an <code>index.gsp</code> file. That makes the <code>index.gsp</code> file in views unnecessary, so I removed it.</p>\n" }, { "answer_id": 4884485, "author": "alk", "author_id": 601267, "author_profile": "https://Stackoverflow.com/users/601267", "pm_score": 0, "selected": false, "text": "<p>In grails 1.3.6 for just adding</p>\n\n<p><code>\"/index.gsp\"(uri:\"/\")</code></p>\n\n<p>to UrlMappings.groovy worked fine for me. It has the same effect as adding a new controller and mappings like described before.</p>\n\n<p>Below is my complete UrlMappings.groovy:</p>\n\n<pre><code>class UrlMappings {\n\n static mappings = {\n \"/$controller/$action?/$id?\"{\n constraints {\n // apply constraints here\n }\n }\n\n \"/\"(view:\"/index\")\n \"500\"(view:'/error')\n\n \"/index.gsp\"(uri:\"/\")\n }\n}\n</code></pre>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2031/" ]
What is the right way to populate the model for the index page in a grails app? There is no IndexController by default, is there some other mechanism for getting lists of this and that into the model?
I won't claim that this is the right way, but it is one way to start things off. It doesn't take much to have a controller be the default. Add a mapping to UrlMappings.groovy: ``` class UrlMappings { static mappings = { "/$controller/$action?/$id?"{ constraints { // apply constraints here } } "500"(view:'/error') "/" { controller = "quote" } } } ``` Then add an index action to the now default controller: ``` class QuoteController { def index = { ... } } ``` If what you want to load is already part of another action simply redirect: ``` def index = { redirect(action: random) } ``` Or to really get some reuse going, put the logic in a service: ``` class QuoteController { def quoteService def index = { redirect(action: random) } def random = { def randomQuote = quoteService.getRandomQuote() [ quote : randomQuote ] } } ```
198,945
<p>How can you get a <strong>raw</strong> socket in Perl, and then what's the best way to built a packet for use with it?</p>
[ { "answer_id": 198954, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 3, "selected": false, "text": "<p>Perhaps searching <a href=\"http://search.cpan.org\" rel=\"nofollow noreferrer\">CPAN</a> might help? <a href=\"http://search.cpan.org/dist/IO\" rel=\"nofollow noreferrer\">IO::Socket</a> comes to mind.</p>\n" }, { "answer_id": 198973, "author": "edebill", "author_id": 27603, "author_profile": "https://Stackoverflow.com/users/27603", "pm_score": 1, "selected": false, "text": "<p>The basic call to get a socket is... socket(). It comes standard with perl 5. perl 5 basically gives you the standard socket(), bind(), listen(), accept() calls that traditional UNIX does.</p>\n\n<p>For a more object oriented model, check out IO::Socket.</p>\n" }, { "answer_id": 198995, "author": "oz10", "author_id": 14069, "author_profile": "https://Stackoverflow.com/users/14069", "pm_score": 3, "selected": false, "text": "<p>The same way you do in C... by setting the socket type when creating the socket. </p>\n\n<p>In the example on <a href=\"http://search.cpan.org/~rgarcia/perl-5.10.0/ext/Socket/Socket.pm\" rel=\"noreferrer\">CPAN</a> use <strong>SOCK_RAW</strong> rather than <strong>SOCK_DGRAM</strong> (UDP) or <strong>SOCK_STREAM</strong> (TCP).</p>\n\n<p>NOTE: creating raw sockets typically requires administrative privileges (i.e. root on UNIX). Windows OS's may have disabled ability to create raw sockets, you'll just have to test it and see. </p>\n" }, { "answer_id": 199031, "author": "raldi", "author_id": 7598, "author_profile": "https://Stackoverflow.com/users/7598", "pm_score": 3, "selected": true, "text": "<p>Looks like <a href=\"http://search.cpan.org/dist/Net-RawIP\" rel=\"nofollow noreferrer\">Net::RawIP</a> was what I was looking for:</p>\n\n<pre><code>use Net::RawIP;\n$a = new Net::RawIP;\n$a-&gt;set({ip =&gt; {saddr =&gt; 'my.target.lan',daddr =&gt; 'my.target.lan'},\n tcp =&gt; {source =&gt; 139,dest =&gt; 139,psh =&gt; 1, syn =&gt; 1}});\n$a-&gt;send;\n\n$a-&gt;ethnew(\"eth0\");\n$a-&gt;ethset(source =&gt; 'my.target.lan',dest =&gt;'my.target.lan'); \n$a-&gt;ethsend;\n\n$p = $a-&gt;pcapinit(\"eth0\",\"dst port 21\",1500,30);\n$f = dump_open($p,\"/my/home/log\");\nloop $p,10,\\&amp;dump,$f;\n</code></pre>\n" }, { "answer_id": 199194, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 2, "selected": false, "text": "<p>As austirg and others said, Socket will do this just fine:</p>\n\n<pre><code>use Socket;\n\nsocket my $socket, PF_INET, SOCK_RAW, 0 or die \"Couldn't create raw socket: $!\";\n\nsend $socket, $message, $flags, $to or die \"Couldn't send packet: $!\";\n\nmy $from = recv $socket, $message, $length, $flags or die \"Couldn't receive from socket: $!\";\n</code></pre>\n" }, { "answer_id": 199427, "author": "Liudvikas Bukys", "author_id": 5845, "author_profile": "https://Stackoverflow.com/users/5845", "pm_score": 3, "selected": false, "text": "<p>At first I was thinking that most previous answers were not responsive to the question.\nAfter further thought, I think the author is probably not asking the right question.</p>\n\n<p>If you're writing an application, you don't usually think of \"building packets\". you just open sockets, format up the data payload, and it's the protocol stack that builds packets with your data. OK, if you're using datagrams, you do need to define, generate and parse your payloads. But you typically let the kernel encapsulate it at the network level (e.g. add IP header) or link layer (e.g. add Ethernet framing). You usually don't use pcap. Sometimes just pack and unpack and maybe vec is enough.</p>\n\n<p>If you're writing an unusual packet processor such as an active hostile attack tool, a man-in-the-middle process, or a traffic shaping device, then would be more likely to be \"building packets\" and using pcap. Maybe Net::Packet is for you also.</p>\n" }, { "answer_id": 22368915, "author": "cnd", "author_id": 1233840, "author_profile": "https://Stackoverflow.com/users/1233840", "pm_score": 0, "selected": false, "text": "<p>Be aware that if you're trying to use raw sockets to send a pile of SYN packets, and you just \"use Socket;\" that's going to fill up your ARP tables and bomb out with \"No buffer space available\" and a stack of \"CLOSE_WAIT\" entries in \"netstat\" (which stops your machine doing any more connections of any kind until some of them free up).</p>\n\n<p>Or in other words - you do really need Net::RawIP - it makes a difference.</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
How can you get a **raw** socket in Perl, and then what's the best way to built a packet for use with it?
Looks like [Net::RawIP](http://search.cpan.org/dist/Net-RawIP) was what I was looking for: ``` use Net::RawIP; $a = new Net::RawIP; $a->set({ip => {saddr => 'my.target.lan',daddr => 'my.target.lan'}, tcp => {source => 139,dest => 139,psh => 1, syn => 1}}); $a->send; $a->ethnew("eth0"); $a->ethset(source => 'my.target.lan',dest =>'my.target.lan'); $a->ethsend; $p = $a->pcapinit("eth0","dst port 21",1500,30); $f = dump_open($p,"/my/home/log"); loop $p,10,\&dump,$f; ```
198,952
<p>I have two users Bob and Alice in Oracle, both created by running the following commands as sysdba from sqlplus:</p> <pre> create user $blah identified by $password; grant resource, connect, create view to $blah; </pre> <p>I want Bob to have complete access to Alice's schema (that is, all tables), but I'm not sure what grant to run, and whether to run it as sysdba or as Alice.</p> <p>Happy to hear about any good pointers to reference material as well -- don't seem to be able to get a good answer to this from either the Internet or "Oracle Database 10g The Complete Reference", which is sitting on my desk.</p>
[ { "answer_id": 198962, "author": "cagcowboy", "author_id": 19629, "author_profile": "https://Stackoverflow.com/users/19629", "pm_score": 5, "selected": true, "text": "<p>AFAIK you need to do the grants object one at a time.</p>\n\n<p>Typically you'd use a script to do this, something along the lines of:</p>\n\n<pre><code>SELECT 'GRANT ALL ON '||table_name||' TO BOB;'\nFROM ALL_TABLES\nWHERE OWNER = 'ALICE';\n</code></pre>\n\n<p>And similar for other db objects.</p>\n\n<p>You could put a package in each schema that you need to issue the grant from which will go through all call each GRANT statement via an EXECUTE IMMEDIATE.</p>\n\n<p>e.g.</p>\n\n<pre><code> PROCEDURE GRANT_TABLES\n IS\n BEGIN\n\n FOR tab IN (SELECT table_name\n FROM all_tables\n WHERE owner = this_user) LOOP\n EXECUTE IMMEDIATE 'GRANT SELECT, INSERT, UPDATE, DELETE ON '||tab.table_name||' TO other_user';\n END LOOP;\n END;\n</code></pre>\n" }, { "answer_id": 198985, "author": "Brett McCann", "author_id": 9293, "author_profile": "https://Stackoverflow.com/users/9293", "pm_score": 3, "selected": false, "text": "<p>There are many things to consider. When you say access, do you want to prefix the tables with the other users name? You can use public synonyms so that you can hide the original owner, if that is an issue. And then grant privs on the synonym.</p>\n\n<p>You also want to plan ahead as best you can. Later, will you want Frank to be able to access Alice's schema as well? You don't want to have to regrant privileges on N number of tables. Using a database role would be a better solution. Grant the select to role \"ALICE_TABLES\" for example and when another user needs access, just grant them privilege to the role. This helps to organize the grants you make inside the DB.</p>\n" }, { "answer_id": 2789143, "author": "arnep", "author_id": 217711, "author_profile": "https://Stackoverflow.com/users/217711", "pm_score": 3, "selected": false, "text": "<p>Another solution if you have different owner:</p>\n\n<pre><code>BEGIN\n\n FOR x IN (SELECT owner||'.'||table_name ownertab\n FROM all_tables\n WHERE owner IN ('A', 'B', 'C', 'D'))\n LOOP\n EXECUTE IMMEDIATE 'GRANT SELECT ON '||x.ownertab||' TO other_user';\n END LOOP;\nEND;\n</code></pre>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25915/" ]
I have two users Bob and Alice in Oracle, both created by running the following commands as sysdba from sqlplus: ``` create user $blah identified by $password; grant resource, connect, create view to $blah; ``` I want Bob to have complete access to Alice's schema (that is, all tables), but I'm not sure what grant to run, and whether to run it as sysdba or as Alice. Happy to hear about any good pointers to reference material as well -- don't seem to be able to get a good answer to this from either the Internet or "Oracle Database 10g The Complete Reference", which is sitting on my desk.
AFAIK you need to do the grants object one at a time. Typically you'd use a script to do this, something along the lines of: ``` SELECT 'GRANT ALL ON '||table_name||' TO BOB;' FROM ALL_TABLES WHERE OWNER = 'ALICE'; ``` And similar for other db objects. You could put a package in each schema that you need to issue the grant from which will go through all call each GRANT statement via an EXECUTE IMMEDIATE. e.g. ``` PROCEDURE GRANT_TABLES IS BEGIN FOR tab IN (SELECT table_name FROM all_tables WHERE owner = this_user) LOOP EXECUTE IMMEDIATE 'GRANT SELECT, INSERT, UPDATE, DELETE ON '||tab.table_name||' TO other_user'; END LOOP; END; ```
198,970
<p>I have a fairly simple const struct in some C code that simply holds a few pointers and would like to initialize it statically if possible. Can I and, if so, how?</p>
[ { "answer_id": 198980, "author": "Lev", "author_id": 7224, "author_profile": "https://Stackoverflow.com/users/7224", "pm_score": 5, "selected": true, "text": "<p>You can, if the pointers point to global objects:</p>\n\n<pre><code>// In global scope\nint x, y;\nconst struct {int *px, *py; } s = {&amp;x, &amp;y};\n</code></pre>\n" }, { "answer_id": 198983, "author": "AShelly", "author_id": 10396, "author_profile": "https://Stackoverflow.com/users/10396", "pm_score": 3, "selected": false, "text": "<pre><code>const struct mytype foo = {&amp;var1, &amp;var2};\n</code></pre>\n" }, { "answer_id": 202461, "author": "Frank Szczerba", "author_id": 8964, "author_profile": "https://Stackoverflow.com/users/8964", "pm_score": 2, "selected": false, "text": "<p>A const struct can <em>only</em> be initialized statically.</p>\n" }, { "answer_id": 3684193, "author": "ylzhang", "author_id": 416860, "author_profile": "https://Stackoverflow.com/users/416860", "pm_score": 0, "selected": false, "text": "<p>But if there is some <code>struct</code> as following:</p>\n\n<pre><code>struct Foo\n{\n const int a;\n int b;\n};\n</code></pre>\n\n<p>and we want to dynamically create the pointer to the <code>struct</code> using <code>malloc</code>, so can we play the trick:</p>\n\n<pre><code>struct Foo foo = { 10, 20 };\nchar *ptr = (char*)malloc(sizeof(struct Foo));\nmemcpy(ptr, &amp;foo, sizeof(foo));\nstruct Foo *pfoo = (struct Foo*)ptr;\n</code></pre>\n\n<p>this is very useful especially when some function needs to return pointer to <code>struct Foo</code></p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26551/" ]
I have a fairly simple const struct in some C code that simply holds a few pointers and would like to initialize it statically if possible. Can I and, if so, how?
You can, if the pointers point to global objects: ``` // In global scope int x, y; const struct {int *px, *py; } s = {&x, &y}; ```
198,974
<p>I have a validation control that has the following expression:</p> <pre><code>(?=(.*\\d.*){2,})(?=(.*\\w.*){2,})(?=(.*\\W.*){1,}).{8,} </code></pre> <p>That's a password with at least <strong>2 digits</strong>, <strong>2 alpha characters</strong>, <strong>1 non-alphanumeric</strong> and <strong>8 character minimum</strong>. Unfortunately this doesn't seem to be cross-browser compliant.</p> <p>This validation works perfectly in Firefox, but it does not in Internet Explorer.</p> <p><strong><em>A combination of each of your answers results in:</em></strong></p> <pre><code>var format = "^(?=.{" + minLength + ",})" + (minAlpha &gt; 0 ? "(?=(.*[A-Za-z].*){" + minAlpha + ",})" : "") + (minNum &gt; 0 ? "(?=(.*[0-9].*){" + minNum + ",})" : "") + (minNonAlpha &gt; 0 ? "(?=(.*\\W.*){" + minNonAlpha + ",})" : "") + ".*$"; EX: "^(?=.{x,})(?=(.*[A-Za-z].*){y,})(?=(.*[0-9].*){z,})(?=(.*\W.*){a,}).*$" </code></pre> <p>The important piece is having the (?.{x,}) for the length <strong>first</strong>.</p>
[ { "answer_id": 198981, "author": "David Laing", "author_id": 13238, "author_profile": "https://Stackoverflow.com/users/13238", "pm_score": -1, "selected": false, "text": "<p>How about one of the existing jQuery based password strength validators - like:\n<a href=\"http://scripts.simplythebest.net/4/Ajax-Password-Strength-Meter-software.html\" rel=\"nofollow noreferrer\">http://scripts.simplythebest.net/4/Ajax-Password-Strength-Meter-software.html</a></p>\n" }, { "answer_id": 199085, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 5, "selected": true, "text": "<p><code>(?=(.*\\W.*){0,})</code> is not 0 non-alphanumeric characters. It is <em>at least 0</em> non-alphanumeric characters. If you wanted the password to not contain any non-alphanumeric characters you could do either <code>(?!.*\\W)</code> or <code>(?=\\w*$)</code>.</p>\n\n<p>A simpler solution would be to skip the <code>\\W</code> look-ahead, and use <code>\\w{8,}</code> instead of <code>.{8,}</code>.</p>\n\n<p>Also, <code>\\w</code> includes <code>\\d</code>. If you wanted just the alpha you could do either <code>[^\\W\\d]</code> or <code>[A-Za-z]</code>.</p>\n\n<pre><code>/^(?=(?:.*?\\d){2})(?=(?:.*?[A-Za-z]){2})\\w{8,}$/\n</code></pre>\n\n<p>This would validate the password to contain at least <strong>two digits</strong>, <strong>two alphas</strong>, be <strong>at least 8 characters long</strong>, and contain <strong>only alpha-numeric characters</strong> (including underscore).</p>\n\n<ul>\n<li><code>\\w</code> = <code>[A-Za-z0-9_]</code></li>\n<li><code>\\d</code> = <code>[0-9]</code></li>\n<li><code>\\s</code> = <code>[ \\t\\n\\r\\f\\v]</code></li>\n</ul>\n\n<p><strong>Edit:</strong>\nTo use this in all browsers you probably need to do something like this:</p>\n\n<pre><code>var re = new RegExp(\"^(?=(?:.*?\\\\d){2})(?=(?:.*?[A-Za-z]){2})\\\\w{8,}$\");\nif (re.test(password)) { /* ok */ }\n</code></pre>\n\n<p><strong>Edit2:</strong> The recent update in the question almost invalidates my whole answer. <code>^^;;</code></p>\n\n<p>You should still be able to use the JavaScript code in the end, if you replace the pattern with what you had originally.</p>\n\n<p><strong>Edit3:</strong> OK. Now I see what you mean.</p>\n\n<pre><code>/^(?=.*[a-z].*[a-z])(?=.*[0-9].*[0-9]).{3,}/.test(\"password123\") // matches\n/^(?=.*[a-z].*[a-z])(?=.*[0-9].*[0-9]).{4,}/.test(\"password123\") // does not match\n/^(?=.*[a-z].*[a-z]).{4,}/.test(\"password123\") // matches\n</code></pre>\n\n<p>It seems <code>(?= )</code> isn't really zero-width in Internet Explorer.</p>\n\n<p><a href=\"http://development.thatoneplace.net/2008/05/bug-discovered-in-internet-explorer-7.html\" rel=\"noreferrer\">http://development.thatoneplace.net/2008/05/bug-discovered-in-internet-explorer-7.html</a></p>\n\n<p><strong>Edit4:</strong> More reading: <a href=\"http://blog.stevenlevithan.com/archives/regex-lookahead-bug\" rel=\"noreferrer\">http://blog.stevenlevithan.com/archives/regex-lookahead-bug</a></p>\n\n<p>I think this can solve your problem:</p>\n\n<pre><code>/^(?=.{8,}$)(?=(?:.*?\\d){2})(?=(?:.*?[A-Za-z]){2})(?=(?:.*?\\W){1})/\nnew RegExp(\"^(?=.{8,}$)(?=(?:.*?\\\\d){2})(?=(?:.*?[A-Za-z]){2})(?=(?:.*?\\\\W){1})\")\n</code></pre>\n\n<p>The <code>(?=.{8,}$)</code> needs to come first.</p>\n" }, { "answer_id": 199090, "author": "sontek", "author_id": 17176, "author_profile": "https://Stackoverflow.com/users/17176", "pm_score": 1, "selected": false, "text": "<p>This will get you 2 min digits, 2 min characters, and min 8 character length... I refuse to show you how to not allow users to have non-alphanumeric characters in their passwords, why do sites want to enforce less secure passwords?</p>\n\n<pre><code>^(?=.*\\d{2})(?=.*[a-zA-Z]{2}).{8,}$\n</code></pre>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19753/" ]
I have a validation control that has the following expression: ``` (?=(.*\\d.*){2,})(?=(.*\\w.*){2,})(?=(.*\\W.*){1,}).{8,} ``` That's a password with at least **2 digits**, **2 alpha characters**, **1 non-alphanumeric** and **8 character minimum**. Unfortunately this doesn't seem to be cross-browser compliant. This validation works perfectly in Firefox, but it does not in Internet Explorer. ***A combination of each of your answers results in:*** ``` var format = "^(?=.{" + minLength + ",})" + (minAlpha > 0 ? "(?=(.*[A-Za-z].*){" + minAlpha + ",})" : "") + (minNum > 0 ? "(?=(.*[0-9].*){" + minNum + ",})" : "") + (minNonAlpha > 0 ? "(?=(.*\\W.*){" + minNonAlpha + ",})" : "") + ".*$"; EX: "^(?=.{x,})(?=(.*[A-Za-z].*){y,})(?=(.*[0-9].*){z,})(?=(.*\W.*){a,}).*$" ``` The important piece is having the (?.{x,}) for the length **first**.
`(?=(.*\W.*){0,})` is not 0 non-alphanumeric characters. It is *at least 0* non-alphanumeric characters. If you wanted the password to not contain any non-alphanumeric characters you could do either `(?!.*\W)` or `(?=\w*$)`. A simpler solution would be to skip the `\W` look-ahead, and use `\w{8,}` instead of `.{8,}`. Also, `\w` includes `\d`. If you wanted just the alpha you could do either `[^\W\d]` or `[A-Za-z]`. ``` /^(?=(?:.*?\d){2})(?=(?:.*?[A-Za-z]){2})\w{8,}$/ ``` This would validate the password to contain at least **two digits**, **two alphas**, be **at least 8 characters long**, and contain **only alpha-numeric characters** (including underscore). * `\w` = `[A-Za-z0-9_]` * `\d` = `[0-9]` * `\s` = `[ \t\n\r\f\v]` **Edit:** To use this in all browsers you probably need to do something like this: ``` var re = new RegExp("^(?=(?:.*?\\d){2})(?=(?:.*?[A-Za-z]){2})\\w{8,}$"); if (re.test(password)) { /* ok */ } ``` **Edit2:** The recent update in the question almost invalidates my whole answer. `^^;;` You should still be able to use the JavaScript code in the end, if you replace the pattern with what you had originally. **Edit3:** OK. Now I see what you mean. ``` /^(?=.*[a-z].*[a-z])(?=.*[0-9].*[0-9]).{3,}/.test("password123") // matches /^(?=.*[a-z].*[a-z])(?=.*[0-9].*[0-9]).{4,}/.test("password123") // does not match /^(?=.*[a-z].*[a-z]).{4,}/.test("password123") // matches ``` It seems `(?= )` isn't really zero-width in Internet Explorer. <http://development.thatoneplace.net/2008/05/bug-discovered-in-internet-explorer-7.html> **Edit4:** More reading: <http://blog.stevenlevithan.com/archives/regex-lookahead-bug> I think this can solve your problem: ``` /^(?=.{8,}$)(?=(?:.*?\d){2})(?=(?:.*?[A-Za-z]){2})(?=(?:.*?\W){1})/ new RegExp("^(?=.{8,}$)(?=(?:.*?\\d){2})(?=(?:.*?[A-Za-z]){2})(?=(?:.*?\\W){1})") ``` The `(?=.{8,}$)` needs to come first.
198,975
<p>I am tring to get the <a href="http://www.herrodius.com/blog/85" rel="nofollow noreferrer">ASDoc Ant task</a> to work:</p> <pre><code>&lt;target name="asdoc" depends="compile"&gt; &lt;mkdir dir="${dist_asdocs}"/&gt; &lt;asdoc docSources="${srcdir}" output="${dist_asdocs}" executable="${FLEX_HOME}/bin/asdoc.exe" /&gt; &lt;/target&gt; </code></pre> <p>When I run it I get errors from ASDoc like "Error: Type was not found or was not a compile-time constant: XXX". When I run ASDoc manually I do: "asdoc -source-path src -doc-sources src". If I omit the -source-path value I get the same errors... so how am I supposed to get the Ant task to work?</p>
[ { "answer_id": 199586, "author": "Simon Lehmann", "author_id": 27011, "author_profile": "https://Stackoverflow.com/users/27011", "pm_score": 2, "selected": false, "text": "<p>Well, I can't test it because it is implemented for Windows only (tries to execute asdoc.exe).</p>\n\n<p>But I have written my own solution for the lack of an ant task for asdoc:</p>\n\n<pre><code>&lt;exec executable=\"${FLEX_HOME}/bin/asdoc\" dir=\"${basedir}\"&gt;\n &lt;arg value=\"-source-path\"/&gt;\n &lt;arg path=\"${basedir}/src\"/&gt;\n\n &lt;arg value=\"-doc-sources\"/&gt;\n &lt;arg path=\"${basedir}/src\"/&gt;\n\n &lt;arg value=\"-output\"/&gt;\n &lt;arg path=\"${DOC_DIR}\"/&gt;\n\n &lt;arg value=\"-main-title\"/&gt;\n &lt;arg path=\"${ant.project.name} Documentation\"/&gt;\n\n &lt;arg line=\"-library-path+=${basedir}/libs\"/&gt;\n&lt;/exec&gt;\n</code></pre>\n\n<p>Of course, you have to change the executable to asdoc.exe if you are on windows. I don't know if you also have to replace all / with \\ or if ant does this for you. The last can be omitted if you don't use any .swcs which aren't already on the library-path. Or at least you have to change it to point to the right directory.</p>\n\n<p><strong>Edit:</strong> I have looked at the <a href=\"http://prana.svn.sourceforge.net/viewvc/prana/trunk/ant/src/org/pranaframework/ant/Asdoc.java?view=markup\" rel=\"nofollow noreferrer\">source code of the asdoc-task</a> and it is essentially the same I do with my exec-task, it just only allows a small subset of command line arguments.</p>\n\n<p>I also have tested my solution without the source-path argument and to my surprise it <em>still</em> worked. I did some further testing and this is what I found out:</p>\n\n<p>When no source-path is specified, asdoc(.exe) assumes <code>src</code> as a default. Thus the asdoc-task usually works if you use that convention (e.g. Flex Builder does this), but fails if you don't.</p>\n\n<p>So to use the asdoc-task you have to name your source directory <code>src</code>.</p>\n" }, { "answer_id": 537651, "author": "Christophe Herreman", "author_id": 17255, "author_profile": "https://Stackoverflow.com/users/17255", "pm_score": 1, "selected": false, "text": "<p>I would suggest not using the asdoc ant task since I haven't developed it further since I first released it. As mentioned by Simon, it only supports a small subset of what is possible so you're most likely better off using the exec task.</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13220/" ]
I am tring to get the [ASDoc Ant task](http://www.herrodius.com/blog/85) to work: ``` <target name="asdoc" depends="compile"> <mkdir dir="${dist_asdocs}"/> <asdoc docSources="${srcdir}" output="${dist_asdocs}" executable="${FLEX_HOME}/bin/asdoc.exe" /> </target> ``` When I run it I get errors from ASDoc like "Error: Type was not found or was not a compile-time constant: XXX". When I run ASDoc manually I do: "asdoc -source-path src -doc-sources src". If I omit the -source-path value I get the same errors... so how am I supposed to get the Ant task to work?
Well, I can't test it because it is implemented for Windows only (tries to execute asdoc.exe). But I have written my own solution for the lack of an ant task for asdoc: ``` <exec executable="${FLEX_HOME}/bin/asdoc" dir="${basedir}"> <arg value="-source-path"/> <arg path="${basedir}/src"/> <arg value="-doc-sources"/> <arg path="${basedir}/src"/> <arg value="-output"/> <arg path="${DOC_DIR}"/> <arg value="-main-title"/> <arg path="${ant.project.name} Documentation"/> <arg line="-library-path+=${basedir}/libs"/> </exec> ``` Of course, you have to change the executable to asdoc.exe if you are on windows. I don't know if you also have to replace all / with \ or if ant does this for you. The last can be omitted if you don't use any .swcs which aren't already on the library-path. Or at least you have to change it to point to the right directory. **Edit:** I have looked at the [source code of the asdoc-task](http://prana.svn.sourceforge.net/viewvc/prana/trunk/ant/src/org/pranaframework/ant/Asdoc.java?view=markup) and it is essentially the same I do with my exec-task, it just only allows a small subset of command line arguments. I also have tested my solution without the source-path argument and to my surprise it *still* worked. I did some further testing and this is what I found out: When no source-path is specified, asdoc(.exe) assumes `src` as a default. Thus the asdoc-task usually works if you use that convention (e.g. Flex Builder does this), but fails if you don't. So to use the asdoc-task you have to name your source directory `src`.
198,979
<p>I'm using Visual Studio 2008 Team System with SP1, and I've noticed an annoying tendency for the IDE to hang for several (10-15) seconds whenever I stop debugging an application. At first I thought this only happened with WPF apps, but I've observed the behavior in Windows Forms apps and ASP.NET sites as well. I've made a series of changes to the Options based on <a href="https://stackoverflow.com/questions/8440/visual-studio-optimizations">this previous post</a> and done exhaustive Google/MSDN searches, but still haven't found a way to stop this. </p> <p>Anyone have any ideas?</p> <hr> <p>@<a href="https://stackoverflow.com/users/25731/korona">korona</a> - Nope, that didn't fix it. Thanks for your suggestion, though.</p> <p>More research in ProcMon shows this interesting tidbit, not sure if it is related:</p> <pre><code>8:45:46.6790857 AM WindowsFormsApplication1.vshost.exe 7684 FASTIO_CHECK_IF_POSSIBLE C:\WINXP\Microsoft.NET\Framework\v2.0.50727\CONFIG\enterprisesec.config.cch FAST IO DISALLOWED Operation: Read, Offset: 48, Length: 12 8:45:46.6793569 AM WindowsFormsApplication1.vshost.exe 7684 ReadFile C:\WINXP\Microsoft.NET\Framework\v2.0.50727\CONFIG\enterprisesec.config.cch FAST IO DISALLOWED Offset: 508, Length: 12 </code></pre> <p>This repeats several times, like hundreds of times, then it switches to a different path:</p> <pre><code>8:45:46.7470314 AM WindowsFormsApplication1.vshost.exe 7684 FASTIO_CHECK_IF_POSSIBLE D:\documents and settings\myusername\Application Data\Microsoft\CLR Security Config\v2.0.50727.42\security.config.cch FAST IO DISALLOWED Operation: Read, Offset: 48, Length: 12 8:45:46.7472187 AM WindowsFormsApplication1.vshost.exe 7684 ReadFile D:\documents and settings\myusername\Application Data\Microsoft\CLR Security Config\v2.0.50727.42\security.config.cch FAST IO DISALLOWED Offset: 508, Length: 12 </code></pre> <p>And repeats again many more times, with slight changes in the offset each iteration. Maybe unrelated, but....</p>
[ { "answer_id": 199033, "author": "Joel", "author_id": 13713, "author_profile": "https://Stackoverflow.com/users/13713", "pm_score": 0, "selected": false, "text": "<p>Does it hangover even with basic apps? Like making a new windows form then hitting debug, or is it only with more complicated apps? Because I've noticed that before too (maybe not quite 10-15 seconds, but there has been a bit of a lag that I've noticed) but when I just tried debugging a relatively simple windows form app, I didn't get it at all.</p>\n" }, { "answer_id": 199062, "author": "AJ.", "author_id": 27457, "author_profile": "https://Stackoverflow.com/users/27457", "pm_score": 0, "selected": false, "text": "<p>Good question. I created a very simple Windows Forms app: </p>\n\n<pre><code>private void button1_Click(object sender, EventArgs e)\n{\n MessageBox.Show(\"I am saying hello.\");\n}\n</code></pre>\n\n<p>Still hangs a good 10 seconds on closing the form. </p>\n" }, { "answer_id": 200864, "author": "Pierre Arnaud", "author_id": 4597, "author_profile": "https://Stackoverflow.com/users/4597", "pm_score": 2, "selected": false, "text": "<p>I observed this kind of behaviour on one of my development machines and Visual Studio 2005. The problem was caused by Visual Studio trying to reach some non existent network share (I don't remember exactly why). You could give <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx\" rel=\"nofollow noreferrer\">Process Monitor</a> a try in order to see if your Visual Studio is trying to do something silly when finishing debugging and returning to the normal view. Maybe because you have some broken plug-in in some tool bar or in your toolbox.</p>\n" }, { "answer_id": 201259, "author": "AJ.", "author_id": 27457, "author_profile": "https://Stackoverflow.com/users/27457", "pm_score": 0, "selected": false, "text": "<p>@<a href=\"https://stackoverflow.com/users/4597/pierre\">Pierre</a> - I ran ProcMon on devenv.exe and timed the application close. The results are interesting. It hung for 15 seconds, and you can see the hang in ProcMon. From 8:45:31 to 8:45:46, there isn't any activity recorded. I'm going to mess around with the filter in ProcMon and see if it's something outside of devenv.exe, but here's what I recorded from devenv.exe around the 15 second span:</p>\n\n<pre><code>8:45:31.0221244 AM devenv.exe 7096 QueryNameInformationFile D:\\Working\\WindowsFormsApplication1\\WindowsFormsApplication1\\bin\\Debug\\WindowsFormsApplication1.vshost.exe BUFFER OVERFLOW Name: \\W\n8:45:31.0227991 AM devenv.exe 7096 CreateFile D:\\Working\\WindowsFormsApplication1\\WindowsFormsApplication1\\bin\\Debug\\WindowsFormsApplication1.vshost.exe.Manifest NAME NOT FOUND Desired Access: Generic Read/Execute, Disposition: Open, Options: Synchronous IO Non-Alert, Non-Directory File, Attributes: n/a, ShareMode: Read, AllocationSize: n/a\n8:45:46.7647624 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\CLSID\\{141243A4-76E6-4FC3-A114-EAE02389304E} NAME NOT FOUND Desired Access: Read\n8:45:46.7647792 AM devenv.exe 7096 RegOpenKey HKCR\\CLSID\\{141243A4-76E6-4FC3-A114-EAE02389304E} NAME NOT FOUND Desired Access: Read\n8:45:46.7649139 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\CLSID\\{141243A4-76E6-4FC3-A114-EAE02389304E} NAME NOT FOUND Desired Access: Read\n8:45:46.7649264 AM devenv.exe 7096 RegOpenKey HKCR\\CLSID\\{141243A4-76E6-4FC3-A114-EAE02389304E} NAME NOT FOUND Desired Access: Read\n8:45:46.9834610 AM devenv.exe 7096 RegQueryValue HKCU\\Software\\Microsoft\\VisualStudio\\9.0\\UseMRUDocOrdering NAME NOT FOUND Length: 144\n8:45:46.9835087 AM devenv.exe 7096 RegQueryValue HKLM\\SOFTWARE\\Microsoft\\VisualStudio\\9.0\\UseMRUDocOrdering NAME NOT FOUND Length: 144\n8:45:46.9865681 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\ReSharper.ReSharper_MoveLeft NAME NOT FOUND Desired Access: Read\n8:45:46.9865881 AM devenv.exe 7096 RegOpenKey HKCR\\ReSharper.ReSharper_MoveLeft NAME NOT FOUND Desired Access: Read\n8:45:46.9866155 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\ReSharper.ReSharper_MoveLeft NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9866285 AM devenv.exe 7096 RegOpenKey HKCR\\ReSharper.ReSharper_MoveLeft NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9869661 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\ReSharper.ReSharper_MoveRight NAME NOT FOUND Desired Access: Read\n8:45:46.9869813 AM devenv.exe 7096 RegOpenKey HKCR\\ReSharper.ReSharper_MoveRight NAME NOT FOUND Desired Access: Read\n8:45:46.9870055 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\ReSharper.ReSharper_MoveRight NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9870177 AM devenv.exe 7096 RegOpenKey HKCR\\ReSharper.ReSharper_MoveRight NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9872667 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\ReSharper.ReSharper_MoveUp NAME NOT FOUND Desired Access: Read\n8:45:46.9872818 AM devenv.exe 7096 RegOpenKey HKCR\\ReSharper.ReSharper_MoveUp NAME NOT FOUND Desired Access: Read\n8:45:46.9873078 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\ReSharper.ReSharper_MoveUp NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9873207 AM devenv.exe 7096 RegOpenKey HKCR\\ReSharper.ReSharper_MoveUp NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9875683 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\ReSharper.ReSharper_MoveDown NAME NOT FOUND Desired Access: Read\n8:45:46.9875873 AM devenv.exe 7096 RegOpenKey HKCR\\ReSharper.ReSharper_MoveDown NAME NOT FOUND Desired Access: Read\n8:45:46.9876141 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\ReSharper.ReSharper_MoveDown NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9876276 AM devenv.exe 7096 RegOpenKey HKCR\\ReSharper.ReSharper_MoveDown NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9912375 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\CLSID\\{00020424-0000-0000-C000-000000000046}\\TreatAs NAME NOT FOUND Desired Access: Query Value\n8:45:46.9912529 AM devenv.exe 7096 RegOpenKey HKCR\\CLSID\\{00020424-0000-0000-C000-000000000046}\\TreatAs NAME NOT FOUND Desired Access: Query Value\n8:45:46.9914799 AM devenv.exe 7096 RegOpenKey HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\Managed\\S-1-5-21-2966119792-2635991036-4117835597-414090\\Installer\\Features\\7F9CD27BF7173A842A185F81E7100860 NAME NOT FOUND Desired Access: Read\n8:45:46.9915751 AM devenv.exe 7096 RegOpenKey HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\Managed\\S-1-5-21-2966119792-2635991036-4117835597-414090\\Installer\\Features\\7F9CD27BF7173A842A185F81E7100860 NAME NOT FOUND Desired Access: Read\n8:45:46.9916485 AM devenv.exe 7096 RegEnumValue HKCU\\Software\\Microsoft\\Installer\\Features\\7F9CD27BF7173A842A185F81E7100860 NO MORE ENTRIES Index: 1, Length: 220\n8:45:46.9916921 AM devenv.exe 7096 RegQueryValue HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Group Policy\\AppMgmt\\{B72DC9F7-717F-48A3-A281-F5187E018006} NAME NOT FOUND Length: 144\n8:45:46.9917220 AM devenv.exe 7096 RegOpenKey HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\Managed\\S-1-5-21-2966119792-2635991036-4117835597-414090\\Installer\\Features\\7F9CD27BF7173A842A185F81E7100860 NAME NOT FOUND Desired Access: Read\n8:45:46.9918086 AM devenv.exe 7096 RegOpenKey HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\Managed\\S-1-5-21-2966119792-2635991036-4117835597-414090\\Installer\\Features\\7F9CD27BF7173A842A185F81E7100860 NAME NOT FOUND Desired Access: Read\n8:45:46.9918661 AM devenv.exe 7096 RegEnumValue HKCU\\Software\\Microsoft\\Installer\\Features\\7F9CD27BF7173A842A185F81E7100860 NO MORE ENTRIES Index: 1, Length: 220\n8:45:46.9919019 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\CLSID\\{00020424-0000-0000-C000-000000000046}\\LocalServer32 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9919204 AM devenv.exe 7096 RegOpenKey HKCR\\CLSID\\{00020424-0000-0000-C000-000000000046}\\LocalServer32 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9919447 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\CLSID\\{00020424-0000-0000-C000-000000000046}\\InprocHandler32 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9919595 AM devenv.exe 7096 RegOpenKey HKCR\\CLSID\\{00020424-0000-0000-C000-000000000046}\\InprocHandler32 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9919825 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\CLSID\\{00020424-0000-0000-C000-000000000046}\\InprocHandlerX86 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9919969 AM devenv.exe 7096 RegOpenKey HKCR\\CLSID\\{00020424-0000-0000-C000-000000000046}\\InprocHandlerX86 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9920191 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\CLSID\\{00020424-0000-0000-C000-000000000046}\\LocalServer32 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9920322 AM devenv.exe 7096 RegOpenKey HKCR\\CLSID\\{00020424-0000-0000-C000-000000000046}\\LocalServer32 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9920543 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\CLSID\\{00020424-0000-0000-C000-000000000046}\\LocalServer NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9920677 AM devenv.exe 7096 RegOpenKey HKCR\\CLSID\\{00020424-0000-0000-C000-000000000046}\\LocalServer NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9921310 AM devenv.exe 7096 RegQueryValue HKCU\\Software\\Classes\\CLSID\\{00020424-0000-0000-C000-000000000046}\\AppID NAME NOT FOUND Length: 144\n8:45:46.9921387 AM devenv.exe 7096 RegQueryValue HKCR\\CLSID\\{00020424-0000-0000-C000-000000000046}\\AppID NAME NOT FOUND Length: 144\n8:45:46.9921910 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\Interface\\{A6FAF38C-284B-48B3-B871-84B9A66010E9}\\ProxyStubClsid32 NAME NOT FOUND Desired Access: Query Value\n8:45:46.9922398 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\Interface\\{A6FAF38C-284B-48B3-B871-84B9A66010E9}\\ProxyStubClsid32 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9922774 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\Interface\\{A6FAF38C-284B-48B3-B871-84B9A66010E9}\\ProxyStubClsid32 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9923306 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\Interface\\{A6FAF38C-284B-48B3-B871-84B9A66010E9}\\Forward NAME NOT FOUND Desired Access: Query Value\n8:45:46.9923447 AM devenv.exe 7096 RegOpenKey HKCR\\Interface\\{A6FAF38C-284B-48B3-B871-84B9A66010E9}\\Forward NAME NOT FOUND Desired Access: Query Value\n8:45:46.9923676 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\Interface\\{A6FAF38C-284B-48B3-B871-84B9A66010E9}\\TypeLib NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9924159 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\Interface\\{A6FAF38C-284B-48B3-B871-84B9A66010E9}\\TypeLib NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9924549 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\Interface\\{A6FAF38C-284B-48B3-B871-84B9A66010E9}\\TypeLib NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9924925 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\Interface\\{A6FAF38C-284B-48B3-B871-84B9A66010E9}\\TypeLib NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9925301 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\Interface\\{A6FAF38C-284B-48B3-B871-84B9A66010E9}\\TypeLib NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9925761 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\TypeLib\\{95FF4B0C-E6EC-470C-82AC-EB0471714C5A} NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9926243 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\TypeLib\\{95FF4B0C-E6EC-470C-82AC-EB0471714C5A} NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9926490 AM devenv.exe 7096 RegEnumKey HKCR\\TypeLib\\{95FF4B0C-E6EC-470C-82AC-EB0471714C5A} NO MORE ENTRIES Index: 1, Length: 288\n8:45:46.9926676 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\TypeLib\\{95FF4B0C-E6EC-470C-82AC-EB0471714C5A}\\1.0 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9927153 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\TypeLib\\{95FF4B0C-E6EC-470C-82AC-EB0471714C5A}\\1.0 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9927525 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\TypeLib\\{95FF4B0C-E6EC-470C-82AC-EB0471714C5A}\\1.0\\0 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9928018 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\TypeLib\\{95FF4B0C-E6EC-470C-82AC-EB0471714C5A}\\1.0\\0\\win32 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9928530 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\TypeLib\\{95FF4B0C-E6EC-470C-82AC-EB0471714C5A}\\1.0\\0\\win32 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9928710 AM devenv.exe 7096 RegQueryValue HKCR\\TypeLib\\{95FF4B0C-E6EC-470C-82AC-EB0471714C5A}\\1.0\\0\\win32\\(Default) BUFFER OVERFLOW Length: 144\n8:45:46.9928986 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\TypeLib\\{95FF4B0C-E6EC-470C-82AC-EB0471714C5A}\\1.0\\0\\win32 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9929159 AM devenv.exe 7096 RegQueryValue HKCR\\TypeLib\\{95FF4B0C-E6EC-470C-82AC-EB0471714C5A}\\1.0\\0\\win32\\(Default) BUFFER OVERFLOW Length: 144\n8:45:46.9936201 AM devenv.exe 7096 ReadFile C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Offset: 224, Length: 4\n8:45:46.9936267 AM devenv.exe 7096 FASTIO_CHECK_IF_POSSIBLE C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Operation: Read, Offset: 224, Length: 4\n8:45:46.9938304 AM devenv.exe 7096 ReadFile C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Offset: 228, Length: 20\n8:45:46.9938360 AM devenv.exe 7096 FASTIO_CHECK_IF_POSSIBLE C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Operation: Read, Offset: 228, Length: 20\n8:45:46.9939826 AM devenv.exe 7096 ReadFile C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Offset: 472, Length: 40\n8:45:46.9939877 AM devenv.exe 7096 FASTIO_CHECK_IF_POSSIBLE C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Operation: Read, Offset: 472, Length: 40\n8:45:46.9941335 AM devenv.exe 7096 ReadFile C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Offset: 512, Length: 40\n8:45:46.9941384 AM devenv.exe 7096 FASTIO_CHECK_IF_POSSIBLE C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Operation: Read, Offset: 512, Length: 40\n8:45:46.9943155 AM devenv.exe 7096 ReadFile C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Offset: 552, Length: 40\n8:45:46.9943207 AM devenv.exe 7096 FASTIO_CHECK_IF_POSSIBLE C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Operation: Read, Offset: 552, Length: 40\n8:45:46.9944710 AM devenv.exe 7096 ReadFile C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Offset: 3,072, Length: 16\n8:45:46.9944762 AM devenv.exe 7096 FASTIO_CHECK_IF_POSSIBLE C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Operation: Read, Offset: 3,072, Length: 16\n8:45:46.9947328 AM devenv.exe 7096 ReadFile C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Offset: 3,088, Length: 8\n8:45:46.9947380 AM devenv.exe 7096 FASTIO_CHECK_IF_POSSIBLE C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Operation: Read, Offset: 3,088, Length: 8\n8:45:46.9948846 AM devenv.exe 7096 ReadFile C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Offset: 3,232, Length: 2\n8:45:46.9948895 AM devenv.exe 7096 FASTIO_CHECK_IF_POSSIBLE C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Operation: Read, Offset: 3,232, Length: 2\n8:45:46.9954480 AM devenv.exe 7096 ReadFile C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Offset: 3,234, Length: 14\n8:45:46.9954536 AM devenv.exe 7096 FASTIO_CHECK_IF_POSSIBLE C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Operation: Read, Offset: 3,234, Length: 14\n8:45:46.9956052 AM devenv.exe 7096 ReadFile C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Offset: 3,104, Length: 16\n8:45:46.9956103 AM devenv.exe 7096 FASTIO_CHECK_IF_POSSIBLE C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Operation: Read, Offset: 3,104, Length: 16\n8:45:46.9957616 AM devenv.exe 7096 ReadFile C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Offset: 3,120, Length: 8\n8:45:46.9957666 AM devenv.exe 7096 FASTIO_CHECK_IF_POSSIBLE C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Operation: Read, Offset: 3,120, Length: 8\n8:45:46.9959108 AM devenv.exe 7096 ReadFile C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Offset: 3,152, Length: 16\n8:45:46.9959158 AM devenv.exe 7096 FASTIO_CHECK_IF_POSSIBLE C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Operation: Read, Offset: 3,152, Length: 16\n8:45:46.9961043 AM devenv.exe 7096 ReadFile C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Offset: 3,168, Length: 8\n8:45:46.9961095 AM devenv.exe 7096 FASTIO_CHECK_IF_POSSIBLE C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Operation: Read, Offset: 3,168, Length: 8\n8:45:46.9962559 AM devenv.exe 7096 ReadFile C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Offset: 3,200, Length: 16\n8:45:46.9962612 AM devenv.exe 7096 FASTIO_CHECK_IF_POSSIBLE C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Operation: Read, Offset: 3,200, Length: 16\n8:45:47.0162060 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\CLSID\\{00020424-0000-0000-C000-000000000046}\\TreatAs NAME NOT FOUND Desired Access: Query Value\n</code></pre>\n\n<p>Thanks for your help.</p>\n" }, { "answer_id": 201307, "author": "korona", "author_id": 25731, "author_profile": "https://Stackoverflow.com/users/25731", "pm_score": 0, "selected": false, "text": "<p>I'm not 100% sure it's the same problem, but I've had VC++ behave in a similar manner during debugging. This mostly happened when breaking into a crashed program though, so once again I'm not sure if it's the same issue but it might be worth a try.</p>\n\n<p>The reason:\nThe debugged process dies while having locks acquired on mutexes that Text Services Framework uses to render text. When other apps try to render any text they end up being deadlocked until the debugged process dies.</p>\n\n<p>The fix:\nTurn off advanced text services by opening Control Panel, Regional and Language Options, Languages, Details..., Advanced and checking the box labeled \"Turn off advanced text services\".</p>\n\n<p>Sorry if this is unrelated to your problem, but it sure has helped me with my debugger acting up and locking my system.</p>\n\n<p>More information: <a href=\"http://www.virtualdub.org/blog/pivot/entry.php?id=118\" rel=\"nofollow noreferrer\">http://www.virtualdub.org/blog/pivot/entry.php?id=118</a></p>\n" }, { "answer_id": 201719, "author": "Kevin Crumley", "author_id": 1818, "author_profile": "https://Stackoverflow.com/users/1818", "pm_score": 3, "selected": true, "text": "<p>Looking at your ProcMon results, it appears that it's that CreateFile() call that's taking all the time. I'm assuming that all activity is waiting for that thread to return. You can verify this -- with some difficulty -- in Process Explorer (also part of the SysInternals package previously linked), using the Threads tab on the Properties window.</p>\n\n<p>So, if CreateFile is what's causing the blockage, that would suggest that it's a delay in Windows itself. What Pierre said -- look out for network shares -- was my first instinct, too. I've had a lot of seemingly-inexplicable slowdowns in the past when Explorer had a mapping to a share that I couldn't currently reach, even though I wasn't doing any work on those shares at the time.</p>\n\n<p>Can you test this possibility by unmapping all your drives and unplugging from the network? Is D: a separate physical drive from C:? If so, see if it goes faster if you move your build directory to C:.</p>\n" }, { "answer_id": 202239, "author": "AJ.", "author_id": 27457, "author_profile": "https://Stackoverflow.com/users/27457", "pm_score": 1, "selected": false, "text": "<p>Bingo! It's something to do with a network share. I don't know which one yet, but it should be pretty easy to figure out now that I know where to look. I took your advice, unhooked my NIC, disconnected my network drives, and re-ran. No hang! Thank you so, so much. This will make life much better.</p>\n" }, { "answer_id": 217673, "author": "Pierre Arnaud", "author_id": 4597, "author_profile": "https://Stackoverflow.com/users/4597", "pm_score": 0, "selected": false, "text": "<p>Great, as in my case, then. Have you been able to find out what network share Visual Studio was trying to access. You might want to try <a href=\"http://www.wireshark.org/\" rel=\"nofollow noreferrer\">wireshark</a> to investigate further. You'll see what traffic your PC is generating...</p>\n" }, { "answer_id": 2106572, "author": "Jason", "author_id": 255432, "author_profile": "https://Stackoverflow.com/users/255432", "pm_score": 1, "selected": false, "text": "<p>From the site below I found several possible solutions.</p>\n\n<p><a href=\"http://social.msdn.microsoft.com/Forums/en/vsdebug/thread/e9c5da47-a194-4051-a3d5-28b404263b3f\" rel=\"nofollow noreferrer\">http://social.msdn.microsoft.com/Forums/en/vsdebug/thread/e9c5da47-a194-4051-a3d5-28b404263b3f</a></p>\n\n<p>The one that worked best was to run Internet Explorer\nThen go to Tools -> Internet Options -> Advanced tab -> Security section, uncheck \"Check for Publisher's Certificate Revocation\" </p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27457/" ]
I'm using Visual Studio 2008 Team System with SP1, and I've noticed an annoying tendency for the IDE to hang for several (10-15) seconds whenever I stop debugging an application. At first I thought this only happened with WPF apps, but I've observed the behavior in Windows Forms apps and ASP.NET sites as well. I've made a series of changes to the Options based on [this previous post](https://stackoverflow.com/questions/8440/visual-studio-optimizations) and done exhaustive Google/MSDN searches, but still haven't found a way to stop this. Anyone have any ideas? --- @[korona](https://stackoverflow.com/users/25731/korona) - Nope, that didn't fix it. Thanks for your suggestion, though. More research in ProcMon shows this interesting tidbit, not sure if it is related: ``` 8:45:46.6790857 AM WindowsFormsApplication1.vshost.exe 7684 FASTIO_CHECK_IF_POSSIBLE C:\WINXP\Microsoft.NET\Framework\v2.0.50727\CONFIG\enterprisesec.config.cch FAST IO DISALLOWED Operation: Read, Offset: 48, Length: 12 8:45:46.6793569 AM WindowsFormsApplication1.vshost.exe 7684 ReadFile C:\WINXP\Microsoft.NET\Framework\v2.0.50727\CONFIG\enterprisesec.config.cch FAST IO DISALLOWED Offset: 508, Length: 12 ``` This repeats several times, like hundreds of times, then it switches to a different path: ``` 8:45:46.7470314 AM WindowsFormsApplication1.vshost.exe 7684 FASTIO_CHECK_IF_POSSIBLE D:\documents and settings\myusername\Application Data\Microsoft\CLR Security Config\v2.0.50727.42\security.config.cch FAST IO DISALLOWED Operation: Read, Offset: 48, Length: 12 8:45:46.7472187 AM WindowsFormsApplication1.vshost.exe 7684 ReadFile D:\documents and settings\myusername\Application Data\Microsoft\CLR Security Config\v2.0.50727.42\security.config.cch FAST IO DISALLOWED Offset: 508, Length: 12 ``` And repeats again many more times, with slight changes in the offset each iteration. Maybe unrelated, but....
Looking at your ProcMon results, it appears that it's that CreateFile() call that's taking all the time. I'm assuming that all activity is waiting for that thread to return. You can verify this -- with some difficulty -- in Process Explorer (also part of the SysInternals package previously linked), using the Threads tab on the Properties window. So, if CreateFile is what's causing the blockage, that would suggest that it's a delay in Windows itself. What Pierre said -- look out for network shares -- was my first instinct, too. I've had a lot of seemingly-inexplicable slowdowns in the past when Explorer had a mapping to a share that I couldn't currently reach, even though I wasn't doing any work on those shares at the time. Can you test this possibility by unmapping all your drives and unplugging from the network? Is D: a separate physical drive from C:? If so, see if it goes faster if you move your build directory to C:.
198,984
<p>I have a solution with multiple projects and we need to do some serious global replacements.</p> <p>Is there a way to do a wildcard replacement where some values remain in after the replace?</p> <p>So, for instance if I want every <strong>HttpContext.Current.Session[“whatevervalue”]</strong> to become <strong>HttpContext.Current.Session[“whatevervalue”].ToString()</strong> the string value being passed in will be respected? I don’t want to replace “whatevervalue” I just want to append a .ToString() where the pattern matches. </p> <p>Is this possible in Visual Studio?</p>
[ { "answer_id": 198988, "author": "IAmCodeMonkey", "author_id": 27613, "author_profile": "https://Stackoverflow.com/users/27613", "pm_score": 2, "selected": false, "text": "<p>Easy...use regular expressions and grouping.</p>\n\n<p>Find what:\n(HttpContext.Current.Session[“whatevervalue”])</p>\n\n<p>Replace with:\n\\0.ToString();</p>\n\n<p>Remember to check the Use: and select Regular expressions</p>\n" }, { "answer_id": 198993, "author": "Degvik", "author_id": 26276, "author_profile": "https://Stackoverflow.com/users/26276", "pm_score": 0, "selected": false, "text": "<p>You can use <a href=\"http://www.wholetomato.com/\" rel=\"nofollow noreferrer\">Visual Assist</a> for tasks like this. It's a powerful tool for different kinds of refactoring.</p>\n" }, { "answer_id": 199002, "author": "Gordon Bell", "author_id": 16473, "author_profile": "https://Stackoverflow.com/users/16473", "pm_score": 5, "selected": true, "text": "<p>First, Backup your Projects, just in case... Always a good idea before mass replacements.</p>\n\n<p>Then, in the Find/Replace Dialog, select the Use Regular Expressions checkbox:</p>\n\n<p>In the Find box, use the pattern:</p>\n\n<pre><code>HttpContext\\.Current\\.Session\\[\"{.@}\"\\]\n</code></pre>\n\n<p>and in the Replace box, use:</p>\n\n<pre><code>HttpContext.Current.Session[\"\\1\"].ToString()\n</code></pre>\n" }, { "answer_id": 199010, "author": "Amanda Mitchell", "author_id": 26628, "author_profile": "https://Stackoverflow.com/users/26628", "pm_score": 2, "selected": false, "text": "<p>You want to open the \"Find Options\" expander and select the \"Use Regular Expressions\" option. After you've done that, you want these as your find/replace entries:</p>\n\n<p>Find:</p>\n\n<pre><code>HttpContext\\.Current\\.Session\\[{(\"([^\"]|\\\")*\")}\\]\n</code></pre>\n\n<p>Replace:</p>\n\n<pre><code>HttpContext.Current.Session[\\1].ToString()\n</code></pre>\n\n<p>Additional Note:</p>\n\n<p>Once you've enabled regular expressions option, you'll be able to use the right-pointing triangle buttons to access snippets of Visual Studio's Regex syntax.</p>\n\n<p>Also note that Visual Studio's Regex syntax is pretty ghetto, as it hasn't changed since the days of Visual Studio 6 (or earlier?)--so don't take any syntax elements for granted.</p>\n\n<p>For example, one might expect that my find regex above is broken because the backslash before the double-quote is not properly escaped, but in reality, putting a double-backslash there will break the expression, not fix it.</p>\n" }, { "answer_id": 199128, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 0, "selected": false, "text": "<p>You could also consider using the free download tool Refactor available at <a href=\"http://www.devexpress.com/Products/NET/IDETools/RefactorASP/\" rel=\"nofollow noreferrer\">http://www.devexpress.com/Products/NET/IDETools/RefactorASP/</a></p>\n\n<p>It does a whole lot more than just find &amp; replace, which they call renaming members with more understandable names. Its various features will easily help you to improve your code.</p>\n" }, { "answer_id": 26615557, "author": "lightmotive", "author_id": 2033465, "author_profile": "https://Stackoverflow.com/users/2033465", "pm_score": 2, "selected": false, "text": "<p>None of these answers seem to work in Visual Studio 2013, as that version seems to have finally made the switch to standard RegEx. However, those who are non-RegEx Experts or those who are used to the old VS Find/Replace RegEx syntax will find the RegEx Shortcut buttons very useful.</p>\n\n<p>Please see this answer for more information, including Find/Replace/Surround With examples:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/17591818/visual-studio-find-and-surround-with-instead-of-find-and-replace/26615388#26615388\">Visual Studio &#39;Find and Surround With&#39; instead of &#39;Find and Replace&#39;</a></p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/198984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2213/" ]
I have a solution with multiple projects and we need to do some serious global replacements. Is there a way to do a wildcard replacement where some values remain in after the replace? So, for instance if I want every **HttpContext.Current.Session[“whatevervalue”]** to become **HttpContext.Current.Session[“whatevervalue”].ToString()** the string value being passed in will be respected? I don’t want to replace “whatevervalue” I just want to append a .ToString() where the pattern matches. Is this possible in Visual Studio?
First, Backup your Projects, just in case... Always a good idea before mass replacements. Then, in the Find/Replace Dialog, select the Use Regular Expressions checkbox: In the Find box, use the pattern: ``` HttpContext\.Current\.Session\["{.@}"\] ``` and in the Replace box, use: ``` HttpContext.Current.Session["\1"].ToString() ```
199,014
<p>I have a proxy object generated by Visual Studio (client side) named ServerClient. I am attempting to set ClientCredentials.UserName.UserName/Password before opening up a new connection using this code:</p> <pre><code>InstanceContext context = new InstanceContext(this); m_client = new ServerClient(context); m_client.ClientCredentials.UserName.UserName = "Sample"; </code></pre> <p>As soon as the code hits the UserName line it fails with an "Object is read-only" error. I know this can happen if the connection is already open or faulted, but at this point I haven't called context.Open() yet. </p> <p>I have configured the Bindings (which uses netTcpBinding) to use Message as it's security mode, and MessageClientCredentialType is set to UserName.</p> <p>Any ideas?</p>
[ { "answer_id": 200713, "author": "Mike Two", "author_id": 23659, "author_profile": "https://Stackoverflow.com/users/23659", "pm_score": 0, "selected": false, "text": "<p>I think your problem might be related to the use of the InstanceContext. I thought that was only needed for duplex communication channels from the server side. </p>\n\n<p>I admit I'm not sure about this, but I think in this case you are telling the client to use an existing instance context so it thinks there is already a running service and will not allow changes.</p>\n\n<p>What is driving the use of InstanceContext?</p>\n" }, { "answer_id": 201190, "author": "Paul Mrozowski", "author_id": 3656, "author_profile": "https://Stackoverflow.com/users/3656", "pm_score": 4, "selected": true, "text": "<p>It appears that you can only access these properties pretty early in the instanciation cycle. If I override the constructor in the proxy class (ServerClient), I'm able to set these properties:</p>\n\n<pre><code>base.ClientCredentials.UserName.UserName = \"Sample\";\n</code></pre>\n\n<p>I'm beginning to appreciate the people who suggest not using the automatically built proxies provided by VS. </p>\n" }, { "answer_id": 800233, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 2, "selected": false, "text": "<p>I have similar code that's passing <code>UserName</code> fine:</p>\n\n<pre><code> FooServiceClient client = new FooServiceClient(\"BasicHttpBinding_IFooService\");\n client.ClientCredentials.UserName.UserName = \"user\";\n client.ClientCredentials.UserName.Password = \"password\";\n</code></pre>\n\n<p>Try creating the proxy with binding name in app.config.</p>\n" }, { "answer_id": 1058577, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>here is the solution:</p>\n\n<pre><code>using SysSvcmod = System.ServiceModel.Description;\n\nSysSvcmod.ClientCredentials clientCredentials = new SysSvcmod.ClientCredentials();\nclientCredentials.UserName.UserName = \"user_name\";\nclientCredentials.UserName.Password = \"pass_word\";\n\nm_client.ChannelFactory.Endpoint.Behaviors.RemoveAt(1);\nm_client.ChannelFactory.Endpoint.Behaviors.Add(clientCredentials);\n</code></pre>\n" }, { "answer_id": 1982516, "author": "Kwal", "author_id": 35220, "author_profile": "https://Stackoverflow.com/users/35220", "pm_score": 0, "selected": false, "text": "<p>If using a duplex client, when you instantiate it the DuplexChannelFactory within the DuplexClientBase that your client is derived from is initialized with existing credentials so it can open the callback channel, which is why the credentials would be read only.</p>\n\n<p>I second Mike's question and also ask why are you using NetTcpBinding if you are not going to use its inherent transport level security? Perhaps an HTTP based binding would be a better fit? That would allow you to use certificate based security which I believe can be modified after instantiation (<a href=\"http://msdn.microsoft.com/en-us/library/ms576164.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms576164.aspx</a>).</p>\n" }, { "answer_id": 2623003, "author": "Shane", "author_id": 314641, "author_profile": "https://Stackoverflow.com/users/314641", "pm_score": 0, "selected": false, "text": "<p>A shot in the dark but does netTcpBinding allow username and password validation? Try using application layer (SOAP) security using a http binding</p>\n" }, { "answer_id": 13204160, "author": "Gerhard", "author_id": 1795642, "author_profile": "https://Stackoverflow.com/users/1795642", "pm_score": 4, "selected": false, "text": "<p>I noticed that after creating an instance of the proxy class for the service, I can set the Username and Password once without errors and do a successful call to my webservice. When I then try to set the Username and Password again on the existing instance (unnecessary of course) I get the 'Object is Read-Only' error you mentioned. Setting the values once per instance lifetime worked for me.</p>\n" }, { "answer_id": 19564548, "author": "Fabienne Bonzon", "author_id": 2915490, "author_profile": "https://Stackoverflow.com/users/2915490", "pm_score": 2, "selected": false, "text": "<p>The correct syntax is:</p>\n\n<pre><code>// Remove the ClientCredentials behavior.\nclient.ChannelFactory.Endpoint.Behaviors.Remove&lt;ClientCredentials&gt;();\n\n// Add a custom client credentials instance to the behaviors collection.\nclient.ChannelFactory.Endpoint.Behaviors.Add(new MyClientCredentials());\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms730868.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms730868.aspx</a></p>\n\n<p>It worked for me.</p>\n" }, { "answer_id": 28292014, "author": "savitha", "author_id": 4522761, "author_profile": "https://Stackoverflow.com/users/4522761", "pm_score": 2, "selected": false, "text": "<p>I was facing same problem, my code started working when I changed my code i.e. assigning values to Client credential immediately after initializing Client object.</p>\n\n<p>here is the solution ,</p>\n\n<pre><code>ProductClient Manager = new ProductClient(); \nManager.ClientCredentials.UserName.UserName = txtUserName.Text;\nManager.ClientCredentials.UserName.Password = txtPassword.Text;\n</code></pre>\n" }, { "answer_id": 49654264, "author": "Blue Clouds", "author_id": 1501191, "author_profile": "https://Stackoverflow.com/users/1501191", "pm_score": 2, "selected": false, "text": "<p>This will not happen if the service reference is added through -> Add service reference ->Advanced->Add Web Reference-> Url/wsdl (local disk file).</p>\n" }, { "answer_id": 52768005, "author": "Atul", "author_id": 8449956, "author_profile": "https://Stackoverflow.com/users/8449956", "pm_score": 2, "selected": false, "text": "<p>I was facing this issue where I was trying to create a generic method to create a clients for different end points.</p>\n\n<p>Here how I achieved this.</p>\n\n<pre><code> public static T CreateClient&lt;T&gt;(string url) where T : class\n {\n EndpointAddress endPoint = new EndpointAddress(url);\n CustomBinding binding = CreateCustomBinding();\n\n T client = (T)Activator.CreateInstance(typeof(T), new object[] { binding, endPoint });\n SetClientCredentials(client);\n\n return client;\n }\n\n public static void SetClientCredentials(dynamic obj)\n {\n obj.ChannelFactory.Endpoint.Behaviors.Remove&lt;ClientCredentials&gt;();\n obj.ChannelFactory.Endpoint.Behaviors.Add(new CustomCredentials());\n\n obj.ClientCredentials.UserName.UserName = \"UserId\";\n obj.ClientCredentials.UserName.Password = \"Password\";\n }\n</code></pre>\n" }, { "answer_id": 58555093, "author": "Davit Mikuchadze", "author_id": 7611527, "author_profile": "https://Stackoverflow.com/users/7611527", "pm_score": 0, "selected": false, "text": "<p>or you could just simply check the Credentials</p>\n\n<pre><code> if (client.ClientCredentials.ClientCertificate.Certificate == null || string.IsNullOrEmpty(client.ClientCredentials.ClientCertificate.Certificate.Thumbprint))\n {\n client.ClientCredentials.ClientCertificate.SetCertificate(\n StoreLocation.LocalMachine,\n StoreName.My,\n X509FindType.FindByThumbprint, ConfigurationManager.AppSettings.Get(\"CertificateThumbprint\"));\n }\n</code></pre>\n" }, { "answer_id": 71669519, "author": "jcs", "author_id": 2526059, "author_profile": "https://Stackoverflow.com/users/2526059", "pm_score": 0, "selected": false, "text": "<p>In .NET 4.6 I couldn't remove the credentials using Fabienne's answer. Kept getting Compiler Error CS0308 in the <strong>Remove</strong> method. What worked for me was this:</p>\n<pre><code>Type endpointBehaviorType = serviceClient.ClientCredentials.GetType();\nserviceClient.Endpoint.EndpointBehaviors.Remove(endpointBehaviorType);\n\nClientCredentials clientCredentials = new ClientCredentials();\nclientCredentials.UserName.UserName = userName;\nclientCredentials.UserName.Password = password;\n\nserviceClient.Endpoint.EndpointBehaviors.Add(clientCredentials);\n</code></pre>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3656/" ]
I have a proxy object generated by Visual Studio (client side) named ServerClient. I am attempting to set ClientCredentials.UserName.UserName/Password before opening up a new connection using this code: ``` InstanceContext context = new InstanceContext(this); m_client = new ServerClient(context); m_client.ClientCredentials.UserName.UserName = "Sample"; ``` As soon as the code hits the UserName line it fails with an "Object is read-only" error. I know this can happen if the connection is already open or faulted, but at this point I haven't called context.Open() yet. I have configured the Bindings (which uses netTcpBinding) to use Message as it's security mode, and MessageClientCredentialType is set to UserName. Any ideas?
It appears that you can only access these properties pretty early in the instanciation cycle. If I override the constructor in the proxy class (ServerClient), I'm able to set these properties: ``` base.ClientCredentials.UserName.UserName = "Sample"; ``` I'm beginning to appreciate the people who suggest not using the automatically built proxies provided by VS.
199,016
<p>I'm trying to use opengl in C#. I have following code which fails with error 2000 ERROR_INVALID_PIXEL_FORMAT<br> First definitions:</p> <pre><code>[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] public static extern IntPtr GetDC(IntPtr hWnd); [StructLayout(LayoutKind.Sequential)] public struct PIXELFORMATDESCRIPTOR { public void Init() { nSize = (ushort) Marshal.SizeOf(typeof (PIXELFORMATDESCRIPTOR)); nVersion = 1; dwFlags = PFD_FLAGS.PFD_DRAW_TO_WINDOW | PFD_FLAGS.PFD_SUPPORT_OPENGL | PFD_FLAGS.PFD_DOUBLEBUFFER | PFD_FLAGS.PFD_SUPPORT_COMPOSITION; iPixelType = PFD_PIXEL_TYPE.PFD_TYPE_RGBA; cColorBits = 24; cRedBits = cRedShift = cGreenBits = cGreenShift = cBlueBits = cBlueShift = 0; cAlphaBits = cAlphaShift = 0; cAccumBits = cAccumRedBits = cAccumGreenBits = cAccumBlueBits = cAccumAlphaBits = 0; cDepthBits = 32; cStencilBits = cAuxBuffers = 0; iLayerType = PFD_LAYER_TYPES.PFD_MAIN_PLANE; bReserved = 0; dwLayerMask = dwVisibleMask = dwDamageMask = 0; } ushort nSize; ushort nVersion; PFD_FLAGS dwFlags; PFD_PIXEL_TYPE iPixelType; byte cColorBits; byte cRedBits; byte cRedShift; byte cGreenBits; byte cGreenShift; byte cBlueBits; byte cBlueShift; byte cAlphaBits; byte cAlphaShift; byte cAccumBits; byte cAccumRedBits; byte cAccumGreenBits; byte cAccumBlueBits; byte cAccumAlphaBits; byte cDepthBits; byte cStencilBits; byte cAuxBuffers; PFD_LAYER_TYPES iLayerType; byte bReserved; uint dwLayerMask; uint dwVisibleMask; uint dwDamageMask; } [Flags] public enum PFD_FLAGS : uint { PFD_DOUBLEBUFFER = 0x00000001, PFD_STEREO = 0x00000002, PFD_DRAW_TO_WINDOW = 0x00000004, PFD_DRAW_TO_BITMAP = 0x00000008, PFD_SUPPORT_GDI = 0x00000010, PFD_SUPPORT_OPENGL = 0x00000020, PFD_GENERIC_FORMAT = 0x00000040, PFD_NEED_PALETTE = 0x00000080, PFD_NEED_SYSTEM_PALETTE = 0x00000100, PFD_SWAP_EXCHANGE = 0x00000200, PFD_SWAP_COPY = 0x00000400, PFD_SWAP_LAYER_BUFFERS = 0x00000800, PFD_GENERIC_ACCELERATED = 0x00001000, PFD_SUPPORT_DIRECTDRAW = 0x00002000, PFD_DIRECT3D_ACCELERATED = 0x00004000, PFD_SUPPORT_COMPOSITION = 0x00008000, PFD_DEPTH_DONTCARE = 0x20000000, PFD_DOUBLEBUFFER_DONTCARE = 0x40000000, PFD_STEREO_DONTCARE = 0x80000000 } public enum PFD_LAYER_TYPES : byte { PFD_MAIN_PLANE = 0, PFD_OVERLAY_PLANE = 1, PFD_UNDERLAY_PLANE = 255 } public enum PFD_PIXEL_TYPE : byte { PFD_TYPE_RGBA = 0, PFD_TYPE_COLORINDEX = 1 } [DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] public static extern int ChoosePixelFormat(IntPtr hdc, [In] ref PIXELFORMATDESCRIPTOR ppfd); [DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] public static extern bool SetPixelFormat(IntPtr hdc, int iPixelFormat, ref PIXELFORMATDESCRIPTOR ppfd); [DllImport("opengl32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] public static extern IntPtr wglCreateContext(IntPtr hDC); </code></pre> <p>And now the code that fails:</p> <pre><code>IntPtr dc = Win.GetDC(hwnd); var pixelformatdescriptor = new GL.PIXELFORMATDESCRIPTOR(); pixelformatdescriptor.Init(); var pixelFormat = GL.ChoosePixelFormat(dc, ref pixelformatdescriptor); if(!GL.SetPixelFormat(dc, pixelFormat, ref pixelformatdescriptor)) throw new Win32Exception(Marshal.GetLastWin32Error()); IntPtr hglrc; if((hglrc = GL.wglCreateContext(dc)) == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error()); //&lt;----- here I have exception </code></pre> <p>the same code in managed C++ is working</p> <pre><code>HDC dc = GetDC(hWnd); PIXELFORMATDESCRIPTOR pf; pf.nSize = sizeof(PIXELFORMATDESCRIPTOR); pf.nVersion = 1; pf.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_SUPPORT_COMPOSITION; pf.cColorBits = 24; pf.cRedBits = pf.cRedShift = pf.cGreenBits = pf.cGreenShift = pf.cBlueBits = pf.cBlueShift = 0; pf.cAlphaBits = pf.cAlphaShift = 0; pf.cAccumBits = pf.cAccumRedBits = pf.cAccumGreenBits = pf.cAccumBlueBits = pf.cAccumAlphaBits = 0; pf.cDepthBits = 32; pf.cStencilBits = pf.cAuxBuffers = 0; pf.iLayerType = PFD_MAIN_PLANE; pf.bReserved = 0; pf.dwLayerMask = pf.dwVisibleMask = pf.dwDamageMask = 0; int ipf = ChoosePixelFormat(dc, &amp;pf); SetPixelFormat(dc, ipf, &amp;pf); HGLRC hglrc = wglCreateContext(dc); </code></pre> <p>I've tried it on VIsta 64-bit with ATI graphic card and on Windows XP 32-bit with Nvidia with the same result in both cases.<br> Also I want to mention that I don't want to use any already written framework for it.<br> <br> Can anyone show me where is the bug in C# code that is causing the exception?<br> <br></p>
[ { "answer_id": 205675, "author": "Brian", "author_id": 17356, "author_profile": "https://Stackoverflow.com/users/17356", "pm_score": 0, "selected": false, "text": "<p>I cannot test this right now, but my first suspicion would be the structure packing. Have you tried setting the packing to 1 in the StructLayout attribute? For example:</p>\n\n<pre><code>[StructLayout(LayoutKind.Sequential, Pack=1)]\n</code></pre>\n\n<p>Cheers,\nBrian</p>\n" }, { "answer_id": 206933, "author": "SeeR", "author_id": 22569, "author_profile": "https://Stackoverflow.com/users/22569", "pm_score": 5, "selected": true, "text": "<p>Found solution.<br>\nProblem is very strange ugly and really hard to find. Somwhere on the internet I found that when you are linking opengl32.lib while compiling c++ application it must be placed before gdi32.lib. The reason for this is that (supposedly) opengl32.dll is overwriting ChoosePixelFormat and SetPixelFormat functions (and probably more :-). As I found in my c++ version, accidentally it was the case.<br>\nHeh, but how to do it in C#<br>\nAfter few days of searching I found that in <a href=\"http://www.taoframework.com/\" rel=\"noreferrer\">tao framework</a> they solved it using kernel32.dll LoadLibrary() function and loading opengl32.dll before calling SetPixelFormat</p>\n\n<pre><code>public static bool SetPixelFormat(IntPtr deviceContext, int pixelFormat, ref PIXELFORMATDESCRIPTOR pixelFormatDescriptor) {\n Kernel.LoadLibrary(\"opengl32.dll\");\n return _SetPixelFormat(deviceContext, pixelFormat, ref pixelFormatDescriptor);\n }\n</code></pre>\n\n<p>So we know that opengl32.dll must be loaded before gdi32.dll, is there any other way of doing this. After while I thought that we can call some NOP function from opengl32.dll to load it. For example:</p>\n\n<pre><code>[DllImport(\"opengl32.dll\", EntryPoint = \"glGetString\", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]\nstatic extern IntPtr _glGetString(StringName name);\npublic static string glGetString(StringName name)\n{\n return Marshal.PtrToStringAnsi(_glGetString(name));\n}\npublic enum StringName : uint\n{\n GL_VENDOR = 0x1F00,\n GL_RENDERER = 0x1F01,\n GL_VERSION = 0x1F02,\n GL_EXTENSIONS = 0x1F03\n}\n</code></pre>\n\n<p>and on the start of application, before any call to gdi32.dll I use this:</p>\n\n<pre><code>GL.glGetString(0);\n</code></pre>\n\n<p>Both ways solves the problem.</p>\n" }, { "answer_id": 11994774, "author": "Yuriy", "author_id": 878178, "author_profile": "https://Stackoverflow.com/users/878178", "pm_score": 0, "selected": false, "text": "<p>Calling wglCreateContext twice helps too.</p>\n\n<pre><code>if (SetPixelFormat(DC, iPixelformat, ref pfd) == false)\n throw new Win32Exception(Marshal.GetLastWin32Error());\n\nRC = wglCreateContext(DC);\nif (RC == HGLRC.Zero)\n{ \n if (SetPixelFormat(DC, iPixelformat, ref pfd) == false)\n throw new Win32Exception(Marshal.GetLastWin32Error());\n RC = wglCreateContext(DC);\n if (RC == HGLRC.Zero)\n throw new Win32Exception(Marshal.GetLastWin32Error());\n}\n</code></pre>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22569/" ]
I'm trying to use opengl in C#. I have following code which fails with error 2000 ERROR\_INVALID\_PIXEL\_FORMAT First definitions: ``` [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] public static extern IntPtr GetDC(IntPtr hWnd); [StructLayout(LayoutKind.Sequential)] public struct PIXELFORMATDESCRIPTOR { public void Init() { nSize = (ushort) Marshal.SizeOf(typeof (PIXELFORMATDESCRIPTOR)); nVersion = 1; dwFlags = PFD_FLAGS.PFD_DRAW_TO_WINDOW | PFD_FLAGS.PFD_SUPPORT_OPENGL | PFD_FLAGS.PFD_DOUBLEBUFFER | PFD_FLAGS.PFD_SUPPORT_COMPOSITION; iPixelType = PFD_PIXEL_TYPE.PFD_TYPE_RGBA; cColorBits = 24; cRedBits = cRedShift = cGreenBits = cGreenShift = cBlueBits = cBlueShift = 0; cAlphaBits = cAlphaShift = 0; cAccumBits = cAccumRedBits = cAccumGreenBits = cAccumBlueBits = cAccumAlphaBits = 0; cDepthBits = 32; cStencilBits = cAuxBuffers = 0; iLayerType = PFD_LAYER_TYPES.PFD_MAIN_PLANE; bReserved = 0; dwLayerMask = dwVisibleMask = dwDamageMask = 0; } ushort nSize; ushort nVersion; PFD_FLAGS dwFlags; PFD_PIXEL_TYPE iPixelType; byte cColorBits; byte cRedBits; byte cRedShift; byte cGreenBits; byte cGreenShift; byte cBlueBits; byte cBlueShift; byte cAlphaBits; byte cAlphaShift; byte cAccumBits; byte cAccumRedBits; byte cAccumGreenBits; byte cAccumBlueBits; byte cAccumAlphaBits; byte cDepthBits; byte cStencilBits; byte cAuxBuffers; PFD_LAYER_TYPES iLayerType; byte bReserved; uint dwLayerMask; uint dwVisibleMask; uint dwDamageMask; } [Flags] public enum PFD_FLAGS : uint { PFD_DOUBLEBUFFER = 0x00000001, PFD_STEREO = 0x00000002, PFD_DRAW_TO_WINDOW = 0x00000004, PFD_DRAW_TO_BITMAP = 0x00000008, PFD_SUPPORT_GDI = 0x00000010, PFD_SUPPORT_OPENGL = 0x00000020, PFD_GENERIC_FORMAT = 0x00000040, PFD_NEED_PALETTE = 0x00000080, PFD_NEED_SYSTEM_PALETTE = 0x00000100, PFD_SWAP_EXCHANGE = 0x00000200, PFD_SWAP_COPY = 0x00000400, PFD_SWAP_LAYER_BUFFERS = 0x00000800, PFD_GENERIC_ACCELERATED = 0x00001000, PFD_SUPPORT_DIRECTDRAW = 0x00002000, PFD_DIRECT3D_ACCELERATED = 0x00004000, PFD_SUPPORT_COMPOSITION = 0x00008000, PFD_DEPTH_DONTCARE = 0x20000000, PFD_DOUBLEBUFFER_DONTCARE = 0x40000000, PFD_STEREO_DONTCARE = 0x80000000 } public enum PFD_LAYER_TYPES : byte { PFD_MAIN_PLANE = 0, PFD_OVERLAY_PLANE = 1, PFD_UNDERLAY_PLANE = 255 } public enum PFD_PIXEL_TYPE : byte { PFD_TYPE_RGBA = 0, PFD_TYPE_COLORINDEX = 1 } [DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] public static extern int ChoosePixelFormat(IntPtr hdc, [In] ref PIXELFORMATDESCRIPTOR ppfd); [DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] public static extern bool SetPixelFormat(IntPtr hdc, int iPixelFormat, ref PIXELFORMATDESCRIPTOR ppfd); [DllImport("opengl32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] public static extern IntPtr wglCreateContext(IntPtr hDC); ``` And now the code that fails: ``` IntPtr dc = Win.GetDC(hwnd); var pixelformatdescriptor = new GL.PIXELFORMATDESCRIPTOR(); pixelformatdescriptor.Init(); var pixelFormat = GL.ChoosePixelFormat(dc, ref pixelformatdescriptor); if(!GL.SetPixelFormat(dc, pixelFormat, ref pixelformatdescriptor)) throw new Win32Exception(Marshal.GetLastWin32Error()); IntPtr hglrc; if((hglrc = GL.wglCreateContext(dc)) == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error()); //<----- here I have exception ``` the same code in managed C++ is working ``` HDC dc = GetDC(hWnd); PIXELFORMATDESCRIPTOR pf; pf.nSize = sizeof(PIXELFORMATDESCRIPTOR); pf.nVersion = 1; pf.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_SUPPORT_COMPOSITION; pf.cColorBits = 24; pf.cRedBits = pf.cRedShift = pf.cGreenBits = pf.cGreenShift = pf.cBlueBits = pf.cBlueShift = 0; pf.cAlphaBits = pf.cAlphaShift = 0; pf.cAccumBits = pf.cAccumRedBits = pf.cAccumGreenBits = pf.cAccumBlueBits = pf.cAccumAlphaBits = 0; pf.cDepthBits = 32; pf.cStencilBits = pf.cAuxBuffers = 0; pf.iLayerType = PFD_MAIN_PLANE; pf.bReserved = 0; pf.dwLayerMask = pf.dwVisibleMask = pf.dwDamageMask = 0; int ipf = ChoosePixelFormat(dc, &pf); SetPixelFormat(dc, ipf, &pf); HGLRC hglrc = wglCreateContext(dc); ``` I've tried it on VIsta 64-bit with ATI graphic card and on Windows XP 32-bit with Nvidia with the same result in both cases. Also I want to mention that I don't want to use any already written framework for it. Can anyone show me where is the bug in C# code that is causing the exception?
Found solution. Problem is very strange ugly and really hard to find. Somwhere on the internet I found that when you are linking opengl32.lib while compiling c++ application it must be placed before gdi32.lib. The reason for this is that (supposedly) opengl32.dll is overwriting ChoosePixelFormat and SetPixelFormat functions (and probably more :-). As I found in my c++ version, accidentally it was the case. Heh, but how to do it in C# After few days of searching I found that in [tao framework](http://www.taoframework.com/) they solved it using kernel32.dll LoadLibrary() function and loading opengl32.dll before calling SetPixelFormat ``` public static bool SetPixelFormat(IntPtr deviceContext, int pixelFormat, ref PIXELFORMATDESCRIPTOR pixelFormatDescriptor) { Kernel.LoadLibrary("opengl32.dll"); return _SetPixelFormat(deviceContext, pixelFormat, ref pixelFormatDescriptor); } ``` So we know that opengl32.dll must be loaded before gdi32.dll, is there any other way of doing this. After while I thought that we can call some NOP function from opengl32.dll to load it. For example: ``` [DllImport("opengl32.dll", EntryPoint = "glGetString", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] static extern IntPtr _glGetString(StringName name); public static string glGetString(StringName name) { return Marshal.PtrToStringAnsi(_glGetString(name)); } public enum StringName : uint { GL_VENDOR = 0x1F00, GL_RENDERER = 0x1F01, GL_VERSION = 0x1F02, GL_EXTENSIONS = 0x1F03 } ``` and on the start of application, before any call to gdi32.dll I use this: ``` GL.glGetString(0); ``` Both ways solves the problem.
199,035
<p>Has anyone used <a href="http://pear.php.net/package/Spreadsheet_Excel_Writer/" rel="nofollow noreferrer">Pear: Spreadsheet_Excel_Writer</a>?</p> <p>The <a href="http://pear.php.net/manual/en/package.fileformats.spreadsheet-excel-writer.intro-format.php" rel="nofollow noreferrer">Formatting Tutorial</a> lists a script similar to what I'm working with: (trimmed down)</p> <pre><code>&lt;?php require_once 'Spreadsheet/Excel/Writer.php'; $workbook = new Spreadsheet_Excel_Writer(); $worksheet =&amp; $workbook-&gt;addWorksheet(); $worksheet-&gt;write(0, 0, "Quarterly Profits for Dotcom.Com"); $workbook-&gt;send('test.xls'); $workbook-&gt;close(); ?&gt; </code></pre> <p>What I think I understand so far about it...<br> <code>$workbook-&gt;send('test.xls');</code> sets the headers up for Excel file transfer. Now, no errors seem to come up, but the file downloaded is entirely empty (even in a hex editor).</p> <p>So...<br> Where (in what class/method) is the <code>$workbook</code> binary supposed to be written? Or, am I misunderstanding it all?</p> <p><strong>Note</strong>: I honestly don't know what version of Spreadsheet_Excel_Writer is being used; the sources don't include such useful information.<br> I can tell you the copyright is <strong><em>2002-2003</em></strong>; so, anywhere from version 0.1 to 0.6.</p> <p>[<strong>Edit</strong>] Sorry, thought I'd mentioned this somewhere.. This is someone else's script that I've been assigned to fix.</p>
[ { "answer_id": 199166, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 3, "selected": true, "text": "<p>Here is some sample code:</p>\n\n<pre><code>&lt;?php\nrequire_once 'Spreadsheet/Excel/Writer.php';\n$workbook = new Spreadsheet_Excel_Writer('test.xls');\n$worksheet =&amp; $workbook-&gt;addWorksheet('My first worksheet');\nif (PEAR::isError($worksheet)) {\n die($worksheet-&gt;getMessage());\n}\n$workbook-&gt;close();\n?&gt;\n</code></pre>\n\n<p>I think for starters, give your worksheet a name and try to write a file directly (without <code>send()</code>).</p>\n\n<p>Also, make sure with all methods you call, test the response with <code>PEAR::isError()</code>.</p>\n" }, { "answer_id": 199230, "author": "gnud", "author_id": 27204, "author_profile": "https://Stackoverflow.com/users/27204", "pm_score": 0, "selected": false, "text": "<p>send() sends cache-control headers and content type headers, but not content.\nThe content is sendt, as I understand from the code, when $workbook->close() is called.</p>\n" }, { "answer_id": 1323890, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Use this to download the worksheet in your Browser</p>\n\n<pre><code>$workbook = new Spreadsheet_Excel_Writer(); // &lt;-- leave parantheses empty\n$workbook-&gt;send($DownloadFileName);\n// Your fancy spreadsheet generating code\n$workbook-&gt;close();\n</code></pre>\n\n<p>and this to write it to a file.</p>\n\n<pre><code>$workbook = new Spreadsheet_Excel_Writer($SaveFileName);\n// Your fancy spreadsheet generating code\n$workbook-&gt;close();\n</code></pre>\n" }, { "answer_id": 1574633, "author": "Mávil", "author_id": 190844, "author_profile": "https://Stackoverflow.com/users/190844", "pm_score": 0, "selected": false, "text": "<p>You need to name your worksheet at <code>$worksheet =&amp; $workbook-&gt;addWorksheet();</code>.<br>\nCheck the code below:</p>\n\n<pre><code>require_once 'Spreadsheet/Excel/Writer.php';\n\n//Create a workbook\n$workbook = new Spreadsheet_Excel_Writer(); //() must be empty or your downloaded file will be corrupt.\n\n// Create a worksheet \n$worksheet =&amp; $workbook-&gt;addWorksheet('test'); &lt;-- You forgot to name your worksheet in your code, yours is \"addWorksheet()\"\n\n// The actual data \n$worksheet-&gt;write(0, 0, 'Name'); \n$worksheet-&gt;write(0, 1, 'Age'); \n$worksheet-&gt;write(1, 0, 'John Smith'); \n$worksheet-&gt;write(1, 1, 30);\n$worksheet-&gt;write(2, 0, 'Johann Schmidt');\n$worksheet-&gt;write(2, 1, 31); $worksheet-&gt;write(3, 0, 'Juan Herrera');\n$worksheet-&gt;write(3, 1, 32);\n\n// send HTTP headers \n$workbook-&gt;send('prueba.xls');\n\n// Let's send the file\n$workbook-&gt;close();\n</code></pre>\n" }, { "answer_id": 4743114, "author": "John R. Tipton", "author_id": 582396, "author_profile": "https://Stackoverflow.com/users/582396", "pm_score": 1, "selected": false, "text": "<p>It is not very clear, but I think that the send command only creates the headers with the correct content type and file name. You have to send the data afterwards, with something lik</p>\n\n<pre><code>$tmpDocument = '/path/to/tmp/file.xls';\n$workbook = new Spreadsheet_Excel_Writer($tmpDocument); \n</code></pre>\n\n<p>/* Code to generate the XLS file */</p>\n\n<pre><code>$workbook-&gt;close();\n$workbook-&gt;send('Report.xls');\nreadfile($tmpDocument);\n</code></pre>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15031/" ]
Has anyone used [Pear: Spreadsheet\_Excel\_Writer](http://pear.php.net/package/Spreadsheet_Excel_Writer/)? The [Formatting Tutorial](http://pear.php.net/manual/en/package.fileformats.spreadsheet-excel-writer.intro-format.php) lists a script similar to what I'm working with: (trimmed down) ``` <?php require_once 'Spreadsheet/Excel/Writer.php'; $workbook = new Spreadsheet_Excel_Writer(); $worksheet =& $workbook->addWorksheet(); $worksheet->write(0, 0, "Quarterly Profits for Dotcom.Com"); $workbook->send('test.xls'); $workbook->close(); ?> ``` What I think I understand so far about it... `$workbook->send('test.xls');` sets the headers up for Excel file transfer. Now, no errors seem to come up, but the file downloaded is entirely empty (even in a hex editor). So... Where (in what class/method) is the `$workbook` binary supposed to be written? Or, am I misunderstanding it all? **Note**: I honestly don't know what version of Spreadsheet\_Excel\_Writer is being used; the sources don't include such useful information. I can tell you the copyright is ***2002-2003***; so, anywhere from version 0.1 to 0.6. [**Edit**] Sorry, thought I'd mentioned this somewhere.. This is someone else's script that I've been assigned to fix.
Here is some sample code: ``` <?php require_once 'Spreadsheet/Excel/Writer.php'; $workbook = new Spreadsheet_Excel_Writer('test.xls'); $worksheet =& $workbook->addWorksheet('My first worksheet'); if (PEAR::isError($worksheet)) { die($worksheet->getMessage()); } $workbook->close(); ?> ``` I think for starters, give your worksheet a name and try to write a file directly (without `send()`). Also, make sure with all methods you call, test the response with `PEAR::isError()`.
199,044
<p>My rails app is in a svn repository, but several of the plugins are installed through git and later added to the svn repo. How can I update these plugins? I can't seem to get script/plugin update to do anything. I'd really like to update activemerchant to get rid of the Inflector warnings.</p>
[ { "answer_id": 200349, "author": "Greg Borenstein", "author_id": 10419, "author_profile": "https://Stackoverflow.com/users/10419", "pm_score": 0, "selected": false, "text": "<p>You should just be able to navigate to the plugin's directory and hit:\n<code>\ngit pull\n</code>. I'm pretty sure that <code>script/install plugin</code> just checks the code out from the git repo.</p>\n" }, { "answer_id": 215380, "author": "Matt", "author_id": 29228, "author_profile": "https://Stackoverflow.com/users/29228", "pm_score": 2, "selected": false, "text": "<p>If you haven't made any local changes to the plugin and you don't need to track what changes to it the update will bring, you can just run <code>script/plugin install</code> again, passing in <code>--force</code> if you need to. For example:</p>\n\n<pre><code>script/plugin install --force git://github.com/dchelimsky/rspec.git\n</code></pre>\n" }, { "answer_id": 241000, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 0, "selected": false, "text": "<p>In order for Git to be able to recognise the repository as a Git repository, you will need to add the <code>.git</code> subdirectory and everything under it to Subversion as well. Otherwise, the plugin will just look like another pile of source code and Git will say it's \"Not a Git repository\".</p>\n" }, { "answer_id": 1476218, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Ran into the same situation and used this solution: had paperclip installed as a plugin sitting in an svn repo as part of my app. Now I wanted to use the latest version instead and didnt change a bit of the paperclip plugin so I could easyly remove it from the app/svn and install it as a gem instead. done.</p>\n" }, { "answer_id": 2420012, "author": "Grant Hutchins", "author_id": 6304, "author_profile": "https://Stackoverflow.com/users/6304", "pm_score": 2, "selected": false, "text": "<p>If you already have a static copy of a plugin checked into Subversion, it can be a pain to update it via <code>script/plugin</code>, so here's what I end up doing in order to switch it from a static install to a Git checkout all within one Subversion commit:</p>\n\n<pre><code>git clone git://github.com/foo/bar.git ~/foobar\nmv ~/foobar/.git rails_app/vendor/plugins/foobar/.git\nrm -rf ~/foobar\ncd rails_app/vendor/plugins\ngit reset --hard\n</code></pre>\n\n<p>Then make sure to add <code>.git</code> and everything else that has changed to the Subversion project and you will be all up-to-date. You can use other git commands to pull down updates, move to a different branch, etc. Then just check things in again once they are at the state that you want.</p>\n" }, { "answer_id": 4207438, "author": "Yves L", "author_id": 511128, "author_profile": "https://Stackoverflow.com/users/511128", "pm_score": 1, "selected": false, "text": "<p>One thing I do in this case, I remove the plugin directory then I commit to SVN, this will remove the old plugin in the repo. (I usually moved it in a tmp directory, just in case and delate it later once the new one is working fine)\nI then reinstall the new version of the plugin, and commit again.\nEasy.</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2884/" ]
My rails app is in a svn repository, but several of the plugins are installed through git and later added to the svn repo. How can I update these plugins? I can't seem to get script/plugin update to do anything. I'd really like to update activemerchant to get rid of the Inflector warnings.
If you haven't made any local changes to the plugin and you don't need to track what changes to it the update will bring, you can just run `script/plugin install` again, passing in `--force` if you need to. For example: ``` script/plugin install --force git://github.com/dchelimsky/rspec.git ```
199,045
<p>I'm looking for a library that has functionality similar to Perl's <a href="http://search.cpan.org/dist/WWW-Mechanize/lib/WWW/Mechanize.pm#SYNOPSIS" rel="noreferrer">WWW::Mechanize</a>, but for PHP. Basically, it should allow me to submit HTTP GET and POST requests with a simple syntax, and then parse the resulting page and return in a simple format all forms and their fields, along with all links on the page.</p> <p>I know about CURL, but it's a little too barebones, and the syntax is pretty ugly (tons of <code>curl_foo($curl_handle, ...)</code> statements</p> <p><strong>Clarification:</strong></p> <p>I want something more high-level than the answers so far. For example, in Perl, you could do something like:</p> <pre><code># navigate to the main page $mech-&gt;get( 'http://www.somesite.com/' ); # follow a link that contains the text 'download this' $mech-&gt;follow_link( text_regex =&gt; qr/download this/i ); # submit a POST form, to log into the site $mech-&gt;submit_form( with_fields =&gt; { username =&gt; 'mungo', password =&gt; 'lost-and-alone', } ); # save the results as a file $mech-&gt;save_content('somefile.zip'); </code></pre> <p>To do the same thing using HTTP_Client or wget or CURL would be a lot of work, I'd have to manually parse the pages to find the links, find the form URL, extract all the hidden fields, and so on. The reason I'm asking for a PHP solution is that I have no experience with Perl, and I could probably build what I need with a lot of work, but it would be much quicker if I could do the above in PHP.</p>
[ { "answer_id": 199054, "author": "moo", "author_id": 23107, "author_profile": "https://Stackoverflow.com/users/23107", "pm_score": 1, "selected": false, "text": "<p>Try looking in the PEAR library. If all else fails, create an object wrapper for curl.</p>\n\n<p>You can so something simple like this:</p>\n\n<pre><code>class curl {\n private $resource;\n\n public function __construct($url) {\n $this-&gt;resource = curl_init($url);\n }\n\n public function __call($function, array $params) {\n array_unshift($params, $this-&gt;resource);\n return call_user_func_array(\"curl_$function\", $params);\n }\n}\n</code></pre>\n" }, { "answer_id": 199160, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 1, "selected": false, "text": "<p>Try one of the following:</p>\n\n<ul>\n<li>PEAR's <a href=\"http://pear.php.net/package/HTTP_Request\" rel=\"nofollow noreferrer\">HTTP_Request</a></li>\n<li><a href=\"http://framework.zend.com/manual/en/zend.http.html#zend.http.client\" rel=\"nofollow noreferrer\">Zend_Http_Client</a></li>\n</ul>\n\n<p>(Yes, it's ZendFramework code, but it doesn't make your class slower using it since it just loads the required libs.)</p>\n" }, { "answer_id": 199183, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": -1, "selected": false, "text": "<p>If you're on a *nix system you could use shell_exec() with wget, which has a lot of nice options.</p>\n" }, { "answer_id": 199365, "author": "Eli", "author_id": 27580, "author_profile": "https://Stackoverflow.com/users/27580", "pm_score": 1, "selected": false, "text": "<p>Look into Snoopy:\n<a href=\"http://sourceforge.net/projects/snoopy/\" rel=\"nofollow noreferrer\">http://sourceforge.net/projects/snoopy/</a></p>\n" }, { "answer_id": 199386, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 6, "selected": true, "text": "<p>SimpleTest's <a href=\"http://simpletest.sourceforge.net/en/browser_documentation.html\" rel=\"nofollow noreferrer\">ScriptableBrowser</a> can be used independendly from the testing framework. I've used it for numerous automation-jobs.</p>\n" }, { "answer_id": 199387, "author": "SchizoDuckie", "author_id": 18077, "author_profile": "https://Stackoverflow.com/users/18077", "pm_score": 1, "selected": false, "text": "<p>Curl is the way to go for simple requests. It runs cross platform, has a PHP extension and is widely adopted and tested.</p>\n\n<p>I created a nice class that can GET and POST an array of data (INCLUDING FILES!) to a url by just calling CurlHandler::Get($url, $data) || CurlHandler::Post($url, $data). There's an optional HTTP User authentication option too :)</p>\n\n<pre><code>/**\n * CURLHandler handles simple HTTP GETs and POSTs via Curl \n * \n * @package Pork\n * @author SchizoDuckie\n * @copyright SchizoDuckie 2008\n * @version 1.0\n * @access public\n */\nclass CURLHandler\n{\n\n /**\n * CURLHandler::Get()\n * \n * Executes a standard GET request via Curl.\n * Static function, so that you can use: CurlHandler::Get('http://www.google.com');\n * \n * @param string $url url to get\n * @return string HTML output\n */\n public static function Get($url)\n {\n return self::doRequest('GET', $url);\n }\n\n /**\n * CURLHandler::Post()\n * \n * Executes a standard POST request via Curl.\n * Static function, so you can use CurlHandler::Post('http://www.google.com', array('q'=&gt;'StackOverFlow'));\n * If you want to send a File via post (to e.g. PHP's $_FILES), prefix the value of an item with an @ ! \n * @param string $url url to post data to\n * @param Array $vars Array with key=&gt;value pairs to post.\n * @return string HTML output\n */\n public static function Post($url, $vars, $auth = false) \n {\n return self::doRequest('POST', $url, $vars, $auth);\n }\n\n /**\n * CURLHandler::doRequest()\n * This is what actually does the request\n * &lt;pre&gt;\n * - Create Curl handle with curl_init\n * - Set options like CURLOPT_URL, CURLOPT_RETURNTRANSFER and CURLOPT_HEADER\n * - Set eventual optional options (like CURLOPT_POST and CURLOPT_POSTFIELDS)\n * - Call curl_exec on the interface\n * - Close the connection\n * - Return the result or throw an exception.\n * &lt;/pre&gt;\n * @param mixed $method Request Method (Get/ Post)\n * @param mixed $url URI to get or post to\n * @param mixed $vars Array of variables (only mandatory in POST requests)\n * @return string HTML output\n */\n public static function doRequest($method, $url, $vars=array(), $auth = false)\n {\n $curlInterface = curl_init();\n\n curl_setopt_array ($curlInterface, array( \n CURLOPT_URL =&gt; $url,\n CURLOPT_RETURNTRANSFER =&gt; 1,\n CURLOPT_FOLLOWLOCATION =&gt;1,\n CURLOPT_HEADER =&gt; 0));\n if (strtoupper($method) == 'POST')\n {\n curl_setopt_array($curlInterface, array(\n CURLOPT_POST =&gt; 1,\n CURLOPT_POSTFIELDS =&gt; http_build_query($vars))\n ); \n }\n if($auth !== false)\n {\n curl_setopt($curlInterface, CURLOPT_USERPWD, $auth['username'] . \":\" . $auth['password']);\n }\n $result = curl_exec ($curlInterface);\n curl_close ($curlInterface);\n\n if($result === NULL)\n {\n throw new Exception('Curl Request Error: '.curl_errno($curlInterface) . \" - \" . curl_error($curlInterface));\n }\n else\n {\n return($result);\n }\n }\n\n}\n\n?&gt;\n</code></pre>\n\n<p>[edit] Read the clarification only now... You probably want to go with one of the tools mentioned above that automates stuff. You could also decide to use a clientside firefox extension like <a href=\"http://groups.csail.mit.edu/uid/chickenfoot/examples.html\" rel=\"nofollow noreferrer\">ChickenFoot</a> for more flexibility. I'll leave the example class above here for future searches.</p>\n" }, { "answer_id": 3174287, "author": "Rick", "author_id": 378874, "author_profile": "https://Stackoverflow.com/users/378874", "pm_score": 2, "selected": false, "text": "<p>I feel compelled to answer this, even though its an old post... I've been working with PHP curl a lot and it is not as good anywhere near comparable to something like WWW:Mechanize, which I am switching to (I think I am going to go with the Ruby language implementation).. Curl is outdated as it requires too much \"grunt work\" to automate anything, the simpletest scriptable browser looked promising to me but in testing it, it won't work on most web forms I try it on... honestly, I think PHP is lacking in this category of scraping, web automation so its best to look at a different language, just wanted to post this since I have spent countless hours on this topic and maybe it will save someone else some time in the future.</p>\n" }, { "answer_id": 5169099, "author": "method", "author_id": 40883, "author_profile": "https://Stackoverflow.com/users/40883", "pm_score": 1, "selected": false, "text": "<p>If you're using CakePHP in your project, or if you're inclined to extract the relevant library you can use their curl wrapper HttpSocket. It has the simple page-fetching syntax you describe, e.g., </p>\n\n<pre><code># This is the sugar for importing the library within CakePHP \nApp::import('Core', 'HttpSocket');\n$HttpSocket = new HttpSocket();\n\n$result = $HttpSocket-&gt;post($login_url,\narray(\n \"username\" =&gt; \"username\",\n \"password\" =&gt; \"password\"\n)\n);\n</code></pre>\n\n<p>...although it doesn't have a way to parse the response page. For that I'm going to use simplehtmldom: <a href=\"http://net.tutsplus.com/tutorials/php/html-parsing-and-screen-scraping-with-the-simple-html-dom-library/\" rel=\"nofollow\">http://net.tutsplus.com/tutorials/php/html-parsing-and-screen-scraping-with-the-simple-html-dom-library/</a> which describes itself as having a jQuery-like syntax.</p>\n\n<p>I tend to agree that the bottom line is that PHP doesn't have the awesome scraping/automation libraries that Perl/Ruby have.</p>\n" }, { "answer_id": 38262338, "author": "mbirth", "author_id": 3293109, "author_profile": "https://Stackoverflow.com/users/3293109", "pm_score": 2, "selected": false, "text": "<p>It's 2016 now and there's <a href=\"http://mink.behat.org/en/latest/at-a-glance.html\" rel=\"nofollow\">Mink</a>. It even supports different engines from headless pure-PHP \"browser\" (without JavaScript), over Selenium (which needs a browser like Firefox or Chrome) to a headless \"browser.js\" in NPM, which DOES support JavaScript.</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14569/" ]
I'm looking for a library that has functionality similar to Perl's [WWW::Mechanize](http://search.cpan.org/dist/WWW-Mechanize/lib/WWW/Mechanize.pm#SYNOPSIS), but for PHP. Basically, it should allow me to submit HTTP GET and POST requests with a simple syntax, and then parse the resulting page and return in a simple format all forms and their fields, along with all links on the page. I know about CURL, but it's a little too barebones, and the syntax is pretty ugly (tons of `curl_foo($curl_handle, ...)` statements **Clarification:** I want something more high-level than the answers so far. For example, in Perl, you could do something like: ``` # navigate to the main page $mech->get( 'http://www.somesite.com/' ); # follow a link that contains the text 'download this' $mech->follow_link( text_regex => qr/download this/i ); # submit a POST form, to log into the site $mech->submit_form( with_fields => { username => 'mungo', password => 'lost-and-alone', } ); # save the results as a file $mech->save_content('somefile.zip'); ``` To do the same thing using HTTP\_Client or wget or CURL would be a lot of work, I'd have to manually parse the pages to find the links, find the form URL, extract all the hidden fields, and so on. The reason I'm asking for a PHP solution is that I have no experience with Perl, and I could probably build what I need with a lot of work, but it would be much quicker if I could do the above in PHP.
SimpleTest's [ScriptableBrowser](http://simpletest.sourceforge.net/en/browser_documentation.html) can be used independendly from the testing framework. I've used it for numerous automation-jobs.
199,059
<p>I've got a file whose format I'm altering via a python script. I have several camel cased strings in this file where I just want to insert a single space before the capital letter - so "WordWordWord" becomes "Word Word Word".</p> <p>My limited regex experience just stalled out on me - can someone think of a decent regex to do this, or (better yet) is there a more pythonic way to do this that I'm missing?</p>
[ { "answer_id": 199075, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 7, "selected": true, "text": "<p>You could try:</p>\n\n<pre><code>&gt;&gt;&gt; re.sub(r\"(\\w)([A-Z])\", r\"\\1 \\2\", \"WordWordWord\")\n'Word Word Word'\n</code></pre>\n" }, { "answer_id": 199094, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 3, "selected": false, "text": "<p>With regexes you can do this:</p>\n\n<pre><code>re.sub('([A-Z])', r' \\1', str)\n</code></pre>\n\n<p>Of course, that will only work for ASCII characters, if you want to do Unicode it's a whole new can of worms :-)</p>\n" }, { "answer_id": 199120, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>If there are consecutive capitals, then Gregs result could\nnot be what you look for, since the \\w consumes the caracter\nin front of the captial letter to be replaced.</p>\n\n<pre><code>&gt;&gt;&gt; re.sub(r\"(\\w)([A-Z])\", r\"\\1 \\2\", \"WordWordWWWWWWWord\")\n'Word Word WW WW WW Word'\n</code></pre>\n\n<p>A look-behind would solve this:</p>\n\n<pre><code>&gt;&gt;&gt; re.sub(r\"(?&lt;=\\w)([A-Z])\", r\" \\1\", \"WordWordWWWWWWWord\")\n'Word Word W W W W W W Word'\n</code></pre>\n" }, { "answer_id": 199126, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 4, "selected": false, "text": "<p>Have a look at my answer on <em><a href=\"https://stackoverflow.com/questions/155303/net-how-can-you-split-a-caps-delimited-string-into-an-array#155487\">.NET - How can you split a “caps” delimited string into an array?</a></em></p>\n\n<p><strong>Edit:</strong> Maybe better to include it here.</p>\n\n<pre><code>re.sub(r'([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))', r'\\1 ', text)\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>\"SimpleHTTPServer\" =&gt; [\"Simple\", \"HTTP\", \"Server\"]\n</code></pre>\n" }, { "answer_id": 199215, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 4, "selected": false, "text": "<p>Perhaps shorter:</p>\n\n<pre><code>&gt;&gt;&gt; re.sub(r\"\\B([A-Z])\", r\" \\1\", \"DoIThinkThisIsABetterAnswer?\")\n</code></pre>\n" }, { "answer_id": 200122, "author": "monkut", "author_id": 24718, "author_profile": "https://Stackoverflow.com/users/24718", "pm_score": 1, "selected": false, "text": "<p>I agree that the regex solution is the easiest, but I wouldn't say it's the most pythonic.</p>\n\n<p>How about:</p>\n\n<pre><code>text = 'WordWordWord'\nnew_text = ''\n\nfor i, letter in enumerate(text):\n if i and letter.isupper():\n new_text += ' '\n\n new_text += letter\n</code></pre>\n" }, { "answer_id": 200456, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 0, "selected": false, "text": "<p>I think regexes are the way to go here, but just to give a pure python version without (hopefully) any of the problems ΤΖΩΤΖΙΟΥ has pointed out:</p>\n\n<pre><code>def splitCaps(s):\n result = []\n for ch, next in window(s+\" \", 2):\n result.append(ch)\n if next.isupper() and not ch.isspace():\n result.append(' ')\n return ''.join(result)\n</code></pre>\n\n<p>window() is a utility function I use to operate on a sliding window of items, defined as:</p>\n\n<pre><code>import collections, itertools\n\ndef window(it, winsize, step=1):\n it=iter(it) # Ensure we have an iterator\n l=collections.deque(itertools.islice(it, winsize))\n while 1: # Continue till StopIteration gets raised.\n yield tuple(l)\n for i in range(step):\n l.append(it.next())\n l.popleft()\n</code></pre>\n" }, { "answer_id": 45778633, "author": "Yaroslav Surzhikov", "author_id": 8489834, "author_profile": "https://Stackoverflow.com/users/8489834", "pm_score": 3, "selected": false, "text": "<p>Maybe you would be interested in one-liner implementation without using regexp:</p>\n\n<pre><code>''.join(' ' + char if char.isupper() else char.strip() for char in text).strip()\n</code></pre>\n" }, { "answer_id": 46760056, "author": "David Underhill", "author_id": 164602, "author_profile": "https://Stackoverflow.com/users/164602", "pm_score": 2, "selected": false, "text": "<p>If you have acronyms, you probably do not want spaces between them. This two-stage regex will keep acronyms intact (and also treat punctuation and other non-uppercase letters as something to add a space on):</p>\n\n<pre><code>re_outer = re.compile(r'([^A-Z ])([A-Z])')\nre_inner = re.compile(r'(?&lt;!^)([A-Z])([^A-Z])')\nre_outer.sub(r'\\1 \\2', re_inner.sub(r' \\1\\2', 'DaveIsAFKRightNow!Cool'))\n</code></pre>\n\n<p>The output will be: <code>'Dave Is AFK Right Now! Cool'</code></p>\n" }, { "answer_id": 67114560, "author": "Srini", "author_id": 1939379, "author_profile": "https://Stackoverflow.com/users/1939379", "pm_score": 0, "selected": false, "text": "<p>To the old thread - wanted to try an option for one of my requirements. Of course the <code>re.sub()</code> is the cool solution, but also got a 1 liner if re module isn't (or shouldn't be) imported.</p>\n<pre class=\"lang-py prettyprint-override\"><code>st = 'ThisIsTextStringToSplitWithSpace'\nprint(''.join([' '+ s if s.isupper() else s for s in st]).lstrip())\n</code></pre>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19074/" ]
I've got a file whose format I'm altering via a python script. I have several camel cased strings in this file where I just want to insert a single space before the capital letter - so "WordWordWord" becomes "Word Word Word". My limited regex experience just stalled out on me - can someone think of a decent regex to do this, or (better yet) is there a more pythonic way to do this that I'm missing?
You could try: ``` >>> re.sub(r"(\w)([A-Z])", r"\1 \2", "WordWordWord") 'Word Word Word' ```
199,065
<p>I've declared Javascript arrays in such a way that I could then access them by a key, but it was a long time ago, and I've forgotten how I did it.</p> <p>Basically, I have two fields I want to store, a unique key, and its value. I know there is a way to do it.. something like:</p> <pre><code>var jsArray = new {key: 'test test', value: 'value value'}, new {key: 'test 2', value: 'value 2'}; </code></pre> <p>and accessed like:</p> <pre><code>value = jsArray[key] </code></pre> <p>Can someone remind me?</p>
[ { "answer_id": 199083, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 4, "selected": true, "text": "<p>You can do it in different ways:</p>\n\n<pre><code>var a = {'a':0, 'b':1, 'c':2};\n\nvar b = new Array();\nb['a'] = 0;\nb['b'] = 1;\nb['c'] = 2;\n\nvar c = new Object();\nc.a = 0;\nc.b = 1;\nc.c = 2;\n</code></pre>\n" }, { "answer_id": 199093, "author": "aaaidan", "author_id": 26331, "author_profile": "https://Stackoverflow.com/users/26331", "pm_score": 2, "selected": false, "text": "<pre><code>var myFancyDictionary = {\n key: 'value',\n anotherKey: 'anotherValue',\n youGet: 'the idea'\n}\n</code></pre>\n" }, { "answer_id": 199097, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>If you are already using Prototype, try using its Hash. If using jQuery, try using Map.</p>\n" }, { "answer_id": 199114, "author": "rp.", "author_id": 2536, "author_profile": "https://Stackoverflow.com/users/2536", "pm_score": -1, "selected": false, "text": "<p>Here is a JavaScript class that provides a simple dictionary.</p>\n\n<pre><code>if( typeof( rp ) == \"undefined\" ) rp = {};\n\nrp.clientState = new function()\n{\n this.items = new Object();\n this.length = 0;\n\n this.set = function( key, value )\n {\n if ( ! this.keyExists( key ) )\n {\n this.length++;\n }\n this.items[ key ] = value; \n }\n\n this.get = function( key )\n {\n if ( this.keyExists( key ) )\n {\n return this.items[ key ];\n } \n }\n\n this.keyExists = function( key )\n {\n return typeof( this.items[ key ] ) != \"undefined\"; \n }\n\n this.remove = function( key )\n {\n if ( this.keyExists( key ) )\n {\n delete this.items[ key ];\n this.length--; \n return true;\n }\n return false;\n }\n\n this.removeAll = function()\n {\n this.items = null;\n this.items = new Object();\n this.length = 0;\n }\n}\n</code></pre>\n\n<p>Example use:</p>\n\n<pre><code>// Add a value pair.\nrp.clientState.set( key, value );\n\n// Fetch a value.\nvar x = rp.clientState.Get( key );\n\n// Check to see if a key exists.\nif ( rp.clientState.keyExists( key ) \n{\n // Do something.\n}\n\n// Remove a key.\nrp.clientState.remove( key );\n\n// Remove all keys.\nrp.clientState.removeAll();\n</code></pre>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
I've declared Javascript arrays in such a way that I could then access them by a key, but it was a long time ago, and I've forgotten how I did it. Basically, I have two fields I want to store, a unique key, and its value. I know there is a way to do it.. something like: ``` var jsArray = new {key: 'test test', value: 'value value'}, new {key: 'test 2', value: 'value 2'}; ``` and accessed like: ``` value = jsArray[key] ``` Can someone remind me?
You can do it in different ways: ``` var a = {'a':0, 'b':1, 'c':2}; var b = new Array(); b['a'] = 0; b['b'] = 1; b['c'] = 2; var c = new Object(); c.a = 0; c.b = 1; c.c = 2; ```
199,068
<p>Is it possible to play video from data that has been embedded in a swf at compile time (with the <code>[Embed]</code> metatag)?</p> <p>The "Import Video->Embed" feature provided by Flash CS3 etc. is not acceptable because it has many severe limitations (including sound synchronization issues, a maximum number of frames, and other caveats)</p> <p>I'm interested in being able to bundle flv video data in a swf (along with other assets), which will be played by an AIR application.</p> <p>I don't think it can be done. Anyone disagree?</p>
[ { "answer_id": 199125, "author": "James Fassett", "author_id": 27081, "author_profile": "https://Stackoverflow.com/users/27081", "pm_score": 2, "selected": false, "text": "<p>You can import a flv into a swf file using the Flash IDE - I've done that before. You can drop it onto the timeline of a MovieClip just like a sound and then drop that movieclip onto the stage for it to play. In Flash CS3 do File>Import>Import Video and select the flv. Choose the video and then on the next stop of the wizard choose \"Embed ..... \", Here is a link to an <a href=\"http://www.adobe.com/devnet/flash/articles/video_guide_02.html#embedding\" rel=\"nofollow noreferrer\">Adobe Developer center article on embedding flvs into swfs</a>.</p>\n\n<p>I have not done so myself, but I can see no reason why you could access the flv from the library of a loaded swf.</p>\n\n<p>FYI: It looks like this was a bug that was deferred. It doesn't look like Adobe currently allows embedding using the Embed meta tag. Here is a <a href=\"http://www.kirupa.com/forum/showthread.php?t=274183\" rel=\"nofollow noreferrer\">forum post</a> on the issue and a link to the <a href=\"https://bugs.adobe.com/jira/browse/SDK-259\" rel=\"nofollow noreferrer\">bug tracker</a>.</p>\n" }, { "answer_id": 201713, "author": "hasseg", "author_id": 4111, "author_profile": "https://Stackoverflow.com/users/4111", "pm_score": 1, "selected": false, "text": "<p>It's possible to embed video into SWFs with the Flash IDE but it's not a very good option:</p>\n\n<blockquote>\n <p><em>\"Playback is limited to simple play and stop commands, and the video\n framerate must match that of the host\n movie, an important consideration that\n will require authoring for the\n lowest-common-denominator download\n speed.\"</em></p>\n \n <p><em>\"The biggest limitations to embedded\n video are movies having a maximum of\n 16,000 frames and audio sync cannot be\n maintained beyond about two minutes.\"</em></p>\n</blockquote>\n\n<p>Those quotes are from <a href=\"http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_14571\" rel=\"nofollow noreferrer\">this article</a>. It's a bit old but as far as I know, what is said there about embedding video still holds true.</p>\n" }, { "answer_id": 2519192, "author": "aaaidan", "author_id": 26331, "author_profile": "https://Stackoverflow.com/users/26331", "pm_score": 0, "selected": false, "text": "<p>Oh yeah, so apparently you can embed binary data in a swf using the <code>Embed</code> meta tag. </p>\n\n<pre><code>[Embed(\n source=\"local_data_file.flv\",\n mimeType=\"application/octet-stream\") ]\nprivate static var __FlvClass123:Class;\nprotected static var flvData:ByteArray = new __FlvClass123();\n</code></pre>\n\n<p>Whether you can playback embedded video from a ByteArray or not is not something I cannot answer one way or another at this stage ...</p>\n" }, { "answer_id": 9887078, "author": "Thom", "author_id": 24618, "author_profile": "https://Stackoverflow.com/users/24618", "pm_score": 4, "selected": true, "text": "<p>As long as your video is an FLV, then the answer is yes - you can use <code>NetStream.appendBytes()</code> to play the embedded <code>ByteArray</code>:</p>\n\n<pre><code>public class Main extends MovieClip\n{\n [Embed(source=\"sample.flv\", mimeType=\"application/octet-stream\")]\n private var SampleVideo:Class;\n\n public function Main():void \n {\n var video:Video = new Video(320, 240);\n addChild(video);\n\n var netConnection:NetConnection = new NetConnection();\n netConnection.connect(null);\n var netStream:NetStream = new NetStream(netConnection);\n netStream.client = {};\n video.attachNetStream(netStream);\n\n var byteArray:ByteArray = new SampleVideo();\n netStream.play(null);\n netStream.appendBytes(byteArray);\n }\n}\n</code></pre>\n" }, { "answer_id": 50616790, "author": "George Hummet", "author_id": 9469669, "author_profile": "https://Stackoverflow.com/users/9469669", "pm_score": 0, "selected": false, "text": "<p>just had the same problem and searched for a more \"flex\"ible solution.\nseems these Days dynamic embedding works perfectly simple:</p>\n\n<pre><code>public function loadSWF(){\n\n var _assetLdr:Loader;\n_assetLdr = new Loader();\n_assetLdr.load(new URLRequest(\"1.swf\"));\n_assetLdr.contentLoaderInfo.addEventListener(Event.COMPLETE, this.handleComplete);\naddChild(_assetLdr); \n}\n\n\npublic function handleComplete(event:Event):void {\n\n trace(\"complete\");\n var loaderInfo:LoaderInfo=event.target as LoaderInfo;\n var content:MovieClip = loaderInfo.loader.content as MovieClip;\n addChild(content);\n\n}\n</code></pre>\n\n<p>Note: Check the screen offsets within the <code>library.swf</code>. In my case they were messed up, so it simply displayed offscreen. (ThankGodForCoffee)\nHave a nice Day!</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26331/" ]
Is it possible to play video from data that has been embedded in a swf at compile time (with the `[Embed]` metatag)? The "Import Video->Embed" feature provided by Flash CS3 etc. is not acceptable because it has many severe limitations (including sound synchronization issues, a maximum number of frames, and other caveats) I'm interested in being able to bundle flv video data in a swf (along with other assets), which will be played by an AIR application. I don't think it can be done. Anyone disagree?
As long as your video is an FLV, then the answer is yes - you can use `NetStream.appendBytes()` to play the embedded `ByteArray`: ``` public class Main extends MovieClip { [Embed(source="sample.flv", mimeType="application/octet-stream")] private var SampleVideo:Class; public function Main():void { var video:Video = new Video(320, 240); addChild(video); var netConnection:NetConnection = new NetConnection(); netConnection.connect(null); var netStream:NetStream = new NetStream(netConnection); netStream.client = {}; video.attachNetStream(netStream); var byteArray:ByteArray = new SampleVideo(); netStream.play(null); netStream.appendBytes(byteArray); } } ```
199,080
<p>A similar question was asked <a href="https://stackoverflow.com/questions/198931/how-do-i-tell-if-net-35-sp1-is-installed">here</a>, but it was specific to .NET 3.5. Specifically, I'm looking for the following:</p> <ol> <li>What is the correct way to determine which .NET Framework versions and service packs are installed?</li> <li>Is there a list of registry keys that can be used?</li> <li>Are there any dependencies between Framework versions?</li> </ol>
[ { "answer_id": 199121, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 3, "selected": false, "text": "<p>Enumerate the subkeys of <code>HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP</code>. Each subkey is a <a href=\"http://en.wikipedia.org/wiki/.NET_Framework\" rel=\"nofollow noreferrer\">.NET</a> version. It should have <code>Install=1</code> value if it's present on the machine, an SP value that shows the service pack and an <code>MSI=1</code> value if it was installed using an MSI. (.NET 2.0 on Windows&nbsp;Vista doesn't have the last one for example, as it is part of the OS.)</p>\n" }, { "answer_id": 199783, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 10, "selected": true, "text": "<p>The registry is <a href=\"https://learn.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-determine-which-versions-are-installed\" rel=\"noreferrer\">the official way</a> to detect if a specific version of the Framework is installed. </p>\n\n<p><img src=\"https://i.stack.imgur.com/hiLch.png\" alt=\"enter image description here\"></p>\n\n<p>Which registry keys are needed change depending on the Framework version you are looking for:</p>\n\n<pre>\nFramework Version Registry Key\n------------------------------------------------------------------------------------------\n1.0 HKLM\\Software\\Microsoft\\.NETFramework\\Policy\\v1.0\\3705 \n1.1 HKLM\\Software\\Microsoft\\NET Framework Setup\\NDP\\v1.1.4322\\Install \n2.0 HKLM\\Software\\Microsoft\\NET Framework Setup\\NDP\\v2.0.50727\\Install \n3.0 HKLM\\Software\\Microsoft\\NET Framework Setup\\NDP\\v3.0\\Setup\\InstallSuccess \n3.5 HKLM\\Software\\Microsoft\\NET Framework Setup\\NDP\\v3.5\\Install \n4.0 Client Profile HKLM\\Software\\Microsoft\\NET Framework Setup\\NDP\\v4\\Client\\Install\n4.0 Full Profile HKLM\\Software\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\Install\n</pre>\n\n<p>Generally you are looking for:</p>\n\n<pre><code>\"Install\"=dword:00000001\n</code></pre>\n\n<p>except for .NET 1.0, where the value is a string (<code>REG_SZ</code>) rather than a number (<code>REG_DWORD</code>).</p>\n\n<p>Determining the service pack level follows a similar pattern:</p>\n\n<pre>\nFramework Version Registry Key\n------------------------------------------------------------------------------------------\n1.0 HKLM\\Software\\Microsoft\\Active Setup\\Installed Components\\{78705f0d-e8db-4b2d-8193-982bdda15ecd}\\Version \n1.0[1] HKLM\\Software\\Microsoft\\Active Setup\\Installed Components\\{FDC11A6F-17D1-48f9-9EA3-9051954BAA24}\\Version \n1.1 HKLM\\Software\\Microsoft\\NET Framework Setup\\NDP\\v1.1.4322\\SP \n2.0 HKLM\\Software\\Microsoft\\NET Framework Setup\\NDP\\v2.0.50727\\SP \n3.0 HKLM\\Software\\Microsoft\\NET Framework Setup\\NDP\\v3.0\\SP \n3.5 HKLM\\Software\\Microsoft\\NET Framework Setup\\NDP\\v3.5\\SP \n4.0 Client Profile HKLM\\Software\\Microsoft\\NET Framework Setup\\NDP\\v4\\Client\\Servicing\n4.0 Full Profile HKLM\\Software\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\Servicing\n\n[1] Windows Media Center or Windows XP Tablet Edition\n</pre>\n\n<p>As you can see, determining the SP level for .NET 1.0 changes if you are running on Windows Media Center or Windows XP Tablet Edition. Again, .NET 1.0 uses a string value while all of the others use a DWORD.</p>\n\n<p>For .NET 1.0 the string value at either of these keys has a format of #,#,####,#. The last # is the Service Pack level.</p>\n\n<p>While I didn't explicitly ask for this, if you want to know the exact version number of the Framework you would use these registry keys:</p>\n\n<pre>\nFramework Version Registry Key\n------------------------------------------------------------------------------------------\n1.0 HKLM\\Software\\Microsoft\\Active Setup\\Installed Components\\{78705f0d-e8db-4b2d-8193-982bdda15ecd}\\Version \n1.0[1] HKLM\\Software\\Microsoft\\Active Setup\\Installed Components\\{FDC11A6F-17D1-48f9-9EA3-9051954BAA24}\\Version \n1.1 HKLM\\Software\\Microsoft\\NET Framework Setup\\NDP\\v1.1.4322 \n2.0[2] HKLM\\Software\\Microsoft\\NET Framework Setup\\NDP\\v2.0.50727\\Version \n2.0[3] HKLM\\Software\\Microsoft\\NET Framework Setup\\NDP\\v2.0.50727\\Increment\n3.0 HKLM\\Software\\Microsoft\\NET Framework Setup\\NDP\\v3.0\\Version \n3.5 HKLM\\Software\\Microsoft\\NET Framework Setup\\NDP\\v3.5\\Version \n4.0 Client Profile HKLM\\Software\\Microsoft\\NET Framework Setup\\NDP\\v4\\Version \n4.0 Full Profile HKLM\\Software\\Microsoft\\NET Framework Setup\\NDP\\v4\\Version \n\n[1] Windows Media Center or Windows XP Tablet Edition\n[2] .NET 2.0 SP1\n[3] .NET 2.0 Original Release (RTM)\n</pre>\n\n<p>Again, .NET 1.0 uses a string value while all of the others use a DWORD.</p>\n\n<h2>Additional Notes</h2>\n\n<ul>\n<li><p>for .NET 1.0 the string value at either of these keys has a format of <code>#,#,####,#</code>. The <code>#,#,####</code> portion of the string is the Framework version.</p></li>\n<li><p>for .NET 1.1, we use the name of the registry key itself, which represents the version number.</p></li>\n<li><p>Finally, if you look at dependencies, .NET 3.0 adds additional functionality to .NET 2.0 so both .NET 2.0 and .NET 3.0 must both evaulate as being installed to correctly say that .NET 3.0 is installed. Likewise, .NET 3.5 adds additional functionality to .NET 2.0 and .NET 3.0, so .NET 2.0, .NET 3.0, and .NET 3. should all evaluate to being installed to correctly say that .NET 3.5 is installed.</p></li>\n<li><p>.NET 4.0 installs a new version of the CLR (CLR version 4.0) which can run side-by-side with CLR 2.0.</p></li>\n</ul>\n\n<h2>Update for .NET 4.5</h2>\n\n<p>There won't be a <code>v4.5</code> key in the registry if .NET 4.5 is installed. Instead you have to check if the <code>HKLM\\Software\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full</code> key contains a value called <code>Release</code>. If this value is present, .NET 4.5 is installed, otherwise it is not. More details can be found <a href=\"https://stackoverflow.com/a/15227828/270591\">here</a> and <a href=\"https://learn.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-determine-which-versions-are-installed\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 644266, "author": "mapache", "author_id": 41422, "author_profile": "https://Stackoverflow.com/users/41422", "pm_score": 2, "selected": false, "text": "<p>Using the <a href=\"http://www.signumframework.com/Default.aspx?Page=Others&amp;AspxAutoDetectCookieSupport=1#AboutTools\" rel=\"nofollow noreferrer\">Signum.Utilities</a> library from <a href=\"http://www.signumframework.com\" rel=\"nofollow noreferrer\">SignumFramework</a> (which you can use stand-alone), you can get it nicely and without dealing with the registry by yourself:</p>\n\n<pre><code>AboutTools.FrameworkVersions().ToConsole();\n//Writes in my machine:\n//v2.0.50727 SP2\n//v3.0 SP2\n//v3.5 SP1\n</code></pre>\n" }, { "answer_id": 2451408, "author": "midspace", "author_id": 294393, "author_profile": "https://Stackoverflow.com/users/294393", "pm_score": 4, "selected": false, "text": "<p>The Framework 4 beta installs to a differing registry key.</p>\n\n<pre><code>using System;\nusing System.Collections.ObjectModel;\nusing Microsoft.Win32;\n\nclass Program\n{\n static void Main(string[] args)\n {\n foreach(Version ver in InstalledDotNetVersions())\n Console.WriteLine(ver);\n\n Console.ReadKey();\n }\n\n\n public static Collection&lt;Version&gt; InstalledDotNetVersions()\n {\n Collection&lt;Version&gt; versions = new Collection&lt;Version&gt;();\n RegistryKey NDPKey = Registry.LocalMachine.OpenSubKey(@\"SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\");\n if (NDPKey != null)\n {\n string[] subkeys = NDPKey.GetSubKeyNames();\n foreach (string subkey in subkeys)\n {\n GetDotNetVersion(NDPKey.OpenSubKey(subkey), subkey, versions);\n GetDotNetVersion(NDPKey.OpenSubKey(subkey).OpenSubKey(\"Client\"), subkey, versions);\n GetDotNetVersion(NDPKey.OpenSubKey(subkey).OpenSubKey(\"Full\"), subkey, versions);\n }\n }\n return versions;\n }\n\n private static void GetDotNetVersion(RegistryKey parentKey, string subVersionName, Collection&lt;Version&gt; versions)\n {\n if (parentKey != null)\n {\n string installed = Convert.ToString(parentKey.GetValue(\"Install\"));\n if (installed == \"1\")\n {\n string version = Convert.ToString(parentKey.GetValue(\"Version\"));\n if (string.IsNullOrEmpty(version))\n {\n if (subVersionName.StartsWith(\"v\"))\n version = subVersionName.Substring(1);\n else\n version = subVersionName;\n }\n\n Version ver = new Version(version);\n\n if (!versions.Contains(ver))\n versions.Add(ver);\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 2810884, "author": "abhishek mehta", "author_id": 338291, "author_profile": "https://Stackoverflow.com/users/338291", "pm_score": 3, "selected": false, "text": "<p>For a 64-bit OS, the path would be:</p>\n\n<pre><code>HKEY_LOCAL_MACHINE\\SOFTWARE\\wow6432Node\\Microsoft\\NET Framework Setup\\NDP\\\n</code></pre>\n" }, { "answer_id": 3087128, "author": "anon", "author_id": 372426, "author_profile": "https://Stackoverflow.com/users/372426", "pm_score": 4, "selected": false, "text": "<p>There is an official Microsoft answer to this question at the following knowledge base article:</p>\n\n<p><a href=\"http://support.microsoft.com/kb/318785/en-us\" rel=\"noreferrer\">Article ID: 318785 - Last Review: November 7, 2008 - Revision: 20.1\nHow to determine which versions of the .NET Framework are installed and whether service packs have been applied</a></p>\n\n<p>Unfortunately, it doesn't appear to work, because the mscorlib.dll version in the 2.0 directory has a 2.0 version, and there is no mscorlib.dll version in either the 3.0 or 3.5 directories even though 3.5 SP1 is installed ... why would the official Microsoft answer be so misinformed?</p>\n" }, { "answer_id": 10242199, "author": "Kudzai K", "author_id": 1345946, "author_profile": "https://Stackoverflow.com/users/1345946", "pm_score": 2, "selected": false, "text": "<p>I was needing to find out just which version of .NET framework I had on my computer, and all I did was go to the control panel and select the \"Uninstall a Program\" option. After that, I sorted the programs by name, and found Microsoft .NET Framework 4 Client Profile.</p>\n" }, { "answer_id": 19560439, "author": "Olivier de Rivoyre", "author_id": 740362, "author_profile": "https://Stackoverflow.com/users/740362", "pm_score": 1, "selected": false, "text": "<p>See <em><a href=\"http://msdn.microsoft.com/en-us/library/hh925568.aspx\" rel=\"nofollow\">How to: Determine Which .NET Framework Versions Are Installed</a></em> (MSDN).</p>\n\n<p>MSDN proposes one function example that seems to do the job for version 1-4. According to the article, the method output is:</p>\n\n<pre><code>v2.0.50727 2.0.50727.4016 SP2\nv3.0 3.0.30729.4037 SP2\nv3.5 3.5.30729.01 SP1\nv4\n Client 4.0.30319\n Full 4.0.30319\n</code></pre>\n\n<p>Note that for \"versions 4.5 and later\" there is another function.</p>\n" }, { "answer_id": 20539905, "author": "JasonMcF", "author_id": 2728374, "author_profile": "https://Stackoverflow.com/users/2728374", "pm_score": 3, "selected": false, "text": "<h2>Update for .NET 4.5.1</h2>\n\n<p>Now that .NET 4.5.1 is available the actual value of the key named Release in the registry needs to be checked, not just its existence. A value of 378758 means that .NET Framework 4.5.1 is installed. However, as described <a href=\"http://blogs.msdn.com/b/astebner/archive/2013/11/11/10466402.aspx\" rel=\"noreferrer\">here</a> this value is 378675 on Windows 8.1.</p>\n" }, { "answer_id": 20554361, "author": "CarlR", "author_id": 849865, "author_profile": "https://Stackoverflow.com/users/849865", "pm_score": 3, "selected": false, "text": "<p>There is a GUI tool available, <em><a href=\"http://www.asoft.be/prod_netver.html\" rel=\"nofollow\">ASoft .NET Version Detector</a></em>, which has always proven highly reliable. It can create XML files by specifying the file name of the XML output on the command line.</p>\n\n<p>You could use this for automation. It is a tiny program, written in a non-.NET dependent language and does not require installation.</p>\n" }, { "answer_id": 23349906, "author": "Mayank Agarwal", "author_id": 1643414, "author_profile": "https://Stackoverflow.com/users/1643414", "pm_score": 1, "selected": false, "text": "<p>In Windows 7 (it should work for Windows&nbsp;8 also, but I haven't tested it):</p>\n\n<p>Go to a command prompt</p>\n\n<p>Steps to go to a command prompt:</p>\n\n<ol>\n<li>Click Start Menu</li>\n<li>In Search Box, type \"cmd\" (without quotes)</li>\n<li>Open cmd.exe</li>\n</ol>\n\n<p>In cmd, type this command</p>\n\n<pre><code>wmic /namespace:\\\\root\\cimv2 path win32_product where \"name like '%%.NET%%'\" get version\n</code></pre>\n\n<p>This gives the latest version of NET Framework installed.</p>\n\n<p>One can also try <a href=\"https://www.raymond.cc/blog/how-to-check-what-version-of-microsoft-net-framework-is-installed-in-computer/\" rel=\"nofollow\">Raymond.cc Utilties</a> for the same.</p>\n" }, { "answer_id": 29891512, "author": "Faisal Mq", "author_id": 379916, "author_profile": "https://Stackoverflow.com/users/379916", "pm_score": 3, "selected": false, "text": "<p>I wanted to detect for the presence of .NET version 4.5.2 installed on my system, and I found no better solution than <em><a href=\"http://www.asoft.be/prod_netver.html\">ASoft .NET Version Detector</a></em>.</p>\n\n<p>Snapshot of this tool showing different .NET versions:</p>\n\n<p><img src=\"https://i.stack.imgur.com/GomST.png\" alt=\"Snapshot of this tool showing different .NET versions\"></p>\n" }, { "answer_id": 34773812, "author": "cezarypiatek", "author_id": 876060, "author_profile": "https://Stackoverflow.com/users/876060", "pm_score": 2, "selected": false, "text": "<p>Here is a PowerShell script to obtain installed .NET framework versions</p>\n\n<pre><code>function Get-KeyPropertyValue($key, $property)\n{\n if($key.Property -contains $property)\n {\n Get-ItemProperty $key.PSPath -name $property | select -expand $property\n }\n}\n\nfunction Get-VersionName($key)\n{\n $name = Get-KeyPropertyValue $key Version\n $sp = Get-KeyPropertyValue $key SP\n $install = Get-KeyPropertyValue $key Install\n if($sp)\n {\n \"$($_.PSChildName) $name SP $sp\"\n }\n else{\n \"$($_.PSChildName) $name\"\n }\n}\n\nfunction Get-FrameworkVersion{\n dir \"hklm:\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\\" |? {$_.PSChildName -like \"v*\"} |%{\n if( $_.Property -contains \"Version\")\n {\n Get-VersionName $_\n }\n else{\n $parent = $_\n Get-ChildItem $_.PSPath |%{\n $versionName = Get-VersionName $_\n \"$($parent.PSChildName) $versionName\"\n }\n }\n }\n}\n\n\n$v4Directory = \"hklm:\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\"\nif(Test-Path $v4Directory)\n{\n $v4 = Get-Item $v4Directory\n $version = Get-KeyPropertyValue $v4 Release\n switch($version){\n 378389 {\".NET Framework 4.5\"; break;}\n 378675 {\".NET Framework 4.5.1 installed with Windows 8.1 or Windows Server 2012 R2\"; break;}\n 378758 {\".NET Framework 4.5.1 installed on Windows 8, Windows 7 SP1, or Windows Vista SP2\"; break;}\n 379893 {\".NET Framework 4.5.2\"; break;}\n { 393295, 393297 -contains $_} {\".NET Framework 4.6\"; break;}\n { 394254, 394271 -contains $_} {\".NET Framework 4.6.1\"; break;}\n { 394802, 394806 -contains $_} {\".NET Framework 4.6.2\"; break; }\n }\n}\n</code></pre>\n\n<p>It was written based on <em><a href=\"https://msdn.microsoft.com/en-us/library/hh925568.aspx\" rel=\"nofollow noreferrer\">How to: Determine Which .NET Framework Versions Are Installed</a></em>. Please use THE Get-FrameworkVersion() function to get information about installed .NET framework versions.</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1559/" ]
A similar question was asked [here](https://stackoverflow.com/questions/198931/how-do-i-tell-if-net-35-sp1-is-installed), but it was specific to .NET 3.5. Specifically, I'm looking for the following: 1. What is the correct way to determine which .NET Framework versions and service packs are installed? 2. Is there a list of registry keys that can be used? 3. Are there any dependencies between Framework versions?
The registry is [the official way](https://learn.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-determine-which-versions-are-installed) to detect if a specific version of the Framework is installed. ![enter image description here](https://i.stack.imgur.com/hiLch.png) Which registry keys are needed change depending on the Framework version you are looking for: ``` Framework Version Registry Key ------------------------------------------------------------------------------------------ 1.0 HKLM\Software\Microsoft\.NETFramework\Policy\v1.0\3705 1.1 HKLM\Software\Microsoft\NET Framework Setup\NDP\v1.1.4322\Install 2.0 HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\Install 3.0 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.0\Setup\InstallSuccess 3.5 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\Install 4.0 Client Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Client\Install 4.0 Full Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Full\Install ``` Generally you are looking for: ``` "Install"=dword:00000001 ``` except for .NET 1.0, where the value is a string (`REG_SZ`) rather than a number (`REG_DWORD`). Determining the service pack level follows a similar pattern: ``` Framework Version Registry Key ------------------------------------------------------------------------------------------ 1.0 HKLM\Software\Microsoft\Active Setup\Installed Components\{78705f0d-e8db-4b2d-8193-982bdda15ecd}\Version 1.0[1] HKLM\Software\Microsoft\Active Setup\Installed Components\{FDC11A6F-17D1-48f9-9EA3-9051954BAA24}\Version 1.1 HKLM\Software\Microsoft\NET Framework Setup\NDP\v1.1.4322\SP 2.0 HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\SP 3.0 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.0\SP 3.5 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\SP 4.0 Client Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Client\Servicing 4.0 Full Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Full\Servicing [1] Windows Media Center or Windows XP Tablet Edition ``` As you can see, determining the SP level for .NET 1.0 changes if you are running on Windows Media Center or Windows XP Tablet Edition. Again, .NET 1.0 uses a string value while all of the others use a DWORD. For .NET 1.0 the string value at either of these keys has a format of #,#,####,#. The last # is the Service Pack level. While I didn't explicitly ask for this, if you want to know the exact version number of the Framework you would use these registry keys: ``` Framework Version Registry Key ------------------------------------------------------------------------------------------ 1.0 HKLM\Software\Microsoft\Active Setup\Installed Components\{78705f0d-e8db-4b2d-8193-982bdda15ecd}\Version 1.0[1] HKLM\Software\Microsoft\Active Setup\Installed Components\{FDC11A6F-17D1-48f9-9EA3-9051954BAA24}\Version 1.1 HKLM\Software\Microsoft\NET Framework Setup\NDP\v1.1.4322 2.0[2] HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\Version 2.0[3] HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\Increment 3.0 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.0\Version 3.5 HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\Version 4.0 Client Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Version 4.0 Full Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Version [1] Windows Media Center or Windows XP Tablet Edition [2] .NET 2.0 SP1 [3] .NET 2.0 Original Release (RTM) ``` Again, .NET 1.0 uses a string value while all of the others use a DWORD. Additional Notes ---------------- * for .NET 1.0 the string value at either of these keys has a format of `#,#,####,#`. The `#,#,####` portion of the string is the Framework version. * for .NET 1.1, we use the name of the registry key itself, which represents the version number. * Finally, if you look at dependencies, .NET 3.0 adds additional functionality to .NET 2.0 so both .NET 2.0 and .NET 3.0 must both evaulate as being installed to correctly say that .NET 3.0 is installed. Likewise, .NET 3.5 adds additional functionality to .NET 2.0 and .NET 3.0, so .NET 2.0, .NET 3.0, and .NET 3. should all evaluate to being installed to correctly say that .NET 3.5 is installed. * .NET 4.0 installs a new version of the CLR (CLR version 4.0) which can run side-by-side with CLR 2.0. Update for .NET 4.5 ------------------- There won't be a `v4.5` key in the registry if .NET 4.5 is installed. Instead you have to check if the `HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Full` key contains a value called `Release`. If this value is present, .NET 4.5 is installed, otherwise it is not. More details can be found [here](https://stackoverflow.com/a/15227828/270591) and [here](https://learn.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-determine-which-versions-are-installed).
199,092
<p>I have a stub Qt application and I keep getting compiler errors</p> <pre><code>#include &lt;QApplication&gt; int main(int argc, char *argv[]) { return 0; } </code></pre> <p>I used <code>qmake -project</code> and <code>qmake</code> commands and as far as I can tell they did their job correctly. When I subsequently call <code>make</code> at the command line I get the following error:</p> <blockquote> <pre><code>g++ -c -O2 -frtti -fexceptions -mthreads -Wall -DUNICODE -DQT_LARGEFILE_SUPPORT -DQT_NO_DEBUG -DQT_GUI_LIB -DQT_CORE_LIB -DQT_THREAD_SUPPORT -DQT_NEEDS_QMAIN -I '../../../../qt/include/QtCore' -I'../../../../qt/include/QtCore' -I'../../../.. /qt/include/QtGui' -I'../../../../qt/include/QtGui' -I'../../../../qt/include' - I'.' -I'c:/qt/include/ActiveQt' -I'release' -I'.' -I'../../../../qt/mkspecs/defa ult' -o release/Main.o Main.cpp cc1plus.exe: Invalid option 'threads' make[1]: *** [release/Main.o] Error 1 make: *** [release] Error 2 </code></pre> </blockquote> <p>My searches on Google tell me that threading is important to keep but not how to fix this error. Any help will be appreciated.</p> <p><strong>EDIT</strong> (copied from an answer the OP left):</p> <p>I now get:</p> <pre><code>g++ -enable-stdcall-fixup -Wl,-enable-auto-import -Wl,-enable-runtime-pseudo-rel oc -Wl,-s -pthread -Wl -Wl,-subsystem,windows -o release/raytrace.exe object_scr ipt.raytrace.Release -L'c:/qt/lib' -lmingw32 -lqtmain -lQtGui -lgdi32 -lcomdlg3 2 -loleaut32 -limm32 -lwinmm -lwinspool -lmsimg32 -lQtCore -lkernel32 -luser32 - lshell32 -luuid -lole32 -ladvapi32 -lws2_32 g++: unrecognized option `-pthread' /cygnus/cygwin-b20/H-i586-cygwin32/i586-cygwin32/bin/ld: cannot open -lmsimg32: No such file or directory collect2: ld returned 1 exit status make[1]: *** [release/raytrace.exe] Error 1 make: *** [release] Error 2 </code></pre>
[ { "answer_id": 199552, "author": "Adam Mitz", "author_id": 2574, "author_profile": "https://Stackoverflow.com/users/2574", "pm_score": 0, "selected": false, "text": "<p>Based on the later response from the questioner, not the original question.</p>\n\n<p>From the MSYS prompt run \"ls /mingw/lib/libmsimg32.a\" and see if you have that file. My installation does (MinGW GCC 3.4.5). If you have that file you may need to add -L/mingw/lib. If you don't have the file you may have missed installing the windows api part of MinGW.</p>\n\n<p>Either way remove -pthread. You're using the Win32 api.</p>\n\n<p>If this doesn't work you need to specify which version of MinGW you're using and, if you're using MSYS, which version of MSYS.</p>\n" }, { "answer_id": 199566, "author": "milot", "author_id": 22637, "author_profile": "https://Stackoverflow.com/users/22637", "pm_score": 2, "selected": false, "text": "<p>Well I had similar problem before when I was installing MingW downloaded from the web, but in the other hand while installing Qt it will ask you to download the version of MingW which is compatible with Qt. So have you tried installing it when the Qt installer asked you?</p>\n" }, { "answer_id": 202390, "author": "Chris Roland", "author_id": 27975, "author_profile": "https://Stackoverflow.com/users/27975", "pm_score": 2, "selected": false, "text": "<p>++milot </p>\n\n<p>I only use MinGW to compile Qt on Windows and that's the easiest way to make sure you have everything you need.</p>\n\n<p>Here is the link for the Open Source Qt version:\n<a href=\"http://trolltech.com/downloads/opensource/appdev/windows-cpp\" rel=\"nofollow noreferrer\">http://trolltech.com/downloads/opensource/appdev/windows-cpp</a></p>\n\n<p>Use the \"Or download Qt with the MinGW compiler included: Size: 149,3 Mb\" link.</p>\n\n<p>The other way to use MinGW is to compile Qt with MinGW and then compile your application, but it depends on if you're compiling in MSYS or just using MinGW.</p>\n" }, { "answer_id": 969597, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Qt 4.5 has Qt Creator 1.1 which is easy to develop applications.</p>\n\n<p>Designing and coding is combined in Qt Creator and mucy easier to use.</p>\n\n<p>you can experience it like using VB IDE(or rather like eclipse,netbeans,etc.)</p>\n\n<p>when run the app. the project is compiled in either in debug or release mode.</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8923/" ]
I have a stub Qt application and I keep getting compiler errors ``` #include <QApplication> int main(int argc, char *argv[]) { return 0; } ``` I used `qmake -project` and `qmake` commands and as far as I can tell they did their job correctly. When I subsequently call `make` at the command line I get the following error: > > > ``` > g++ -c -O2 -frtti -fexceptions -mthreads -Wall -DUNICODE -DQT_LARGEFILE_SUPPORT > -DQT_NO_DEBUG -DQT_GUI_LIB -DQT_CORE_LIB -DQT_THREAD_SUPPORT -DQT_NEEDS_QMAIN -I > '../../../../qt/include/QtCore' -I'../../../../qt/include/QtCore' -I'../../../.. > /qt/include/QtGui' -I'../../../../qt/include/QtGui' -I'../../../../qt/include' - > I'.' -I'c:/qt/include/ActiveQt' -I'release' -I'.' -I'../../../../qt/mkspecs/defa > ult' -o release/Main.o Main.cpp > cc1plus.exe: Invalid option 'threads' > make[1]: *** [release/Main.o] Error 1 > make: *** [release] Error 2 > > ``` > > My searches on Google tell me that threading is important to keep but not how to fix this error. Any help will be appreciated. **EDIT** (copied from an answer the OP left): I now get: ``` g++ -enable-stdcall-fixup -Wl,-enable-auto-import -Wl,-enable-runtime-pseudo-rel oc -Wl,-s -pthread -Wl -Wl,-subsystem,windows -o release/raytrace.exe object_scr ipt.raytrace.Release -L'c:/qt/lib' -lmingw32 -lqtmain -lQtGui -lgdi32 -lcomdlg3 2 -loleaut32 -limm32 -lwinmm -lwinspool -lmsimg32 -lQtCore -lkernel32 -luser32 - lshell32 -luuid -lole32 -ladvapi32 -lws2_32 g++: unrecognized option `-pthread' /cygnus/cygwin-b20/H-i586-cygwin32/i586-cygwin32/bin/ld: cannot open -lmsimg32: No such file or directory collect2: ld returned 1 exit status make[1]: *** [release/raytrace.exe] Error 1 make: *** [release] Error 2 ```
Well I had similar problem before when I was installing MingW downloaded from the web, but in the other hand while installing Qt it will ask you to download the version of MingW which is compatible with Qt. So have you tried installing it when the Qt installer asked you?
199,099
<p>I'm using <code>$.post()</code> to call a servlet using Ajax and then using the resulting HTML fragment to replace a <code>div</code> element in the user's current page. However, if the session times out, the server sends a redirect directive to send the user to the login page. In this case, jQuery is replacing the <code>div</code> element with the contents of the login page, forcing the user's eyes to witness a rare scene indeed. </p> <p>How can I manage a redirect directive from an Ajax call with jQuery 1.2.6?</p>
[ { "answer_id": 199156, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 6, "selected": false, "text": "<p>Use the low-level <code>$.ajax()</code> call:</p>\n\n<pre><code>$.ajax({\n url: \"/yourservlet\",\n data: { },\n complete: function(xmlHttp) {\n // xmlHttp is a XMLHttpRquest object\n alert(xmlHttp.status);\n }\n});\n</code></pre>\n\n<p>Try this for a redirect:</p>\n\n<pre><code>if (xmlHttp.code != 200) {\n top.location.href = '/some/other/page';\n}\n</code></pre>\n" }, { "answer_id": 216245, "author": "Vladimir Prudnikov", "author_id": 29364, "author_profile": "https://Stackoverflow.com/users/29364", "pm_score": -1, "selected": false, "text": "<p>Additionally you will probably want to redirect user to the given in headers URL. So finally it will looks like this:</p>\n\n<pre><code>$.ajax({\n //.... other definition\n complete:function(xmlHttp){\n if(xmlHttp.status.toString()[0]=='3'){\n top.location.href = xmlHttp.getResponseHeader('Location');\n }\n});\n</code></pre>\n\n<p>UPD: Opps. Have the same task, but it not works. Doing this stuff. I'll show you solution when I'll find it.</p>\n" }, { "answer_id": 291376, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>in the servlet you should put \n<code>response.setStatus(response.SC_MOVED_PERMANENTLY);</code>\nto send the '301' xmlHttp status you need for a redirection...</p>\n\n<p>and in the $.ajax function you should not use the <code>.toString()</code> function..., just</p>\n\n<p><code>if (xmlHttp.status == 301) {\n top.location.href = 'xxxx.jsp';\n}</code></p>\n\n<p>the problem is it is not very flexible, you can't decide where you want to redirect..</p>\n\n<p>redirecting through the servlets should be the best way. but i still can not find the right way to do it.</p>\n" }, { "answer_id": 304654, "author": "Thomas Hansen", "author_id": 29746, "author_profile": "https://Stackoverflow.com/users/29746", "pm_score": 7, "selected": false, "text": "<p>No browsers handle 301 and 302 responses correctly. And in fact the standard even says they should handle them \"transparently\" which is a MASSIVE headache for Ajax Library vendors. In <a href=\"http://code.google.com/p/ra-ajax/\" rel=\"noreferrer\">Ra-Ajax</a> we were forced into using HTTP response status code 278 (just some \"unused\" success code) to handle transparently redirects from the server...</p>\n\n<p>This really annoys me, and if someone here have some \"pull\" in W3C I would appreciate that you could let W3C <em>know</em> that we really need to handle 301 and 302 codes ourselves...! ;)</p>\n" }, { "answer_id": 484541, "author": "Elliot Vargas", "author_id": 2024, "author_profile": "https://Stackoverflow.com/users/2024", "pm_score": 8, "selected": true, "text": "<p>The solution that was eventually implemented was to use a wrapper for the callback function of the Ajax call and in this wrapper check for the existence of a specific element on the returned HTML chunk. If the element was found then the wrapper executed a redirection. If not, the wrapper forwarded the call to the actual callback function. </p>\n\n<p>For example, our wrapper function was something like:</p>\n\n<pre><code>function cbWrapper(data, funct){\n if($(\"#myForm\", data).length &gt; 0)\n top.location.href=\"login.htm\";//redirection\n else\n funct(data);\n}\n</code></pre>\n\n<p>Then, when making the Ajax call we used something like:</p>\n\n<pre><code>$.post(\"myAjaxHandler\", \n {\n param1: foo,\n param2: bar\n },\n function(data){\n cbWrapper(data, myActualCB);\n }, \n \"html\"\n);\n</code></pre>\n\n<p>This worked for us because all Ajax calls always returned HTML inside a DIV element that we use to replace a piece of the page. Also, we only needed to redirect to the login page.</p>\n" }, { "answer_id": 579895, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": false, "text": "<p>I solved this issue by:</p>\n\n<ol>\n<li><p>Adding a custom header to the response:</p>\n\n<pre><code>public ActionResult Index(){\n if (!HttpContext.User.Identity.IsAuthenticated)\n {\n HttpContext.Response.AddHeader(\"REQUIRES_AUTH\",\"1\");\n }\n return View();\n}\n</code></pre></li>\n<li><p>Binding a JavaScript function to the <a href=\"http://api.jquery.com/ajaxsuccess/\" rel=\"noreferrer\"><code>ajaxSuccess</code></a> event and checking to see if the header exists:</p>\n\n<pre><code>$(document).ajaxSuccess(function(event, request, settings) {\n if (request.getResponseHeader('REQUIRES_AUTH') === '1') {\n window.location = '/';\n }\n});\n</code></pre></li>\n</ol>\n" }, { "answer_id": 1241149, "author": "Graham King", "author_id": 146620, "author_profile": "https://Stackoverflow.com/users/146620", "pm_score": 4, "selected": false, "text": "<p>Putting together what Vladimir Prudnikov and Thomas Hansen said:</p>\n\n<ul>\n<li>Change your server-side code to detect if it's an XHR. If it is, set the response code of the redirect to 278.\nIn django:</li>\n</ul>\n\n<blockquote>\n<pre><code> if request.is_ajax():\n response.status_code = 278\n</code></pre>\n</blockquote>\n\n<p>This makes the browser treat the response as a success, and hand it to your Javascript.</p>\n\n<ul>\n<li>In your JS, make sure the form submission is via Ajax, check the response code and redirect if needed:</li>\n</ul>\n\n<blockquote>\n<pre><code>$('#my-form').submit(function(event){ \n\n event.preventDefault(); \n var options = {\n url: $(this).attr('action'),\n type: 'POST',\n complete: function(response, textStatus) { \n if (response.status == 278) { \n window.location = response.getResponseHeader('Location')\n }\n else { ... your code here ... } \n },\n data: $(this).serialize(), \n }; \n $.ajax(options); \n});\n</code></pre>\n</blockquote>\n" }, { "answer_id": 1534662, "author": "Steg", "author_id": 121872, "author_profile": "https://Stackoverflow.com/users/121872", "pm_score": 10, "selected": false, "text": "<p>I read this question and implemented the approach that has been stated regarding setting the response <em>HTTP status code</em> to 278 in order to avoid the browser transparently handling the redirects. Even though this worked, I was a little dissatisfied as it is a bit of a hack.</p>\n\n<p>After more digging around, I ditched this approach and used <a href=\"http://en.wikipedia.org/wiki/JSON\" rel=\"noreferrer\">JSON</a>. In this case, all responses to AJAX requests have the <em>status code</em> 200 and the body of the response contains a JSON object that is constructed on the server. The JavaScript on the client can then use the JSON object to decide what it needs to do.</p>\n\n<p>I had a similar problem to yours. I perform an AJAX request that has 2 possible responses: one that <em>redirects</em> the browser to a new page and one that <em>replaces</em> an existing HTML form on the current page with a new one. The jQuery code to do this looks something like:</p>\n\n<pre><code>$.ajax({\n type: \"POST\",\n url: reqUrl,\n data: reqBody,\n dataType: \"json\",\n success: function(data, textStatus) {\n if (data.redirect) {\n // data.redirect contains the string URL to redirect to\n window.location.href = data.redirect;\n } else {\n // data.form contains the HTML for the replacement form\n $(\"#myform\").replaceWith(data.form);\n }\n }\n});\n</code></pre>\n\n<p>The JSON object \"data\" is constructed on the server to have 2 members: <code>data.redirect</code> and <code>data.form</code>. I found this approach to be much better.</p>\n" }, { "answer_id": 3408763, "author": "Bretticus", "author_id": 411075, "author_profile": "https://Stackoverflow.com/users/411075", "pm_score": 3, "selected": false, "text": "<p>I just wanted to latch on to any ajax requests for the entire page. @SuperG got me started. Here is what I ended up with:</p>\n\n<pre><code>// redirect ajax requests that are redirected, not found (404), or forbidden (403.)\n$('body').bind('ajaxComplete', function(event,request,settings){\n switch(request.status) {\n case 301: case 404: case 403: \n window.location.replace(\"http://mysite.tld/login\");\n break;\n }\n});\n</code></pre>\n\n<p>I wanted to specifically check for certain http status codes to base my decision on. However, you can just bind to ajaxError to get anything other than success (200 only perhaps?) I could have just written:</p>\n\n<pre><code>$('body').bind('ajaxError', function(event,request,settings){\n window.location.replace(\"http://mysite.tld/login\");\n}\n</code></pre>\n" }, { "answer_id": 3505514, "author": "Timmerz", "author_id": 408992, "author_profile": "https://Stackoverflow.com/users/408992", "pm_score": 4, "selected": false, "text": "<p>I have a simple solution that works for me, no server code change needed...just add a tsp of nutmeg...</p>\n\n<pre><code>$(document).ready(function ()\n{\n $(document).ajaxSend(\n function(event,request,settings)\n {\n var intercepted_success = settings.success;\n settings.success = function( a, b, c ) \n { \n if( request.responseText.indexOf( \"&lt;html&gt;\" ) &gt; -1 )\n window.location = window.location;\n else\n intercepted_success( a, b, c );\n };\n });\n});\n</code></pre>\n\n<p>I check the presence of html tag, but you can change the indexOf to search for whatever unique string exists in your login page...</p>\n" }, { "answer_id": 3861414, "author": "podeig", "author_id": 284405, "author_profile": "https://Stackoverflow.com/users/284405", "pm_score": 4, "selected": false, "text": "<p>Try</p>\n\n<pre><code> $(document).ready(function () {\n if ($(\"#site\").length &gt; 0) {\n window.location = \"&lt;%= Url.Content(\"~\") %&gt;\" + \"Login/LogOn\";\n }\n });\n</code></pre>\n\n<p>Put it on the login page. If it was loaded in a div on the main page, it will redirect til the login page. \"#site\" is a id of a div which is located on all pages except login page.</p>\n" }, { "answer_id": 7166385, "author": "BrianY", "author_id": 908376, "author_profile": "https://Stackoverflow.com/users/908376", "pm_score": 6, "selected": false, "text": "<p>I like Timmerz's method with a slight twist of lemon. If you ever get returned <strong>contentType</strong> of <strong>text/html</strong> when you're expecting <strong>JSON</strong>, you are most likely being redirected. In my case, I just simply reload the page, and it gets redirected to the login page. Oh, and check that the jqXHR status is 200, which seems silly, because you are in the error function, right? Otherwise, legitimate error cases will force an iterative reload (oops)</p>\n\n<pre><code>$.ajax(\n error: function (jqXHR, timeout, message) {\n var contentType = jqXHR.getResponseHeader(\"Content-Type\");\n if (jqXHR.status === 200 &amp;&amp; contentType.toLowerCase().indexOf(\"text/html\") &gt;= 0) {\n // assume that our login has expired - reload our current page\n window.location.reload();\n }\n\n});\n</code></pre>\n" }, { "answer_id": 7220299, "author": "Benny Jobigan", "author_id": 262748, "author_profile": "https://Stackoverflow.com/users/262748", "pm_score": 2, "selected": false, "text": "<p>I was having this problem on a django app I'm tinkering with (disclaimer: I'm tinkering to learn, and am in no way an expert). What I wanted to do was use jQuery ajax to send a DELETE request to a resource, delete it on the server side, then send a redirect back to (basically) the homepage. When I sent <code>HttpResponseRedirect('/the-redirect/')</code> from the python script, jQuery's ajax method was receiving 200 instead of 302. So, what I did was to send a response of 300 with:</p>\n\n<pre><code>response = HttpResponse(status='300')\nresponse['Location'] = '/the-redirect/' \nreturn response\n</code></pre>\n\n<p>Then I sent/handled the request on the client with jQuery.ajax like so:</p>\n\n<pre><code>&lt;button onclick=\"*the-jquery*\"&gt;Delete&lt;/button&gt;\n\nwhere *the-jquery* =\n$.ajax({ \n type: 'DELETE', \n url: '/resource-url/', \n complete: function(jqxhr){ \n window.location = jqxhr.getResponseHeader('Location'); \n } \n});\n</code></pre>\n\n<p>Maybe using 300 isn't \"right\", but at least it worked just like I wanted it to.</p>\n\n<p>PS :this was a huge pain to edit on the mobile version of SO. Stupid ISP put my service cancellation request through right when I was done with my answer! </p>\n" }, { "answer_id": 7373118, "author": "Priyanka", "author_id": 705876, "author_profile": "https://Stackoverflow.com/users/705876", "pm_score": 4, "selected": false, "text": "<pre><code> &lt;script&gt;\n function showValues() {\n var str = $(\"form\").serialize();\n $.post('loginUser.html', \n str,\n function(responseText, responseStatus, responseXML){\n if(responseStatus==\"success\"){\n window.location= \"adminIndex.html\";\n }\n }); \n }\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 8391074, "author": "Paul Richards", "author_id": 1082225, "author_profile": "https://Stackoverflow.com/users/1082225", "pm_score": 4, "selected": false, "text": "<p>I solved this by putting the following in my login.php page.</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n if (top.location.href.indexOf('login.php') == -1) {\n top.location.href = '/login.php';\n }\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 8752354, "author": "Tyr", "author_id": 547524, "author_profile": "https://Stackoverflow.com/users/547524", "pm_score": 5, "selected": false, "text": "<p>I resolved this issue like this:</p>\n\n<p>Add a middleware to process response, if it is a redirect for an ajax request, change the response to a normal response with the redirect url.</p>\n\n<pre><code>class AjaxRedirect(object):\n def process_response(self, request, response):\n if request.is_ajax():\n if type(response) == HttpResponseRedirect:\n r = HttpResponse(json.dumps({'redirect': response['Location']}))\n return r\n return response\n</code></pre>\n\n<p>Then in ajaxComplete, if the response contains redirect, it must be a redirect, so change the browser's location.</p>\n\n<pre><code>$('body').ajaxComplete(function (e, xhr, settings) {\n if (xhr.status == 200) {\n var redirect = null;\n try {\n redirect = $.parseJSON(xhr.responseText).redirect;\n if (redirect) {\n window.location.href = redirect.replace(/\\?.*$/, \"?next=\" + window.location.pathname);\n }\n } catch (e) {\n return;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 10095275, "author": "Curtis Yallop", "author_id": 854342, "author_profile": "https://Stackoverflow.com/users/854342", "pm_score": 2, "selected": false, "text": "<p>You can also hook XMLHttpRequest send prototype. This will work for all sends (jQuery/dojo/etc) with one handler.</p>\n\n<p>I wrote this code to handle a 500 page expired error, but it should work just as well to trap a 200 redirect. Ready the wikipedia entry on <a href=\"http://en.wikipedia.org/wiki/XMLHttpRequest\" rel=\"nofollow\">XMLHttpRequest</a> onreadystatechange about the meaning of readyState.</p>\n\n<pre><code>// Hook XMLHttpRequest\nvar oldXMLHttpRequestSend = XMLHttpRequest.prototype.send;\n\nXMLHttpRequest.prototype.send = function() {\n //console.dir( this );\n\n this.onreadystatechange = function() {\n if (this.readyState == 4 &amp;&amp; this.status == 500 &amp;&amp; this.responseText.indexOf(\"Expired\") != -1) {\n try {\n document.documentElement.innerHTML = this.responseText;\n } catch(error) {\n // IE makes document.documentElement read only\n document.body.innerHTML = this.responseText;\n }\n }\n };\n\n oldXMLHttpRequestSend.apply(this, arguments);\n}\n</code></pre>\n" }, { "answer_id": 10717647, "author": "Juri", "author_id": 50109, "author_profile": "https://Stackoverflow.com/users/50109", "pm_score": 5, "selected": false, "text": "<p>I just wanted to share my approach as this might it might help someone:</p>\n\n<p>I basically included a JavaScript module which handles the authentication stuff like displaying the username and also this case handling the <strong>redirect to the login page</strong>.</p>\n\n<p>My scenario: We basically have an ISA server in between which listens to all requests and <strong>responds with a 302 and a location header</strong> to our login page.</p>\n\n<p>In my JavaScript module my <strong>initial approach</strong> was something like</p>\n\n<pre><code>$(document).ajaxComplete(function(e, xhr, settings){\n if(xhr.status === 302){\n //check for location header and redirect...\n }\n});\n</code></pre>\n\n<p>The problem (as many here already mentioned) is that the browser handles the redirect by itself wherefore my <code>ajaxComplete</code> callback got never called, but instead I got the <strong>response of the already redirected Login page</strong> which obviously was a <code>status 200</code>. The problem: how do you detect whether the successful 200 response is your actual login page or just some other arbitrary page??</p>\n\n<h2>The solution</h2>\n\n<p>Since I was not able to capture 302 redirect responses, I added a <code>LoginPage</code> header on my login page which contained the url of the login page itself. In the module I now listen for the header and do a redirect:</p>\n\n<pre><code>if(xhr.status === 200){\n var loginPageRedirectHeader = xhr.getResponseHeader(\"LoginPage\");\n if(loginPageRedirectHeader &amp;&amp; loginPageRedirectHeader !== \"\"){\n window.location.replace(loginPageRedirectHeader);\n }\n}\n</code></pre>\n\n<p>...and that works like charm :). You might wonder why I include the url in the <code>LoginPage</code> header...well basically because I found no way of determining the url of <code>GET</code> resulting from the automatic location redirect from the <code>xhr</code> object...</p>\n" }, { "answer_id": 13035088, "author": "rynop", "author_id": 563420, "author_profile": "https://Stackoverflow.com/users/563420", "pm_score": 5, "selected": false, "text": "<p>I think a better way to handle this is to leverage the existing HTTP protocol response codes, specifically <code>401 Unauthorized</code>.</p>\n\n<p>Here is how I solved it:</p>\n\n<ol>\n<li>Server side: If session expires, and request is ajax. send a 401 response code header</li>\n<li><p>Client side: Bind to the ajax events</p>\n\n<pre><code>$('body').bind('ajaxSuccess',function(event,request,settings){\nif (401 == request.status){\n window.location = '/users/login';\n}\n}).bind('ajaxError',function(event,request,settings){\nif (401 == request.status){\n window.location = '/users/login';\n}\n});\n</code></pre></li>\n</ol>\n\n<p>IMO this is more generic and you are not writing some new custom spec/header. You also should not have to modify any of your existing ajax calls.</p>\n\n<p><strong>Edit:</strong> Per @Rob's comment below, 401 (the HTTP status code for authentication errors) should be the indicator. See <a href=\"https://stackoverflow.com/questions/3297048/403-forbidden-vs-401-unauthorized-http-responses\">403 Forbidden vs 401 Unauthorized HTTP responses</a> for more detail. With that being said some web frameworks use 403 for both authentication AND authorization errors - so adapt accordingly. Thanks Rob.</p>\n" }, { "answer_id": 14191048, "author": "karthik339", "author_id": 563436, "author_profile": "https://Stackoverflow.com/users/563436", "pm_score": 3, "selected": false, "text": "<p>If you also want to pass the values then you can also set the session variables and access \nEg: \nIn your jsp you can write </p>\n\n<pre><code>&lt;% HttpSession ses = request.getSession(true);\n String temp=request.getAttribute(\"what_you_defined\"); %&gt;\n</code></pre>\n\n<p>And then you can store this temp value in your javascript variable and play around </p>\n" }, { "answer_id": 14730592, "author": "jocull", "author_id": 97964, "author_profile": "https://Stackoverflow.com/users/97964", "pm_score": 3, "selected": false, "text": "<p>I didn't have any success with the header solution - they were never picked up in my ajaxSuccess / ajaxComplete method. I used Steg's answer with the custom response, but I modified the JS side some. I setup a method that I call in each function so I can use standard <code>$.get</code> and <code>$.post</code> methods.</p>\n\n<pre><code>function handleAjaxResponse(data, callback) {\n //Try to convert and parse object\n try {\n if (jQuery.type(data) === \"string\") {\n data = jQuery.parseJSON(data);\n }\n if (data.error) {\n if (data.error == 'login') {\n window.location.reload();\n return;\n }\n else if (data.error.length &gt; 0) {\n alert(data.error);\n return;\n }\n }\n }\n catch(ex) { }\n\n if (callback) {\n callback(data);\n }\n}\n</code></pre>\n\n<p>Example of it in use...</p>\n\n<pre><code>function submitAjaxForm(form, url, action) {\n //Lock form\n form.find('.ajax-submit').hide();\n form.find('.loader').show();\n\n $.post(url, form.serialize(), function (d) {\n //Unlock form\n form.find('.ajax-submit').show();\n form.find('.loader').hide();\n\n handleAjaxResponse(d, function (data) {\n // ... more code for if auth passes ...\n });\n });\n return false;\n}\n</code></pre>\n" }, { "answer_id": 16409097, "author": "jwaliszko", "author_id": 270315, "author_profile": "https://Stackoverflow.com/users/270315", "pm_score": 5, "selected": false, "text": "<p>I know this topic is old, but I'll give yet another approach I've found and previously described <a href=\"https://stackoverflow.com/questions/11049690/session-cookies-expiration-handling-in-asp-net-mvc-3-while-using-wif-and-jquery\">here</a>. Basically I'm using ASP.MVC with WIF <em>(but this is not really important for the context of this topic - answer is adequate no matter which frameworks are used. The clue stays unchanged - dealing with issues related to authentication failures while performing ajax requests)</em>. </p>\n\n<p>The approach shown below can be applied to all ajax requests out of the box (if they do not redefine beforeSend event obviously).</p>\n\n<pre><code>$.ajaxSetup({\n beforeSend: checkPulse,\n error: function (XMLHttpRequest, textStatus, errorThrown) {\n document.open();\n document.write(XMLHttpRequest.responseText);\n document.close();\n }\n});\n</code></pre>\n\n<p>Before any ajax request is performed <code>CheckPulse</code> method is invoked (the controller method which can be anything simplest):</p>\n\n<pre><code>[Authorize]\npublic virtual void CheckPulse() {}\n</code></pre>\n\n<p>If user is not authenticated (token has expired) such method cannot be accessed (protected by <code>Authorize</code> attribute). Because the framework handles authentication, while token expires, it puts http status 302 to the response. If you don't want your browser to handle 302 response transparently, catch it in Global.asax and change response status - for example to 200 OK. Additionally, add header, which instructs you to process such response in special way (later at the client side):</p>\n\n<pre><code>protected void Application_EndRequest()\n{\n if (Context.Response.StatusCode == 302\n &amp;&amp; (new HttpContextWrapper(Context)).Request.IsAjaxRequest())\n { \n Context.Response.StatusCode = 200;\n Context.Response.AddHeader(\"REQUIRES_AUTH\", \"1\");\n }\n}\n</code></pre>\n\n<p>Finally at the client side check for such custom header. If present - full redirection to logon page should be done (in my case <code>window.location</code> is replaced by url from request which is handled automatically by my framework).</p>\n\n<pre><code>function checkPulse(XMLHttpRequest) {\n var location = window.location.href;\n $.ajax({\n url: \"/Controller/CheckPulse\",\n type: 'GET',\n async: false,\n beforeSend: null,\n success:\n function (result, textStatus, xhr) {\n if (xhr.getResponseHeader('REQUIRES_AUTH') === '1') {\n XMLHttpRequest.abort(); // terminate further ajax execution\n window.location = location;\n }\n }\n });\n}\n</code></pre>\n" }, { "answer_id": 18854676, "author": "John", "author_id": 795252, "author_profile": "https://Stackoverflow.com/users/795252", "pm_score": 4, "selected": false, "text": "<p>While the answers seem to work for people if you're using Spring Security I have found extending LoginUrlAuthenticationEntryPoint and adding specific code to handle AJAX more robust. Most of the examples intercept <em>all</em> redirects not just authentication failures. This was undesirable for the project I work on. You may find the need to also extend ExceptionTranslationFilter and override the \"sendStartAuthentication\" method to remove the caching step if you don't want the failed AJAX request cached.</p>\n\n<p>Example AjaxAwareAuthenticationEntryPoint:</p>\n\n<pre><code>public class AjaxAwareAuthenticationEntryPoint extends\n LoginUrlAuthenticationEntryPoint {\n\n public AjaxAwareAuthenticationEntryPoint(String loginUrl) {\n super(loginUrl);\n }\n\n @Override\n public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {\n if (isAjax(request)) {\n response.sendError(HttpStatus.UNAUTHORIZED.value(), \"Please re-authenticate yourself\");\n } else {\n super.commence(request, response, authException);\n }\n }\n\n public static boolean isAjax(HttpServletRequest request) {\n return request != null &amp;&amp; \"XMLHttpRequest\".equals(request.getHeader(\"X-Requested-With\"));\n }\n}\n</code></pre>\n\n<p>Sources:\n<a href=\"https://stackoverflow.com/questions/11242174/handle-session-expired-event-in-spring-based-web-application\">1</a>, <a href=\"http://yoyar.com/blog/2012/06/dealing-with-the-spring-security-ajax-session-timeout-problem/\" rel=\"nofollow noreferrer\">2</a></p>\n" }, { "answer_id": 21781321, "author": "Rob", "author_id": 755949, "author_profile": "https://Stackoverflow.com/users/755949", "pm_score": 4, "selected": false, "text": "<p>Most of the given solutions use a workaround, using an extra header or an inappropiate HTTP code. Those solutions will most probably work but feel a bit 'hacky'. I've come up with another solution.</p>\n\n<p>We're using WIF which is configured to redirect (passiveRedirectEnabled=\"true\") on a 401 response. The redirect is usefull when handling normal requests but won't work for AJAX requests (since browsers won't execute the 302/redirect). </p>\n\n<p>Using the following code in your global.asax you can disable the redirect for AJAX requests:</p>\n\n<pre><code> void WSFederationAuthenticationModule_AuthorizationFailed(object sender, AuthorizationFailedEventArgs e)\n {\n string requestedWithHeader = HttpContext.Current.Request.Headers[\"X-Requested-With\"];\n\n if (!string.IsNullOrEmpty(requestedWithHeader) &amp;&amp; requestedWithHeader.Equals(\"XMLHttpRequest\", StringComparison.OrdinalIgnoreCase))\n {\n e.RedirectToIdentityProvider = false;\n }\n }\n</code></pre>\n\n<p>This allows you to return 401 responses for AJAX requests, which your javascript can then handle by reloading the page. Reloading the page will throw a 401 which will be handled by WIF (and WIF will redirect the user to the login page).</p>\n\n<p>An example javascript to handle 401 errors:</p>\n\n<pre><code>$(document).ajaxError(function (event, jqxhr, settings, exception) {\n\n if (jqxhr.status == 401) { //Forbidden, go to login\n //Use a reload, WIF will redirect to Login\n location.reload(true);\n }\n});\n</code></pre>\n" }, { "answer_id": 22426015, "author": "camara90100", "author_id": 1001610, "author_profile": "https://Stackoverflow.com/users/1001610", "pm_score": -1, "selected": false, "text": "<p>this worked for me: </p>\n\n<pre><code>success: function(data, textStatus, xhr) {\n\n console.log(xhr.status);\n}\n</code></pre>\n\n<p>on success, ajax will get the same status code the browser gets from the server and execute it.</p>\n" }, { "answer_id": 23417149, "author": "morten.c", "author_id": 2236166, "author_profile": "https://Stackoverflow.com/users/2236166", "pm_score": 4, "selected": false, "text": "<p>Another solution I found (especially useful if you want to set a global behaviour) is to use the <a href=\"https://api.jquery.com/jQuery.ajax/\"><code>$.ajaxsetup()</code> method</a> together with the <a href=\"https://api.jquery.com/jquery.ajaxsetup/\"><code>statusCode</code> property</a>. Like others pointed out, don't use a redirect statuscode (<code>3xx</code>), instead use a <code>4xx</code> statuscode and handle the redirect client-side.</p>\n\n<pre><code>$.ajaxSetup({ \n statusCode : {\n 400 : function () {\n window.location = \"/\";\n }\n }\n});\n</code></pre>\n\n<p>Replace <code>400</code> with the statuscode you want to handle. Like already mentioned <code>401 Unauthorized</code> could be a good idea. I use the <code>400</code> since it's very unspecific and I can use the <code>401</code> for more specific cases (like wrong login credentials). So instead of redirecting directly your backend should return a <code>4xx</code> error-code when the session timed out and you you handle the redirect client-side. Works perfect for me even with frameworks like backbone.js</p>\n" }, { "answer_id": 31716188, "author": "Ali Adlavaran", "author_id": 1249792, "author_profile": "https://Stackoverflow.com/users/1249792", "pm_score": 3, "selected": false, "text": "<p>Finally, I solve the problem by adding a custom <code>HTTP Header</code>. Just before response for every request in server side, i add the current requested url to response's header.</p>\n\n<p>My application type on server is <code>Asp.Net MVC</code>, and it has a good place to do it. in <code>Global.asax</code> i implemented the <code>Application_EndRequest</code> event so:</p>\n\n<pre><code> public class MvcApplication : System.Web.HttpApplication\n {\n\n // ...\n // ...\n\n protected void Application_EndRequest(object sender, EventArgs e)\n {\n var app = (HttpApplication)sender;\n app.Context.Response.Headers.Add(\"CurrentUrl\",app.Context. Request.CurrentExecutionFilePath);\n }\n\n }\n</code></pre>\n\n<p>It works perfect for me! Now in every response of the <code>JQuery</code> <code>$.post</code> i have the requested <code>url</code> and also other response headers which comes as result of <code>POST</code> method by status <code>302</code>, <code>303</code> ,... .</p>\n\n<p>and other important thing is that there is no need to modify code on server side nor client side.</p>\n\n<p>and the next is the ability to get access to the other information of post action such errors, messages, and ..., In this way.</p>\n\n<p>I posted this, maybe help someone :)</p>\n" }, { "answer_id": 36510887, "author": "Tomer", "author_id": 2279765, "author_profile": "https://Stackoverflow.com/users/2279765", "pm_score": 3, "selected": false, "text": "<p>Some might find the below useful:</p>\n\n<p>I wanted clients to be redirected to the login page for any rest-action that is sent without an authorization token. Since all of my rest-actions are Ajax based, I needed a good generic way to redirect to the login page instead of handling the Ajax success function.</p>\n\n<p>This is what I've done:</p>\n\n<p>On any Ajax request my server will return a Json 200 response \"NEED TO AUTHENTICATE\" (if the client needs to authenticate).</p>\n\n<p>Simple example in Java (server side):</p>\n\n<pre><code>@Secured\n@Provider\n@Priority(Priorities.AUTHENTICATION)\npublic class AuthenticationFilter implements ContainerRequestFilter {\n\n private final Logger m_logger = LoggerFactory.getLogger(AuthenticationFilter.class);\n\n public static final String COOKIE_NAME = \"token_cookie\"; \n\n @Override\n public void filter(ContainerRequestContext context) throws IOException { \n // Check if it has a cookie.\n try {\n Map&lt;String, Cookie&gt; cookies = context.getCookies();\n\n if (!cookies.containsKey(COOKIE_NAME)) {\n m_logger.debug(\"No cookie set - redirect to login page\");\n throw new AuthenticationException();\n }\n }\n catch (AuthenticationException e) {\n context.abortWith(Response.ok(\"\\\"NEED TO AUTHENTICATE\\\"\").type(\"json/application\").build());\n }\n }\n}\n</code></pre>\n\n<p>In my Javascript I've added the following code:</p>\n\n<pre><code>$.ajaxPrefilter(function(options, originalOptions, jqXHR) {\n var originalSuccess = options.success;\n\n options.success = function(data) {\n if (data == \"NEED TO AUTHENTICATE\") {\n window.location.replace(\"/login.html\");\n }\n else {\n originalSuccess(data);\n }\n }; \n});\n</code></pre>\n\n<p>And that's about it.</p>\n" }, { "answer_id": 40285917, "author": "Przemek Marcinkiewicz", "author_id": 1449780, "author_profile": "https://Stackoverflow.com/users/1449780", "pm_score": 4, "selected": false, "text": "<p>This problem may appear then using ASP.NET MVC RedirectToAction method. To prevent form displaying the response in div you can simply do some kind of ajax response filter for incomming responses with <strong>$.ajaxSetup</strong>. If the response contains MVC redirection you can evaluate this expression on JS side. Example code for JS below:</p>\n\n<pre><code>$.ajaxSetup({\n dataFilter: function (data, type) {\n if (data &amp;&amp; typeof data == \"string\") {\n if (data.indexOf('window.location') &gt; -1) {\n eval(data);\n }\n }\n return data;\n }\n});\n</code></pre>\n\n<p>If data is: <em>\"window.location = '/Acount/Login'\"</em> above filter will catch that and evaluate to make the redirection instead of letting the data to be displayed.</p>\n" }, { "answer_id": 49416672, "author": "Darren Parker", "author_id": 4505142, "author_profile": "https://Stackoverflow.com/users/4505142", "pm_score": 2, "selected": false, "text": "<p>I got a working solulion using the answers from @John and @Arpad <a href=\"https://stackoverflow.com/a/8426947/4505142\">link</a> and @RobWinch <a href=\"https://stackoverflow.com/a/34366885/4505142\">link</a></p>\n\n<p>I use Spring Security 3.2.9 and jQuery 1.10.2.</p>\n\n<p>Extend Spring's class to cause 4XX response only from AJAX requests:</p>\n\n<pre><code>public class CustomLoginUrlAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {\n\n public CustomLoginUrlAuthenticationEntryPoint(final String loginFormUrl) {\n super(loginFormUrl);\n }\n\n // For AJAX requests for user that isn't logged in, need to return 403 status.\n // For normal requests, Spring does a (302) redirect to login.jsp which the browser handles normally.\n @Override\n public void commence(final HttpServletRequest request,\n final HttpServletResponse response,\n final AuthenticationException authException)\n throws IOException, ServletException {\n if (\"XMLHttpRequest\".equals(request.getHeader(\"X-Requested-With\"))) {\n response.sendError(HttpServletResponse.SC_FORBIDDEN, \"Access Denied\");\n } else {\n super.commence(request, response, authException);\n }\n }\n}\n</code></pre>\n\n<p>applicationContext-security.xml</p>\n\n<pre><code> &lt;security:http auto-config=\"false\" use-expressions=\"true\" entry-point-ref=\"customAuthEntryPoint\" &gt;\n &lt;security:form-login login-page='/login.jsp' default-target-url='/index.jsp' \n authentication-failure-url=\"/login.jsp?error=true\"\n /&gt; \n &lt;security:access-denied-handler error-page=\"/errorPage.jsp\"/&gt; \n &lt;security:logout logout-success-url=\"/login.jsp?logout\" /&gt;\n...\n &lt;bean id=\"customAuthEntryPoint\" class=\"com.myapp.utils.CustomLoginUrlAuthenticationEntryPoint\" scope=\"singleton\"&gt;\n &lt;constructor-arg value=\"/login.jsp\" /&gt;\n &lt;/bean&gt;\n...\n&lt;bean id=\"requestCache\" class=\"org.springframework.security.web.savedrequest.HttpSessionRequestCache\"&gt;\n &lt;property name=\"requestMatcher\"&gt;\n &lt;bean class=\"org.springframework.security.web.util.matcher.NegatedRequestMatcher\"&gt;\n &lt;constructor-arg&gt;\n &lt;bean class=\"org.springframework.security.web.util.matcher.MediaTypeRequestMatcher\"&gt;\n &lt;constructor-arg&gt;\n &lt;bean class=\"org.springframework.web.accept.HeaderContentNegotiationStrategy\"/&gt;\n &lt;/constructor-arg&gt;\n &lt;constructor-arg value=\"#{T(org.springframework.http.MediaType).APPLICATION_JSON}\"/&gt;\n &lt;property name=\"useEquals\" value=\"true\"/&gt;\n &lt;/bean&gt;\n &lt;/constructor-arg&gt;\n &lt;/bean&gt;\n &lt;/property&gt;\n&lt;/bean&gt;\n</code></pre>\n\n<p>In my JSPs, add a global AJAX error handler as shown <a href=\"https://stackoverflow.com/a/17990019/4505142\">here</a></p>\n\n<pre><code> $( document ).ajaxError(function( event, jqxhr, settings, thrownError ) {\n if ( jqxhr.status === 403 ) {\n window.location = \"login.jsp\";\n } else {\n if(thrownError != null) {\n alert(thrownError);\n } else {\n alert(\"error\");\n }\n }\n });\n</code></pre>\n\n<p>Also, remove existing error handlers from AJAX calls in JSP pages:</p>\n\n<pre><code> var str = $(\"#viewForm\").serialize();\n $.ajax({\n url: \"get_mongoDB_doc_versions.do\",\n type: \"post\",\n data: str,\n cache: false,\n async: false,\n dataType: \"json\",\n success: function(data) { ... },\n// error: function (jqXHR, textStatus, errorStr) {\n// if(textStatus != null)\n// alert(textStatus);\n// else if(errorStr != null)\n// alert(errorStr);\n// else\n// alert(\"error\");\n// }\n });\n</code></pre>\n\n<p>I hope it helps others.</p>\n\n<p><strong>Update1</strong>\nI found that I needed to add the option (always-use-default-target=\"true\") to the form-login config.\nThis was needed since after an AJAX request gets redirected to the login page (due to expired session), Spring remembers the previous AJAX request and auto redirects to it after login. This causes the returned JSON to be displayed on the browser page. Of course, not what I want.</p>\n\n<p><strong>Update2</strong>\nInstead of using <code>always-use-default-target=\"true\"</code>, use @RobWinch example of blocking AJAX requests from the requstCache. This allows normal links to be redirected to their original target after login, but AJAX go to the home page after login.</p>\n" }, { "answer_id": 51314921, "author": "Chaim Klar", "author_id": 1475310, "author_profile": "https://Stackoverflow.com/users/1475310", "pm_score": 4, "selected": false, "text": "<p>Let me just quote again the problem as described by @Steg</p>\n\n<blockquote>\n <p>I had a similar problem to yours. I perform an ajax request that has 2\n possible responses: one that redirects the browser to a new page and\n one that replaces an existing HTML form on the current page with a new\n one.</p>\n</blockquote>\n\n<p>IMHO this is a real challenge and will have to be officially extended to the current HTTP standards.</p>\n\n<p>I believe the new Http Standard will be to use a new status-code.\nmeaning: currently <code>301/302</code> tells the browser to go and fetch the content of <em>this</em> request to a new <code>location</code>.</p>\n\n<p>In the extended standard, it will say that if the response <code>status: 308</code> (just an example), then the browser should redirect the main page to the <code>location</code> provided.</p>\n\n<p>That being said; I'm inclined to already mimic this <em>future</em> behavior, and therefore when a document.redirect is needed, I have the server respond as:</p>\n\n<pre><code>status: 204 No Content\nx-status: 308 Document Redirect\nx-location: /login.html\n</code></pre>\n\n<p>When JS gets the \"<code>status: 204</code>\", it checks for the existence of the <code>x-status: 308</code> header, and does a document.redirect to the page provided in the <code>location</code> header.</p>\n\n<p>Does this make any sense to you?</p>\n" }, { "answer_id": 59501322, "author": "Sumit Kumar", "author_id": 842050, "author_profile": "https://Stackoverflow.com/users/842050", "pm_score": 0, "selected": false, "text": "<p>Use statusCode option as in below case, redirects are usually 301, 302 status codes for redirects.</p>\n<pre><code>$.ajax({\n type: &lt;HTTP_METHOD&gt;,\n url: {server.url},\n data: {someData: true},\n statusCode: {\n 301: function(responseObject, textStatus, errorThrown) {\n //yor code goes here\n },\n 302: function(responseObject, textStatus, errorThrown) {\n //yor code goes here\n } \n }\n})\n.done(function(data){\n alert(data);\n})\n.fail(function(jqXHR, textStatus){\n alert('Something went wrong: ' + textStatus);\n})\n.always(function(jqXHR, textStatus) {\n alert('Ajax request was finished')\n});\n</code></pre>\n" }, { "answer_id": 67684994, "author": "Mike", "author_id": 448078, "author_profile": "https://Stackoverflow.com/users/448078", "pm_score": 0, "selected": false, "text": "<p>Backend Spring <code>@ExceptionHandler</code>.</p>\n<ul>\n<li>400 and error string for business related exception (to be shown on pop-up)</li>\n<li>302 and Location header to error/login page for application exceptions for browser request (to be automatically redirected by the browser)</li>\n<li>500/400 and Location header to error/login page for ajax requests to redirect by ajax callback</li>\n</ul>\n<p>Exception details passed to error page via user session</p>\n<pre><code>@Order(HIGHEST_PRECEDENCE)\npublic class ExceptionHandlerAdvise {\n\n private static Logger logger = LoggerFactory.getLogger(ExceptionHandlerAdvise.class);\n\n @Autowired\n private UserInfo userInfo;\n\n @ExceptionHandler(value = Exception.class)\n protected ResponseEntity&lt;Object&gt; handleException(Exception ex, WebRequest request) {\n HttpHeaders headers = new HttpHeaders();\n if (isBusinessException(ex)) {\n logger.warn(getRequestURL(request), ex);\n return new ResponseEntity&lt;&gt;(getUserFriendlyErrorMessage(ex), headers, BAD_REQUEST);\n } else {\n logger.error(getRequestURL(request), ex);\n userInfo.setLastError(ex);\n headers.add(&quot;Location&quot;, &quot;/euc-portal/fault&quot;);\n return new ResponseEntity&lt;&gt;(null, headers, isAjaxRequest(request) ? INTERNAL_SERVER_ERROR : FOUND);\n }\n }\n}\n\nprivate boolean isAjaxRequest(WebRequest request) {\n return request.getHeader(&quot;x-requested-with&quot;) != null;\n}\n\nprivate String getRequestURL(WebRequest request) {\n if (request instanceof ServletWebRequest) {\n HttpServletRequest servletRequest = ((ServletWebRequest) request).getRequest();\n StringBuilder uri = new StringBuilder(servletRequest.getRequestURI());\n if (servletRequest.getQueryString() != null) {\n uri.append(&quot;?&quot;);\n uri.append(servletRequest.getQueryString());\n }\n return uri.toString();\n }\n return request.getContextPath();\n}\n</code></pre>\n<p>LoginHandlerInterceptor</p>\n<pre><code>@Service\npublic class LoginHandlerInterceptor implements HandlerInterceptor {\n\n @Autowired\n private UserInfo userInfo;\n\n @Override\n public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {\n if (userInfo.getPrincipal() == null &amp;&amp; !(request.getRequestURI().contains(LOGIN_URL) || request.getRequestURI().contains(FAULT_URL) || request.getRequestURI().startsWith(&quot;/app/css&quot;))) {\n response.addHeader(&quot;Location&quot;, LOGIN_URL);\n response.setStatus(isAjaxRequest(request) ? BAD_REQUEST.value() : FOUND.value());\n return false;\n }\n return true;\n }\n}\n</code></pre>\n<p>Client code</p>\n<pre><code>$.post('/app/request', params).done(function(response) {\n ...\n}).fail(function(response) {\n if (response.getResponseHeader('Location')) {\n window.top.location.href = response.getResponseHeader('Location');\n return;\n }\n alert(response);\n});\n</code></pre>\n" }, { "answer_id": 69378012, "author": "Eugen Konkov", "author_id": 4632019, "author_profile": "https://Stackoverflow.com/users/4632019", "pm_score": 1, "selected": false, "text": "<p>As alternative to ajax, there is a new <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API\" rel=\"nofollow noreferrer\"><strong>Fetch API</strong></a> being developed, which allows manual redirect handling. <a href=\"https://caniuse.com/?search=fetch\" rel=\"nofollow noreferrer\">You need to check</a> if the current browser support is enough for your needs.</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2024/" ]
I'm using `$.post()` to call a servlet using Ajax and then using the resulting HTML fragment to replace a `div` element in the user's current page. However, if the session times out, the server sends a redirect directive to send the user to the login page. In this case, jQuery is replacing the `div` element with the contents of the login page, forcing the user's eyes to witness a rare scene indeed. How can I manage a redirect directive from an Ajax call with jQuery 1.2.6?
The solution that was eventually implemented was to use a wrapper for the callback function of the Ajax call and in this wrapper check for the existence of a specific element on the returned HTML chunk. If the element was found then the wrapper executed a redirection. If not, the wrapper forwarded the call to the actual callback function. For example, our wrapper function was something like: ``` function cbWrapper(data, funct){ if($("#myForm", data).length > 0) top.location.href="login.htm";//redirection else funct(data); } ``` Then, when making the Ajax call we used something like: ``` $.post("myAjaxHandler", { param1: foo, param2: bar }, function(data){ cbWrapper(data, myActualCB); }, "html" ); ``` This worked for us because all Ajax calls always returned HTML inside a DIV element that we use to replace a piece of the page. Also, we only needed to redirect to the login page.
199,113
<p>I have a <code>BasePage</code> which inherits from <code>System.Web.UI.Page</code>, and every page that inherits the <code>BasePage</code> will have the same master page.</p> <p>How do I cast the <code>Page.Master</code> of the <code>BasePage</code> to the specific master page so I can access properties on it?</p>
[ { "answer_id": 199116, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 0, "selected": false, "text": "<p>In VB.Net</p>\n\n<pre><code>MasterPageVariable = Ctype(page.MasterPage, MasterPageClass)\n</code></pre>\n" }, { "answer_id": 199122, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": true, "text": "<p>Overriden Master can't be done (its not Virtual), and masking it with new causes an issue with the page class not being able to get its master, so the best thing to do is a second property.</p>\n\n<p>Something like:</p>\n\n<pre><code>public CustomMasterPage MasterPage\n{\n get { return this.Master as CustomMasterPage; }\n}\n</code></pre>\n\n<p>In your BasePage class.</p>\n" }, { "answer_id": 199124, "author": "Jason Stevenson", "author_id": 13368, "author_profile": "https://Stackoverflow.com/users/13368", "pm_score": 3, "selected": false, "text": "<p>A better way is to add the MasterType property to the pages that use that master. Then you can simply access the master page properties through the page object.</p>\n\n<pre><code>&lt;%@ MasterType VirtualPath=\"~/site.master\" %&gt;\n</code></pre>\n\n<p>You just use this in your code:</p>\n\n<pre><code>this.Master.propertyName\n</code></pre>\n\n<p>To access the property of the master page for the current page.</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4998/" ]
I have a `BasePage` which inherits from `System.Web.UI.Page`, and every page that inherits the `BasePage` will have the same master page. How do I cast the `Page.Master` of the `BasePage` to the specific master page so I can access properties on it?
Overriden Master can't be done (its not Virtual), and masking it with new causes an issue with the page class not being able to get its master, so the best thing to do is a second property. Something like: ``` public CustomMasterPage MasterPage { get { return this.Master as CustomMasterPage; } } ``` In your BasePage class.
199,127
<p>I have asp.net form that contains fields. When I access this window, my javascript functions can access the fields via the DOM with the getElementById() method and when I postpack to the server I am receiving the updates made by the client.</p> <p>However, when I launch the form as a child window using Telerik's RadWindow control, the javascript can not access the hidden fields on the child form. Instead I get null. </p> <p>My questions are:</p> <ol> <li>Are hidden fields on a child window not accessible when the window is launched from a parent asp.net form?</li> <li>Has anyone attempted this with Telerik controls and run into issues?</li> </ol> <p><strong>EDIT</strong> Craig pointed out that the id may be different. Two additional questions then:</p> <ol> <li>Can you ensure that the id you assign at the server is actually used?</li> <li>Is using getElementByName() a better mechanism to access DOM elements?</li> </ol>
[ { "answer_id": 199187, "author": "Craig", "author_id": 2894, "author_profile": "https://Stackoverflow.com/users/2894", "pm_score": 1, "selected": false, "text": "<p>It is quite possible that the element's ID is not what you think it is. Check the rendered page and see if the ID is there. I am guessing that the page is given a different ID since it is rendered inside another control. </p>\n\n<p>If that is the case, you can have the form render some script that returns the element ID by accessing the controls client ID.</p>\n" }, { "answer_id": 199524, "author": "TonyB", "author_id": 3543, "author_profile": "https://Stackoverflow.com/users/3543", "pm_score": 2, "selected": true, "text": "<p>To get the ID of your asp.net control do something like this:</p>\n\n<pre><code>&lt;%= theControl.ClientID %&gt;\n</code></pre>\n\n<p>getElementByName is not as commonly used as getElementById. The ID attribute is supposed to be unique for each element on the page whereas the name attribute can be duplicated.</p>\n" }, { "answer_id": 202756, "author": "Kon", "author_id": 22303, "author_profile": "https://Stackoverflow.com/users/22303", "pm_score": 0, "selected": false, "text": "<p>I use getElementsByName for checkboxes within the same group.</p>\n\n<p>As for the control's ID, TonyB has the right idea, but make sure you refer to the ClientID property in the PreRender event handler, because if you do it too early in the page life cycle, it will not be available yet).</p>\n" }, { "answer_id": 210285, "author": "Jeremy Bade", "author_id": 13284, "author_profile": "https://Stackoverflow.com/users/13284", "pm_score": 0, "selected": false, "text": "<p>Is it possible the that javascript is trying to get a reference to the hidden field before the RadWindow has loaded it? I believe I've run into this before and had to use setTimeout to get around the problem.</p>\n" }, { "answer_id": 440701, "author": "LarryF", "author_id": 18518, "author_profile": "https://Stackoverflow.com/users/18518", "pm_score": 1, "selected": false, "text": "<p>David, I'm sending you this answer because I saw the same issue in my code, and the only REAL solution I found was that I had to support the \"OnClick\" function in two places... In my case, I was using PetersDatePackage, but it was on a Telerik RAD Strip.</p>\n\n<p>In my case, the control was on a .ascx page, and the JS code was as follows:</p>\n\n<pre><code>function OnIncidentDateChange(ctrl, dtDate, bErr)\n{\n var weekday = new Array(7);\n weekday[0] = \"Sunday\";\n weekday[1] = \"Monday\";\n weekday[2] = \"Tuesday\";\n weekday[3] = \"Wednesday\";\n weekday[4] = \"Thursday\";\n weekday[5] = \"Friday\";\n weekday[6] = \"Saturday\";\n\n &lt;%=LabelDayOfWeek.ClientID %&gt;.innerText = weekday[dtDate.getDay()];\n}\n</code></pre>\n\n<p>But, this itself was not enough. I had to add THIS code to my parent page. The page that holds the controls for the Telerik strip.</p>\n\n<pre><code>// Dummy function?\nfunction OnIncidentDateChange()\n{\n}\n</code></pre>\n\n<p>Once I did that, it worked...</p>\n\n<p>I'm not certain why, to tell you the truth, and it makes no sense to me, and may just be a issue with the PDP package...</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19799/" ]
I have asp.net form that contains fields. When I access this window, my javascript functions can access the fields via the DOM with the getElementById() method and when I postpack to the server I am receiving the updates made by the client. However, when I launch the form as a child window using Telerik's RadWindow control, the javascript can not access the hidden fields on the child form. Instead I get null. My questions are: 1. Are hidden fields on a child window not accessible when the window is launched from a parent asp.net form? 2. Has anyone attempted this with Telerik controls and run into issues? **EDIT** Craig pointed out that the id may be different. Two additional questions then: 1. Can you ensure that the id you assign at the server is actually used? 2. Is using getElementByName() a better mechanism to access DOM elements?
To get the ID of your asp.net control do something like this: ``` <%= theControl.ClientID %> ``` getElementByName is not as commonly used as getElementById. The ID attribute is supposed to be unique for each element on the page whereas the name attribute can be duplicated.
199,130
<p>For my Java apps with very long classpaths, I cannot see the main class specified near the end of the arg list when using ps. I think this stems from my Ubuntu system's size limit on /proc/pid/cmdline. How can I increase this limit?</p>
[ { "answer_id": 199140, "author": "caskey", "author_id": 114986, "author_profile": "https://Stackoverflow.com/users/114986", "pm_score": -1, "selected": false, "text": "<p>Perhaps the 'w' parameter to ps is what you want. Add two 'w' for greater output. It tells ps to ignore the line width of the terminal.</p>\n" }, { "answer_id": 199197, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": -1, "selected": false, "text": "<p>I'm pretty sure that if you're actually seeing the arguments truncated in /proc/$pid/cmdline then you're actually exceeding the maximum argument length supported by the OS. As far as I can tell, in Linux, the size is limited to the memory page size. See <a href=\"http://www.linuxquestions.org/questions/linux-general-1/ps-ww-length-restriction-665255/\" rel=\"nofollow noreferrer\">\"ps ww\" length restriction </a> for reference.</p>\n\n<p>The only way to get around that would be to recompile the kernel. If you're interested in going that far to resolve this then you may find this post useful: <a href=\"http://www.linuxjournal.com/article/6060\" rel=\"nofollow noreferrer\">\"Argument list too long\": Beyond Arguments and Limitations</a> </p>\n\n<p>Additional reference:<br />\n<a href=\"http://www.in-ulm.de/~mascheck/various/argmax/\" rel=\"nofollow noreferrer\">ARG_MAX, maximum length of arguments for a new process</a></p>\n" }, { "answer_id": 199199, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 5, "selected": true, "text": "<p>You can't change this dynamically, the limit is hard-coded in the kernel to PAGE_SIZE in fs/proc/base.c:</p>\n\n<pre><code> 274 int res = 0;\n 275 unsigned int len;\n 276 struct mm_struct *mm = get_task_mm(task);\n 277 if (!mm)\n 278 goto out;\n 279 if (!mm-&gt;arg_end)\n 280 goto out_mm; /* Shh! No looking before we're done */\n 281\n 282 len = mm-&gt;arg_end - mm-&gt;arg_start;\n 283 \n 284 if (len &gt; PAGE_SIZE)\n 285 len = PAGE_SIZE;\n 286 \n 287 res = access_process_vm(task, mm-&gt;arg_start, buffer, len, 0);\n</code></pre>\n" }, { "answer_id": 1286297, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I temporarily get around the 4096 character command line argument limitation of ps (or rather /proc/PID/cmdline) is by using a small script to replace the java command.</p>\n\n<p>During development, I always use an unpacked JDK version from SUN and never use the installed JRE or JDK of the OS no matter if Linux or Windows (eg. download the bin versus the rpm.bin).\nI do not recommend changing the script for your default Java installation (e.g. because it might break updates or get overwritten or create problems or ...)</p>\n\n<p>So assuming the java command is in /x/jdks/jdk1.6.0_16_x32/bin/java</p>\n\n<p>first move the actual binary away:</p>\n\n<pre><code>mv /x/jdks/jdk1.6.0_16_x32/bin/java /x/jdks/jdk1.6.0_16_x32/bin/java.orig\n</code></pre>\n\n<p>then create a script /x/jdks/jdk1.6.0_16_x32/bin/java like e.g.:</p>\n\n<pre><code> #!/bin/bash\n\n echo \"$@\" &gt; /tmp/java.$$.cmdline\n /x/jdks/jdk1.6.0_16_x32/bin/java.orig $@\n</code></pre>\n\n<p>and then make the script runnable</p>\n\n<pre><code>chmod a+x /x/jdks/jdk1.6.0_16_x32/bin/java\n</code></pre>\n\n<p>in case of copy and pasting the above, you should make sure that there are not extra spaces in /x/jdks/jdk1.6.0_16_x32/bin/java and #!/bin/bash is the first line</p>\n\n<p>The complete command line ends up in e.g. /tmp/java.26835.cmdline where 26835 is the PID of the shell script.\nI think there is also some shell limit on the number of command line arguments, cannot remember but it was possibly 64K characters.</p>\n\n<p>you can change the script to remove the command line text from /tmp/java.PROCESS_ID.cmdline\nat the end </p>\n\n<p>After I got the commandline, I always move the script to something like \"java.script\" and copy (cp -a) the actual binary java.orig back to java. I only use the script when I hit the 4K limit.</p>\n\n<p>There might be problems with escaped characters and maybe even spaces in paths or such, but it works fine for me.</p>\n" }, { "answer_id": 3418186, "author": "Matt", "author_id": 401688, "author_profile": "https://Stackoverflow.com/users/401688", "pm_score": 3, "selected": false, "text": "<p>You can use <code>jconsole</code> to get access to the original command line without all the length limits.</p>\n" }, { "answer_id": 3669146, "author": "Kevin Cross", "author_id": 219424, "author_profile": "https://Stackoverflow.com/users/219424", "pm_score": 5, "selected": false, "text": "<p>For looking at Java processes <a href=\"http://download.oracle.com/javase/6/docs/technotes/tools/share/jps.html\" rel=\"noreferrer\">jps</a> is very useful.</p>\n\n<p>This will give you the main class and jvm args:</p>\n\n<pre><code>jps -vl | grep &lt;pid&gt;\n</code></pre>\n" }, { "answer_id": 37454888, "author": "kamstrup", "author_id": 2285564, "author_profile": "https://Stackoverflow.com/users/2285564", "pm_score": 0, "selected": false, "text": "<p>For Java based programs where you are just interested in inspecting the command line args your main class got, you can run:</p>\n\n<pre><code>jps -m\n</code></pre>\n" }, { "answer_id": 42760922, "author": "riverfall", "author_id": 5039637, "author_profile": "https://Stackoverflow.com/users/5039637", "pm_score": 2, "selected": false, "text": "<p>It is possible to use newer linux distributions, where this limit was removed, for example RHEL 6.8 or later</p>\n\n<p><em>\"The /proc/pid/cmdline file length limit for the ps command was previously hard-coded in the kernel to 4096 characters. This update makes sure the length of /proc/pid/cmdline is unlimited, which is especially useful for listing processes with long command line arguments. (BZ#1100069)\"</em></p>\n\n<p><a href=\"https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/6.8_Release_Notes/new_features_kernel.html\" rel=\"nofollow noreferrer\">https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/6.8_Release_Notes/new_features_kernel.html</a></p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27635/" ]
For my Java apps with very long classpaths, I cannot see the main class specified near the end of the arg list when using ps. I think this stems from my Ubuntu system's size limit on /proc/pid/cmdline. How can I increase this limit?
You can't change this dynamically, the limit is hard-coded in the kernel to PAGE\_SIZE in fs/proc/base.c: ``` 274 int res = 0; 275 unsigned int len; 276 struct mm_struct *mm = get_task_mm(task); 277 if (!mm) 278 goto out; 279 if (!mm->arg_end) 280 goto out_mm; /* Shh! No looking before we're done */ 281 282 len = mm->arg_end - mm->arg_start; 283 284 if (len > PAGE_SIZE) 285 len = PAGE_SIZE; 286 287 res = access_process_vm(task, mm->arg_start, buffer, len, 0); ```
199,142
<p>I'm designing some VB based ASP.NET 2.0, and I am trying to make more use of the various ASP tags that visual studio provides, rather than hand writing everything in the code-behind. I want to pass in an outside variable from the Session to identify who the user is for the query.</p> <pre><code>&lt;asp:sqldatasource id="DataStores" runat="server" connectionstring="&lt;%$ ConnectionStrings:MY_CONNECTION %&gt;" providername="&lt;%$ ConnectionStrings:MY_CONNECTION.ProviderName %&gt;" selectcommand="SELECT THING1, THING2 FROM DATA_TABLE WHERE (THING2 IN (SELECT THING2 FROM RELATED_DATA_TABLE WHERE (USERNAME = @user)))" onselecting="Data_Stores_Selecting"&gt; &lt;SelectParameters&gt; &lt;asp:parameter name="user" defaultvalue ="" /&gt; &lt;/SelectParameters&gt; &lt;/asp:sqldatasource&gt; </code></pre> <p>And on my code behind I have:</p> <pre><code>Protected Sub Data_Stores_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) Handles Data_Stores.Selecting e.Command.Parameters("user").Value = Session("userid") End Sub </code></pre> <p>Oracle squaks at me with ORA-01036, illegal variable name. Am I declaring the variable wrong in the query? </p> <p>I thought external variables share the same name with a @ prefixed. from what I understand, this should be placing the value I want into the query when it executes the select.</p> <p>EDIT: Okay, thanks for the advice so far, first error was corrected, I need to use : and not @ for the variable declaration in the query. Now it generates an ORA-01745 invalid host/bind variable name.</p> <p>EDIT AGAIN: Okay, looks like user was a reserved word. It works now! Thanks for other points of view on this one. I hadn't thought of that approach.</p>
[ { "answer_id": 199148, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 3, "selected": true, "text": "<p>I believe Oracle uses the colon \":\", not the at-symbol \"@\".\n<hr>\n\"user\" is probably a reserved word. Change it to \"userID\", or something similar.</p>\n" }, { "answer_id": 199574, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>You may want to consider using a <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sessionparameter(VS.80).aspx\" rel=\"nofollow noreferrer\">SessionParameter</a> instead of just a Parameter and let the SqlDataSource extract the user id directly from the session without any intervention on your part. Also, the example on the page linked above seems to imply that you should use ? instead of @user for parameter replacement for an ODBC connection. I think the parameter replacement would be done by the SqlDataSource and not passed to Oracle, that is it would substitute the actual value of the user id in place of the parameter (properly quoted of course) before sending the query to the database.</p>\n\n<pre><code>&lt;SelectParameters&gt;\n &lt;SessionParameter Name=\"userID\" SessionField=\"user\" DefaultValue=\"\" /&gt;\n&lt;/SelectParameters&gt;\n</code></pre>\n" }, { "answer_id": 238877, "author": "Eilon", "author_id": 31668, "author_profile": "https://Stackoverflow.com/users/31668", "pm_score": 0, "selected": false, "text": "<p>Using ASP.NET's SessionParameter is definitely the way to go here - that's why we have it :)</p>\n\n<p>Using ASP.NET parameters you can easily include in your queries values from static sources, session state, query string, control property values, form post data, cookies, and user profile.</p>\n" }, { "answer_id": 249466, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;asp:sqldatasource id=\"DataStores\" runat=\"server\" connectionstring=\"&lt;%$ ConnectionStrings:MY_CONNECTION %&gt;\"\n providername=\"&lt;%$ ConnectionStrings:MY_CONNECTION.ProviderName %&gt;\"\n selectcommand=\"SELECT THING1, THING2 FROM DATA_TABLE WHERE (THING2 IN (SELECT THING2 FROM RELATED_DATA_TABLE WHERE (USERNAME = @user)))\"\n onselecting=\"NAME_OF_SUB_Selecting\"&gt;\n &lt;SelectParameters&gt;\n &lt;asp:parameter name=\"@user1\" defaultvalue =\"\" /&gt;\n &lt;/SelectParameters&gt;\n &lt;/asp:sqldatasource&gt;\n\n\nProtected Sub NAME_OF_SUB_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) Handles Data_Stores.Selecting\n e.Command.Parameters(\"@user1\").Value = Membership.GetUser.ProviderUserKey.ToString()\nEnd Sub\n</code></pre>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12545/" ]
I'm designing some VB based ASP.NET 2.0, and I am trying to make more use of the various ASP tags that visual studio provides, rather than hand writing everything in the code-behind. I want to pass in an outside variable from the Session to identify who the user is for the query. ``` <asp:sqldatasource id="DataStores" runat="server" connectionstring="<%$ ConnectionStrings:MY_CONNECTION %>" providername="<%$ ConnectionStrings:MY_CONNECTION.ProviderName %>" selectcommand="SELECT THING1, THING2 FROM DATA_TABLE WHERE (THING2 IN (SELECT THING2 FROM RELATED_DATA_TABLE WHERE (USERNAME = @user)))" onselecting="Data_Stores_Selecting"> <SelectParameters> <asp:parameter name="user" defaultvalue ="" /> </SelectParameters> </asp:sqldatasource> ``` And on my code behind I have: ``` Protected Sub Data_Stores_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) Handles Data_Stores.Selecting e.Command.Parameters("user").Value = Session("userid") End Sub ``` Oracle squaks at me with ORA-01036, illegal variable name. Am I declaring the variable wrong in the query? I thought external variables share the same name with a @ prefixed. from what I understand, this should be placing the value I want into the query when it executes the select. EDIT: Okay, thanks for the advice so far, first error was corrected, I need to use : and not @ for the variable declaration in the query. Now it generates an ORA-01745 invalid host/bind variable name. EDIT AGAIN: Okay, looks like user was a reserved word. It works now! Thanks for other points of view on this one. I hadn't thought of that approach.
I believe Oracle uses the colon ":", not the at-symbol "@". --- "user" is probably a reserved word. Change it to "userID", or something similar.
199,145
<p>I'm using this code, and I get the stack trace that is listed below. I've got this working with just https and with basic authentication, but not ntlm.</p> <pre><code>HttpClient client = null; HttpMethod get = null; try { Protocol myhttps = new Protocol("https", ((ProtocolSocketFactory) new EasySSLProtocolSocketFactory()), 443); Protocol.registerProtocol("https", myhttps); client = new HttpClient(); get = new GetMethod("https://tt.dummycorp.com/tmtrack/"); Credentials creds = new NTCredentials("dummy", "dummy123", "host", "DUMMYDOMAIN"); client.getState().setCredentials(AuthScope.ANY, creds); get.setDoAuthentication(true); int resultCode = client.executeMethod(get); System.out.println(get.getResponseBodyAsString()); } javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: signature check failed at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1591) at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:187) at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:181) at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:975) at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:123) at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:516) at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:454) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:884) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1096) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:623) at com.sun.net.ssl.internal.ssl.AppOutputStream.write(AppOutputStream.java:59) at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:65) at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:123) at org.apache.commons.httpclient.HttpConnection.flushRequestOutputStream(HttpConnection.java:828) at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2116) at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096) at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398) at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323) at com.dummycorp.teamtrack.TeamTrackHack.main(TeamTrackHack.java:38) Caused by: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: signature check failed at sun.security.validator.PKIXValidator.doValidate(PKIXValidator.java:251) at sun.security.validator.PKIXValidator.doValidate(PKIXValidator.java:234) at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:158) at sun.security.validator.Validator.validate(Validator.java:218) at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:126) at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:209) at org.apache.commons.httpclient.contrib.ssl.EasyX509TrustManager.checkServerTrusted(EasyX509TrustManager.java:104) at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:967) ... 17 more Caused by: java.security.cert.CertPathValidatorException: signature check failed at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:139) at sun.security.provider.certpath.PKIXCertPathValidator.doValidate(PKIXCertPathValidator.java:316) at sun.security.provider.certpath.PKIXCertPathValidator.engineValidate(PKIXCertPathValidator.java:178) at java.security.cert.CertPathValidator.validate(CertPathValidator.java:250) at sun.security.validator.PKIXValidator.doValidate(PKIXValidator.java:246) ... 24 more Caused by: java.security.SignatureException: Signature does not match. at sun.security.x509.X509CertImpl.verify(X509CertImpl.java:446) at sun.security.provider.certpath.BasicChecker.verifySignature(BasicChecker.java:133) at sun.security.provider.certpath.BasicChecker.check(BasicChecker.java:112) at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:117) ... 28 more </code></pre>
[ { "answer_id": 200471, "author": "Sergey Mikhanov", "author_id": 3894, "author_profile": "https://Stackoverflow.com/users/3894", "pm_score": 0, "selected": false, "text": "<p>Have a look at the utility posted <a href=\"http://nodsw.com/blog/leeland/2006/12/06-no-more-unable-find-valid-certification-path-requested-target\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>It solves different problem, namely the absence of the certificate, whereas you have invalid certificate installed, but probably its verbose output about installed certificates could be helpful.</p>\n" }, { "answer_id": 336820, "author": "Gennady Shumakher", "author_id": 42512, "author_profile": "https://Stackoverflow.com/users/42512", "pm_score": 3, "selected": true, "text": "<p>HttpClient does not fully support NTLM. Please have a look at <a href=\"http://hc.apache.org/httpclient-3.x/authentication.html#Known_limitations_and_problems\" rel=\"nofollow noreferrer\">Known limitations and problems</a>. The HttpClient documentation regarding NTLM is a bit confusing, but the bottom line is that they do not support NTLMv2 which makes it hardly usable in this regard.</p>\n\n<p>NTLM is supported by standard java HttpURLConnection (<a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4626557\" rel=\"nofollow noreferrer\">link</a>), but HttpClient has some advantages over jdk's HttpURLConnection.</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310/" ]
I'm using this code, and I get the stack trace that is listed below. I've got this working with just https and with basic authentication, but not ntlm. ``` HttpClient client = null; HttpMethod get = null; try { Protocol myhttps = new Protocol("https", ((ProtocolSocketFactory) new EasySSLProtocolSocketFactory()), 443); Protocol.registerProtocol("https", myhttps); client = new HttpClient(); get = new GetMethod("https://tt.dummycorp.com/tmtrack/"); Credentials creds = new NTCredentials("dummy", "dummy123", "host", "DUMMYDOMAIN"); client.getState().setCredentials(AuthScope.ANY, creds); get.setDoAuthentication(true); int resultCode = client.executeMethod(get); System.out.println(get.getResponseBodyAsString()); } javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: signature check failed at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1591) at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:187) at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:181) at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:975) at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:123) at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:516) at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:454) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:884) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1096) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:623) at com.sun.net.ssl.internal.ssl.AppOutputStream.write(AppOutputStream.java:59) at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:65) at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:123) at org.apache.commons.httpclient.HttpConnection.flushRequestOutputStream(HttpConnection.java:828) at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2116) at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096) at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398) at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323) at com.dummycorp.teamtrack.TeamTrackHack.main(TeamTrackHack.java:38) Caused by: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: signature check failed at sun.security.validator.PKIXValidator.doValidate(PKIXValidator.java:251) at sun.security.validator.PKIXValidator.doValidate(PKIXValidator.java:234) at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:158) at sun.security.validator.Validator.validate(Validator.java:218) at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:126) at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:209) at org.apache.commons.httpclient.contrib.ssl.EasyX509TrustManager.checkServerTrusted(EasyX509TrustManager.java:104) at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:967) ... 17 more Caused by: java.security.cert.CertPathValidatorException: signature check failed at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:139) at sun.security.provider.certpath.PKIXCertPathValidator.doValidate(PKIXCertPathValidator.java:316) at sun.security.provider.certpath.PKIXCertPathValidator.engineValidate(PKIXCertPathValidator.java:178) at java.security.cert.CertPathValidator.validate(CertPathValidator.java:250) at sun.security.validator.PKIXValidator.doValidate(PKIXValidator.java:246) ... 24 more Caused by: java.security.SignatureException: Signature does not match. at sun.security.x509.X509CertImpl.verify(X509CertImpl.java:446) at sun.security.provider.certpath.BasicChecker.verifySignature(BasicChecker.java:133) at sun.security.provider.certpath.BasicChecker.check(BasicChecker.java:112) at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:117) ... 28 more ```
HttpClient does not fully support NTLM. Please have a look at [Known limitations and problems](http://hc.apache.org/httpclient-3.x/authentication.html#Known_limitations_and_problems). The HttpClient documentation regarding NTLM is a bit confusing, but the bottom line is that they do not support NTLMv2 which makes it hardly usable in this regard. NTLM is supported by standard java HttpURLConnection ([link](http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4626557)), but HttpClient has some advantages over jdk's HttpURLConnection.
199,151
<p>I'm trying to link a Qt application with its libraries and the linker (MinGW) spews hundreds of lines like the following, and I am unsure how to proceed.</p> <pre> cpp: undefined reference to `_Unwind_SjLj_Register' c:/qt/lib/libQtCore.a(qcoreapplication_win.o)(.text+0x29d):qcoreapplication_win. cpp: undefined reference to `_Unwind_SjLj_Unregister' c:/qt/lib/libQtCore.a(qcoreapplication_win.o)(.text+0x38c):qcoreapplication_win. cpp: undefined reference to `_Unwind_SjLj_Resume' c:/qt/lib/libQtCore.a(qcoreapplication_win.o)(.text+0x4ce):qcoreapplication_win. cpp: undefined reference to `_Unwind_SjLj_Register' c:/qt/lib/libQtCore.a(qcoreapplication_win.o)(.text+0x53e):qcoreapplication_win. cpp: undefined reference to `_Unwind_SjLj_Unregister' c:/qt/lib/libQtCore.a(qcoreapplication_win.o)(.text+0x635):qcoreapplication_win. cpp: undefined reference to `_Unwind_SjLj_Resume' </pre>
[ { "answer_id": 199328, "author": "Steve Moyer", "author_id": 17008, "author_profile": "https://Stackoverflow.com/users/17008", "pm_score": 1, "selected": false, "text": "<p>It's been a while since I did any Qt development, but there were only a couple instances that I remember spewing out huge numbers of messages like this.</p>\n\n<ul>\n<li>Include files for Qt were a\ndifferent version than the shared\nlibraries ... this happened when I\nupgraded and for some reason, you\nhad to manually upgrade the include\nfiles.</li>\n<li>The Qt libraries were missing altogether ... I vaguely remember the compiler working, but the linker failing when I first started.</li>\n</ul>\n\n<p>I was doing Qt development targeted at an ARM processor, so I had extra oddities involved when cross-compiling.</p>\n" }, { "answer_id": 199372, "author": "Colin Jensen", "author_id": 9884, "author_profile": "https://Stackoverflow.com/users/9884", "pm_score": 3, "selected": false, "text": "<p>I don't know... but to me, spewing stuff about Unwind suggests that you have a mismatch between whether the library is compiled with exceptions and your application is compiled with exceptions.</p>\n\n<p>If you want exceptions, make sure you have enabled them by adding the following line in your qmake file:</p>\n\n<pre><code>CONFIG += exceptions\n</code></pre>\n\n<p>or, if you do not want exceptions, use the opposite</p>\n\n<pre><code>CONFIG -= exceptions\n</code></pre>\n\n<p>And whatever you do, do not use C++ compiler options to set this yourself.</p>\n" }, { "answer_id": 11979569, "author": "chacham15", "author_id": 516813, "author_profile": "https://Stackoverflow.com/users/516813", "pm_score": 0, "selected": false, "text": "<p>2 possible reasons that i know of:</p>\n\n<ol>\n<li>if you try to link gcc4 libraries with a gcc3 linker. </li>\n<li>You need the <code>-lstdc++</code> flag to the end of the compile command</li>\n</ol>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8923/" ]
I'm trying to link a Qt application with its libraries and the linker (MinGW) spews hundreds of lines like the following, and I am unsure how to proceed. ``` cpp: undefined reference to `_Unwind_SjLj_Register' c:/qt/lib/libQtCore.a(qcoreapplication_win.o)(.text+0x29d):qcoreapplication_win. cpp: undefined reference to `_Unwind_SjLj_Unregister' c:/qt/lib/libQtCore.a(qcoreapplication_win.o)(.text+0x38c):qcoreapplication_win. cpp: undefined reference to `_Unwind_SjLj_Resume' c:/qt/lib/libQtCore.a(qcoreapplication_win.o)(.text+0x4ce):qcoreapplication_win. cpp: undefined reference to `_Unwind_SjLj_Register' c:/qt/lib/libQtCore.a(qcoreapplication_win.o)(.text+0x53e):qcoreapplication_win. cpp: undefined reference to `_Unwind_SjLj_Unregister' c:/qt/lib/libQtCore.a(qcoreapplication_win.o)(.text+0x635):qcoreapplication_win. cpp: undefined reference to `_Unwind_SjLj_Resume' ```
I don't know... but to me, spewing stuff about Unwind suggests that you have a mismatch between whether the library is compiled with exceptions and your application is compiled with exceptions. If you want exceptions, make sure you have enabled them by adding the following line in your qmake file: ``` CONFIG += exceptions ``` or, if you do not want exceptions, use the opposite ``` CONFIG -= exceptions ``` And whatever you do, do not use C++ compiler options to set this yourself.
199,154
<p>I get the following error when trying to load an RSS feed:</p> <blockquote> <p>Attempted to read or write protected memory. This is often an indication that other memory is corrupt.</p> </blockquote> <p>My code works fine from my local host, error only occurs when i upload it to my dedicated server!</p> <p>Here is the code:</p> <pre><code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim signJ As String = DropDownList1.SelectedValue If signJ &lt;&gt; "" Then Try Dim xmlDoc As XmlDocument = New XmlDocument Dim xdsData As XmlDataSource = New XmlDataSource Dim xpath_path As String = String.Empty Dim RSS_Feed As String = String.Empty xpath_path = "rss/channel/item[title='" &amp; signJ &amp; "']" RSS_Feed = "http://feedurl.." xmlDoc.Load(RSS_Feed) xdsData.Data = xmlDoc.OuterXml xdsData.XPath = xpath_path rptData.DataSource = xdsData rptData.DataBind() Catch ex As Exception Response.Write(ex.Message) End Try End If End Sub </code></pre> <p>Error occurs on this line: <code>xmlDoc.Load(RSS_Feed)</code></p> <p>Real stuck on this one! cheers</p>
[ { "answer_id": 199168, "author": "Jonathan S.", "author_id": 2034, "author_profile": "https://Stackoverflow.com/users/2034", "pm_score": 0, "selected": false, "text": "<p>I'm not familiar with this error but have you verified that your security/permissions are set correctly on the dedicated server? </p>\n\n<p>Also you might want to confirm that you can access the feed directly from a browser on the dedicated server.</p>\n\n<p><a href=\"http://forums.asp.net/p/675515/675515.aspx\" rel=\"nofollow noreferrer\">This link</a> may be helpful.</p>\n" }, { "answer_id": 250942, "author": "Todd Smith", "author_id": 31624, "author_profile": "https://Stackoverflow.com/users/31624", "pm_score": 0, "selected": false, "text": "<p>I get the </p>\n\n<blockquote>\n <p>Attempted to read or write protected memory</p>\n</blockquote>\n\n<p>Error when I install .NET 3.5 <strong>SP1</strong> (so I can develop asp.net mvc apps). </p>\n\n<p>Downgrading to .NET 3.5 without the service pack fixes the error but of course prevents me from doing mvc development. Time to dust off the virtual machine.</p>\n" }, { "answer_id": 709369, "author": "PeterFromCologne", "author_id": 36546, "author_profile": "https://Stackoverflow.com/users/36546", "pm_score": 1, "selected": false, "text": "<p>We had the same behaviour as Todd Smith mentions. After the upgrade to .Net 3.5 SP1 we got this error.</p>\n\n<p>In our case the reason was the <strong>protection / obfuscation</strong> of our DLLs with Remotesoft Protector.</p>\n\n<p>This is most likely only our problem and not a solution for anyone else. Nevertheless I thought I'd mention it here cause it did cost us some hours to find out.</p>\n\n<p>If you protect, obfuscate your DLLs: disabling that might be worth a try.</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I get the following error when trying to load an RSS feed: > > Attempted to read or write protected memory. This is often an indication that other memory is corrupt. > > > My code works fine from my local host, error only occurs when i upload it to my dedicated server! Here is the code: ``` Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim signJ As String = DropDownList1.SelectedValue If signJ <> "" Then Try Dim xmlDoc As XmlDocument = New XmlDocument Dim xdsData As XmlDataSource = New XmlDataSource Dim xpath_path As String = String.Empty Dim RSS_Feed As String = String.Empty xpath_path = "rss/channel/item[title='" & signJ & "']" RSS_Feed = "http://feedurl.." xmlDoc.Load(RSS_Feed) xdsData.Data = xmlDoc.OuterXml xdsData.XPath = xpath_path rptData.DataSource = xdsData rptData.DataBind() Catch ex As Exception Response.Write(ex.Message) End Try End If End Sub ``` Error occurs on this line: `xmlDoc.Load(RSS_Feed)` Real stuck on this one! cheers
We had the same behaviour as Todd Smith mentions. After the upgrade to .Net 3.5 SP1 we got this error. In our case the reason was the **protection / obfuscation** of our DLLs with Remotesoft Protector. This is most likely only our problem and not a solution for anyone else. Nevertheless I thought I'd mention it here cause it did cost us some hours to find out. If you protect, obfuscate your DLLs: disabling that might be worth a try.
199,158
<p>I have a table that stores all the volunteers, and each volunteer will be assigned to an appropriate venue to work the event. There is a table that stores all the venues.</p> <p>It stores the volunteer's appropriate venue assignment into the column <code>venue_id</code>.</p> <pre><code>table: venues columns: id, venue_name table: volunteers_2009 columns: id, lname, fname, etc.., venue_id </code></pre> <p>Here is the function to display the list of volunteers, and the problem I am having is to display their venue assignment. I have never worked much with MySQL joins, because this is the first time I have joined two tables together to grab the appropriate info I need.</p> <p>So I want it to go to the volunteers_2009 table, grab the venue_id, go to the venues table, match up <code>volunteers_2009.venue_id to venues.id</code>, to display <code>venues.venue_name</code>, so in the list it will display the volunteer's venue assignment.</p> <p><img src="https://i.stack.imgur.com/83QdA.jpg" alt="alt text"></p> <pre><code>&lt;?php // ----------------------------------------------------- //it displays appropriate columns based on what table you are viewing function displayTable($table, $order, $sort) { $query = "select * from $table ORDER by $order $sort"; $result = mysql_query($query); // volunteer's venue query $query_venues = "SELECT volunteers_2009.venue_id, venues.venue_name FROM volunteers_2009 JOIN venues ON volunteers_2009.venue_id = venues.id"; $result_venues = mysql_query($query_venues); if($_POST) { ?&gt; &lt;table id="box-table-a"&gt; &lt;tr&gt; &lt;th&gt;Name&lt;/th&gt; &lt;?php if($table == 'maillist') { ?&gt; &lt;th&gt;Email&lt;/th&gt; &lt;?php } ?&gt; &lt;?php if($table == 'volunteers_2008' || $table == 'volunteers_2009') { ?&gt; &lt;th&gt;Comments&lt;/th&gt; &lt;?php } ?&gt; &lt;?php if($table == 'volunteers_2009') { ?&gt; &lt;th&gt;Interests&lt;/th&gt; &lt;th&gt;Venue&lt;/th&gt; &lt;?php } ?&gt; &lt;th&gt;Edit&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;?php while($row = mysql_fetch_array($result)) { $i = 0; while($i &lt;=0) { print '&lt;td&gt;'.$row['fname'].' '.$row['lname'].'&lt;/td&gt;'; if($table == 'maillist') { print '&lt;td&gt;&lt;a href="mailto:'.strtolower($row['email']).'"&gt;'.strtolower($row['email']).'&lt;/a&gt;&lt;/td&gt;'; } if($table == 'volunteers_2008' || $table == 'volunteers_2009') { print '&lt;td&gt;&lt;small&gt;'.substr($row['comments'], 0, 32).'&lt;/small&gt;&lt;/td&gt;'; } if($table == 'volunteers_2009') { print '&lt;td&gt;&lt;small&gt;1) '.$row['choice1'].'&lt;br&gt;2) '.$row['choice2'].'&lt;br&gt;3) '.$row['choice3'].'&lt;/small&gt;&lt;/td&gt;'; ?&gt; &lt;td&gt; &lt;?php if($row_venues['venue_name'] != '') { // print venue assigned print $row_venues['venue_id'].' '.$row_venues['venue_name'].' '; } else { print 'No Venue Assigned'; } ?&gt; &lt;/td&gt; &lt;?php } ?&gt; &lt;td&gt;&lt;a href="?mode=upd&amp;id=&lt;?= $row[id] ?&gt;&amp;table=&lt;?= $table ?&gt;"&gt;Upd&lt;/a&gt; / &lt;a href="?mode=del&amp;id=&lt;?= $row[id] ?&gt;&amp;table=&lt;?= $table ?&gt;" onclick="return confirm('Are you sure you want to delete?')"&gt;Del&lt;/a&gt;&lt;/td&gt; &lt;?php $i++; } print '&lt;/tr&gt;'; } print '&lt;/table&gt;'; } } // ----------------------------------------------------- ?&gt; </code></pre>
[ { "answer_id": 199168, "author": "Jonathan S.", "author_id": 2034, "author_profile": "https://Stackoverflow.com/users/2034", "pm_score": 0, "selected": false, "text": "<p>I'm not familiar with this error but have you verified that your security/permissions are set correctly on the dedicated server? </p>\n\n<p>Also you might want to confirm that you can access the feed directly from a browser on the dedicated server.</p>\n\n<p><a href=\"http://forums.asp.net/p/675515/675515.aspx\" rel=\"nofollow noreferrer\">This link</a> may be helpful.</p>\n" }, { "answer_id": 250942, "author": "Todd Smith", "author_id": 31624, "author_profile": "https://Stackoverflow.com/users/31624", "pm_score": 0, "selected": false, "text": "<p>I get the </p>\n\n<blockquote>\n <p>Attempted to read or write protected memory</p>\n</blockquote>\n\n<p>Error when I install .NET 3.5 <strong>SP1</strong> (so I can develop asp.net mvc apps). </p>\n\n<p>Downgrading to .NET 3.5 without the service pack fixes the error but of course prevents me from doing mvc development. Time to dust off the virtual machine.</p>\n" }, { "answer_id": 709369, "author": "PeterFromCologne", "author_id": 36546, "author_profile": "https://Stackoverflow.com/users/36546", "pm_score": 1, "selected": false, "text": "<p>We had the same behaviour as Todd Smith mentions. After the upgrade to .Net 3.5 SP1 we got this error.</p>\n\n<p>In our case the reason was the <strong>protection / obfuscation</strong> of our DLLs with Remotesoft Protector.</p>\n\n<p>This is most likely only our problem and not a solution for anyone else. Nevertheless I thought I'd mention it here cause it did cost us some hours to find out.</p>\n\n<p>If you protect, obfuscate your DLLs: disabling that might be worth a try.</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26130/" ]
I have a table that stores all the volunteers, and each volunteer will be assigned to an appropriate venue to work the event. There is a table that stores all the venues. It stores the volunteer's appropriate venue assignment into the column `venue_id`. ``` table: venues columns: id, venue_name table: volunteers_2009 columns: id, lname, fname, etc.., venue_id ``` Here is the function to display the list of volunteers, and the problem I am having is to display their venue assignment. I have never worked much with MySQL joins, because this is the first time I have joined two tables together to grab the appropriate info I need. So I want it to go to the volunteers\_2009 table, grab the venue\_id, go to the venues table, match up `volunteers_2009.venue_id to venues.id`, to display `venues.venue_name`, so in the list it will display the volunteer's venue assignment. ![alt text](https://i.stack.imgur.com/83QdA.jpg) ``` <?php // ----------------------------------------------------- //it displays appropriate columns based on what table you are viewing function displayTable($table, $order, $sort) { $query = "select * from $table ORDER by $order $sort"; $result = mysql_query($query); // volunteer's venue query $query_venues = "SELECT volunteers_2009.venue_id, venues.venue_name FROM volunteers_2009 JOIN venues ON volunteers_2009.venue_id = venues.id"; $result_venues = mysql_query($query_venues); if($_POST) { ?> <table id="box-table-a"> <tr> <th>Name</th> <?php if($table == 'maillist') { ?> <th>Email</th> <?php } ?> <?php if($table == 'volunteers_2008' || $table == 'volunteers_2009') { ?> <th>Comments</th> <?php } ?> <?php if($table == 'volunteers_2009') { ?> <th>Interests</th> <th>Venue</th> <?php } ?> <th>Edit</th> </tr> <tr> <?php while($row = mysql_fetch_array($result)) { $i = 0; while($i <=0) { print '<td>'.$row['fname'].' '.$row['lname'].'</td>'; if($table == 'maillist') { print '<td><a href="mailto:'.strtolower($row['email']).'">'.strtolower($row['email']).'</a></td>'; } if($table == 'volunteers_2008' || $table == 'volunteers_2009') { print '<td><small>'.substr($row['comments'], 0, 32).'</small></td>'; } if($table == 'volunteers_2009') { print '<td><small>1) '.$row['choice1'].'<br>2) '.$row['choice2'].'<br>3) '.$row['choice3'].'</small></td>'; ?> <td> <?php if($row_venues['venue_name'] != '') { // print venue assigned print $row_venues['venue_id'].' '.$row_venues['venue_name'].' '; } else { print 'No Venue Assigned'; } ?> </td> <?php } ?> <td><a href="?mode=upd&id=<?= $row[id] ?>&table=<?= $table ?>">Upd</a> / <a href="?mode=del&id=<?= $row[id] ?>&table=<?= $table ?>" onclick="return confirm('Are you sure you want to delete?')">Del</a></td> <?php $i++; } print '</tr>'; } print '</table>'; } } // ----------------------------------------------------- ?> ```
We had the same behaviour as Todd Smith mentions. After the upgrade to .Net 3.5 SP1 we got this error. In our case the reason was the **protection / obfuscation** of our DLLs with Remotesoft Protector. This is most likely only our problem and not a solution for anyone else. Nevertheless I thought I'd mention it here cause it did cost us some hours to find out. If you protect, obfuscate your DLLs: disabling that might be worth a try.
199,180
<p>The only thing I can get python omnicomplete to work with are system modules. I get nothing for help with modules in my site-packages or modules that I'm currently working on.</p>
[ { "answer_id": 199636, "author": "technomalogical", "author_id": 6173, "author_profile": "https://Stackoverflow.com/users/6173", "pm_score": 2, "selected": false, "text": "<p>Just ran across this on Python reddit tonight: <a href=\"http://orestis.gr/blog/2008/10/13/pysmell-v06-released/\" rel=\"nofollow noreferrer\">PySmell</a>. Looks like what you're looking for.</p>\n<blockquote>\n<p>PySmell is a python IDE completion helper.</p>\n<p>It tries to statically analyze Python source code, without executing it, and generates information about a project’s structure that IDE tools can use.</p>\n</blockquote>\n" }, { "answer_id": 200227, "author": "Simon Peverett", "author_id": 6063, "author_profile": "https://Stackoverflow.com/users/6063", "pm_score": 0, "selected": false, "text": "<p>I think your after the <a href=\"http://www.vim.org/scripts/script.php?script_id=850\" rel=\"nofollow noreferrer\">pydiction</a> script. It lets you add your own stuff and site-packages to omni complete. </p>\n\n<p>While your at it, add the following to your python.vim file...</p>\n\n<pre><code> set iskeyword+=.\n</code></pre>\n\n<p>This will let you auto-complete package functions e.g. if you enter...</p>\n\n<pre><code> os.path.\n</code></pre>\n\n<p>and then [CTRL][N], you'll get a list of the functions for os.path.</p>\n" }, { "answer_id": 201420, "author": "Jeremy Cantrell", "author_id": 18866, "author_profile": "https://Stackoverflow.com/users/18866", "pm_score": 3, "selected": true, "text": "<p>I get completion for my own modules in my PYTHONPATH or site-packages. I'm not sure what version of the pythoncomplete.vim script you're using, but you may want to make sure it's the latest.</p>\n\n<p>EDIT: Here's some examples of what I'm seeing on my system...</p>\n\n<p>This file (mymodule.py), I puth in a directory in PYTHONPATH, and then in site-packages. Both times I was able to get the screenshot below.</p>\n\n<pre><code>myvar = 'test'\n\ndef myfunction(foo='test'):\n pass\n\nclass MyClass(object):\n pass\n</code></pre>\n" }, { "answer_id": 213253, "author": "andrew", "author_id": 1367022, "author_profile": "https://Stackoverflow.com/users/1367022", "pm_score": 2, "selected": false, "text": "<p>Once I generated ctags for one of my site-packages, it started working for that package -- so I'm guessing that the omnicomplete function depends on ctags for non-sys modules.</p>\n\n<p>EDIT: Not true at all.</p>\n\n<p>Here's the problem -- poor testing on my part -- omnicomplete WAS working for parts of my project, just not most of it.</p>\n\n<p>The issue was that I'm working on a django project, and in order to import django.db, you need to have an environment variable set. Since I couldn't import django.db, any class that inherited from django.db, or any module that imported a class that inherited from django.db wouldn't complete.</p>\n" }, { "answer_id": 851255, "author": "gotgenes", "author_id": 38140, "author_profile": "https://Stackoverflow.com/users/38140", "pm_score": 2, "selected": false, "text": "<p>While it's important to note that you must properly set your <code>PYTHONPATH</code> environmental variable, per the the previous answer, there is a notable <a href=\"http://groups.google.com/group/vim_dev/browse_thread/thread/58191d176ebd9722/d9cd31cee304b7df\" rel=\"nofollow noreferrer\">bug in Vim which prevents omnicompletion from working when an import fails</a>. As of Vim 7.2.79, this bug hasn't been fixed.</p>\n" }, { "answer_id": 1104576, "author": "RobM", "author_id": 83100, "author_profile": "https://Stackoverflow.com/users/83100", "pm_score": 2, "selected": false, "text": "<p>Trouble-shooting tip: verify that the module you are trying to omni-complete can be imported by VIM. I had some syntactically correct Python that VIM didn't like:</p>\n\n<pre><code>:python import {module-name}\n Traceback (most recent call last):\n File \"&lt;string&gt;\", line 1, in ?\n File \"modulename/__init__.py\", line 9\n class empty_paranthesis():\n ^\n SyntaxError: invalid syntax\n</code></pre>\n\n<p>Case-in-point, removing the parenthesis from my class definition allowed VIM to import the module, and subsequently OmniComplete on that module started to work.</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1367022/" ]
The only thing I can get python omnicomplete to work with are system modules. I get nothing for help with modules in my site-packages or modules that I'm currently working on.
I get completion for my own modules in my PYTHONPATH or site-packages. I'm not sure what version of the pythoncomplete.vim script you're using, but you may want to make sure it's the latest. EDIT: Here's some examples of what I'm seeing on my system... This file (mymodule.py), I puth in a directory in PYTHONPATH, and then in site-packages. Both times I was able to get the screenshot below. ``` myvar = 'test' def myfunction(foo='test'): pass class MyClass(object): pass ```
199,182
<p>I'm working on a program that is form based but I have been asked to add some command line support, this works fine apart from the form flashes up and closes down when running from the command line. Is there anyway to hide the form whilst the command line is running? Some code does refer to controls so the gui would need to be accessible but not visible, is this workable?</p>
[ { "answer_id": 199198, "author": "benPearce", "author_id": 4490, "author_profile": "https://Stackoverflow.com/users/4490", "pm_score": 2, "selected": false, "text": "<p>In your Main method you can create the form such as:</p>\n\n<pre><code>main = new MainForm();\n</code></pre>\n\n<p>then do any command line processing required.</p>\n\n<p>When not in command line mode simply call:</p>\n\n<pre><code>Application.Run(main);\n</code></pre>\n" }, { "answer_id": 199446, "author": "Jeff Schumacher", "author_id": 27498, "author_profile": "https://Stackoverflow.com/users/27498", "pm_score": 1, "selected": false, "text": "<p>There are a few apps that I've run across which have this behavior right from the constructor of the form class. Basically their constructor handles the command line arguments and the calls an Environment.Exit(0) when the process for the command line args has completed successfully. Calling Environment.Exit before the constructor of the form class complete effectively prevents the form from ever showing up.</p>\n\n<p>Having said that, it's error prone, and I would say that it's been to not have the form class as the startup of the app. Use another class instead which can instantiate and show the form as needed, or process the command line arguments instead.</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm working on a program that is form based but I have been asked to add some command line support, this works fine apart from the form flashes up and closes down when running from the command line. Is there anyway to hide the form whilst the command line is running? Some code does refer to controls so the gui would need to be accessible but not visible, is this workable?
In your Main method you can create the form such as: ``` main = new MainForm(); ``` then do any command line processing required. When not in command line mode simply call: ``` Application.Run(main); ```
199,219
<p>Im getting frustrated because of OpenDNS and other services (ie: roadrunner) that now always returns a ping even if you type any invalid url ie: lkjsdaflkjdsjf.com --- I had created software for my own use that would ping a url to verify if the site was up or not. This no longer works. Does anyone have any ideas about this?</p> <p>Requirements:</p> <ol> <li>It should work with any valid web site, even ones i dont control</li> <li>It should be able to run from any network that has internet access</li> </ol> <p>I would greatly appreciate to hear how others now handle this. I would like to add, im attempting to do this using System.Net in c#</p> <p>Thank you greatly :-)</p> <p>New addition: Looking for a solution that i can either buy and run on my windows machine, or program in c#. :-)</p> <p><strong>Update:</strong></p> <p>Thank you all very much for your answers. Ultimately i ended up creating a solution by doing this:</p> <ol> <li>Creating a simple webclient that downloaed the specified page from the url (may change to just headers or use this to notify of page changes)</li> <li>Read in xml file that simply lists the full url to the site/pages to check</li> <li>Created a windows service to host the solution so it would recover server restarts.</li> <li>On error an email and text message is sent to defined list of recipients</li> <li>Most values (interval, smtp, to, from, etc) are defined in the .config for easy change</li> </ol> <p>I will be taking some of your advice to add 'features' to this later, which includes:</p> <ul> <li>AJAX page for real-time monitoring. I will use WCF to connect to the existing windows service from the asp.net page</li> <li>Download Headers only (with option for page change comparison)</li> <li>make more configurable (ie: retries on failure before notification)</li> </ul>
[ { "answer_id": 199234, "author": "Sherm Pendley", "author_id": 27631, "author_profile": "https://Stackoverflow.com/users/27631", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.gnu.org/software/wget/\" rel=\"nofollow noreferrer\">Wget</a> is a nice alternative. It will check not only whether the machine is active, but also whether the HTTP server is accepting connections.</p>\n" }, { "answer_id": 199240, "author": "stephenbayer", "author_id": 18893, "author_profile": "https://Stackoverflow.com/users/18893", "pm_score": 2, "selected": false, "text": "<p>To see if a service is up, not only should you ping, but it's good to have scripts that will hit a service, such as a website, and get back a valid response. I've used What's Up Gold in the past, rather than write my own. I like all the features in products like that. such as sending me a page when a service is down.</p>\n" }, { "answer_id": 199243, "author": "Jeff Schumacher", "author_id": 27498, "author_profile": "https://Stackoverflow.com/users/27498", "pm_score": 0, "selected": false, "text": "<p>I've found ping to be very unreliable just because of all the hops you're having to jump through, and something in between can always interfere.</p>\n\n<p>Trying to open up an http connection with a web server is probably the best way to go.</p>\n" }, { "answer_id": 199254, "author": "IAmCodeMonkey", "author_id": 27613, "author_profile": "https://Stackoverflow.com/users/27613", "pm_score": 3, "selected": true, "text": "<p>You could create a simple web page with an address bar for the website and some javascript that uses AJAX to hit a site. If you get any HTTP response other than 200 on the async callback, the site isn't working.</p>\n\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;script language=\"javascript\" type=\"text/javascript\"&gt;\n &lt;!--\n var ajax = new XMLHttpRequest();\n\n function pingSite() {\n ajax.onreadystatechange = stateChanged;\n ajax.open('GET', document.getElementById('siteToCheck').value, true);\n ajax.send(null);\n }\n\n function stateChanged() {\n if (ajax.readyState == 4) {\n if (ajax.status == 200) {\n document.getElementById('statusLabel').innerHTML = \"Success!\";\n }\n else {\n document.getElementById('statusLabel').innerHTML = \"Failure!\";\n }\n }\n }\n --&gt;\n &lt;/script&gt;\n &lt;/head&gt;\n\n &lt;body&gt;\n Site To Check:&lt;br /&gt;\n &lt;input type=\"text\" id=\"siteToCheck\" /&gt;&lt;input type=\"button\" onclick=\"javascript:pingSite()\" /&gt;\n\n &lt;p&gt;\n &lt;span id=\"statusLabel\"&gt;&lt;/span&gt;\n &lt;/p&gt;\n &lt;/body&gt;\n</code></pre>\n\n<p></p>\n\n<p>This code depends on the browser not being IE and I haven't tested it, but it should give you a really good idea.</p>\n" }, { "answer_id": 199264, "author": "dr_pepper", "author_id": 18415, "author_profile": "https://Stackoverflow.com/users/18415", "pm_score": 0, "selected": false, "text": "<p>You could try running 'httping' if you have cygwin available or</p>\n\n<p><a href=\"http://freshmeat.net/projects/httping/\" rel=\"nofollow noreferrer\"><a href=\"http://freshmeat.net/projects/httping/\" rel=\"nofollow noreferrer\">http://freshmeat.net/projects/httping/</a></a></p>\n" }, { "answer_id": 199313, "author": "Michael Kohne", "author_id": 5801, "author_profile": "https://Stackoverflow.com/users/5801", "pm_score": 1, "selected": false, "text": "<p>For the record, lkjsdaflkjdsjf.com is a hostname (which at the moment is not registered to anyone). ping does not work with URLs, ping works with hostnames. hostnames are looked up using the <a href=\"http://en.wikipedia.org/wiki/Domain_name_system\" rel=\"nofollow noreferrer\">Domain Name System</a>. DNS is supposed to fail when hostnames are not registered.</p>\n\n<p>The problem is that some services (apparently your ISP, and definitely OpenDNS) do NOT fail DNS requests for hostnames that aren't registered. Instead they return the IP address of a host on their network that presents a search page to any http request.</p>\n\n<p>You appear to want to know two things: Is the name real (that is, is there a host with this name registered to some actual machine)? and Is that machine functioning?</p>\n\n<p>If you already know that the name in question is real (for instance, you want to know if www.google.com is up), then you can use ping because you know that the name will resolve to a real address (the ISP can't return their IP for a registered name) and you'll only be measuring whether that machine is in operation.</p>\n\n<p>If you don't know whether the name is real, then the problem is harder because your ISP is returning false data to your DNS request. The ONLY solution here is to find a DNS server that is not going to lie to you about unresolved names. </p>\n\n<p>The only way I can think of to differentiate between your ISP's fake records and real ones is to do a <a href=\"http://en.wikipedia.org/wiki/Reverse_DNS_lookup\" rel=\"nofollow noreferrer\">reverse lookup</a> on the IP you get back and see if that IP is in your ISP's network. The problem with this trick is that if the ISP doesn't have reverse DNS info for that IP, you won't know whether it's the ISP or just some knucklehead who didn't configure his DNS properly (I've made that mistake many times in the past).</p>\n\n<p>I'm sure there are other techniques, but the fact that DNS lies underneath everything makes it hard to deal with this problem.</p>\n" }, { "answer_id": 199360, "author": "Martin", "author_id": 24364, "author_profile": "https://Stackoverflow.com/users/24364", "pm_score": 0, "selected": false, "text": "<p>As far as I can see, the problem here that OpenDNS resolves invalid domains back to themselves to forward you on to something close to what you're after (so if you typo ggooggllee.com you end up at the right place via a bounce from the OpenDNS servers). (correct me if I'm wrong)</p>\n\n<p>If that's the case, you should just be able to check whether the IP you've resolved == any of the IPs of OpenDNS? No more ping - no protocol (HTTP) level stuff - just checking for the exceptional case?</p>\n" }, { "answer_id": 199376, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 0, "selected": false, "text": "<p>If you tend toward the sys-admin solution rather than the programming solution you could install a local name server and tell it not to accept anything but NS records for delegation only zones. This was the fix I (and I assumed everyone else on the internet) used when Network Solution/Verisign broke this last time. I installed BIND on a couple of local machine, told my DHCP servers to hand out those addrs as the local name servers, and set up something like the following for each of the delegation only zones that I cared about:</p>\n\n<pre><code>zone \"com\" { type delegation-only; };\nzone \"net\" { type delegation-only; };\n</code></pre>\n\n<p>Come to think of this, I think this might be turned on by default in later BIND versions. As an added bonus you tend to get more stable DNS resolution than most ISPs provide, you control your own cache, a little patching and you don't have to rely on your ISP to fix the latest DNS attack, etc.</p>\n" }, { "answer_id": 199443, "author": "seanb", "author_id": 3354, "author_profile": "https://Stackoverflow.com/users/3354", "pm_score": 1, "selected": false, "text": "<p>Don't directly know of any off the shelf options in c#, although I'd be very suprised if there aren't a few available. </p>\n\n<p>I wrote something similar a few years ago, don't have the code anymore cos it belongs to someone else, but the basic idea was using a WebClient to hit the domain default page, and check for a http status code of 200. </p>\n\n<p>You can then wire any notification logic around the success or fail of this operation. </p>\n\n<p>If bandwidth is a concern you can trim it back to just use a HEAD request. </p>\n\n<p>For more complex sites that you control, you can wire up a health monitoring page that does some more in depth testing before it sends the response, eg is DB connection up etc. </p>\n\n<p>Often a machine that is dead on port 80 will still respond to a ping, so testing port 80 (or whatever other one you are interested in) will be a much more reliable way to go.</p>\n" }, { "answer_id": 199662, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 0, "selected": false, "text": "<p>i like <a href=\"http://www.nov8r.com/calm.aspx\" rel=\"nofollow noreferrer\">CALM</a> for this sort of thing as it logs to a database and provides email notifications as well as a status dashboard</p>\n\n<p>you can set up a test page on the site and periodically do a GET on it to receive either a 'true' result (all is well) or an error message result that gets emailed to you</p>\n\n<p>caveat: i am the author of CALM</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26685/" ]
Im getting frustrated because of OpenDNS and other services (ie: roadrunner) that now always returns a ping even if you type any invalid url ie: lkjsdaflkjdsjf.com --- I had created software for my own use that would ping a url to verify if the site was up or not. This no longer works. Does anyone have any ideas about this? Requirements: 1. It should work with any valid web site, even ones i dont control 2. It should be able to run from any network that has internet access I would greatly appreciate to hear how others now handle this. I would like to add, im attempting to do this using System.Net in c# Thank you greatly :-) New addition: Looking for a solution that i can either buy and run on my windows machine, or program in c#. :-) **Update:** Thank you all very much for your answers. Ultimately i ended up creating a solution by doing this: 1. Creating a simple webclient that downloaed the specified page from the url (may change to just headers or use this to notify of page changes) 2. Read in xml file that simply lists the full url to the site/pages to check 3. Created a windows service to host the solution so it would recover server restarts. 4. On error an email and text message is sent to defined list of recipients 5. Most values (interval, smtp, to, from, etc) are defined in the .config for easy change I will be taking some of your advice to add 'features' to this later, which includes: * AJAX page for real-time monitoring. I will use WCF to connect to the existing windows service from the asp.net page * Download Headers only (with option for page change comparison) * make more configurable (ie: retries on failure before notification)
You could create a simple web page with an address bar for the website and some javascript that uses AJAX to hit a site. If you get any HTTP response other than 200 on the async callback, the site isn't working. ``` <html> <head> <script language="javascript" type="text/javascript"> <!-- var ajax = new XMLHttpRequest(); function pingSite() { ajax.onreadystatechange = stateChanged; ajax.open('GET', document.getElementById('siteToCheck').value, true); ajax.send(null); } function stateChanged() { if (ajax.readyState == 4) { if (ajax.status == 200) { document.getElementById('statusLabel').innerHTML = "Success!"; } else { document.getElementById('statusLabel').innerHTML = "Failure!"; } } } --> </script> </head> <body> Site To Check:<br /> <input type="text" id="siteToCheck" /><input type="button" onclick="javascript:pingSite()" /> <p> <span id="statusLabel"></span> </p> </body> ``` This code depends on the browser not being IE and I haven't tested it, but it should give you a really good idea.
199,235
<p>I am using Oracle adapter from the BizTalk Adapter Pack (WCF based for BTS 2006 R2). In the configuration of the "solicit-response" send ports, I have used Oracle's username and password to connect to the database. </p> <p>Now I would like to change that and use the SSO. So far I have created the Affiliate application and mapped the BTS Host Instance "user id" to the Oracle database user details.</p> <p>When I run the application I am constantly getting the error: "Unable to redeem ticket, no ticket exists in the message".</p> <p>reading through the BTS documentation I found the following at "ms-help://MS.BTS.2006/BTS06CoreDocs/html/c7bf755c-c37d-4b19-9817-a7f42e1e9656.htm": In scenarios where an orchestration invokes the send adapter, the BizTalk Messaging Engine sends the message to the MessageBox database. The orchestration should ensure that both the <strong>SSOTicket</strong> context property and the <strong>Microsoft.BizTalk.XLANGs.BTXEngine.OriginatorSID</strong> context property of the message that contains the ticket are maintained. When the adapter receives this message from the MessageBox database, the adapter calls the RedeemTicket method with the encrypted ticket to retrieve the back-end credentials from the SSO store. The user designing the orchestration should specifically copy this property to the message.</p> <p>But I receive a message through SQL integrated connection, that doesn't have the SSO Ticket.</p> <p>Please help to resolve this issue?</p>
[ { "answer_id": 2384200, "author": "Sam", "author_id": 47636, "author_profile": "https://Stackoverflow.com/users/47636", "pm_score": 2, "selected": false, "text": "<p>You can add an SSO ticket in a custom pipeline component on the send port. The following code works for me:</p>\n\n<pre><code> public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)\n {\n ISSOTicket ssoTicket = new ISSOTicket();\n pInMsg.Context.Write(\"SSOTicket\", \"http://schemas.microsoft.com/BizTalk/2003/system-properties\", ssoTicket.IssueTicket(0));\n return pInMsg;\n }\n</code></pre>\n\n<p>This will generate a ticket for the Biztalk host instance service account, so your Oracle affiliate application mapping should work as you expect.</p>\n" }, { "answer_id": 36615988, "author": "Rajvardhan Agrawal", "author_id": 6202512, "author_profile": "https://Stackoverflow.com/users/6202512", "pm_score": 0, "selected": false, "text": "<p>You might need to \"Allow tickets\" to the System properties in SSO Administrator. Without that it will not work even if you allow tickets to the Affiliate Application.</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am using Oracle adapter from the BizTalk Adapter Pack (WCF based for BTS 2006 R2). In the configuration of the "solicit-response" send ports, I have used Oracle's username and password to connect to the database. Now I would like to change that and use the SSO. So far I have created the Affiliate application and mapped the BTS Host Instance "user id" to the Oracle database user details. When I run the application I am constantly getting the error: "Unable to redeem ticket, no ticket exists in the message". reading through the BTS documentation I found the following at "ms-help://MS.BTS.2006/BTS06CoreDocs/html/c7bf755c-c37d-4b19-9817-a7f42e1e9656.htm": In scenarios where an orchestration invokes the send adapter, the BizTalk Messaging Engine sends the message to the MessageBox database. The orchestration should ensure that both the **SSOTicket** context property and the **Microsoft.BizTalk.XLANGs.BTXEngine.OriginatorSID** context property of the message that contains the ticket are maintained. When the adapter receives this message from the MessageBox database, the adapter calls the RedeemTicket method with the encrypted ticket to retrieve the back-end credentials from the SSO store. The user designing the orchestration should specifically copy this property to the message. But I receive a message through SQL integrated connection, that doesn't have the SSO Ticket. Please help to resolve this issue?
You can add an SSO ticket in a custom pipeline component on the send port. The following code works for me: ``` public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg) { ISSOTicket ssoTicket = new ISSOTicket(); pInMsg.Context.Write("SSOTicket", "http://schemas.microsoft.com/BizTalk/2003/system-properties", ssoTicket.IssueTicket(0)); return pInMsg; } ``` This will generate a ticket for the Biztalk host instance service account, so your Oracle affiliate application mapping should work as you expect.
199,238
<p>I'm writing a lightweight XML editor, and in cases where the user's input is not well formed, I would like to indicate to the user where the problem is, or at least where the first problem is. Does anyone know of an existing algorithm for this? If looking at code helps, if I could fill in the FindIndexOfInvalidXml method (or something like it), this would answer my question.</p> <pre><code>using System; namespace TempConsoleApp { class Program { static void Main(string[] args) { string text = "&lt;?xml version=\"1.0\"?&gt;&lt;tag1&gt;&lt;tag2&gt;Some text.&lt;/taagg2&gt;&lt;/tag1&gt;"; int index = FindIndexOfInvalidXml(text); Console.WriteLine(index); } private static int FindIndexOfInvalidXml(string theString) { int index = -1; //Some logic return index; } } } </code></pre>
[ { "answer_id": 199327, "author": "theraccoonbear", "author_id": 7210, "author_profile": "https://Stackoverflow.com/users/7210", "pm_score": 2, "selected": false, "text": "<p>Unless this is an academic exercise, I think that writing your own XML parser is probably not the best way to go about this. I would probably check out the <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx\" rel=\"nofollow noreferrer\">XmlDocument class</a> within the System.Xml namespace and try/catch <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmlexception.aspx\" rel=\"nofollow noreferrer\">exceptions</a> for the Load() or LoadXml() methods. The exception's message property should contain info on where the error occurred (row/col numbers) and I suspect it'd be easier to use a regular expression to extract those error messages and the related positional info.</p>\n" }, { "answer_id": 199332, "author": "Pseudo Masochist", "author_id": 8529, "author_profile": "https://Stackoverflow.com/users/8529", "pm_score": 4, "selected": true, "text": "<p>I'd probably just cheat. :) This will get you a line number and position:</p>\n\n<pre><code>string s = \"&lt;?xml version=\\\"1.0\\\"?&gt;&lt;tag1&gt;&lt;tag2&gt;Some text.&lt;/taagg2&gt;&lt;/tag1&gt;\";\nSystem.Xml.XmlDocument doc = new System.Xml.XmlDocument();\n\ntry\n{\n doc.LoadXml(s);\n}\ncatch(System.Xml.XmlException ex)\n{\n MessageBox.Show(ex.LineNumber.ToString());\n MessageBox.Show(ex.LinePosition.ToString());\n}\n</code></pre>\n" }, { "answer_id": 199335, "author": "C. Dragon 76", "author_id": 5682, "author_profile": "https://Stackoverflow.com/users/5682", "pm_score": 1, "selected": false, "text": "<p>You should be able to simply load the string into an XmlDocument or an XmlReader and catch XmlException. The XmlException class has a LineNumber property and a LinePosition property.</p>\n\n<p>You can also use XmlValidatingReader if you want to validate against a schema in addition to checking that a document is well-formed.</p>\n" }, { "answer_id": 199339, "author": "Jared", "author_id": 1980, "author_profile": "https://Stackoverflow.com/users/1980", "pm_score": 0, "selected": false, "text": "<p>You'd want to load the string into an XmlDocument object via the load method and then catch any exceptions.</p>\n\n<pre><code>public bool isValidXml(string xml)\n{\n System.Xml.XmlDocument xDoc = null;\n bool valid = false;\n try\n {\n xDoc = new System.Xml.XmlDocument();\n xDoc.loadXml(xmlString);\n valid = true;\n }\n catch\n {\n // trap for errors\n }\n return valid;\n}\n</code></pre>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27109/" ]
I'm writing a lightweight XML editor, and in cases where the user's input is not well formed, I would like to indicate to the user where the problem is, or at least where the first problem is. Does anyone know of an existing algorithm for this? If looking at code helps, if I could fill in the FindIndexOfInvalidXml method (or something like it), this would answer my question. ``` using System; namespace TempConsoleApp { class Program { static void Main(string[] args) { string text = "<?xml version=\"1.0\"?><tag1><tag2>Some text.</taagg2></tag1>"; int index = FindIndexOfInvalidXml(text); Console.WriteLine(index); } private static int FindIndexOfInvalidXml(string theString) { int index = -1; //Some logic return index; } } } ```
I'd probably just cheat. :) This will get you a line number and position: ``` string s = "<?xml version=\"1.0\"?><tag1><tag2>Some text.</taagg2></tag1>"; System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); try { doc.LoadXml(s); } catch(System.Xml.XmlException ex) { MessageBox.Show(ex.LineNumber.ToString()); MessageBox.Show(ex.LinePosition.ToString()); } ```
199,252
<p>I'm considering the best way to design a permissions system for an "admin" web application. The application is likely to have many users, each of whom could be assigned a certain role; some of these users could be permitted to perform specific tasks outside the role.</p> <p>I can think of two ways to design this: one, with a "permissions" table with a row for every user, and boolean columns, one for each task, that assign them permissions to perform those tasks. Like this:</p> <pre> User ID Manage Users Manage Products Manage Promotions Manage Orders 1 true true true true 2 false true true true 3 false false false true </pre> <p>Another way I thought of was to use a bit mask to store these user permissions. This would limit the number of tasks that could be managed to 31 for a 32-bit signed integer, but in practice we're unlikely to have more than 31 specific tasks that a user could perform. This way, the database schema would be simpler, and we wouldn't have to change the table structure every time we added a new task that would need access control. Like this: </p> <pre> User ID Permissions (8-bit mask), would be ints in table 1 00001111 2 00000111 3 00000001 </pre> <p>What mechanisms have people here typically used, and why?</p> <p>Thanks!</p>
[ { "answer_id": 199268, "author": "Levi Rosol", "author_id": 23458, "author_profile": "https://Stackoverflow.com/users/23458", "pm_score": 5, "selected": false, "text": "<p>how about creating a Permission table, then a UserPermission table to store the relationships?</p>\n\n<p>You'll never have to modify the structure again, and you have the ability to add as many permissionss as you wish.</p>\n" }, { "answer_id": 199272, "author": "Dimitry", "author_id": 27073, "author_profile": "https://Stackoverflow.com/users/27073", "pm_score": 0, "selected": false, "text": "<p>Permissions are usually key words with a 1, 0 or null (indicating inherit). With an bit system, you probably cannot create indexes on the user id and permission keyword; instead, you would have to scan every record to get the permission value.</p>\n\n<p>I would say go for the first option. It seems to me the better solution:</p>\n\n<pre><code>create table permissions (\n user_id INT NOT Null,\n permission VARCHAR(255) NOT NULL,\n value TINYINT(1) NULL\n)\nalter table `permissions` ADD PRIMARY KEY ( `user_id` , `permission` ) \n</code></pre>\n" }, { "answer_id": 199287, "author": "stephenbayer", "author_id": 18893, "author_profile": "https://Stackoverflow.com/users/18893", "pm_score": 5, "selected": false, "text": "<p>I've done it both ways. But I don't use bit masks much anymore. A separate table would be fine that you can use as a cross reference, given a user id or a group id as a foreign key. </p>\n\n<pre><code>UserID | Permission\n===================\n1 | 1 1 representing manage users\n1 | 2 2 being manger products\n2 | 3 \n</code></pre>\n\n<p>This way would be easier to maintain and add on to later on. </p>\n\n<p>I'd also use a separate table to manage what the permissions are. </p>\n\n<pre><code>PermissionID | Description\n==========================\n1 | Manage Users\n2 | Manager Products\n</code></pre>\n" }, { "answer_id": 199297, "author": "TimB", "author_id": 4193, "author_profile": "https://Stackoverflow.com/users/4193", "pm_score": 1, "selected": false, "text": "<p>I've seen a number of somewhat limited permissions systems similar to what you're suggesting -- as well as some truly terrible systems. In some simple situations they can be acceptable, as long as the application doesn't get more complex. However, in so many cases, they do get more complicated, and the systems have to be rewritten to accommodate the required functionality.</p>\n\n<p>If you think you might someday need the expressiveness, I'd go with a full ACL (access control list) system with users and groups (or roles). That is, each thing governed by permissions (e.g. \"manage users\", \"manage products\") has an ACL, which is a list of all users and groups that have access to it. Then users are either added directly to the relevant ACLs, or added to a group that's already a member of an ACL.</p>\n\n<p>Although ACL suggests a list implementation, you'd be better off with a table; <a href=\"https://stackoverflow.com/questions/199252/what-is-the-best-way-to-manage-permissions-for-a-web-application-bitmask-or-dat#199287\">this answer</a> is a good way.</p>\n" }, { "answer_id": 199304, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 7, "selected": true, "text": "<p>I think it's a general rule of thumb to stay away from mystical bitstrings that encode the meaning of the universe.</p>\n\n<p>While perhaps clunkier, having a table of possible permissions, a table of users, and a link table between them is the best and clearest way to organize this. It also makes your queries and maintenance (especially for the new guy) a lot easier.</p>\n" }, { "answer_id": 199312, "author": "J c", "author_id": 25837, "author_profile": "https://Stackoverflow.com/users/25837", "pm_score": 2, "selected": false, "text": "<p>I'd suggest abstracting your web application permissions with the concept of a Role Provider. As of version 2.0, this is provided for you in .NET as <a href=\"http://msdn.microsoft.com/en-us/library/system.web.security.roleprovider.aspx\" rel=\"nofollow noreferrer\">System.Web.Security.RoleProvider</a>.</p>\n\n<p>The basic idea is that you leverage an existing framework by writing your permission checks against the framework rather than a specific storage mechanism. You can then plug-in whatever storage mechanism is available, whether it's an XML file, a database, or even an <a href=\"http://technet.microsoft.com/en-us/library/cc737065.aspx\" rel=\"nofollow noreferrer\">authorization store</a> using the Windows software Authorization Manager (which lets you seamlessly tie in your custom permissions to LDAP, as one example - no code required to configure).</p>\n\n<p>If you decide to use a database as a storage mechanism, several databases are supported for the automatic creation of the underlying tables that the framework needs. This includes running .NET on Mono and using the role provider model on top of MySQL.</p>\n\n<p>See <a href=\"http://msdn.microsoft.com/en-us/library/8fw7xh74.aspx\" rel=\"nofollow noreferrer\">Implementing a Role Provider</a> for more information. It is entirely possible that other languages/environments also have libraries you could leverage to implement this concept - it would be worth looking into.</p>\n\n<p><strong>EDIT</strong>: I should also point out the configuration of how your web application ties in to the storage mechanism is done through a web.config file, and doesn't require code changes. I have found this very useful to test a production version of a codebase on my local machine, using an XML file to mimic permissions instead of the normal database provider - all by modifying two lines in web.config.</p>\n\n<p>The other thing I forgot to mention is that you can plug-in your own custom providers by extending the base classes, allowing you to leverage the permission model but still use a proprietary storage system (eg. bit masks, if you really wanted to).</p>\n" }, { "answer_id": 199450, "author": "Chad Braun-Duin", "author_id": 5458, "author_profile": "https://Stackoverflow.com/users/5458", "pm_score": 3, "selected": false, "text": "<p>Usually I have a Users table, a Roles table, and a UserRoles table. This way you can have an unlimited amount of roles without changing your db structure and users can be in multiple roles.</p>\n\n<p>I force the application to only authorize against roles (never users). Notice how the \"id\" column in the roles table is not an identity column. This is because you may need to control the IDs which get put in this table because your application is going to have to look for specific IDs.</p>\n\n<p>The structure looks like this:</p>\n\n<pre><code>create table Users (\n id int identity not null,\n loginId varchar(30) not null,\n firstName varchar(50) not null,\n etc...\n)\n\ncreate table Roles (\n id int not null,\n name varchar(50) not null\n)\n\ncreate table UserRoles (\n userId int not null,\n roleId int not null\n)\n</code></pre>\n" }, { "answer_id": 739129, "author": "Ed Blackburn", "author_id": 27962, "author_profile": "https://Stackoverflow.com/users/27962", "pm_score": 2, "selected": false, "text": "<p>You could use Active Directory or another LDAP implementation if you're in a managed environment. That way the security groups, which determine permissions can be managed by first line support, using a technology they're most likely already familiar with.</p>\n\n<p>If your app is shrink wrapped then +1 for Levi Rosol's suggestion of normalising the database so that you can have an extensible data model in your app.</p>\n" }, { "answer_id": 57105611, "author": "Bobby Dawson", "author_id": 4147551, "author_profile": "https://Stackoverflow.com/users/4147551", "pm_score": 1, "selected": false, "text": "<p>Can't comment because I am new to SO, but in regards to the accepted answer - a huge advantage that comes with this solution is the ability to universally handle permissions, instead of just if statements everywhere in the code, as well as special abilities such as allowing temporary permissions (permissions that have an expiration date)</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27649/" ]
I'm considering the best way to design a permissions system for an "admin" web application. The application is likely to have many users, each of whom could be assigned a certain role; some of these users could be permitted to perform specific tasks outside the role. I can think of two ways to design this: one, with a "permissions" table with a row for every user, and boolean columns, one for each task, that assign them permissions to perform those tasks. Like this: ``` User ID Manage Users Manage Products Manage Promotions Manage Orders 1 true true true true 2 false true true true 3 false false false true ``` Another way I thought of was to use a bit mask to store these user permissions. This would limit the number of tasks that could be managed to 31 for a 32-bit signed integer, but in practice we're unlikely to have more than 31 specific tasks that a user could perform. This way, the database schema would be simpler, and we wouldn't have to change the table structure every time we added a new task that would need access control. Like this: ``` User ID Permissions (8-bit mask), would be ints in table 1 00001111 2 00000111 3 00000001 ``` What mechanisms have people here typically used, and why? Thanks!
I think it's a general rule of thumb to stay away from mystical bitstrings that encode the meaning of the universe. While perhaps clunkier, having a table of possible permissions, a table of users, and a link table between them is the best and clearest way to organize this. It also makes your queries and maintenance (especially for the new guy) a lot easier.
199,263
<p>The title may not really explain what I'm really trying to get at, couldn't really think of a way to describe what I mean.</p> <p>I was wondering if it is good practice to check the arguments that a function accepts for nulls or empty before using them. I have this function which just wraps some hash creation like so.</p> <pre><code>Public Shared Function GenerateHash(ByVal FilePath As IO.FileInfo) As String If (FilePath Is Nothing) Then Throw New ArgumentNullException("FilePath") End If Dim _sha As New Security.Cryptography.MD5CryptoServiceProvider Dim _Hash = Convert.ToBase64String(_sha.ComputeHash(New IO.FileStream(FilePath.FullName, IO.FileMode.Open, IO.FileAccess.Read))) Return _Hash End Function </code></pre> <p>As you can see I just takes a IO.Fileinfo as an argument, at the start of the function I am checking to make sure that it is not nothing. </p> <p>I'm wondering is this good practice or should I just let it get to the actual hasher and then throw the exception because it is null.?</p> <p>Thanks.</p>
[ { "answer_id": 199276, "author": "gnud", "author_id": 27204, "author_profile": "https://Stackoverflow.com/users/27204", "pm_score": 1, "selected": false, "text": "<p>If NULL is an inacceptable input, throw an exception. By yourself, like you did in your sample, so that the message is helpful.</p>\n\n<p>Another method of handling NULL inputs is just to respont with a NULL in turn. Depends on the type of function -- in the example above I would keep the exception.</p>\n" }, { "answer_id": 199285, "author": "Garry Shutler", "author_id": 6369, "author_profile": "https://Stackoverflow.com/users/6369", "pm_score": 1, "selected": false, "text": "<p>If its for an externally facing API then I would say you want to check every parameter as the input cannot be trusted.</p>\n\n<p>However, if it is only going to be used internally then the input should be able to be trusted and you can save yourself a bunch of code that's not adding value to the software.</p>\n" }, { "answer_id": 199289, "author": "razlebe", "author_id": 27615, "author_profile": "https://Stackoverflow.com/users/27615", "pm_score": 5, "selected": true, "text": "<p>In general, I'd suggest it's good practice to validate all of the arguments to public functions/methods before using them, and fail early rather than after executing half of the function. In this case, you're right to throw the exception.</p>\n\n<p>Depending on what your method is doing, failing early could be important. If your method was altering instance data on your class, you don't want it to alter half of the data, then encounter the null and throw an exception, as your object's data might them be in an intermediate and possibly invalid state. </p>\n\n<p>If you're using an OO language then I'd suggest it's essential to validate the arguments to public methods, but less important with private and protected methods. My rationale here is that you don't know what the inputs to a public method will be - any other code could create an instance of your class and call it's public methods, and pass in unexpected/invalid data. Private methods, however, are called from inside the class, and the class should already have validated any data passing around internally. </p>\n" }, { "answer_id": 199290, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 0, "selected": false, "text": "<p>Most of the time, letting it just throw the exception is pretty reasonable as long as you are sure the exception won't be ignored.</p>\n\n<p>If you can add something to it, however, it doesn't hurt to wrap the exception with one that is more accurate and rethrow it. Decoding \"NullPointerException\" is going to take a bit longer than \"IllegalArgumentException(\"FilePath MUST be supplied\")\" (Or whatever).</p>\n\n<p>Lately I've been working on a platform where you have to run an obfuscator before you test. Every stack trace looks like monkeys typing random crap, so I got in the habit of checking my arguments all the time. </p>\n\n<p>I'd love to see a \"nullable\" or \"nonull\" modifier on variables and arguments so the compiler can check for you.</p>\n" }, { "answer_id": 199292, "author": "C. Dragon 76", "author_id": 5682, "author_profile": "https://Stackoverflow.com/users/5682", "pm_score": 2, "selected": false, "text": "<p>Yes, it's good practice to validate all arguments at the beginning of a method and throw appropriate exceptions like ArgumentException, ArgumentNullException, or ArgumentOutOfRangeException.</p>\n\n<p>If the method is private such that only you the programmer could pass invalid arguments, then you may choose to assert each argument is valid (Debug.Assert) instead of throw.</p>\n" }, { "answer_id": 199294, "author": "James Fassett", "author_id": 27081, "author_profile": "https://Stackoverflow.com/users/27081", "pm_score": 2, "selected": false, "text": "<p>One of my favourite techniques in C++ was to DEBUG_ASSERT on NULL pointers. This was drilled into me by senior programmers (along with const correctness) and is one of the things I was most strict on during code reviews. We <em>never</em> dereferenced a pointer without first asserting it wasn't null.</p>\n\n<p>A debug assert is only active for debug targets (it gets stripped in release) so you don't have the extra overhead in production to test for thousands of if's. Generally it would either throw an exception or trigger a hardware breakpoint. We even had systems that would throw up a debug console with the file/line info and an option to ignore the assert (once or indefinitely for the session). That was such a great debug and QA tool (we'd get screenshots with the assert on the testers screen and information on whether the program continued if ignored).</p>\n\n<p>I suggest asserting all invariants in your code including unexpected nulls. If performance of the if's becomes a concern find a way to conditionally compile and keep them active in debug targets. Like source control, this is a technique that has saved my ass more often than it has caused me grief (the most important litmus test of any development technique).</p>\n" }, { "answer_id": 199300, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 0, "selected": false, "text": "<p>If you're writing a public API, do your caller the favor of helping them find their bugs quickly, and check for valid inputs.</p>\n\n<p>If you're writing an API where the caller might untrusted (or the caller of the caller), checked for valid inputs, because it's good security.</p>\n\n<p>If your APIs are only reachable by trusted callers, like \"internal\" in C#, then don't feel like you have to write all that extra code. It won't be useful to anyone.</p>\n" }, { "answer_id": 199308, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 1, "selected": false, "text": "<p>You should check all arguments against the set of assumptions that you make in that function about their values.</p>\n\n<p>As in your example, if a null argument to your function doesn't make any sense and you're assuming that anyone using your function will know this then being passed a null argument shows some sort of error and some sort of action taken (eg. throwing an exception). And if you use asserts (as James Fassett got in and said before me ;-) ) they cost you nothing in a release version. (they cost you almost nothing in a debug version either)</p>\n\n<p>The same thing applies to any other assumption.</p>\n\n<p>And it's going to be easier to trace the error if you generate it than if you leave it to some standard library routine to throw the exception. You will be able to provide much more useful contextual information.</p>\n\n<p>It's outside the bounds of this question, but you do need to expose the assumptions that your function makes - for example, through the comment header to your function.</p>\n" }, { "answer_id": 199533, "author": "Brian", "author_id": 18192, "author_profile": "https://Stackoverflow.com/users/18192", "pm_score": 1, "selected": false, "text": "<p>According to <em>The Pragmatic Programmer</em> by Andrew Hunt and David Thomas, it is the responsibility of the caller to make sure it gives valid input. So, you must now choose whether you consider a null input to be valid. Unless it makes specific sense to consider null to be a valid input (e.g. it is probably a good idea to consider null to be a legal input if you're testing for equality), I would consider it invalid. That way your program, when it hits incorrect input, will fail sooner. If your program is going to encounter an error condition, you want it to happen as soon as possible. In the event your function does inadvertently get passed a null, you should consider it to be a bug, and react accordingly (i.e. instead of throwing an exception, you should consider making use of an assertion that kills the program, until you are releasing the program).</p>\n\n<p>Classic design by contract: If input is right, output will be right. If input is wrong, there is a bug. (if input is right but output is wrong, there is a bug. That's a gimme.)</p>\n" }, { "answer_id": 199831, "author": "6eorge Jetson", "author_id": 23422, "author_profile": "https://Stackoverflow.com/users/23422", "pm_score": 1, "selected": false, "text": "<p>I'll add a couple of elaborations (<b>in bold</b>) to the excellent design by contract advice offerred by Brian earlier...</p>\n\n<p>The priniples of \"design by contract\" require that you define what is acceptable for the caller to pass in (the valid domain of input values) and then, for any valid input, what the method/provider will do. </p>\n\n<p>For an internal method, you can define NULLs as outside the domain of valid input parameters. In this case, you would immediately assert that the input parameter value is NOT NULL. <b>The key insight in this contract specification is that any call passing in a NULL value <i>IS A CALLER'S BUG</i> and the error thrown by the assert statement is the proper behavior.</b></p>\n\n<p>Now, while very well defined and parsimonius, if you're exposing the method to external/public callers, you should ask yourself, is that the contract I/we really want?\nProbably not. In a public interface, you'd probably accept the NULL (as technically in the domain of inputs that the method accepts), but then decline to process gracefully w/ a return message. (More work to meet the naturally more complex customer-facing requirement.)</p>\n\n<p>In either case, <b>what you're after is a protocol that handles all of the cases from both the perspective of the caller and the provider, not lots of scattershot tests that can make it difficult to assess the completeness or lack of completeness of the contractual condition coverage.</b></p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6335/" ]
The title may not really explain what I'm really trying to get at, couldn't really think of a way to describe what I mean. I was wondering if it is good practice to check the arguments that a function accepts for nulls or empty before using them. I have this function which just wraps some hash creation like so. ``` Public Shared Function GenerateHash(ByVal FilePath As IO.FileInfo) As String If (FilePath Is Nothing) Then Throw New ArgumentNullException("FilePath") End If Dim _sha As New Security.Cryptography.MD5CryptoServiceProvider Dim _Hash = Convert.ToBase64String(_sha.ComputeHash(New IO.FileStream(FilePath.FullName, IO.FileMode.Open, IO.FileAccess.Read))) Return _Hash End Function ``` As you can see I just takes a IO.Fileinfo as an argument, at the start of the function I am checking to make sure that it is not nothing. I'm wondering is this good practice or should I just let it get to the actual hasher and then throw the exception because it is null.? Thanks.
In general, I'd suggest it's good practice to validate all of the arguments to public functions/methods before using them, and fail early rather than after executing half of the function. In this case, you're right to throw the exception. Depending on what your method is doing, failing early could be important. If your method was altering instance data on your class, you don't want it to alter half of the data, then encounter the null and throw an exception, as your object's data might them be in an intermediate and possibly invalid state. If you're using an OO language then I'd suggest it's essential to validate the arguments to public methods, but less important with private and protected methods. My rationale here is that you don't know what the inputs to a public method will be - any other code could create an instance of your class and call it's public methods, and pass in unexpected/invalid data. Private methods, however, are called from inside the class, and the class should already have validated any data passing around internally.
199,266
<p>How can I make xargs execute the command exactly once for each line of input given? It's default behavior is to chunk the lines and execute the command once, passing multiple lines to each instance. </p> <blockquote> <p>From <a href="http://en.wikipedia.org/wiki/Xargs" rel="noreferrer">http://en.wikipedia.org/wiki/Xargs</a>: </p> <p>find /path -type f -print0 | xargs -0 rm</p> <p>In this example, find feeds the input of xargs with a long list of file names. xargs then splits this list into sublists and calls rm once for every sublist. This is more efficient than this functionally equivalent version:</p> <p>find /path -type f -exec rm '{}' \;</p> </blockquote> <p>I know that find has the "exec" flag. I am just quoting an illustrative example from another resource.</p>
[ { "answer_id": 199270, "author": "Draemon", "author_id": 26334, "author_profile": "https://Stackoverflow.com/users/26334", "pm_score": 10, "selected": true, "text": "<p>The following will only work if you do not have spaces in your input:</p>\n\n<pre><code>xargs -L 1\nxargs --max-lines=1 # synonym for the -L option\n</code></pre>\n\n<p>\nfrom the man page:</p>\n\n<pre><code>-L max-lines\n Use at most max-lines nonblank input lines per command line.\n Trailing blanks cause an input line to be logically continued on\n the next input line. Implies -x.\n</code></pre>\n" }, { "answer_id": 199293, "author": "readonly", "author_id": 4883, "author_profile": "https://Stackoverflow.com/users/4883", "pm_score": 2, "selected": false, "text": "<p>You can limit the number of lines, or arguments (if there are spaces between each argument) using the --max-lines or --max-args flags, respectively.</p>\n<blockquote>\n<pre><code> -L max-lines\n Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input\n line. Implies -x.\n\n --max-lines[=max-lines], -l[max-lines]\n Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-args is not specified, it defaults to one. The -l option\n is deprecated since the POSIX standard specifies -L instead.\n\n --max-args=max-args, -n max-args\n Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded,\n unless the -x option is given, in which case xargs will exit.\n</code></pre>\n</blockquote>\n" }, { "answer_id": 199324, "author": "Sherm Pendley", "author_id": 27631, "author_profile": "https://Stackoverflow.com/users/27631", "pm_score": -1, "selected": false, "text": "<p>In your example, the point of piping the output of find to xargs is that the standard behavior of find's -exec option is to execute the command once for each found file. If you're using find, and you want its standard behavior, then the answer is simple - don't use xargs to begin with.</p>\n" }, { "answer_id": 199325, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 5, "selected": false, "text": "<p>If you want to run the command for <em>every</em> line (i.e. result) coming from <code>find</code>, then what do you need the <code>xargs</code> for?</p>\n\n<p>Try:</p>\n\n<p><code>find</code> <em>path</em> <code>-type f -exec</code> <em>your-command</em> <code>{} \\;</code></p>\n\n<p>where the literal <code>{}</code> gets substituted by the filename and the literal <code>\\;</code> is needed for <code>find</code> to know that the custom command ends there.</p>\n\n<h1>EDIT:</h1>\n\n<p>(after the edit of your question clarifying that you know about <code>-exec</code>)</p>\n\n<p>From <code>man xargs</code>:</p>\n\n<blockquote>\n <p><strong>-L</strong> <em>max-lines</em><br>\n Use at most <em>max-lines</em> nonblank input lines per command line. Trailing\n blanks cause an input line to be logically continued on the next input line.\n Implies -x.</p>\n</blockquote>\n\n<p>Note that filenames ending in blanks would cause you trouble if you use <code>xargs</code>:</p>\n\n<pre><code>$ mkdir /tmp/bax; cd /tmp/bax\n$ touch a\\ b c\\ c\n$ find . -type f -print | xargs -L1 wc -l\n0 ./c\n0 ./c\n0 total\n0 ./b\nwc: ./a: No such file or directory\n</code></pre>\n\n<p>So if you don't care about the <code>-exec</code> option, you better use <code>-print0</code> and <code>-0</code>:</p>\n\n<pre><code>$ find . -type f -print0 | xargs -0L1 wc -l\n0 ./c\n0 ./c\n0 ./b\n0 ./a\n</code></pre>\n" }, { "answer_id": 199396, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<pre><code>find path -type f | xargs -L1 command \n</code></pre>\n\n<p>is all you need.</p>\n" }, { "answer_id": 948716, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The following command will find all the files (-type f) in <code>/path</code> and then copy them using <code>cp</code> to the current folder. Note the use if <code>-I %</code> to specify a placeholder character in the <code>cp</code> command line so that arguments can be placed after the file name.</p>\n\n<p><code>find /path -type f -print0 | xargs -0 -I % cp % .</code></p>\n\n<p>Tested with xargs (GNU findutils) 4.4.0</p>\n" }, { "answer_id": 2646238, "author": "sergiofbsilva", "author_id": 317605, "author_profile": "https://Stackoverflow.com/users/317605", "pm_score": -1, "selected": false, "text": "<p>execute ant task clean-all on every build.xml on current or sub-folder.</p>\n\n<pre><code>find . -name 'build.xml' -exec ant -f {} clean-all \\;\n</code></pre>\n" }, { "answer_id": 13930396, "author": "Richard", "author_id": 1912470, "author_profile": "https://Stackoverflow.com/users/1912470", "pm_score": 4, "selected": false, "text": "<p>Another alternative...</p>\n\n<pre><code>find /path -type f | while read ln; do echo \"processing $ln\"; done\n</code></pre>\n" }, { "answer_id": 25319740, "author": "Alex Riedler", "author_id": 3943248, "author_profile": "https://Stackoverflow.com/users/3943248", "pm_score": 4, "selected": false, "text": "<p>These two ways also work, and will work for other commands that are not using find!</p>\n\n<pre><code>xargs -I '{}' rm '{}'\nxargs -i rm '{}'\n</code></pre>\n\n<p>example use case:</p>\n\n<pre><code>find . -name \"*.pyc\" | xargs -i rm '{}'\n</code></pre>\n\n<p>will delete all pyc files under this directory even if the pyc files contain spaces.</p>\n" }, { "answer_id": 28806991, "author": "Tobia", "author_id": 517371, "author_profile": "https://Stackoverflow.com/users/517371", "pm_score": 8, "selected": false, "text": "<p>It seems to me all existing answers on this page are wrong, including the one marked as correct. That stems from the fact that the question is ambiguously worded.</p>\n<p><strong>Summary:</strong>   If you want to execute the command <em>&quot;exactly once for each line of input,&quot;</em> passing the entire line (without newline) to the command as a <em>single argument,</em> then this is the best UNIX-compatible way to do it:</p>\n<pre><code>... | tr '\\n' '\\0' | xargs -0 -n1 ...\n</code></pre>\n<p>If you are using GNU <code>xargs</code> and don't need to be compatible with all other UNIX's (FreeBSD, Mac OS X, etc.) then you can use the GNU-specific option <code>-d</code>:</p>\n<pre><code>... | xargs -d\\\\n -n1 ...\n</code></pre>\n<p>Now for the long explanation…</p>\n<hr />\n<p>There are two issues to take into account when using xargs:</p>\n<ol>\n<li>how does it split the input into &quot;arguments&quot;; and</li>\n<li>how many arguments to pass the child command at a time.</li>\n</ol>\n<p>To test xargs' behavior, we need an utility that shows how many times it's being executed and with how many arguments. I don't know if there is a standard utility to do that, but we can code it quite easily in bash:</p>\n<pre><code>#!/bin/bash\necho -n &quot;-&gt; &quot;; for a in &quot;$@&quot;; do echo -n &quot;\\&quot;$a\\&quot; &quot;; done; echo\n</code></pre>\n<p>Assuming you save it as <code>show</code> in your current directory and make it executable, here is how it works:</p>\n<pre><code>$ ./show one two 'three and four'\n-&gt; &quot;one&quot; &quot;two&quot; &quot;three and four&quot; \n</code></pre>\n<p>Now, if the original question is really about point 2. above (as I think it is, after reading it a few times over) and it is to be read like this (changes in bold):</p>\n<blockquote>\n<p><em>How can I make xargs execute the command exactly once for each <strong>argument</strong> of input given? Its default behavior is to chunk the <strong>input into arguments</strong> and execute the command <strong>as few times as possible</strong>, passing multiple <strong>arguments</strong> to each instance.</em></p>\n</blockquote>\n<p>then the answer is <code>-n 1</code>.</p>\n<p>Let's compare xargs' default behavior, which splits the input around whitespace and calls the command as few times as possible:</p>\n<pre><code>$ echo one two 'three and four' | xargs ./show \n-&gt; &quot;one&quot; &quot;two&quot; &quot;three&quot; &quot;and&quot; &quot;four&quot; \n</code></pre>\n<p>and its behavior with <code>-n 1</code>:</p>\n<pre><code>$ echo one two 'three and four' | xargs -n 1 ./show \n-&gt; &quot;one&quot; \n-&gt; &quot;two&quot; \n-&gt; &quot;three&quot; \n-&gt; &quot;and&quot; \n-&gt; &quot;four&quot; \n</code></pre>\n<p>If, on the other hand, the original question was about point 1. input splitting and it was to be read like this (many people coming here seem to think that's the case, or are confusing the two issues):</p>\n<blockquote>\n<p><em>How can I make xargs execute the command <strong>with</strong> exactly <strong>one argument</strong> for each line of input given? Its default behavior is to chunk the lines <strong>around whitespace</strong>.</em></p>\n</blockquote>\n<p>then the answer is more subtle.</p>\n<p>One would think that <code>-L 1</code> could be of help, but it turns out it doesn't change argument parsing. It only executes the command once for each input line, with as many arguments as were there on that input line:</p>\n<pre><code>$ echo $'one\\ntwo\\nthree and four' | xargs -L 1 ./show \n-&gt; &quot;one&quot; \n-&gt; &quot;two&quot; \n-&gt; &quot;three&quot; &quot;and&quot; &quot;four&quot; \n</code></pre>\n<p>Not only that, but if a line ends with whitespace, it is appended to the next:</p>\n<pre><code>$ echo $'one \\ntwo\\nthree and four' | xargs -L 1 ./show \n-&gt; &quot;one&quot; &quot;two&quot; \n-&gt; &quot;three&quot; &quot;and&quot; &quot;four&quot; \n</code></pre>\n<p>Clearly, <code>-L</code> is not about changing the way xargs splits the input into arguments.</p>\n<p>The only argument that does so in a cross-platform fashion (excluding GNU extensions) is <code>-0</code>, which splits the input around NUL bytes.</p>\n<p>Then, it's just a matter of translating newlines to NUL with the help of <code>tr</code>:</p>\n<pre><code>$ echo $'one \\ntwo\\nthree and four' | tr '\\n' '\\0' | xargs -0 ./show \n-&gt; &quot;one &quot; &quot;two&quot; &quot;three and four&quot; \n</code></pre>\n<p>Now the argument parsing looks all right, including the trailing whitespace.</p>\n<p>Finally, if you combine this technique with <code>-n 1</code>, you get exactly one command execution per input line, whatever input you have, which may be yet another way to look at the original question (possibly the most intuitive, given the title):</p>\n<pre><code>$ echo $'one \\ntwo\\nthree and four' | tr '\\n' '\\0' | xargs -0 -n1 ./show \n-&gt; &quot;one &quot; \n-&gt; &quot;two&quot; \n-&gt; &quot;three and four&quot; \n</code></pre>\n<p>As mentioned above, if you are using GNU <code>xargs</code> you can replace the <code>tr</code> with the GNU-specific option <code>-d</code>:</p>\n<pre><code>$ echo $'one \\ntwo\\nthree and four' | xargs -d\\\\n -n1 ./show \n-&gt; &quot;one &quot; \n-&gt; &quot;two&quot; \n-&gt; &quot;three and four&quot; \n</code></pre>\n" }, { "answer_id": 30104264, "author": "Gray", "author_id": 179850, "author_profile": "https://Stackoverflow.com/users/179850", "pm_score": 5, "selected": false, "text": "<blockquote>\n <p>How can I make xargs execute the command exactly once for each line of input given?</p>\n</blockquote>\n\n<p><code>-L 1</code> is the simple solution but it does not work if any of the files contain spaces in them. This is a key function of find's <code>-print0</code> argument – to separate the arguments by '\\0' character instead of whitespace. Here's an example:</p>\n\n<pre><code>echo \"file with space.txt\" | xargs -L 1 ls\nls: file: No such file or directory\nls: with: No such file or directory\nls: space.txt: No such file or directory\n</code></pre>\n\n<p>A better solution is to use <code>tr</code> to convert newlines to null (<code>\\0</code>) characters, and then use the <code>xargs -0</code> argument. Here's an example:</p>\n\n<pre><code>echo \"file with space.txt\" | tr '\\n' '\\0' | xargs -0 ls\nfile with space.txt\n</code></pre>\n\n<p>If you then need to limit the number of calls you can use the <code>-n 1</code> argument to make one call to the program for each input:</p>\n\n<pre><code>echo \"file with space.txt\" | tr '\\n' '\\0' | xargs -0 -n 1 ls\n</code></pre>\n\n<p>This also allows you to filter the output of find <em>before</em> converting the breaks into nulls.</p>\n\n<pre><code>find . -name \\*.xml | grep -v /target/ | tr '\\n' '\\0' | xargs -0 tar -cf xml.tar\n</code></pre>\n" }, { "answer_id": 35820260, "author": "CrashNeb", "author_id": 5844631, "author_profile": "https://Stackoverflow.com/users/5844631", "pm_score": 0, "selected": false, "text": "<p>It seems I don't have enough reputation to add a comment to <a href=\"https://stackoverflow.com/a/28806991/5844631\">Tobia's answer above</a>, so I am adding this \"answer\" to help those of us wanting to experiment with <code>xargs</code> the same way on the Windows platforms.</p>\n\n<p>Here is a windows batch file that does the same thing as Tobia's quickly coded \"show\" script:</p>\n\n<pre><code>@echo off\nREM\nREM cool trick of using \"set\" to echo without new line\nREM (from: http://www.psteiner.com/2012/05/windows-batch-echo-without-new-line.html)\nREM\nif \"%~1\" == \"\" (\n exit /b\n)\n\n&lt;nul set /p=Args: \"%~1\"\nshift\n\n:start\nif not \"%~1\" == \"\" (\n &lt;nul set /p=, \"%~1\"\n shift\n goto start\n)\necho.\n</code></pre>\n" }, { "answer_id": 53754994, "author": "Mohammad Karmi", "author_id": 1865719, "author_profile": "https://Stackoverflow.com/users/1865719", "pm_score": 1, "selected": false, "text": "<p>@Draemon answers seems to be right with \"-0\" even with space in the file.</p>\n\n<p>I was trying the xargs command and I found that \"-0\" works perfectly with \"-L\". even the spaces are treated (if input was null terminated ). the following is an example :</p>\n\n<pre><code>#touch \"file with space\"\n#touch \"file1\"\n#touch \"file2\"\n</code></pre>\n\n<p>The following will split the nulls and execute the command on each argument in the list :</p>\n\n<pre><code> #find . -name 'file*' -print0 | xargs -0 -L1\n./file with space\n./file1\n./file2\n</code></pre>\n\n<p>so <code>-L1</code> will execute the argument on each null terminated character if used with \"-0\". To see the difference try :</p>\n\n<pre><code> #find . -name 'file*' -print0 | xargs -0 | xargs -L1\n ./file with space ./file1 ./file2\n</code></pre>\n\n<p>even this will execute once :</p>\n\n<pre><code> #find . -name 'file*' -print0 | xargs -0 | xargs -0 -L1\n./file with space ./file1 ./file2\n</code></pre>\n\n<p>The command will execute once as the \"-L\" now doesn't split on null byte. you need to provide both \"-0\" and \"-L\" to work. </p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
How can I make xargs execute the command exactly once for each line of input given? It's default behavior is to chunk the lines and execute the command once, passing multiple lines to each instance. > > From <http://en.wikipedia.org/wiki/Xargs>: > > > find /path -type f -print0 | xargs -0 rm > > > In this example, find feeds the input of xargs with a long list of file names. xargs then splits this list into sublists and calls rm once for every sublist. This is more efficient than this functionally equivalent version: > > > find /path -type f -exec rm '{}' \; > > > I know that find has the "exec" flag. I am just quoting an illustrative example from another resource.
The following will only work if you do not have spaces in your input: ``` xargs -L 1 xargs --max-lines=1 # synonym for the -L option ``` from the man page: ``` -L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. ```
199,333
<p>I was writing a program in C++ to find all solutions of <em>a</em><sup><em>b</em></sup> = <em>c</em>, where <em>a</em>, <em>b</em> and <em>c</em> together use all the digits 0-9 exactly once. The program looped over values of <em>a</em> and <em>b</em>, and it ran a digit-counting routine each time on <em>a</em>, <em>b</em> and <em>a<sup>b</sup></em> to check if the digits condition was satisfied.</p> <p>However, spurious solutions can be generated when <em>a</em><sup><em>b</em></sup> overflows the integer limit. I ended up checking for this using code like:</p> <pre><code>unsigned long b, c, c_test; ... c_test=c*b; // Possible overflow if (c_test/b != c) {/* There has been an overflow*/} else c=c_test; // No overflow </code></pre> <p>Is there a better way of testing for overflow? I know that some chips have an internal flag that is set when overflow occurs, but I've never seen it accessed through C or C++.</p> <hr> <p>Beware that <strong><em>signed</em> <code>int</code> overflow is undefined behaviour in C and C++</strong>, and thus you have to detect it without actually causing it. For signed int overflow before addition, see <em><a href="https://stackoverflow.com/questions/3944505/detecting-signed-overflow-in-c-c">Detecting signed overflow in C/C++</a></em>.</p>
[ { "answer_id": 199353, "author": "Jonathan Allen", "author_id": 5274, "author_profile": "https://Stackoverflow.com/users/5274", "pm_score": -1, "selected": false, "text": "<p>Inline assembly lets you check the overflow bit directly. If you are going to be using C++, you really should learn assembly.</p>\n" }, { "answer_id": 199354, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 4, "selected": false, "text": "<p>The simplest way is to convert your <code>unsigned long</code>s into <code>unsigned long long</code>s, do your multiplication, and compare the result to 0x100000000LL.</p>\n\n<p>You'll probably find that this is more efficient than doing the division as you've done in your example.</p>\n\n<p>Oh, and it'll work in both C and C++ (as you've tagged the question with both).</p>\n\n<hr>\n\n<p>Just been taking a look at the <a href=\"http://www.gnu.org/software/libc/manual/html_node/Program-Error-Signals.html#Program%20Error%20Signals\" rel=\"noreferrer\">glibc manual</a>. There's a mention of an integer overflow trap (<code>FPE_INTOVF_TRAP</code>) as part of <code>SIGFPE</code>. That would be ideal, apart from the nasty bits in the manual:</p>\n\n<blockquote>\n <p><code>FPE_INTOVF_TRAP</code>\n Integer overflow (impossible in a C program unless you enable overflow trapping in a hardware-specific fashion). </p>\n</blockquote>\n\n<p>A bit of a shame really.</p>\n" }, { "answer_id": 199355, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 4, "selected": false, "text": "<p>You can't access the overflow flag from C/C++.</p>\n\n<p>Some compilers allow you to insert trap instructions into the code. On GCC the option is <code>-ftrapv</code>.</p>\n\n<p>The only portable and compiler independent thing you can do is to check for overflows on your own. Just like you did in your example.</p>\n\n<p>However, <code>-ftrapv</code> seems to do nothing on x86 using the latest GCC. I guess it's a leftover from an old version or specific to some other architecture. I had expected the compiler to insert an INTO opcode after each addition. Unfortunately it does not do this.</p>\n" }, { "answer_id": 199363, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 6, "selected": false, "text": "<p>Some compilers provide access to the integer overflow flag in the CPU which you could then test but this isn't standard.</p>\n\n<p>You could also test for the possibility of overflow before you perform the multiplication:</p>\n\n<pre><code>if ( b &gt; ULONG_MAX / a ) // a * b would overflow\n</code></pre>\n" }, { "answer_id": 199375, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": -1, "selected": false, "text": "<p>A clean way to do it would be to override all operators (+ and * in particular) and check for an overflow before performing the operations.</p>\n" }, { "answer_id": 199407, "author": "Tarski", "author_id": 27653, "author_profile": "https://Stackoverflow.com/users/27653", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>You can't access the overflow flag from C/C++.</p>\n</blockquote>\n\n<p>I don't agree with this. You could write some inline assembly language and use a <code>jo</code> (jump overflow) instruction assuming you are on x86 to trap the overflow. Of course, your code would no longer be portable to other architectures.</p>\n\n<p>Look at <code>info as</code> and <code>info gcc</code>.</p>\n" }, { "answer_id": 199455, "author": "Head Geek", "author_id": 12193, "author_profile": "https://Stackoverflow.com/users/12193", "pm_score": 7, "selected": false, "text": "<p>There <em>is</em> a way to determine whether an operation is likely to overflow, using the positions of the most-significant one-bits in the operands and a little basic binary-math knowledge.</p>\n\n<p>For addition, any two operands will result in (at most) one bit more than the largest operand's highest one-bit. For example:</p>\n\n<pre><code>bool addition_is_safe(uint32_t a, uint32_t b) {\n size_t a_bits=highestOneBitPosition(a), b_bits=highestOneBitPosition(b);\n return (a_bits&lt;32 &amp;&amp; b_bits&lt;32);\n}\n</code></pre>\n\n<p>For multiplication, any two operands will result in (at most) the sum of the bits of the operands. For example:</p>\n\n<pre><code>bool multiplication_is_safe(uint32_t a, uint32_t b) {\n size_t a_bits=highestOneBitPosition(a), b_bits=highestOneBitPosition(b);\n return (a_bits+b_bits&lt;=32);\n}\n</code></pre>\n\n<p>Similarly, you can estimate the maximum size of the result of <code>a</code> to the power of <code>b</code> like this:</p>\n\n<pre><code>bool exponentiation_is_safe(uint32_t a, uint32_t b) {\n size_t a_bits=highestOneBitPosition(a);\n return (a_bits*b&lt;=32);\n}\n</code></pre>\n\n<p>(Substitute the number of bits for your target integer, of course.)</p>\n\n<p>I'm not sure of the fastest way to determine the position of the highest one-bit in a number, here's a brute-force method:</p>\n\n<pre><code>size_t highestOneBitPosition(uint32_t a) {\n size_t bits=0;\n while (a!=0) {\n ++bits;\n a&gt;&gt;=1;\n };\n return bits;\n}\n</code></pre>\n\n<p>It's not perfect, but that'll give you a good idea whether any two numbers could overflow before you do the operation. I don't know whether it would be faster than simply checking the result the way you suggested, because of the loop in the <code>highestOneBitPosition</code> function, but it might (especially if you knew how many bits were in the operands beforehand).</p>\n" }, { "answer_id": 199668, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 5, "selected": false, "text": "<p>If you have a datatype which is bigger than the one you want to test (say you do a 32-bit add and you have a 64-bit type), then this will detect if an overflow occurred. My example is for an 8-bit add. But it can be scaled up.</p>\n\n<pre><code>uint8_t x, y; /* Give these values */\nconst uint16_t data16 = x + y;\nconst bool carry = (data16 &gt; 0xFF);\nconst bool overflow = ((~(x ^ y)) &amp; (x ^ data16) &amp; 0x80);\n</code></pre>\n\n<p>It is based on the concepts explained on this page: <a href=\"http://www.cs.umd.edu/class/spring2003/cmsc311/Notes/Comb/overflow.html\" rel=\"nofollow noreferrer\">http://www.cs.umd.edu/class/spring2003/cmsc311/Notes/Comb/overflow.html</a></p>\n\n<p>For a 32-bit example, <code>0xFF</code> becomes <code>0xFFFFFFFF</code> and <code>0x80</code> becomes <code>0x80000000</code> and finally <code>uint16_t</code> becomes a <code>uint64_t</code>.</p>\n\n<p><strong>NOTE</strong>: this catches integer addition/subtraction overflows, and I realized that your question involves multiplication. In which case, division is likely the best approach. This is commonly a way that <code>calloc</code> implementations make sure that the parameters don't overflow as they are multiplied to get the final size.</p>\n" }, { "answer_id": 200258, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 3, "selected": false, "text": "<p>Calculate the results with doubles. They have 15 significant digits. Your requirement has a hard upper bound on <em>c</em> of 10<sup>8</sup>&thinsp;&mdash;&thinsp;it can have at most 8 digits. Hence, the result will be precise if it's in range, and it will not overflow otherwise.</p>\n" }, { "answer_id": 202325, "author": "Frank Szczerba", "author_id": 8964, "author_profile": "https://Stackoverflow.com/users/8964", "pm_score": -1, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/199333/how-do-i-detect-unsigned-integer-multiply-overflow/200258#200258\">MSalter's answer</a> is a good idea.</p>\n\n<p>If the integer calculation is required (for precision), but floating point is available, you could do something like:</p>\n\n<pre><code>uint64_t foo(uint64_t a, uint64_t b) {\n double dc;\n\n dc = pow(a, b);\n\n if (dc &lt; UINT_MAX) {\n return (powu64(a, b));\n }\n else {\n // Overflow\n }\n}\n</code></pre>\n" }, { "answer_id": 528249, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>For unsigned integers, just check that the result is smaller than one of the arguments:</p>\n\n<pre><code>unsigned int r, a, b;\nr = a + b;\nif (r &lt; a)\n{\n // Overflow\n}\n</code></pre>\n\n<p>For signed integers you can check the signs of the arguments and of the result.</p>\n\n<p>Integers of different signs can't overflow, and integers of the same sign overflow only if the result is of a different sign:</p>\n\n<pre><code>signed int r, a, b, s;\nr = a + b;\ns = a&gt;=0;\nif (s == (b&gt;=0) &amp;&amp; s != (r&gt;=0))\n{\n // Overflow\n}\n</code></pre>\n" }, { "answer_id": 1514246, "author": "Robert C. Seacord", "author_id": 183661, "author_profile": "https://Stackoverflow.com/users/183661", "pm_score": 3, "selected": false, "text": "<p>CERT has developed a new approach to detecting and reporting signed integer overflow, unsigned integer wrapping, and integer truncation using the \"as-if\" infinitely ranged (AIR) integer model. CERT has published a <a href=\"http://www.sei.cmu.edu/library/abstracts/reports/09tn023.cfm\" rel=\"noreferrer\">technical report</a> describing the model and produced a working prototype based on GCC 4.4.0 and GCC 4.5.0. </p>\n\n<p>The AIR integer model either produces a value equivalent to one that would have been obtained using infinitely ranged integers or results in a runtime constraint violation. Unlike previous integer models, AIR integers do not require precise traps, and consequently do not break or inhibit most existing optimizations.</p>\n" }, { "answer_id": 1514309, "author": "pmg", "author_id": 25324, "author_profile": "https://Stackoverflow.com/users/25324", "pm_score": 8, "selected": false, "text": "<p>I see you're using unsigned integers. By definition, <strong>in C</strong> (I don't know about C++), unsigned arithmetic does not overflow ... so, at least for C, your point is moot :)</p>\n<p>With signed integers, once there has been overflow, <a href=\"http://en.wikipedia.org/wiki/Undefined_behavior\" rel=\"noreferrer\">undefined behaviour</a> (UB) has occurred and your program can do anything (for example: render tests inconclusive). </p>\n<pre><code>#include &lt;limits.h&gt;\n\nint a = &lt;something&gt;;\nint x = &lt;something&gt;;\na += x; /* UB */\nif (a &lt; 0) { /* Unreliable test */\n /* ... */\n}\n</code></pre>\n<p>To create a conforming program, you need to test for overflow <strong>before</strong> generating said overflow. The method can be used with unsigned integers too:</p>\n<pre><code>// For addition\n#include &lt;limits.h&gt;\n\nint a = &lt;something&gt;;\nint x = &lt;something&gt;;\nif (x &gt; 0 &amp;&amp; a &gt; INT_MAX - x) // `a + x` would overflow\nif (x &lt; 0 &amp;&amp; a &lt; INT_MIN - x) // `a + x` would underflow\n</code></pre>\n<hr />\n<pre><code>// For subtraction\n#include &lt;limits.h&gt;\nint a = &lt;something&gt;;\nint x = &lt;something&gt;;\nif (x &lt; 0 &amp;&amp; a &gt; INT_MAX + x) // `a - x` would overflow\nif (x &gt; 0 &amp;&amp; a &lt; INT_MIN + x) // `a - x` would underflow\n</code></pre>\n<hr />\n<pre><code>// For multiplication\n#include &lt;limits.h&gt;\n\nint a = &lt;something&gt;;\nint x = &lt;something&gt;;\n// There may be a need to check for -1 for two's complement machines.\n// If one number is -1 and another is INT_MIN, multiplying them we get abs(INT_MIN) which is 1 higher than INT_MAX\nif (a == -1 &amp;&amp; x == INT_MIN) // `a * x` can overflow\nif (x == -1 &amp;&amp; a == INT_MIN) // `a * x` (or `a / x`) can overflow\n// general case\nif (x != 0 &amp;&amp; a &gt; INT_MAX / x) // `a * x` would overflow\nif (x != 0 &amp;&amp; a &lt; INT_MIN / x) // `a * x` would underflow\n</code></pre>\n<hr />\n<p>For division (except for the <code>INT_MIN</code> and <code>-1</code> special case), there isn't any possibility of going over <code>INT_MIN</code> or <code>INT_MAX</code>.</p>\n" }, { "answer_id": 2751112, "author": "Blaisorblade", "author_id": 53974, "author_profile": "https://Stackoverflow.com/users/53974", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.fefe.de/intof.html\" rel=\"noreferrer\">Catching Integer Overflows in C</a> points out a solution more general than the one discussed by CERT (it is more general in term of handled types), even if it requires some GCC extensions (I don't know how widely supported they are).</p>\n" }, { "answer_id": 2751206, "author": "Dustin", "author_id": 233239, "author_profile": "https://Stackoverflow.com/users/233239", "pm_score": -1, "selected": false, "text": "<p>The simple way to test for overflow is to do validation by checking whether the current value is less than the previous value. For example, suppose you had a loop to print the powers of 2:</p>\n\n<pre><code>long lng;\nint n;\nfor (n = 0; n &lt; 34; ++n)\n{\n lng = pow (2, n);\n printf (\"%li\\n\", lng);\n}\n</code></pre>\n\n<p>Adding overflow checking the way that I described results in this:</p>\n\n<pre><code>long signed lng, lng_prev = 0;\nint n;\nfor (n = 0; n &lt; 34; ++n)\n{\n lng = pow (2, n);\n if (lng &lt;= lng_prev)\n {\n printf (\"Overflow: %i\\n\", n);\n /* Do whatever you do in the event of overflow. */\n }\n printf (\"%li\\n\", lng);\n lng_prev = lng;\n}\n</code></pre>\n\n<p>It works for unsigned values as well as both positive and negative signed values.</p>\n\n<p>Of course, if you wanted to do something similar for decreasing values instead of increasing values, you would flip the <code>&lt;=</code> sign to make it <code>&gt;=</code>, assuming the behaviour of underflow is the same as the behaviour of overflow. In all honesty, that's about as portable as you'll get without access to a CPU's overflow flag (and that would require inline assembly code, making your code non-portable across implementations anyway).</p>\n" }, { "answer_id": 6472982, "author": "DX-MON", "author_id": 814674, "author_profile": "https://Stackoverflow.com/users/814674", "pm_score": 5, "selected": false, "text": "<p>Here is a really fast way to detect overflow for at least additions, which might give a lead for multiplication, division and power-of.</p>\n<p>The idea is that exactly because the processor will just let the value wrap back to zero and that C/C++ is to abstracted from any specific processor, you can:</p>\n<pre><code>uint32_t x, y;\nuint32_t value = x + y;\nbool overflow = value &lt; (x | y);\n</code></pre>\n<p>This both ensures that if one operand is zero and one isn't, then overflow won't be falsely detected and is significantly faster than a lot of NOT/XOR/AND/test operations as previously suggested.</p>\n<p>As pointed out, this approach, although better than other more elaborate ways, is still optimisable. The following is a revision of the original code containing the optimisation:</p>\n<pre><code>uint32_t x, y;\nuint32_t value = x + y;\nconst bool overflow = value &lt; x; // Alternatively &quot;value &lt; y&quot; should also work\n</code></pre>\n<p>A more efficient and cheap way to detect multiplication overflow is:</p>\n<pre><code>uint32_t x, y;\nconst uint32_t a = (x &gt;&gt; 16U) * (y &amp; 0xFFFFU);\nconst uint32_t b = (x &amp; 0xFFFFU) * (y &gt;&gt; 16U);\nconst bool overflow = ((x &gt;&gt; 16U) * (y &gt;&gt; 16U)) +\n (a &gt;&gt; 16U) + (b &gt;&gt; 16U);\nuint32_t value = overflow ? UINT32_MAX : x * y;\n</code></pre>\n<p>This results in either UINT32_MAX on overflow, or the result of the multiplication. <em>It is strictly undefined behaviour to allow the multiplication to proceed for signed integers in this case.</em></p>\n<p>Of note, this uses the partial Karatsuba method multiplicative decomposition to compute the high 32 bits of the 64-bit multiplication to check if any of them should become set to know if the 32-bit multiplication overflows.</p>\n<p>If using C++, you can turn this into a neat little lambda to compute overflow so the inner workings of the detector get hidden:</p>\n<pre><code>uint32_t x, y;\nconst bool overflow\n{\n [](const uint32_t x, const uint32_t y) noexcept -&gt; bool\n {\n const uint32_t a{(x &gt;&gt; 16U) * uint16_t(y)};\n const uint32_t b{uint16_t(x) * (y &gt;&gt; 16U)};\n return ((x &gt;&gt; 16U) * (y &gt;&gt; 16U)) + (a &gt;&gt; 16U) + (b &gt;&gt; 16U);\n }(x, y)\n};\nuint32_t value{overflow ? UINT32_MAX : x * y};\n</code></pre>\n" }, { "answer_id": 6822698, "author": "A Fog", "author_id": 862391, "author_profile": "https://Stackoverflow.com/users/862391", "pm_score": 6, "selected": false, "text": "<p>Warning: GCC can optimize away an overflow check when compiling with <code>-O2</code>.\nThe option <code>-Wall</code> will give you a warning in some cases like</p>\n\n<pre><code>if (a + b &lt; a) { /* Deal with overflow */ }\n</code></pre>\n\n<p>but not in this example:</p>\n\n<pre><code>b = abs(a);\nif (b &lt; 0) { /* Deal with overflow */ }\n</code></pre>\n\n<p>The only safe way is to check for overflow before it occurs, as described in the <a href=\"https://www.securecoding.cert.org/confluence/display/seccode/INT32-C.+Ensure+that+operations+on+signed+integers+do+not+result+in+overflow?showComments=false\" rel=\"noreferrer\">CERT paper</a>, and this would be incredibly tedious to use systematically.</p>\n\n<p>Compiling with <code>-fwrapv</code> solves the problem, but disables some optimizations.</p>\n\n<p>We desperately need a better solution. I think the compiler should issue a warning by default when making an optimization that relies on overflow not occurring. The present situation allows the compiler to optimize away an overflow check, which is unacceptable in my opinion.</p>\n" }, { "answer_id": 10687629, "author": "Paul Chernoch", "author_id": 127251, "author_profile": "https://Stackoverflow.com/users/127251", "pm_score": 4, "selected": false, "text": "<p>I needed to answer this same question for floating point numbers, where bit masking and shifting does not look promising. The approach I settled on works for signed and unsigned, integer and floating point numbers. It works even if there is no larger data type to promote to for intermediate calculations. It is not the most efficient for all of these types, but because it does work for all of them, it is worth using.</p>\n\n<p>Signed Overflow test, Addition and Subtraction:</p>\n\n<ol>\n<li><p>Obtain the constants that represent the largest and smallest possible values for the type,\nMAXVALUE and MINVALUE.</p></li>\n<li><p>Compute and compare the signs of the operands. </p>\n\n<p>a. If either value is zero, then neither addition nor subtraction can overflow. Skip remaining tests.</p>\n\n<p>b. If the signs are opposite, then addition cannot overflow. Skip remaining tests.</p>\n\n<p>c. If the signs are the same, then subtraction cannot overflow. Skip remaining tests.</p></li>\n<li><p>Test for positive overflow of MAXVALUE.</p>\n\n<p>a. If both signs are positive and MAXVALUE - A &lt; B, then addition will overflow.</p>\n\n<p>b. If the sign of B is negative and MAXVALUE - A &lt; -B, then subtraction will overflow.</p></li>\n<li><p>Test for negative overflow of MINVALUE.</p>\n\n<p>a. If both signs are negative and MINVALUE - A > B, then addition will overflow.</p>\n\n<p>b. If the sign of A is negative and MINVALUE - A > B, then subtraction will overflow.</p></li>\n<li><p>Otherwise, no overflow.</p></li>\n</ol>\n\n<p>Signed Overflow test, Multiplication and Division:</p>\n\n<ol>\n<li><p>Obtain the constants that represent the largest and smallest possible values for the type,\nMAXVALUE and MINVALUE.</p></li>\n<li><p>Compute and compare the magnitudes (absolute values) of the operands to one. (Below, assume A and B are these magnitudes, not the signed originals.)</p>\n\n<p>a. If either value is zero, multiplication cannot overflow, and division will yield zero or an infinity.</p>\n\n<p>b. If either value is one, multiplication and division cannot overflow.</p>\n\n<p>c. If the magnitude of one operand is below one and of the other is greater than one, multiplication cannot overflow.</p>\n\n<p>d. If the magnitudes are both less than one, division cannot overflow.</p></li>\n<li><p>Test for positive overflow of MAXVALUE.</p>\n\n<p>a. If both operands are greater than one and MAXVALUE / A &lt; B, then multiplication will overflow.</p>\n\n<p>b. If B is less than one and MAXVALUE * B &lt; A, then division will overflow.</p></li>\n<li><p>Otherwise, no overflow.</p></li>\n</ol>\n\n<p>Note: Minimum overflow of MINVALUE is handled by 3, because we took absolute values. However, if\nABS(MINVALUE) > MAXVALUE, then we will have some rare false positives.</p>\n\n<p>The tests for underflow are similar, but involve EPSILON (the smallest positive number greater than zero).</p>\n" }, { "answer_id": 12726956, "author": "Willem Hengeveld", "author_id": 1049677, "author_profile": "https://Stackoverflow.com/users/1049677", "pm_score": 3, "selected": false, "text": "<p>Another interesting tool is <em><a href=\"http://embed.cs.utah.edu/ioc/\" rel=\"nofollow noreferrer\">IOC: An Integer Overflow Checker for C/C++</a></em>.</p>\n\n<p>This is a patched <a href=\"http://en.wikipedia.org/wiki/Clang\" rel=\"nofollow noreferrer\">Clang</a> compiler, which adds checks to the code at compile time.</p>\n\n<p>You get output looking like this:</p>\n\n<pre><code>CLANG ARITHMETIC UNDEFINED at &lt;add.c, (9:11)&gt; :\nOp: +, Reason : Signed Addition Overflow,\nBINARY OPERATION: left (int32): 2147483647 right (int32): 1\n</code></pre>\n" }, { "answer_id": 13764376, "author": "Angel Sinigersky", "author_id": 754396, "author_profile": "https://Stackoverflow.com/users/754396", "pm_score": 5, "selected": false, "text": "<p>Here is a \"non-portable\" solution to the question. The Intel x86 and x64 CPUs have the so-called <a href=\"http://en.wikipedia.org/wiki/EFLAGS\" rel=\"nofollow noreferrer\">EFLAGS-register</a>, which is filled in by the processor after each integer arithmetic operation. I will skip a detailed description here. The relevant flags are the \"Overflow\" Flag (mask 0x800) and the \"Carry\" Flag (mask 0x1). To interpret them correctly, one should consider if the operands are of signed or unsigned type.</p>\n\n<p>Here is a practical way to check the flags from C/C++. The following code will work on <a href=\"http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2005\" rel=\"nofollow noreferrer\">Visual Studio 2005</a> or newer (both 32 and 64 bit), as well as on GNU C/C++ 64 bit.</p>\n\n<pre><code>#include &lt;cstddef&gt;\n#if defined( _MSC_VER )\n#include &lt;intrin.h&gt;\n#endif\n\ninline size_t query_intel_x86_eflags(const size_t query_bit_mask)\n{\n #if defined( _MSC_VER )\n\n return __readeflags() &amp; query_bit_mask;\n\n #elif defined( __GNUC__ )\n // This code will work only on 64-bit GNU-C machines.\n // Tested and does NOT work with Intel C++ 10.1!\n size_t eflags;\n __asm__ __volatile__(\n \"pushfq \\n\\t\"\n \"pop %%rax\\n\\t\"\n \"movq %%rax, %0\\n\\t\"\n :\"=r\"(eflags)\n :\n :\"%rax\"\n );\n return eflags &amp; query_bit_mask;\n\n #else\n\n #pragma message(\"No inline assembly will work with this compiler!\")\n return 0;\n #endif\n}\n\nint main(int argc, char **argv)\n{\n int x = 1000000000;\n int y = 20000;\n int z = x * y;\n int f = query_intel_x86_eflags(0x801);\n printf(\"%X\\n\", f);\n}\n</code></pre>\n\n<p>If the operands were multiplied without overflow, you would get a return value of 0 from <code>query_intel_eflags(0x801)</code>, i.e. neither the carry nor the overflow flags are set. In the provided example code of main(), an overflow occurs and the both flags are set to 1. This check does not imply any further calculations, so it should be quite fast.</p>\n" }, { "answer_id": 14568062, "author": "ZAB", "author_id": 942218, "author_profile": "https://Stackoverflow.com/users/942218", "pm_score": 5, "selected": false, "text": "<p>Clang now supports dynamic overflow checks for both signed and unsigned integers. See the <a href=\"http://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#availablle-checks\" rel=\"noreferrer\">-fsanitize=integer</a> switch. For now, it is the only C++ compiler with fully supported dynamic overflow checking for debug purposes.</p>\n" }, { "answer_id": 14859480, "author": "Steztric", "author_id": 1069178, "author_profile": "https://Stackoverflow.com/users/1069178", "pm_score": 0, "selected": false, "text": "<p>To expand on Head Geek's answer, there is a faster way to do the <code>addition_is_safe</code>;</p>\n\n<pre><code>bool addition_is_safe(unsigned int a, unsigned int b)\n{\n unsigned int L_Mask = std::numeric_limits&lt;unsigned int&gt;::max();\n L_Mask &gt;&gt;= 1;\n L_Mask = ~L_Mask;\n\n a &amp;= L_Mask;\n b &amp;= L_Mask;\n\n return ( a == 0 || b == 0 );\n}\n</code></pre>\n\n<p>This uses machine-architecture safe, in that 64-bit and 32-bit unsigned integers will still work fine. Basically, I create a mask that will mask out all but the most significant bit. Then, I mask both integers, and if either of them do not have that bit set, then addition is safe.</p>\n\n<p>This would be even faster if you pre-initialize the mask in some constructor, since it never changes.</p>\n" }, { "answer_id": 15330077, "author": "hdante", "author_id": 1797000, "author_profile": "https://Stackoverflow.com/users/1797000", "pm_score": 5, "selected": false, "text": "<p>I see that a lot of people answered the question about overflow, but I wanted to address his original problem. He said the problem was to find a<sup>b</sup>=c such that all digits are used without repeating. Ok, that's not what he asked in this post, but I'm still think that it was necessary to study the upper bound of the problem and conclude that he would never need to calculate or detect an overflow (note: I'm not proficient in math so I did this step by step, but the end result was so simple that this might have a simple formula).</p>\n\n<p>The main point is that the upper bound that the problem requires for either a, b or c is 98.765.432. Anyway, starting by splitting the problem in the trivial and non trivial parts:</p>\n\n<ul>\n<li>x<sup>0</sup> == 1 (all permutations of 9, 8, 7, 6, 5, 4, 3, 2 are solutions)</li>\n<li>x<sup>1</sup> == x (no solution possible)</li>\n<li>0<sup>b</sup> == 0 (no solution possible)</li>\n<li>1<sup>b</sup> == 1 (no solution possible)</li>\n<li>a<sup>b</sup>, a > 1, b > 1 (non trivial)</li>\n</ul>\n\n<p>Now we just need to show that no other solution is possible and only the permutations are valid (and then the code to print them is trivial). We go back to the upper bound. Actually the upper bound is c ≤ 98.765.432. It's the upper bound because it's the largest number with 8 digits (10 digits total minus 1 for each a and b). This upper bound is only for c because the bounds for a and b must be much lower because of the exponential growth, as we can calculate, varying b from 2 to the upper bound:</p>\n\n<pre><code> 9938.08^2 == 98765432\n 462.241^3 == 98765432\n 99.6899^4 == 98765432\n 39.7119^5 == 98765432\n 21.4998^6 == 98765432\n 13.8703^7 == 98765432\n 9.98448^8 == 98765432\n 7.73196^9 == 98765432\n 6.30174^10 == 98765432\n 5.33068^11 == 98765432\n 4.63679^12 == 98765432\n 4.12069^13 == 98765432\n 3.72429^14 == 98765432\n 3.41172^15 == 98765432\n 3.15982^16 == 98765432\n 2.95305^17 == 98765432\n 2.78064^18 == 98765432\n 2.63493^19 == 98765432\n 2.51033^20 == 98765432\n 2.40268^21 == 98765432\n 2.30883^22 == 98765432\n 2.22634^23 == 98765432\n 2.15332^24 == 98765432\n 2.08826^25 == 98765432\n 2.02995^26 == 98765432\n 1.97741^27 == 98765432\n</code></pre>\n\n<p>Notice, for example the last line: it says that 1.97^27 ~98M. So, for example, 1^27 == 1 and 2^27 == 134.217.728 and that's not a solution because it has 9 digits (2 > 1.97 so it's actually bigger than what should be tested). As it can be seen, the combinations available for testing a and b are really small. For b == 14, we need to try 2 and 3. For b == 3, we start at 2 and stop at 462. All the results are granted to be less than ~98M.</p>\n\n<p>Now just test all the combinations above and look for the ones that do not repeat any digits:</p>\n\n<pre><code> ['0', '2', '4', '5', '6', '7', '8'] 84^2 = 7056\n ['1', '2', '3', '4', '5', '8', '9'] 59^2 = 3481\n ['0', '1', '2', '3', '4', '5', '8', '9'] 59^2 = 3481 (+leading zero)\n ['1', '2', '3', '5', '8'] 8^3 = 512\n ['0', '1', '2', '3', '5', '8'] 8^3 = 512 (+leading zero)\n ['1', '2', '4', '6'] 4^2 = 16\n ['0', '1', '2', '4', '6'] 4^2 = 16 (+leading zero)\n ['1', '2', '4', '6'] 2^4 = 16\n ['0', '1', '2', '4', '6'] 2^4 = 16 (+leading zero)\n ['1', '2', '8', '9'] 9^2 = 81\n ['0', '1', '2', '8', '9'] 9^2 = 81 (+leading zero)\n ['1', '3', '4', '8'] 3^4 = 81\n ['0', '1', '3', '4', '8'] 3^4 = 81 (+leading zero)\n ['2', '3', '6', '7', '9'] 3^6 = 729\n ['0', '2', '3', '6', '7', '9'] 3^6 = 729 (+leading zero)\n ['2', '3', '8'] 2^3 = 8\n ['0', '2', '3', '8'] 2^3 = 8 (+leading zero)\n ['2', '3', '9'] 3^2 = 9\n ['0', '2', '3', '9'] 3^2 = 9 (+leading zero)\n ['2', '4', '6', '8'] 8^2 = 64\n ['0', '2', '4', '6', '8'] 8^2 = 64 (+leading zero)\n ['2', '4', '7', '9'] 7^2 = 49\n ['0', '2', '4', '7', '9'] 7^2 = 49 (+leading zero)\n</code></pre>\n\n<p>None of them matches the problem (which can also be seen by the absence of '0', '1', ..., '9').</p>\n\n<p>The example code that solves it follows. Also note that's written in Python, not because it needs arbitrary precision integers (the code doesn't calculate anything bigger than 98 million), but because we found out that the amount of tests is so small that we should use a high level language to make use of its built-in containers and libraries (also note: the code has 28 lines).</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> import math\n\n m = 98765432\n l = []\n for i in xrange(2, 98765432):\n inv = 1.0/i\n r = m**inv\n if (r &lt; 2.0): break\n top = int(math.floor(r))\n assert(top &lt;= m)\n\n for j in xrange(2, top+1):\n s = str(i) + str(j) + str(j**i)\n l.append((sorted(s), i, j, j**i))\n assert(j**i &lt;= m)\n\n l.sort()\n for s, i, j, ji in l:\n assert(ji &lt;= m)\n ss = sorted(set(s))\n if s == ss:\n print '%s %d^%d = %d' % (s, i, j, ji)\n\n # Try with non significant zero somewhere\n s = ['0'] + s\n ss = sorted(set(s))\n if s == ss:\n print '%s %d^%d = %d (+leading zero)' % (s, i, j, ji)\n</code></pre>\n" }, { "answer_id": 18062322, "author": "Markus Demarmels", "author_id": 2653743, "author_profile": "https://Stackoverflow.com/users/2653743", "pm_score": 3, "selected": false, "text": "<p>Try this macro to test the overflow bit of 32-bit machines (adapted the solution of Angel Sinigersky)</p>\n\n<pre><code>#define overflowflag(isOverflow){ \\\nsize_t eflags; \\\nasm (\"pushfl ;\" \\\n \"pop %%eax\" \\\n : \"=a\" (eflags)); \\\nisOverflow = (eflags &gt;&gt; 11) &amp; 1;}\n</code></pre>\n\n<p>I defined it as a macro because otherwise the overflow bit would have been overwritten.</p>\n\n<p>Subsequent is a little application with the code segement above:</p>\n\n<pre><code>#include &lt;cstddef&gt;\n#include &lt;stdio.h&gt;\n#include &lt;iostream&gt;\n#include &lt;conio.h&gt;\n#if defined( _MSC_VER )\n#include &lt;intrin.h&gt;\n#include &lt;oskit/x86&gt;\n#endif\n\nusing namespace std;\n\n#define detectOverflow(isOverflow){ \\\nsize_t eflags; \\\nasm (\"pushfl ;\" \\\n \"pop %%eax\" \\\n : \"=a\" (eflags)); \\\nisOverflow = (eflags &gt;&gt; 11) &amp; 1;}\n\nint main(int argc, char **argv) {\n\n bool endTest = false;\n bool isOverflow;\n\n do {\n cout &lt;&lt; \"Enter two intergers\" &lt;&lt; endl;\n int x = 0;\n int y = 0;\n cin.clear();\n cin &gt;&gt; x &gt;&gt; y;\n int z = x * y;\n detectOverflow(isOverflow)\n printf(\"\\nThe result is: %d\", z);\n if (!isOverflow) {\n std::cout &lt;&lt; \": no overflow occured\\n\" &lt;&lt; std::endl;\n } else {\n std::cout &lt;&lt; \": overflow occured\\n\" &lt;&lt; std::endl;\n }\n\n z = x * x * y;\n detectOverflow(isOverflow)\n printf(\"\\nThe result is: %d\", z);\n if (!isOverflow) {\n std::cout &lt;&lt; \": no overflow ocurred\\n\" &lt;&lt; std::endl;\n } else {\n std::cout &lt;&lt; \": overflow occured\\n\" &lt;&lt; std::endl;\n }\n\n cout &lt;&lt; \"Do you want to stop? (Enter \\\"y\\\" or \\\"Y)\" &lt;&lt; endl;\n\n char c = 0;\n\n do {\n c = getchar();\n } while ((c == '\\n') &amp;&amp; (c != EOF));\n\n if (c == 'y' || c == 'Y') {\n endTest = true;\n }\n\n do {\n c = getchar();\n } while ((c != '\\n') &amp;&amp; (c != EOF));\n\n } while (!endTest);\n}\n</code></pre>\n" }, { "answer_id": 19170906, "author": "Spyros Panaoussis", "author_id": 2844725, "author_profile": "https://Stackoverflow.com/users/2844725", "pm_score": -1, "selected": false, "text": "<p>It depends what you use it for.\nPerforming unsigned long (DWORD) addition or multiplication, the best solution is to use ULARGE_INTEGER.</p>\n\n<p>ULARGE_INTEGER is a structure of two DWORDs. The full value\ncan be accessed as \"QuadPart\" while the high DWORD is accessed\nas \"HighPart\" and the low DWORD is accessed as \"LowPart\".</p>\n\n<p>For example:</p>\n\n<pre><code>DWORD\nMy Addition(DWORD Value_A, DWORD Value_B)\n{\n ULARGE_INTEGER a, b;\n\n b.LowPart = Value_A; // A 32 bit value(up to 32 bit)\n b.HighPart = 0;\n a.LowPart = Value_B; // A 32 bit value(up to 32 bit)\n a.HighPart = 0;\n\n a.QuadPart += b.QuadPart;\n\n // If a.HighPart\n // Then a.HighPart contains the overflow (carry)\n\n return (a.LowPart + a.HighPart)\n\n // Any overflow is stored in a.HighPart (up to 32 bits)\n</code></pre>\n" }, { "answer_id": 20956705, "author": "zneak", "author_id": 251153, "author_profile": "https://Stackoverflow.com/users/251153", "pm_score": 8, "selected": false, "text": "<p>Starting with C23, the standard header <code>&lt;stdckdint.h&gt;</code> provides the following three function-like macros:</p>\n<pre class=\"lang-c prettyprint-override\"><code>bool ckd_add(type1 *result, type2 a, type3 b);\nbool ckd_sub(type1 *result, type2 a, type3 b);\nbool ckd_mul(type1 *result, type2 a, type3 b);\n</code></pre>\n<p>where <code>type1</code>, <code>type2</code> and <code>type3</code> are any integer type. These functions respectively add, subtract or multiply a and b with arbitrary precision and store the result in <code>*result</code>. If the result cannot be represented exactly by <code>type1</code>, the function returns <code>true</code> (&quot;calculation has overflowed&quot;). (Arbitrary precision is an illusion; the calculations are very fast and almost all hardware available since the early 1990s can do it in just one or two instructions.)</p>\n<p>Rewriting OP's example:</p>\n<pre><code>unsigned long b, c, c_test;\n// ...\nif (ckd_mul(&amp;c_test, c, b))\n{\n // returned non-zero: there has been an overflow\n}\nelse\n{\n c = c_test; // returned 0: no overflow\n}\n</code></pre>\n<p>c_test contains the potentially-overflowed result of the multiplication in all cases.</p>\n<p>Long before C23, <a href=\"https://gcc.gnu.org/gcc-5/changes.html#c-family\" rel=\"noreferrer\">GCC 5+</a> and Clang 3.8+ offer built-ins that work the same way, except that the result pointer is passed last instead of first: <code>__builtin_add_overflow</code>, <code>__builtin_sub_overflow</code> and <code>__builtin_mul_overflow</code>. These also work on types smaller than <code>int</code>.</p>\n<pre><code>unsigned long b, c, c_test;\n// ...\nif (__builtin_mul_overflow(c, b, &amp;c_test))\n{\n // returned non-zero: there has been an overflow\n}\nelse\n{\n c = c_test; // returned 0: no overflow\n}\n</code></pre>\n<p><a href=\"http://clang.llvm.org/docs/LanguageExtensions.html#checked-arithmetic-builtins\" rel=\"noreferrer\">Clang 3.4+</a> introduced arithmetic-overflow builtins with fixed types, but they are much less flexible and Clang 3.8 has been available for a long time now. Look for <code>__builtin_umull_overflow</code> if you need to use this despite the more convenient newer alternative.</p>\n<p><a href=\"http://en.wikipedia.org/wiki/Microsoft_Visual_Studio\" rel=\"noreferrer\">Visual Studio</a>'s cl.exe doesn't have direct equivalents. For unsigned additions and subtractions, including <code>&lt;intrin.h&gt;</code> will allow you to use <code>addcarry_uNN</code> and <code>subborrow_uNN</code> (where NN is the number of bits, like <code>addcarry_u8</code> or <code>subborrow_u64</code>). Their signature is a bit obtuse:</p>\n<pre><code>unsigned char _addcarry_u32(unsigned char c_in, unsigned int src1, unsigned int src2, unsigned int *sum);\nunsigned char _subborrow_u32(unsigned char b_in, unsigned int src1, unsigned int src2, unsigned int *diff);\n</code></pre>\n<p><code>c_in</code>/<code>b_in</code> is the carry/borrow flag on input, and the return value is the carry/borrow on output. It does not appear to have equivalents for signed operations or multiplications.</p>\n<p>Otherwise, Clang for Windows is now production-ready (good enough for Chrome), so that could be an option, too.</p>\n" }, { "answer_id": 21050394, "author": "bartolo-otrit", "author_id": 704244, "author_profile": "https://Stackoverflow.com/users/704244", "pm_score": 3, "selected": false, "text": "<p>Another variant of a solution, using assembly language, is an external procedure. This example for unsigned integer multiplication using g++ and fasm under Linux x64.</p>\n\n<p>This procedure multiplies two unsigned integer arguments (32 bits) (according to <a href=\"http://www.x86-64.org/documentation/\" rel=\"nofollow noreferrer\">specification</a> for amd64 (section <em>3.2.3 Parameter Passing</em>).</p>\n\n<blockquote>\n <p>If the class is INTEGER, the next available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8, and %r9 is used</p>\n</blockquote>\n\n<p>(edi and esi registers in my code)) and returns the result or 0 if an overflow has occured.</p>\n\n<pre><code>format ELF64\n\nsection '.text' executable\n\npublic u_mul\n\nu_mul:\n MOV eax, edi\n mul esi\n jnc u_mul_ret\n xor eax, eax\nu_mul_ret:\nret\n</code></pre>\n\n<p>Test:</p>\n\n<pre><code>extern \"C\" unsigned int u_mul(const unsigned int a, const unsigned int b);\n\nint main() {\n printf(\"%u\\n\", u_mul(4000000000,2)); // 0\n printf(\"%u\\n\", u_mul(UINT_MAX/2,2)); // OK\n return 0;\n}\n</code></pre>\n\n<p>Link the program with the asm object file. In my case, in <a href=\"http://en.wikipedia.org/wiki/Qt_Creator\" rel=\"nofollow noreferrer\">Qt Creator</a>, add it to <code>LIBS</code> in a .pro file.</p>\n" }, { "answer_id": 24334290, "author": "Scott Franco", "author_id": 2352564, "author_profile": "https://Stackoverflow.com/users/2352564", "pm_score": -1, "selected": false, "text": "<pre class=\"lang-c prettyprint-override\"><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\n#define MAX 100 \n\nint mltovf(int a, int b)\n{\n if (a &amp;&amp; b) return abs(a) &gt; MAX/abs(b);\n else return 0;\n}\n\nmain()\n{\n int a, b;\n\n for (a = 0; a &lt;= MAX; a++)\n for (b = 0; b &lt; MAX; b++) {\n\n if (mltovf(a, b) != (a*b &gt; MAX)) \n printf(\"Bad calculation: a: %d b: %d\\n\", a, b);\n\n }\n}\n</code></pre>\n" }, { "answer_id": 28077168, "author": "Tyler Durden", "author_id": 1655700, "author_profile": "https://Stackoverflow.com/users/1655700", "pm_score": -1, "selected": false, "text": "<p>To perform an unsigned multiplication without overflowing in a portable way the following can be used:</p>\n\n<pre><code>... /* begin multiplication */\nunsigned multiplicand, multiplier, product, productHalf;\nint zeroesMultiplicand, zeroesMultiplier;\nzeroesMultiplicand = number_of_leading_zeroes( multiplicand );\nzeroesMultiplier = number_of_leading_zeroes( multiplier );\nif( zeroesMultiplicand + zeroesMultiplier &lt;= 30 ) goto overflow;\nproductHalf = multiplicand * ( c &gt;&gt; 1 );\nif( (int)productHalf &lt; 0 ) goto overflow;\nproduct = productHalf * 2;\nif( multiplier &amp; 1 ){\n product += multiplicand;\n if( product &lt; multiplicand ) goto overflow;\n}\n..../* continue code here where \"product\" is the correct product */\n....\noverflow: /* put overflow handling code here */\n\nint number_of_leading_zeroes( unsigned value ){\n int ctZeroes;\n if( value == 0 ) return 32;\n ctZeroes = 1;\n if( ( value &gt;&gt; 16 ) == 0 ){ ctZeroes += 16; value = value &lt;&lt; 16; }\n if( ( value &gt;&gt; 24 ) == 0 ){ ctZeroes += 8; value = value &lt;&lt; 8; }\n if( ( value &gt;&gt; 28 ) == 0 ){ ctZeroes += 4; value = value &lt;&lt; 4; }\n if( ( value &gt;&gt; 30 ) == 0 ){ ctZeroes += 2; value = value &lt;&lt; 2; }\n ctZeroes -= x &gt;&gt; 31;\n return ctZeroes;\n}\n</code></pre>\n" }, { "answer_id": 33788713, "author": "Pauli Nieminen", "author_id": 3945377, "author_profile": "https://Stackoverflow.com/users/3945377", "pm_score": 0, "selected": false, "text": "<p>The x86 instruction set includes an unsigned multiply instruction that stores the result to two registers. To use that instruction from C, one can write the following code in a 64-bit program (GCC):</p>\n\n<pre><code>unsigned long checked_imul(unsigned long a, unsigned long b) {\n unsigned __int128 res = (unsigned __int128)a * b;\n if ((unsigned long)(res &gt;&gt; 64))\n printf(\"overflow in integer multiply\");\n return (unsigned long)res;\n}\n</code></pre>\n\n<p>For a 32-bit program, one needs to make the result 64 bit and parameters 32 bit.</p>\n\n<p>An alternative is to use compiler-dependent intrinsic to check the flag register. GCC documentation for overflow intrinsic can be found from <em><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.html\" rel=\"nofollow noreferrer\">6.56 Built-in Functions to Perform Arithmetic with Overflow Checking</a></em>.</p>\n" }, { "answer_id": 49303966, "author": "hsivonen", "author_id": 18721, "author_profile": "https://Stackoverflow.com/users/18721", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://searchfox.org/mozilla-central/source/mfbt/CheckedInt.h\" rel=\"nofollow noreferrer\"><code>mozilla::CheckedInt&lt;T&gt;</code></a> provides overflow-checked integer math for integer type <code>T</code> (using compiler intrinsics on clang and gcc as available). The code is under MPL 2.0 and depends on three (<a href=\"https://searchfox.org/mozilla-central/source/mfbt/IntegerTypeTraits.h\" rel=\"nofollow noreferrer\"><code>IntegerTypeTraits.h</code></a>, <a href=\"https://searchfox.org/mozilla-central/source/mfbt/Attributes.h\" rel=\"nofollow noreferrer\"><code>Attributes.h</code></a> and <a href=\"https://searchfox.org/mozilla-central/source/mfbt/Compiler.h\" rel=\"nofollow noreferrer\"><code>Compiler.h</code></a>) other header-only non-standard library headers plus Mozilla-specific <a href=\"https://searchfox.org/mozilla-central/source/mfbt/Assertions.h\" rel=\"nofollow noreferrer\">assertion machinery</a>. You probably want to replace the assertion machinery if you import the code.</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23732/" ]
I was writing a program in C++ to find all solutions of *a**b* = *c*, where *a*, *b* and *c* together use all the digits 0-9 exactly once. The program looped over values of *a* and *b*, and it ran a digit-counting routine each time on *a*, *b* and *ab* to check if the digits condition was satisfied. However, spurious solutions can be generated when *a**b* overflows the integer limit. I ended up checking for this using code like: ``` unsigned long b, c, c_test; ... c_test=c*b; // Possible overflow if (c_test/b != c) {/* There has been an overflow*/} else c=c_test; // No overflow ``` Is there a better way of testing for overflow? I know that some chips have an internal flag that is set when overflow occurs, but I've never seen it accessed through C or C++. --- Beware that ***signed* `int` overflow is undefined behaviour in C and C++**, and thus you have to detect it without actually causing it. For signed int overflow before addition, see *[Detecting signed overflow in C/C++](https://stackoverflow.com/questions/3944505/detecting-signed-overflow-in-c-c)*.
I see you're using unsigned integers. By definition, **in C** (I don't know about C++), unsigned arithmetic does not overflow ... so, at least for C, your point is moot :) With signed integers, once there has been overflow, [undefined behaviour](http://en.wikipedia.org/wiki/Undefined_behavior) (UB) has occurred and your program can do anything (for example: render tests inconclusive).  ``` #include <limits.h> int a = <something>; int x = <something>; a += x; /* UB */ if (a < 0) { /* Unreliable test */ /* ... */ } ``` To create a conforming program, you need to test for overflow **before** generating said overflow. The method can be used with unsigned integers too: ``` // For addition #include <limits.h> int a = <something>; int x = <something>; if (x > 0 && a > INT_MAX - x) // `a + x` would overflow if (x < 0 && a < INT_MIN - x) // `a + x` would underflow ``` --- ``` // For subtraction #include <limits.h> int a = <something>; int x = <something>; if (x < 0 && a > INT_MAX + x) // `a - x` would overflow if (x > 0 && a < INT_MIN + x) // `a - x` would underflow ``` --- ``` // For multiplication #include <limits.h> int a = <something>; int x = <something>; // There may be a need to check for -1 for two's complement machines. // If one number is -1 and another is INT_MIN, multiplying them we get abs(INT_MIN) which is 1 higher than INT_MAX if (a == -1 && x == INT_MIN) // `a * x` can overflow if (x == -1 && a == INT_MIN) // `a * x` (or `a / x`) can overflow // general case if (x != 0 && a > INT_MAX / x) // `a * x` would overflow if (x != 0 && a < INT_MIN / x) // `a * x` would underflow ``` --- For division (except for the `INT_MIN` and `-1` special case), there isn't any possibility of going over `INT_MIN` or `INT_MAX`.
199,336
<p>How would I print a spinning curser in a utility that runs in a terminal using standard C?</p> <p>I'm looking for something that prints: \ | / - over and over in the same position on the screen?</p> <p>Thanks </p>
[ { "answer_id": 199344, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 6, "selected": true, "text": "<p>You could use the backspace character (<code>\\b</code>) like this:</p>\n\n<pre><code>printf(\"processing... |\");\nfflush(stdout);\n// do something\nprintf(\"\\b/\");\nfflush(stdout);\n// do some more\nprintf(\"\\b-\");\nfflush(stdout);\n</code></pre>\n\n<p>etc. You need the <code>fflush(stdout)</code> because normally stdout is buffered until you output a newline.</p>\n" }, { "answer_id": 199349, "author": "MBCook", "author_id": 18189, "author_profile": "https://Stackoverflow.com/users/18189", "pm_score": 2, "selected": false, "text": "<p>I've done that, long ago. There are two ways.</p>\n\n<ol>\n<li><p>Use a library like ncurses to give you control over the terminal. This works well if you want to do a lot of this kind of stuff. If you just one this in one little spot, it's obviously overkill.</p></li>\n<li><p>Print a control character.</p></li>\n</ol>\n\n<p>First you print \"/\", then 0x08 (backspace), then \"-\", then 0x08, then \"\\\"....</p>\n\n<p>The backspace character moves the cursor position back one space, but leaves the current character there until you overwrite it. Get the timing right (so it doesn't spin to fast or slow) and you're golden.</p>\n" }, { "answer_id": 199380, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 1, "selected": false, "text": "<p>There is no truly \"standard\" way to do this, since the C Standard Library (<a href=\"http://members.aol.com/wantondeb/\" rel=\"nofollow noreferrer\">http://members.aol.com/wantondeb/</a>) does not provide functions to do raw terminal/console output.</p>\n\n<p>In DOS/Windows console, the standard-ish way to do it is with <a href=\"http://en.wikipedia.org/wiki/Conio.h\" rel=\"nofollow noreferrer\"><code>conio.h</code></a>, while under Unix/Linux the accepted library for this purpose is <a href=\"http://en.wikipedia.org/wiki/Ncurses\" rel=\"nofollow noreferrer\"><code>ncurses</code></a> (<code>ncurses</code> basically encapsulates the control-character behavior that MBCook describes, in a terminal-independent way).</p>\n" }, { "answer_id": 199400, "author": "Diego Zamboni", "author_id": 5562, "author_profile": "https://Stackoverflow.com/users/5562", "pm_score": 4, "selected": false, "text": "<p>Here's some example code. Call advance_cursor() every once in a while while the task completes.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nvoid advance_cursor() {\n static int pos=0;\n char cursor[4]={'/','-','\\\\','|'};\n printf(\"%c\\b\", cursor[pos]);\n fflush(stdout);\n pos = (pos+1) % 4;\n}\n\nint main(int argc, char **argv) {\n int i;\n for (i=0; i&lt;100; i++) {\n advance_cursor();\n usleep(100000);\n }\n printf(\"\\n\");\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 890760, "author": "Miki Tebeka", "author_id": 7650, "author_profile": "https://Stackoverflow.com/users/7650", "pm_score": 2, "selected": false, "text": "<p>You can also use <em>\\r</em>:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;unistd.h&gt;\n\nvoid\nadvance_spinner() {\n static char bars[] = { '/', '-', '\\\\', '|' };\n static int nbars = sizeof(bars) / sizeof(char);\n static int pos = 0;\n\n printf(\"%c\\r\", bars[pos]);\n fflush(stdout);\n pos = (pos + 1) % nbars;\n}\n\nint\nmain() {\n while (1) {\n advance_spinner();\n usleep(300);\n }\n\n return 0;\n}\n</code></pre>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3467/" ]
How would I print a spinning curser in a utility that runs in a terminal using standard C? I'm looking for something that prints: \ | / - over and over in the same position on the screen? Thanks
You could use the backspace character (`\b`) like this: ``` printf("processing... |"); fflush(stdout); // do something printf("\b/"); fflush(stdout); // do some more printf("\b-"); fflush(stdout); ``` etc. You need the `fflush(stdout)` because normally stdout is buffered until you output a newline.
199,390
<p>I have an application used by pretty tech-savey people and they want small island of programmability so I've used embedded Iron Python.</p> <p>However, since IronPython 2.0 Eval() doesn't work any more. Specifically I can't both load modules and inject local variables.</p> <p>There is a work around where I can still call Execute(), print out my answer and listen to StandardOut, but then it comes out as a string and I've lost the type.</p> <p>Not a disaster for a long, but a huge pain for more complex objects.</p> <p>Does anyone know how to get Eval() working again in 2.0 like it did in 1.x?</p> <p>Cheers, Jan</p>
[ { "answer_id": 199406, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 3, "selected": true, "text": "<p>Could you be a little more specific about the problem, and maybe provide a code example? The \"eval\"-style functionality is definitely still present, though as you've noticed, the hosting interface has changed considerably since 1.0.</p>\n\n<p>This works in beta 5:</p>\n\n<pre><code>ScriptEngine engine = Python.CreateEngine();\nScriptSource source = engine.CreateScriptSourceFromString(\"2 + 5\", SourceCodeKind.Expression);\nint result = source.Execute&lt;int&gt;();\n</code></pre>\n\n<p>By the way, using the right <code>SourceCodeKind</code> is critical here.</p>\n" }, { "answer_id": 199410, "author": "Antonio Cangiano", "author_id": 6551, "author_profile": "https://Stackoverflow.com/users/6551", "pm_score": 1, "selected": false, "text": "<p>This example may help you: <a href=\"http://www.voidspace.org.uk/ironpython/dlr_hosting.shtml\" rel=\"nofollow noreferrer\">http://www.voidspace.org.uk/ironpython/dlr_hosting.shtml</a></p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/460845/" ]
I have an application used by pretty tech-savey people and they want small island of programmability so I've used embedded Iron Python. However, since IronPython 2.0 Eval() doesn't work any more. Specifically I can't both load modules and inject local variables. There is a work around where I can still call Execute(), print out my answer and listen to StandardOut, but then it comes out as a string and I've lost the type. Not a disaster for a long, but a huge pain for more complex objects. Does anyone know how to get Eval() working again in 2.0 like it did in 1.x? Cheers, Jan
Could you be a little more specific about the problem, and maybe provide a code example? The "eval"-style functionality is definitely still present, though as you've noticed, the hosting interface has changed considerably since 1.0. This works in beta 5: ``` ScriptEngine engine = Python.CreateEngine(); ScriptSource source = engine.CreateScriptSourceFromString("2 + 5", SourceCodeKind.Expression); int result = source.Execute<int>(); ``` By the way, using the right `SourceCodeKind` is critical here.
199,418
<p>I have a C++ library that provides various classes for managing data. I have the source code for the library.</p> <p>I want to extend the C++ API to support C function calls so that the library can be used with C code and C++ code at the same time.</p> <p>I'm using GNU tool chain (gcc, glibc, etc), so language and architecture support are not an issue.</p> <p>Are there any reasons why this is <strong>technically</strong> not possible?</p> <p>Are there any <strong>gotcha's</strong> that I need to watch out for?</p> <p>Are there resources, example code and/or documentation available regarding this?</p> <hr> <p>Some other things that I have found out:</p> <ol> <li>Use the following to wrap your C++ headers that need to be used by C code.</li> </ol> <p></p> <pre><code>#ifdef __cplusplus extern "C" { #endif // // Code goes here ... // #ifdef __cplusplus } // extern "C" #endif </code></pre> <ol start="2"> <li>Keep "real" C++ interfaces in separate header files that are not included by C. Think <a href="http://en.wikipedia.org/wiki/Private_class_data_pattern" rel="noreferrer">PIMPL principle</a> here. Using <code>#ifndef __cplusplus #error</code> stuff helps here to detect any craziness.</li> <li>Careful of C++ identifiers as names in C code</li> <li>Enums varying in size between C and C++ compilers. Probably not an issue if you're using GNU tool chain, but still, be careful.</li> <li><p>For structs follow the following form so that C does not get confused.</p> <pre><code>typedef struct X { ... } X </code></pre></li> <li><p>Then use pointers for passing around C++ objects, they just have to be declared in C as struct X where X is the C++ object.</p></li> </ol> <p>All of this is courtesy of a friend who's a wizard at C++.</p>
[ { "answer_id": 199422, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 7, "selected": true, "text": "<p>Yes, this is certainly possible. You will need to write an interface layer in C++ that declares functions with <code>extern \"C\"</code>:</p>\n\n<pre><code>extern \"C\" int foo(char *bar)\n{\n return realFoo(std::string(bar));\n}\n</code></pre>\n\n<p>Then, you will call <code>foo()</code> from your C module, which will pass the call on to the <code>realFoo()</code> function which is implemented in C++.</p>\n\n<p>If you need to expose a full C++ class with data members and methods, then you may need to do more work than this simple function example.</p>\n" }, { "answer_id": 199438, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 2, "selected": false, "text": "<p>you can mix C/C++ code. If your main() function in in C++, then you just need to make sure your c functions are declared </p>\n\n<pre><code>extern \"C\"\n</code></pre>\n\n<p>If your main is C, then you are probably OK except for static variables. Any constructors with your static variables are supposed to be called before main() start. This won't happen if C is your main. I you have a lot of static variables, the best thing to do is to replace static variables with singletons.</p>\n" }, { "answer_id": 199456, "author": "ejgottl", "author_id": 9808, "author_profile": "https://Stackoverflow.com/users/9808", "pm_score": 4, "selected": false, "text": "<p>Main gotcha: exceptions can not be caught in C. If there is the possibility of an exception rising in the C++ code, either write your C code or your C++ wrappers very carefully. Conversely, exception like mechanisms (i.e., longjump) in the C code (as found in various scripting languages) are not required to invoke destructors for C++ objects on the stack.</p>\n" }, { "answer_id": 199460, "author": "Alex B", "author_id": 23643, "author_profile": "https://Stackoverflow.com/users/23643", "pm_score": 5, "selected": false, "text": "<p>C++ FAQ Lite: <a href=\"https://isocpp.org/wiki/faq/mixing-c-and-cpp\" rel=\"noreferrer\">\"How to mix C and C++ code\"</a>.</p>\n\n<p>Some gotchas are described in answers to these questions:</p>\n\n<ul>\n<li>[32.8] How can I pass an object of a C++ class to/from a C function?</li>\n<li>[32.9] Can my C function directly access data in an object of a C++ class?</li>\n</ul>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3467/" ]
I have a C++ library that provides various classes for managing data. I have the source code for the library. I want to extend the C++ API to support C function calls so that the library can be used with C code and C++ code at the same time. I'm using GNU tool chain (gcc, glibc, etc), so language and architecture support are not an issue. Are there any reasons why this is **technically** not possible? Are there any **gotcha's** that I need to watch out for? Are there resources, example code and/or documentation available regarding this? --- Some other things that I have found out: 1. Use the following to wrap your C++ headers that need to be used by C code. ``` #ifdef __cplusplus extern "C" { #endif // // Code goes here ... // #ifdef __cplusplus } // extern "C" #endif ``` 2. Keep "real" C++ interfaces in separate header files that are not included by C. Think [PIMPL principle](http://en.wikipedia.org/wiki/Private_class_data_pattern) here. Using `#ifndef __cplusplus #error` stuff helps here to detect any craziness. 3. Careful of C++ identifiers as names in C code 4. Enums varying in size between C and C++ compilers. Probably not an issue if you're using GNU tool chain, but still, be careful. 5. For structs follow the following form so that C does not get confused. ``` typedef struct X { ... } X ``` 6. Then use pointers for passing around C++ objects, they just have to be declared in C as struct X where X is the C++ object. All of this is courtesy of a friend who's a wizard at C++.
Yes, this is certainly possible. You will need to write an interface layer in C++ that declares functions with `extern "C"`: ``` extern "C" int foo(char *bar) { return realFoo(std::string(bar)); } ``` Then, you will call `foo()` from your C module, which will pass the call on to the `realFoo()` function which is implemented in C++. If you need to expose a full C++ class with data members and methods, then you may need to do more work than this simple function example.
199,428
<p>I Have one entity [Project] that contains a collection of other entities [Questions].</p> <p>I have mapped the relation with a cascade attribute of &quot;all-delete-orphan&quot;.</p> <p>In my DB the relation is mapped with a project_id (FK) field on the questions table. this field cannot be null since I don't want a Question without a Project.</p> <p>When I do <code>session.delete(project)</code> it throws an exception saying that <code>project_id</code> cant be <code>null</code>, but if I remove the <code>not-null</code> constraint to that field, the deletion works nice.</p> <p>Anyone knows how to solve this?</p>
[ { "answer_id": 199474, "author": "Steve Moyer", "author_id": 17008, "author_profile": "https://Stackoverflow.com/users/17008", "pm_score": -1, "selected": false, "text": "<p>The delete is occurring on the Project first and cascading to the Question, but the Project delete includes a nulling of the project_id in the Questions (for referential integrity. You're not getting an exception on the deletion of the Question object, but because the cascade is trying to null the FK in the Question(s).</p>\n\n<p>Looking at \"<a href=\"http://www.manning.com/bauer2/\" rel=\"nofollow noreferrer\">Java Persistence with Hibernate</a>\", I think that what you really want a cascade type of delete or remove, not delete-orphans.</p>\n" }, { "answer_id": 199545, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 0, "selected": false, "text": "<p>One strategy is to mark the foreign-key in the database with on-delete-cascade, so as soon as NHibernate tells the database to delete a project, the database itself will cascade the deletes. Then you have to tell NHibernate that the database itself does a cascade delete.</p>\n" }, { "answer_id": 199683, "author": "abarax", "author_id": 24390, "author_profile": "https://Stackoverflow.com/users/24390", "pm_score": 4, "selected": false, "text": "<p>Straight from the <a href=\"http://www.hibernate.org/hib_docs/nhibernate/html/example-parentchild.html#example-parentchild-cascades\" rel=\"noreferrer\">documentation</a>. This explains your problem exactly i believe:</p>\n\n<p>However, this code</p>\n\n<pre><code>Parent p = (Parent) session.Load(typeof(Parent), pid);\n// Get one child out of the set\nIEnumerator childEnumerator = p.Children.GetEnumerator();\nchildEnumerator.MoveNext();\nChild c = (Child) childEnumerator.Current;\n\np.Children.Remove(c);\nc.Parent = null;\nsession.Flush();\n</code></pre>\n\n<p>will not remove c from the database; it will only remove the link to p (and cause a NOT NULL constraint violation, in this case). You need to explicitly Delete() the Child.</p>\n\n<pre><code>Parent p = (Parent) session.Load(typeof(Parent), pid);\n// Get one child out of the set\nIEnumerator childEnumerator = p.Children.GetEnumerator();\nchildEnumerator.MoveNext();\nChild c = (Child) childEnumerator.Current;\n\np.Children.Remove(c);\nsession.Delete(c);\nsession.Flush();\n</code></pre>\n\n<p>Now, in our case, a Child can't really exist without its parent. So if we remove a Child from the collection, we really do want it to be deleted. For this, we must use cascade=\"all-delete-orphan\".</p>\n\n<pre><code>&lt;set name=\"Children\" inverse=\"true\" cascade=\"all-delete-orphan\"&gt;\n &lt;key column=\"parent_id\"/&gt;\n &lt;one-to-many class=\"Child\"/&gt;\n&lt;/set&gt;\n</code></pre>\n\n<p>Edit: </p>\n\n<p>With regards to the inverse stuff, i believe this only determines how the sql is generated, see this <a href=\"http://simoes.org/docs/hibernate-2.1/155.html\" rel=\"noreferrer\">doc</a> for more info.</p>\n\n<p>One thing to note is, have you got </p>\n\n<pre><code>not-null=\"true\"\n</code></pre>\n\n<p>on the many-to-one relationship in your hibernate config?</p>\n" }, { "answer_id": 73638227, "author": "Klioda", "author_id": 3544063, "author_profile": "https://Stackoverflow.com/users/3544063", "pm_score": 0, "selected": false, "text": "<p>If anyone have situation like this then make sure you actually have set proper CascadeType (one of: ALL, REMOVE, DELETE). It needs to be in the entity that you try to delete:</p>\n<pre><code>public class Project {\n\n @Id\n private long id;\n\n @OneToMany(mappedBy = &quot;project&quot;, cascade = {CascadeType.REMOVE})\n public List&lt;Question&gt; questions;\n}\n</code></pre>\n<p>Deleting should work whether there is NOT NULL constraint on foreign key or not just with:</p>\n<pre><code>session.delete(project);\n</code></pre>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7595/" ]
I Have one entity [Project] that contains a collection of other entities [Questions]. I have mapped the relation with a cascade attribute of "all-delete-orphan". In my DB the relation is mapped with a project\_id (FK) field on the questions table. this field cannot be null since I don't want a Question without a Project. When I do `session.delete(project)` it throws an exception saying that `project_id` cant be `null`, but if I remove the `not-null` constraint to that field, the deletion works nice. Anyone knows how to solve this?
Straight from the [documentation](http://www.hibernate.org/hib_docs/nhibernate/html/example-parentchild.html#example-parentchild-cascades). This explains your problem exactly i believe: However, this code ``` Parent p = (Parent) session.Load(typeof(Parent), pid); // Get one child out of the set IEnumerator childEnumerator = p.Children.GetEnumerator(); childEnumerator.MoveNext(); Child c = (Child) childEnumerator.Current; p.Children.Remove(c); c.Parent = null; session.Flush(); ``` will not remove c from the database; it will only remove the link to p (and cause a NOT NULL constraint violation, in this case). You need to explicitly Delete() the Child. ``` Parent p = (Parent) session.Load(typeof(Parent), pid); // Get one child out of the set IEnumerator childEnumerator = p.Children.GetEnumerator(); childEnumerator.MoveNext(); Child c = (Child) childEnumerator.Current; p.Children.Remove(c); session.Delete(c); session.Flush(); ``` Now, in our case, a Child can't really exist without its parent. So if we remove a Child from the collection, we really do want it to be deleted. For this, we must use cascade="all-delete-orphan". ``` <set name="Children" inverse="true" cascade="all-delete-orphan"> <key column="parent_id"/> <one-to-many class="Child"/> </set> ``` Edit: With regards to the inverse stuff, i believe this only determines how the sql is generated, see this [doc](http://simoes.org/docs/hibernate-2.1/155.html) for more info. One thing to note is, have you got ``` not-null="true" ``` on the many-to-one relationship in your hibernate config?
199,468
<p>Why am I getting an out of memory exception?</p> <p>So this dies in C# on the first time through:</p> <p><strong>splitBitmaps.Add(neededImage.Clone(rectDimensions, neededImage.PixelFormat));</strong> </p> <p>Where splitBitmaps is a List&lt;BitMap&gt; BUT this works in VB for at least 4 iterations:</p> <p><strong>arlSplitBitmaps.Add(Image.Clone(rectDimensions, Image.PixelFormat))</strong></p> <p>Where arlSplitBitmaps is a simple array list. (And yes I've tried arraylist in c#)</p> <p>This is the fullsection:</p> <pre><code>for (Int32 splitIndex = 0; splitIndex &lt;= numberOfResultingImages - 1; splitIndex++) { Rectangle rectDimensions; if (splitIndex &lt; numberOfResultingImages - 1) { rectDimensions = new Rectangle(splitImageWidth * splitIndex, 0, splitImageWidth, splitImageHeight); } else { rectDimensions = new Rectangle(splitImageWidth * splitIndex, 0, sourceImageWidth - (splitImageWidth * splitIndex), splitImageHeight); } splitBitmaps.Add(neededImage.Clone(rectDimensions, neededImage.PixelFormat)); </code></pre> <p>} </p> <p>neededImage is a Bitmap by the way. </p> <p>I can't find any useful answers on the intarweb, especially not why it works just fine in VB.</p> <p><strong>Update:</strong></p> <p>I actually found a reason (sort of) for this working but forgot to post it. It has to do with converting the image to a bitmap instead of just trying to clone the raw image if I remember.</p>
[ { "answer_id": 199497, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 2, "selected": false, "text": "<p>Make sure that you're calling .Dispose() properly on your images, otherwise unmanaged resources won't be freed up. I wonder how many images are you actually creating here -- hundreds? Thousands?</p>\n" }, { "answer_id": 199596, "author": "Mike L", "author_id": 12085, "author_profile": "https://Stackoverflow.com/users/12085", "pm_score": 2, "selected": false, "text": "<p>This is a reach, but I've often found that if pulling images directly from disk that it's better to copy them to a new bitmap and dispose of the disk-bound image. I've seen great improvement in memory consumption when doing so.</p>\n\n<p>Dave M. is on the money too... make sure to dispose when finished.</p>\n" }, { "answer_id": 654861, "author": "Tomas Andrle", "author_id": 35440, "author_profile": "https://Stackoverflow.com/users/35440", "pm_score": 7, "selected": false, "text": "<p>Clone() may also throw an Out of memory exception when the coordinates specified in the Rectangle are outside the bounds of the bitmap. It will not clip them automatically for you.</p>\n" }, { "answer_id": 2116632, "author": "Andy", "author_id": 45062, "author_profile": "https://Stackoverflow.com/users/45062", "pm_score": 3, "selected": false, "text": "<p>I got this too when I tried to use the Clone() method to change the pixel format of a bitmap. If memory serves, I was trying to convert a 24 bpp bitmap to an 8 bit indexed format, naively hoping that the Bitmap class would magically handle the palette creation and so on. Obviously not :-/</p>\n" }, { "answer_id": 21624203, "author": "user3283232", "author_id": 3283232, "author_profile": "https://Stackoverflow.com/users/3283232", "pm_score": 4, "selected": false, "text": "<p>I found that I was using Image.Clone to crop a bitmap and the width took the crop outside the bounds of the original image. This causes an Out of Memory error. Seems a bit strange but can beworth knowing.</p>\n" }, { "answer_id": 29024741, "author": "dellyjm", "author_id": 1810774, "author_profile": "https://Stackoverflow.com/users/1810774", "pm_score": 2, "selected": false, "text": "<p>I struggled to figure this out recently - the answers above are correct. Key to solving this issue is to ensure the rectangle is actually within the boundaries of the image. See example of how I solved this.</p>\n\n<p>In a nutshell, checked to if the area that was being cloned was outside the area of the image.</p>\n\n<pre><code>int totalWidth = rect.Left + rect.Width; //think -the same as Right property\n\nint allowableWidth = localImage.Width - rect.Left;\nint finalWidth = 0;\n\nif (totalWidth &gt; allowableWidth){\n finalWidth = allowableWidth;\n} else {\n finalWidth = totalWidth;\n}\n\nrect.Width = finalWidth;\n\nint totalHeight = rect.Top + rect.Height; //think same as Bottom property\nint allowableHeight = localImage.Height - rect.Top;\nint finalHeight = 0;\n\nif (totalHeight &gt; allowableHeight){\n finalHeight = allowableHeight;\n} else {\n finalHeight = totalHeight;\n}\n\nrect.Height = finalHeight;\ncropped = ((Bitmap)localImage).Clone(rect, System.Drawing.Imaging.PixelFormat.DontCare);\n</code></pre>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21691/" ]
Why am I getting an out of memory exception? So this dies in C# on the first time through: **splitBitmaps.Add(neededImage.Clone(rectDimensions, neededImage.PixelFormat));** Where splitBitmaps is a List<BitMap> BUT this works in VB for at least 4 iterations: **arlSplitBitmaps.Add(Image.Clone(rectDimensions, Image.PixelFormat))** Where arlSplitBitmaps is a simple array list. (And yes I've tried arraylist in c#) This is the fullsection: ``` for (Int32 splitIndex = 0; splitIndex <= numberOfResultingImages - 1; splitIndex++) { Rectangle rectDimensions; if (splitIndex < numberOfResultingImages - 1) { rectDimensions = new Rectangle(splitImageWidth * splitIndex, 0, splitImageWidth, splitImageHeight); } else { rectDimensions = new Rectangle(splitImageWidth * splitIndex, 0, sourceImageWidth - (splitImageWidth * splitIndex), splitImageHeight); } splitBitmaps.Add(neededImage.Clone(rectDimensions, neededImage.PixelFormat)); ``` } neededImage is a Bitmap by the way. I can't find any useful answers on the intarweb, especially not why it works just fine in VB. **Update:** I actually found a reason (sort of) for this working but forgot to post it. It has to do with converting the image to a bitmap instead of just trying to clone the raw image if I remember.
Clone() may also throw an Out of memory exception when the coordinates specified in the Rectangle are outside the bounds of the bitmap. It will not clip them automatically for you.
199,469
<p>I need to change the capitalization of a set of files in a subversion working copy, like so:</p> <pre> svn mv test.txt Test.txt svn mv test2.txt Test2.txt svn mv testn.txt Testn.txt ... svn commit -m "caps" </pre> <p>How can I automate this process? Standard linux install tools available.</p>
[ { "answer_id": 199485, "author": "Andrew", "author_id": 826, "author_profile": "https://Stackoverflow.com/users/826", "pm_score": 0, "selected": false, "text": "<p>I typically do this by redirecting the 'ls' output to a file, using vim macros to massage each filename into the command line I want, then execute the file as a shell script. It's crude but effective.</p>\n" }, { "answer_id": 199510, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 2, "selected": false, "text": "<p>If you have a decent install you should have python, give this a try:</p>\n\n<pre><code>#!/usr/bin/python\nfrom os import rename, listdir\npath = \"/path/to/folder\"\ntry:\n dirList = listdir(path)\nexcept:\n print 'There was an error while trying to access the directory: '+path\nfor name in dirList:\n try:\n rename(path+'\\\\'+name, path+'\\\\'+name.upper())\n except:\n print 'Process failed for file: '+name\n</code></pre>\n" }, { "answer_id": 199516, "author": "ejgottl", "author_id": 9808, "author_profile": "https://Stackoverflow.com/users/9808", "pm_score": 5, "selected": true, "text": "<p>ls | awk '{system(\"svn mv \" $0 \" \" toupper(substr($0,1,1)) substr($0,2))}'</p>\n\n<p>obviously, other scripting languages will work just as well. awk has the advantage that it it ubiquitous.</p>\n" }, { "answer_id": 199520, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 1, "selected": false, "text": "<p>I don't think theres an easy way to do it with bash/sed/tr/find. </p>\n\n<p>I'd make a Ruby/Perl script that does the renaming. </p>\n\n<pre><code> #!/usr/bin/ruby \n # Upcase.rb \n ARGV.each{ |i|\n newname = i.gsub(/(^.|\\s.)/{ |x| x.upcase }\n `svn mv \"#{i}\" \"#{newname}\" `\n }\n</code></pre>\n\n<p>Then just do </p>\n\n<pre><code> ./Upcase.rb foo.txt test.txt test2.txt foo/bar/test.txt \n</code></pre>\n\n<p>or if you want to do a whole dir </p>\n\n<pre><code> find ./ -exec ./Upcase.rb {} + \n</code></pre>\n" }, { "answer_id": 215789, "author": "Bert Huijben", "author_id": 2094, "author_profile": "https://Stackoverflow.com/users/2094", "pm_score": 1, "selected": false, "text": "<p>Please note that this change breaks existing workingcopies on Windows and Mac systems, as they can't handle case only renames.</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27667/" ]
I need to change the capitalization of a set of files in a subversion working copy, like so: ``` svn mv test.txt Test.txt svn mv test2.txt Test2.txt svn mv testn.txt Testn.txt ... svn commit -m "caps" ``` How can I automate this process? Standard linux install tools available.
ls | awk '{system("svn mv " $0 " " toupper(substr($0,1,1)) substr($0,2))}' obviously, other scripting languages will work just as well. awk has the advantage that it it ubiquitous.
199,483
<p>This is the constraint I have on the Customers table.</p> <pre><code>ALTER TABLE Customers ADD CONSTRAINT CN_CustomerPhone CHECK (Phone LIKE '([0-9][0-9][0-9]) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]') </code></pre> <p>Why does this fail?</p> <pre><code>INSERT INTO Customers (CustomerName, Address, City, State, Zip, Phone) VALUES ('Some Name','An Address', 'City goes here', 'WI', 12345, '(800) 555-1212') </code></pre> <p>With this error message.</p> <blockquote> <p>Msg 547, Level 16, State 0, Line 1 The INSERT statement conflicted with the CHECK constraint "CN_CustomerPhoneNo". The conflict occurred in database "Accounting", table "dbo.Customers", column 'Phone'. The statement has been terminated.</p> </blockquote> <p>I'm sure I'm missing something really simple, but I can't find it.</p> <p>I've tried simplifying the constraint to only 'Phone LIKE '[0-9]'' and inserting a single digit, but it still fails. WTF?</p>
[ { "answer_id": 199500, "author": "shahkalpesh", "author_id": 23574, "author_profile": "https://Stackoverflow.com/users/23574", "pm_score": 4, "selected": true, "text": "<p>Check the length of the Phone field.<br>\nIs it 15 or more characters?</p>\n\n<p>Using your code with a temp table here<br></p>\n\n<pre>\n<code>\ncreate table #temp\n(phone varchar(15))\n\nALTER TABLE #temp\n ADD CONSTRAINT CN_CustomerPhone\n CHECK (Phone LIKE '([0-9][0-9][0-9]) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]')\n\nINSERT INTO #temp\n(Phone)\nVALUES\n('(800) 555-1212')\n\nselect * from #temp\n\ndrop table #temp\n</code>\n</pre>\n" }, { "answer_id": 199502, "author": "Eric Haskins", "author_id": 100, "author_profile": "https://Stackoverflow.com/users/100", "pm_score": 1, "selected": false, "text": "<p>I'm an idiot, the field was declared as an nchar, and I didn't' take the padding spaces into account.</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/100/" ]
This is the constraint I have on the Customers table. ``` ALTER TABLE Customers ADD CONSTRAINT CN_CustomerPhone CHECK (Phone LIKE '([0-9][0-9][0-9]) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]') ``` Why does this fail? ``` INSERT INTO Customers (CustomerName, Address, City, State, Zip, Phone) VALUES ('Some Name','An Address', 'City goes here', 'WI', 12345, '(800) 555-1212') ``` With this error message. > > Msg 547, Level 16, State 0, Line 1 The > INSERT statement conflicted with the > CHECK constraint "CN\_CustomerPhoneNo". > The conflict occurred in database > "Accounting", table "dbo.Customers", > column 'Phone'. The statement has been > terminated. > > > I'm sure I'm missing something really simple, but I can't find it. I've tried simplifying the constraint to only 'Phone LIKE '[0-9]'' and inserting a single digit, but it still fails. WTF?
Check the length of the Phone field. Is it 15 or more characters? Using your code with a temp table here ``` create table #temp (phone varchar(15)) ALTER TABLE #temp ADD CONSTRAINT CN_CustomerPhone CHECK (Phone LIKE '([0-9][0-9][0-9]) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]') INSERT INTO #temp (Phone) VALUES ('(800) 555-1212') select * from #temp drop table #temp ```
199,488
<p>For some reason I am having troubles with a DBI handle. Basically what happened was that I made a special connect function in a perl module and switched from doing:</p> <pre><code>do 'foo.pl' </code></pre> <p>to</p> <pre><code>use Foo; </code></pre> <p>and then I do</p> <pre><code>$dbh = Foo-&gt;connect; </code></pre> <p>And now for some reason I keep getting the error:</p> <blockquote> <p>Can't locate object method "rollback" via package "Foo" at ../Foo.pm line 171.</p> </blockquote> <p>So the weird thing is that $dbh is definitely not a Foo, it's just defined in foo. Anyway, I haven't had any troubles with it up until now. Any ideas what's up?</p> <p><strong>Edit</strong>: @Axeman: <code>connect</code> did not exist in the original. Before we just had a string that we used like this:</p> <pre><code>do 'foo.pl'; $dbh = DBI-&gt;connect($DBConnectString); </code></pre> <p>and so <code>connect</code> is something like this</p> <pre><code>sub connect { my $dbh = DBI-&gt;connect('blah'); return $dbh; } </code></pre>
[ { "answer_id": 199635, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 3, "selected": true, "text": "<p>From <a href=\"http://perldoc.perl.org/perlfunc.html#do-EXPR\" rel=\"nofollow noreferrer\">perlfunc</a>:</p>\n\n<blockquote><pre>\n do 'stat.pl';\n\n is just like\n\n eval `cat stat.pl`;\n</pre></blockquote>\n\n<p>So when you <code>do 'foo.pl'</code>, you execute the code in the current context. Because I don't know what goes on in <code>foo.pl</code> or <code>Foo.pm</code>, I can't tell you what's changed. But, I can tell you that it's always executed in the current context, and now in executes in <code>Foo::</code> namespace. </p>\n\n<p>The way you're calling this, you are passing <code>'Foo'</code> as the first parameter to <code>Foo::connect</code> or the returned sub from <code>Foo-&gt;can('connect')</code>. It seems that somehow that's being passed to some code that thinks it's a database handle, and that's telling that object to <code>rollback</code>. </p>\n" }, { "answer_id": 200016, "author": "Frentos", "author_id": 23978, "author_profile": "https://Stackoverflow.com/users/23978", "pm_score": 2, "selected": false, "text": "<p>I agree with Axeman. You should probably be calling your function using</p>\n\n<pre><code>use Foo;\n...\n$dbh = Foo::connect();\n</code></pre>\n\n<p>instead of Foo->connect();</p>\n" }, { "answer_id": 200739, "author": "Ovid", "author_id": 8003, "author_profile": "https://Stackoverflow.com/users/8003", "pm_score": 3, "selected": false, "text": "<p>We need to see the actual code in Foo to be able to answer this. You probably want to read <a href=\"http://search.cpan.org/dist/DBI/DBI.pm#Subclassing_the_DBI\" rel=\"nofollow noreferrer\">Subclassing the DBI</a> from the documentation to see how to do this properly.</p>\n\n<p>Basically, you either need Foo to subclass DBI properly (again, you'll need to read the docs), or you need to declare a connect function to properly delegate to the DBI::connect method. Be careful about writing a producedural wrapper for OO code, though. It gets awfully hard to maintain state that way.</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12448/" ]
For some reason I am having troubles with a DBI handle. Basically what happened was that I made a special connect function in a perl module and switched from doing: ``` do 'foo.pl' ``` to ``` use Foo; ``` and then I do ``` $dbh = Foo->connect; ``` And now for some reason I keep getting the error: > > Can't locate object method "rollback" via package "Foo" at ../Foo.pm line 171. > > > So the weird thing is that $dbh is definitely not a Foo, it's just defined in foo. Anyway, I haven't had any troubles with it up until now. Any ideas what's up? **Edit**: @Axeman: `connect` did not exist in the original. Before we just had a string that we used like this: ``` do 'foo.pl'; $dbh = DBI->connect($DBConnectString); ``` and so `connect` is something like this ``` sub connect { my $dbh = DBI->connect('blah'); return $dbh; } ```
From [perlfunc](http://perldoc.perl.org/perlfunc.html#do-EXPR): > > ``` > > do 'stat.pl'; > > is just like > > eval `cat stat.pl`; > > ``` > So when you `do 'foo.pl'`, you execute the code in the current context. Because I don't know what goes on in `foo.pl` or `Foo.pm`, I can't tell you what's changed. But, I can tell you that it's always executed in the current context, and now in executes in `Foo::` namespace. The way you're calling this, you are passing `'Foo'` as the first parameter to `Foo::connect` or the returned sub from `Foo->can('connect')`. It seems that somehow that's being passed to some code that thinks it's a database handle, and that's telling that object to `rollback`.
199,498
<p>I'm just getting started working with foreign keys for the first time and I'm wondering if there's a standard naming scheme to use for them?</p> <p>Given these tables:</p> <pre><code>task (id, userid, title) note (id, taskid, userid, note); user (id, name) </code></pre> <p>Where Tasks have Notes, Tasks are owned by Users, and Users author Notes.</p> <p>How would the three foreign keys be named in this situation? Or alternatively, <em>does it even matter at all</em>?</p> <p><em>Update</em>: This question is about foreign key names, not field names!</p>
[ { "answer_id": 199504, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 4, "selected": false, "text": "<p>How about <code>FK_TABLENAME_COLUMNNAME</code>?</p>\n\n<p><strong>K</strong>eep <strong>I</strong>t <strong>S</strong>imple <strong>S</strong>tupid whenever possible.</p>\n" }, { "answer_id": 199506, "author": "Steve Moyer", "author_id": 17008, "author_profile": "https://Stackoverflow.com/users/17008", "pm_score": 3, "selected": false, "text": "<p>I usually just leave my PK named id, and then concatenate my table name and key column name when naming FKs in other tables. I never bother with camel-casing, because some databases discard case-sensitivity and simply return all upper or lower case names anyway. In any case, here's what my version of your tables would look like:</p>\n\n<pre><code>task (id, userid, title);\nnote (id, taskid, userid, note);\nuser (id, name);\n</code></pre>\n\n<p>Note that I also name my tables in the singular, because a row represents one of the objects I'm persisting. Many of these conventions are personal preference. I'd suggest that it's more important to choose a convention and always use it, than it is to adopt someone else's convention.</p>\n" }, { "answer_id": 199549, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 9, "selected": true, "text": "<p>The standard convention in SQL Server is:</p>\n\n<pre><code>FK_ForeignKeyTable_PrimaryKeyTable\n</code></pre>\n\n<p>So, for example, the key between notes and tasks would be:</p>\n\n<pre><code>FK_note_task\n</code></pre>\n\n<p>And the key between tasks and users would be:</p>\n\n<pre><code>FK_task_user\n</code></pre>\n\n<p>This gives you an 'at a glance' view of which tables are involved in the key, so it makes it easy to see which tables a particular one (the first one named) depends on (the second one named). In this scenario the complete set of keys would be:</p>\n\n<pre><code>FK_task_user\nFK_note_task\nFK_note_user\n</code></pre>\n\n<p>So you can see that tasks depend on users, and notes depend on both tasks and users.</p>\n" }, { "answer_id": 200253, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 6, "selected": false, "text": "<p>I use two underscore characters as delimiter i.e. </p>\n\n<pre><code>fk__ForeignKeyTable__PrimaryKeyTable \n</code></pre>\n\n<p>This is because table names will occasionally contain underscore characters themselves. This follows the naming convention for constraints generally because data elements' names will frequently contain underscore characters e.g. </p>\n\n<pre><code>CREATE TABLE NaturalPersons (\n ...\n person_death_date DATETIME, \n person_death_reason VARCHAR(30) \n CONSTRAINT person_death_reason__not_zero_length\n CHECK (DATALENGTH(person_death_reason) &gt; 0), \n CONSTRAINT person_death_date__person_death_reason__interaction\n CHECK ((person_death_date IS NULL AND person_death_reason IS NULL)\n OR (person_death_date IS NOT NULL AND person_death_reason IS NOT NULL))\n ...\n</code></pre>\n" }, { "answer_id": 22673186, "author": "Chad Kieffer", "author_id": 437101, "author_profile": "https://Stackoverflow.com/users/437101", "pm_score": 0, "selected": false, "text": "<p>Based on the answers and comments here, a naming convention which includes the FK table, FK field, and PK table (FK_FKTbl_FKCol_PKTbl) should avoid FK constraint name collisions.</p>\n\n<p>So, for the given tables here:</p>\n\n<pre><code>fk_task_userid_user\nfk_note_userid_user\n</code></pre>\n\n<p>So, if you add a column to track who last modified a task or a note...</p>\n\n<pre><code>fk_task_modifiedby_user\nfk_note_modifiedby_user\n</code></pre>\n" }, { "answer_id": 24729967, "author": "bvj", "author_id": 241296, "author_profile": "https://Stackoverflow.com/users/241296", "pm_score": 4, "selected": false, "text": "<p>A note from Microsoft concerning SQL Server:</p>\n\n<blockquote>\n <p>A FOREIGN KEY constraint does not have to be linked only to a PRIMARY\n KEY constraint in another table; it can also be defined to reference\n the columns of a UNIQUE constraint in another table.</p>\n</blockquote>\n\n<p>so, I'll use terms describing dependency instead of the conventional primary/foreign relationship terms.</p>\n\n<p>When referencing the PRIMARY KEY of the <em>independent (parent)</em> table by the similarly named column(s) in the <em>dependent (child)</em> table, I omit the column name(s):</p>\n\n<pre><code>FK_ChildTable_ParentTable\n</code></pre>\n\n<p>When referencing other columns, or the column names vary between the two tables, or just to be explicit:</p>\n\n<pre><code>FK_ChildTable_childColumn_ParentTable_parentColumn\n</code></pre>\n" }, { "answer_id": 25337036, "author": "user12345", "author_id": 1048805, "author_profile": "https://Stackoverflow.com/users/1048805", "pm_score": -1, "selected": false, "text": "<p>If you aren't referencing your FK's that often and using MySQL (and InnoDB) then you can just let MySQL name the FK for you.</p>\n\n<p>At a later time you can <a href=\"https://stackoverflow.com/a/25336979/1048805\">find the FK name you need by running a query</a>. </p>\n" }, { "answer_id": 35051349, "author": "Cary Bondoc", "author_id": 2947415, "author_profile": "https://Stackoverflow.com/users/2947415", "pm_score": 2, "selected": false, "text": "<p>My usual approach is</p>\n\n<pre><code>FK_ColumnNameOfForeignKey_TableNameOfReference_ColumnNameOfReference\n</code></pre>\n\n<p>Or in other terms</p>\n\n<pre><code>FK_ChildColumnName_ParentTableName_ParentColumnName\n</code></pre>\n\n<p>This way I can name two foreign keys that reference the same table like a <code>history_info table</code> with <code>column actionBy and actionTo</code> from <code>users_info</code> table</p>\n\n<p>It will be like</p>\n\n<pre><code>FK_actionBy_usersInfo_name - For actionBy\nFK_actionTo_usersInfo_name - For actionTo\n</code></pre>\n\n<p><strong>Note that:</strong></p>\n\n<p>I didn't include the child table name because it seems common sense to me, I am in the table of the child so I can easily assume the child's table name. <strong>The total character of it is 26 and fits well to the 30 character limit of oracle</strong> which was stated by Charles Burns on a comment <a href=\"https://stackoverflow.com/q/199498/2947415\">here</a></p>\n\n<blockquote>\n <p>Note for readers: Many of the best practices listed below do not work\n in Oracle because of its 30 character name limit. A table name or\n column name may already be close to 30 characters, so a convention\n combining the two into a single name requires a truncation standard or\n other tricks. – Charles Burns</p>\n</blockquote>\n" }, { "answer_id": 35470097, "author": "SSISPissesMeOff", "author_id": 704906, "author_profile": "https://Stackoverflow.com/users/704906", "pm_score": 3, "selected": false, "text": "<p>This is probably over-kill, but it works for me. It helps me a great deal when I am dealing with VLDBs especially. I use the following: </p>\n\n<pre><code>CONSTRAINT [FK_ChildTableName_ChildColName_ParentTableName_PrimaryKeyColName]\n</code></pre>\n\n<p>Of course if for some reason you are not referencing a primary key you must be referencing a column contained in a unique constraint, in this case: </p>\n\n<pre><code>CONSTRAINT [FK_ChildTableName_ChildColumnName_ParentTableName_ColumnInUniqueConstaintName]\n</code></pre>\n\n<p>Can it be long, yes. Has it helped keep info clear for reports, or gotten me a quick jump on that the potential issue is during a prod-alert 100% would love to know peoples thoughts on this naming convention. </p>\n" }, { "answer_id": 50710247, "author": "coldserenity", "author_id": 3112116, "author_profile": "https://Stackoverflow.com/users/3112116", "pm_score": -1, "selected": false, "text": "<p>Try using upper-cased Version 4 UUID with first octet replaced by FK and '_' (underscore) instead of '-' (dash).</p>\n\n<p>E.g.</p>\n\n<ul>\n<li><code>FK_4VPO_K4S2_A6M1_RQLEYLT1VQYV</code></li>\n<li><code>FK_1786_45A6_A17C_F158C0FB343E</code></li>\n<li><code>FK_45A5_4CFA_84B0_E18906927B53</code></li>\n</ul>\n\n<p>Rationale is the following</p>\n\n<ul>\n<li>Strict generation algorithm => <strong>uniform names</strong>;</li>\n<li><strong>Key length is less than 30 characters</strong>, which is naming length limitation in Oracle (before 12c);</li>\n<li>If your entity name changes you <strong>don't need to rename your FK</strong> like in entity-name based approach (if DB supports table rename operator);</li>\n<li>One would seldom use foreign key constraint's name. E.g. DB tool usually shows what the constraint applies to. No need to be afraid of cryptic look, because you can avoid using it for \"decryption\".</li>\n</ul>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
I'm just getting started working with foreign keys for the first time and I'm wondering if there's a standard naming scheme to use for them? Given these tables: ``` task (id, userid, title) note (id, taskid, userid, note); user (id, name) ``` Where Tasks have Notes, Tasks are owned by Users, and Users author Notes. How would the three foreign keys be named in this situation? Or alternatively, *does it even matter at all*? *Update*: This question is about foreign key names, not field names!
The standard convention in SQL Server is: ``` FK_ForeignKeyTable_PrimaryKeyTable ``` So, for example, the key between notes and tasks would be: ``` FK_note_task ``` And the key between tasks and users would be: ``` FK_task_user ``` This gives you an 'at a glance' view of which tables are involved in the key, so it makes it easy to see which tables a particular one (the first one named) depends on (the second one named). In this scenario the complete set of keys would be: ``` FK_task_user FK_note_task FK_note_user ``` So you can see that tasks depend on users, and notes depend on both tasks and users.
199,499
<p>I'm creating a custom Java Struts tag that is for building and formatting an html select box in a standardised way (part of our usability guidelines).</p> <p>Each select box has an additional/initial value which describes the requirement of the value returned by the select element, i.e.:</p> <ul> <li><i>Mandatory</i> - with the label "Please Select" <li><i>Optional</i> - "None Selected" <li><i>Select All</i> - "Select All" </ul> <p>The custom tag will have a property that controls which of these are to be used.</p> <p>So the problem is, I need to think of a variable name that can adequately explain that is is holding one of these three values!<br> I will be commenting the code in any case, but I'd prefer that co-workers didn't have to look up the source code to remember what the tag variable's purpose is.</p> <p><strong>Edit:</strong> To put some context around this problem, the usability strategy that I'm implementing here is that if there are more than 5 items that can be selected, the options should appear as a select box. 5 or less items will appear as radio buttons.<br> When radio buttons are being used, the mandatory label won't be displayed (form validation will complain if there's no value selected anyway). </p>
[ { "answer_id": 199507, "author": "caskey", "author_id": 114986, "author_profile": "https://Stackoverflow.com/users/114986", "pm_score": 2, "selected": false, "text": "<p>'multiplicity' would seem the right name.</p>\n\n<p>Looks like you're describing the following values:</p>\n\n<p>Mandatory: 1\nOptional: 0+\nSelect All: n</p>\n" }, { "answer_id": 199532, "author": "Brandon", "author_id": 23133, "author_profile": "https://Stackoverflow.com/users/23133", "pm_score": 0, "selected": false, "text": "<p><strong>optionality</strong></p>\n\n<p>Mandatory/Optional seems like a boolean whether this is an optional field.</p>\n\n<p>Select All nearly seems unrelated and could be its own property.</p>\n" }, { "answer_id": 199572, "author": "Mike Spross", "author_id": 17862, "author_profile": "https://Stackoverflow.com/users/17862", "pm_score": 4, "selected": true, "text": "<p><strong>NOTE: See EDIT below for a different approach than the one given here</strong></p>\n\n<p>How about <code>requirementConstraint</code>?</p>\n\n<pre><code>&lt;my:customSelect requirementConstraint=\"Mandatory\"&gt;\n &lt;option value=\"1\"&gt;A&lt;/option&gt;\n &lt;option value=\"2\"&gt;B&lt;/option&gt;\n &lt;option value=\"3\"&gt;C&lt;/option&gt;\n&lt;/my:customSelect&gt;\n</code></pre>\n\n<p>Another possiblity is not to tri-state the value in the first place. For example, you can instead provide two separate properties: <code>required</code> (<code>\"yes\" | \"no\"</code>), and <code>selectAll</code> (<code>\"yes\" | \"no\"</code>) to make the intent clearer.</p>\n\n<hr/>\n\n<p><strong>EDIT</strong>: Actually, I can see how a tri-state might still be useful, if I understand your requirements correctly. Another possibility would be to call the property <code>mustSelect</code> and make the allowed values <code>one</code> (mandatory), <code>any</code> (optional), and <code>all</code> (select all). Also, since \"Select All\" is a possibility, I'm assuming your <code>customSelect</code> tag renders each option as a checkbox. An example of how <code>mustSelect</code> might be used:</p>\n\n<p><strong>Mandatory (at least one)</strong></p>\n\n<pre><code>&lt;my:customSelect mustSelect=\"one\"&gt;\n &lt;option value=\"1\"&gt;A&lt;/option&gt;\n &lt;option value=\"2\"&gt;B&lt;/option&gt;\n &lt;option value=\"3\"&gt;C&lt;/option&gt;\n&lt;/my:customSelect&gt;\n</code></pre>\n\n<p><strong>Optional (zero or more)</strong></p>\n\n<pre><code>&lt;my:customSelect mustSelect=\"any\"&gt;\n &lt;option value=\"1\"&gt;A&lt;/option&gt;\n &lt;option value=\"2\"&gt;B&lt;/option&gt;\n &lt;option value=\"3\"&gt;C&lt;/option&gt;\n&lt;/my:customSelect&gt;\n</code></pre>\n\n<p><strong>Select all</strong></p>\n\n<pre><code>&lt;my:customSelect mustSelect=\"all\"&gt;\n &lt;option value=\"1\"&gt;A&lt;/option&gt;\n &lt;option value=\"2\"&gt;B&lt;/option&gt;\n &lt;option value=\"3\"&gt;C&lt;/option&gt;\n&lt;/my:customSelect&gt;\n</code></pre>\n" }, { "answer_id": 199591, "author": "Pitarou", "author_id": 1260685, "author_profile": "https://Stackoverflow.com/users/1260685", "pm_score": 1, "selected": false, "text": "<p>That's an interesting question. I must have come across this situation many times before, but never really thought about it in that way.</p>\n\n<p>Your problem is that your programming language supports two-way options (e.g. zero-or-one) much better than three-way options (zero-one-or-many). The shorthand that arises \"naturally\" is generally the shorthand that arises from the programming language, so there is no \"natural\" shorthand for three-way options.</p>\n\n<p>In the spirit of KISS*, I suggest that you append \"ZeroOneOrMany\" to the property name.</p>\n\n<hr>\n\n<p>[*] Keep It Simple, Stupid!</p>\n" } ]
2008/10/13
[ "https://Stackoverflow.com/questions/199499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6340/" ]
I'm creating a custom Java Struts tag that is for building and formatting an html select box in a standardised way (part of our usability guidelines). Each select box has an additional/initial value which describes the requirement of the value returned by the select element, i.e.: * *Mandatory* - with the label "Please Select" * *Optional* - "None Selected" * *Select All* - "Select All" The custom tag will have a property that controls which of these are to be used. So the problem is, I need to think of a variable name that can adequately explain that is is holding one of these three values! I will be commenting the code in any case, but I'd prefer that co-workers didn't have to look up the source code to remember what the tag variable's purpose is. **Edit:** To put some context around this problem, the usability strategy that I'm implementing here is that if there are more than 5 items that can be selected, the options should appear as a select box. 5 or less items will appear as radio buttons. When radio buttons are being used, the mandatory label won't be displayed (form validation will complain if there's no value selected anyway).
**NOTE: See EDIT below for a different approach than the one given here** How about `requirementConstraint`? ``` <my:customSelect requirementConstraint="Mandatory"> <option value="1">A</option> <option value="2">B</option> <option value="3">C</option> </my:customSelect> ``` Another possiblity is not to tri-state the value in the first place. For example, you can instead provide two separate properties: `required` (`"yes" | "no"`), and `selectAll` (`"yes" | "no"`) to make the intent clearer. --- **EDIT**: Actually, I can see how a tri-state might still be useful, if I understand your requirements correctly. Another possibility would be to call the property `mustSelect` and make the allowed values `one` (mandatory), `any` (optional), and `all` (select all). Also, since "Select All" is a possibility, I'm assuming your `customSelect` tag renders each option as a checkbox. An example of how `mustSelect` might be used: **Mandatory (at least one)** ``` <my:customSelect mustSelect="one"> <option value="1">A</option> <option value="2">B</option> <option value="3">C</option> </my:customSelect> ``` **Optional (zero or more)** ``` <my:customSelect mustSelect="any"> <option value="1">A</option> <option value="2">B</option> <option value="3">C</option> </my:customSelect> ``` **Select all** ``` <my:customSelect mustSelect="all"> <option value="1">A</option> <option value="2">B</option> <option value="3">C</option> </my:customSelect> ```
199,508
<p>Is it possible to show other processes in progress on an Oracle database? Something like Sybases <code>sp_who</code></p>
[ { "answer_id": 199523, "author": "jim", "author_id": 27628, "author_profile": "https://Stackoverflow.com/users/27628", "pm_score": 3, "selected": false, "text": "<p>After looking at sp_who, Oracle does not have that ability per se. Oracle has at least 8 processes running which run the db. Like RMON etc.</p>\n\n<p>You can ask the DB which queries are running as that just a table query. Look at the V$ tables.</p>\n\n<p>Quick Example:</p>\n\n<pre><code>SELECT sid,\n opname,\n sofar,\n totalwork,\n units,\n elapsed_seconds,\n time_remaining\nFROM v$session_longops\nWHERE sofar != totalwork;\n</code></pre>\n" }, { "answer_id": 199567, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 8, "selected": true, "text": "<p>I suspect you would just want to grab a few columns from V$SESSION and the SQL statement from V$SQL. Assuming you want to exclude the background processes that Oracle itself is running</p>\n\n<pre><code>SELECT sess.process, sess.status, sess.username, sess.schemaname, sql.sql_text\n FROM v$session sess,\n v$sql sql\n WHERE sql.sql_id(+) = sess.sql_id\n AND sess.type = 'USER'\n</code></pre>\n\n<p>The outer join is to handle those sessions that aren't currently active, assuming you want those. You could also get the sql_fulltext column from V$SQL which will have the full SQL statement rather than the first 1000 characters, but that is a CLOB and so likely a bit more complicated to deal with.</p>\n\n<p>Realistically, you probably want to look at everything that is available in V$SESSION because it's likely that you can get a lot more information than SP_WHO provides.</p>\n" }, { "answer_id": 17952845, "author": "Ryan", "author_id": 2040330, "author_profile": "https://Stackoverflow.com/users/2040330", "pm_score": 2, "selected": false, "text": "<p>Keep in mind that there are processes on the database which may not currently support a session.</p>\n\n<p>If you're interested in all processes you'll want to look to v$process (or gv$process on RAC)</p>\n" }, { "answer_id": 24946439, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 3, "selected": false, "text": "<p>This one shows SQL that is currently \"ACTIVE\":-</p>\n\n<pre><code>select S.USERNAME, s.sid, s.osuser, t.sql_id, sql_text\nfrom v$sqltext_with_newlines t,V$SESSION s\nwhere t.address =s.sql_address\nand t.hash_value = s.sql_hash_value\nand s.status = 'ACTIVE'\nand s.username &lt;&gt; 'SYSTEM'\norder by s.sid,t.piece\n/\n</code></pre>\n\n<p>This shows locks. Sometimes things are going slow, but it's because it is blocked waiting for a lock:</p>\n\n<pre><code>select\n object_name, \n object_type, \n session_id, \n type, -- Type or system/user lock\n lmode, -- lock mode in which session holds lock\n request, \n block, \n ctime -- Time since current mode was granted\nfrom\n v$locked_object, all_objects, v$lock\nwhere\n v$locked_object.object_id = all_objects.object_id AND\n v$lock.id1 = all_objects.object_id AND\n v$lock.sid = v$locked_object.session_id\norder by\n session_id, ctime desc, object_name\n/\n</code></pre>\n\n<p>This is a good one for finding long operations (e.g. full table scans). If it is because of lots of short operations, nothing will show up.</p>\n\n<pre><code>COLUMN percent FORMAT 999.99 \n\nSELECT sid, to_char(start_time,'hh24:mi:ss') stime, \nmessage,( sofar/totalwork)* 100 percent \nFROM v$session_longops\nWHERE sofar/totalwork &lt; 1\n/\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14952/" ]
Is it possible to show other processes in progress on an Oracle database? Something like Sybases `sp_who`
I suspect you would just want to grab a few columns from V$SESSION and the SQL statement from V$SQL. Assuming you want to exclude the background processes that Oracle itself is running ``` SELECT sess.process, sess.status, sess.username, sess.schemaname, sql.sql_text FROM v$session sess, v$sql sql WHERE sql.sql_id(+) = sess.sql_id AND sess.type = 'USER' ``` The outer join is to handle those sessions that aren't currently active, assuming you want those. You could also get the sql\_fulltext column from V$SQL which will have the full SQL statement rather than the first 1000 characters, but that is a CLOB and so likely a bit more complicated to deal with. Realistically, you probably want to look at everything that is available in V$SESSION because it's likely that you can get a lot more information than SP\_WHO provides.
199,521
<p>I have a form with a "Clear" button.</p> <p>When the user clicks "Clear", I want to clear the value of all the visible elements on the form. In the case of date controls, I want to reset them to the current date.</p> <p>All of my controls are contained on a Panel.</p> <p>Right now, I'm doing this with the below code. Is there an easier way than manually checking for each control type? This method seems excessively unwieldy.</p> <p>To make matters worse, in order to recursively clear controls inside sub-containers (i.e., a group box within the panel) I have to repeat the whole monster with an overloaded "GroupBox" version.</p> <p><em>Edit: Thanks to your suggestions, the below code is greatly simplified.</em></p> <pre><code>Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click 'User clicks Clear, so clear all the controls within this panel ClearAllControls(panMid, True) 'True indicates that yes, i want to recurse through sub-containers End Sub ClearAllControls(ByRef container As Panel, Optional Recurse As Boolean = True) 'Clear all of the controls within the container object 'If "Recurse" is true, then also clear controls within any sub-containers Dim ctrl As Control For Each ctrl In container.Controls If (ctrl.GetType() Is GetType(TextBox)) Then Dim txt As TextBox = CType(ctrl, TextBox) txt.Text = "" End If If (ctrl.GetType() Is GetType(CheckBox)) Then Dim chkbx As CheckBox = CType(ctrl, CheckBox) chkbx.Checked = False End If If (ctrl.GetType() Is GetType(ComboBox)) Then Dim cbobx As ComboBox = CType(ctrl, ComboBox) cbobx.SelectedIndex = -1 End If If (ctrl.GetType() Is GetType(DateTimePicker)) Then Dim dtp As DateTimePicker = CType(ctrl, DateTimePicker) dtp.Value = Now() End If If Recurse Then If (ctrl.GetType() Is GetType(Panel)) Then Dim pnl As Panel = CType(ctrl, Panel) ClearAllControls(pnl, Recurse) End If If ctrl.GetType() Is GetType(GroupBox) Then Dim grbx As GroupBox = CType(ctrl, GroupBox) ClearAllControls(grbx, Recurse) End If End If Next End Sub </code></pre> <p>@Theraccoonbear: I like your suggestion, but when I change the declaration to this:</p> <pre><code>Private Sub ClearAllControls(ByRef controls As ControlCollection, Optional ByVal Recurse As Boolean = True) </code></pre> <p>Then this line gives me "Unable to cast object of type 'ControlCollection' to type 'ControlCollection'.":</p> <pre><code> ClearAllControls(panMid.Controls) </code></pre>
[ { "answer_id": 199540, "author": "theraccoonbear", "author_id": 7210, "author_profile": "https://Stackoverflow.com/users/7210", "pm_score": 1, "selected": false, "text": "<p>I've done something similar and this is basically how I went about doing it. The only change I might suggest would be instead of overloading the method, just make the passed in type a Control and you can use the same version for GroupBox, Panel, or any other container control that provides a .Controls property. Other than that, I think the definition of \"clearing\" a control can be somewhat ambiguous and thus there's no Clear() method belonging to the Control class so you need to implement what that means for your purposes for each control type.</p>\n" }, { "answer_id": 199553, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 5, "selected": true, "text": "<p>You can skip the GetType and CType dance with <a href=\"http://msdn.microsoft.com/en-us/library/zyy863x8(VS.80).aspx\" rel=\"noreferrer\">TryCast</a>:</p>\n\n<pre><code>Dim dtp as DateTimePicker = TryCast(ctrl, DateTimePicker)\nIf dtp IsNot Nothing then dtp.Value = Now()\n</code></pre>\n\n<p>That'll save you about 10 lines.</p>\n\n<p>An <a href=\"http://msdn.microsoft.com/en-us/library/bb384936.aspx\" rel=\"noreferrer\">extension method</a> off the Control class should keep it pretty tidy:</p>\n\n<pre><code>&lt;Extension()&gt; _\nPublic Shared Sub ClearValue(c as Control, recursive as Boolean)\n Dim dtp as DateTimePicker = TryCast(c, DateTimePicker)\n If dtp IsNot Nothing Then dtp.Value = Now()\n ' Blah, Blah, Blah\nEnd Sub\n</code></pre>\n\n<p>Edit: If the thought of Evil extension methods that ignore NullReferenceExceptions don't make you cringe:</p>\n\n<pre><code>&lt;Extension()&gt; _\nPublic Shared Sub ClearValue(c as CheckBox)\n If c IsNot Nothing Then c.Checked = False\nEnd Sub\n\nTryCast(ctrl, CheckBox).ClearValue()\n</code></pre>\n" }, { "answer_id": 199558, "author": "rjrapson", "author_id": 1616, "author_profile": "https://Stackoverflow.com/users/1616", "pm_score": 2, "selected": false, "text": "<p>Why not just have one routine</p>\n\n<pre><code>ClearAllControls(ByRef container As Control, Optional ByVal Recurse As Boolean = True)\n</code></pre>\n\n<p>You can recurse into it regardless of what level in the hierarchy you begin the call, from the form level down to a single container.</p>\n\n<p>Also, on the TextBox controls, I use <code>Textbox.Text = String.Empty</code></p>\n" }, { "answer_id": 1961621, "author": "ShoushouLebanon", "author_id": 238637, "author_profile": "https://Stackoverflow.com/users/238637", "pm_score": 1, "selected": false, "text": "<pre><code>For Each c In CONTAINER.Controls\n If TypeOf c Is TextBox Then\n c.Text = \"\"\n End If\nNext\n</code></pre>\n\n<p>Replace the (CONTAINER) by the name of yours (it may be a FORM, a PANEL, a GROUPBOX)<br>\nPay attention to which you had included your controls in.</p>\n" }, { "answer_id": 12541586, "author": "Sekhar Babu", "author_id": 1690479, "author_profile": "https://Stackoverflow.com/users/1690479", "pm_score": 1, "selected": false, "text": "<p>Here it works for all inner controls.<br>\nAdd if any other controls do you need to clear.</p>\n\n<pre><code>Private Sub ClearAll()\n Try\n For Each ctrl As Control In Me.Controls\n If ctrl.[GetType]().Name = \"Panel\" Then\n ClearControls(ctrl)\n End If\n\n If ctrl.[GetType]().Name = \"GroupBox\" Then\n ClearControls(ctrl)\n End If\n If ctrl.[GetType]().Name = \"ComboBox\" Then\n Dim tb As ComboBox = TryCast(ctrl, ComboBox)\n tb.SelectedText = \"\"\n End If\n\n\n If ctrl.[GetType]().Name = \"TabControl\" Then\n ClearControls(ctrl)\n End If\n\n If ctrl.[GetType]().Name = \"TextBox\" Then\n Dim tb As TextBox = TryCast(ctrl, TextBox)\n tb.Clear()\n End If\n\n If ctrl.[GetType]().Name = \"RadioButton\" Then\n Dim tb As RadioButton = TryCast(ctrl, RadioButton)\n tb.Checked = False\n End If\n\n If ctrl.[GetType]().Name = \"CheckBox\" Then\n Dim tb As CheckBox = TryCast(ctrl, CheckBox)\n tb.Checked = False\n End If\n\n If ctrl.[GetType]().Name = \"ComboBox\" Then\n Dim tb As ComboBox = TryCast(ctrl, ComboBox)\n tb.SelectedIndex = 0\n End If\n\n If ctrl.[GetType]().Name = \"RichTextBox\" Then\n Dim tb As RichTextBox = TryCast(ctrl, RichTextBox)\n tb.Clear()\n\n End If\n Next\n Catch ex As Exception\n MessageBox.Show(ex.Message, \"Error Message\", MessageBoxButtons.OK, MessageBoxIcon.Error)\n End Try\nEnd Sub\n\n\nPrivate Sub ClearControls(ByVal Type As Control)\n\n Try\n For Each ctrl As Control In Type.Controls\n\n If ctrl.[GetType]().Name = \"TextBox\" Then\n Dim tb As TextBox = TryCast(ctrl, TextBox)\n tb.Clear()\n End If\n\n If ctrl.[GetType]().Name = \"Panel\" Then\n ClearControls(ctrl)\n End If\n\n If ctrl.[GetType]().Name = \"GroupBox\" Then\n ClearControls(ctrl)\n End If\n\n If ctrl.[GetType]().Name = \"TabPage\" Then\n ClearControls(ctrl)\n End If\n\n If ctrl.[GetType]().Name = \"ComboBox\" Then\n Dim tb As ComboBox = TryCast(ctrl, ComboBox)\n tb.SelectedText = \"\"\n End If\n\n If ctrl.[GetType]().Name = \"RadioButton\" Then\n Dim tb As RadioButton = TryCast(ctrl, RadioButton)\n tb.Checked = False\n End If\n\n If ctrl.[GetType]().Name = \"CheckBox\" Then\n Dim tb As CheckBox = TryCast(ctrl, CheckBox)\n tb.Checked = False\n End If\n\n If ctrl.[GetType]().Name = \"RichTextBox\" Then\n Dim tb As RichTextBox = TryCast(ctrl, RichTextBox)\n tb.Clear()\n\n End If\n Next\n Catch ex As Exception\n MessageBox.Show(ex.Message, \"Error Message\", MessageBoxButtons.OK, MessageBoxIcon.Error)\n End Try\nEnd Sub\n</code></pre>\n" }, { "answer_id": 12985464, "author": "Imran", "author_id": 1760995, "author_profile": "https://Stackoverflow.com/users/1760995", "pm_score": 3, "selected": false, "text": "<p>here is the code to get all control of a Form's All GroupControls \nand you can do something in the GroupBox Control</p>\n\n<pre><code>Private Sub GetControls()\n For Each GroupBoxCntrol As Control In Me.Controls\n If TypeOf GroupBoxCntrol Is GroupBox Then\n For Each cntrl As Control In GroupBoxCntrol.Controls\n 'do somethin here\n\n Next\n End If\n\n Next\nEnd Sub\n</code></pre>\n" }, { "answer_id": 14756578, "author": "dmcgill50", "author_id": 168617, "author_profile": "https://Stackoverflow.com/users/168617", "pm_score": 1, "selected": false, "text": "<p>This comes straight from an <a href=\"http://msdn.microsoft.com/en-us/library/aa289142%28v=vs.71%29.aspx\" rel=\"nofollow\">article</a> discussing techniques to use now that Control Arrays have been done away with going from VB6 to VB.NET.</p>\n\n<pre><code>Private Sub ClearForm(ByVal ctrlParent As Control)\n Dim ctrl As Control\n For Each ctrl In ctrlParent.Controls\n If TypeOf ctrl Is TextBox Then\n ctrl.Text = \"\"\n End If\n ' If the control has children, \n ' recursively call this function\n If ctrl.HasChildren Then\n ClearForm(ctrl)\n End If\n Next\nEnd Sub\n</code></pre>\n" }, { "answer_id": 21934768, "author": "ElektroStudios", "author_id": 1248295, "author_profile": "https://Stackoverflow.com/users/1248295", "pm_score": 0, "selected": false, "text": "<p>I present you my <code>ControlIterator</code> Class</p>\n\n<p>Source: <a href=\"http://pastebin.com/dubt4nPG\" rel=\"nofollow\">http://pastebin.com/dubt4nPG</a></p>\n\n<p>Some usage examples:</p>\n\n<pre><code> ControlIterator.Disable(CheckBox1)\n\n ControlIterator.Enable({CheckBox1, CheckBox2})\n\n ControlIterator.Check(Of CheckBox)(Me)\n\n ControlIterator.Uncheck(Of CheckBox)(Me.GroupBox1)\n\n ControlIterator.Hide(Of CheckBox)(\"1\")\n\n ControlIterator.PerformAction(Of CheckBox)(Sub(ctrl As CheckBox) ctrl.Visible = True)\n\n ControlIterator.AsyncPerformAction(RichTextBox1,\n Sub(rb As RichTextBox)\n For n As Integer = 0 To 9\n rb.AppendText(CStr(n))\n Next\n End Sub)\n\n ControlIterator.PerformAction(Me.Controls, Sub(c As Control)\n c.BackColor = Color.Green\n End Sub)\n</code></pre>\n" }, { "answer_id": 29611813, "author": "user3692282", "author_id": 3692282, "author_profile": "https://Stackoverflow.com/users/3692282", "pm_score": 1, "selected": false, "text": "<pre><code>Public Sub raz(lst As Control.ControlCollection, Optional recursive As Boolean = True)\n For Each ctrl As Control In lst\n If TypeOf ctrl Is TextBox Then\n CType(ctrl, TextBox).Clear()\n End If\n\n If TypeOf ctrl Is MaskedTextBox Then\n CType(ctrl, MaskedTextBox).Clear()\n End If\n\n If TypeOf ctrl Is ComboBox Then\n CType(ctrl, ComboBox).SelectedIndex = -1\n End If\n\n If TypeOf ctrl Is DateTimePicker Then\n Dim dtp As DateTimePicker = CType(ctrl, DateTimePicker)\n dtp.CustomFormat = \" \"\n End If\n\n If TypeOf ctrl Is CheckedListBox Then\n Dim clbox As CheckedListBox = CType(ctrl, CheckedListBox)\n For i As Integer = 0 To clbox.Items.Count - 1\n clbox.SetItemChecked(i, False)\n Next\n End If\n\n If TypeOf ctrl Is RadioButton Then\n CType(ctrl, RadioButton).Checked = False\n\n End If\n\n If recursive Then\n If TypeOf ctrl Is GroupBox Then\n raz(CType(ctrl, GroupBox).Controls)\n End If\n End If\n Next\nEnd Sub\n</code></pre>\n" }, { "answer_id": 64253564, "author": "user14410512", "author_id": 14410512, "author_profile": "https://Stackoverflow.com/users/14410512", "pm_score": 0, "selected": false, "text": "<p>This May Help in Future Development ...</p>\n<pre><code>GetAllButtons(Me)\n\nPublic Sub GetAllButtons(ByRef forms As Object)\n Dim list As New List(Of Button)\n Dim iIndx As Integer\n For Each c In forms.Controls\n For iIndx = 0 To forms.Controls.Count - 1\n If (TypeOf forms.Controls(iIndx) Is Button) Then\n list.Add(forms.Controls(iIndx))\n End If\n If (TypeOf forms.controls(iIndx) Is Panel) Then\n For Each cntrl As Control In forms.controls(iIndx).Controls\n If TypeOf cntrl Is Button Then\n list.Add(cntrl)\n End If\n Next\n End If\n Next\n Next\n\nButton(list.ToArray)\n\nEnd Sub\n\nPublic Sub Button(btn() As Button)\n For Each bt In btn\n Do Something with Buttons\n next\nEnd Sub\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672/" ]
I have a form with a "Clear" button. When the user clicks "Clear", I want to clear the value of all the visible elements on the form. In the case of date controls, I want to reset them to the current date. All of my controls are contained on a Panel. Right now, I'm doing this with the below code. Is there an easier way than manually checking for each control type? This method seems excessively unwieldy. To make matters worse, in order to recursively clear controls inside sub-containers (i.e., a group box within the panel) I have to repeat the whole monster with an overloaded "GroupBox" version. *Edit: Thanks to your suggestions, the below code is greatly simplified.* ``` Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click 'User clicks Clear, so clear all the controls within this panel ClearAllControls(panMid, True) 'True indicates that yes, i want to recurse through sub-containers End Sub ClearAllControls(ByRef container As Panel, Optional Recurse As Boolean = True) 'Clear all of the controls within the container object 'If "Recurse" is true, then also clear controls within any sub-containers Dim ctrl As Control For Each ctrl In container.Controls If (ctrl.GetType() Is GetType(TextBox)) Then Dim txt As TextBox = CType(ctrl, TextBox) txt.Text = "" End If If (ctrl.GetType() Is GetType(CheckBox)) Then Dim chkbx As CheckBox = CType(ctrl, CheckBox) chkbx.Checked = False End If If (ctrl.GetType() Is GetType(ComboBox)) Then Dim cbobx As ComboBox = CType(ctrl, ComboBox) cbobx.SelectedIndex = -1 End If If (ctrl.GetType() Is GetType(DateTimePicker)) Then Dim dtp As DateTimePicker = CType(ctrl, DateTimePicker) dtp.Value = Now() End If If Recurse Then If (ctrl.GetType() Is GetType(Panel)) Then Dim pnl As Panel = CType(ctrl, Panel) ClearAllControls(pnl, Recurse) End If If ctrl.GetType() Is GetType(GroupBox) Then Dim grbx As GroupBox = CType(ctrl, GroupBox) ClearAllControls(grbx, Recurse) End If End If Next End Sub ``` @Theraccoonbear: I like your suggestion, but when I change the declaration to this: ``` Private Sub ClearAllControls(ByRef controls As ControlCollection, Optional ByVal Recurse As Boolean = True) ``` Then this line gives me "Unable to cast object of type 'ControlCollection' to type 'ControlCollection'.": ``` ClearAllControls(panMid.Controls) ```
You can skip the GetType and CType dance with [TryCast](http://msdn.microsoft.com/en-us/library/zyy863x8(VS.80).aspx): ``` Dim dtp as DateTimePicker = TryCast(ctrl, DateTimePicker) If dtp IsNot Nothing then dtp.Value = Now() ``` That'll save you about 10 lines. An [extension method](http://msdn.microsoft.com/en-us/library/bb384936.aspx) off the Control class should keep it pretty tidy: ``` <Extension()> _ Public Shared Sub ClearValue(c as Control, recursive as Boolean) Dim dtp as DateTimePicker = TryCast(c, DateTimePicker) If dtp IsNot Nothing Then dtp.Value = Now() ' Blah, Blah, Blah End Sub ``` Edit: If the thought of Evil extension methods that ignore NullReferenceExceptions don't make you cringe: ``` <Extension()> _ Public Shared Sub ClearValue(c as CheckBox) If c IsNot Nothing Then c.Checked = False End Sub TryCast(ctrl, CheckBox).ClearValue() ```
199,527
<p><code>$0</code> is the variable for the top level Ruby program, but is there one for the current method?</p>
[ { "answer_id": 199550, "author": "Mark A. Nicolosi", "author_id": 1103052, "author_profile": "https://Stackoverflow.com/users/1103052", "pm_score": 5, "selected": false, "text": "<p>From <a href=\"http://snippets.dzone.com/posts/show/2785\" rel=\"noreferrer\">http://snippets.dzone.com/posts/show/2785</a>:</p>\n\n<pre><code>module Kernel\nprivate\n def this_method_name\n caller[0] =~ /`([^']*)'/ and $1\n end\nend\n\nclass Foo\n def test_method\n this_method_name\n end\nend\n\nputs Foo.new.test_method # =&gt; test_method\n</code></pre>\n" }, { "answer_id": 199560, "author": "Mark A. Nicolosi", "author_id": 1103052, "author_profile": "https://Stackoverflow.com/users/1103052", "pm_score": 10, "selected": true, "text": "<p>Even better than my first answer you can use __method__:</p>\n\n<pre><code>class Foo\n def test_method\n __method__\n end\nend\n</code></pre>\n\n<p>This returns a symbol – for example, <code>:test_method</code>. To return the method name as a string, call <code>__method__.to_s</code> instead.</p>\n\n<p><strong>Note:</strong> This requires Ruby 1.8.7.</p>\n" }, { "answer_id": 20365877, "author": "l3x", "author_id": 1978383, "author_profile": "https://Stackoverflow.com/users/1978383", "pm_score": 4, "selected": false, "text": "<p>For Ruby 1.9+ I'd recommend using <code>__callee__</code></p>\n" }, { "answer_id": 26887616, "author": "Hetal Khunti", "author_id": 4238841, "author_profile": "https://Stackoverflow.com/users/4238841", "pm_score": -1, "selected": false, "text": "<p>I got the same issue to retrieve method name in view file. I got the solution by</p>\n\n<pre><code>params[:action] # it will return method's name\n</code></pre>\n\n<p>if you want to get controller's name then</p>\n\n<pre><code>params[:controller] # it will return you controller's name\n</code></pre>\n" }, { "answer_id": 35634927, "author": "Kelvin", "author_id": 498594, "author_profile": "https://Stackoverflow.com/users/498594", "pm_score": 5, "selected": false, "text": "<p>Depending on what you actually want, you can use either <code>__method__</code> or <code>__callee__</code>, which return the currently executing method's name as a symbol.</p>\n\n<p>On ruby 1.9, both of them behave identically (as far as the <a href=\"http://ruby-doc.org/core-1.9.3/Kernel.html#method-i-__callee__\" rel=\"noreferrer\">docs</a> and my testing are concerned).</p>\n\n<p>On ruby 2.1 &amp; 2.2 <code>__callee__</code> behaves differently if you call an alias of the defined method. The <a href=\"http://ruby-doc.org/core-2.1.2/Kernel.html#method-i-__callee__\" rel=\"noreferrer\">docs</a> for the two are different:</p>\n\n<ul>\n<li><code>__method__</code>: \"the name at the definition of the current method\" (i.e. the name as it was defined)</li>\n<li><code>__callee__</code>: \"the called name of the current method\" (i.e. the name as it was called (invoked))</li>\n</ul>\n\n<p>Test script:</p>\n\n<pre><code>require 'pp'\nputs RUBY_VERSION\nclass Foo\n def orig\n {callee: __callee__, method: __method__}\n end\n alias_method :myalias, :orig\nend\npp( {call_orig: Foo.new.orig, call_alias: Foo.new.myalias} )\n</code></pre>\n\n<p>1.9.3 Output:</p>\n\n<pre><code>1.9.3\n{:call_orig=&gt;{:callee=&gt;:orig, :method=&gt;:orig},\n :call_alias=&gt;{:callee=&gt;:orig, :method=&gt;:orig}}\n</code></pre>\n\n<p>2.1.2 Output (<code>__callee__</code> returns the aliased name, but <code>__method__</code> returns the name at the point the method was defined):</p>\n\n<pre><code>2.1.2\n{:call_orig=&gt;{:callee=&gt;:orig, :method=&gt;:orig},\n :call_alias=&gt;{:callee=&gt;:myalias, :method=&gt;:orig}}\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/757/" ]
`$0` is the variable for the top level Ruby program, but is there one for the current method?
Even better than my first answer you can use \_\_method\_\_: ``` class Foo def test_method __method__ end end ``` This returns a symbol – for example, `:test_method`. To return the method name as a string, call `__method__.to_s` instead. **Note:** This requires Ruby 1.8.7.
199,528
<p>I know how to program Console application with parameters, example : myProgram.exe param1 param2.</p> <p>My question is, how can I make my program works with |, example : echo "word" | myProgram.exe?</p>
[ { "answer_id": 199534, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 7, "selected": true, "text": "<p>You need to use <code>Console.Read()</code> and <code>Console.ReadLine()</code> as if you were reading user input. Pipes replace user input transparently. You can't use both easily (although I'm sure it's quite possible...).</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>A simple <code>cat</code> style program:</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n string s;\n while ((s = Console.ReadLine()) != null)\n {\n Console.WriteLine(s);\n }\n\n }\n}\n</code></pre>\n\n<p>And when run, as expected, the output:</p>\n\n<pre>\nC:\\...\\ConsoleApplication1\\bin\\Debug>echo \"Foo bar baz\" | ConsoleApplication1.exe\n\"Foo bar baz\"\n\nC:\\...\\ConsoleApplication1\\bin\\Debug>\n</pre>\n" }, { "answer_id": 199654, "author": "Joel Mueller", "author_id": 24380, "author_profile": "https://Stackoverflow.com/users/24380", "pm_score": 2, "selected": false, "text": "<p>Console.In is a reference to a TextReader wrapped around the standard input stream. When piping large amounts of data to your program, it might be easier to work with that way.</p>\n" }, { "answer_id": 2151545, "author": "Alex N", "author_id": 207445, "author_profile": "https://Stackoverflow.com/users/207445", "pm_score": 1, "selected": false, "text": "<p>there is a problem with supplied example.</p>\n\n<blockquote>\n<pre><code> while ((s = Console.ReadLine()) != null)\n</code></pre>\n</blockquote>\n\n<p>will stuck waiting for input if program was launched without piped data. so user has to manually press any key to exit program.</p>\n" }, { "answer_id": 4074212, "author": "CodeMiller", "author_id": 425529, "author_profile": "https://Stackoverflow.com/users/425529", "pm_score": 4, "selected": false, "text": "<p>The following will not suspend the application for input and works when data is <em>or</em> is not piped. A bit of a hack; and due to the error catching, performance could lack when numerous piped calls are made but... easy.</p>\n\n<pre><code>public static void Main(String[] args)\n{\n\n String pipedText = \"\";\n bool isKeyAvailable;\n\n try\n {\n isKeyAvailable = System.Console.KeyAvailable;\n }\n catch (InvalidOperationException expected)\n {\n pipedText = System.Console.In.ReadToEnd();\n }\n\n //do something with pipedText or the args\n}\n</code></pre>\n" }, { "answer_id": 9712392, "author": "Matthew Benedict", "author_id": 498771, "author_profile": "https://Stackoverflow.com/users/498771", "pm_score": 2, "selected": false, "text": "<p>Here is another alternate solution that was put together from the other solutions plus a peek().</p>\n\n<p>Without the Peek() I was experiencing that the app would not return without ctrl-c at the end when doing \"type t.txt | prog.exe\" where t.txt is a multi-line file. But just \"prog.exe\" or \"echo hi | prog.exe\" worked fine.</p>\n\n<p>this code is meant to only process piped input.</p>\n\n<pre><code>static int Main(string[] args)\n{\n // if nothing is being piped in, then exit\n if (!IsPipedInput())\n return 0;\n\n while (Console.In.Peek() != -1)\n {\n string input = Console.In.ReadLine();\n Console.WriteLine(input);\n }\n\n return 0;\n}\n\nprivate static bool IsPipedInput()\n{\n try\n {\n bool isKey = Console.KeyAvailable;\n return false;\n }\n catch\n {\n return true;\n }\n}\n</code></pre>\n" }, { "answer_id": 21240198, "author": "matt burns", "author_id": 276093, "author_profile": "https://Stackoverflow.com/users/276093", "pm_score": 3, "selected": false, "text": "<p>This is the way to do it:</p>\n\n<pre><code>static void Main(string[] args)\n{\n Console.SetIn(new StreamReader(Console.OpenStandardInput(8192))); // This will allow input &gt;256 chars\n while (Console.In.Peek() != -1)\n {\n string input = Console.In.ReadLine();\n Console.WriteLine(\"Data read was \" + input);\n }\n}\n</code></pre>\n\n<p>This allows two usage methods. Read from <strong>standard input</strong>:</p>\n\n<pre><code>C:\\test&gt;myProgram.exe\nhello\nData read was hello\n</code></pre>\n\n<p>or read from <strong>piped input</strong>:</p>\n\n<pre><code>C:\\test&gt;echo hello | myProgram.exe\nData read was hello\n</code></pre>\n" }, { "answer_id": 29047721, "author": "gordy", "author_id": 99691, "author_profile": "https://Stackoverflow.com/users/99691", "pm_score": 4, "selected": false, "text": "<p>in .NET 4.5 it's</p>\n\n<pre><code>if (Console.IsInputRedirected)\n{\n using(stream s = Console.OpenStandardInput())\n {\n ...\n</code></pre>\n" }, { "answer_id": 46964766, "author": "Si Zi", "author_id": 1970498, "author_profile": "https://Stackoverflow.com/users/1970498", "pm_score": 2, "selected": false, "text": "<p>This will also work for</p>\n\n<blockquote>\n <p>c:\\MyApp.exe &lt; input.txt</p>\n</blockquote>\n\n<p>I had to use a StringBuilder to manipulate the inputs captured from Stdin:</p>\n\n<pre><code>public static void Main()\n{\n List&lt;string&gt; salesLines = new List&lt;string&gt;();\n Console.InputEncoding = Encoding.UTF8;\n using (StreamReader reader = new StreamReader(Console.OpenStandardInput(), Console.InputEncoding))\n {\n string stdin;\n do\n {\n StringBuilder stdinBuilder = new StringBuilder();\n stdin = reader.ReadLine();\n stdinBuilder.Append(stdin);\n var lineIn = stdin;\n if (stdinBuilder.ToString().Trim() != \"\")\n {\n salesLines.Add(stdinBuilder.ToString().Trim());\n }\n\n } while (stdin != null);\n\n }\n}\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ]
I know how to program Console application with parameters, example : myProgram.exe param1 param2. My question is, how can I make my program works with |, example : echo "word" | myProgram.exe?
You need to use `Console.Read()` and `Console.ReadLine()` as if you were reading user input. Pipes replace user input transparently. You can't use both easily (although I'm sure it's quite possible...). **Edit:** A simple `cat` style program: ``` class Program { static void Main(string[] args) { string s; while ((s = Console.ReadLine()) != null) { Console.WriteLine(s); } } } ``` And when run, as expected, the output: ``` C:\...\ConsoleApplication1\bin\Debug>echo "Foo bar baz" | ConsoleApplication1.exe "Foo bar baz" C:\...\ConsoleApplication1\bin\Debug> ```
199,537
<p>Newish to Oracle programming (from Sybase and MS SQL Server). What is the "Oracle way" to avoid filling the trans log with large updates?</p> <p>In my specific case, I'm doing an update of potentially a very large number of rows. Here's my approach:</p> <pre><code>UPDATE my_table SET a_col = null WHERE my_table_id IN (SELECT my_table_id FROM my_table WHERE some_col &lt; some_val and rownum &lt; 1000) </code></pre> <p>...where I execute this inside a loop until the updated row count is zero,</p> <p>Is this the best approach?</p> <p>Thanks,</p>
[ { "answer_id": 199578, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 0, "selected": false, "text": "<p>Any UPDATE is going to generate redo. Realistically, a single UPDATE that updates all the rows is going to generate the smallest total amount of redo and run for the shortest period of time.</p>\n\n<p>Assuming you are updating the vast majority of the rows in the table, if there are any indexes that use A_COL, you may be better off disabling those indexes before the update and then doing a rebuild of those indexes with NOLOGGING specified after the massive UPDATE statement. In addition, if there are any triggers or foreign keys that would need to be fired/ validated as a result of the update, getting rid of those temporarily might be helpful.</p>\n" }, { "answer_id": 199585, "author": "Andrew not the Saint", "author_id": 23670, "author_profile": "https://Stackoverflow.com/users/23670", "pm_score": 2, "selected": true, "text": "<p>The amount of updates to the redo and undo logs will not at all be reduced if you break up the UPDATE in multiple runs of, say 1000 records. On top of it, the total query time will be most likely be higher compared to running a single large SQL.</p>\n\n<p>There's no real way to address the UNDO/REDO log issue in UPDATEs. With INSERTs and CREATE TABLEs you can use a DIRECT aka APPEND option, but I guess this doesn't easily work for you.</p>\n" }, { "answer_id": 202530, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Depends on the percent of rows almost as much as the number. And it also depends on if the update makes the row longer than before. i.e. going from null to 200bytes in every row. This could have an effect on your performance - chained rows.</p>\n\n<p>Either way, you might want to try this.</p>\n\n<p>Build a new table with the column corrected as part of the select instead of an update. You can build that new table via CTAS (Create Table as Select) which can avoid logging.</p>\n\n<p>Drop the original table.</p>\n\n<p>Rename the new table.</p>\n\n<p>Reindex, repoint contrainst, rebuild triggers, recompile packages, etc.</p>\n\n<p>you can avoid a lot of logging this way.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14952/" ]
Newish to Oracle programming (from Sybase and MS SQL Server). What is the "Oracle way" to avoid filling the trans log with large updates? In my specific case, I'm doing an update of potentially a very large number of rows. Here's my approach: ``` UPDATE my_table SET a_col = null WHERE my_table_id IN (SELECT my_table_id FROM my_table WHERE some_col < some_val and rownum < 1000) ``` ...where I execute this inside a loop until the updated row count is zero, Is this the best approach? Thanks,
The amount of updates to the redo and undo logs will not at all be reduced if you break up the UPDATE in multiple runs of, say 1000 records. On top of it, the total query time will be most likely be higher compared to running a single large SQL. There's no real way to address the UNDO/REDO log issue in UPDATEs. With INSERTs and CREATE TABLEs you can use a DIRECT aka APPEND option, but I guess this doesn't easily work for you.
199,564
<p>My professor wrote this shell script to time my program, and display the results. For some reason it just outputs 0s with my program. He provided the following files:</p> <pre><code>timeit.csh sequence ecoli2500.txt ecoli3000.txt ecoli5000.txt ecoli7000.txt ecoli8000.txt ecoli9000.txt ecoli10000.txt </code></pre> <p>Here are the contents of sequence</p> <pre><code>java EditDistance </code></pre> <p>The contents of timeit.csh are further below.</p> <p>java EditDistance &lt; ecoli2500.txt works as expected</p> <p>In fact the program executes flawlessly with each of the above files other than sequence.</p> <p>What I don't understand is why </p> <pre><code>./timeit.csh sequence </code></pre> <p>produces all zeros</p> <p>Here is timeit.csh... (further below is EditDistance.java):</p> <pre><code>#!/bin/csh # # A Unix script to time programs. # # Command line: timeit sequence # the array of programs from the commandline set program = $argv[1] # adjust as needed set CPULIMIT = 120 limit cpu $CPULIMIT seconds limit core 0 # input files set input = ( stx1230.txt \ ecoli2500.txt \ ecoli3000.txt \ ecoli5000.txt \ ecoli7000.txt \ ecoli8000.txt \ ecoli9000.txt \ ecoli10000.txt) # adjust as needed set inputpath = `pwd` # print header printf "CPU limit = %d seconds\n\n" $CPULIMIT printf "%-25s" "Data File" foreach program ($argv) printf "%16s" $program end printf "\n" # print right number of = for table @ i = 25 + 16 * $#argv while ($i &gt; 0) printf "=" @ i = $i - 1 end printf "\n" # time it and print out row for each data file and column for each program foreach datafile ($input) printf "%-25s" $datafile if (-f $inputpath/$datafile) then foreach program ($argv) # printing running time of program on datafile # -p flag with time to ensure its output is measured in seconds and not minutes nice /usr/bin/time -p $program &lt; \ $inputpath/$datafile |&amp; \ egrep '^user[ ]*[0-9]' | \ awk '{ if ($2 &gt;= '$CPULIMIT') printf " CPU limit"; else printf("%16.2f", $2) }' # egrep, awk commands extract second column of row corresponding to user time end else printf "could not open" $datafile endif printf "\n" end </code></pre> <p>Here is EditDistance.java</p> <pre><code>import java.util.*; class EditDistance { public static int min(int a, int b, int c) { return Math.min(a,Math.min(b,c)); } public static int distance(String one, String two) { if (one.length()&gt;two.length()) { String temp1 = one; String temp2 = two; one = temp2; two = temp1; } int[][] d = new int[one.length()+1][two.length()+1]; d[0][0] = 0; int top, left, topleft, cost; for (int i = 1; i &lt;= one.length(); i++) { d[0][i] = 2*i; d[i][0] = 2*i; } for (int i = 1; i &lt;= one.length(); i++) { for (int j = 1; j &lt;= two.length(); j++) { if (one.charAt(i-1) == two.charAt(j-1)) cost = 0; else cost = 1; top = d[i][j-1]; left = d[i-1][j]; topleft = d[i-1][j-1]; d[i][j] = min(top+2,left+2,topleft+cost); } } return d[one.length()][two.length()]; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String one = scanner.next(); String two = scanner.next(); System.out.println(distance(one,two)); } } </code></pre> <p>Any Ideas why things aren't working? I don't know much about shell scripts, but this section of the shell script:</p> <pre><code>nice /usr/bin/time -p $program &lt; \ $inputpath/$datafile |&amp; \ egrep '^user[ ]*[0-9]' | \ awk '{ if ($2 &gt;= '$CPULIMIT') printf " CPU limit"; else printf("%16.2f", $2) }' </code></pre> <p>confirms in my mind that my program should be expecting this command: </p> <pre><code>java EditDistance &lt; ecoli2500.txt java EditDistance...etc. etc. </code></pre> <p>but the program works with those commands. I need to set up my program to respond correctly to the shell script. Maybe some of you can help. </p>
[ { "answer_id": 199592, "author": "Kyle Burton", "author_id": 19784, "author_profile": "https://Stackoverflow.com/users/19784", "pm_score": 0, "selected": false, "text": "<p>I'm not sure what the state of the environment (eg: PATH) or the state of the files and permissions are, but it could be as simple as a permissions problem with the sequence shell script (which I think you're saying contains 'java EditDistance'). If you 'chmod +x sequence', does it work? The other issue is that it may not be in your path, can you run sequence by typing: './sequence &lt; ecoli2500.txt'?</p>\n" }, { "answer_id": 202628, "author": "objectivesea", "author_id": 27763, "author_profile": "https://Stackoverflow.com/users/27763", "pm_score": 1, "selected": false, "text": "<p>Fixed. The problem was here:</p>\n\n<pre><code> nice /usr/bin/time -p $program &lt; \n</code></pre>\n\n<p>in the script. My computer doesn't execute shell scripts without a \"./\" before the command. My professors computer must be different. Changing the script to </p>\n\n<pre><code>nice /usr/bin/time -p ./$program &lt;\n</code></pre>\n\n<p>Ran the program perfectly.</p>\n\n<p>I know for certain that my professor and I are both using Fedora 8. What would be the difference that would let me run programs in the terminal simply by typing their name?</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
My professor wrote this shell script to time my program, and display the results. For some reason it just outputs 0s with my program. He provided the following files: ``` timeit.csh sequence ecoli2500.txt ecoli3000.txt ecoli5000.txt ecoli7000.txt ecoli8000.txt ecoli9000.txt ecoli10000.txt ``` Here are the contents of sequence ``` java EditDistance ``` The contents of timeit.csh are further below. java EditDistance < ecoli2500.txt works as expected In fact the program executes flawlessly with each of the above files other than sequence. What I don't understand is why ``` ./timeit.csh sequence ``` produces all zeros Here is timeit.csh... (further below is EditDistance.java): ``` #!/bin/csh # # A Unix script to time programs. # # Command line: timeit sequence # the array of programs from the commandline set program = $argv[1] # adjust as needed set CPULIMIT = 120 limit cpu $CPULIMIT seconds limit core 0 # input files set input = ( stx1230.txt \ ecoli2500.txt \ ecoli3000.txt \ ecoli5000.txt \ ecoli7000.txt \ ecoli8000.txt \ ecoli9000.txt \ ecoli10000.txt) # adjust as needed set inputpath = `pwd` # print header printf "CPU limit = %d seconds\n\n" $CPULIMIT printf "%-25s" "Data File" foreach program ($argv) printf "%16s" $program end printf "\n" # print right number of = for table @ i = 25 + 16 * $#argv while ($i > 0) printf "=" @ i = $i - 1 end printf "\n" # time it and print out row for each data file and column for each program foreach datafile ($input) printf "%-25s" $datafile if (-f $inputpath/$datafile) then foreach program ($argv) # printing running time of program on datafile # -p flag with time to ensure its output is measured in seconds and not minutes nice /usr/bin/time -p $program < \ $inputpath/$datafile |& \ egrep '^user[ ]*[0-9]' | \ awk '{ if ($2 >= '$CPULIMIT') printf " CPU limit"; else printf("%16.2f", $2) }' # egrep, awk commands extract second column of row corresponding to user time end else printf "could not open" $datafile endif printf "\n" end ``` Here is EditDistance.java ``` import java.util.*; class EditDistance { public static int min(int a, int b, int c) { return Math.min(a,Math.min(b,c)); } public static int distance(String one, String two) { if (one.length()>two.length()) { String temp1 = one; String temp2 = two; one = temp2; two = temp1; } int[][] d = new int[one.length()+1][two.length()+1]; d[0][0] = 0; int top, left, topleft, cost; for (int i = 1; i <= one.length(); i++) { d[0][i] = 2*i; d[i][0] = 2*i; } for (int i = 1; i <= one.length(); i++) { for (int j = 1; j <= two.length(); j++) { if (one.charAt(i-1) == two.charAt(j-1)) cost = 0; else cost = 1; top = d[i][j-1]; left = d[i-1][j]; topleft = d[i-1][j-1]; d[i][j] = min(top+2,left+2,topleft+cost); } } return d[one.length()][two.length()]; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String one = scanner.next(); String two = scanner.next(); System.out.println(distance(one,two)); } } ``` Any Ideas why things aren't working? I don't know much about shell scripts, but this section of the shell script: ``` nice /usr/bin/time -p $program < \ $inputpath/$datafile |& \ egrep '^user[ ]*[0-9]' | \ awk '{ if ($2 >= '$CPULIMIT') printf " CPU limit"; else printf("%16.2f", $2) }' ``` confirms in my mind that my program should be expecting this command: ``` java EditDistance < ecoli2500.txt java EditDistance...etc. etc. ``` but the program works with those commands. I need to set up my program to respond correctly to the shell script. Maybe some of you can help.
Fixed. The problem was here: ``` nice /usr/bin/time -p $program < ``` in the script. My computer doesn't execute shell scripts without a "./" before the command. My professors computer must be different. Changing the script to ``` nice /usr/bin/time -p ./$program < ``` Ran the program perfectly. I know for certain that my professor and I are both using Fedora 8. What would be the difference that would let me run programs in the terminal simply by typing their name?
199,597
<p>I have a table ("venues") that stores all the possible venues a volunteer can work, each volunteer is assigned to work one venue each.</p> <p>I want to create a select drop down from the venues table.</p> <p>Right now I can display the venue each volunteer is assigned, but I want it to display the drop down box, with the venue already selected in the list.</p> <pre><code>&lt;form action="upd.php?id=7"&gt; &lt;select name="venue_id"&gt; &lt;?php //some sort of loop goes here print '&lt;option value="'.$row['venue_id'].'"&gt;'.$row['venue_name'].'&lt;/option&gt;'; //end loop here ?&gt; &lt;/select&gt; &lt;input type="submit" value="submit" name="submit"&gt; &lt;/form&gt; </code></pre> <p>For example, volunteer with the id of 7, is assigned to venue_id 4</p> <pre><code>&lt;form action="upd.php?id=7"&gt; &lt;select name="venue_id"&gt; &lt;option value="1"&gt;Bagpipe Competition&lt;/option&gt; &lt;option value="2"&gt;Band Assistance&lt;/option&gt; &lt;option value="3"&gt;Beer/Wine Pouring&lt;/option&gt; &lt;option value="4" selected&gt;Brochure Distribution&lt;/option&gt; &lt;option value="5"&gt;Childrens Area&lt;/option&gt; &lt;option value="6"&gt;Cleanup&lt;/option&gt; &lt;option value="7"&gt;Cultural Center Display&lt;/option&gt; &lt;option value="8"&gt;Festival Merch&lt;/option&gt; &lt;/select&gt; &lt;input type="submit" value="submit" name="submit"&gt; &lt;/form&gt; Brochure Distribution option will already be selected when it displays the drop down list, because in the volunteers_2009 table, column venue_id is 4. </code></pre> <p>I know it will take a form of a for or while loop to pull the list of venues from the venues table</p> <p>My query is:</p> <pre><code>$query = "SELECT volunteers_2009.id, volunteers_2009.comments, volunteers_2009.choice1, volunteers_2009.choice2, volunteers_2009.choice3, volunteers_2009.lname, volunteers_2009.fname, volunteers_2009.venue_id, venues.venue_name FROM volunteers_2009 AS volunteers_2009 LEFT OUTER JOIN venues ON (volunteers_2009.venue_id = venues.id) ORDER by $order $sort"; </code></pre> <p>How do I populate the select drop down box with the venues (<strong>volunteers_2009.venue_id</strong>, <strong>venues.id</strong>) from the venues table and have it pre-select the venue in the list?</p>
[ { "answer_id": 199614, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "<pre class=\"lang-php prettyprint-override\"><code>$query = &quot;SELECT volunteers_2009.id, volunteers_2009.comments, volunteers_2009.choice1, volunteers_2009.choice2, volunteers_2009.choice3, volunteers_2009.lname, volunteers_2009.fname, volunteers_2009.venue_id, venues.venue_name FROM volunteers_2009 AS volunteers_2009 LEFT OUTER JOIN venues ON (volunteers_2009.venue_id = venues.id) ORDER by $order $sort&quot;;\n\n$res = mysql_query($query);\necho &quot;&lt;select name = 'venue'&gt;&quot;;\nwhile (($row = mysql_fetch_row($res)) != null)\n{\n echo &quot;&lt;option value = '{$row['venue_id']}'&quot;;\n if ($selected_venue_id == $row['venue_id'])\n echo &quot;selected = 'selected'&quot;;\n echo &quot;&gt;{$row['venue_name']}&lt;/option&gt;&quot;;\n}\necho &quot;&lt;/select&gt;&quot;;\n</code></pre>\n" }, { "answer_id": 199742, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>assuming you have an array of venues...personally i don't like to mix the sql with other wizardry.</p>\n\n<pre><code>function displayDropDown($items, $name, $label, $default='') {\n if (count($items)) {\n echo '&lt;select name=\"' . $name . '\"&gt;';\n echo '&lt;option value=\"\"&gt;' . $label . '&lt;/option&gt;';\n echo '&lt;option value=\"\"&gt;----------&lt;/option&gt;';\n foreach($items as $item) {\n $selected = ($item['id'] == $default) ? ' selected=\"selected\" : '';\n echo &lt;option value=\"' . $item['id'] . '\"' . $selected . '&gt;' . $item['name'] . '&lt;/option&gt;';\n }\n echo '&lt;/select&gt;';\n } else {\n echo 'There are no venues';\n }\n}\n</code></pre>\n" }, { "answer_id": 5611885, "author": "duc14s", "author_id": 375277, "author_profile": "https://Stackoverflow.com/users/375277", "pm_score": 2, "selected": false, "text": "<pre><code> &lt;?php \n $query = \"SELECT * from blogcategory\";\n //$res = mysql_query($query);\n $rows = $db-&gt;query($query);\n echo \"&lt;select name = 'venue'&gt;\";\n // while (($row = mysql_fetch_row($res)) != null)\n while ($record = $db-&gt;fetch_array($rows)) \n {\n echo \"&lt;option value = '{$record['CategoryId']}'\";\n if ($CategoryId == $record['CategoryId'])\n echo \"selected = 'selected'\";\n echo \"&gt;{$record['CategoryName']}&lt;/option&gt;\";\n }\n echo \"&lt;/select&gt;\";\n ?&gt;\n</code></pre>\n" }, { "answer_id": 46338462, "author": "Risheekant Vishwakarma", "author_id": 7995612, "author_profile": "https://Stackoverflow.com/users/7995612", "pm_score": -1, "selected": false, "text": "<pre><code>&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;title&gt;table binding&lt;/title&gt;\n &lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"&gt;&lt;/script&gt;\n\n&lt;/head&gt;\n&lt;body&gt;\n &lt;div id=\"mydiv\" style=\"width:100px;height:100px;background-color:yellow\"&gt;\n\n &lt;select id=\"myselect\"&gt;&lt;/select&gt;\n &lt;/div&gt;\n\n&lt;/body&gt;\n&lt;/html&gt;\n\n\n&lt;?php\ninclude('dbconnection.php');\n\n$sql = \"SHOW TABLES FROM $dbname\";\n$result = mysqli_query($conn,$sql);\n\nif (!$result) {\n echo \"DB Error, could not list tables\\n\";\n echo 'MySQL Error: ' . mysqli_error();\n exit;\n}\n\nwhile ($row = mysqli_fetch_row($result)) {\n echo \"&lt;script&gt;\n var z = document.createElement('option');\n z.setAttribute('value', '\".$row[0].\"');\n var t = document.createTextNode('\".$row[0].\"');\n z.appendChild(t);\n document.getElementById('myselect').appendChild(z);&lt;/script&gt;\";\n\n}\n\n\n\n?&gt;\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26130/" ]
I have a table ("venues") that stores all the possible venues a volunteer can work, each volunteer is assigned to work one venue each. I want to create a select drop down from the venues table. Right now I can display the venue each volunteer is assigned, but I want it to display the drop down box, with the venue already selected in the list. ``` <form action="upd.php?id=7"> <select name="venue_id"> <?php //some sort of loop goes here print '<option value="'.$row['venue_id'].'">'.$row['venue_name'].'</option>'; //end loop here ?> </select> <input type="submit" value="submit" name="submit"> </form> ``` For example, volunteer with the id of 7, is assigned to venue\_id 4 ``` <form action="upd.php?id=7"> <select name="venue_id"> <option value="1">Bagpipe Competition</option> <option value="2">Band Assistance</option> <option value="3">Beer/Wine Pouring</option> <option value="4" selected>Brochure Distribution</option> <option value="5">Childrens Area</option> <option value="6">Cleanup</option> <option value="7">Cultural Center Display</option> <option value="8">Festival Merch</option> </select> <input type="submit" value="submit" name="submit"> </form> Brochure Distribution option will already be selected when it displays the drop down list, because in the volunteers_2009 table, column venue_id is 4. ``` I know it will take a form of a for or while loop to pull the list of venues from the venues table My query is: ``` $query = "SELECT volunteers_2009.id, volunteers_2009.comments, volunteers_2009.choice1, volunteers_2009.choice2, volunteers_2009.choice3, volunteers_2009.lname, volunteers_2009.fname, volunteers_2009.venue_id, venues.venue_name FROM volunteers_2009 AS volunteers_2009 LEFT OUTER JOIN venues ON (volunteers_2009.venue_id = venues.id) ORDER by $order $sort"; ``` How do I populate the select drop down box with the venues (**volunteers\_2009.venue\_id**, **venues.id**) from the venues table and have it pre-select the venue in the list?
```php $query = "SELECT volunteers_2009.id, volunteers_2009.comments, volunteers_2009.choice1, volunteers_2009.choice2, volunteers_2009.choice3, volunteers_2009.lname, volunteers_2009.fname, volunteers_2009.venue_id, venues.venue_name FROM volunteers_2009 AS volunteers_2009 LEFT OUTER JOIN venues ON (volunteers_2009.venue_id = venues.id) ORDER by $order $sort"; $res = mysql_query($query); echo "<select name = 'venue'>"; while (($row = mysql_fetch_row($res)) != null) { echo "<option value = '{$row['venue_id']}'"; if ($selected_venue_id == $row['venue_id']) echo "selected = 'selected'"; echo ">{$row['venue_name']}</option>"; } echo "</select>"; ```
199,603
<p>I want to be able to write a lambda/Proc in my Ruby code, serialize it so that I can write it to disk, and then execute the lambda later. Sort of like...</p> <pre><code>x = 40 f = lambda { |y| x + y } save_for_later(f) </code></pre> <p>Later, in a separate run of the Ruby interpreter, I want to be able to say...</p> <pre><code>f = load_from_before z = f.call(2) z.should == 42 </code></pre> <p>Marshal.dump does not work for Procs. I know Perl has <a href="http://search.cpan.org/~yves/Data-Dump-Streamer-2.08-40/lib/Data/Dump/Streamer.pm" rel="nofollow noreferrer">Data::Dump::Streamer</a>, and in Lisp this is trivial. But is there a way to do it in Ruby? In other words, what would be the implementation of <code>save<code>_</code>for<code>_</code>later</code>?</p> <p><strong>Edit</strong>: <a href="https://stackoverflow.com/questions/199603/how-do-you-stringize-serialize-ruby-code/199803#199803">My answer below</a> is nice, but it does not close over free variables (like <code>x</code>) and serialize them along with the lambda. So in my example ...</p> <pre><code>x = 40 s = save_for_later { |y| x + y } # =&gt; "lambda { |y|\n (x + y)\n}" </code></pre> <p>... the string output does not include a definition for <code>x</code>. Is there a solution that takes this into account, perhaps by serializing the symbol table? Can you access that in Ruby?</p> <p><strong>Edit 2</strong>: I updated my answer to incorporate serializing local variables. This seems acceptable.</p>
[ { "answer_id": 199617, "author": "Mark", "author_id": 26310, "author_profile": "https://Stackoverflow.com/users/26310", "pm_score": -1, "selected": false, "text": "<p>Ruby has the Marshal class that has a dump method that you can call.</p>\n<p>Take a look here:</p>\n<p><a href=\"http://rubylearning.com/satishtalim/object_serialization.html\" rel=\"nofollow noreferrer\">http://rubylearning.com/satishtalim/object_serialization.html</a></p>\n" }, { "answer_id": 199732, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 2, "selected": false, "text": "<p>Check out the answers to <a href=\"https://stackoverflow.com/questions/23970/how-do-i-marshall-a-lambda-proc-in-ruby\">this question</a>.</p>\n" }, { "answer_id": 199803, "author": "Jonathan Tran", "author_id": 12887, "author_profile": "https://Stackoverflow.com/users/12887", "pm_score": 5, "selected": true, "text": "<p><strong>Use Ruby2Ruby</strong></p>\n\n<pre><code>def save_for_later(&amp;block)\n return nil unless block_given?\n\n c = Class.new\n c.class_eval do\n define_method :serializable, &amp;block\n end\n s = Ruby2Ruby.translate(c, :serializable)\n s.sub(/^def \\S+\\(([^\\)]*)\\)/, 'lambda { |\\1|').sub(/end$/, '}')\nend\n\nx = 40\ns = save_for_later { |y| x + y }\n# =&gt; \"lambda { |y|\\n (x + y)\\n}\"\ng = eval(s)\n# =&gt; #&lt;Proc:0x4037bb2c@(eval):1&gt;\ng.call(2) \n# =&gt; 42\n</code></pre>\n\n<p>This is great, but it does not close over free variables (like <code>x</code>) and serialize them along with the lambda.</p>\n\n<p>To <a href=\"https://stackoverflow.com/questions/503583/how-do-you-access-the-symbol-table-in-ruby\">serialize variables</a> also, you can iterate over <code>local_variables</code> and serialize them as well. The problem, though, is that <code>local_variables</code> from within <code>save_for_later</code> accesses only <code>c</code> and <code>s</code> in the code above -- i.e. variables local to the serialization code, not the caller. So unfortunately, we must push the grabbing of local variables and their values to the caller.</p>\n\n<p>Maybe this is a good thing, though, because in general, finding all free variables in a piece of Ruby code is <a href=\"http://en.wikipedia.org/wiki/Undecidable\" rel=\"nofollow noreferrer\">undecidable</a>. Plus, ideally we would also save <code>global_variables</code> and any loaded classes and their overridden methods. This seems impractical.</p>\n\n<p>Using this simple approach, you get the following:</p>\n\n<pre><code>def save_for_later(local_vars, &amp;block)\n return nil unless block_given?\n\n c = Class.new\n c.class_eval do\n define_method :serializable, &amp;block\n end\n s = Ruby2Ruby.translate(c, :serializable)\n locals = local_vars.map { |var,val| \"#{var} = #{val.inspect}; \" }.join\n s.sub(/^def \\S+\\(([^\\)]*)\\)/, 'lambda { |\\1| ' + locals).sub(/end$/, '}')\nend\n\nx = 40\ns = save_for_later(local_variables.map{ |v| [v,eval(v)] }) { |y| x + y }\n# =&gt; \"lambda { |y| _ = 40; x = 40;\\n (x + y)\\n}\"\n\n# In a separate run of Ruby, where x is not defined...\ng = eval(\"lambda { |y| _ = 40; x = 40;\\n (x + y)\\n}\")\n# =&gt; #&lt;Proc:0xb7cfe9c0@(eval):1&gt;\ng.call(2)\n# =&gt; 42\n\n# Changing x does not affect it.\nx = 7\ng.call(3)\n# =&gt; 43\n</code></pre>\n" }, { "answer_id": 6072624, "author": "Jonathan Tran", "author_id": 12887, "author_profile": "https://Stackoverflow.com/users/12887", "pm_score": 4, "selected": false, "text": "<p><strong>Use <a href=\"https://github.com/ngty/sourcify\" rel=\"nofollow noreferrer\">sourcify</a></strong></p>\n\n<p>This will work on Ruby 1.8 or 1.9.</p>\n\n<pre><code>def save_for_later(&amp;block)\n block.to_source\nend\n\nx = 40\ns = save_for_later {|y| x + y }\n# =&gt; \"proc { |y| (x + y) }\"\ng = eval(s)\n# =&gt; #&lt;Proc:0x00000100e88450@(eval):1&gt;\ng.call(2) \n# =&gt; 42\n</code></pre>\n\n<p>See <a href=\"https://stackoverflow.com/questions/199603/how-do-you-stringize-serialize-ruby-code/199803#199803\">my other answer</a> for capturing free variables.</p>\n\n<p><strong>Update</strong>:\nNow you can also use the <a href=\"https://github.com/ngty/serializable_proc\" rel=\"nofollow noreferrer\">serializable_proc</a> gem, which uses sourcify, and captures local, instance, class, and global variables.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12887/" ]
I want to be able to write a lambda/Proc in my Ruby code, serialize it so that I can write it to disk, and then execute the lambda later. Sort of like... ``` x = 40 f = lambda { |y| x + y } save_for_later(f) ``` Later, in a separate run of the Ruby interpreter, I want to be able to say... ``` f = load_from_before z = f.call(2) z.should == 42 ``` Marshal.dump does not work for Procs. I know Perl has [Data::Dump::Streamer](http://search.cpan.org/~yves/Data-Dump-Streamer-2.08-40/lib/Data/Dump/Streamer.pm), and in Lisp this is trivial. But is there a way to do it in Ruby? In other words, what would be the implementation of `save`_`for`_`later`? **Edit**: [My answer below](https://stackoverflow.com/questions/199603/how-do-you-stringize-serialize-ruby-code/199803#199803) is nice, but it does not close over free variables (like `x`) and serialize them along with the lambda. So in my example ... ``` x = 40 s = save_for_later { |y| x + y } # => "lambda { |y|\n (x + y)\n}" ``` ... the string output does not include a definition for `x`. Is there a solution that takes this into account, perhaps by serializing the symbol table? Can you access that in Ruby? **Edit 2**: I updated my answer to incorporate serializing local variables. This seems acceptable.
**Use Ruby2Ruby** ``` def save_for_later(&block) return nil unless block_given? c = Class.new c.class_eval do define_method :serializable, &block end s = Ruby2Ruby.translate(c, :serializable) s.sub(/^def \S+\(([^\)]*)\)/, 'lambda { |\1|').sub(/end$/, '}') end x = 40 s = save_for_later { |y| x + y } # => "lambda { |y|\n (x + y)\n}" g = eval(s) # => #<Proc:0x4037bb2c@(eval):1> g.call(2) # => 42 ``` This is great, but it does not close over free variables (like `x`) and serialize them along with the lambda. To [serialize variables](https://stackoverflow.com/questions/503583/how-do-you-access-the-symbol-table-in-ruby) also, you can iterate over `local_variables` and serialize them as well. The problem, though, is that `local_variables` from within `save_for_later` accesses only `c` and `s` in the code above -- i.e. variables local to the serialization code, not the caller. So unfortunately, we must push the grabbing of local variables and their values to the caller. Maybe this is a good thing, though, because in general, finding all free variables in a piece of Ruby code is [undecidable](http://en.wikipedia.org/wiki/Undecidable). Plus, ideally we would also save `global_variables` and any loaded classes and their overridden methods. This seems impractical. Using this simple approach, you get the following: ``` def save_for_later(local_vars, &block) return nil unless block_given? c = Class.new c.class_eval do define_method :serializable, &block end s = Ruby2Ruby.translate(c, :serializable) locals = local_vars.map { |var,val| "#{var} = #{val.inspect}; " }.join s.sub(/^def \S+\(([^\)]*)\)/, 'lambda { |\1| ' + locals).sub(/end$/, '}') end x = 40 s = save_for_later(local_variables.map{ |v| [v,eval(v)] }) { |y| x + y } # => "lambda { |y| _ = 40; x = 40;\n (x + y)\n}" # In a separate run of Ruby, where x is not defined... g = eval("lambda { |y| _ = 40; x = 40;\n (x + y)\n}") # => #<Proc:0xb7cfe9c0@(eval):1> g.call(2) # => 42 # Changing x does not affect it. x = 7 g.call(3) # => 43 ```
199,606
<p>C++ is mostly a superset of C, but not always. In particular, while enumeration values in both C and C++ implicitly convert into int, the reverse isn't true: only in C do ints convert back into enumeration values. Thus, bitflags defined via enumeration declarations don't work correctly. Hence, this is OK in C, but not in C++:</p> <pre><code>typedef enum Foo { Foo_First = 1&lt;&lt;0, Foo_Second = 1&lt;&lt;1, } Foo; int main(void) { Foo x = Foo_First | Foo_Second; // error in C++ return 0; } </code></pre> <p>How should this problem be handled efficiently and correctly, ideally without harming the debugger-friendly nature of using Foo as the variable type (it decomposes into the component bitflags in watches etc.)?</p> <p>Consider also that there may be hundreds of such flag enumerations, and many thousands of use-points. Ideally some kind of efficient operator overloading would do the trick, but it really ought to be efficient; the application I have in mind is compute-bound and has a reputation of being fast.</p> <p>Clarification: I'm translating a large (>300K) C program into C++, so I'm looking for an efficient translation in both run-time and developer-time. Simply inserting casts in all the appropriate locations could take weeks.</p>
[ { "answer_id": 199618, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 4, "selected": true, "text": "<p>Why not just cast the result back to a Foo?</p>\n\n<pre><code>Foo x = Foo(Foo_First | Foo_Second);\n</code></pre>\n\n<p>EDIT: I didn't understand the scope of your problem when I first answered this question. The above will work for doing a few spot fixes. For what you want to do, you will need to define a | operator that takes 2 Foo arguments and returns a Foo:</p>\n\n<pre><code>Foo operator|(Foo a, Foo b)\n{\n return Foo(int(a) | int(b));\n}\n</code></pre>\n\n<p>The int casts are there to prevent undesired recursion.</p>\n" }, { "answer_id": 199619, "author": "ejgottl", "author_id": 9808, "author_profile": "https://Stackoverflow.com/users/9808", "pm_score": 0, "selected": false, "text": "<p>Either leave the result as an int or static_cast:</p>\n\n<pre><code>Foo x = static_cast&lt;Foo&gt;(Foo_First | Foo_Second); // not an error in C++\n</code></pre>\n" }, { "answer_id": 199623, "author": "Mike G.", "author_id": 18901, "author_profile": "https://Stackoverflow.com/users/18901", "pm_score": 2, "selected": false, "text": "<p>It sounds like an ideal application for a cast - it's up to you to tell the compiler that yes, you DO mean to instantiate a Foo with a random integer.</p>\n\n<p>Of course, technically speaking, Foo_First | Foo_Second isn't a valid value for a Foo.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3712/" ]
C++ is mostly a superset of C, but not always. In particular, while enumeration values in both C and C++ implicitly convert into int, the reverse isn't true: only in C do ints convert back into enumeration values. Thus, bitflags defined via enumeration declarations don't work correctly. Hence, this is OK in C, but not in C++: ``` typedef enum Foo { Foo_First = 1<<0, Foo_Second = 1<<1, } Foo; int main(void) { Foo x = Foo_First | Foo_Second; // error in C++ return 0; } ``` How should this problem be handled efficiently and correctly, ideally without harming the debugger-friendly nature of using Foo as the variable type (it decomposes into the component bitflags in watches etc.)? Consider also that there may be hundreds of such flag enumerations, and many thousands of use-points. Ideally some kind of efficient operator overloading would do the trick, but it really ought to be efficient; the application I have in mind is compute-bound and has a reputation of being fast. Clarification: I'm translating a large (>300K) C program into C++, so I'm looking for an efficient translation in both run-time and developer-time. Simply inserting casts in all the appropriate locations could take weeks.
Why not just cast the result back to a Foo? ``` Foo x = Foo(Foo_First | Foo_Second); ``` EDIT: I didn't understand the scope of your problem when I first answered this question. The above will work for doing a few spot fixes. For what you want to do, you will need to define a | operator that takes 2 Foo arguments and returns a Foo: ``` Foo operator|(Foo a, Foo b) { return Foo(int(a) | int(b)); } ``` The int casts are there to prevent undesired recursion.
199,608
<p>How can I rotate a layer using Core Animation around an arbitrary point? ( In my case a point that is not inside the layer I want to rotate )</p> <p>I prefer doing this without changing the anchor point, because unless I get something wrong every time I change the anchor point it also changes the position of the layer.</p> <p>I tried something like that but it didn't work:</p> <pre><code>[UIImageView beginAnimations:nil context:nil]; CATransform3D rotationTransform = CATransform3DIdentity; rotationTransform = CATransform3DTranslate(rotationTransform, 0.0, -100.0, 0.0); rotationTransform = CATransform3DRotate(rotationTransform, DegreesToRadians(180), 0.0, 0.0, 1.0); rotationTransform = CATransform3DTranslate(rotationTransform, 0.0, 100.0, 0.0) shape1.layer.transform = rotationTransform; [UIImageView commitAnimations]; </code></pre> <p>It looks like the rotation axis is moving during the rotate.</p>
[ { "answer_id": 199877, "author": "lajos", "author_id": 3740, "author_profile": "https://Stackoverflow.com/users/3740", "pm_score": 2, "selected": false, "text": "<p>You can do this by appending multiple transformations:</p>\n\n<ol>\n<li>translate the layer by (-rotCenterX, rotCenterY)</li>\n<li>rotate the layer</li>\n<li>translate the layer by (rotCenterX, rotCenterY)</li>\n</ol>\n" }, { "answer_id": 219019, "author": "Gu1234", "author_id": 407138, "author_profile": "https://Stackoverflow.com/users/407138", "pm_score": 1, "selected": true, "text": "<p>I finaly did it by creating a new bigger layer with it's center at my rotation axis and setting the layer i want to rotate as it's sub layer.</p>\n\n<p>Then I rotate the bigger layer instead of the sub layer</p>\n" }, { "answer_id": 517553, "author": "Bill Dudney", "author_id": 50894, "author_profile": "https://Stackoverflow.com/users/50894", "pm_score": 2, "selected": false, "text": "<p>Your solution is fine but the 'expected way' is to use the anchor point.</p>\n\n<p>It is moving around when you set the anchor point because the position is attached to the anchor point, i.e. setting the position sets where the anchorPoint is in the superlayer's coord system.</p>\n\n<p>Probably not worth changing since you have something working, but just something to add to the grey matter for next time.</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 753481, "author": "Till", "author_id": 91282, "author_profile": "https://Stackoverflow.com/users/91282", "pm_score": 1, "selected": false, "text": "<p>Your initial solution is not fine as the translation is animated just like the rotation is. So the \"custom-center\" of your rotation is moving during the rotation. What you actually want is a translation without animation and the rotation with the animation based on that non-animated translation.\nThing is, I currently have the exact same problem and couldnt come up with a solution yet. I am looking at CATransaction at the moment, hoping that could be the key...</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/407138/" ]
How can I rotate a layer using Core Animation around an arbitrary point? ( In my case a point that is not inside the layer I want to rotate ) I prefer doing this without changing the anchor point, because unless I get something wrong every time I change the anchor point it also changes the position of the layer. I tried something like that but it didn't work: ``` [UIImageView beginAnimations:nil context:nil]; CATransform3D rotationTransform = CATransform3DIdentity; rotationTransform = CATransform3DTranslate(rotationTransform, 0.0, -100.0, 0.0); rotationTransform = CATransform3DRotate(rotationTransform, DegreesToRadians(180), 0.0, 0.0, 1.0); rotationTransform = CATransform3DTranslate(rotationTransform, 0.0, 100.0, 0.0) shape1.layer.transform = rotationTransform; [UIImageView commitAnimations]; ``` It looks like the rotation axis is moving during the rotate.
I finaly did it by creating a new bigger layer with it's center at my rotation axis and setting the layer i want to rotate as it's sub layer. Then I rotate the bigger layer instead of the sub layer
199,612
<p>So far I've figured out how to pass Unicode strings, bSTRs, to and from a Euphoria DLL using a Typelib. What I can't figure out, thus far, is how to create and pass back an array of BSTRs.</p> <p>The code I have thus far (along with <code>include</code>s for EuCOM itself and parts of Win32lib):</p> <pre><code>global function REALARR() sequence seq atom psa atom var seq = { "cat","cow","wolverine" } psa = create_safearray( seq, VT_BSTR ) make_variant( var, VT_ARRAY + VT_BSTR, psa ) return var end function </code></pre> <p>Part of the typelib is:</p> <pre><code> [ helpstring("get an array of strings"), entry("REALARR") ] void __stdcall REALARR( [out,retval] VARIANT* res ); </code></pre> <p>And the test code, in VB6 is:</p> <pre><code>... Dim v() as String V = REALARR() ... </code></pre> <p>So far all I've managed to get is an error '0' from the DLL. Any ideas? Anyone?</p>
[ { "answer_id": 211288, "author": "bugmagnet", "author_id": 426, "author_profile": "https://Stackoverflow.com/users/426", "pm_score": 0, "selected": false, "text": "<p>I've been in touch with the Euphoria people via their <a href=\"http://openeuphoria.org/EUforum/index.cgi?module=forum&amp;action=flat&amp;id=102589#unread\" rel=\"nofollow noreferrer\">forum</a>, and have gotten this far. The routine is failing on the the make_variant line. I haven't figured it out any further than that and neither have they.</p>\n\n<pre><code>global function REALARR() \n atom psa \n atom var \n atom bounds_ptr \n atom dim \n atom bstr \n object void \n\n dim = 1 \n bounds_ptr = allocate( 8 * dim ) -- now figure out which part is Extent and which is LBound \n poke4( bounds_ptr, { 3, 0 } ) -- assuming Extent and LBound in that order \n\n psa = c_func( SafeArrayCreate, { VT_BSTR, 1, bounds_ptr } ) \n\n bstr = alloc_bstr( \"cat\" ) \n poke4( bounds_ptr, 0 ) \n void = c_func( SafeArrayPutElement, {psa, bounds_ptr, bstr}) \n free_bstr( bstr ) \n\n bstr = alloc_bstr( \"cow\" ) \n poke4( bounds_ptr, 1 ) \n void = c_func( SafeArrayPutElement, {psa, bounds_ptr, bstr}) \n free_bstr( bstr ) \n\n bstr = alloc_bstr( \"wolverine\" ) \n poke4( bounds_ptr, 2 ) \n void = c_func( SafeArrayPutElement, {psa, bounds_ptr, bstr}) \n free_bstr( bstr ) \n\n make_variant( var, VT_ARRAY + VT_BSTR, psa ) \n return var \nend function \n</code></pre>\n" }, { "answer_id": 218867, "author": "bugmagnet", "author_id": 426, "author_profile": "https://Stackoverflow.com/users/426", "pm_score": 0, "selected": false, "text": "<p>Okay, <code>var</code> hasn't been initialised. Not that it matters as the routine still crashes. Nevertheless, one needs a</p>\n\n<pre><code>var = allocate( 16 )\n</code></pre>\n\n<p>just before the make_variant</p>\n" }, { "answer_id": 1675812, "author": "Matt Lewis", "author_id": 28987, "author_profile": "https://Stackoverflow.com/users/28987", "pm_score": 2, "selected": true, "text": "<p>You should use the <code>create_safearray()</code> function. It's documented (hidden?) under Utilities. Basically, put your BSTR pointers into a sequence and pass it to <code>create_safearray()</code>:</p>\n\n<pre><code>sequence s, bstrs\ns = {\"A\", \"B\"}\nbstrs = {}\nfor i = 1 to length(s) do\n bstrs &amp;= alloc_bstr( s[i] )\nend for\n\natom array\narray = create_safearray( bstrs, VT_BSTR )\n\n...\n\ndestroy_safearray( array )\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/426/" ]
So far I've figured out how to pass Unicode strings, bSTRs, to and from a Euphoria DLL using a Typelib. What I can't figure out, thus far, is how to create and pass back an array of BSTRs. The code I have thus far (along with `include`s for EuCOM itself and parts of Win32lib): ``` global function REALARR() sequence seq atom psa atom var seq = { "cat","cow","wolverine" } psa = create_safearray( seq, VT_BSTR ) make_variant( var, VT_ARRAY + VT_BSTR, psa ) return var end function ``` Part of the typelib is: ``` [ helpstring("get an array of strings"), entry("REALARR") ] void __stdcall REALARR( [out,retval] VARIANT* res ); ``` And the test code, in VB6 is: ``` ... Dim v() as String V = REALARR() ... ``` So far all I've managed to get is an error '0' from the DLL. Any ideas? Anyone?
You should use the `create_safearray()` function. It's documented (hidden?) under Utilities. Basically, put your BSTR pointers into a sequence and pass it to `create_safearray()`: ``` sequence s, bstrs s = {"A", "B"} bstrs = {} for i = 1 to length(s) do bstrs &= alloc_bstr( s[i] ) end for atom array array = create_safearray( bstrs, VT_BSTR ) ... destroy_safearray( array ) ```
199,629
<p>I am working with an existing code base made up of some COM interfaces written in C++ with a C# front end. There is some new functionality that needs to be added, so I'm having to modify the COM portions. In one particular case, I need to pass an array (allocated from C#) to the component to be filled.</p> <p>What I would like to do is to be able to pass an array of int to the method from C#, something like:</p> <pre><code>// desired C# signature void GetFoo(int bufferSize, int[] buffer); // desired usage int[] blah = ...; GetFoo(blah.Length, blah); </code></pre> <p>A couple of wrenches in the works:</p> <ul> <li>C++/CLI or Managed C++ can't be used (COM could be done away with in this case).</li> <li>The C# side can't be compiled with /unsafe (using Marshal is allowed).</li> </ul> <p>The COM interface is only used (an will only ever be used) by the C# part, so I'm less concerned with interoperability with other COM consumers. Portability between 32 and 64 bit is also not a concern (everything is being compiled and run from a 32 bit machine, so code generators are converting pointers to integers). Eventually, it will be replaced by just C++/CLI, but that is a ways off.</p> <hr /> <h2>My initial attempt</h2> <p>is something similar to:</p> <pre><code>HRESULT GetFoo([in] int bufferSize, [in, size_is(bufferSize)] int buffer[]); </code></pre> <p>And the output TLB definition is (seems reasonable):</p> <pre><code>HRESULT _stdcall GetFoo([in] int bufferSize, [in] int* buffer); </code></pre> <p>Which is imported by C# as (not so reasonable):</p> <pre><code>void GetFoo(int bufferSize, ref int buffer); </code></pre> <p>Which I <em>could</em> use with</p> <pre><code>int[] b = ...; fixed(int *bp = &amp;b[0]) { GetFoo(b.Length, ref *bp); } </code></pre> <p>...except that I can't compile with /unsafe.</p> <hr /> <h2>At the moment</h2> <p>I am using:</p> <pre><code>HRESULT GetFoo([in] int bufferSize, [in] INT_PTR buffer); </code></pre> <p>Which imports as:</p> <pre><code>void GetFoo(int bufferSize, int buffer); </code></pre> <p>And I need use use it like:</p> <pre><code>int[] b = ...; GCHandle bPin = GCHandle.Alloc(b, GCHandleType.Pinned); try { GetFoo(b.Length, (int)Marshal.UnsafeAddrOfPinnedArrayElement(b, 0)); } finally { bPin.Free(); } </code></pre> <p>Which works..., but I'd like to find a cleaner way.</p> <hr /> <h2>So, the question is</h2> <p>Is there an IDL definition that is friendly to the C# import from TLB generator for this case? If not, what can be done on the C# side to make it a little safer?</p>
[ { "answer_id": 199707, "author": "Gerald", "author_id": 19404, "author_profile": "https://Stackoverflow.com/users/19404", "pm_score": 0, "selected": false, "text": "<p>I don't know much about C# COM operability, but have you tried using SAFEARRAY(INT_PTR) or something similar?</p>\n" }, { "answer_id": 199767, "author": "Corey Ross", "author_id": 5927, "author_profile": "https://Stackoverflow.com/users/5927", "pm_score": 1, "selected": true, "text": "<p>Hmmm... I've found some information that gets me closer...</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ek1fb3c6.aspx#cpconeditingmicrosoftintermediatelanguagemsilanchor1\" rel=\"nofollow noreferrer\">Marshaling Changes - Conformant C-Style Arrays</a></p>\n\n<p>This IDL declaration (C++)</p>\n\n<pre><code>HRESULT GetFoo([in] int bufferSize, [in, size_is(bufferSize)] int buffer[]);\n</code></pre>\n\n<p>Is imported as (MSIL)</p>\n\n<pre><code>method public hidebysig newslot virtual instance void GetFoo([in] int32 bufferSize, [in] int32&amp; buffer) runtime managed internalcall\n</code></pre>\n\n<p>And if changed to (MSIL)</p>\n\n<pre><code>method public hidebysig newslot virtual instance void GetFoo([in] int32 bufferSize, [in] int32[] marshal([]) buffer) runtime managed internalcall\n</code></pre>\n\n<p>Can be used like (C#)</p>\n\n<pre><code>int[] b = ...;\nGetFoo(b.Length, b);\n</code></pre>\n\n<p>Exactly what I was gunning for!</p>\n\n<h2>But, are there any other solutions that don't require fixing up the MSIL of the runtime callable wrapper that is generated by tlbimport?</h2>\n" }, { "answer_id": 201749, "author": "Tony Lee", "author_id": 5819, "author_profile": "https://Stackoverflow.com/users/5819", "pm_score": 1, "selected": false, "text": "<p>So you're asking for an IDL datatype that is 32-bits on a 32-bit machine and 64-bits on a 64-bit machine. But you don't want the marshaling code to treat it like a pointer, just as an int. So what do you expect to happen to the extra 32-bits when you call from a 64-bit process to a 32-bit process?</p>\n\n<p>Sound like a violation of physics to me.</p>\n\n<p>If it's inproc only, see the bottom of this discussion: <a href=\"http://www.techtalkz.com/vc-net/125190-how-interop-net-client-com-dll.html\" rel=\"nofollow noreferrer\">http://www.techtalkz.com/vc-net/125190-how-interop-net-client-com-dll.html</a>.</p>\n\n<p>The recommendation seems to be to use void * instead of intptr and flag with the [local] so the marshaller doesn't get involved.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5927/" ]
I am working with an existing code base made up of some COM interfaces written in C++ with a C# front end. There is some new functionality that needs to be added, so I'm having to modify the COM portions. In one particular case, I need to pass an array (allocated from C#) to the component to be filled. What I would like to do is to be able to pass an array of int to the method from C#, something like: ``` // desired C# signature void GetFoo(int bufferSize, int[] buffer); // desired usage int[] blah = ...; GetFoo(blah.Length, blah); ``` A couple of wrenches in the works: * C++/CLI or Managed C++ can't be used (COM could be done away with in this case). * The C# side can't be compiled with /unsafe (using Marshal is allowed). The COM interface is only used (an will only ever be used) by the C# part, so I'm less concerned with interoperability with other COM consumers. Portability between 32 and 64 bit is also not a concern (everything is being compiled and run from a 32 bit machine, so code generators are converting pointers to integers). Eventually, it will be replaced by just C++/CLI, but that is a ways off. --- My initial attempt ------------------ is something similar to: ``` HRESULT GetFoo([in] int bufferSize, [in, size_is(bufferSize)] int buffer[]); ``` And the output TLB definition is (seems reasonable): ``` HRESULT _stdcall GetFoo([in] int bufferSize, [in] int* buffer); ``` Which is imported by C# as (not so reasonable): ``` void GetFoo(int bufferSize, ref int buffer); ``` Which I *could* use with ``` int[] b = ...; fixed(int *bp = &b[0]) { GetFoo(b.Length, ref *bp); } ``` ...except that I can't compile with /unsafe. --- At the moment ------------- I am using: ``` HRESULT GetFoo([in] int bufferSize, [in] INT_PTR buffer); ``` Which imports as: ``` void GetFoo(int bufferSize, int buffer); ``` And I need use use it like: ``` int[] b = ...; GCHandle bPin = GCHandle.Alloc(b, GCHandleType.Pinned); try { GetFoo(b.Length, (int)Marshal.UnsafeAddrOfPinnedArrayElement(b, 0)); } finally { bPin.Free(); } ``` Which works..., but I'd like to find a cleaner way. --- So, the question is ------------------- Is there an IDL definition that is friendly to the C# import from TLB generator for this case? If not, what can be done on the C# side to make it a little safer?
Hmmm... I've found some information that gets me closer... [Marshaling Changes - Conformant C-Style Arrays](http://msdn.microsoft.com/en-us/library/ek1fb3c6.aspx#cpconeditingmicrosoftintermediatelanguagemsilanchor1) This IDL declaration (C++) ``` HRESULT GetFoo([in] int bufferSize, [in, size_is(bufferSize)] int buffer[]); ``` Is imported as (MSIL) ``` method public hidebysig newslot virtual instance void GetFoo([in] int32 bufferSize, [in] int32& buffer) runtime managed internalcall ``` And if changed to (MSIL) ``` method public hidebysig newslot virtual instance void GetFoo([in] int32 bufferSize, [in] int32[] marshal([]) buffer) runtime managed internalcall ``` Can be used like (C#) ``` int[] b = ...; GetFoo(b.Length, b); ``` Exactly what I was gunning for! But, are there any other solutions that don't require fixing up the MSIL of the runtime callable wrapper that is generated by tlbimport? ----------------------------------------------------------------------------------------------------------------------------------------
199,642
<p>I have a combo box on a WinForms app in which an item may be selected, but it is not mandatory. I therefore need an 'Empty' first item to indicate that no value has been set.</p> <p>The combo box is bound to a DataTable being returned from a stored procedure (I offer no apologies for Hungarian notation on my UI controls :p ):</p> <pre><code> DataTable hierarchies = _database.GetAvailableHierarchies(cmbDataDefinition.SelectedValue.ToString()).Copy();//Calls SP cmbHierarchies.DataSource = hierarchies; cmbHierarchies.ValueMember = "guid"; cmbHierarchies.DisplayMember = "ObjectLogicalName"; </code></pre> <p>How can I insert such an empty item?</p> <p>I do have access to change the SP, but I would really prefer not to 'pollute' it with UI logic.</p> <p><strong>Update:</strong> It was the DataTable.NewRow() that I had blanked on, thanks. I have upmodded you all (all 3 answers so far anyway). I am trying to get the Iterator pattern working before I decide on an 'answer'</p> <p><strong>Update:</strong> I think this edit puts me in Community Wiki land, I have decided not to specify a single answer, as they all have merit in context of their domains. Thanks for your collective input.</p>
[ { "answer_id": 199669, "author": "Mark", "author_id": 26310, "author_profile": "https://Stackoverflow.com/users/26310", "pm_score": 2, "selected": false, "text": "<p>Cant you add a new DataRow to the DataTable before you bind it to your DataSource?</p>\n<p>You can use the NewRow function of the DataTable to achieve this:</p>\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.data.datatable.newrow.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.data.datatable.newrow.aspx</a></p>\n" }, { "answer_id": 199671, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 2, "selected": false, "text": "<p>insert a blank row in your datatable, and check for it in validation/update/create</p>\n" }, { "answer_id": 199695, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 3, "selected": false, "text": "<p>I usually create an iterator for this type of thing. It avoids polluting your data, and works well with data-binding:</p>\n\n<pre><code>DataTable hierarchies = _database.GetAvailableHierarchies(cmbDataDefinition.SelectedValue.ToString()).Copy();//Calls SP\ncmbHierarchies.DataSource = GetDisplayTable(hierarchies);\ncmbHierarchies.ValueMember = \"guid\";\ncmbHierarchies.DisplayMember = \"ObjectLogicalName\";\n\n...\n\nprivate IEnumerable GetDisplayTable(DataTable tbl)\n{\n yield return new { ObjectLogicalName = string.Empty, guid = Guid.Empty };\n\n foreach (DataRow row in tbl.Rows)\n yield return new { ObjectLogicalName = row[\"ObjectLogicalName\"].ToString(), guid = (Guid)row[\"guid\"] };\n}\n</code></pre>\n\n<p>Disclaimer: I have not compiled this code, but have used this pattern many times.</p>\n\n<p><strong>Note:</strong> I have been in WPF and ASP.Net land for the last couple of years. Apparently the Winforms combo box wants an IList, not an IEnumerable. A more costly operation would be to create a list. This code is really stream-of-conciseness and I really, really have not compiled it:</p>\n\n<pre><code>DataTable hierarchies = _database.GetAvailableHierarchies(cmbDataDefinition.SelectedValue.ToString()).Copy();\nList&lt;KeyValuePair&lt;string, Guid&gt;&gt; list = new List&lt;KeyValuePair&lt;string, Guid&gt;&gt;(hierarchies.Rows.Cast&lt;DataRow&gt;().Select(row =&gt; new KeyValuePair&lt;string, Guid&gt;(row[\"Name\"].ToString(), (Guid)row[\"Guid\"])));\nlist.Insert(0, new KeyValuePair&lt;string,Guid&gt;(string.Empty, Guid.Empty));\ncmbHierarchies.DataSource = list;\ncmbHierarchies.ValueMember = \"Value\";\ncmbHierarchies.DisplayMember = \"Key\";\n</code></pre>\n" }, { "answer_id": 199715, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 6, "selected": true, "text": "<p>There are two things you can do:</p>\n\n<ol>\n<li><p>Add an empty row to the <code>DataTable</code> that is returned from the stored procedure.</p>\n\n<pre><code>DataRow emptyRow = hierarchies.NewRow();\nemptyRow[\"guid\"] = \"\";\nemptyRow[\"ObjectLogicalName\"] = \"\";\nhierarchies.Rows.Add(emptyRow);\n</code></pre>\n\n<p>Create a DataView and sort it using ObjectLogicalName column. This will make the newly added row the first row in DataView.</p>\n\n<pre><code>DataView newView = \n new DataView(hierarchies, // source table\n \"\", // filter\n \"ObjectLogicalName\", // sort by column\n DataViewRowState.CurrentRows); // rows with state to display\n</code></pre>\n\n<p>Then set the dataview as <code>DataSource</code> of the <code>ComboBox</code>.</p></li>\n<li><p>If you really don't want to add a new row as mentioned above. You can allow the user to set the <code>ComboBox</code> value to null by simply handling the \"Delete\" keypress event. When a user presses Delete key, set the <code>SelectedIndex</code> to -1. You should also set <code>ComboBox.DropDownStyle</code> to <code>DropDownList</code>. As this will prevent user to edit the values in the <code>ComboBox</code>.</p></li>\n</ol>\n" }, { "answer_id": 199734, "author": "flipdoubt", "author_id": 470, "author_profile": "https://Stackoverflow.com/users/470", "pm_score": 0, "selected": false, "text": "<p>Er, can't you just add a default item to the ComboBox after data binding?</p>\n" }, { "answer_id": 200433, "author": "Arry", "author_id": 26792, "author_profile": "https://Stackoverflow.com/users/26792", "pm_score": 0, "selected": false, "text": "<p>I would bind the data then insert an blank item at position 0 using the ComboxBox.Items.Insert method. Similar to what flipdoubt suggested, but it adds the item to the top.</p>\n" }, { "answer_id": 796705, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code>cmbHierarchies.SelectedIndex = -1;\n</code></pre>\n" }, { "answer_id": 3986674, "author": "Vincent De Smet", "author_id": 138469, "author_profile": "https://Stackoverflow.com/users/138469", "pm_score": 1, "selected": false, "text": "<p>I wrote this method based on the suggestions here by Jason Jackson: </p>\n\n<pre><code>private IEnumerable&lt;KeyValuePair&lt;object,object&gt;&gt; GetDisplayTable(DataTable dataTable, DataColumn ValueMember, string sep,params DataColumn[] DisplayMembers)\n{\n yield return new KeyValuePair&lt;object,object&gt;(\"&lt;ALL&gt;\",null);\n\n if (DisplayMembers.Length &lt; 1)\n throw new ArgumentException(\"At least 1 DisplayMember column is required\");\n\n foreach (DataRow r in dataTable.Rows)\n {\n StringBuilder sbDisplayMember = new StringBuilder();\n foreach(DataColumn col in DisplayMembers)\n {\n if (sbDisplayMember.Length &gt; 0) sbDisplayMember.Append(sep);\n sbDisplayMember.Append(r[col]);\n }\n yield return new KeyValuePair&lt;object, object&gt;(sbDisplayMember.ToString(), r[ValueMember]);\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>bindingSource1.DataSource = GetDisplayTable(\n /*DataTable*/typedDataTable, \n /*ValueMember*/typedDataTable.IDColumn, \n /*DisplayColumn Seperator*/\" - \",\n /*List of Display Columns*/\n typedDataTable.DB_CODEColumn,\n typedDataTable.DB_NAMEColumn);\n\ncomboBox1.DataSource = bindingSource1;\ncomboBox1.DisplayMember = \"Key\";\ncomboBox1.ValueMember = \"Value\";\n\n//another example without multiple display data columns:\nbindingSource2.DataSource = GetDisplayTable(\n /*DataTable*/typedDataTable, \n /*ValueMember*/typedDataTable.IDColumn, \n /*DisplayColumn Seperator*/null,\n /*List of Display Columns*/\n typedDataTable.DESCColumn );\n</code></pre>\n\n<p>further down, where the Selected Value is consumed:</p>\n\n<pre><code>if (comboBox1.SelectedValue != null)\n // Do Something with SelectedValue \nelse \n // All was selected (all is my 'empty')\n</code></pre>\n\n<p>This will allow to display several columns concatenated in the ComboBox, while keeping the Value member to the single identifier + it uses the iterator block with the BindingSource, BindingSource might be overkill for your situation.</p>\n\n<p>Сomments and suggestions are welcome.</p>\n" }, { "answer_id": 6292182, "author": "Ray", "author_id": 579788, "author_profile": "https://Stackoverflow.com/users/579788", "pm_score": 2, "selected": false, "text": "<p>I found another solution:</p>\n\n<p>Just after your data table is created (before using fill), add new row and use AcceptChanges method to the table. The new record would get RowState = Unchanged, and would not be added to database, but would be visible in your datatable and combobox.</p>\n\n<pre><code> DataTable dt = new DataTable();\n dt.Rows.Add();\n dt.AcceptChanges();\n ...\n dt.Fill(\"your query\");\n</code></pre>\n" }, { "answer_id": 11237746, "author": "Trevor", "author_id": 1487411, "author_profile": "https://Stackoverflow.com/users/1487411", "pm_score": 0, "selected": false, "text": "<p>I had a similar challenge. As part of the form load event I set the SelectedIndex of the control to -1 </p>\n\n<p>ie</p>\n\n<pre><code>private void Form1_Load(object sender, EventArgs e)\n{ \n this.TableAdapter.Fill(this.dsListOfCampaigns.EvolveCampaignTargetListMasterInfo);\n this.comboCampaignID.SelectedIndex = -1;\n}\n</code></pre>\n\n<p>Effectively, the combo box is populated and the first item is selected. Then the item is unselected. May not be a viable solution for all cases.</p>\n" }, { "answer_id": 15813287, "author": "Sujith Radhakrishnan", "author_id": 1788322, "author_profile": "https://Stackoverflow.com/users/1788322", "pm_score": 0, "selected": false, "text": "<p><code>\n this.recieptDateTimePicker.SelectedIndex = -1;\n</code>this.dateCompoBox.SelectedIndex = -1;</p>\n" }, { "answer_id": 18127379, "author": "Zen", "author_id": 2637667, "author_profile": "https://Stackoverflow.com/users/2637667", "pm_score": 0, "selected": false, "text": "<p>I have found this way:</p>\n\n<pre><code> DataTable hierarchies = new DataTable(); \n\n cmbHierarchies.BeginUpdate();\n cmbHierarchies.ValueMember = this.Value;\n cmbHierarchies.DisplayMember = this.Display;\n hierarchies = DataView.ToTable();\n cmbHierarchies.DataSource = table;\n cmbHierarchies.EndUpdate();\n\n //Add empty row\n DataRow row = table.NewRow();\n table.Rows.InsertAt(row, 0);\n cmbHierarchies.SelectedIndex = 0;\n</code></pre>\n" }, { "answer_id": 26455969, "author": "joshman1019", "author_id": 3602084, "author_profile": "https://Stackoverflow.com/users/3602084", "pm_score": 0, "selected": false, "text": "<p>Instead of adding a new row to your datatable, just bind the data to the combobox and at load set the SelectedIndex to -1. This will cause the selection to be null until the user selects an item. </p>\n\n<p>I clipped this from one of my current projects. </p>\n\n<pre><code> Attorney_List_CB.DataSource = DA_Attorney_List.BS.DataSource;\n Attorney_List_CB.DisplayMember = \"Attorney Name\";\n Attorney_List_CB.SelectedIndex = -1; \n</code></pre>\n\n<p>In order to clear the selection I usually insert a button that sets the SelectedIndex back to -1. </p>\n\n<pre><code> private void Clear_Selection_BTN_Click(object sender, EventArgs e)\n {\n Attorney_List_CB.SelectedIndex = -1; // Clears user selection\n }\n</code></pre>\n\n<p>Finally, once I validate the data on my form, if the SelectedIndex of any combobox is -1 then it is skipped, or I will generate some type of default value such as \"N/A\" or whatever I need under the circumstances. </p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5302/" ]
I have a combo box on a WinForms app in which an item may be selected, but it is not mandatory. I therefore need an 'Empty' first item to indicate that no value has been set. The combo box is bound to a DataTable being returned from a stored procedure (I offer no apologies for Hungarian notation on my UI controls :p ): ``` DataTable hierarchies = _database.GetAvailableHierarchies(cmbDataDefinition.SelectedValue.ToString()).Copy();//Calls SP cmbHierarchies.DataSource = hierarchies; cmbHierarchies.ValueMember = "guid"; cmbHierarchies.DisplayMember = "ObjectLogicalName"; ``` How can I insert such an empty item? I do have access to change the SP, but I would really prefer not to 'pollute' it with UI logic. **Update:** It was the DataTable.NewRow() that I had blanked on, thanks. I have upmodded you all (all 3 answers so far anyway). I am trying to get the Iterator pattern working before I decide on an 'answer' **Update:** I think this edit puts me in Community Wiki land, I have decided not to specify a single answer, as they all have merit in context of their domains. Thanks for your collective input.
There are two things you can do: 1. Add an empty row to the `DataTable` that is returned from the stored procedure. ``` DataRow emptyRow = hierarchies.NewRow(); emptyRow["guid"] = ""; emptyRow["ObjectLogicalName"] = ""; hierarchies.Rows.Add(emptyRow); ``` Create a DataView and sort it using ObjectLogicalName column. This will make the newly added row the first row in DataView. ``` DataView newView = new DataView(hierarchies, // source table "", // filter "ObjectLogicalName", // sort by column DataViewRowState.CurrentRows); // rows with state to display ``` Then set the dataview as `DataSource` of the `ComboBox`. 2. If you really don't want to add a new row as mentioned above. You can allow the user to set the `ComboBox` value to null by simply handling the "Delete" keypress event. When a user presses Delete key, set the `SelectedIndex` to -1. You should also set `ComboBox.DropDownStyle` to `DropDownList`. As this will prevent user to edit the values in the `ComboBox`.
199,651
<p>I'm looking for a generic "Row Picker" for JQuery.</p> <p>We've all seen the cool "Picker" tools like date pickers, color pickers, time pickers, etc, where you click in a text box and a little calendar or color palate or clock or something comes up. You select something (like a date) and the text box is then populated with a value.</p> <p>I really need an all-purpose "row picker" where you can populate something (a table, divs, etc) with some rows of data (say a list of timezones). This would be linked to a text field and would pop up when the user clicks in the field.</p> <p>They would click a row (say a timezone), and the timezone id would be passed back to the field.</p> <p>Anyone know of anything that does this? </p> <p>Thanks!</p>
[ { "answer_id": 199710, "author": "Duncan", "author_id": 25035, "author_profile": "https://Stackoverflow.com/users/25035", "pm_score": 3, "selected": true, "text": "<p>I don't know about totally generic though you can certainly achieve a row selector fairly easily in jQuery. </p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt; $(function() {\n $('table#data_table tr').click(function() {\n alert($(this).find('td.id').html());\n }); }); \n&lt;/script&gt;\n\n\n&lt;table border=\"0\" id=\"data_table\"&gt;\n&lt;tr&gt;\n&lt;td class=\"id\"&gt;45&lt;/td&gt;&lt;td&gt;GMT&lt;/td&gt;\n&lt;/tr&gt;\n&lt;tr&gt;\n&lt;td class=\"id\"&gt;47&lt;/td&gt;&lt;td&gt;CST&lt;/td&gt;\n&lt;/tr&gt;\n&lt;/table&gt;\n</code></pre>\n\n<p>This adds a click to each row, finds the tagged id within the row which would then allow you to do something with it. Obviously you would need to target this to your data table and filter based on the contents. JQuery can then be used to populate the result of the click into the target field. You can then come up with some convention where all your data tables work the same which would allow you to generalise this into a generic picker for your application.</p>\n" }, { "answer_id": 200368, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": 2, "selected": false, "text": "<p>In this scenario it is better to use event delegation. So put the event handler onto the table itself, this avoids having to bind a handler for each row which is quite expensive if you have a good few rows. You can then use the event.target to query which element was responsible for the event and go from there.</p>\n\n<p>More info <a href=\"http://www.danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>E.g</p>\n\n<pre><code>$('#someTable').click(function(e) {\n var target = $(e.target);\n\n});\n</code></pre>\n" }, { "answer_id": 2704710, "author": "Andrew M. Andrews III", "author_id": 210158, "author_profile": "https://Stackoverflow.com/users/210158", "pm_score": 1, "selected": false, "text": "<p>This isn't exactly what you <strong>asked</strong> for, but it may be what you're <strong>looking</strong> for: The <a href=\"http://www.ama3.com/anytime/\" rel=\"nofollow noreferrer\">Any+Time(TM) Datepicker/Timepicker AJAX Widget with Time Zone Support</a> can display a list of timezones right in a time picker, making it easy for the user to select the appropriate timezone. It is also easy to customize, and allows faster selection than most other time pickers that use drop downs or sliders. I hope this helps!</p>\n" }, { "answer_id": 2704734, "author": "Matchu", "author_id": 107415, "author_profile": "https://Stackoverflow.com/users/107415", "pm_score": 0, "selected": false, "text": "<p>I know I'm a year late, and that I'm probably missing something here, but what's wrong with the <code>select</code> element with the <code>size</code> attribute?</p>\n\n<pre><code>&lt;select name=\"test\" size=\"5\"&gt;\n &lt;option value=\"1\"&gt;One&lt;/option&gt;\n &lt;option value=\"2\"&gt;Two&lt;/option&gt;\n &lt;option value=\"3\"&gt;Three&lt;/option&gt;\n &lt;option value=\"4\"&gt;Four&lt;/option&gt;\n &lt;option value=\"5\"&gt;Five&lt;/option&gt;\n&lt;/select&gt;\n</code></pre>\n\n<p>This will show all 5 options, and allow the user to select one. It also has absolutely no Javascript dependency if just used in a standard form, but also can handle typical Javascript events well, and also seems to produce the exact appearance that you wanted - not to mention that, as always, you can use CSS to style it as you like.</p>\n\n<p>When standard HTML will work, I say: Use standard HTML.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27580/" ]
I'm looking for a generic "Row Picker" for JQuery. We've all seen the cool "Picker" tools like date pickers, color pickers, time pickers, etc, where you click in a text box and a little calendar or color palate or clock or something comes up. You select something (like a date) and the text box is then populated with a value. I really need an all-purpose "row picker" where you can populate something (a table, divs, etc) with some rows of data (say a list of timezones). This would be linked to a text field and would pop up when the user clicks in the field. They would click a row (say a timezone), and the timezone id would be passed back to the field. Anyone know of anything that does this? Thanks!
I don't know about totally generic though you can certainly achieve a row selector fairly easily in jQuery. ``` <script type="text/javascript"> $(function() { $('table#data_table tr').click(function() { alert($(this).find('td.id').html()); }); }); </script> <table border="0" id="data_table"> <tr> <td class="id">45</td><td>GMT</td> </tr> <tr> <td class="id">47</td><td>CST</td> </tr> </table> ``` This adds a click to each row, finds the tagged id within the row which would then allow you to do something with it. Obviously you would need to target this to your data table and filter based on the contents. JQuery can then be used to populate the result of the click into the target field. You can then come up with some convention where all your data tables work the same which would allow you to generalise this into a generic picker for your application.
199,665
<p>I have a SOAP client in Ruby that I'm trying to get working with a Ruby SOAP server, to no avail. The client works fine over SSL with a Python SOAP server, but not with the Ruby version. Here's what the server looks like:</p> <pre><code>require 'soap/rpc/standaloneServer' require 'soap/rpc/driver' require 'rubygems' require 'httpclient' def cert(filename) OpenSSL::X509::Certificate.new(File.open("path to cert.cert") { |f| f.read }) end def key(filename) OpenSSL::PKey::RSA.new(File.open("path to rsaprivate.key") { |f| f.read }) end class Server &lt; SOAP::RPC::HTTPServer ~code snipped for readability~ end server = Server.new(:BindAddress =&gt; HelperFunctions.local_ip, :Port =&gt; 1234, :SSLCertificate =&gt; cert("path to cert"), :SSLPrivateKey =&gt; key("path to rsa private key")) new_thread = Thread.new { server.start } </code></pre> <p>I've trimmed some of the code out for readability's sake (e.g., I have some methods in there I expose) and it works fine with SSL off. But when the client tries to connect, it sees this:</p> <pre><code>warning: peer certificate won't be verified in this SSL session /usr/lib/ruby/1.8/net/http.rb:567: warning: using default DH parameters. /usr/lib/ruby/1.8/net/http.rb:586:in `connect': unknown protocol (OpenSSL::SSL::SSLError) </code></pre> <p>I tried taking some advice from <a href="https://stackoverflow.com/questions/128660/how-can-i-make-rubys-soaprpcdriver-work-with-self-signed-certificates">this post</a> and now I see this message:</p> <pre><code>/usr/lib/ruby/1.8/soap/httpconfigloader.rb:64:in `set_ssl_config': SSL not supported (NotImplementedError) </code></pre> <p>Any ideas on how to fix this would be greatly appreciated.</p>
[ { "answer_id": 199817, "author": "Chris Bunch", "author_id": 422, "author_profile": "https://Stackoverflow.com/users/422", "pm_score": 3, "selected": true, "text": "<p>Arg. I was trying to follow along <a href=\"http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/108292\" rel=\"nofollow noreferrer\">this link</a> and it turns out I was missing a simple include statement:</p>\n\n<pre><code>require 'webrick/https'\n</code></pre>\n\n<p>That, combined with the help from the link in the original question solves the problem. Hopefully this saves someone else down the line an hour of grief :)</p>\n" }, { "answer_id": 765311, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Me too.. and don't forget to put the :SSLEnable => true spend couple of hours figuring that out...</p>\n\n<pre><code>server = Server.new(:BindAddress =&gt; HelperFunctions.local_ip, :Port =&gt; 1234, :SSLEnable =&gt; true, :SSLCertificate =&gt; cert(\"path to cert\"), :SSLPrivateKey =&gt; key(\"path to rsa private key\"))\n</code></pre>\n" }, { "answer_id": 770737, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>\"SSL not supported\" can be caused by not having httpclient installed.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/422/" ]
I have a SOAP client in Ruby that I'm trying to get working with a Ruby SOAP server, to no avail. The client works fine over SSL with a Python SOAP server, but not with the Ruby version. Here's what the server looks like: ``` require 'soap/rpc/standaloneServer' require 'soap/rpc/driver' require 'rubygems' require 'httpclient' def cert(filename) OpenSSL::X509::Certificate.new(File.open("path to cert.cert") { |f| f.read }) end def key(filename) OpenSSL::PKey::RSA.new(File.open("path to rsaprivate.key") { |f| f.read }) end class Server < SOAP::RPC::HTTPServer ~code snipped for readability~ end server = Server.new(:BindAddress => HelperFunctions.local_ip, :Port => 1234, :SSLCertificate => cert("path to cert"), :SSLPrivateKey => key("path to rsa private key")) new_thread = Thread.new { server.start } ``` I've trimmed some of the code out for readability's sake (e.g., I have some methods in there I expose) and it works fine with SSL off. But when the client tries to connect, it sees this: ``` warning: peer certificate won't be verified in this SSL session /usr/lib/ruby/1.8/net/http.rb:567: warning: using default DH parameters. /usr/lib/ruby/1.8/net/http.rb:586:in `connect': unknown protocol (OpenSSL::SSL::SSLError) ``` I tried taking some advice from [this post](https://stackoverflow.com/questions/128660/how-can-i-make-rubys-soaprpcdriver-work-with-self-signed-certificates) and now I see this message: ``` /usr/lib/ruby/1.8/soap/httpconfigloader.rb:64:in `set_ssl_config': SSL not supported (NotImplementedError) ``` Any ideas on how to fix this would be greatly appreciated.
Arg. I was trying to follow along [this link](http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/108292) and it turns out I was missing a simple include statement: ``` require 'webrick/https' ``` That, combined with the help from the link in the original question solves the problem. Hopefully this saves someone else down the line an hour of grief :)
199,692
<p>I have only a basic knowledge of css, is it possible to inherit a property from one style into another style. So for instance I could inherit the font size specified in my default paragrah tag settings into my hyperlink tags.</p> <p>The reason I want to do this is to make it easier to maintain multiple styles.</p>
[ { "answer_id": 199714, "author": "leek", "author_id": 3765, "author_profile": "https://Stackoverflow.com/users/3765", "pm_score": 4, "selected": true, "text": "<p>You can define common styles for two elements at once like so:</p>\n\n<pre><code>p, a {\n font-size: 1em;\n}\n</code></pre>\n\n<p>And then extend each one with their individual properties as you want:</p>\n\n<pre><code>p {\n color: red;\n}\n\na {\n font-weight: bold;\n}\n</code></pre>\n\n<p><strong>Keep in mind:</strong> Styles defined later in a style sheet generally override properties defined earlier.</p>\n\n<p><strong>Extra:</strong> If you haven't already, I recommend getting the <a href=\"http://walmart.ca/wps-portal/storelocator/Canada-HealthAndBeauty.jsp?selection=listingDetails&amp;page=hb&amp;lang=null&amp;assetId=11727&amp;imageId=39727&amp;suggestedItem=&amp;priceType=1&amp;page=null&amp;departmentId=14&amp;categoryId=193#\" rel=\"noreferrer\">Firebug</a> Firefox extension so you can see what styles the elements on your page are receiving and where they are inherited from.</p>\n" }, { "answer_id": 199719, "author": "timmfin", "author_id": 27488, "author_profile": "https://Stackoverflow.com/users/27488", "pm_score": 2, "selected": false, "text": "<p>No CSS doesn't have any way to inherit styles. But there are several ways you can share styles. Here are a few examples:</p>\n\n<p><strong>Using multiple classes</strong> </p>\n\n<pre><code>&lt;p class=\"first all\"&gt;Some text&lt;/p&gt;\n&lt;p class=\"all\"&gt;More text&lt;/p&gt;\n&lt;p class=\"last all\"&gt;Yet more text&lt;/p&gt;\n\np.all { font-weight: bold }\np.first { color: red; }\np.last { color: blue; }\n</code></pre>\n\n<p><strong>Use the comma operator in your styles</strong> </p>\n\n<pre><code>&lt;p class=\"first\"&gt;Some text&lt;/p&gt;\n&lt;p class=\"middle\"&gt;More text&lt;/p&gt;\n&lt;p class=\"last\"&gt;Yet more text&lt;/p&gt;\n\np.first, p.middle, p.last { font-weight: bold }\np.first { color: red; }\np.last { color: blue; }\n</code></pre>\n\n<p><strong>Using container elements</strong> </p>\n\n<pre><code>&lt;div class=\"container\"&gt;\n &lt;p class=\"first\"&gt;Some text&lt;/p&gt;\n &lt;p class=\"middle\"&gt;More text&lt;/p&gt;\n &lt;p class=\"last\"&gt;Yet more text&lt;/p&gt;\n&lt;/div&gt;\n\ndiv p { font-weight: bold }\np.first { color: red; }\np.last { color: blue; }\n</code></pre>\n\n<p>None of these are exactly what you are looking for, but using these techniques will help you keep CSS duplication to a minimum.</p>\n\n<p>If you are willing to use server side code to preprocess your CSS, you can get the type of CSS inheritance you are looking for.</p>\n\n<ul>\n<li><a href=\"http://wiki.framwurk.org/documents:csspp/\" rel=\"nofollow noreferrer\">http://wiki.framwurk.org/documents:csspp/</a></li>\n<li><a href=\"http://mail.python.org/pipermail/python-list/2006-August/397266.html\" rel=\"nofollow noreferrer\">http://mail.python.org/pipermail/python-list/2006-August/397266.html</a></li>\n<li><a href=\"http://www.shauninman.com/archive/2008/05/30/check_out_css_cacheer\" rel=\"nofollow noreferrer\">http://www.shauninman.com/archive/2008/05/30/check_out_css_cacheer</a></li>\n</ul>\n" }, { "answer_id": 199722, "author": "Jonathan Arkell", "author_id": 11052, "author_profile": "https://Stackoverflow.com/users/11052", "pm_score": 1, "selected": false, "text": "<p>Yes.</p>\n\n<p>You should understand how the cascade in CSS works, and also understand how inheritance works. Some styles will inherit (like the font face) and some styles wont (like the border). However, you can also tell styles to inherit from their parent elements inside the DOM.</p>\n\n<p>Of some help here is knowledge of how style rules are specified. <a href=\"http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html\" rel=\"nofollow noreferrer\" title=\"CSS Specificity Wars\">This site about the CSS Specifity Wars</a> might help (Note: this site is currently down, but hopefully it will be back soon).</p>\n\n<p>Additionally, I find it sometimes helps to overload styles like this:</p>\n\n<pre><code>h1, h2, h3, h4, h5 h6 { font-weight: normal; border: 1px solid #ff0; }\nh1 { font-size: 300%; }\n... etc ...\n</code></pre>\n" }, { "answer_id": 199724, "author": "Joe Basirico", "author_id": 20795, "author_profile": "https://Stackoverflow.com/users/20795", "pm_score": 0, "selected": false, "text": "<p>CSS will automatically inherit from the parent style. For example, if you say in your body style that all text should be <code>#EEE</code> and your background should be <code>#000</code> then all text, whether it’s in a div or a span will always be <code>#EEE</code>. </p>\n\n<p>There has been quite a bit of talk about adding inheritance the way you describe in CSS3, but that spec isn’t out yet, so right now we’re stuck repeating ourselves quite a bit.</p>\n" }, { "answer_id": 201585, "author": "Traingamer", "author_id": 27609, "author_profile": "https://Stackoverflow.com/users/27609", "pm_score": 0, "selected": false, "text": "<p>\"...is it possible to inherit a property from one style into another style. So for instance I could inherit the font size specified in my default paragrah tag settings into my hyperlink tags.\"</p>\n\n<p>The link tags will automatically use the fonts from the paragraph, if, and only if, they are <strong>within</strong> a paragraph. If they are outside of a paragraph (say in a list) they will not use the same font, etc. </p>\n\n<p>For instance this css: </p>\n\n<pre><code>* {\nmargin: 0 10px;\npadding:0;\nfont-size: 1 em;\n}\np, a { font-size: 75%; }\n</code></pre>\n\n<p>will generate links and paragraphs that are sized at .75em. <strong>But</strong> it will display links within paragraphs at about .56em (.75 * .75).</p>\n\n<p>In addition to the specificity reference cited by Jonathan Arkell, I recommend the <a href=\"http://www.w3schools.com/css/default.asp\" rel=\"nofollow noreferrer\">CSS Tutorial</a> at W3Schools.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16989/" ]
I have only a basic knowledge of css, is it possible to inherit a property from one style into another style. So for instance I could inherit the font size specified in my default paragrah tag settings into my hyperlink tags. The reason I want to do this is to make it easier to maintain multiple styles.
You can define common styles for two elements at once like so: ``` p, a { font-size: 1em; } ``` And then extend each one with their individual properties as you want: ``` p { color: red; } a { font-weight: bold; } ``` **Keep in mind:** Styles defined later in a style sheet generally override properties defined earlier. **Extra:** If you haven't already, I recommend getting the [Firebug](http://walmart.ca/wps-portal/storelocator/Canada-HealthAndBeauty.jsp?selection=listingDetails&page=hb&lang=null&assetId=11727&imageId=39727&suggestedItem=&priceType=1&page=null&departmentId=14&categoryId=193#) Firefox extension so you can see what styles the elements on your page are receiving and where they are inherited from.
199,718
<p>Since Object Initializers are very similar to JSON, and now there are Anonymous Types in .NET. It would be cool to be able to take a string, such as JSON, and create an Anonymous Object that represents the JSON string.</p> <p>Use Object Initializers to create an Anonymous Type:</p> <pre><code>var person = new { FirstName = "Chris", LastName = "Johnson" }; </code></pre> <p>It would be awesome if you could pass in a string representation of the Object Initializer code (preferably something like JSON) to create an instance of an Anonymous Type with that data.</p> <p>I don't know if it's possible, since C# isn't dynamic, and the compiler actually converts the Object Initializer an<a href="http://www.developer.com/net/csharp/article.php/3589916" rel="noreferrer">d Anonymous Type into strongly typed code that can run. This is explained in</a> this article.</p> <p>Maybe functionality to take JSON and create a key/value Dictionary with it would work best.</p> <p>I know you can serialize/deserializer an object to JSON in .NET, but what I'm look for is a way to create an object that is essentially loosely typed, similarly to how JavaScript works.</p> <p>Does anyone know the best solution for doing this in .NET?</p> <p>UPDATE: Too clarify the context of why I'm asking this... I was thinking of how C# could better support JSON at the language level (possibly) and I was trying to think of ways that it could be done today, for conceptual reasons. So, I thought I'd post it here to start a discussion.</p>
[ { "answer_id": 199748, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>What is the application for this?</p>\n\n<p>I would not go down this road for a few reasons. </p>\n\n<ul>\n<li><p>First; it may require a lot of support code using reflection and such to create the transparent method that you are talking about.</p></li>\n<li><p>Second, like you said, C# is a strongly typed language and things like these were left out of the language specification for a reason.</p></li>\n<li><p>Third, the overhead for doing this would not be worth it. Remember that web pages (especially AJAX queries) should be really fast or it defeats the purpose. If you go ahead and spend 50% serializing your objects between C# and Javascript then you have a problem.</p></li>\n</ul>\n\n<p>My solution would be to create a class that just encapsulates a dictionary and that takes a JSON string as a ctor argument. Then just extend that class for each type of JSON query you want to handle. This will be a strongly typed and faster solution but still maintain extensibility and ease of use. The downside is that there is more code to write per type of JSON request. </p>\n\n<p>:)</p>\n" }, { "answer_id": 199797, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 4, "selected": true, "text": "<p>There are languages for .NET that have duck-typing but it's not possible with C# using Dot.Notation since C# requires that all member references are resolved at compile time. If you want to use the Dot.Notation, you still have to define a class somewhere with the required properties, and use whatever method you want to instantiate the class from the JSON data. Pre-defining a class <em>does</em> have benefits like strong typing, IDE support including intellisense, and not worrying about spelling mistakes. You can still use anonymous types:</p>\n\n<pre><code> T deserialize&lt;T&gt;(string jsonStr, T obj) { /* ... */}\n\n var jsonString = \"{FirstName='Chris', LastName='Johnson, Other='unused'}\";\n var person = deserialize(jsonString, new {FirstName=\"\",LastName=\"\"});\n var x = person.FirstName; //strongly-typed\n</code></pre>\n" }, { "answer_id": 199816, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 3, "selected": false, "text": "<p>You should check out the <strong>JSON.net</strong> project:</p>\n\n<p><a href=\"http://james.newtonking.com/pages/json-net.aspx\" rel=\"noreferrer\">http://james.newtonking.com/pages/json-net.aspx</a></p>\n\n<p>You are basically talking about the ability to hydrate an object from JSON, which this will do. It won't do the anonymous types, but maybe it will get you close enough.</p>\n" }, { "answer_id": 199922, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>You can't return an anonymous type from a method**, so a \"rehydrated\" anonymous type's existence would be limited to the method in which it is rehydrated. Kind of pointless.</p>\n\n<p>** You can return it as an object (which requires reflection to access its properties--yeech) or you can \"cast it by example\", which is pointless as well, since it takes extra steps and it means you already KNOW what the object's type should look like, so why not just create an object and fill it up in the first place?</p>\n" }, { "answer_id": 199923, "author": "Chris Pietschmann", "author_id": 7831, "author_profile": "https://Stackoverflow.com/users/7831", "pm_score": 2, "selected": false, "text": "<p>I wrote a relatively short method that will Parse JSON and return a name/value Dictionary that can be accessed similarly to the actual object in JavaScript.</p>\n\n<p>Here's a sample usage of the below method:</p>\n\n<pre><code>var obj = ParseJsonToDictionary(\"{FirstName: \\\"Chris\\\", \\\"Address\\\":{Street:\\\"My Street\\\",Number:123}}\");\n\n// Access the Address.Number value\nobject streetNumber = ((Dictionary&lt;string, object&gt;)obj[\"Address\"])[\"Number\"];\n</code></pre>\n\n<p>And, here's the code for the ParseJsonToDictionary method:</p>\n\n<pre><code>public static Dictionary&lt;string, object&gt; ParseJsonToDictionary(string json)\n{\n var d = new Dictionary&lt;string, object&gt;();\n\n if (json.StartsWith(\"{\"))\n {\n json = json.Remove(0, 1);\n if (json.EndsWith(\"}\"))\n json = json.Substring(0, json.Length - 1);\n }\n json.Trim();\n\n // Parse out Object Properties from JSON\n while (json.Length &gt; 0)\n {\n var beginProp = json.Substring(0, json.IndexOf(':'));\n json = json.Substring(beginProp.Length);\n\n var indexOfComma = json.IndexOf(',');\n string endProp;\n if (indexOfComma &gt; -1)\n {\n endProp = json.Substring(0, indexOfComma);\n json = json.Substring(endProp.Length);\n }\n else\n {\n endProp = json;\n json = string.Empty;\n }\n\n var curlyIndex = endProp.IndexOf('{');\n if (curlyIndex &gt; -1)\n {\n var curlyCount = 1;\n while (endProp.Substring(curlyIndex + 1).IndexOf(\"{\") &gt; -1)\n {\n curlyCount++;\n curlyIndex = endProp.Substring(curlyIndex + 1).IndexOf(\"{\");\n }\n while (curlyCount &gt; 0)\n {\n endProp += json.Substring(0, json.IndexOf('}') + 1);\n json = json.Remove(0, json.IndexOf('}') + 1);\n curlyCount--;\n }\n }\n\n json = json.Trim();\n if (json.StartsWith(\",\"))\n json = json.Remove(0, 1);\n json.Trim();\n\n\n // Individual Property (Name/Value Pair) Is Isolated\n var s = (beginProp + endProp).Trim();\n\n\n // Now parse the name/value pair out and put into Dictionary\n var name = s.Substring(0, s.IndexOf(\":\")).Trim();\n var value = s.Substring(name.Length + 1).Trim();\n\n if (name.StartsWith(\"\\\"\") &amp;&amp; name.EndsWith(\"\\\"\"))\n {\n name = name.Substring(1, name.Length - 2);\n }\n\n double valueNumberCheck;\n if (value.StartsWith(\"\\\"\") &amp;&amp; value.StartsWith(\"\\\"\"))\n {\n // String Value\n d.Add(name, value.Substring(1, value.Length - 2));\n }\n else if (value.StartsWith(\"{\") &amp;&amp; value.EndsWith(\"}\"))\n {\n // JSON Value\n d.Add(name, ParseJsonToDictionary(value));\n }\n else if (double.TryParse(value, out valueNumberCheck))\n {\n // Numeric Value\n d.Add(name, valueNumberCheck);\n }\n else\n d.Add(name, value);\n }\n\n return d;\n}\n</code></pre>\n\n<p>I know this method may be a little rough, and it could probably be optimized quite a bit, but it's the first draft and it just works.</p>\n\n<p>Also, before you complain about it not using regular expressions, keep in mind that not everyone really understands regular expressions, and writing it that way would make in more difficult for others to fix if needed. Also, I currently don't know regular expression too well, and string parsing was just easier.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7831/" ]
Since Object Initializers are very similar to JSON, and now there are Anonymous Types in .NET. It would be cool to be able to take a string, such as JSON, and create an Anonymous Object that represents the JSON string. Use Object Initializers to create an Anonymous Type: ``` var person = new { FirstName = "Chris", LastName = "Johnson" }; ``` It would be awesome if you could pass in a string representation of the Object Initializer code (preferably something like JSON) to create an instance of an Anonymous Type with that data. I don't know if it's possible, since C# isn't dynamic, and the compiler actually converts the Object Initializer an[d Anonymous Type into strongly typed code that can run. This is explained in](http://www.developer.com/net/csharp/article.php/3589916) this article. Maybe functionality to take JSON and create a key/value Dictionary with it would work best. I know you can serialize/deserializer an object to JSON in .NET, but what I'm look for is a way to create an object that is essentially loosely typed, similarly to how JavaScript works. Does anyone know the best solution for doing this in .NET? UPDATE: Too clarify the context of why I'm asking this... I was thinking of how C# could better support JSON at the language level (possibly) and I was trying to think of ways that it could be done today, for conceptual reasons. So, I thought I'd post it here to start a discussion.
There are languages for .NET that have duck-typing but it's not possible with C# using Dot.Notation since C# requires that all member references are resolved at compile time. If you want to use the Dot.Notation, you still have to define a class somewhere with the required properties, and use whatever method you want to instantiate the class from the JSON data. Pre-defining a class *does* have benefits like strong typing, IDE support including intellisense, and not worrying about spelling mistakes. You can still use anonymous types: ``` T deserialize<T>(string jsonStr, T obj) { /* ... */} var jsonString = "{FirstName='Chris', LastName='Johnson, Other='unused'}"; var person = deserialize(jsonString, new {FirstName="",LastName=""}); var x = person.FirstName; //strongly-typed ```
199,728
<p>How do I set gc.reflogExpire so that items will never expire?<br> What other time interval formats does it accept?</p> <p>The man page says that you can set it to "90 days or 3 months," but doesn't specify what format it expects.</p>
[ { "answer_id": 199927, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 3, "selected": false, "text": "<p>I’m not sure where the format is documented, if at all, but <code>git reflog</code> uses the <code>approxidate</code> function from <a href=\"http://git.kernel.org/?p=git/git.git;a=blob;f=date.c\" rel=\"noreferrer\"><code>date.c</code></a> to parse the expiry time. One of the possible values is “never.”</p>\n" }, { "answer_id": 202947, "author": "CB Bailey", "author_id": 19563, "author_profile": "https://Stackoverflow.com/users/19563", "pm_score": 5, "selected": true, "text": "<p>Setting gc.refLogExpire to &quot;never&quot; should do the trick.</p>\n<pre><code>git config gc.reflogExpire &quot;never&quot;\n</code></pre>\n" }, { "answer_id": 72538799, "author": "sunyunxian", "author_id": 11235640, "author_profile": "https://Stackoverflow.com/users/11235640", "pm_score": 1, "selected": false, "text": "<p>Setting in cli</p>\n<ul>\n<li>day: <code>git reflog expire --expire=180</code></li>\n<li>never: <code>git reflog expire --expire=never</code></li>\n</ul>\n<p>Or</p>\n<p>Setting this reflogExpire in you .gitconfig file</p>\n<pre><code>[gc]\n reflogExpire = never # Make reflog never expire\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
How do I set gc.reflogExpire so that items will never expire? What other time interval formats does it accept? The man page says that you can set it to "90 days or 3 months," but doesn't specify what format it expects.
Setting gc.refLogExpire to "never" should do the trick. ``` git config gc.reflogExpire "never" ```
199,747
<p>Is there a standard way to see how much stack space your app has and what the highest watermark for stack usage is during a run?</p> <p>Also in the dreaded case of actual overflow what happens? </p> <p>Does it crash, trigger an exception or signal? Is there a standard or is it different on all systems and compilers?</p> <p>I'm looking specifically for Windows, Linux and Macintosh. </p>
[ { "answer_id": 199809, "author": "jussij", "author_id": 14738, "author_profile": "https://Stackoverflow.com/users/14738", "pm_score": 4, "selected": false, "text": "<p>On <strong>Windows</strong> a stack overflow <strong>exception</strong> will be generated.</p>\n\n<p>The following windows code illustrates this:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;windows.h&gt;\n\nvoid StackOverFlow()\n{\n CONTEXT context;\n\n // we are interested control registers\n context.ContextFlags = CONTEXT_CONTROL;\n\n // get the details\n GetThreadContext(GetCurrentThread(), &amp;context);\n\n // print the stack pointer\n printf(\"Esp: %X\\n\", context.Esp);\n\n // this will eventually overflow the stack\n StackOverFlow();\n}\n\nDWORD ExceptionFilter(EXCEPTION_POINTERS *pointers, DWORD dwException)\n{\n return EXCEPTION_EXECUTE_HANDLER;\n}\n\nvoid main()\n{\n CONTEXT context;\n\n // we are interested control registers\n context.ContextFlags = CONTEXT_CONTROL;\n\n // get the details\n GetThreadContext(GetCurrentThread(), &amp;context);\n\n // print the stack pointer\n printf(\"Esp: %X\\n\", context.Esp);\n\n __try\n {\n // cause a stack overflow\n StackOverFlow();\n }\n __except(ExceptionFilter(GetExceptionInformation(), GetExceptionCode()))\n {\n printf(\"\\n****** ExceptionFilter fired ******\\n\");\n }\n}\n</code></pre>\n\n<p>When this exe is run the following output is generated:</p>\n\n<pre><code>Esp: 12FC4C\nEsp: 12F96C\nEsp: 12F68C\n.....\nEsp: 33D8C\nEsp: 33AAC\nEsp: 337CC\n\n****** ExceptionFilter fired ******\n</code></pre>\n" }, { "answer_id": 199813, "author": "Kknd", "author_id": 18403, "author_profile": "https://Stackoverflow.com/users/18403", "pm_score": 3, "selected": false, "text": "<p>gcc places an extra block of memory between the return address and the normal variables in \"unsafe\" function calls, like (in this example the function is void test() {char a[10]; b[20]}:</p>\n\n<pre><code>call stack:\n-----------\nreturn address\ndummy\nchar b[10]\nchar a[20]\n</code></pre>\n\n<p>If the function write 36 bytes in the pointer 'a', the overflow will 'corrupt' the return address (possible security breach). But it will also change the value of the 'dummy', that is between the pointer and the return address, so the program will crash with a warning (you can disable this with a -fno-stack-protector)</p>\n" }, { "answer_id": 199837, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 2, "selected": false, "text": "<p>Stack overflow is probably the nastiest type of exception to handle -- because your exception handler has to deal with a minimal amount of stack (usually only a single page is reserved for this purpose).</p>\n\n<p>For an interesting discussion of the difficulties handling this type of exception see these blog posts: <a href=\"http://blogs.msdn.com/cbrumme/archive/2003/06/23/51482.aspx\" rel=\"nofollow noreferrer\">1</a> and <a href=\"http://blogs.msdn.com/cbrumme/archive/2003/10/01/51524.aspx\" rel=\"nofollow noreferrer\">2</a> from Chris Brumme which focus on the issue from the .NET perspective, particularly hosting the CLR.</p>\n" }, { "answer_id": 200370, "author": "dmityugov", "author_id": 3232, "author_profile": "https://Stackoverflow.com/users/3232", "pm_score": 1, "selected": false, "text": "<p>Some compilers support stackavail() function, which returns the amount of remaining free space of the stack. You can use this function before calling functions in your programs that require a lot of stack space, to determine if it is safe to call them</p>\n" }, { "answer_id": 201352, "author": "adl", "author_id": 27835, "author_profile": "https://Stackoverflow.com/users/27835", "pm_score": 4, "selected": false, "text": "<p>On Linux you get a segmentation fault if your code tries to write past the stack.</p>\n<p>The size of the stack is a property inherited between processes. If you can read or modify it in the the shell using commands like <code>ulimit -s</code> (in <code>sh</code>, <code>ksh</code>, <code>zsh</code>) or <code>limit stacksize</code> (<code>tcsh</code>, <code>zsh</code>).</p>\n<p>From a program, the size of the stack can be read using</p>\n<pre><code>#include &lt;sys/resource.h&gt;\n#include &lt;stdio.h&gt;\n\nint main() {\n struct rlimit l;\n getrlimit(RLIMIT_STACK, &amp;l);\n printf(&quot;stack_size = %ld\\n&quot;, l.rlim_cur);\n return 0;\n}\n</code></pre>\n<p>I don't know of a standard way to get the size of the available stack.</p>\n<p>The stack starts with <code>argc</code> followed by the contents of <code>argv</code> and a copy of the environment, and then your variables. However because the kernel can randomize the location of the start of the stack, and there can be some dummy values above <code>argc</code>, it would be wrong to assume that you have <code>l.rlim_cur</code> bytes available below <code>&amp;argc</code>.</p>\n<p>One way to retrieve the exact location of the stack is to look at the file <code>/proc/1234/maps</code> (where <code>1234</code> is the process ID of your program). Once you know these bounds you can compute how much of your stack is used by looking at the address of the latest local variable.</p>\n" }, { "answer_id": 380297, "author": "Shyam Sunder Verma", "author_id": 46605, "author_profile": "https://Stackoverflow.com/users/46605", "pm_score": 1, "selected": false, "text": "<p>I would suggest you to use alternate-signal-stack if you are on linux.</p>\n\n<ol>\n<li>In this case all the signal will be handled over alternate stack.</li>\n<li>In case stack overflow occurs, system generates a SEGV signal, this can be handled over alternate stack.</li>\n<li>If you do not use it ... then you may not be able to handle the signal, and your program may crash without any handling/erro-reporting.</li>\n</ol>\n" }, { "answer_id": 380393, "author": "deemok", "author_id": 23713, "author_profile": "https://Stackoverflow.com/users/23713", "pm_score": 3, "selected": false, "text": "<p>On windows, the stack (for specific thread) grows on-demand until the stack size specified for this thread prior to its creation has been reached. \n<p>On-demand growing is impelmented using guard pages, in that there's a only a fragment of stack available initially, followed by a guard page, which, when hit, will trigger an exception - this exception is special, and is handled by the system for you - the handling increases the available stack space (also checked if a limit has been reached!) and the read operation is retried. \n<p>Once the limit is reached, there's no more growing which results in stack overflow exception.\nThe current stack base and limit are stored in thread environment block, in a struct called <code>_NT_TIB</code> (thread information block).\nIf you have a debugger handy, this is what you see:</p>\n\n<pre><code>0:000&gt; dt ntdll!_teb @$teb nttib.\n +0x000 NtTib : \n +0x000 ExceptionList : 0x0012e030 _EXCEPTION_REGISTRATION_RECORD\n +0x004 StackBase : 0x00130000 \n +0x008 StackLimit : 0x0011e000 \n +0x00c SubSystemTib : (null) \n +0x010 FiberData : 0x00001e00 \n +0x010 Version : 0x1e00\n +0x014 ArbitraryUserPointer : (null) \n +0x018 Self : 0x7ffdf000 _NT_TIB\n</code></pre>\n\n<p>The StackLimit attribute will get updated on-demand.\nIf you check the attributes on this memory block, you'll see something similar to that:</p>\n\n<pre><code>0:000&gt; !address 0x0011e000 \n 00030000 : 0011e000 - 00012000\n Type 00020000 MEM_PRIVATE\n Protect 00000004 PAGE_READWRITE\n State 00001000 MEM_COMMIT\n Usage RegionUsageStack\n Pid.Tid abc.560\n</code></pre>\n\n<p>And checking a page next to it reveals the guard attribute:</p>\n\n<pre><code>0:000&gt; !address 0x0011e000-1000\n 00030000 : 0011d000 - 00001000\n Type 00020000 MEM_PRIVATE\n Protect 00000104 PAGE_READWRITE | PAGE_GUARD\n State 00001000 MEM_COMMIT\n Usage RegionUsageStack\n Pid.Tid abc.560\n</code></pre>\n\n<p>Hope it helps.</p>\n" }, { "answer_id": 1581369, "author": "Norman Ramsey", "author_id": 41661, "author_profile": "https://Stackoverflow.com/users/41661", "pm_score": 3, "selected": false, "text": "<p>On Linux, the Gnu <a href=\"http://savannah.gnu.org/projects/libsigsegv/\" rel=\"noreferrer\"><strong>libsigsegv</strong> library</a> includes the function <code>stackoverflow_install_handler</code>, which can detect (and in some cases help you recover from) stack overflow.</p>\n" }, { "answer_id": 7024267, "author": "Richard", "author_id": 888941, "author_profile": "https://Stackoverflow.com/users/888941", "pm_score": 1, "selected": false, "text": "<p>It is possible to use editbin in Visual Studio to change the stack size. The information can be found at <a href=\"http://msdn.microsoft.com/en-us/library/35yc2tc3.aspx\" rel=\"nofollow\">msdn.microsoft.com/en-us/library/35yc2tc3.aspx</a>.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13676/" ]
Is there a standard way to see how much stack space your app has and what the highest watermark for stack usage is during a run? Also in the dreaded case of actual overflow what happens? Does it crash, trigger an exception or signal? Is there a standard or is it different on all systems and compilers? I'm looking specifically for Windows, Linux and Macintosh.
On **Windows** a stack overflow **exception** will be generated. The following windows code illustrates this: ``` #include <stdio.h> #include <windows.h> void StackOverFlow() { CONTEXT context; // we are interested control registers context.ContextFlags = CONTEXT_CONTROL; // get the details GetThreadContext(GetCurrentThread(), &context); // print the stack pointer printf("Esp: %X\n", context.Esp); // this will eventually overflow the stack StackOverFlow(); } DWORD ExceptionFilter(EXCEPTION_POINTERS *pointers, DWORD dwException) { return EXCEPTION_EXECUTE_HANDLER; } void main() { CONTEXT context; // we are interested control registers context.ContextFlags = CONTEXT_CONTROL; // get the details GetThreadContext(GetCurrentThread(), &context); // print the stack pointer printf("Esp: %X\n", context.Esp); __try { // cause a stack overflow StackOverFlow(); } __except(ExceptionFilter(GetExceptionInformation(), GetExceptionCode())) { printf("\n****** ExceptionFilter fired ******\n"); } } ``` When this exe is run the following output is generated: ``` Esp: 12FC4C Esp: 12F96C Esp: 12F68C ..... Esp: 33D8C Esp: 33AAC Esp: 337CC ****** ExceptionFilter fired ****** ```
199,761
<p><sup><strong>Note:</strong> This question was asked at a time when C# did not yet support optional parameters (i.e. before C# 4).</sup></p> <p>We're building a web API that's programmatically generated from a C# class. The class has method <code>GetFooBar(int a, int b)</code> and the API has a method <code>GetFooBar</code> taking query params like <code>&amp;a=foo &amp;b=bar</code>. </p> <p>The classes needs to support optional parameters, which isn't supported in C# the language. What's the best approach?</p>
[ { "answer_id": 199765, "author": "Kalid", "author_id": 109, "author_profile": "https://Stackoverflow.com/users/109", "pm_score": 6, "selected": false, "text": "<p>From this site:</p>\n<p><a href=\"https://www.tek-tips.com/viewthread.cfm?qid=1500861\" rel=\"nofollow noreferrer\">https://www.tek-tips.com/viewthread.cfm?qid=1500861</a></p>\n<p>C# does allow the use of the [Optional] attribute (from VB, though not functional in C#). So you can have a method like this:</p>\n<pre><code>using System.Runtime.InteropServices;\npublic void Foo(int a, int b, [Optional] int c)\n{\n ...\n}\n</code></pre>\n<p>In our API wrapper, we detect optional parameters (ParameterInfo p.IsOptional) and set a default value. The goal is to mark parameters as optional without resorting to kludges like having &quot;optional&quot; in the parameter name.</p>\n" }, { "answer_id": 199770, "author": "stephenbayer", "author_id": 18893, "author_profile": "https://Stackoverflow.com/users/18893", "pm_score": 6, "selected": false, "text": "<p>In C#, I would normally use multiple forms of the method:</p>\n\n<pre><code>void GetFooBar(int a) { int defaultBValue; GetFooBar(a, defaultBValue); }\nvoid GetFooBar(int a, int b)\n{\n // whatever here\n}\n</code></pre>\n\n<p><strong>UPDATE:</strong> This mentioned above WAS the way that I did default values with C# 2.0. The projects I'm working on now are using C# 4.0 which now directly supports optional parameters. Here is an example I just used in my own code:</p>\n\n<pre><code>public EDIDocument ApplyEDIEnvelop(EDIVanInfo sender, \n EDIVanInfo receiver, \n EDIDocumentInfo info,\n EDIDocumentType type \n = new EDIDocumentType(EDIDocTypes.X12_814),\n bool Production = false)\n{\n // My code is here\n}\n</code></pre>\n" }, { "answer_id": 199778, "author": "Kepboy", "author_id": 21429, "author_profile": "https://Stackoverflow.com/users/21429", "pm_score": 5, "selected": false, "text": "<p>You could use method overloading...</p>\n\n<pre>\nGetFooBar()\nGetFooBar(int a)\nGetFooBar(int a, int b)\n</pre>\n\n<p>It depends on the method signatures, the example I gave is missing the \"int b\" only method because it would have the same signature as the \"int a\" method.</p>\n\n<p>You could use Nullable types...</p>\n\n<pre>\nGetFooBar(int? a, int? b)\n</pre>\n\n<p>You could then check, using a.HasValue, to see if a parameter has been set.</p>\n\n<p>Another option would be to use a 'params' parameter.</p>\n\n<pre>\nGetFooBar(params object[] args)\n</pre>\n\n<p>If you wanted to go with named parameters would would need to create a type to handle them, although I think there is already something like this for web apps.</p>\n" }, { "answer_id": 199779, "author": "Tim Jarvis", "author_id": 10387, "author_profile": "https://Stackoverflow.com/users/10387", "pm_score": 7, "selected": false, "text": "<p>Another option is to use the params keyword</p>\n\n<pre><code>public void DoSomething(params object[] theObjects)\n{\n foreach(object o in theObjects)\n {\n // Something with the Objects…\n }\n}\n</code></pre>\n\n<p>Called like...</p>\n\n<pre><code>DoSomething(this, that, theOther);\n</code></pre>\n" }, { "answer_id": 199781, "author": "cfbarbero", "author_id": 2218, "author_profile": "https://Stackoverflow.com/users/2218", "pm_score": 2, "selected": false, "text": "<p>The typical way this is handled in C# as stephen mentioned is to overload the method. By creating multiple versions of the method with different parameters you effectively create optional parameters. In the forms with fewer parameters you would typically call the form of the method with all of the parameters setting your default values in the call to that method.</p>\n" }, { "answer_id": 199789, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 0, "selected": false, "text": "<p>Instead of default parameters, why not just construct a dictionary class from the querystring passed .. an implementation that is almost identical to the way asp.net forms work with querystrings. </p>\n\n<p>i.e. Request.QueryString[\"a\"] </p>\n\n<p>This will decouple the leaf class from the factory / boilerplate code.</p>\n\n<hr>\n\n<p>You also might want to check out <a href=\"http://msdn.microsoft.com/en-us/library/ms972326.aspx\" rel=\"nofollow noreferrer\">Web Services with ASP.NET</a>. Web services are a web api generated automatically via attributes on C# classes.</p>\n" }, { "answer_id": 199790, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 3, "selected": false, "text": "<p>I agree with stephenbayer. But since it is a webservice, it is easier for end-user to use just one form of the webmethod, than using multiple versions of the same method. I think in this situation Nullable Types are perfect for optional parameters.</p>\n\n<pre><code>public void Foo(int a, int b, int? c)\n{\n if(c.HasValue)\n {\n // do something with a,b and c\n }\n else\n {\n // do something with a and b only\n } \n}\n</code></pre>\n" }, { "answer_id": 200719, "author": "Hugh Allen", "author_id": 15069, "author_profile": "https://Stackoverflow.com/users/15069", "pm_score": 4, "selected": false, "text": "<h2>Hello Optional World</h2>\n\n<p>If you want the runtime to supply a default parameter value, you have to use reflection to make the call. Not as nice as the other suggestions for this question, but compatible with VB.NET.</p>\n\n<pre><code>using System;\nusing System.Runtime.InteropServices;\nusing System.Reflection;\n\nnamespace ConsoleApplication1\n{\n class Class1\n {\n public static void sayHelloTo(\n [Optional,\n DefaultParameterValue(\"world\")] string whom)\n {\n Console.WriteLine(\"Hello \" + whom);\n }\n\n [STAThread]\n static void Main(string[] args)\n {\n MethodInfo mi = typeof(Class1).GetMethod(\"sayHelloTo\");\n mi.Invoke(null, new Object[] { Missing.Value });\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 1746099, "author": "Ron K", "author_id": 212541, "author_profile": "https://Stackoverflow.com/users/212541", "pm_score": 0, "selected": false, "text": "<p>A little late to the party, but I was looking for the answer to this question and ultimately figured out yet another way to do this. Declare the data types for the optional args of your web method to be type XmlNode. If the optional arg is omitted this will be set to null, and if it's present you can get is string value by calling arg.Value, i.e.,</p>\n\n<pre><code>[WebMethod]\npublic string Foo(string arg1, XmlNode optarg2)\n{\n string arg2 = \"\";\n if (optarg2 != null)\n {\n arg2 = optarg2.Value;\n }\n ... etc\n}\n</code></pre>\n\n<p>What's also decent about this approach is the .NET generated home page for the ws still shows the argument list (though you do lose the handy text entry boxes for testing).</p>\n" }, { "answer_id": 1943548, "author": "Spanky", "author_id": 1899246, "author_profile": "https://Stackoverflow.com/users/1899246", "pm_score": 0, "selected": false, "text": "<p>I have a web service to write that takes 7 parameters. Each is an optional query attribute to a sql statement wrapped by this web service. So two workarounds to non-optional params come to mind... both pretty poor:</p>\n\n<p>method1(param1, param2, param 3, param 4, param 5, param 6, param7)\nmethod1(param1, param2, param3, param 4, param5, param 6)\nmethod 1(param1, param2, param3, param4, param5, param7)... start to see the picture. This way lies madness. Way too many combinations.</p>\n\n<p>Now for a simpler way that looks awkward but should work:\nmethod1(param1, bool useParam1, param2, bool useParam2, etc...)</p>\n\n<p>That's one method call, values for all parameters are required, and it will handle each case inside it. It's also clear how to use it from the interface.</p>\n\n<p>It's a hack, but it will work.</p>\n" }, { "answer_id": 3343769, "author": "Alex from Jitbit", "author_id": 56621, "author_profile": "https://Stackoverflow.com/users/56621", "pm_score": 11, "selected": true, "text": "<p>Surprised no one mentioned C# 4.0 optional parameters that work like this:</p>\n\n<pre><code>public void SomeMethod(int a, int b = 0)\n{\n //some code\n}\n</code></pre>\n\n<p><strong>Edit:</strong> I know that at the time the question was asked, C# 4.0 didn't exist. But this question still ranks #1 in Google for \"C# optional arguments\" so I thought - this answer worth being here. Sorry.</p>\n" }, { "answer_id": 4588021, "author": "Matt", "author_id": 561716, "author_profile": "https://Stackoverflow.com/users/561716", "pm_score": 0, "selected": false, "text": "<p>I had to do this in a VB.Net 2.0 Web Service. I ended up specifying the parameters as strings, then converting them to whatever I needed. An optional parameter was specified with an empty string. Not the cleanest solution, but it worked. Just be careful that you catch all the exceptions that can occur.</p>\n" }, { "answer_id": 5076579, "author": "kristi_io", "author_id": 1646259, "author_profile": "https://Stackoverflow.com/users/1646259", "pm_score": 5, "selected": false, "text": "<p>You can use optional parameters in C# 4.0 without any worries.\nIf we have a method like:</p>\n\n<pre><code>int MyMetod(int param1, int param2, int param3=10, int param4=20){....}\n</code></pre>\n\n<p>when you call the method, you can skip parameters like this:</p>\n\n<pre><code>int variab = MyMethod(param3:50; param1:10);\n</code></pre>\n\n<p>C# 4.0 implements a feature called \"named parameters\", you can actually pass parameters by their names, and of course you can pass parameters in whatever order you want :) </p>\n" }, { "answer_id": 6100565, "author": "baskinhu", "author_id": 766403, "author_profile": "https://Stackoverflow.com/users/766403", "pm_score": 3, "selected": false, "text": "<p>optional parameters are for methods. if you need optional arguments for a class and you are:</p>\n\n<ul>\n<li><p>using c# 4.0: use optional arguments in the constructor of the class, a solution i prefer, since it's closer to what is done with methods, so easier to remember. here's an example:</p>\n\n<pre><code>class myClass\n{\n public myClass(int myInt = 1, string myString =\n \"wow, this is cool: i can have a default string\")\n {\n // do something here if needed\n }\n}\n</code></pre></li>\n<li><p>using c# versions previous to c#4.0: you should use constructor chaining (using the :this keyword), where simpler constructors lead to a \"master constructor\".\nexample:</p>\n\n<pre><code>class myClass\n{\n public myClass()\n {\n // this is the default constructor\n }\n\n public myClass(int myInt)\n : this(myInt, \"whatever\")\n {\n // do something here if needed\n }\n public myClass(string myString)\n : this(0, myString)\n {\n // do something here if needed\n }\n public myClass(int myInt, string myString)\n {\n // do something here if needed - this is the master constructor\n }\n}\n</code></pre></li>\n</ul>\n" }, { "answer_id": 27374682, "author": "user2933082", "author_id": 2933082, "author_profile": "https://Stackoverflow.com/users/2933082", "pm_score": 2, "selected": false, "text": "<p>You can overload your method. One method contains one parameter <code>GetFooBar(int a)</code> and the other contain both parameters, <code>GetFooBar(int a, int b)</code></p>\n" }, { "answer_id": 29820290, "author": "SteakOverflow", "author_id": 802435, "author_profile": "https://Stackoverflow.com/users/802435", "pm_score": 5, "selected": false, "text": "<p>An easy way which allows you to omit <strong>any parameters</strong> in <strong>any position</strong>, is taking advantage of <a href=\"https://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx\" rel=\"noreferrer\">nullable types</a> as follows:</p>\n\n<pre><code>public void PrintValues(int? a = null, int? b = null, float? c = null, string s = \"\")\n{\n if(a.HasValue)\n Console.Write(a);\n else\n Console.Write(\"-\");\n\n if(b.HasValue)\n Console.Write(b);\n else\n Console.Write(\"-\");\n\n if(c.HasValue)\n Console.Write(c);\n else\n Console.Write(\"-\");\n\n if(string.IsNullOrEmpty(s)) // Different check for strings\n Console.Write(s);\n else\n Console.Write(\"-\");\n}\n</code></pre>\n\n<p>Strings are already nullable types so they don't need the <strong>?</strong>.</p>\n\n<p>Once you have this method, the following calls are <strong>all valid</strong>:</p>\n\n<pre><code>PrintValues (1, 2, 2.2f);\nPrintValues (1, c: 1.2f);\nPrintValues(b:100);\nPrintValues (c: 1.2f, s: \"hello\");\nPrintValues();\n</code></pre>\n\n<p>When you define a method that way you have the freedom to set just the parameters you want by <strong>naming</strong> them. See the following link for more information on named and optional parameters:</p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/dd264739.aspx\" rel=\"noreferrer\">Named and Optional Arguments (C# Programming Guide) @ MSDN</a></p>\n" }, { "answer_id": 30893531, "author": "CodeArtist", "author_id": 1843190, "author_profile": "https://Stackoverflow.com/users/1843190", "pm_score": 0, "selected": false, "text": "<p>For just in case if someone wants to pass a callback (or <code>delegate</code>) as an optional parameter, can do it this way.</p>\n\n<p><strong>Optional Callback parameter:</strong></p>\n\n<pre><code>public static bool IsOnlyOneElement(this IList lst, Action callbackOnTrue = (Action)((null)), Action callbackOnFalse = (Action)((null)))\n{\n var isOnlyOne = lst.Count == 1;\n if (isOnlyOne &amp;&amp; callbackOnTrue != null) callbackOnTrue();\n if (!isOnlyOne &amp;&amp; callbackOnFalse != null) callbackOnFalse();\n return isOnlyOne;\n}\n</code></pre>\n" }, { "answer_id": 49442384, "author": "Ankit Panwar", "author_id": 2042974, "author_profile": "https://Stackoverflow.com/users/2042974", "pm_score": -1, "selected": false, "text": "<p>You can try this too<br/>\nType 1<br/>\n <code>public void YourMethod(int a=0, int b = 0)\n {\n //some code\n }</code></p>\n\n<p><br/>\nType 2 <br/>\n <code>public void YourMethod(int? a, int? b)\n {\n //some code\n }\n</code></p>\n" }, { "answer_id": 51661227, "author": "user3555836", "author_id": 3555836, "author_profile": "https://Stackoverflow.com/users/3555836", "pm_score": 0, "selected": false, "text": "<p>optional parameters are nothing but default parameters!\ni suggest you give both of them default parameters.\nGetFooBar(int a=0, int b=0) if you don't have any overloaded method, will result in a=0, b=0 if you don't pass any values,if you pass 1 value, will result in, passed value for a, 0 and if you pass 2 values 1st will be assigned to a and second to b.</p>\n\n<p>hope that answers your question.</p>\n" }, { "answer_id": 57903337, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Using overloads or using C# 4.0 or above </p>\n\n<pre><code> private void GetVal(string sName, int sRoll)\n {\n if (sRoll &gt; 0)\n {\n // do some work\n }\n }\n\n private void GetVal(string sName)\n {\n GetVal(\"testing\", 0);\n }\n</code></pre>\n" }, { "answer_id": 58060016, "author": "Sharunas Bielskis", "author_id": 4403269, "author_profile": "https://Stackoverflow.com/users/4403269", "pm_score": 0, "selected": false, "text": "<p>In the case when default values aren't available the way to add an optional parameter is to use .NET OptionalAttribute class - <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.optionalattribute?view=netframework-4.8\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.optionalattribute?view=netframework-4.8</a> </p>\n\n<p>Example of the code is below:</p>\n\n<pre><code>namespace OptionalParameterWithOptionalAttribute\n{\n class Program\n {\n static void Main(string[] args)\n {\n //Calling the helper method Hello only with required parameters\n Hello(\"Vardenis\", \"Pavardenis\");\n //Calling the helper method Hello with required and optional parameters\n Hello(\"Vardenis\", \"Pavardenis\", \"Palanga\");\n }\n public static void Hello(string firstName, string secondName, \n [System.Runtime.InteropServices.OptionalAttribute] string fromCity)\n {\n string result = firstName + \" \" + secondName;\n if (fromCity != null)\n {\n result += \" from \" + fromCity;\n }\n Console.WriteLine(\"Hello \" + result);\n }\n\n }\n}\n</code></pre>\n" }, { "answer_id": 61372049, "author": "Ryan", "author_id": 13383975, "author_profile": "https://Stackoverflow.com/users/13383975", "pm_score": 1, "selected": false, "text": "<p>For a larger number of optional parameters, a single parameter of <code>Dictionary&lt;string,Object&gt;</code> could be used with the <code>ContainsKey</code> method. I like this approach because it allows me to pass a <code>List&lt;T&gt;</code> or a <code>T</code> individually without having to create a whole other method (nice if parameters are to be used as filters, for example).</p>\n<p>Example (<code>new Dictionary&lt;string,Object&gt;()</code> would be passed if no optional parameters are desired):</p>\n<pre><code>public bool Method(string ParamA, Dictionary&lt;string,Object&gt; AddlParams) {\n if(ParamA == &quot;Alpha&quot; &amp;&amp; (AddlParams.ContainsKey(&quot;foo&quot;) || AddlParams.ContainsKey(&quot;bar&quot;))) {\n return true;\n } else {\n return false;\n }\n}\n</code></pre>\n" }, { "answer_id": 63138018, "author": "Sean Franklin", "author_id": 10529399, "author_profile": "https://Stackoverflow.com/users/10529399", "pm_score": 1, "selected": false, "text": "<p>You can use default.</p>\n<pre><code>public void OptionalParameters(int requerid, int optinal = default){}\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109/" ]
**Note:** This question was asked at a time when C# did not yet support optional parameters (i.e. before C# 4). We're building a web API that's programmatically generated from a C# class. The class has method `GetFooBar(int a, int b)` and the API has a method `GetFooBar` taking query params like `&a=foo &b=bar`. The classes needs to support optional parameters, which isn't supported in C# the language. What's the best approach?
Surprised no one mentioned C# 4.0 optional parameters that work like this: ``` public void SomeMethod(int a, int b = 0) { //some code } ``` **Edit:** I know that at the time the question was asked, C# 4.0 didn't exist. But this question still ranks #1 in Google for "C# optional arguments" so I thought - this answer worth being here. Sorry.
199,769
<p>I'm on a Hardy Heron Ubuntu build, BTW.</p>
[ { "answer_id": 199810, "author": "andy", "author_id": 6152, "author_profile": "https://Stackoverflow.com/users/6152", "pm_score": 0, "selected": false, "text": "<p>Hate to give this answer, because it isn't very helpful, but it works fine for me (scroll wheel in gvim on ubuntu hardy).\n<p>\nBut maybe I can suggest some things that help debug the issue:\n<p></p>\n\n<ol>\n<li>Confirm you are running \"gvim\" and trying to scroll the new window that comes up (i.e. you are not running vim in an xterm and trying to scroll that with the mouse)\n<li>Confirm the scroll wheel works in other apps. Use \"xev\" to make sure the X server is seeing the scroll events if you're unsure.\n</ol>\n\n<p><p>\nHope that helps.</p>\n" }, { "answer_id": 201055, "author": "pk.", "author_id": 10615, "author_profile": "https://Stackoverflow.com/users/10615", "pm_score": 1, "selected": false, "text": "<p>Try:</p>\n\n<p>:set mouse=a</p>\n\n<p>\":help mouse\" says</p>\n\n<pre><code>Enable the use of the mouse. Only works for certain terminals\n(xterm, MS-DOS, Win32 |win32-mouse|, qnx pterm, and Linux console\nwith gpm). For using the mouse in the GUI, see |gui-mouse|.\nThe mouse can be enabled for different modes:\n n Normal mode\n v Visual mode\n i Insert mode\n c Command-line mode\n h all previous modes when editing a help file\n a all previous modes\n r for |hit-enter| and |more-prompt| prompt\n A auto-select in Visual mode\nNormally you would enable the mouse in all four modes with: &gt;\n :set mouse=a\nWhen the mouse is not enabled, the GUI will still use the mouse for\nmodeless selection. This doesn't move the text cursor.\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20273/" ]
I'm on a Hardy Heron Ubuntu build, BTW.
Try: :set mouse=a ":help mouse" says ``` Enable the use of the mouse. Only works for certain terminals (xterm, MS-DOS, Win32 |win32-mouse|, qnx pterm, and Linux console with gpm). For using the mouse in the GUI, see |gui-mouse|. The mouse can be enabled for different modes: n Normal mode v Visual mode i Insert mode c Command-line mode h all previous modes when editing a help file a all previous modes r for |hit-enter| and |more-prompt| prompt A auto-select in Visual mode Normally you would enable the mouse in all four modes with: > :set mouse=a When the mouse is not enabled, the GUI will still use the mouse for modeless selection. This doesn't move the text cursor. ```
199,774
<p>I'm trying to get a postgres jdbc connection working in eclipse. It would be nice to use the Data Source Explorer, but for now I'm just trying to get a basic connection. What I have done so far is download the postgres JDBC connector. I then tried two different things. First, Preferences-> Data Management, I tried to add the postgres connector. Second, I added the jar to my project and tried to load the driver using Class.forName("org.postgresql.Driver"); but neither worked. Does anyone have any ideas?</p> <p>Thanks, Charlie</p>
[ { "answer_id": 211512, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Here's one way to get PostgreSQL connectivity to your application:</p>\n\n<ol>\n<li>Get an instance of <code>org.postgresql.ds.PGSimpleDataSource</code></li>\n<li>Setup it with values matching to your database (see methods below)</li>\n<li>Proceed using the DataSource as you would use any other, I'd assume at this point you'd be interested in the <code>DataSource.getConnection()</code> method.</li>\n</ol>\n\n<p>The proprietary methods for configuring this particular DataSource are <code>setServerName()</code>, <code>setDatabaseName()</code>, <code>setUser()</code> and <code>setPassword()</code>.</p>\n\n<p>I wouldn't recommend doing this for anything else than testing though and it's possible your problem lies in the way you're trying to get an instance of the object using <code>Class.forName()</code> There's almost a dozen different ways to get an instance of an object with subtle differences, I suggest Googling for it since it is a subject a lot of people have already written about all over the Internet.</p>\n" }, { "answer_id": 214750, "author": "eflles", "author_id": 26567, "author_profile": "https://Stackoverflow.com/users/26567", "pm_score": 4, "selected": false, "text": "<p>This is how I have made a connection: (I do not know if this is \"best practice\", but it works.)</p>\n\n<p>Importing the driver:</p>\n\n<ol>\n<li>Right click on your project</li>\n<li>Choose property</li>\n<li>Choose <code>Java build path</code></li>\n<li>Choose <code>Add external JARS..</code> and select the location to the JDBC driver.</li>\n</ol>\n\n<p>Here is my code:</p>\n\n<pre><code>try{\n Class.forName(\"org.postgresql.Driver\");\n } catch (ClassNotFoundException cnfe){\n System.out.println(\"Could not find the JDBC driver!\");\n System.exit(1);\n }\nConnection conn = null;\ntry {\n conn = DriverManager.getConnection\n (String url, String user, String password);\n } catch (SQLException sqle) {\n System.out.println(\"Could not connect\");\n System.exit(1);\n }\n</code></pre>\n\n<p>The url can be of one of the following formats:</p>\n\n<pre><code>jdbc:postgresql:database\njdbc:postgresql://host/database\njdbc:postgresql://host:port/database\n</code></pre>\n" }, { "answer_id": 1907537, "author": "Vjeux", "author_id": 232122, "author_profile": "https://Stackoverflow.com/users/232122", "pm_score": 1, "selected": false, "text": "<p>I had the same problem using GWT.</p>\n\n<p>I fixed it by copying the jar file inside the \"lib\" folder: (Project\\war\\WEB-INF\\lib). When you add a jar to the Build Path it seems to do the link statically, however we want the lib at run time!</p>\n\n<p>Hope it fixes your problem.</p>\n" }, { "answer_id": 3774630, "author": "Jamie Carl", "author_id": 393329, "author_profile": "https://Stackoverflow.com/users/393329", "pm_score": 2, "selected": false, "text": "<p>I was also having this problem as well and Vjeux's answer helped point me in the right direction. </p>\n\n<p>I have a local copy of Tomcat6 that was installed and is managed by Eclipse. It was installed into '$HOME/bin/tomcat6'. To get the PostgreSQL JDBC driver working I simply copied my postgresql.jar file into the '$HOME/bin/tomcat6/lib' directory.</p>\n\n<p>Also, if you don't know where to get the driver from in the first place, try this. I'm running Ubuntu so I ran 'sudo apt-get install libpg-java' which installed the driver into '/usr/share/java/postgresql.jar' and so I just copied it from there.</p>\n" }, { "answer_id": 15044459, "author": "jsina", "author_id": 1734778, "author_profile": "https://Stackoverflow.com/users/1734778", "pm_score": 0, "selected": false, "text": "<p>you can write this code in persistence.xml</p>\n\n<blockquote>\n<pre><code> &lt;property name=\"javax.persistence.jdbc.driver\" value=\"org.postgresql.Driver\"/&gt;\n &lt;property name=\"javax.persistence.jdbc.url\" value=\"jdbc:postgresql://localhost:5432/yourDataBaseName\"/&gt;\n &lt;property name=\"javax.persistence.jdbc.user\" value=\"postgres\"/&gt;\n &lt;property name=\"javax.persistence.jdbc.password\" value=\"yourPassword\"/&gt;\n</code></pre>\n</blockquote>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27689/" ]
I'm trying to get a postgres jdbc connection working in eclipse. It would be nice to use the Data Source Explorer, but for now I'm just trying to get a basic connection. What I have done so far is download the postgres JDBC connector. I then tried two different things. First, Preferences-> Data Management, I tried to add the postgres connector. Second, I added the jar to my project and tried to load the driver using Class.forName("org.postgresql.Driver"); but neither worked. Does anyone have any ideas? Thanks, Charlie
This is how I have made a connection: (I do not know if this is "best practice", but it works.) Importing the driver: 1. Right click on your project 2. Choose property 3. Choose `Java build path` 4. Choose `Add external JARS..` and select the location to the JDBC driver. Here is my code: ``` try{ Class.forName("org.postgresql.Driver"); } catch (ClassNotFoundException cnfe){ System.out.println("Could not find the JDBC driver!"); System.exit(1); } Connection conn = null; try { conn = DriverManager.getConnection (String url, String user, String password); } catch (SQLException sqle) { System.out.println("Could not connect"); System.exit(1); } ``` The url can be of one of the following formats: ``` jdbc:postgresql:database jdbc:postgresql://host/database jdbc:postgresql://host:port/database ```