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
156,013
<p>I can't quite figure out this syntax problem with a <code>case</code> expression in a <code>do</code> block.</p> <p>What is the correct syntax? </p> <p>If you could correct my example and explain it that would be the best.</p> <pre><code>module Main where main = do putStrLn "This is a test" s &lt;- foo putStrLn s foo = do args &lt;- getArgs return case args of [] -&gt; "No Args" [s]-&gt; "Some Args" </code></pre> <p>A little update. My source file was a mix of spaces and tabs and it was causing all kinds of problems. Just a tip for any one else starting in Haskell. If you are having problems check for tabs and spaces in your source code.</p>
[ { "answer_id": 156050, "author": "wnoise", "author_id": 15464, "author_profile": "https://Stackoverflow.com/users/15464", "pm_score": 6, "selected": true, "text": "<p>return is an (overloaded) function, and it's not expecting its first argument to be a keyword. You can either parenthesize:</p>\n\n<pre><code>module Main where \nimport System(getArgs)\n\nmain = do \n putStrLn \"This is a test\"\n s &lt;- foo\n putStrLn s \n\nfoo = do\n args &lt;- getArgs \n return (case args of\n [] -&gt; \"No Args\"\n [s]-&gt; \"Some Args\")\n</code></pre>\n\n<p>or use the handy application operator ($):</p>\n\n<pre><code>foo = do\n args &lt;- getArgs \n return $ case args of\n [] -&gt; \"No Args\"\n [s]-&gt; \"Some Args\"\n</code></pre>\n\n<p>Stylewise, I'd break it out into another function:</p>\n\n<pre><code>foo = do\n args &lt;- getArgs \n return (has_args args)\n\nhas_args [] = \"No Args\"\nhas_args _ = \"Some Args\"\n</code></pre>\n\n<p>but you still need to parenthesize or use ($), because return takes one argument, and function application is the highest precedence.</p>\n" }, { "answer_id": 156459, "author": "Peter Burns", "author_id": 101, "author_profile": "https://Stackoverflow.com/users/101", "pm_score": 4, "selected": false, "text": "<p>Equivalently:</p>\n\n<pre><code>foo = do\n args &lt;- getArgs \n case args of\n [] -&gt; return \"No Args\"\n [s]-&gt; return \"Some Args\"\n</code></pre>\n\n<p>It's probably preferable to do as wnoise suggests, but this might help someone understand a bit better.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8965/" ]
I can't quite figure out this syntax problem with a `case` expression in a `do` block. What is the correct syntax? If you could correct my example and explain it that would be the best. ``` module Main where main = do putStrLn "This is a test" s <- foo putStrLn s foo = do args <- getArgs return case args of [] -> "No Args" [s]-> "Some Args" ``` A little update. My source file was a mix of spaces and tabs and it was causing all kinds of problems. Just a tip for any one else starting in Haskell. If you are having problems check for tabs and spaces in your source code.
return is an (overloaded) function, and it's not expecting its first argument to be a keyword. You can either parenthesize: ``` module Main where import System(getArgs) main = do putStrLn "This is a test" s <- foo putStrLn s foo = do args <- getArgs return (case args of [] -> "No Args" [s]-> "Some Args") ``` or use the handy application operator ($): ``` foo = do args <- getArgs return $ case args of [] -> "No Args" [s]-> "Some Args" ``` Stylewise, I'd break it out into another function: ``` foo = do args <- getArgs return (has_args args) has_args [] = "No Args" has_args _ = "Some Args" ``` but you still need to parenthesize or use ($), because return takes one argument, and function application is the highest precedence.
156,046
<p>I'm using a Form to show notifications (it appears at the bottom right of the screen), but when I show this form it steals the focus from the main Form. Is there a way to show this "notification" form without stealing focus?</p>
[ { "answer_id": 156067, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 3, "selected": false, "text": "<p>Doing this seems like a hack, but it seems to work:</p>\n\n<pre><code>this.TopMost = true; // as a result the form gets thrown to the front\nthis.TopMost = false; // but we don't actually want our form to always be on top\n</code></pre>\n\n<p>Edit: Note, this merely raises an already created form without stealing focus.</p>\n" }, { "answer_id": 156078, "author": "Alex Lyman", "author_id": 5897, "author_profile": "https://Stackoverflow.com/users/5897", "pm_score": 4, "selected": false, "text": "<p>If you're willing to use <a href=\"http://en.wikipedia.org/wiki/Windows_API\" rel=\"nofollow noreferrer\">Win32</a> <a href=\"http://en.wikipedia.org/wiki/Platform_Invocation_Services\" rel=\"nofollow noreferrer\">P/Invoke</a>, then you can use the <a href=\"http://www.pinvoke.net/default.aspx/user32/ShowWindow.html\" rel=\"nofollow noreferrer\">ShowWindow</a> method (the first code sample does exactly what you want).</p>\n" }, { "answer_id": 156082, "author": "Fry", "author_id": 23553, "author_profile": "https://Stackoverflow.com/users/23553", "pm_score": -1, "selected": false, "text": "<p>When you create a new form using </p>\n\n<pre><code>Form f = new Form();\nf.ShowDialog();\n</code></pre>\n\n<p>it steals focus because your code can't continue executing on the main form until this form is closed.</p>\n\n<p>The exception is by using threading to create a new form then Form.Show(). Make sure the thread is globally visible though, because if you declare it within a function, as soon as your function exits, your thread will end and the form will disappear.</p>\n" }, { "answer_id": 156087, "author": "Silver Dragon", "author_id": 9440, "author_profile": "https://Stackoverflow.com/users/9440", "pm_score": 2, "selected": false, "text": "<p>You might want to consider what kind of notification you would like to display.</p>\n<p>If it's absolutely critical to let the user know about some event, using Messagebox.Show would be the recommended way, due to its nature to block any other events to the main window, until the user confirms it. Be aware of pop-up blindness, though.</p>\n<p>If it's less than critical, you might want to use an alternative way to display notifications, such as a toolbar on the bottom of the window. You wrote, that you display notifications on the bottom-right of the screen - the standard way to do this would be using a <a href=\"http://www.geekzilla.co.uk/viewBF3C2DB6-7924-4DD1-B4DE-D024AE31C6C2.htm\" rel=\"nofollow noreferrer\">balloon tip</a> with the combination of a <a href=\"https://devblogs.microsoft.com/oldnewthing/20030910-00/?p=42583\" rel=\"nofollow noreferrer\">system tray</a> icon.</p>\n" }, { "answer_id": 156117, "author": "Bob Nadler", "author_id": 2514, "author_profile": "https://Stackoverflow.com/users/2514", "pm_score": 2, "selected": false, "text": "<p>Create and start the notification Form in a separate thread and reset the focus back to your main form after the Form opens. Have the notification Form provide an OnFormOpened event that is fired from the <code>Form.Shown</code> event. Something like this:</p>\n\n<pre><code>private void StartNotfication()\n{\n Thread th = new Thread(new ThreadStart(delegate\n {\n NotificationForm frm = new NotificationForm();\n frm.OnFormOpen += NotificationOpened;\n frm.ShowDialog();\n }));\n th.Name = \"NotificationForm\";\n th.Start();\n} \n\nprivate void NotificationOpened()\n{\n this.Focus(); // Put focus back on the original calling Form\n}\n</code></pre>\n\n<p>You can also keep a handle to your NotifcationForm object around so that it can be programmatically closed by the main Form (<code>frm.Close()</code>).</p>\n\n<p>Some details are missing, but hopefully this will get you going in the right direction.</p>\n" }, { "answer_id": 156159, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 6, "selected": false, "text": "<p>Stolen from <a href=\"http://www.pinvoke.net/\" rel=\"noreferrer\">PInvoke.net</a>'s <a href=\"http://www.pinvoke.net/default.aspx/user32/ShowWindow.html\" rel=\"noreferrer\">ShowWindow</a> method:</p>\n\n<pre><code>private const int SW_SHOWNOACTIVATE = 4;\nprivate const int HWND_TOPMOST = -1;\nprivate const uint SWP_NOACTIVATE = 0x0010;\n\n[DllImport(\"user32.dll\", EntryPoint = \"SetWindowPos\")]\nstatic extern bool SetWindowPos(\n int hWnd, // Window handle\n int hWndInsertAfter, // Placement-order handle\n int X, // Horizontal position\n int Y, // Vertical position\n int cx, // Width\n int cy, // Height\n uint uFlags); // Window positioning flags\n\n[DllImport(\"user32.dll\")]\nstatic extern bool ShowWindow(IntPtr hWnd, int nCmdShow);\n\nstatic void ShowInactiveTopmost(Form frm)\n{\n ShowWindow(frm.Handle, SW_SHOWNOACTIVATE);\n SetWindowPos(frm.Handle.ToInt32(), HWND_TOPMOST,\n frm.Left, frm.Top, frm.Width, frm.Height,\n SWP_NOACTIVATE);\n}\n</code></pre>\n\n<p>(Alex Lyman answered this, I'm just expanding it by directly pasting the code. Someone with edit rights can copy it over there and delete this for all I care ;) )</p>\n" }, { "answer_id": 156262, "author": "Micah", "author_id": 6209, "author_profile": "https://Stackoverflow.com/users/6209", "pm_score": 3, "selected": false, "text": "<p>The sample code from pinvoke.net in Alex Lyman/TheSoftwareJedi's answers will make the window a \"topmost\" window, meaning that you can't put it behind normal windows after it's popped up. Given Matias's description of what he wants to use this for, that could be what he wants. But if you want the user to be able to put your window behind other windows after you've popped it up, just use HWND_TOP (0) instead of HWND_TOPMOST (-1) in the sample.</p>\n" }, { "answer_id": 157843, "author": "Martin Plante", "author_id": 4898, "author_profile": "https://Stackoverflow.com/users/4898", "pm_score": 8, "selected": true, "text": "<p>Hmmm, isn't simply overriding Form.ShowWithoutActivation enough?</p>\n\n<pre><code>protected override bool ShowWithoutActivation\n{\n get { return true; }\n}\n</code></pre>\n\n<p>And if you don't want the user to click this notification window either, you can override CreateParams:</p>\n\n<pre><code>protected override CreateParams CreateParams\n{\n get\n {\n CreateParams baseParams = base.CreateParams;\n\n const int WS_EX_NOACTIVATE = 0x08000000;\n const int WS_EX_TOOLWINDOW = 0x00000080;\n baseParams.ExStyle |= ( int )( WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW );\n\n return baseParams;\n }\n}\n</code></pre>\n" }, { "answer_id": 884706, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>This works well. </p>\n\n<p>See: <a href=\"https://learn.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-openicon\" rel=\"nofollow noreferrer\">OpenIcon - MSDN</a> and <a href=\"https://learn.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-setforegroundwindow\" rel=\"nofollow noreferrer\">SetForegroundWindow - MSDN</a> </p>\n\n<pre><code>using System.Runtime.InteropServices;\n\n[DllImport(\"user32.dll\")]\nstatic extern bool OpenIcon(IntPtr hWnd);\n\n[DllImport(\"user32.dll\")]\nstatic extern bool SetForegroundWindow(IntPtr hWnd);\n\npublic static void ActivateInstance()\n{\n IntPtr hWnd = IntPtr hWnd = Process.GetCurrentProcess().MainWindowHandle;\n\n // Restore the program.\n bool result = OpenIcon(hWnd); \n // Activate the application.\n result = SetForegroundWindow(hWnd);\n\n // End the current instance of the application.\n //System.Environment.Exit(0); \n}\n</code></pre>\n" }, { "answer_id": 1472053, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I know it may sound stupid, but this worked:</p>\n\n<pre><code>this.TopMost = true;\nthis.TopMost = false;\nthis.TopMost = true;\nthis.SendToBack();\n</code></pre>\n" }, { "answer_id": 8144035, "author": "pkr", "author_id": 774828, "author_profile": "https://Stackoverflow.com/users/774828", "pm_score": 2, "selected": false, "text": "<p>I have something similar, and I simply show the notification form and then do</p>\n\n<pre><code>this.Focus();\n</code></pre>\n\n<p>to bring the focus back on the main form.</p>\n" }, { "answer_id": 9370064, "author": "Ziketo", "author_id": 1222233, "author_profile": "https://Stackoverflow.com/users/1222233", "pm_score": 3, "selected": false, "text": "<p>In WPF you can solve it like this:</p>\n\n<p>In the window put these attributes: </p>\n\n<pre><code>&lt;Window\n x:Class=\"myApplication.winNotification\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Title=\"Notification Popup\" Width=\"300\" SizeToContent=\"Height\"\n WindowStyle=\"None\" AllowsTransparency=\"True\" Background=\"Transparent\" ShowInTaskbar=\"False\" Topmost=\"True\" Focusable=\"False\" ShowActivated=\"False\" &gt;\n&lt;/Window&gt;\n</code></pre>\n\n<p>The last one attribute is the one you need ShowActivated=\"False\".</p>\n" }, { "answer_id": 13790153, "author": "Pawel Pawlowski", "author_id": 1886141, "author_profile": "https://Stackoverflow.com/users/1886141", "pm_score": -1, "selected": false, "text": "<p>Figured it out: <code>window.WindowState = WindowState.Minimized;</code>.</p>\n" }, { "answer_id": 15271415, "author": "Meta", "author_id": 2144113, "author_profile": "https://Stackoverflow.com/users/2144113", "pm_score": 1, "selected": false, "text": "<p>You <em>can</em> handle it by logic alone too, although I have to admit that the suggestions above where you end up with a BringToFront method without actually stealing focus is the most elegant one.</p>\n\n<p>Anyhow, I ran into this and solved it by using a DateTime property to not allow further BringToFront calls if calls were made already recently.</p>\n\n<p>Assume a core class, 'Core', which handles for example three forms, 'Form1, 2, and 3'. Each form needs a DateTime property and an Activate event that call Core to bring windows to front:</p>\n\n<pre><code>internal static DateTime LastBringToFrontTime { get; set; }\n\nprivate void Form1_Activated(object sender, EventArgs e)\n{\n var eventTime = DateTime.Now;\n if ((eventTime - LastBringToFrontTime).TotalMilliseconds &gt; 500)\n Core.BringAllToFront(this);\n LastBringToFrontTime = eventTime;\n}\n</code></pre>\n\n<p>And then create the work in the Core Class:</p>\n\n<pre><code>internal static void BringAllToFront(Form inForm)\n{\n Form1.BringToFront();\n Form2.BringToFront();\n Form3.BringToFront();\n inForm.Focus();\n}\n</code></pre>\n\n<p>On a side note, if you want to restore a minimized window to its original state (not maximized), use:</p>\n\n<pre><code>inForm.WindowState = FormWindowState.Normal;\n</code></pre>\n\n<p>Again, I know this is just a patch solution in the lack of a BringToFrontWithoutFocus. It is meant as a suggestion if you want to avoid the DLL file.</p>\n" }, { "answer_id": 25219399, "author": "RenniePet", "author_id": 253938, "author_profile": "https://Stackoverflow.com/users/253938", "pm_score": 4, "selected": false, "text": "<p>This is what worked for me. It provides TopMost but without focus-stealing. </p>\n\n<pre><code> protected override bool ShowWithoutActivation\n {\n get { return true; }\n }\n\n private const int WS_EX_TOPMOST = 0x00000008;\n protected override CreateParams CreateParams\n {\n get\n {\n CreateParams createParams = base.CreateParams;\n createParams.ExStyle |= WS_EX_TOPMOST;\n return createParams;\n }\n }\n</code></pre>\n\n<p>Remember to omit setting TopMost in Visual Studio designer, or elsewhere.</p>\n\n<p>This is stolen, err, borrowed, from here (click on Workarounds):</p>\n\n<p><a href=\"https://connect.microsoft.com/VisualStudio/feedback/details/401311/showwithoutactivation-is-not-supported-with-topmost\" rel=\"noreferrer\">https://connect.microsoft.com/VisualStudio/feedback/details/401311/showwithoutactivation-is-not-supported-with-topmost</a></p>\n" }, { "answer_id": 30612891, "author": "Domi", "author_id": 4733663, "author_profile": "https://Stackoverflow.com/users/4733663", "pm_score": 1, "selected": false, "text": "<p>I don't know if this is considered as necro-posting, but this is what I did since I couln't get it working with user32's \"ShowWindow\" and \"SetWindowPos\" methods. And no, overriding \"ShowWithoutActivation\" doesn't work in this case since the new window should be always-on-top.\nAnyway, I created a helper method that takes a form as parameter; when called, it shows the form, brings it to the front and makes it TopMost without stealing the focus of the current window (apparently it does, but the user won't notice).</p>\n\n<pre><code> [DllImport(\"user32.dll\")]\n static extern IntPtr GetForegroundWindow();\n\n [DllImport(\"user32.dll\")]\n static extern IntPtr SetForegroundWindow(IntPtr hWnd);\n\n public static void ShowTopmostNoFocus(Form f)\n {\n IntPtr activeWin = GetForegroundWindow();\n\n f.Show();\n f.BringToFront();\n f.TopMost = true;\n\n if (activeWin.ToInt32() &gt; 0)\n {\n SetForegroundWindow(activeWin);\n }\n }\n</code></pre>\n" }, { "answer_id": 35929506, "author": "Steven Cvetko", "author_id": 6047481, "author_profile": "https://Stackoverflow.com/users/6047481", "pm_score": 0, "selected": false, "text": "<p>I needed to do this with my window TopMost. I implemented the PInvoke method above but found that my Load event wasn't getting called like Talha above. I finally succeeded. Maybe this will help someone. Here is my solution:</p>\n\n<pre><code> form.Visible = false;\n form.TopMost = false;\n ShowWindow(form.Handle, ShowNoActivate);\n SetWindowPos(form.Handle, HWND_TOPMOST,\n form.Left, form.Top, form.Width, form.Height,\n NoActivate);\n form.Visible = true; //So that Load event happens\n</code></pre>\n" }, { "answer_id": 69726485, "author": "Antony Cartwright", "author_id": 16692341, "author_profile": "https://Stackoverflow.com/users/16692341", "pm_score": 0, "selected": false, "text": "<p>You don't need to make it anywhere near as complicated.</p>\n<pre><code>a = new Assign_Stock(); \na.MdiParent = this.ParentForm;\na.Visible = false; //hide for a bit. \na.Show(); //show the form. Invisible form now at the top.\nthis.Focus(); //focus on this form. make old form come to the top.\na.Visible = true; //make other form visible now. Behind the main form.\n</code></pre>\n" }, { "answer_id": 70596793, "author": "lava", "author_id": 7706354, "author_profile": "https://Stackoverflow.com/users/7706354", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://i.stack.imgur.com/1Qful.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1Qful.gif\" alt=\"enter image description here\" /></a></p>\n<p><a href=\"https://github.com/lavahasif/steaaling_focuse.git\" rel=\"nofollow noreferrer\">Github Sample</a></p>\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.form.showwithoutactivation?view=windowsdesktop-6.0\" rel=\"nofollow noreferrer\">Form.ShowWithoutActivation Property</a></p>\n<p><strong>Add this in your child form class</strong></p>\n<pre class=\"lang-cs prettyprint-override\"><code> protected override bool ShowWithoutActivation\n {\n get { return true; }\n }\n</code></pre>\n<p><strong>Working Code</strong></p>\n<p><strong>Form2</strong></p>\n<pre><code> public partial class Form2 : Form\n {\n Form3 c;\n public Form2()\n {\n InitializeComponent();\n c = new Form3();\n }\n\n private void textchanged(object sender, EventArgs e)\n {\n\n\n c.ResetText(textBox1.Text.ToString());\n c.Location = new Point(this.Location.X+150, this.Location.Y);\n c .Show();\n\n//removethis\n//if mdiparent 2 add this.focus() after show form\n\n c.MdiParent = this.MdiParent;\n c.ResetText(textBox1.Text.ToString());\n c.Location = new Point(this.Location.X+150, this.Location.Y);\n c .Show();\n this.Focus();\n////-----------------\n\n\n }\n\n\n \n }\n</code></pre>\n<p><strong>Form3</strong></p>\n<pre class=\"lang-cs prettyprint-override\"><code> public partial class Form3 : Form\n {\n public Form3()\n {\n InitializeComponent();\n //ShowWithoutActivation = false;\n }\n protected override bool ShowWithoutActivation\n {\n get { return true; }\n }\n\n\n internal void ResetText(string toString)\n {\n label2.Text = toString;\n }\n\n \n }\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4386/" ]
I'm using a Form to show notifications (it appears at the bottom right of the screen), but when I show this form it steals the focus from the main Form. Is there a way to show this "notification" form without stealing focus?
Hmmm, isn't simply overriding Form.ShowWithoutActivation enough? ``` protected override bool ShowWithoutActivation { get { return true; } } ``` And if you don't want the user to click this notification window either, you can override CreateParams: ``` protected override CreateParams CreateParams { get { CreateParams baseParams = base.CreateParams; const int WS_EX_NOACTIVATE = 0x08000000; const int WS_EX_TOOLWINDOW = 0x00000080; baseParams.ExStyle |= ( int )( WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW ); return baseParams; } } ```
156,051
<p>I've got a dropdown list that is being populated via a webservice using ASP>NET AJAX. On the success callback of the method in javascript, I'm populating the dropdown via a loop:</p> <pre><code>function populateDropDown(dropdownId, list, enable, showCount) { var dropdown = $get(dropdownId); dropdown.options.length = 1; for (var i = 0; i &lt; list.length; i++) { var opt = document.createElement("option"); if (showCount) { opt.text = list[i].Name + ' (' + list[i].ChildCount + ')'; } else { opt.text = list[i].Name; } opt.value = list[i].Name; dropdown.options.add(opt); } dropdown.disabled = !enable; } </code></pre> <p>However when I submit the form that this control is on, the control's list is always empty on postback. How do I get the populated lists data to persist over postback?</p> <p><strong>Edit:</strong> Maybe I'm coming at this backwards. A better question would probably be, how do I populate a dropdown list from a webservice without having to use an updatepanel due to the full page lifecycle it has to run through?</p>
[ { "answer_id": 156059, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>You need to use Request.Form for this - you can't encrypt ViewState on the fly from the client - it would defeat the whole point of it :).</p>\n\n<p>Edit: Responding to your Edit :) the Page Lifecycle is the thing that allows you to use the ViewState persistence in the first place. The control tree is handled there and, well, there's just no getting around it.</p>\n\n<p>Request.Form is a perfectly viable way to do this - it will tell you the value of the selection. If you want to know all of the values, you could do some type of serialization to a hidden control.</p>\n\n<p>Ugly, yes, But that's why god (some call him ScottGu) invented ASP.NET MVC :).</p>\n" }, { "answer_id": 156065, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 3, "selected": true, "text": "<p>Although I'm not really sure how it does it the CascadingDropDown in the AJAX Control Toolkit does support this.</p>\n\n<p>This is the line that appears to do it:</p>\n\n<pre><code>AjaxControlToolkit.CascadingDropDownBehavior.callBaseMethod(this, 'set_ClientState', [ this._selectedValue+':::'+text ]);\n</code></pre>\n\n<p>But the simplest idea would be to put the selected value into a hidden input field for the postback event.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2975/" ]
I've got a dropdown list that is being populated via a webservice using ASP>NET AJAX. On the success callback of the method in javascript, I'm populating the dropdown via a loop: ``` function populateDropDown(dropdownId, list, enable, showCount) { var dropdown = $get(dropdownId); dropdown.options.length = 1; for (var i = 0; i < list.length; i++) { var opt = document.createElement("option"); if (showCount) { opt.text = list[i].Name + ' (' + list[i].ChildCount + ')'; } else { opt.text = list[i].Name; } opt.value = list[i].Name; dropdown.options.add(opt); } dropdown.disabled = !enable; } ``` However when I submit the form that this control is on, the control's list is always empty on postback. How do I get the populated lists data to persist over postback? **Edit:** Maybe I'm coming at this backwards. A better question would probably be, how do I populate a dropdown list from a webservice without having to use an updatepanel due to the full page lifecycle it has to run through?
Although I'm not really sure how it does it the CascadingDropDown in the AJAX Control Toolkit does support this. This is the line that appears to do it: ``` AjaxControlToolkit.CascadingDropDownBehavior.callBaseMethod(this, 'set_ClientState', [ this._selectedValue+':::'+text ]); ``` But the simplest idea would be to put the selected value into a hidden input field for the postback event.
156,084
<p>Using VBA i have a set of functions that return an <code>ADODB.Recordset</code> where all the columns as <code>adVarChar</code>. Unfortunately this means numerics get sorted as text. So 1,7,16,22 becomes 1,16,22,7</p> <p>Is there any methods that can sort numerics as text columns without resorting to changing the type of the column?</p> <pre><code>Sub TestSortVarChar() Dim strBefore, strAfter As String Dim r As ADODB.RecordSet Set r = New ADODB.RecordSet r.Fields.Append "ID", adVarChar, 100 r.Fields.Append "Field1", adVarChar, 100 r.Open r.AddNew r.Fields("ID") = "1" r.Fields("Field1") = "A" r.AddNew r.Fields("ID") = "7" r.Fields("Field1") = "B" r.AddNew r.Fields("ID") = "16" r.Fields("Field1") = "C" r.AddNew r.Fields("ID") = "22" r.Fields("Field1") = "D" r.MoveFirst Do Until r.EOF strBefore = strBefore &amp; r.Fields("ID") &amp; " " &amp; r.Fields("Field1") &amp; vbCrLf r.MoveNext Loop r.Sort = "[ID] ASC" r.MoveFirst Do Until r.EOF strAfter = strAfter &amp; r.Fields("ID") &amp; " " &amp; r.Fields("Field1") &amp; vbCrLf r.MoveNext Loop MsgBox strBefore &amp; vbCrLf &amp; vbCrLf &amp; strAfter End Sub </code></pre> <p>NB: I am using Project 2003 and Excel 2003 and referencing <strong>Microsoft ActiveX DataObject 2.8 Library</strong></p>
[ { "answer_id": 156104, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 3, "selected": true, "text": "<p>Left pad with Zeros with at least as many as maximum number digits.\ne.g.</p>\n\n<p>0001\n0010\n0022\n1000</p>\n\n<p>You can use Right$() to accomplish this.</p>\n" }, { "answer_id": 157741, "author": "Chris OC", "author_id": 11041, "author_profile": "https://Stackoverflow.com/users/11041", "pm_score": 2, "selected": false, "text": "<p>Use the Val() function to sort numerically on a text column. Example:</p>\n\n<pre><code>SELECT ID, Field1\nFROM tablename\nORDER BY Val(Field1);\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4134/" ]
Using VBA i have a set of functions that return an `ADODB.Recordset` where all the columns as `adVarChar`. Unfortunately this means numerics get sorted as text. So 1,7,16,22 becomes 1,16,22,7 Is there any methods that can sort numerics as text columns without resorting to changing the type of the column? ``` Sub TestSortVarChar() Dim strBefore, strAfter As String Dim r As ADODB.RecordSet Set r = New ADODB.RecordSet r.Fields.Append "ID", adVarChar, 100 r.Fields.Append "Field1", adVarChar, 100 r.Open r.AddNew r.Fields("ID") = "1" r.Fields("Field1") = "A" r.AddNew r.Fields("ID") = "7" r.Fields("Field1") = "B" r.AddNew r.Fields("ID") = "16" r.Fields("Field1") = "C" r.AddNew r.Fields("ID") = "22" r.Fields("Field1") = "D" r.MoveFirst Do Until r.EOF strBefore = strBefore & r.Fields("ID") & " " & r.Fields("Field1") & vbCrLf r.MoveNext Loop r.Sort = "[ID] ASC" r.MoveFirst Do Until r.EOF strAfter = strAfter & r.Fields("ID") & " " & r.Fields("Field1") & vbCrLf r.MoveNext Loop MsgBox strBefore & vbCrLf & vbCrLf & strAfter End Sub ``` NB: I am using Project 2003 and Excel 2003 and referencing **Microsoft ActiveX DataObject 2.8 Library**
Left pad with Zeros with at least as many as maximum number digits. e.g. 0001 0010 0022 1000 You can use Right$() to accomplish this.
156,113
<p>I have some linq entities that inherit something like this:</p> <pre><code>public abstract class EntityBase { public int Identifier { get; } } public interface IDeviceEntity { int DeviceId { get; set; } } public abstract class DeviceEntityBase : EntityBase, IDeviceEntity { public abstract int DeviceId { get; set; } } public partial class ActualLinqGeneratedEntity : DeviceEntityBase { } </code></pre> <p>In a generic method I am querying DeviceEnityBase derived entities with:</p> <pre><code>return unitOfWork.GetRepository&lt;TEntity&gt;().FindOne(x =&gt; x.DeviceId == evt.DeviceId); </code></pre> <p>where TEntity has a contraint that is it a DeviceEntityBase. This query is always failing with an InvalidOperationException with the message "Class member DeviceEntityBase.DeviceId is unmapped". Even if I add some mapping info in the abstract base class with</p> <pre><code>[Column(Storage = "_DeviceId", DbType = "Int", Name = "DeviceId", IsDbGenerated = false, UpdateCheck = UpdateCheck.Never)] </code></pre>
[ { "answer_id": 156124, "author": "Micah", "author_id": 17744, "author_profile": "https://Stackoverflow.com/users/17744", "pm_score": 1, "selected": false, "text": "<p>This kind of heirarchial mapping isnot possible with LinqToSql. The the mapping is setup it cannot map to properties in base classes. I went around on this for a couple of months when it first came out. The best solution is to use the entity framework. It gives you much more flexibility with creating your object model. It will allow you to do exactly what your trying to do here.</p>\n\n<p>Here is some information on the entity framework: <a href=\"http://msdn.microsoft.com/en-us/library/aa697427(VS.80).aspx\" rel=\"nofollow noreferrer\">MSDN Article</a></p>\n" }, { "answer_id": 156365, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": "<p>LINQ-to-SQL has <em>some</em> support for inheritance via a discriminator (<a href=\"http://www.davidhayden.com/blog/dave/archive/2007/10/28/LINQToSQLEnumSupportExampleDiscriminatorColumnInheritanceMapping.aspx\" rel=\"nofollow noreferrer\">here</a>, <a href=\"http://weblogs.asp.net/zeeshanhirani/archive/2008/06/25/inheritance-in-linq-to-sql.aspx\" rel=\"nofollow noreferrer\">here</a>), but you can only query on classes that are defined in the LINQ model - i.e. data classes themselves, and (more perhaps importantly for this example) the query itself must be phrased in terms of data classes: although TEntity is a data class, it knows that the property here is declared on the entity base.</p>\n\n<p>One option might be dynamic expressions; it the classes themselves declared the property (i.e. lose the base class, but keep the interface) - but this isn't trivial.</p>\n\n<p>The Expression work would be something like below, noting that you might want to either pass in the string as an argument, or obtain the primary key via reflection (if it is attributed):</p>\n\n<pre><code>static Expression&lt;Func&lt;T, bool&gt;&gt; BuildWhere&lt;T&gt;(int deviceId) {\n var id = Expression.Constant(deviceId, typeof(int));\n var arg = Expression.Parameter(typeof(T), \"x\");\n var prop = Expression.Property(arg, \"DeviceId\");\n return Expression.Lambda&lt;Func&lt;T, bool&gt;&gt;(\n Expression.Equal(prop, id), arg);\n}\n</code></pre>\n" }, { "answer_id": 5070997, "author": "Shaul Behr", "author_id": 7850, "author_profile": "https://Stackoverflow.com/users/7850", "pm_score": 3, "selected": false, "text": "<p>Wow, looks like for once I may be able to one-up @MarcGravell!</p>\n\n<p>I had the same problem, then I discovered <a href=\"https://stackoverflow.com/questions/1021274/linq-to-sql-mapping-exception-when-using-abstract-base-classes/1068499#1068499\">this answer</a>, which solved the problem for me!</p>\n\n<p>In your case, you would say:</p>\n\n<pre><code>return unitOfWork.GetRepository&lt;TEntity&gt;().Select(x =&gt; x).FindOne(x =&gt; x.DeviceId == evt.DeviceId);\n</code></pre>\n\n<p>and Bob's your uncle!</p>\n" }, { "answer_id": 41870896, "author": "ViRuSTriNiTy", "author_id": 3936440, "author_profile": "https://Stackoverflow.com/users/3936440", "pm_score": 0, "selected": false, "text": "<p>Try <code>.OfType&lt;&gt;()</code> as posted here <a href=\"https://stackoverflow.com/a/17734469/3936440\">https://stackoverflow.com/a/17734469/3936440</a>, it works for me having the exact same issue.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2281/" ]
I have some linq entities that inherit something like this: ``` public abstract class EntityBase { public int Identifier { get; } } public interface IDeviceEntity { int DeviceId { get; set; } } public abstract class DeviceEntityBase : EntityBase, IDeviceEntity { public abstract int DeviceId { get; set; } } public partial class ActualLinqGeneratedEntity : DeviceEntityBase { } ``` In a generic method I am querying DeviceEnityBase derived entities with: ``` return unitOfWork.GetRepository<TEntity>().FindOne(x => x.DeviceId == evt.DeviceId); ``` where TEntity has a contraint that is it a DeviceEntityBase. This query is always failing with an InvalidOperationException with the message "Class member DeviceEntityBase.DeviceId is unmapped". Even if I add some mapping info in the abstract base class with ``` [Column(Storage = "_DeviceId", DbType = "Int", Name = "DeviceId", IsDbGenerated = false, UpdateCheck = UpdateCheck.Never)] ```
LINQ-to-SQL has *some* support for inheritance via a discriminator ([here](http://www.davidhayden.com/blog/dave/archive/2007/10/28/LINQToSQLEnumSupportExampleDiscriminatorColumnInheritanceMapping.aspx), [here](http://weblogs.asp.net/zeeshanhirani/archive/2008/06/25/inheritance-in-linq-to-sql.aspx)), but you can only query on classes that are defined in the LINQ model - i.e. data classes themselves, and (more perhaps importantly for this example) the query itself must be phrased in terms of data classes: although TEntity is a data class, it knows that the property here is declared on the entity base. One option might be dynamic expressions; it the classes themselves declared the property (i.e. lose the base class, but keep the interface) - but this isn't trivial. The Expression work would be something like below, noting that you might want to either pass in the string as an argument, or obtain the primary key via reflection (if it is attributed): ``` static Expression<Func<T, bool>> BuildWhere<T>(int deviceId) { var id = Expression.Constant(deviceId, typeof(int)); var arg = Expression.Parameter(typeof(T), "x"); var prop = Expression.Property(arg, "DeviceId"); return Expression.Lambda<Func<T, bool>>( Expression.Equal(prop, id), arg); } ```
156,114
<p>When paging through data that comes from a DB, you need to know how many pages there will be to render the page jump controls.</p> <p>Currently I do that by running the query twice, once wrapped in a <code>count()</code> to determine the total results, and a second time with a limit applied to get back just the results I need for the current page.</p> <p>This seems inefficient. Is there a better way to determine how many results would have been returned before <code>LIMIT</code> was applied?</p> <p>I am using PHP and Postgres.</p>
[ { "answer_id": 156227, "author": "Steve M", "author_id": 1693, "author_profile": "https://Stackoverflow.com/users/1693", "pm_score": -1, "selected": false, "text": "<p>Seeing as you need to know for the purpose of paging, I'd suggest running the full query once, writing the data to disk as a server-side cache, then feeding that through your paging mechanism.</p>\n\n<p>If you're running the COUNT query for the purpose of deciding whether to provide the data to the user or not (i.e. if there are > X records, give back an error), you need to stick with the COUNT approach.</p>\n" }, { "answer_id": 156259, "author": "Grey Panther", "author_id": 1265, "author_profile": "https://Stackoverflow.com/users/1265", "pm_score": 3, "selected": false, "text": "<p>As I describe <a href=\"http://hype-free.blogspot.com/2008/05/advanced-mysql-features.html\" rel=\"noreferrer\">on my blog</a>, MySQL has a feature called <a href=\"http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows\" rel=\"noreferrer\">SQL_CALC_FOUND_ROWS</a>. This removes the need to do the query twice, but it still needs to do the query in its entireity, even if the limit clause would have allowed it to stop early.</p>\n\n<p>As far as I know, there is no similar feature for PostgreSQL. One thing to watch out for when doing pagination (the most common thing for which LIMIT is used IMHO): doing an \"OFFSET 1000 LIMIT 10\" means that the DB has to fetch <em>at least</em> 1010 rows, even if it only gives you 10. A more performant way to do is to remember the value of the row you are ordering by for the previous row (the 1000th in this case) and rewrite the query like this: \"... WHERE order_row > value_of_1000_th LIMIT 10\". The advantage is that \"order_row\" is most probably indexed (if not, you've go a problem). The disadvantage being that if new elements are added between page views, this can get a little out of synch (but then again, it may not be observable by visitors and can be a big performance gain).</p>\n" }, { "answer_id": 156306, "author": "Bob Somers", "author_id": 1384, "author_profile": "https://Stackoverflow.com/users/1384", "pm_score": 2, "selected": false, "text": "<p>You could mitigate the performance penalty by not running the COUNT() query every time. Cache the number of pages for, say 5 minutes before the query is run again. Unless you're seeing a huge number of INSERTs, that should work just fine.</p>\n" }, { "answer_id": 1479370, "author": "grantwparks", "author_id": 117773, "author_profile": "https://Stackoverflow.com/users/117773", "pm_score": 0, "selected": false, "text": "<p>Since Postgres already does a certain amount of caching things, this type of method isn't as inefficient as it seems. It's definitely not doubling execution time. We have timers built into our DB layer, so I have seen the evidence.</p>\n" }, { "answer_id": 8242764, "author": "Erwin Brandstetter", "author_id": 939860, "author_profile": "https://Stackoverflow.com/users/939860", "pm_score": 8, "selected": true, "text": "\n<h3>Pure SQL</h3>\n<p>Things have changed since 2008. You can use a <a href=\"https://www.postgresql.org/docs/current/functions-window.html\" rel=\"noreferrer\">window function</a> to get the full count <em>and</em> the limited result in one query. Introduced with <a href=\"https://www.postgresql.org/docs/8.4/release-8-4.html\" rel=\"noreferrer\">PostgreSQL 8.4 in 2009</a>.</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT foo\n , <b>count(*) OVER() AS full_count</b>\nFROM bar\nWHERE &lt;some condition>\nORDER BY &lt;some col>\nLIMIT &lt;pagesize>\nOFFSET &lt;offset>;</code></pre>\n<p>Note that this <strong>can be considerably more expensive than without the total count</strong>. All rows have to be counted, and a possible shortcut taking just the top rows from a matching index may not be helpful any more.<br />\nDoesn't matter much with small tables or <code>full_count</code> &lt;= <code>OFFSET</code> + <code>LIMIT</code>. Matters for a substantially bigger <code>full_count</code>.</p>\n<p><em><strong>Corner case</strong></em>: when <code>OFFSET</code> is at least as great as the number of rows from the base query, <em><strong>no row</strong></em> is returned. So you also get no <code>full_count</code>. Possible alternative:</p>\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/28888375/run-a-query-with-a-limit-offset-and-also-get-the-total-number-of-rows/28888696#28888696\">Run a query with a LIMIT/OFFSET and also get the total number of rows</a></li>\n</ul>\n<h2>Sequence of events in a <code>SELECT</code> query</h2>\n<p>( 0. CTEs are evaluated and materialized separately. In Postgres 12 or later the planner may inline those like subqueries before going to work.) Not here.</p>\n<ol>\n<li><code>WHERE</code> clause (and <code>JOIN</code> conditions, though none in your example) filter qualifying rows from the base table(s). <strong>The rest is based on the filtered subset.</strong></li>\n</ol>\n<p>( 2. <code>GROUP BY</code> and aggregate functions would go here.) Not here.</p>\n<p>( 3. Other <code>SELECT</code> list expressions are evaluated, based on grouped / aggregated columns.) Not here.</p>\n<ol start=\"4\">\n<li><p>Window functions are applied depending on the <code>OVER</code> clause and the frame specification of the function. The simple <code>count(*) OVER()</code> is based on all qualifying rows.</p>\n</li>\n<li><p><code>ORDER BY</code></p>\n</li>\n</ol>\n<p>( 6. <code>DISTINCT</code> or <code>DISTINCT ON</code> would go here.) Not here.</p>\n<ol start=\"7\">\n<li><code>LIMIT</code> / <code>OFFSET</code> are applied based on the established order to select rows to return.</li>\n</ol>\n<p><code>LIMIT</code> / <code>OFFSET</code> becomes increasingly inefficient with a growing number of rows in the table. Consider alternative approaches if you need better performance:</p>\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/34110504/optimize-query-with-offset-on-large-table/34291099#34291099\">Optimize query with OFFSET on large table</a></li>\n</ul>\n<h3>Alternatives to get final count</h3>\n<p>There are completely different approaches to get the count of affected rows (<em><strong>not</strong></em> the full count before <code>OFFSET</code> &amp; <code>LIMIT</code> were applied). Postgres has internal bookkeeping how many rows where affected by the last SQL command. Some clients can access that information or count rows themselves (like psql).</p>\n<p>For instance, you can retrieve the number of affected rows in <strong>plpgsql</strong> immediately after executing an SQL command with:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>GET DIAGNOSTICS integer_var = ROW_COUNT;\n</code></pre>\n<p><a href=\"https://www.postgresql.org/docs/current/plpgsql-statements.html#PLPGSQL-STATEMENTS-DIAGNOSTICS\" rel=\"noreferrer\">Details in the manual.</a></p>\n<p>Or you can use <a href=\"https://secure.php.net/manual/en/function.pg-num-rows.php\" rel=\"noreferrer\"><code>pg_num_rows</code> in <strong>PHP</strong></a>. Or similar functions in other clients.</p>\n<p>Related:</p>\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/10175073/calculate-number-of-rows-affected-by-batch-query-in-postgresql/10175149\">Calculate number of rows affected by batch query in PostgreSQL</a></li>\n</ul>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20851/" ]
When paging through data that comes from a DB, you need to know how many pages there will be to render the page jump controls. Currently I do that by running the query twice, once wrapped in a `count()` to determine the total results, and a second time with a limit applied to get back just the results I need for the current page. This seems inefficient. Is there a better way to determine how many results would have been returned before `LIMIT` was applied? I am using PHP and Postgres.
### Pure SQL Things have changed since 2008. You can use a [window function](https://www.postgresql.org/docs/current/functions-window.html) to get the full count *and* the limited result in one query. Introduced with [PostgreSQL 8.4 in 2009](https://www.postgresql.org/docs/8.4/release-8-4.html). ```sql SELECT foo , **count(\*) OVER() AS full\_count** FROM bar WHERE <some condition> ORDER BY <some col> LIMIT <pagesize> OFFSET <offset>; ``` Note that this **can be considerably more expensive than without the total count**. All rows have to be counted, and a possible shortcut taking just the top rows from a matching index may not be helpful any more. Doesn't matter much with small tables or `full_count` <= `OFFSET` + `LIMIT`. Matters for a substantially bigger `full_count`. ***Corner case***: when `OFFSET` is at least as great as the number of rows from the base query, ***no row*** is returned. So you also get no `full_count`. Possible alternative: * [Run a query with a LIMIT/OFFSET and also get the total number of rows](https://stackoverflow.com/questions/28888375/run-a-query-with-a-limit-offset-and-also-get-the-total-number-of-rows/28888696#28888696) Sequence of events in a `SELECT` query -------------------------------------- ( 0. CTEs are evaluated and materialized separately. In Postgres 12 or later the planner may inline those like subqueries before going to work.) Not here. 1. `WHERE` clause (and `JOIN` conditions, though none in your example) filter qualifying rows from the base table(s). **The rest is based on the filtered subset.** ( 2. `GROUP BY` and aggregate functions would go here.) Not here. ( 3. Other `SELECT` list expressions are evaluated, based on grouped / aggregated columns.) Not here. 4. Window functions are applied depending on the `OVER` clause and the frame specification of the function. The simple `count(*) OVER()` is based on all qualifying rows. 5. `ORDER BY` ( 6. `DISTINCT` or `DISTINCT ON` would go here.) Not here. 7. `LIMIT` / `OFFSET` are applied based on the established order to select rows to return. `LIMIT` / `OFFSET` becomes increasingly inefficient with a growing number of rows in the table. Consider alternative approaches if you need better performance: * [Optimize query with OFFSET on large table](https://stackoverflow.com/questions/34110504/optimize-query-with-offset-on-large-table/34291099#34291099) ### Alternatives to get final count There are completely different approaches to get the count of affected rows (***not*** the full count before `OFFSET` & `LIMIT` were applied). Postgres has internal bookkeeping how many rows where affected by the last SQL command. Some clients can access that information or count rows themselves (like psql). For instance, you can retrieve the number of affected rows in **plpgsql** immediately after executing an SQL command with: ```sql GET DIAGNOSTICS integer_var = ROW_COUNT; ``` [Details in the manual.](https://www.postgresql.org/docs/current/plpgsql-statements.html#PLPGSQL-STATEMENTS-DIAGNOSTICS) Or you can use [`pg_num_rows` in **PHP**](https://secure.php.net/manual/en/function.pg-num-rows.php). Or similar functions in other clients. Related: * [Calculate number of rows affected by batch query in PostgreSQL](https://stackoverflow.com/questions/10175073/calculate-number-of-rows-affected-by-batch-query-in-postgresql/10175149)
156,116
<p>I'm using CSS Filters to modify images on the fly within the browser. These work perfectly in Internet Explorer, but aren't supported in Firefox.</p> <p>Does anyone know what the CSS Filter equivalent for these is for Firefox? An answer that would work cross browser (Safari, WebKit, Firefox, etc.) would be preferred.</p> <pre><code>&lt;style type="text/css"&gt; .CSSClassName {filter:Invert;} .CSSClassName {filter:Xray;} .CSSClassName {filter:Gray;} .CSSClassName {filter:FlipV;} &lt;/style&gt; </code></pre> <p>Update: I know Filter is an IE specific feature. Is there any kind of equivalent for any of these that is supported by Firefox?</p>
[ { "answer_id": 156142, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "<p>There are no equivalents in other browsers. The closest you could get is using a graphics library like Canvas and manipulating the images in it, but you'd have to write the manipulations yourself and they'd require JavaScript.</p>\n\n<hr>\n\n<p><code>filter</code> is an IE-only feature -- it is not available in any other browser.</p>\n" }, { "answer_id": 156231, "author": "Geoff", "author_id": 10427, "author_profile": "https://Stackoverflow.com/users/10427", "pm_score": 0, "selected": false, "text": "<p>None that I know of. Filter was an IE only thing and I don't think any other browser has followed with similar functionality.</p>\n\n<p>What is there a specific use case you need?</p>\n" }, { "answer_id": 156238, "author": "Steven Oxley", "author_id": 3831, "author_profile": "https://Stackoverflow.com/users/3831", "pm_score": 0, "selected": false, "text": "<p>I'm afraid that you are pretty much out of luck with most of the cross-browser <code>filter</code>-type functionality. CSS alone will not allow you to do most of these things. For example, there is no way to invert an image cross-browser just using CSS. You will have to have two different copies of the image (one inverted) or you could try using Javascript or maybe go about it a completely different way, but there is no simple solution solely in CSS.</p>\n" }, { "answer_id": 156244, "author": "superfireydave", "author_id": 20563, "author_profile": "https://Stackoverflow.com/users/20563", "pm_score": -1, "selected": false, "text": "<p>Not really, and hopefully there never will be. It's not a web standard CSS feature for the reason that you're using CSS to format the webpage, not the browser itself. The day that other web designers and developers think they should style my browser how they wish and are then do so is the day I stop visiting their pages (and I say this as a front end web guy). </p>\n" }, { "answer_id": 156464, "author": "Rudi", "author_id": 22830, "author_profile": "https://Stackoverflow.com/users/22830", "pm_score": 2, "selected": false, "text": "<p>Could you give us a concrete example of what exactly you're trying to do? You'd probably get fewer <em>\"Your brower sux\"</em> responses and more <em>\"How about trying this different approach?\"</em> ones.</p>\n\n<p>Normally CSS is used to control the look and feel of HTML content, not add effects or edit images in clever ways. What you're trying to do might be possible using javascript, but a behavior-oriented script still probably isn't very well suited for the kind of tweaking you want to do (although something like <a href=\"http://www.kurs.horsesport.pl/inne/rv2.html\" rel=\"nofollow noreferrer\">this</a> is a fun and very inefficient adventure in CSS / JS tomfoolery).</p>\n\n<p>I can't imagine a scenario when you would <strong>need</strong> the client to perform image tweaking in real-time. You could modify images server-side and simply reference these modified versions with your CSS or possibly Javascript, depending on what you're doing exactly. <a href=\"http://www.imagemagick.org/\" rel=\"nofollow noreferrer\">ImageMagick</a> is a great little command-line tool for all the image effects you would ever need, and is pretty simple to use by itself or within the server-side language of your choice. Or if you're using PHP, I believe <a href=\"http://us2.php.net/gd\" rel=\"nofollow noreferrer\">PHP's GD library</a> is pretty popular.</p>\n" }, { "answer_id": 156482, "author": "Andre Bossard", "author_id": 21027, "author_profile": "https://Stackoverflow.com/users/21027", "pm_score": 4, "selected": true, "text": "<p>Please check the <a href=\"http://www.nihilogic.dk/labs/imagefx/\" rel=\"noreferrer\">Nihilogic Javascript Image Effect Library</a>:</p>\n\n<ul>\n<li>supports IE and Fx pretty well</li>\n<li>has a lot of effects</li>\n</ul>\n\n<p>You can find many other effects in the <a href=\"http://www.netzgesta.de/cvi/\" rel=\"noreferrer\">CVI Projects</a>:</p>\n\n<ul>\n<li>they are also JS based</li>\n<li>there's a <a href=\"http://www.netzgesta.de/lab/\" rel=\"noreferrer\">Lab to experiment</a></li>\n</ul>\n\n<p>Good Luck</p>\n" }, { "answer_id": 156606, "author": "garrow", "author_id": 21095, "author_profile": "https://Stackoverflow.com/users/21095", "pm_score": 0, "selected": false, "text": "<p>There are filters, such as Gaussian Blur et al in SVG, which is supported natively by most browsers except IE.</p>\n\n<p>Pure thought experiment here, you could wrap your images in an SVG object on the fly with javascript and attempt to apply filters to them.</p>\n\n<p>I doubt this would work for background images, though perhaps with alot of clever positioning it could work.</p>\n\n<p>It's unlikely to be a realistic solution. If you don't want to permanently modify your source images, <strong>Rudi</strong> has the best answer, using server side tools to apply transformations on the fly (or cached for performance) will be the best cross browser solution.</p>\n" }, { "answer_id": 509596, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://developer.mozilla.org/en-US/docs/Applying_SVG_effects_to_HTML_content\" rel=\"nofollow noreferrer\">SVG filters applied to HTML content</a>.</p>\n\n<p>Only works in Firefox 3.1 and above, though I think Safari is heading in the same direction.</p>\n" }, { "answer_id": 26088245, "author": "aWebDeveloper", "author_id": 406659, "author_profile": "https://Stackoverflow.com/users/406659", "pm_score": 0, "selected": false, "text": "<p>This is a very very old question but css has updated to now support filters. Read more about it at</p>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/filter\" rel=\"nofollow\">https://developer.mozilla.org/en-US/docs/Web/CSS/filter</a></p>\n\n<p><strong>Syntax</strong></p>\n\n<p>With a function, use the following:</p>\n\n<pre><code>filter: &lt;filter-function&gt; [&lt;filter-function&gt;]* | none\n</code></pre>\n\n<p>For a reference to an SVG element, use the following:</p>\n\n<pre><code>filter: url(svg-url#element-id)\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7831/" ]
I'm using CSS Filters to modify images on the fly within the browser. These work perfectly in Internet Explorer, but aren't supported in Firefox. Does anyone know what the CSS Filter equivalent for these is for Firefox? An answer that would work cross browser (Safari, WebKit, Firefox, etc.) would be preferred. ``` <style type="text/css"> .CSSClassName {filter:Invert;} .CSSClassName {filter:Xray;} .CSSClassName {filter:Gray;} .CSSClassName {filter:FlipV;} </style> ``` Update: I know Filter is an IE specific feature. Is there any kind of equivalent for any of these that is supported by Firefox?
Please check the [Nihilogic Javascript Image Effect Library](http://www.nihilogic.dk/labs/imagefx/): * supports IE and Fx pretty well * has a lot of effects You can find many other effects in the [CVI Projects](http://www.netzgesta.de/cvi/): * they are also JS based * there's a [Lab to experiment](http://www.netzgesta.de/lab/) Good Luck
156,243
<p>What is the difference between the following 2 ways to allocate and init an object?</p> <pre><code>AController *tempAController = [[AController alloc] init]; self.aController = tempAController; [tempAController release]; </code></pre> <p>and</p> <pre><code>self.aController= [[AController alloc] init]; </code></pre> <p>Most of the apple example use the first method. Why would you allocate, init and object and then release immediately?</p>
[ { "answer_id": 156289, "author": "benzado", "author_id": 10947, "author_profile": "https://Stackoverflow.com/users/10947", "pm_score": 7, "selected": true, "text": "<p>Every object has a reference count. When it goes to 0, the object is deallocated.</p>\n\n<p>Assuming the property was declared as <code>@property (retain)</code>:</p>\n\n<p>Your first example, line by line:</p>\n\n<ol>\n<li>The object is created by <code>alloc</code>, it has a reference count of 1.</li>\n<li>The object is handed over to <code>self</code>'s <code>setAController:</code> method, which sends it a <code>retain</code> message (because the method doesn't know where the object is coming from), incrementing its reference count to 2.</li>\n<li>The calling code no longer needs the object itself, so it calls <code>release</code>, decrementing the reference count to 1.</li>\n</ol>\n\n<p>Your second example basically does steps 1 and 2 but not 3, so at the end the object's reference count is 2.</p>\n\n<p>The rule is that if you create an object, you are responsible for releasing it when you're done with it. In your example, the code is done with tempAController after it sets the property. It is the setter method's responsibility to call <code>retain</code> if it needs that object to stick around.</p>\n\n<p>It's important to remember that <code>self.property = foo;</code> in Objective-C is really just shorthand for <code>[self setProperty:foo];</code> and that the <code>setProperty:</code> method is going to be retaining or copying objects as needed.</p>\n\n<p>If the property was declared <code>@property (copy)</code>, then the object would have been copied instead of retained. In the first example, the original object would be released right away; in the second example, the original object's reference count would be 1 even though it should be 0. So you would still want to write your code the same way.</p>\n\n<p>If the property was declared <code>@property (assign)</code>, then <code>self</code> isn't claiming ownership of the object, and somebody else needs to retain it. In this case, the first example would be incorrect. These sorts of properties are rare, usually only used for object delegates.</p>\n" }, { "answer_id": 156516, "author": "Kendall Helmstetter Gelner", "author_id": 6330, "author_profile": "https://Stackoverflow.com/users/6330", "pm_score": 3, "selected": false, "text": "<p>Note also that your desire to cut the code down to one line is why many people use Autorelease:</p>\n\n<pre><code>self.aController = [[[AController alloc] init] autorelease];\n</code></pre>\n\n<p>Though in theory on the iPhone autorelease is somehow more expensive (never heard a clear explanation why) and thus you may want to explicitly release right after you assign the object elsewhere.</p>\n" }, { "answer_id": 159069, "author": "Ashley Clark", "author_id": 4556, "author_profile": "https://Stackoverflow.com/users/4556", "pm_score": 2, "selected": false, "text": "<p>One other thing to note is that your example depends on the @property definition of aController also.</p>\n\n<p>If it were defined as <code>@property (readwrite, retain) id aController;</code> then your example works, while if it is defined as <code>@property (readwrite, assign) id aController;</code> then the extra call to release would cause your object to be deallocated.</p>\n" }, { "answer_id": 167783, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 5, "selected": false, "text": "<p>As others have noted, the two code snippets you show are not equivalent (for memory management reasons).\nAs to why the former is chosen over the latter:</p>\n\n<p>The correct formulation of the latter would be</p>\n\n<pre><code>self.aController= [[[AController alloc] init] autorelease];\n</code></pre>\n\n<p>Compared with the former, this adds additional overhead through use of the autorelease pool, and in some circumstances will lead to the lifetime of the object being unnecessarily extended (until the autorelease pool is released) which will increase your application's memory footprint.</p>\n\n<p>The other \"possible\" implementation (depending on where the example is from) is simply:</p>\n\n<pre><code>aController = [[AController alloc] init];\n</code></pre>\n\n<p>However, setting an instance variable directly is strongly discouraged anywhere other than in an init or dealloc method. Elsewhere you should always use accessor methods.</p>\n\n<p>This brings us then to the implementation shown in sample code:</p>\n\n<pre><code>AController *tempAController = [[AController alloc] init];\nself.aController = tempAController;\n[tempAController release];\n</code></pre>\n\n<p>This follows best practice since:</p>\n\n<ul>\n<li>It avoids autorelease;</li>\n<li>It makes the memory management semantics immediately clear;</li>\n<li>It uses an accessor method to set the instance variable.</li>\n</ul>\n" }, { "answer_id": 1225254, "author": "mk12", "author_id": 148195, "author_profile": "https://Stackoverflow.com/users/148195", "pm_score": 2, "selected": false, "text": "<p>You could also do</p>\n\n<pre><code>@property (nonatomic, retain)AController *aController;\n...\nself.aController= [[AController alloc] init];\n[aController release];\n</code></pre>\n\n<p>with a retaining property, and it would function the same way, but its better to use the other way (for retaining properties) because it's less confusing, that code makes it look like you assign aController and then it gets deleted from memory, when actually it doesn't because setAController retains it.</p>\n" }, { "answer_id": 4694356, "author": "leviathan", "author_id": 121158, "author_profile": "https://Stackoverflow.com/users/121158", "pm_score": 3, "selected": false, "text": "<p>If you're using Xcode, it can help you detect such code with the static analyzer.\nJust hit Build >> Build and Analyze</p>\n\n<p><img src=\"https://i.stack.imgur.com/13KNx.png\" alt=\"alt text\"></p>\n\n<p>This will show you a very helpful message at such pieces of code.</p>\n\n<p><img src=\"https://i.stack.imgur.com/3oYsb.png\" alt=\"alt text\"></p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1987/" ]
What is the difference between the following 2 ways to allocate and init an object? ``` AController *tempAController = [[AController alloc] init]; self.aController = tempAController; [tempAController release]; ``` and ``` self.aController= [[AController alloc] init]; ``` Most of the apple example use the first method. Why would you allocate, init and object and then release immediately?
Every object has a reference count. When it goes to 0, the object is deallocated. Assuming the property was declared as `@property (retain)`: Your first example, line by line: 1. The object is created by `alloc`, it has a reference count of 1. 2. The object is handed over to `self`'s `setAController:` method, which sends it a `retain` message (because the method doesn't know where the object is coming from), incrementing its reference count to 2. 3. The calling code no longer needs the object itself, so it calls `release`, decrementing the reference count to 1. Your second example basically does steps 1 and 2 but not 3, so at the end the object's reference count is 2. The rule is that if you create an object, you are responsible for releasing it when you're done with it. In your example, the code is done with tempAController after it sets the property. It is the setter method's responsibility to call `retain` if it needs that object to stick around. It's important to remember that `self.property = foo;` in Objective-C is really just shorthand for `[self setProperty:foo];` and that the `setProperty:` method is going to be retaining or copying objects as needed. If the property was declared `@property (copy)`, then the object would have been copied instead of retained. In the first example, the original object would be released right away; in the second example, the original object's reference count would be 1 even though it should be 0. So you would still want to write your code the same way. If the property was declared `@property (assign)`, then `self` isn't claiming ownership of the object, and somebody else needs to retain it. In this case, the first example would be incorrect. These sorts of properties are rare, usually only used for object delegates.
156,256
<p>The sample below has two TextBoxes. The second TextBox has a handler for the LostFocus event which calls Clear() on itself. Changing focus between the two text boxes works fine; however, if the focus is on the second text box when the window is closed, TextBox.Clear() generates a NullReferenceException. Is this a bug in WPF? How can I easily detect this situation so I can avoid calling Clear() when the window is closing?</p> <p>Edit: Possibly relevant - The window is the application's main window. Test is not null at the time Clear() is called. The exception is thrown from somewhere within the call.</p> <pre><code>using System.Windows; namespace TextBoxClear { public partial class Window1 : Window { public Window1() { InitializeComponent(); } private void Test_LostFocus(object sender, RoutedEventArgs e) { Test.Clear(); } } } &lt;Window x:Class="TextBoxClear.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt; &lt;StackPanel&gt; &lt;TextBox /&gt; &lt;TextBox LostFocus="Test_LostFocus" Name="Test" /&gt; &lt;/StackPanel&gt; &lt;/Window&gt; </code></pre> <p>Assembly references:</p> <ul> <li>mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</li> <li>PresentationCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35</li> <li>PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35</li> <li>System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</li> <li>WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35</li> </ul>
[ { "answer_id": 156277, "author": "Jason Anderson", "author_id": 5142, "author_profile": "https://Stackoverflow.com/users/5142", "pm_score": 2, "selected": false, "text": "<p>Could the Test property be null by the time the LostFocus event is fired?</p>\n\n<p>Try:</p>\n\n<pre><code> private void Test_LostFocus(object sender, RoutedEventArgs e)\n {\n if (Test != null)\n Test.Clear();\n }\n</code></pre>\n\n<p><strong>EDIT:</strong> I'm having trouble reproducing the NullReferenceException with the code you posted. Which version of .NET are you using?</p>\n" }, { "answer_id": 156404, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Hooking LostKeyboardFocus instead of LostFocus works OK for my situation and stops the event handler throwing exceptions.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The sample below has two TextBoxes. The second TextBox has a handler for the LostFocus event which calls Clear() on itself. Changing focus between the two text boxes works fine; however, if the focus is on the second text box when the window is closed, TextBox.Clear() generates a NullReferenceException. Is this a bug in WPF? How can I easily detect this situation so I can avoid calling Clear() when the window is closing? Edit: Possibly relevant - The window is the application's main window. Test is not null at the time Clear() is called. The exception is thrown from somewhere within the call. ``` using System.Windows; namespace TextBoxClear { public partial class Window1 : Window { public Window1() { InitializeComponent(); } private void Test_LostFocus(object sender, RoutedEventArgs e) { Test.Clear(); } } } <Window x:Class="TextBoxClear.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <StackPanel> <TextBox /> <TextBox LostFocus="Test_LostFocus" Name="Test" /> </StackPanel> </Window> ``` Assembly references: * mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 * PresentationCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 * PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 * System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 * WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
Could the Test property be null by the time the LostFocus event is fired? Try: ``` private void Test_LostFocus(object sender, RoutedEventArgs e) { if (Test != null) Test.Clear(); } ``` **EDIT:** I'm having trouble reproducing the NullReferenceException with the code you posted. Which version of .NET are you using?
156,257
<p>In an AI application I am writing in C++, </p> <ol> <li>there is not much numerical computation </li> <li>there are lot of structures for which run-time polymorphism is needed </li> <li>very often, several polymorphic structures interact during computation</li> </ol> <p>In such a situation, are there any optimization techniques? While I won't care to optimize the application just now, one aspect of selecting C++ over Java for the project was to enable more leverage to optimize and to be able to use non-object oriented methods (templates, procedures, overloading). </p> <p>In particular, what are the optimization techniques related to virtual functions? Virtual functions are implemented through virtual tables in memory. Is there some way to pre-fetch these virtual tables onto L2 cache (the cost of fetching from memory/L2 cache is increasing)? </p> <p>Apart from this, are there good references for data locality techniques in C++? These techniques would reduce the wait time for data fetch into L2 cache needed for computation. </p> <p><em>Update</em>: Also see the following related forums: <a href="https://stackoverflow.com/questions/113830/performance-penalty-for-working-with-interfaces-in-c#171549">Performance Penalty for Interface</a>, <a href="https://stackoverflow.com/questions/99510/does-several-levels-of-base-classes-slow-down-a-classstruct-in-c">Several Levels of Base Classes</a> </p>
[ { "answer_id": 156263, "author": "Dark Shikari", "author_id": 11206, "author_profile": "https://Stackoverflow.com/users/11206", "pm_score": 1, "selected": false, "text": "<p>You rarely have to worry about cache in regards to such commonly used items, since they're fetched once and kept there.</p>\n\n<p>Cache is only generally an issue when dealing with large data structures that either:</p>\n\n<ol>\n<li>Are large enough and used for a very long time by a single function so that function can push everything else you need out of the cache, or</li>\n<li>Are randomly accessed enough that the data structures themselves aren't necessarily in cache when you load from them.</li>\n</ol>\n\n<p>Things like Vtables are generally not going to be a performance/cache/memory issue; usually there's only one Vtable per object type, and the object contains a pointer to the Vtable instead of the Vtable itself. So unless you have a few thousand types of objects, I don't think Vtables are going to thrash your cache.</p>\n\n<p>1), by the way, is why functions like memcpy use cache-bypassing streaming instructions like movnt(dq|q) for extremely large (multi-megabyte) data inputs.</p>\n" }, { "answer_id": 156300, "author": "nikhilbelsare", "author_id": 4705, "author_profile": "https://Stackoverflow.com/users/4705", "pm_score": 0, "selected": false, "text": "<p>If an <strong>AI</strong> application does not require great deal of number crunching, I wouldn't worry about performance disadvantage of virtual functions. There will be a marginal performance hit, only if they appear in the complex computations which are evaluated repeatedly. I don't think you can force virtual table to stay in L2 cache either. </p>\n\n<p>There are a couple of optimizations available for virtual functions,</p>\n\n<ol>\n<li>People have written compilers that resort to code analysis and transformation of the program. But, these aren't a production grade compilers. </li>\n<li>You could replace all virtual functions with equivalent \"switch...case\" blocks to call appropriate functions based on the type in the hierarchy. This way you'll get rid of compiler managed virtual table and you'll have your own virtual table in the form of switch...case block. Now, chances of your own virtual table being in the L2 cache are high as it in the code path. Remember, you'll need RTTI or your own \"typeof\" function to achieve this.</li>\n</ol>\n" }, { "answer_id": 156411, "author": "Chris Mayer", "author_id": 4121, "author_profile": "https://Stackoverflow.com/users/4121", "pm_score": 2, "selected": false, "text": "<p>Have you actually profiled and found where, and what needs optimization?</p>\n\n<p>Work on actually optimizing virtual function calls when you have found they actually are the bottleneck.</p>\n" }, { "answer_id": 156420, "author": "loudej", "author_id": 6056, "author_profile": "https://Stackoverflow.com/users/6056", "pm_score": 6, "selected": true, "text": "<p>Virtual functions are very efficient. Assuming 32 bit pointers the memory layout is approximately:</p>\n\n<pre><code>classptr -&gt; [vtable:4][classdata:x]\nvtable -&gt; [first:4][second:4][third:4][fourth:4][...]\nfirst -&gt; [code:x]\nsecond -&gt; [code:x]\n...\n</code></pre>\n\n<p>The classptr points to memory that is typically on the heap, occasionally on the stack, and starts with a four byte pointer to the vtable for that class. But the important thing to remember is the vtable itself is not allocated memory. It's a static resource and all objects of the same class type will point to the exactly the same memory location for their vtable array. Calling on different instances won't pull different memory locations into L2 cache.</p>\n\n<p>This <a href=\"http://msdn.microsoft.com/en-us/magazine/cc301398.aspx\" rel=\"noreferrer\">example from msdn</a> shows the vtable for class A with virtual func1, func2, and func3. Nothing more than 12 bytes. There is a good chance the vtables of different classes will also be physically adjacent in the compiled library (you'll want to verify this is you're especially concerned) which could increase cache efficiency microscopically.</p>\n\n<pre><code>CONST SEGMENT\n??_7A@@6B@\n DD FLAT:?func1@A@@UAEXXZ\n DD FLAT:?func2@A@@UAEXXZ\n DD FLAT:?func3@A@@UAEXXZ\nCONST ENDS\n</code></pre>\n\n<p>The other performance concern would be instruction overhead of calling through a vtable function. This is also very efficient. Nearly identical to calling a non-virtual function. Again from the <a href=\"http://msdn.microsoft.com/en-us/magazine/cc301398.aspx\" rel=\"noreferrer\">example from msdn</a>:</p>\n\n<pre><code>; A* pa;\n; pa-&gt;func3();\nmov eax, DWORD PTR _pa$[ebp]\nmov edx, DWORD PTR [eax]\nmov ecx, DWORD PTR _pa$[ebp]\ncall DWORD PTR [edx+8]\n</code></pre>\n\n<p>In this example ebp, the stack frame base pointer, has the variable <code>A* pa</code> at zero offset. The register eax is loaded with the value at location [ebp], so it has the A*, and edx is loaded with the value at location [eax], so it has class A vtable. Then ecx is loaded with [ebp], because ecx represents \"this\" it now holds the A*, and finally the call is made to the value at location [edx+8] which is the third function address in the vtable.</p>\n\n<p>If this function call was not virtual the mov eax and mov edx would not be needed, but the difference in performance would be immeasurably small.</p>\n" }, { "answer_id": 156425, "author": "iafonov", "author_id": 17308, "author_profile": "https://Stackoverflow.com/users/17308", "pm_score": 2, "selected": false, "text": "<p>You can implement polymorfism in runtime using virtual functions and in compile time by using templates. You can replace virtual functions with templates. Take a look at this article for more information - <a href=\"http://www.codeproject.com/KB/cpp/SimulationofVirtualFunc.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/cpp/SimulationofVirtualFunc.aspx</a></p>\n" }, { "answer_id": 156658, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 2, "selected": false, "text": "<p>A solution to dynamic polymorphism could be static polymmorphism, usable if your types are known at compile type: The CRTP (Curiously recurring template pattern).</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern</a></p>\n\n<p>The explanation on Wikipedia is clear enough, and perhaps It <i>could</i> help you <i>if you really determined</i> virtual method calls were source of performance bottlenecks.</p>\n" }, { "answer_id": 157025, "author": "OldMan", "author_id": 23415, "author_profile": "https://Stackoverflow.com/users/23415", "pm_score": 2, "selected": false, "text": "<p>Virtual calls do not present much greater overhead over normal functions. Although, the greatest loss is that a virtual function when called polymorphically cannot be inlined. And inlining will in a lot of situations represent some real gain in performance.</p>\n\n<p>Something You can do to prevent wastage of that facility in some situations is to declare the function inline virtual.</p>\n\n<pre><code>Class A {\n inline virtual int foo() {...}\n};\n</code></pre>\n\n<p>And when you are at a point of code you are SURE about the type of the object being called, you may make an inline call that will avoid the polymorphic system and enable inlining by the compiler. </p>\n\n<pre><code>class B : public A {\n inline virtual int foo() \n {\n //...do something different\n }\n\n void bar()\n {\n //logic...\n B::foo();\n // more logic\n }\n};\n</code></pre>\n\n<p>In this example, the call to <code>foo()</code> will be made non-polymorphic and bound to <code>B</code> implementation of <code>foo()</code>. But do it only when you know for sure what the instance type is, because the automatic polymorphism feature will be gone, and this is not very obvious for later code readers. </p>\n" }, { "answer_id": 157760, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The only optimization I can think of is Java's JIT compiler. If I understand it correctly, it monitors the calls as the code runs, and if most calls go to particular implementation only, it inserts conditional jump to implementation when the class is right. This way, most of the time, there is no vtable lookup. Of course, for the rare case when we pass a different class, vtable is still used.</p>\n\n<p>I am not aware of any C++ compiler/runtime that uses this technique.</p>\n" }, { "answer_id": 158644, "author": "Xavier Nodet", "author_id": 4177, "author_profile": "https://Stackoverflow.com/users/4177", "pm_score": 4, "selected": false, "text": "<p>Section 5.3.3 of the <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/TR18015.pdf\" rel=\"noreferrer\">draft Technical Report on C++ Performance</a> is entirely devoted to the overhead of virtual functions.</p>\n" }, { "answer_id": 211323, "author": "David Cournapeau", "author_id": 11465, "author_profile": "https://Stackoverflow.com/users/11465", "pm_score": 1, "selected": false, "text": "<p>The cost is more or less the same than normal functions nowadays for recent CPUS, but they can't be inlined. If you call the function millions times, the impact can be significant (try calling millions of times the same function, for example, once with inline once without, and you will see it can be twice slower if the function itself does something simple; this is not a theoritical case: it is quite common for a lot of numerical computation).</p>\n" }, { "answer_id": 651709, "author": "Mike Dunlavey", "author_id": 23771, "author_profile": "https://Stackoverflow.com/users/23771", "pm_score": 2, "selected": false, "text": "<p>I'm reinforcing all answers that say in effect:</p>\n\n<ul>\n<li>If you don't actually know it's a problem, any concern about fixing it is probably misplaced.</li>\n</ul>\n\n<p>What you want to know is:</p>\n\n<ul>\n<li>What fraction of execution time (when it's actually running) is spent in the process of invoking methods, and in particular, which methods are the most costly (by this measure).</li>\n</ul>\n\n<p>Some profilers can give you this information indirectly. They need to summarize at the statement level, but exclusive of the time spent in the method itself.</p>\n\n<p>My favorite technique is to just pause it a number of times under a debugger.</p>\n\n<p>If the time spent in the process of virtual function invocations is significant, like say 20%, then on the average 1 out of 5 samples will show, at the bottom of the call stack, in the disassembly window, the instructions for following the virtual function pointer.</p>\n\n<p>If you don't actually see that, it is not a problem.</p>\n\n<p>In the process, you will probably see other things higher up the call stack, that actually are not needed and could save you a lot of time.</p>\n" }, { "answer_id": 651750, "author": "MSN", "author_id": 6210, "author_profile": "https://Stackoverflow.com/users/6210", "pm_score": 2, "selected": false, "text": "<p>Virtual functions tend to be a lookup and indirection function call. On some platforms, this is fast. On others, e.g., one popular PPC architecture used in consoles, this isn't so fast.</p>\n\n<p>Optimizations usually revolve around expressing variability higher up in the callstack so that you don't need to invoke a virtual function multiple times within hotspots.</p>\n" }, { "answer_id": 651780, "author": "jalf", "author_id": 33213, "author_profile": "https://Stackoverflow.com/users/33213", "pm_score": 2, "selected": false, "text": "<p>As already stated by the other answers, the actual overhead of a virtual function call is fairly small. It may make a difference in a tight loop where it is called millions of times per second, but it's rarely a big deal.</p>\n\n<p>However, it may still have a bigger impact in that it's harder for the compiler to optimize. It can't inline the function call, because it doesn't know at compile-time which function will be called. That also makes some global optimizations harder. And how much performance does this cost you? It depends. It is usually nothing to worry about, but there are cases where it may mean a significant performance hit.</p>\n\n<p>And of course it also depends on the CPU architecture. On some, it can become quite expensive.</p>\n\n<p>But it's worth keeping in mind that any kind of runtime polymorphism carries more or less the same overhead. Implementing the same functionality via switch statements or similar, to select between a number of possible functions may not be cheaper.</p>\n\n<p>The only reliable way to optimize this would be if you could move some of the work to compile-time. If it is possible to implement part of it as static polymorphism, some speedup may be possible.</p>\n\n<p>But first, make sure you have a problem. Is the code actually too slow to be acceptable?\nSecond, find out what makes it slow through a profiler.\nAnd third, fix it.</p>\n" }, { "answer_id": 652025, "author": "Jimmy J", "author_id": 73869, "author_profile": "https://Stackoverflow.com/users/73869", "pm_score": 1, "selected": false, "text": "<p>With modern, ahead-looking, multiple-dispatching CPUs the overhead for a virtual function might well be zero. Nada. Zip.</p>\n" }, { "answer_id": 1774861, "author": "Hernán", "author_id": 48026, "author_profile": "https://Stackoverflow.com/users/48026", "pm_score": 2, "selected": false, "text": "<p>Static polymorphism, as some users answered here. For example, WTL uses this method. A clear explanation of the WTL implementation can be found at <a href=\"http://www.codeproject.com/KB/wtl/wtl4mfc1.aspx#atltemplates\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/wtl/wtl4mfc1.aspx#atltemplates</a></p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19501/" ]
In an AI application I am writing in C++, 1. there is not much numerical computation 2. there are lot of structures for which run-time polymorphism is needed 3. very often, several polymorphic structures interact during computation In such a situation, are there any optimization techniques? While I won't care to optimize the application just now, one aspect of selecting C++ over Java for the project was to enable more leverage to optimize and to be able to use non-object oriented methods (templates, procedures, overloading). In particular, what are the optimization techniques related to virtual functions? Virtual functions are implemented through virtual tables in memory. Is there some way to pre-fetch these virtual tables onto L2 cache (the cost of fetching from memory/L2 cache is increasing)? Apart from this, are there good references for data locality techniques in C++? These techniques would reduce the wait time for data fetch into L2 cache needed for computation. *Update*: Also see the following related forums: [Performance Penalty for Interface](https://stackoverflow.com/questions/113830/performance-penalty-for-working-with-interfaces-in-c#171549), [Several Levels of Base Classes](https://stackoverflow.com/questions/99510/does-several-levels-of-base-classes-slow-down-a-classstruct-in-c)
Virtual functions are very efficient. Assuming 32 bit pointers the memory layout is approximately: ``` classptr -> [vtable:4][classdata:x] vtable -> [first:4][second:4][third:4][fourth:4][...] first -> [code:x] second -> [code:x] ... ``` The classptr points to memory that is typically on the heap, occasionally on the stack, and starts with a four byte pointer to the vtable for that class. But the important thing to remember is the vtable itself is not allocated memory. It's a static resource and all objects of the same class type will point to the exactly the same memory location for their vtable array. Calling on different instances won't pull different memory locations into L2 cache. This [example from msdn](http://msdn.microsoft.com/en-us/magazine/cc301398.aspx) shows the vtable for class A with virtual func1, func2, and func3. Nothing more than 12 bytes. There is a good chance the vtables of different classes will also be physically adjacent in the compiled library (you'll want to verify this is you're especially concerned) which could increase cache efficiency microscopically. ``` CONST SEGMENT ??_7A@@6B@ DD FLAT:?func1@A@@UAEXXZ DD FLAT:?func2@A@@UAEXXZ DD FLAT:?func3@A@@UAEXXZ CONST ENDS ``` The other performance concern would be instruction overhead of calling through a vtable function. This is also very efficient. Nearly identical to calling a non-virtual function. Again from the [example from msdn](http://msdn.microsoft.com/en-us/magazine/cc301398.aspx): ``` ; A* pa; ; pa->func3(); mov eax, DWORD PTR _pa$[ebp] mov edx, DWORD PTR [eax] mov ecx, DWORD PTR _pa$[ebp] call DWORD PTR [edx+8] ``` In this example ebp, the stack frame base pointer, has the variable `A* pa` at zero offset. The register eax is loaded with the value at location [ebp], so it has the A\*, and edx is loaded with the value at location [eax], so it has class A vtable. Then ecx is loaded with [ebp], because ecx represents "this" it now holds the A\*, and finally the call is made to the value at location [edx+8] which is the third function address in the vtable. If this function call was not virtual the mov eax and mov edx would not be needed, but the difference in performance would be immeasurably small.
156,278
<p>Yet again, my teacher was unable to answer my question. I knew who may be able to...</p> <p>So, I've never really learned C. In C++, I would, obviously, use a cout statement all of the time. In a recent assignment, my teacher told us to make sure to put </p> <pre><code>setbuf( stdout , NULL ); </code></pre> <p>at the top of main() in order to get an unbuffered output, thus allowing us to see the output properly.</p> <p>My question is this: will this statement affect a cout statement, or simply a printf() statement that I call? </p> <p>Thanks in advance!</p>
[ { "answer_id": 156321, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 4, "selected": true, "text": "<p>By default, iostreams and stdio are synchronised. <a href=\"http://en.cppreference.com/w/cpp/io/ios_base/sync_with_stdio\" rel=\"nofollow noreferrer\">Reference.</a></p>\n\n<p>This doesn't mean that manually adjusting the stdio buffering is a good idea, though! You may wish to utilise <code>std::endl</code> or <code>std::flush</code> (from <code>&lt;ostream&gt;</code>), which may help you. e.g.,</p>\n\n<pre><code>std::cout &lt;&lt; \"Hello, world!\" &lt;&lt; std::endl;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>std::cout &lt;&lt; \"Hello, world!\\n\" &lt;&lt; std::flush;\n</code></pre>\n\n<p>Both of these do the same thing. (<a href=\"http://en.cppreference.com/w/cpp/io/manip/endl\" rel=\"nofollow noreferrer\"><code>std::endl</code></a> = print endline, then flush.)</p>\n" }, { "answer_id": 156413, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 3, "selected": false, "text": "<p>By default, if stdout or cout is printing to a console, the output is line buffered. This means that every newline that is printed will flush the output. You can explicitly call flush() whenever you want to override the behavior just in case say, the output is going to be redirected to a file and you want to use tail -f and need certain outputs in realtime.</p>\n\n<p>As Chris said, <a href=\"http://www.cplusplus.com/reference/iostream/ios_base/sync_with_stdio.html\" rel=\"noreferrer\">sync_with_stdio</a> should tie the unbuffered stdout with an unbuffered cout (by default), but if all you are doing is using cout, instead of using setbuf on stdout, a better option is to use <a href=\"http://www.cplusplus.com/reference/iostream/streambuf/pubsetbuf.html\" rel=\"noreferrer\">pubsetbuf</a> on the pointer returned by <a href=\"http://www.cplusplus.com/reference/iostream/ios/rdbuf.html\" rel=\"noreferrer\">rdbuf</a>. ie:</p>\n\n<pre><code>// make cout unbuffered\nstd::cout.rdbuf()-&gt;pubsetbuf(0, 0);\n</code></pre>\n\n<p>Another function that may be interesting to look at is <a href=\"http://www.cplusplus.com/reference/iostream/ios/tie.html\" rel=\"noreferrer\">tie</a>.</p>\n" }, { "answer_id": 157718, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Usually, when it's important to see the output immediately, we're talking about complex highly-reliable financial routine that must log a transaction all the way to hard drive before actually sending it to counterparty. Or, (much more common case) we want to see debug messages even when the program is crashing.</p>\n\n<p>Since you're studying, I'll assume you're dealing with the second case. In that case, my advice would be to use stderr rather than stdout. It is unbuffered by default, and you can redirect it separately from stdout, putting your output in one place and your logging in another.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/73/" ]
Yet again, my teacher was unable to answer my question. I knew who may be able to... So, I've never really learned C. In C++, I would, obviously, use a cout statement all of the time. In a recent assignment, my teacher told us to make sure to put ``` setbuf( stdout , NULL ); ``` at the top of main() in order to get an unbuffered output, thus allowing us to see the output properly. My question is this: will this statement affect a cout statement, or simply a printf() statement that I call? Thanks in advance!
By default, iostreams and stdio are synchronised. [Reference.](http://en.cppreference.com/w/cpp/io/ios_base/sync_with_stdio) This doesn't mean that manually adjusting the stdio buffering is a good idea, though! You may wish to utilise `std::endl` or `std::flush` (from `<ostream>`), which may help you. e.g., ``` std::cout << "Hello, world!" << std::endl; ``` or ``` std::cout << "Hello, world!\n" << std::flush; ``` Both of these do the same thing. ([`std::endl`](http://en.cppreference.com/w/cpp/io/manip/endl) = print endline, then flush.)
156,279
<p>The title is self explanatory. Is there a way of directly doing such kind of importing?</p>
[ { "answer_id": 156284, "author": "Levi Rosol", "author_id": 23458, "author_profile": "https://Stackoverflow.com/users/23458", "pm_score": 2, "selected": false, "text": "<p>Although my MySQL background is limited, I don't think you have much luck doing that. However, you should be able to migrate over all of your data by restoring the db to a MSSQL server, then creating a SSIS or DTS package to send your tables and data to the MySQL server.</p>\n\n<p>hope this helps</p>\n" }, { "answer_id": 156301, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 1, "selected": false, "text": "<p>I highly doubt it. You might want to use DTS/SSIS to do this as Levi says. One think that you might want to do is start the process without actually importing the data. Just do enough to get the basic table structures together. Then you are going to want to change around the resulting table structure, because whatever structure tat will likely be created will be shaky at best.</p>\n\n<p>You might also have to take this a step further and create a staging area that takes in all the data first n a string (varchar) form. Then you can create a script that does validation and conversion to get it into the \"real\" database, because the two databases don't always work well together, especially when dealing with dates.</p>\n" }, { "answer_id": 156309, "author": "CyberFonic", "author_id": 23999, "author_profile": "https://Stackoverflow.com/users/23999", "pm_score": 1, "selected": false, "text": "<p>SQL Server databases are very Microsoft proprietary. Two options I can think of are:</p>\n\n<ol>\n<li><p>Dump the database in CSV, XML or similar format that you'd then load into MySQL.</p></li>\n<li><p>Setup ODBC connection to MySQL and then using DTS transport the data. As Charles Graham has suggested, you may need to build the tables before doing this. But that's as easy as a cut and paste from SQL Enterprise Manager windows to the corresponding MySQL window.</p></li>\n</ol>\n" }, { "answer_id": 156479, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 7, "selected": true, "text": "<p>The .BAK files from SQL server are in Microsoft Tape Format (MTF) ref: <a href=\"http://www.fpns.net/willy/msbackup.htm\" rel=\"noreferrer\">http://www.fpns.net/willy/msbackup.htm</a></p>\n\n<p>The bak file will probably contain the LDF and MDF files that SQL server uses to store the database.</p>\n\n<p>You will need to use SQL server to extract these. SQL Server Express is free and will do the job.</p>\n\n<p>So, install SQL Server Express edition, and open the SQL Server Powershell. There execute <code>sqlcmd -S &lt;COMPUTERNAME&gt;\\SQLExpress</code> (whilst logged in as administrator)</p>\n\n<p>then issue the following command.</p>\n\n<pre><code>restore filelistonly from disk='c:\\temp\\mydbName-2009-09-29-v10.bak';\nGO\n</code></pre>\n\n<p>This will list the contents of the backup - what you need is the first fields that tell you the logical names - one will be the actual database and the other the log file.</p>\n\n<pre><code>RESTORE DATABASE mydbName FROM disk='c:\\temp\\mydbName-2009-09-29-v10.bak'\nWITH \n MOVE 'mydbName' TO 'c:\\temp\\mydbName_data.mdf', \n MOVE 'mydbName_log' TO 'c:\\temp\\mydbName_data.ldf';\nGO\n</code></pre>\n\n<p>At this point you have extracted the database - then install <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyID=c039a798-c57a-419e-acbc-2a332cb7f959&amp;displaylang=en\" rel=\"noreferrer\">Microsoft's \"Sql Web Data Administrator\".</a> together with <a href=\"http://www.eggheadcafe.com/articles/20040913.asp\" rel=\"noreferrer\">this export tool</a> and you will have an SQL script that contains the database.</p>\n" }, { "answer_id": 165325, "author": "Marcel", "author_id": 131, "author_profile": "https://Stackoverflow.com/users/131", "pm_score": 3, "selected": false, "text": "<p>I did not manage to find a way to do it directly.</p>\n\n<p>Instead I imported the bak file into SQL Server 2008 Express, and then used <a href=\"http://dev.mysql.com/doc/migration-toolkit/en/index.html\" rel=\"noreferrer\">MySQL Migration Toolkit</a>.</p>\n\n<p>Worked like a charm!</p>\n" }, { "answer_id": 1448045, "author": "Traveling_Monk", "author_id": 113601, "author_profile": "https://Stackoverflow.com/users/113601", "pm_score": 1, "selected": false, "text": "<p>The method I used included part of Richard Harrison's method:</p>\n\n<blockquote>\n <p>So, install SQL Server 2008 Express\n edition,</p>\n</blockquote>\n\n<p>This requires the download of the Web Platform Installer \"wpilauncher_n.exe\"\nOnce you have this installed click on the database selection ( you are also required to download Frameworks and Runtimes)</p>\n\n<p>After instalation go to the windows command prompt and:</p>\n\n<blockquote>\n <p>use sqlcmd -S \\SQLExpress (whilst\n logged in as administrator)</p>\n \n <p>then issue the following command.</p>\n \n <p>restore filelistonly from\n disk='c:\\temp\\mydbName-2009-09-29-v10.bak';\n GO This will list the contents of the\n backup - what you need is the first\n fields that tell you the logical names\n - one will be the actual database and the other the log file.</p>\n \n <p>RESTORE DATABASE mydbName FROM\n disk='c:\\temp\\mydbName-2009-09-29-v10.bak' WITH MOVE 'mydbName' TO\n 'c:\\temp\\mydbName_data.mdf', MOVE\n 'mydbName_log' TO\n 'c:\\temp\\mydbName_data.ldf'; GO</p>\n</blockquote>\n\n<p>I fired up Web Platform Installer and from the what's new tab I installed SQL Server Management Studio and browsed the db to make sure the data was there...</p>\n\n<p>At that point i tried the tool included with MSSQL \"SQL Import and Export Wizard\" but the result of the csv dump only included the column names...</p>\n\n<p>So instead I just exported results of queries like \"select * from users\" from the SQL Server Management Studio</p>\n" }, { "answer_id": 7179605, "author": "Andrew", "author_id": 561698, "author_profile": "https://Stackoverflow.com/users/561698", "pm_score": 1, "selected": false, "text": "<p>For those attempting Richard's solution above, here are some additional information that might help navigate common errors:</p>\n\n<p>1) When running restore filelistonly you may get Operating system error 5(Access is denied). If that's the case, open SQL Server Configuration Manager and change the login for SQLEXPRESS to a user that has local write privileges.</p>\n\n<p>2) @\"This will list the contents of the backup - what you need is the first fields that tell you the logical names\" - if your file lists more than two headers you will need to also account for what to do with those files in the RESTORE DATABASE command. If you don't indicate what to do with files beyond the database and the log, the system will apparently try to use the attributes listed in the .bak file. Restoring a file from someone else's environment will produce a 'The path has invalid attributes. It needs to be a directory' (as the path in question doesn't exist on your machine).\nSimply providing a MOVE statement resolves this problem. </p>\n\n<p>In my case there was a third FTData type file. The MOVE command I added:</p>\n\n<pre><code>MOVE 'mydbName_log' TO 'c:\\temp\\mydbName_data.ldf',\nMOVE 'sysft_...' TO 'c:\\temp\\other';\n</code></pre>\n\n<p>in my case I actually had to make a new directory for the third file. Initially I tried to send it to the same folder as the .mdf file but that produced a 'failed to initialize correctly' error on the third FTData file when I executed the restore.</p>\n" }, { "answer_id": 13783978, "author": "AutoCiudad", "author_id": 1758087, "author_profile": "https://Stackoverflow.com/users/1758087", "pm_score": 3, "selected": false, "text": "<p>MySql have an application to import db from microsoft sql.\nSteps: </p>\n\n<ol>\n<li>Open MySql Workbench</li>\n<li>Click on \"Database Migration\" (if it do not appear you have to install it from MySql update)</li>\n<li>Follow the Migration Task List using the simple Wizard.</li>\n</ol>\n" }, { "answer_id": 40047066, "author": "The Aelfinn", "author_id": 3923962, "author_profile": "https://Stackoverflow.com/users/3923962", "pm_score": 1, "selected": false, "text": "<p>The .bak file from SQL Server is specific to that database dialect, and not compatible with MySQL.</p>\n\n<p>Try using <a href=\"https://github.com/seanharr11/etlalchemy\" rel=\"nofollow\">etlalchemy</a> to migrate your SQL Server database into MySQL. It is an open-sourced tool that I created to facilitate easy migrations between different RDBMS's. </p>\n\n<p>Quick installation and examples are provided here on <a href=\"https://github.com/seanharr11/etlalchemy\" rel=\"nofollow\">the github page</a>, and a more detailed explanation of the project's origins can be found <a href=\"http://thelaziestprogrammer.com/sharrington/databases/migrating-between-databases-with-etlalchemy\" rel=\"nofollow\">here</a>.</p>\n" }, { "answer_id": 59558734, "author": "INDRAJITH EKANAYAKE", "author_id": 8134164, "author_profile": "https://Stackoverflow.com/users/8134164", "pm_score": 3, "selected": false, "text": "<p>In this problem, the answer is not updated in a timely. So it's happy to say that <strong>in 2020</strong> Migrating to <code>MsSQL</code> into <code>MySQL</code> is that much easy. An online converter like <a href=\"https://www.rebasedata.com/convert-bak-to-mysql-online\" rel=\"noreferrer\">RebaseData</a> will do your job with one click. You can just upload your <code>.bak</code> file which is from <code>MsSQL</code> and convert it into <code>.sql</code> format which is readable to <code>MySQL</code>.</p>\n\n<p>Additional note: <a href=\"https://www.rebasedata.com/\" rel=\"noreferrer\">This</a> can not only convert your <code>.bak</code> files but also this site is for all types of Database migrations that you want.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/131/" ]
The title is self explanatory. Is there a way of directly doing such kind of importing?
The .BAK files from SQL server are in Microsoft Tape Format (MTF) ref: <http://www.fpns.net/willy/msbackup.htm> The bak file will probably contain the LDF and MDF files that SQL server uses to store the database. You will need to use SQL server to extract these. SQL Server Express is free and will do the job. So, install SQL Server Express edition, and open the SQL Server Powershell. There execute `sqlcmd -S <COMPUTERNAME>\SQLExpress` (whilst logged in as administrator) then issue the following command. ``` restore filelistonly from disk='c:\temp\mydbName-2009-09-29-v10.bak'; GO ``` This will list the contents of the backup - what you need is the first fields that tell you the logical names - one will be the actual database and the other the log file. ``` RESTORE DATABASE mydbName FROM disk='c:\temp\mydbName-2009-09-29-v10.bak' WITH MOVE 'mydbName' TO 'c:\temp\mydbName_data.mdf', MOVE 'mydbName_log' TO 'c:\temp\mydbName_data.ldf'; GO ``` At this point you have extracted the database - then install [Microsoft's "Sql Web Data Administrator".](http://www.microsoft.com/downloads/details.aspx?FamilyID=c039a798-c57a-419e-acbc-2a332cb7f959&displaylang=en) together with [this export tool](http://www.eggheadcafe.com/articles/20040913.asp) and you will have an SQL script that contains the database.
156,280
<p>When using mercurial, I'd like to be able to diff the working copy of a file with the tip file in my default remote repository. Is there an easy way to do this?</p> <p>I know I can do an "hg incoming -p" to see the patch sets of changes coming in, but it'd be nice to just directly see the actual changes for a particular file that I'd get if I do a pull of the latest stuff (or what I might be about put push out).</p> <p>The easiest thing I can think of right now is to create a little script that takes a look at the default location in .hg/hgrc and downloads the file using curl (if it's over http, otherwise scp it over ssh, or just do a direct diff if it's on the local file system) and then to diff the working copy or the tip against that temporary copy.</p> <p>I'm trying to sell mercurial to my team, and one of my team members brought this up today as something that they're able to do easily in SVN with their GUI tools.</p>
[ { "answer_id": 156340, "author": "Lars Westergren", "author_id": 15627, "author_profile": "https://Stackoverflow.com/users/15627", "pm_score": 2, "selected": false, "text": "<p>You could try having two repositories locally - one for incoming stuff, and one for outgoing. Then you should be able to do diff with any tools. See here:</p>\n\n<p><a href=\"http://weblogs.java.net/blog/kohsuke/archive/2007/11/using_mercurial.html\" rel=\"nofollow noreferrer\">http://weblogs.java.net/blog/kohsuke/archive/2007/11/using_mercurial.html</a></p>\n" }, { "answer_id": 157642, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 2, "selected": false, "text": "<p>to expand on Lars method (for some reason comment doesn't work), you can use the <code>-R</code> option on the <code>diff</code> command to reference a local repository. That way you can use the same diff application that you've specified within <code>hg</code></p>\n" }, { "answer_id": 164566, "author": "Ted Naleid", "author_id": 8912, "author_profile": "https://Stackoverflow.com/users/8912", "pm_score": 4, "selected": true, "text": "<p>After some digging, I came across the <a href=\"https://www.mercurial-scm.org/wiki/RdiffExtension\" rel=\"nofollow noreferrer\">Rdiff extension</a> that does most of what I want it to.</p>\n\n<p>It doesn't come with mercurial, but it can be installed by cloning the repository:</p>\n\n<pre><code>hg clone http://hg.kublai.com/mercurial/extensions/rdiff \n</code></pre>\n\n<p>And then modifing your ~/.hgrc file to load the extension:</p>\n\n<pre><code>[extensions] \nrdiff=~/path/to/rdiff/repo/rdiff.py\n</code></pre>\n\n<p>It's a little quirky in that it actually modifies the existing \"hg diff\" command by detecting if the first parameter is a remote URL. If it is then it will diff that file against your tip file in your local repo (not the working copy). This as the remote repo is first in the arguments, it's the reverse of what I'd expect, but you can pass \"--reverse\" to the hg diff command to switch that around.</p>\n\n<p>I could see these being potential enhancements to the extension, but for now, I can work around them with a bash/zsh shell function in my starup file. It does a temp checkin of my working copy (held by the mercurial transaction so it can be rolled back), executes the reverse diff, and then rolls the transaction back to return things back to the way they were:</p>\n\n<pre><code>hgrdiff() {\n hg commit -m \"temp commit for remote diff\" &amp;&amp; \n hg diff --reverse http://my_hardcoded_repo $* &amp;&amp;\n hg rollback # revert the temporary commit\n}\n</code></pre>\n\n<p>And then call it with:</p>\n\n<pre><code>hgrdiff &lt;filename to diff against remote repo tip&gt;\n</code></pre>\n" }, { "answer_id": 3367041, "author": "Ton Plomp", "author_id": 47860, "author_profile": "https://Stackoverflow.com/users/47860", "pm_score": 0, "selected": false, "text": "<p>Using templates you can get a list of all changed files:</p>\n\n<pre><code>hg incoming --template {files}\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8912/" ]
When using mercurial, I'd like to be able to diff the working copy of a file with the tip file in my default remote repository. Is there an easy way to do this? I know I can do an "hg incoming -p" to see the patch sets of changes coming in, but it'd be nice to just directly see the actual changes for a particular file that I'd get if I do a pull of the latest stuff (or what I might be about put push out). The easiest thing I can think of right now is to create a little script that takes a look at the default location in .hg/hgrc and downloads the file using curl (if it's over http, otherwise scp it over ssh, or just do a direct diff if it's on the local file system) and then to diff the working copy or the tip against that temporary copy. I'm trying to sell mercurial to my team, and one of my team members brought this up today as something that they're able to do easily in SVN with their GUI tools.
After some digging, I came across the [Rdiff extension](https://www.mercurial-scm.org/wiki/RdiffExtension) that does most of what I want it to. It doesn't come with mercurial, but it can be installed by cloning the repository: ``` hg clone http://hg.kublai.com/mercurial/extensions/rdiff ``` And then modifing your ~/.hgrc file to load the extension: ``` [extensions] rdiff=~/path/to/rdiff/repo/rdiff.py ``` It's a little quirky in that it actually modifies the existing "hg diff" command by detecting if the first parameter is a remote URL. If it is then it will diff that file against your tip file in your local repo (not the working copy). This as the remote repo is first in the arguments, it's the reverse of what I'd expect, but you can pass "--reverse" to the hg diff command to switch that around. I could see these being potential enhancements to the extension, but for now, I can work around them with a bash/zsh shell function in my starup file. It does a temp checkin of my working copy (held by the mercurial transaction so it can be rolled back), executes the reverse diff, and then rolls the transaction back to return things back to the way they were: ``` hgrdiff() { hg commit -m "temp commit for remote diff" && hg diff --reverse http://my_hardcoded_repo $* && hg rollback # revert the temporary commit } ``` And then call it with: ``` hgrdiff <filename to diff against remote repo tip> ```
156,292
<p>I'm a bit of a DI newbie, so forgive me if this is the wrong approach or a silly question.</p> <p>Let's say I have a form which creates/updates an order, and I know it's going to need to retrieve a list of products and customers to display. I want to pass in the Order object that it's editing, but I also want to inject the ProductsService and CustomersService as dependencies. </p> <p>So I will want my IoC container (whichever one I go with) to supply the services, but it'll be up to the calling code to supply the Order object to edit.</p> <p>Should I declare the constructor as taking the Order object as the first parameter and the ProductsService and CustomersService after that, eg:</p> <pre><code>public OrderForm(Order order, ProductsService prodsSvc, CustomersService custsSvc) </code></pre> <p>... or should the dependencies come first and the Order object last, eg:</p> <pre><code>public OrderForm(ProductsService prodsSvc, CustomersService custsSvc, Order order) </code></pre> <p>Does it matter? Does it depend on which IoC container I use? Or is there a "better" way?</p>
[ { "answer_id": 156305, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 3, "selected": false, "text": "<p>Matt, you shouldn't mix normal parameters with dependencies. Since your object will be created in the internals of IoC container, how are you going to specify necessary arguments? </p>\n\n<p>Mixing dependency and normal arguments will make logic of your program more complicated.</p>\n\n<p>In this case it would be better to declare dependency properties (i.e. remove dependencies from constructor) or initialize <strong>order</strong> field after IoC constructed <strong>OrderForm</strong> and resolved it's dependencies (i.e. remove normal parameters from constructor).</p>\n\n<p>Also you can declare all of your parameters, including <strong>order</strong> as dependencies.</p>\n" }, { "answer_id": 156383, "author": "Mario", "author_id": 472, "author_profile": "https://Stackoverflow.com/users/472", "pm_score": 2, "selected": false, "text": "<p>I feel a bit uneasy about allowing an instance of OrderForm to be instantiated without the required reference to an Order instance. One reason might be that this would prevent me from doing upfront checking for null orders. Any further thoughts?</p>\n\n<p>I suppose I could take some comfort in knowing that OrderForm objects will only be instantiated by a Factory method that ensures the Order property is set after making the call to the IoC framework.</p>\n" }, { "answer_id": 156400, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 3, "selected": true, "text": "<p>I disagree with @aku's answer. </p>\n\n<p>I think what you're doing is fine and there are also other ways to do it that are no more or less right. For instance, one may question whether this object should be depending on services in the first place. </p>\n\n<p>Regardless of DI, I feel it is helpful to clarify in your mind at least the kind of state each object holds, such as the real state (Order), derived state (if any), and dependencies (services):</p>\n\n<p><a href=\"http://tech.puredanger.com/2007/09/18/spelunking/\" rel=\"nofollow noreferrer\">http://tech.puredanger.com/2007/09/18/spelunking/</a></p>\n\n<p>On any constructor or method, I prefer the real data to be passed first and dependencies or external stuff to be passed last. So in your example I'd prefer the first.</p>\n" }, { "answer_id": 63869152, "author": "Efran Cobisi", "author_id": 904178, "author_profile": "https://Stackoverflow.com/users/904178", "pm_score": 0, "selected": false, "text": "<p>I am just a bit late to the party, but I would suggest using a factory in this case: the factory constructor would take the required <code>*Service</code> dependencies which the DI system would resolve and inject, while its <code>Build()</code> method would accept any additional state parameter - like <code>Order</code>. The factory would be, of course, registered itself in the DI system and would play just nicely with it.</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>public class OrderFormFactory\n{\n private readonly ProductsService _prodsSvc;\n private readonly CustomersService _custsSvc;\n\n public OrderFormFactory(ProductsService prodsSvc, CustomersService custsSvc)\n {\n _prodsService = prodsService ?? throw new ArgumentNullException(nameof(prodsService));\n _custsSvc = custsSvc ?? throw new ArgumentNullException(nameof(custsSvc));\n }\n\n public OrderForm Build(Order order)\n {\n // TODO: Any additional logic\n\n return new OrderForm(_prodsService, _custsSvc, order);\n }\n}\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615/" ]
I'm a bit of a DI newbie, so forgive me if this is the wrong approach or a silly question. Let's say I have a form which creates/updates an order, and I know it's going to need to retrieve a list of products and customers to display. I want to pass in the Order object that it's editing, but I also want to inject the ProductsService and CustomersService as dependencies. So I will want my IoC container (whichever one I go with) to supply the services, but it'll be up to the calling code to supply the Order object to edit. Should I declare the constructor as taking the Order object as the first parameter and the ProductsService and CustomersService after that, eg: ``` public OrderForm(Order order, ProductsService prodsSvc, CustomersService custsSvc) ``` ... or should the dependencies come first and the Order object last, eg: ``` public OrderForm(ProductsService prodsSvc, CustomersService custsSvc, Order order) ``` Does it matter? Does it depend on which IoC container I use? Or is there a "better" way?
I disagree with @aku's answer. I think what you're doing is fine and there are also other ways to do it that are no more or less right. For instance, one may question whether this object should be depending on services in the first place. Regardless of DI, I feel it is helpful to clarify in your mind at least the kind of state each object holds, such as the real state (Order), derived state (if any), and dependencies (services): <http://tech.puredanger.com/2007/09/18/spelunking/> On any constructor or method, I prefer the real data to be passed first and dependencies or external stuff to be passed last. So in your example I'd prefer the first.
156,329
<p>I need to pad numbers with leading zeros (total 8 digits) for display. I'm using oracle.</p> <pre><code>select to_char(1011,'00000000') OPE_NO from dual; select length(to_char(1011,'00000000')) OPE_NO from dual; </code></pre> <p>Instead of '00001011' I get ' 00001011'. Why do I get an extra leading blank space? What is the correct number formatting string to accomplish this?</p> <p>P.S. I realise I can just use <code>trim()</code>, but I want to understand number formatting better.</p> <p>@Eddie: I already read the documentation. And yet I still don't understand how to get rid of the leading whitespace. </p> <p>@David: So does that mean there's no way but to use <code>trim()</code>?</p>
[ { "answer_id": 156361, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 3, "selected": false, "text": "<p>From that same <a href=\"http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/sql_elements004.htm#SQLRF00211\" rel=\"nofollow noreferrer\">documentation</a> mentioned by <a href=\"https://stackoverflow.com/questions/156329/unwanted-leading-blank-space-on-oracle-number-format#156351\">EddieAwad</a>:</p>\n\n<blockquote>\n <p>Negative return values automatically\n contain a leading negative sign and\n positive values automatically contain\n a leading space unless the format\n model contains the MI, S, or PR format\n element.</p>\n</blockquote>\n\n<hr>\n\n<p><strong>EDIT</strong>: The right way is to use the FM modifier, as answered by Steve Bosman. Read the section about <a href=\"http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/sql_elements004.htm#i170559\" rel=\"nofollow noreferrer\">Format Model Modifiers</a> for more info.</p>\n" }, { "answer_id": 156670, "author": "Steve Bosman", "author_id": 4389, "author_profile": "https://Stackoverflow.com/users/4389", "pm_score": 6, "selected": true, "text": "<p>Use FM (Fill Mode), e.g. </p>\n\n<p><code>select to_char(1011,'FM00000000') OPE_NO from dual;</code> </p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3751/" ]
I need to pad numbers with leading zeros (total 8 digits) for display. I'm using oracle. ``` select to_char(1011,'00000000') OPE_NO from dual; select length(to_char(1011,'00000000')) OPE_NO from dual; ``` Instead of '00001011' I get ' 00001011'. Why do I get an extra leading blank space? What is the correct number formatting string to accomplish this? P.S. I realise I can just use `trim()`, but I want to understand number formatting better. @Eddie: I already read the documentation. And yet I still don't understand how to get rid of the leading whitespace. @David: So does that mean there's no way but to use `trim()`?
Use FM (Fill Mode), e.g. `select to_char(1011,'FM00000000') OPE_NO from dual;`
156,330
<p>I'm just trying to time a piece of code. The pseudocode looks like:</p> <pre><code>start = get_ticks() do_long_code() print "It took " + (get_ticks() - start) + " seconds." </code></pre> <p>How does this look in Python?</p> <p>More specifically, how do I get the number of ticks since midnight (or however Python organizes that timing)?</p>
[ { "answer_id": 156335, "author": "blackwing", "author_id": 9107, "author_profile": "https://Stackoverflow.com/users/9107", "pm_score": 5, "selected": false, "text": "<p>What you need is <code>time()</code> function from <code>time</code> module:</p>\n\n<pre><code>import time\nstart = time.time()\ndo_long_code()\nprint \"it took\", time.time() - start, \"seconds.\"\n</code></pre>\n\n<p>You can use <a href=\"http://docs.python.org/lib/module-timeit.html\" rel=\"noreferrer\">timeit</a> module for more options though.</p>\n" }, { "answer_id": 156339, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 2, "selected": false, "text": "<pre><code>import datetime\n\nstart = datetime.datetime.now()\ndo_long_code()\nfinish = datetime.datetime.now()\ndelta = finish - start\nprint delta.seconds\n</code></pre>\n\n<p>From midnight:</p>\n\n<pre><code>import datetime\n\nmidnight = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)\nnow = datetime.datetime.now()\ndelta = now - midnight\nprint delta.seconds\n</code></pre>\n" }, { "answer_id": 156342, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"http://docs.python.org/lib/module-time.html\" rel=\"nofollow noreferrer\">time module</a> in python gives you access to the clock() function, which returns time in seconds as a floating point.</p>\n\n<p>Different systems will have different accuracy based on their internal clock setup (ticks per second) but it's generally at least under 20milliseconds, and in some cases better than a few microseconds.</p>\n\n<p>-Adam</p>\n" }, { "answer_id": 157423, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 6, "selected": true, "text": "<p>In the <code>time</code> module, there are two timing functions: <code>time</code> and <code>clock</code>. <code>time</code> gives you \"wall\" time, if this is what you care about.</p>\n\n<p>However, the python <a href=\"http://docs.python.org/lib/module-time.html\" rel=\"noreferrer\">docs</a> say that <code>clock</code> should be used for benchmarking. Note that <code>clock</code> behaves different in separate systems:</p>\n\n<ul>\n<li>on MS Windows, it uses the Win32 function QueryPerformanceCounter(), with \"resolution typically better than a microsecond\". It has no special meaning, it's just a number (it starts counting the first time you call <code>clock</code> in your process).</li>\n</ul>\n\n<pre>\n # ms windows\n t0= time.clock()\n do_something()\n t= time.clock() - t0 # t is wall seconds elapsed (floating point)\n</pre>\n\n<ul>\n<li>on *nix, <code>clock</code> reports CPU time. Now, this is different, and most probably the value you want, since your program hardly ever is the only process requesting CPU time (even if you have no other processes, the kernel uses CPU time now and then). So, this number, which typically is smaller¹ than the wall time (i.e. time.time() - t0), is more meaningful when benchmarking code:</li>\n</ul>\n\n<pre>\n # linux\n t0= time.clock()\n do_something()\n t= time.clock() - t0 # t is CPU seconds elapsed (floating point)\n</pre>\n\n<p>Apart from all that, the <a href=\"http://docs.python.org/lib/module-timeit.html\" rel=\"noreferrer\">timeit</a> module has the <code>Timer</code> class that is supposed to use what's best for benchmarking from the available functionality.</p>\n\n<p>¹ unless threading gets in the way…</p>\n\n<p>² Python ≥3.3: there are <a href=\"http://www.python.org/dev/peps/pep-0418/#id18\" rel=\"noreferrer\"><code>time.perf_counter()</code> and <code>time.process_time()</code></a>. <code>perf_counter</code> is being used by the <code>timeit</code> module.</p>\n" }, { "answer_id": 13300640, "author": "leetNightshade", "author_id": 353094, "author_profile": "https://Stackoverflow.com/users/353094", "pm_score": 3, "selected": false, "text": "<p>Here's a solution that I started using recently:</p>\n\n<pre><code>class Timer:\n def __enter__(self):\n self.begin = now()\n\n def __exit__(self, type, value, traceback):\n print(format_delta(self.begin, now()))\n</code></pre>\n\n<p>You use it like this (You need at least Python 2.5):</p>\n\n<pre><code>with Timer():\n do_long_code()\n</code></pre>\n\n<p>When your code finishes, Timer automatically prints out the run time. Sweet! If I'm trying to quickly bench something in the Python Interpreter, this is the easiest way to go. </p>\n\n<p>And here's a sample implementation of 'now' and 'format_delta', though feel free to use your preferred timing and formatting method.</p>\n\n<pre><code>import datetime\n\ndef now():\n return datetime.datetime.now()\n\n# Prints one of the following formats*:\n# 1.58 days\n# 2.98 hours\n# 9.28 minutes # Not actually added yet, oops.\n# 5.60 seconds\n# 790 milliseconds\n# *Except I prefer abbreviated formats, so I print d,h,m,s, or ms. \ndef format_delta(start,end):\n\n # Time in microseconds\n one_day = 86400000000\n one_hour = 3600000000\n one_second = 1000000\n one_millisecond = 1000\n\n delta = end - start\n\n build_time_us = delta.microseconds + delta.seconds * one_second + delta.days * one_day\n\n days = 0\n while build_time_us &gt; one_day:\n build_time_us -= one_day\n days += 1\n\n if days &gt; 0:\n time_str = \"%.2fd\" % ( days + build_time_us / float(one_day) )\n else:\n hours = 0\n while build_time_us &gt; one_hour:\n build_time_us -= one_hour\n hours += 1\n if hours &gt; 0:\n time_str = \"%.2fh\" % ( hours + build_time_us / float(one_hour) )\n else:\n seconds = 0\n while build_time_us &gt; one_second:\n build_time_us -= one_second\n seconds += 1\n if seconds &gt; 0:\n time_str = \"%.2fs\" % ( seconds + build_time_us / float(one_second) )\n else:\n ms = 0\n while build_time_us &gt; one_millisecond:\n build_time_us -= one_millisecond\n ms += 1\n time_str = \"%.2fms\" % ( ms + build_time_us / float(one_millisecond) )\n return time_str\n</code></pre>\n\n<p>Please let me know if you have a preferred formatting method, or if there's an easier way to do all of this!</p>\n" }, { "answer_id": 35675299, "author": "Mark", "author_id": 723090, "author_profile": "https://Stackoverflow.com/users/723090", "pm_score": 0, "selected": false, "text": "<p>If you have many statements you want to time, you could use something like this:</p>\n\n<pre><code>class Ticker:\n def __init__(self):\n self.t = clock()\n\n def __call__(self):\n dt = clock() - self.t\n self.t = clock()\n return 1000 * dt\n</code></pre>\n\n<p>Then your code could look like:</p>\n\n<pre><code>tick = Ticker()\n# first command\nprint('first took {}ms'.format(tick())\n# second group of commands\nprint('second took {}ms'.format(tick())\n# third group of commands\nprint('third took {}ms'.format(tick())\n</code></pre>\n\n<p>That way you don't need to type <code>t = time()</code> before each block and <code>1000 * (time() - t)</code> after it, while still keeping control over formatting (though you could easily put that in <code>Ticket</code> too).</p>\n\n<p>It's a minimal gain, but I think it's kind of convenient.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/432/" ]
I'm just trying to time a piece of code. The pseudocode looks like: ``` start = get_ticks() do_long_code() print "It took " + (get_ticks() - start) + " seconds." ``` How does this look in Python? More specifically, how do I get the number of ticks since midnight (or however Python organizes that timing)?
In the `time` module, there are two timing functions: `time` and `clock`. `time` gives you "wall" time, if this is what you care about. However, the python [docs](http://docs.python.org/lib/module-time.html) say that `clock` should be used for benchmarking. Note that `clock` behaves different in separate systems: * on MS Windows, it uses the Win32 function QueryPerformanceCounter(), with "resolution typically better than a microsecond". It has no special meaning, it's just a number (it starts counting the first time you call `clock` in your process). ``` # ms windows t0= time.clock() do_something() t= time.clock() - t0 # t is wall seconds elapsed (floating point) ``` * on \*nix, `clock` reports CPU time. Now, this is different, and most probably the value you want, since your program hardly ever is the only process requesting CPU time (even if you have no other processes, the kernel uses CPU time now and then). So, this number, which typically is smaller¹ than the wall time (i.e. time.time() - t0), is more meaningful when benchmarking code: ``` # linux t0= time.clock() do_something() t= time.clock() - t0 # t is CPU seconds elapsed (floating point) ``` Apart from all that, the [timeit](http://docs.python.org/lib/module-timeit.html) module has the `Timer` class that is supposed to use what's best for benchmarking from the available functionality. ¹ unless threading gets in the way… ² Python ≥3.3: there are [`time.perf_counter()` and `time.process_time()`](http://www.python.org/dev/peps/pep-0418/#id18). `perf_counter` is being used by the `timeit` module.
156,331
<p>I was inserting data into a MS Access database using JDBC-ODBC driver. The blank mdb file was 2KB. After populating this database, the size grew to 155MB. Then I was deleting the data. But I found the size of mdb remains the same as 155MB. I don't get any errors. But is it normal this way? I would expect the file size reduces. If it is designed in this way, what is the idea behind it? Thanks</p>
[ { "answer_id": 156341, "author": "flamingLogos", "author_id": 8161, "author_profile": "https://Stackoverflow.com/users/8161", "pm_score": 4, "selected": false, "text": "<p>MS Access doesn't free up space used by records even after they are deleted. You can free the space manually when you need to or automatically each time you close the application.</p>\n\n<p>To do it manually, use the Compact and Repair utility:</p>\n\n<ol>\n<li><p>Backup your database, as there is a <a href=\"http://blogs.msdn.com/access/archive/2008/05/29/kb-article-950812-compact-and-repair-might-delete-your-database-access-2007.aspx\" rel=\"noreferrer\">bug in Access 2007</a> that may delete your database during the compacting procedure.</p></li>\n<li><p>If you are compacting a multiuser (shared) database that is located on a server or shared folder, make sure that no one else has it open.</p></li>\n<li><p>On the Tools menu, point to Database Utilities, and then click Compact and Repair Database. </p></li>\n</ol>\n\n<p>To do it automatically when you close the application:</p>\n\n<ol>\n<li><p>Open the database that you want MS Access to compact automatically.</p></li>\n<li><p>On the Tools menu, click Options, and then choose the General tab.</p></li>\n<li><p>Select the Compact On Close check box.</p></li>\n</ol>\n\n<p>After deleting the data and compacting the database don't be surprised if is still larger than 100 KB. There is a certain amount of overhead that cannot be removed after you add data the first time.</p>\n\n<p>Also, beware that AutoNumber field values behave differently than advertised after the compacting procedure: According to the MS Access 2000 documentation, if you delete records from the end of a table that has an AutoNumber field, compacting the database resets the AutoNumber value. So the AutoNumber value of the next record you add will be one greater than the AutoNumber value of the last undeleted record in the table. </p>\n\n<p>I have <em>not</em> found this to be the case: If you have 100 Autonumbered records and delete the last 50, the next AutoNumber record (according to the documentation) should be numbered \"51\". But in my experience it is numbered \"101\", instead.</p>\n" }, { "answer_id": 156346, "author": "Jon Cahill", "author_id": 10830, "author_profile": "https://Stackoverflow.com/users/10830", "pm_score": 5, "selected": false, "text": "<p>MS Access doesn't reclaim the space for records until you have compacted the database.</p>\n\n<p>This is something you should do to an access database as part of your regularly maintenance otherwise you will end up with some pretty painful problems.</p>\n\n<p>You can compact a database either through the MS Access UI (Tools -> Database Utilities -><br>\n Compact and Repair Database) of you can use the command prompt using:</p>\n\n<pre><code>msaccess.exe \"target database.accdb\" /compact \n</code></pre>\n\n<p>N.B. the /Compact switch must be after the target database</p>\n" }, { "answer_id": 874260, "author": "Oorang", "author_id": 102270, "author_profile": "https://Stackoverflow.com/users/102270", "pm_score": -1, "selected": false, "text": "<p>The first stop, as mentioned should be attempting to compact/repair the database. However you can also get some size saving past that by creating a new database and importing all of the objects from the old. Past that, converting it to an MDE should get you a hair more. As always, don't play around with your production copy. Also if you go with an MDE, make sure you have properly split the database first. (And of course keep a copy of the source MDB should you need to make modifications in the future.)</p>\n" }, { "answer_id": 2279878, "author": "Andreas", "author_id": 5776, "author_profile": "https://Stackoverflow.com/users/5776", "pm_score": 1, "selected": false, "text": "<p>You can compact the database from code using JRO. See: <a href=\"http://support.microsoft.com/kb/230501\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/230501</a></p>\n" }, { "answer_id": 6087536, "author": "janmejay kumar", "author_id": 764732, "author_profile": "https://Stackoverflow.com/users/764732", "pm_score": 2, "selected": false, "text": "<p>The first stop, as mentioned should be attempting to compact/repair the database. However you can also get some size saving past that by creating a new database and importing all of the objects from the old.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24020/" ]
I was inserting data into a MS Access database using JDBC-ODBC driver. The blank mdb file was 2KB. After populating this database, the size grew to 155MB. Then I was deleting the data. But I found the size of mdb remains the same as 155MB. I don't get any errors. But is it normal this way? I would expect the file size reduces. If it is designed in this way, what is the idea behind it? Thanks
MS Access doesn't reclaim the space for records until you have compacted the database. This is something you should do to an access database as part of your regularly maintenance otherwise you will end up with some pretty painful problems. You can compact a database either through the MS Access UI (Tools -> Database Utilities -> Compact and Repair Database) of you can use the command prompt using: ``` msaccess.exe "target database.accdb" /compact ``` N.B. the /Compact switch must be after the target database
156,360
<p>I have one thread that writes results into a Queue.</p> <p>In another thread (GUI), I periodically (in the IDLE event) check if there are results in the queue, like this:</p> <pre><code>def queue_get_all(q): items = [] while 1: try: items.append(q.get_nowait()) except Empty, e: break return items </code></pre> <p>Is this a good way to do it ? </p> <p><strong>Edit:</strong></p> <blockquote> <p>I'm asking because sometimes the waiting thread gets stuck for a few seconds without taking out new results.</p> </blockquote> <p>The "stuck" problem turned out to be because I was doing the processing in the idle event handler, without making sure that such events are actually generated by calling <code>wx.WakeUpIdle</code>, as is recommended.</p>
[ { "answer_id": 156416, "author": "fuentesjr", "author_id": 10708, "author_profile": "https://Stackoverflow.com/users/10708", "pm_score": 1, "selected": false, "text": "<p>I see you are using get_nowait() which according to the documentation, \"return[s] an item if one is immediately available, else raise the Empty exception\"</p>\n\n<p>Now, you happen to break out of the loop when an Empty exception is thrown. Thus, if there is no result immediately available in the queue, your function returns an empty items list.</p>\n\n<p>Is there a reason why you are not using the get() method instead? It may be the case that the get_nowait() fails because the queue is servicing a put() request at that same moment. </p>\n" }, { "answer_id": 156564, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 4, "selected": false, "text": "<p>If you're always pulling all available items off the queue, is there any real point in using a queue, rather than just a list with a lock? ie:</p>\n\n<pre><code>from __future__ import with_statement\nimport threading\n\nclass ItemStore(object):\n def __init__(self):\n self.lock = threading.Lock()\n self.items = []\n\n def add(self, item):\n with self.lock:\n self.items.append(item)\n\n def getAll(self):\n with self.lock:\n items, self.items = self.items, []\n return items\n</code></pre>\n\n<p>If you're also pulling them individually, and making use of the blocking behaviour for empty queues, then you should use Queue, but your use case looks much simpler, and might be better served by the above approach.</p>\n\n<p><strong>[Edit2]</strong> I'd missed the fact that you're polling the queue from an idle loop, and from your update, I see that the problem isn't related to contention, so the below approach isn't really relevant to your problem. I've left it in in case anyone finds a blocking variant of this useful:</p>\n\n<p>For cases where you do want to block until you get at least one result, you can modify the above code to wait for data to become available through being signalled by the producer thread. Eg.</p>\n\n<pre><code>class ItemStore(object):\n def __init__(self):\n self.cond = threading.Condition()\n self.items = []\n\n def add(self, item):\n with self.cond:\n self.items.append(item)\n self.cond.notify() # Wake 1 thread waiting on cond (if any)\n\n def getAll(self, blocking=False):\n with self.cond:\n # If blocking is true, always return at least 1 item\n while blocking and len(self.items) == 0:\n self.cond.wait()\n items, self.items = self.items, []\n return items\n</code></pre>\n" }, { "answer_id": 156736, "author": "Jon Cage", "author_id": 15369, "author_profile": "https://Stackoverflow.com/users/15369", "pm_score": 4, "selected": true, "text": "<p>I'd be very surprised if the <code>get_nowait()</code> call caused the pause by not returning if the list was empty.</p>\n<p>Could it be that you're posting a large number of (maybe big?) items between checks which means the receiving thread has a large amount of data to pull out of the <code>Queue</code>? You could try limiting the number you retrieve in one batch:</p>\n<pre><code>def queue_get_all(q):\n items = []\n maxItemsToRetrieve = 10\n for numOfItemsRetrieved in range(0, maxItemsToRetrieve):\n try:\n if numOfItemsRetrieved == maxItemsToRetrieve:\n break\n items.append(q.get_nowait())\n except Empty, e:\n break\n return items\n</code></pre>\n<p>This would limit the receiving thread to pulling up to 10 items at a time.</p>\n" }, { "answer_id": 25768255, "author": "Gab", "author_id": 768335, "author_profile": "https://Stackoverflow.com/users/768335", "pm_score": 4, "selected": false, "text": "<p>I think the easiest way of getting all items out of the queue is the following:</p>\n\n<pre><code>def get_all_queue_result(queue):\n\n result_list = []\n while not queue.empty():\n result_list.append(queue.get())\n\n return result_list\n</code></pre>\n" }, { "answer_id": 28571101, "author": "Wraith404", "author_id": 809268, "author_profile": "https://Stackoverflow.com/users/809268", "pm_score": 2, "selected": false, "text": "<p>If you're done writing to the queue, qsize should do the trick without needing to check the queue for each iteration.</p>\n\n<pre><code>responseList = []\nfor items in range(0, q.qsize()):\n responseList.append(q.get_nowait())\n</code></pre>\n" }, { "answer_id": 55519286, "author": "EvertW", "author_id": 1767653, "author_profile": "https://Stackoverflow.com/users/1767653", "pm_score": 3, "selected": false, "text": "<p>The simplest method is using a list comprehension:</p>\n\n<pre><code>items = [q.get() for _ in range(q.qsize())]\n</code></pre>\n\n<p>Use of the <code>range</code> function is generally frowned upon, but I haven't found a simpler method yet.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
I have one thread that writes results into a Queue. In another thread (GUI), I periodically (in the IDLE event) check if there are results in the queue, like this: ``` def queue_get_all(q): items = [] while 1: try: items.append(q.get_nowait()) except Empty, e: break return items ``` Is this a good way to do it ? **Edit:** > > I'm asking because sometimes the > waiting thread gets stuck for a few > seconds without taking out new > results. > > > The "stuck" problem turned out to be because I was doing the processing in the idle event handler, without making sure that such events are actually generated by calling `wx.WakeUpIdle`, as is recommended.
I'd be very surprised if the `get_nowait()` call caused the pause by not returning if the list was empty. Could it be that you're posting a large number of (maybe big?) items between checks which means the receiving thread has a large amount of data to pull out of the `Queue`? You could try limiting the number you retrieve in one batch: ``` def queue_get_all(q): items = [] maxItemsToRetrieve = 10 for numOfItemsRetrieved in range(0, maxItemsToRetrieve): try: if numOfItemsRetrieved == maxItemsToRetrieve: break items.append(q.get_nowait()) except Empty, e: break return items ``` This would limit the receiving thread to pulling up to 10 items at a time.
156,362
<p>Just getting my head around Ruby metaprogramming. The mixin/modules always manage to confuse me. </p> <ul> <li><strong>include</strong>: mixes in specified module methods as <strong>instance methods</strong> in the target class</li> <li><strong>extend</strong>: mixes in specified module methods as <strong>class methods</strong> in the target class</li> </ul> <p><em>So is the major difference just this or is a bigger dragon lurking?</em> e.g.</p> <pre><code>module ReusableModule def module_method puts "Module Method: Hi there!" end end class ClassThatIncludes include ReusableModule end class ClassThatExtends extend ReusableModule end puts "Include" ClassThatIncludes.new.module_method # "Module Method: Hi there!" puts "Extend" ClassThatExtends.module_method # "Module Method: Hi there!" </code></pre>
[ { "answer_id": 156659, "author": "Toby Hede", "author_id": 14971, "author_profile": "https://Stackoverflow.com/users/14971", "pm_score": 4, "selected": false, "text": "<p>That's correct.</p>\n\n<p>Behind the scenes, include is actually an alias for <strong>append_features</strong>, which (from the docs):</p>\n\n<blockquote>\n <p>Ruby's default implementation is to\n add the constants, methods, and module\n variables of this module to aModule if\n this module has not already been added\n to aModule or one of its ancestors.</p>\n</blockquote>\n" }, { "answer_id": 156927, "author": "domgblackwell", "author_id": 16954, "author_profile": "https://Stackoverflow.com/users/16954", "pm_score": 9, "selected": true, "text": "<p>What you have said is correct. However, there is more to it than that.</p>\n<p>If you have a class <code>Klazz</code> and module <code>Mod</code>, including <code>Mod</code> in <code>Klazz</code> gives instances of <code>Klazz</code> access to <code>Mod</code>'s methods. Or you can extend <code>Klazz</code> with <code>Mod</code> giving the <em>class</em> <code>Klazz</code> access to <code>Mod</code>'s methods. But you can also extend an arbitrary object with <code>o.extend Mod</code>. In this case the individual object gets <code>Mod</code>'s methods even though all other objects with the same class as <code>o</code> do not.</p>\n" }, { "answer_id": 5008349, "author": "John Douthat", "author_id": 2774, "author_profile": "https://Stackoverflow.com/users/2774", "pm_score": 9, "selected": false, "text": "<p><strong>extend</strong> - adds the specified module's methods and constants to the target's metaclass (i.e. the singleton class) \n e.g. </p>\n\n<ul>\n<li>if you call <code>Klazz.extend(Mod)</code>, now Klazz has Mod's methods (as class methods)</li>\n<li>if you call <code>obj.extend(Mod)</code>, now obj has Mod's methods (as instance methods), but no other instance of of <code>obj.class</code> has those methods added.</li>\n<li><code>extend</code> is a public method</li>\n</ul>\n\n<p><strong>include</strong> - By default, it mixes in the specified module's methods as instance methods in the target module/class. \n e.g.</p>\n\n<ul>\n<li>if you call <code>class Klazz; include Mod; end;</code>, now all instances of Klazz have access to Mod's methods (as instance methods)</li>\n<li><code>include</code> is a private method, because it's intended to be called from within the container class/module.</li>\n</ul>\n\n<p><strong>However</strong>, modules very often <em>override</em> <code>include</code>'s behavior by monkey-patching the <code>included</code> method. This is very prominent in legacy Rails code. <a href=\"http://yehudakatz.com/2009/11/12/better-ruby-idioms/\" rel=\"noreferrer\">more details from Yehuda Katz</a>. </p>\n\n<p>Further details about <code>include</code>, with its default behavior, assuming you've run the following code</p>\n\n<pre><code>class Klazz\n include Mod\nend\n</code></pre>\n\n<ul>\n<li>If Mod is already included in Klazz, or one of its ancestors, the include statement has no effect</li>\n<li>It also includes Mod's constants in Klazz, as long as they don't clash</li>\n<li>It gives Klazz access to Mod's module variables, e.g. <code>@@foo</code> or <code>@@bar</code></li>\n<li>raises ArgumentError if there are cyclic includes</li>\n<li>Attaches the module as the caller's immediate ancestor (i.e. It adds Mod to Klazz.ancestors, but Mod is not added to the chain of Klazz.superclass.superclass.superclass. So, calling <code>super</code> in Klazz#foo will check for Mod#foo before checking to Klazz's real superclass's foo method. See the RubySpec for details.).</li>\n</ul>\n\n<p>Of course, <a href=\"http://www.ruby-doc.org/core-1.9.3/\" rel=\"noreferrer\">the ruby core documentation</a> is always the best place to go for these things. <a href=\"https://en.wikipedia.org/wiki/RubySpec\" rel=\"noreferrer\">The RubySpec project</a> was also a fantastic resource, because they documented the functionality precisely.</p>\n\n<ul>\n<li><code>#include</code> <a href=\"https://github.com/ruby/rubyspec/blob/master/core/module/include_spec.rb\" rel=\"noreferrer\">RubySpec</a> <a href=\"http://www.ruby-doc.org/core-1.9.3/Module.html#method-i-include\" rel=\"noreferrer\">rubydoc</a></li>\n<li><code>#included</code> <a href=\"https://github.com/ruby/rubyspec/blob/master/core/module/included_spec.rb\" rel=\"noreferrer\">RubySpec</a> <a href=\"http://www.ruby-doc.org/core-1.9.3/Module.html#method-i-included\" rel=\"noreferrer\">rubydoc</a></li>\n<li><code>#extend</code> <a href=\"https://github.com/ruby/rubyspec/blob/master/core/kernel/extend_spec.rb\" rel=\"noreferrer\">RubySpec</a> <a href=\"http://www.ruby-doc.org/core-1.9.3/Object.html#method-i-extend\" rel=\"noreferrer\">rubydoc</a></li>\n<li><code>#extended</code> <a href=\"https://github.com/ruby/rubyspec/blob/master/core/module/extended_spec.rb\" rel=\"noreferrer\">RubySpec</a> <a href=\"http://www.ruby-doc.org/core-1.9.3/Module.html#method-i-extended\" rel=\"noreferrer\">rubydoc</a></li>\n<li><code>#extend_object</code> <a href=\"https://github.com/ruby/rubyspec/blob/master/core/module/extend_object_spec.rb\" rel=\"noreferrer\">RubySpec</a> <a href=\"http://www.ruby-doc.org/core-1.9.3/Module.html#method-i-extend_object\" rel=\"noreferrer\">rubydoc</a></li>\n<li><code>#append_features</code> <a href=\"https://github.com/ruby/rubyspec/blob/master/core/module/append_features_spec.rb\" rel=\"noreferrer\">RubySpec</a> <a href=\"http://www.ruby-doc.org/core-1.9.3/Module.html#method-i-append_features\" rel=\"noreferrer\">rubydoc</a> </li>\n</ul>\n" }, { "answer_id": 7521476, "author": "Ho-Sheng Hsiao", "author_id": 313193, "author_profile": "https://Stackoverflow.com/users/313193", "pm_score": 2, "selected": false, "text": "<p>All the other answers are good, including the tip to dig through RubySpecs:</p>\n\n<p><a href=\"https://github.com/rubyspec/rubyspec/blob/master/core/module/include_spec.rb\" rel=\"nofollow\">https://github.com/rubyspec/rubyspec/blob/master/core/module/include_spec.rb</a></p>\n\n<p><a href=\"https://github.com/rubyspec/rubyspec/blob/master/core/module/extend_object_spec.rb\" rel=\"nofollow\">https://github.com/rubyspec/rubyspec/blob/master/core/module/extend_object_spec.rb</a></p>\n\n<p>As for use cases:</p>\n\n<p>If you <em>include</em> module ReusableModule in class ClassThatIncludes, the methods, constants, classes, submodules, and other declarations gets referenced. </p>\n\n<p>If you <em>extend</em> class ClassThatExtends with module ReusableModule, then the methods and constants gets <em>copied</em>. Obviously, if you are not careful, you can waste a lot of memory by dynamically duplicating definitions.</p>\n\n<p>If you use ActiveSupport::Concern, the .included() functionality lets you rewrite the including class directly. module ClassMethods inside a Concern gets <em>extended</em> (copied) into the including class.</p>\n" }, { "answer_id": 36247164, "author": "user1136228", "author_id": 1136228, "author_profile": "https://Stackoverflow.com/users/1136228", "pm_score": 2, "selected": false, "text": "<p>I would also like to explain the mechanism as it works. If I am not right please correct.</p>\n\n<p>When we use <code>include</code> we are adding a linkage from our class to a module which contains some methods.</p>\n\n<pre><code>class A\ninclude MyMOd\nend\n\na = A.new\na.some_method\n</code></pre>\n\n<p>Objects don't have methods, only clases and modules do.\nSo when <code>a</code> receives mesage <code>some_method</code> it begin search method <code>some_method</code> in <code>a</code>'s eigen class, then in <code>A</code> class and then in linked to <code>A</code> class modules if there are some (in reverse order, last included wins).</p>\n\n<p>When we use <code>extend</code> we are adding linkage to a module in object's eigen class.\nSo if we use A.new.extend(MyMod) we are adding linkage to our module to A's instance eigen class or <code>a'</code> class.\nAnd if we use A.extend(MyMod) we are adding linkage to A(object's, classes are also objects) eigenclass <code>A'</code>.</p>\n\n<p>so method lookup path for <code>a</code> is as follows:\na => a' => linked modules to a' class => A.</p>\n\n<p>also there is a prepend method which changes lookup path:</p>\n\n<p>a => a' => prepended modulesto A => A => included module to A</p>\n\n<p>sorry for my bad english.</p>\n" }, { "answer_id": 58022371, "author": "Chintan", "author_id": 6543250, "author_profile": "https://Stackoverflow.com/users/6543250", "pm_score": 4, "selected": false, "text": "<p>When you <strong><code>include</code></strong> a module into a class, the module methods are imported as <strong>instance methods</strong>. </p>\n\n<p>However, when you <strong><code>extend</code></strong> a module into a class, the module methods are imported as <strong>class methods</strong>.</p>\n\n<p>For example, if we have a module <code>Module_test</code> defined as follows:</p>\n\n<pre><code>module Module_test\n def func\n puts \"M - in module\"\n end\nend\n</code></pre>\n\n<p>Now, for <strong><code>include</code></strong> module. If we define the class <code>A</code> as follows:</p>\n\n<pre><code>class A\n include Module_test\nend\n\na = A.new\na.func\n</code></pre>\n\n<p>The output will be: <code>M - in module</code>.</p>\n\n<p>If we replace the line <code>include Module_test</code> with <code>extend Module_test</code> and run the code again, we receive the following error: <code>undefined method 'func' for #&lt;A:instance_num&gt; (NoMethodError)</code>.</p>\n\n<p>Changing the method call <code>a.func</code> to <code>A.func</code>, the output changes to: <code>M - in module</code>.</p>\n\n<p>From the above code execution, it is clear that when we <strong><code>include</code></strong> a module, its methods become <strong>instance methods</strong> and when we <strong><code>extend</code></strong> a module, its methods become <strong>class methods</strong>.</p>\n" }, { "answer_id": 70124407, "author": "Abdullah Numan", "author_id": 4515413, "author_profile": "https://Stackoverflow.com/users/4515413", "pm_score": 1, "selected": false, "text": "<p>I came across a very useful <a href=\"https://dev.to/abbiecoghlan/ruby-modules-include-vs-extend-vs-prepend-4gmc\" rel=\"nofollow noreferrer\">article</a> that compares <code>include</code>, <code>extend</code> and <code>prepend</code> methods used <strong>inside a class</strong>:</p>\n<p><code>include</code> adds module methods as instance methods to the class, whereas <code>extend</code> adds module methods as class methods. The module being included or extended must be defined accordingly</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
Just getting my head around Ruby metaprogramming. The mixin/modules always manage to confuse me. * **include**: mixes in specified module methods as **instance methods** in the target class * **extend**: mixes in specified module methods as **class methods** in the target class *So is the major difference just this or is a bigger dragon lurking?* e.g. ``` module ReusableModule def module_method puts "Module Method: Hi there!" end end class ClassThatIncludes include ReusableModule end class ClassThatExtends extend ReusableModule end puts "Include" ClassThatIncludes.new.module_method # "Module Method: Hi there!" puts "Extend" ClassThatExtends.module_method # "Module Method: Hi there!" ```
What you have said is correct. However, there is more to it than that. If you have a class `Klazz` and module `Mod`, including `Mod` in `Klazz` gives instances of `Klazz` access to `Mod`'s methods. Or you can extend `Klazz` with `Mod` giving the *class* `Klazz` access to `Mod`'s methods. But you can also extend an arbitrary object with `o.extend Mod`. In this case the individual object gets `Mod`'s methods even though all other objects with the same class as `o` do not.
156,369
<p>It seems quite a few mainstream languages support <a href="http://en.wikipedia.org/wiki/First-class_function" rel="noreferrer">function literals</a> these days. They are also called <a href="http://en.wikipedia.org/wiki/Anonymous_function" rel="noreferrer">anonymous functions</a>, but I don't care if they have a name. The important thing is that a function literal is an expression which yields a function which hasn't already been defined elsewhere, so for example in C, <code>&amp;printf</code> doesn't count.</p> <p>EDIT to add: if you have a genuine function literal expression <code>&lt;exp&gt;</code>, you should be able to pass it to a function <code>f(&lt;exp&gt;)</code> or immediately apply it to an argument, ie. <code>&lt;exp&gt;(5)</code>. </p> <p>I'm curious which languages let you write function literals which are <em>recursive</em>. Wikipedia's "<a href="http://en.wikipedia.org/wiki/Anonymous_recursion" rel="noreferrer">anonymous recursion</a>" article doesn't give any programming examples.</p> <p>Let's use the recursive factorial function as the example.</p> <p>Here are the ones I know:</p> <ul> <li><p>JavaScript / ECMAScript can do it with <code>callee</code>:</p> <pre><code>function(n){if (n&lt;2) {return 1;} else {return n * arguments.callee(n-1);}} </code></pre></li> <li><p>it's easy in languages with <code>letrec</code>, eg Haskell (which calls it <code>let</code>):</p> <blockquote> <p><code>let fac x = if x&lt;2 then 1 else fac (x-1) * x in fac</code></p> </blockquote> <p>and there are equivalents in Lisp and Scheme. Note that the binding of <code>fac</code> is local to the expression, so the whole expression is in fact an anonymous function.</p></li> </ul> <p>Are there any others?</p>
[ { "answer_id": 156371, "author": "Torbjörn Gyllebring", "author_id": 21182, "author_profile": "https://Stackoverflow.com/users/21182", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://research.microsoft.com/fsharp/\" rel=\"nofollow noreferrer\">F#</a> has \"let rec\"</p>\n" }, { "answer_id": 156374, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "<p>Well, apart from Common Lisp (<code>labels</code>) and Scheme (<code>letrec</code>) which you've already mentioned, JavaScript also allows you to name an anonymous function:</p>\n\n<pre><code>var foo = {\"bar\": function baz() {return baz() + 1;}};\n</code></pre>\n\n<p>which can be handier than <a href=\"https://stackoverflow.com/questions/62188#71964\">using <code>callee</code></a>. (This is different from <code>function</code> in top-level; the latter would cause the name to appear in global scope too, whereas in the former case, the name appears only in the scope of the function itself.)</p>\n" }, { "answer_id": 156393, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 4, "selected": false, "text": "<p>Most languages support it through use of the <a href=\"http://en.wikipedia.org/wiki/Fixed_point_combinator#Y_combinator\" rel=\"noreferrer\">Y combinator</a>. Here's an example in Python (from the <a href=\"http://code.activestate.com/recipes/576366/\" rel=\"noreferrer\">cookbook</a>):</p>\n\n<pre><code># Define Y combinator...come on Gudio, put it in functools!\nY = lambda g: (lambda f: g(lambda arg: f(f)(arg))) (lambda f: g(lambda arg: f(f)(arg)))\n\n# Define anonymous recursive factorial function\nfac = Y(lambda f: lambda n: (1 if n&lt;2 else n*f(n-1)))\nassert fac(7) == 5040\n</code></pre>\n" }, { "answer_id": 156409, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 3, "selected": false, "text": "<p>You can do it in Perl:</p>\n\n<pre><code>my $factorial = do {\n my $fac;\n $fac = sub {\n my $n = shift;\n if ($n &lt; 2) { 1 } else { $n * $fac-&gt;($n-1) }\n };\n};\n\nprint $factorial-&gt;(4);\n</code></pre>\n\n<p>The <code>do</code> block isn't strictly necessary; I included it to emphasize that the result is a true anonymous function.</p>\n" }, { "answer_id": 156426, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>In C# you need to declare a variable to hold the delegate, and assign null to it to make sure it's definitely assigned, <em>then</em> you can call it from within a lambda expression which you assign to it:</p>\n\n<pre><code>Func&lt;int, int&gt; fac = null;\nfac = n =&gt; n &lt; 2 ? 1 : n * fac(n-1);\nConsole.WriteLine(fac(7));\n</code></pre>\n\n<p>I <em>think</em> I heard rumours that the C# team was considering changing the rules on definite assignment to make the separate declaration/initialization unnecessary, but I wouldn't swear to it.</p>\n\n<p>One important question for each of these languages / runtime environments is whether they support tail calls. In C#, as far as I'm aware the MS compiler doesn't use the <code>tail.</code> IL opcode, but the JIT <a href=\"http://blogs.msdn.com/davbr/pages/tail-call-jit-conditions.aspx\" rel=\"nofollow noreferrer\"><em>may</em> optimise it anyway, in certain circumstances</a>. Obviously this can very easily make the difference between a working program and stack overflow. (It would be nice to have more control over this and/or guarantees about when it will occur. Otherwise a program which works on one machine may fail on another in a hard-to-fathom manner.)</p>\n\n<p>Edit: as <a href=\"https://stackoverflow.com/questions/156369/which-languages-support-recursive-function-literals-anonymous-functions#156468\">FryHard</a> pointed out, this is only pseudo-recursion. Simple enough to get the job done, but the Y-combinator is a purer approach. There's one other caveat with the code I posted above: if you change the value of <code>fac</code>, anything which tries to use the old value will start to fail, because the lambda expression has captured the <code>fac</code> variable itself. (Which it has to in order to work properly at all, of course...)</p>\n" }, { "answer_id": 156444, "author": "helloandre", "author_id": 50, "author_profile": "https://Stackoverflow.com/users/50", "pm_score": 0, "selected": false, "text": "<p>I think this may not be exactly what you're looking for, but in Lisp 'labels' can be used to dynamically declare functions that can be called recursively.</p>\n\n<pre><code>(labels ((factorial (x) ;define name and params\n ; body of function addrec\n (if (= x 1)\n (return 1)\n (+ (factorial (- x 1))))) ;should not close out labels\n ;call factorial inside labels function\n (factorial 5)) ;this would return 15 from labels\n</code></pre>\n" }, { "answer_id": 156468, "author": "FryHard", "author_id": 231, "author_profile": "https://Stackoverflow.com/users/231", "pm_score": 3, "selected": false, "text": "<p><strong>C#</strong></p>\n\n<p>Reading <a href=\"http://blogs.msdn.com/wesdyer/archive/2007/02/02/anonymous-recursion-in-c.aspx\" rel=\"nofollow noreferrer\"><strong>Wes Dyer's</strong></a> blog, you will see that @Jon Skeet's answer is not totally correct. I am no genius on languages but there is a difference between a recursive anonymous function and the \"<em>fib function really just invokes the delegate that the local variable fib references</em>\" to quote from the blog.</p>\n\n<p>The actual C# answer would look something like this:</p>\n\n<pre><code>delegate Func&lt;A, R&gt; Recursive&lt;A, R&gt;(Recursive&lt;A, R&gt; r);\n\nstatic Func&lt;A, R&gt; Y&lt;A, R&gt;(Func&lt;Func&lt;A, R&gt;, Func&lt;A, R&gt;&gt; f)\n{\n Recursive&lt;A, R&gt; rec = r =&gt; a =&gt; f(r(r))(a);\n return rec(rec);\n}\n\nstatic void Main(string[] args)\n{\n Func&lt;int,int&gt; fib = Y&lt;int,int&gt;(f =&gt; n =&gt; n &gt; 1 ? f(n - 1) + f(n - 2) : n);\n Func&lt;int, int&gt; fact = Y&lt;int, int&gt;(f =&gt; n =&gt; n &gt; 1 ? n * f(n - 1) : 1);\n Console.WriteLine(fib(6)); // displays 8\n Console.WriteLine(fact(6));\n Console.ReadLine();\n} \n</code></pre>\n" }, { "answer_id": 156555, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 0, "selected": false, "text": "<p>Delphi includes the anonymous functions with version 2009.</p>\n\n<p>Example from <a href=\"http://blogs.codegear.com/davidi/2008/07/23/38915/\" rel=\"nofollow noreferrer\">http://blogs.codegear.com/davidi/2008/07/23/38915/</a></p>\n\n<pre><code>type\n // method reference\n TProc = reference to procedure(x: Integer); \n\nprocedure Call(const proc: TProc);\nbegin\n proc(42);\nend;\n</code></pre>\n\n<p>Use:</p>\n\n<pre><code>var\n proc: TProc;\nbegin\n // anonymous method\n proc := procedure(a: Integer)\n begin\n Writeln(a);\n end; \n\n Call(proc);\n readln\nend.\n</code></pre>\n" }, { "answer_id": 156655, "author": "Daniel James", "author_id": 2434, "author_profile": "https://Stackoverflow.com/users/2434", "pm_score": 2, "selected": false, "text": "<p>You've mixed up some terminology here, function literals don't have to be anonymous.</p>\n\n<p>In javascript the difference depends on whether the function is written as a statement or an expression. There's some discussion about the distinction in the answers to <a href=\"https://stackoverflow.com/questions/114525/the-difference-between-the-two-functions\">this question</a>.</p>\n\n<p>Lets say you are passing your example to a function:</p>\n\n<pre><code>foo(function(n){if (n&lt;2) {return 1;} else {return n * arguments.callee(n-1);}});\n</code></pre>\n\n<p>This could also be written:</p>\n\n<pre><code>foo(function fac(n){if (n&lt;2) {return 1;} else {return n * fac(n-1);}});\n</code></pre>\n\n<p>In both cases it's a function literal. But note that in the second example the name is not added to the surrounding scope - which can be confusing. But this isn't widely used as some javascript implementations don't support this or have a buggy implementation. I've also read that it's slower.</p>\n\n<p>Anonymous recursion is something different again, it's when a function recurses without having a reference to itself, the Y Combinator has already been mentioned. In most languages, it isn't necessary as better methods are available. Here's a link to <a href=\"http://w3future.com/weblog/stories/2002/02/22/javascriptYCombinator.xml\" rel=\"nofollow noreferrer\">a javascript implementation</a>.</p>\n" }, { "answer_id": 171023, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 2, "selected": false, "text": "<p>In Perl 6:</p>\n\n<pre><code>my $f = -&gt; $n { if ($n &lt;= 1) {1} else {$n * &amp;?BLOCK($n - 1)} }\n$f(42); # ==&gt; 1405006117752879898543142606244511569936384000000000\n</code></pre>\n" }, { "answer_id": 642890, "author": "gnovice", "author_id": 52738, "author_profile": "https://Stackoverflow.com/users/52738", "pm_score": 0, "selected": false, "text": "<p>Because I was curious, I actually tried to come up with a way to do this in <strong>MATLAB</strong>. It can be done, but it looks a little Rube-Goldberg-esque:</p>\n\n<pre><code>&gt;&gt; fact = @(val,branchFcns) val*branchFcns{(val &lt;= 1)+1}(val-1,branchFcns);\n&gt;&gt; returnOne = @(val,branchFcns) 1;\n&gt;&gt; branchFcns = {fact returnOne};\n&gt;&gt; fact(4,branchFcns)\n\nans =\n\n 24\n\n&gt;&gt; fact(5,branchFcns)\n\nans =\n\n 120\n</code></pre>\n" }, { "answer_id": 1675978, "author": "Andrew Janke", "author_id": 105904, "author_profile": "https://Stackoverflow.com/users/105904", "pm_score": 1, "selected": false, "text": "<p>You can do this in Matlab using an anonymous function which uses the dbstack() introspection to get the function literal of itself and then evaluating it. (I admit this is cheating because dbstack should probably be considered extralinguistic, but it is available in all Matlabs.)</p>\n\n<pre><code>f = @(x) ~x || feval(str2func(getfield(dbstack, 'name')), x-1)\n</code></pre>\n\n<p>This is an anonymous function that counts down from x and then returns 1. It's not very useful because Matlab lacks the ?: operator and disallows if-blocks inside anonymous functions, so it's hard to construct the base case/recursive step form.</p>\n\n<p>You can demonstrate that it is recursive by calling f(-1); it will count down to infinity and eventually throw a max recursion error.</p>\n\n<pre><code>&gt;&gt; f(-1)\n??? Maximum recursion limit of 500 reached. Use set(0,'RecursionLimit',N)\nto change the limit. Be aware that exceeding your available stack space can\ncrash MATLAB and/or your computer.\n</code></pre>\n\n<p>And you can invoke the anonymous function directly, without binding it to any variable, by passing it directly to feval.</p>\n\n<pre><code>&gt;&gt; feval(@(x) ~x || feval(str2func(getfield(dbstack, 'name')), x-1), -1)\n??? Maximum recursion limit of 500 reached. Use set(0,'RecursionLimit',N)\nto change the limit. Be aware that exceeding your available stack space can\ncrash MATLAB and/or your computer.\n\nError in ==&gt; create@(x)~x||feval(str2func(getfield(dbstack,'name')),x-1)\n</code></pre>\n\n<p>To make something useful out of it, you can create a separate function which implements the recursive step logic, using \"if\" to protect the recursive case against evaluation.</p>\n\n<pre><code>function out = basecase_or_feval(cond, baseval, fcn, args, accumfcn)\n%BASECASE_OR_FEVAL Return base case value, or evaluate next step\nif cond\n out = baseval;\nelse\n out = feval(accumfcn, feval(fcn, args{:}));\nend\n</code></pre>\n\n<p>Given that, here's factorial.</p>\n\n<pre><code>recursive_factorial = @(x) basecase_or_feval(x &lt; 2,...\n 1,...\n str2func(getfield(dbstack, 'name')),...\n {x-1},...\n @(z)x*z);\n</code></pre>\n\n<p>And you can call it without binding.</p>\n\n<pre><code>&gt;&gt; feval( @(x) basecase_or_feval(x &lt; 2, 1, str2func(getfield(dbstack, 'name')), {x-1}, @(z)x*z), 5)\nans =\n 120\n</code></pre>\n" }, { "answer_id": 2858779, "author": "Puppy", "author_id": 298661, "author_profile": "https://Stackoverflow.com/users/298661", "pm_score": 0, "selected": false, "text": "<p>Anonymous functions exist in C++0x with lambda, and they may be recursive, although I'm not sure about anonymously.</p>\n\n<pre><code>auto kek = [](){kek();}\n</code></pre>\n" }, { "answer_id": 2870453, "author": "Zorf", "author_id": 2281094, "author_profile": "https://Stackoverflow.com/users/2281094", "pm_score": 0, "selected": false, "text": "<p>'Tseems you've got the idea of anonymous functions wrong, it's not just about runtime creation, it's also about scope. Consider this Scheme macro:</p>\n\n<pre><code>(define-syntax lambdarec\n (syntax-rules ()\n ((lambdarec (tag . params) . body)\n ((lambda ()\n (define (tag . params) . body)\n tag)))))\n</code></pre>\n\n<p>Such that:</p>\n\n<pre><code>(lambdarec (f n) (if (&lt;= n 0) 1 (* n (f (- n 1)))))\n</code></pre>\n\n<p>Evaluates to a true anonymous recursive factorial function that can for instance be used like:</p>\n\n<pre><code>(let ;no letrec used\n ((factorial (lambdarec (f n) (if (&lt;= n 0) 1 (* n (f (- n 1)))))))\n (factorial 4)) ; ===&gt; 24\n</code></pre>\n\n<p>However, the true reason that makes it anonymous is that if I do:</p>\n\n<pre><code>((lambdarec (f n) (if (&lt;= n 0) 1 (* n (f (- n 1))))) 4)\n</code></pre>\n\n<p>The function is afterwards cleared from memory and has no scope, thus after this:</p>\n\n<pre><code>(f 4)\n</code></pre>\n\n<p>Will either signal an error, or will be bound to whatever f was bound to before.</p>\n\n<p>In Haskell, an ad hoc way to achieve same would be:</p>\n\n<pre><code>\\n -&gt; let fac x = if x&lt;2 then 1 else fac (x-1) * x\n in fac n\n</code></pre>\n\n<p>The difference again being that this function has no scope, if I don't use it, with Haskell being Lazy the effect is the same as an empty line of code, it is truly literal as it has the same effect as the C code:</p>\n\n<pre><code>3;\n</code></pre>\n\n<p>A literal number. And even if I use it immediately afterwards it will go away. This is what literal functions are about, not creation at runtime per se.</p>\n" }, { "answer_id": 6949191, "author": "Mechanical snail", "author_id": 319931, "author_profile": "https://Stackoverflow.com/users/319931", "pm_score": 1, "selected": false, "text": "<p>It also seems Mathematica lets you define recursive functions using <code>#0</code> to denote the function itself, as:</p>\n\n<pre><code>(expression[#0]) &amp;\n</code></pre>\n\n<p>e.g. a factorial:</p>\n\n<pre><code>fac = Piecewise[{{1, #1 == 0}, {#1 * #0[#1 - 1], True}}] &amp;;\n</code></pre>\n\n<p>This is in keeping with the notation <code>#i</code> to refer to the ith parameter, and the shell-scripting convention that a script is its own 0th parameter.</p>\n" }, { "answer_id": 41702432, "author": "Ssswift", "author_id": 7419656, "author_profile": "https://Stackoverflow.com/users/7419656", "pm_score": 0, "selected": false, "text": "<p>Clojure can do it, as <code>fn</code> takes an optional name specifically for this purpose (the name doesn't escape the definition scope):</p>\n\n<pre><code>&gt; (def fac (fn self [n] (if (&lt; n 2) 1 (* n (self (dec n))))))\n#'sandbox17083/fac\n&gt; (fac 5)\n120\n&gt; self\njava.lang.RuntimeException: Unable to resolve symbol: self in this context\n</code></pre>\n\n<p>If it happens to be tail recursion, then <code>recur</code> is a much more efficient method:</p>\n\n<pre><code>&gt; (def fac (fn [n] (loop [count n result 1]\n (if (zero? count)\n result\n (recur (dec count) (* result count))))))\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15069/" ]
It seems quite a few mainstream languages support [function literals](http://en.wikipedia.org/wiki/First-class_function) these days. They are also called [anonymous functions](http://en.wikipedia.org/wiki/Anonymous_function), but I don't care if they have a name. The important thing is that a function literal is an expression which yields a function which hasn't already been defined elsewhere, so for example in C, `&printf` doesn't count. EDIT to add: if you have a genuine function literal expression `<exp>`, you should be able to pass it to a function `f(<exp>)` or immediately apply it to an argument, ie. `<exp>(5)`. I'm curious which languages let you write function literals which are *recursive*. Wikipedia's "[anonymous recursion](http://en.wikipedia.org/wiki/Anonymous_recursion)" article doesn't give any programming examples. Let's use the recursive factorial function as the example. Here are the ones I know: * JavaScript / ECMAScript can do it with `callee`: ``` function(n){if (n<2) {return 1;} else {return n * arguments.callee(n-1);}} ``` * it's easy in languages with `letrec`, eg Haskell (which calls it `let`): > > `let fac x = if x<2 then 1 else fac (x-1) * x in fac` > > > and there are equivalents in Lisp and Scheme. Note that the binding of `fac` is local to the expression, so the whole expression is in fact an anonymous function. Are there any others?
Most languages support it through use of the [Y combinator](http://en.wikipedia.org/wiki/Fixed_point_combinator#Y_combinator). Here's an example in Python (from the [cookbook](http://code.activestate.com/recipes/576366/)): ``` # Define Y combinator...come on Gudio, put it in functools! Y = lambda g: (lambda f: g(lambda arg: f(f)(arg))) (lambda f: g(lambda arg: f(f)(arg))) # Define anonymous recursive factorial function fac = Y(lambda f: lambda n: (1 if n<2 else n*f(n-1))) assert fac(7) == 5040 ```
156,373
<p>I'm storing an object (<code>TTF_Font</code>) in a <code>shared_ptr</code> that is provided to me from a third-party API. I cannot use new or delete on the object, so the <code>shared_ptr</code> is also provided a "freeing" functor.</p> <pre><code>// Functor struct CloseFont { void operator()(TTF_Font* font) const { if(font != NULL) { TTF_CloseFont(font); } } }; boost::shared_ptr&lt;TTF_Font&gt; screenFont; screenFont = boost::shared_ptr&lt;TTF_Font&gt;( TTF_OpenFont("slkscr.ttf", 8), CloseFont() ); </code></pre> <p>If, later, I need to explicitly free this object is it correct to do this:</p> <pre><code>screenFont.reset(); </code></pre> <p>And then let <code>screenFont</code> (the actual <code>shared_ptr</code> object) be destroyed naturally?</p>
[ { "answer_id": 156382, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 5, "selected": true, "text": "<p>shared_ptr&lt;>::reset() will drop the refcount by one. If that results in the count dropping to zero, the resource pointed to by the shared_ptr&lt;> will be freed.</p>\n\n<p>So I think the answer for you is, yes that will work. Or you can simply let the screenFont variable be destructed due to dropping out of scope or whatever, if that's what's about to happen.</p>\n\n<p>To be clear, the normal usage of shared_ptr&lt;> is that you let it be destructed naturally, and it will deal with the refcount and freeing the resource when it drops to zero naturally. reset() is only required if you need to release that particular instance of the shared resource before the shared_ptr&lt;> would be naturally destructed.</p>\n" }, { "answer_id": 156386, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 0, "selected": false, "text": "<p>Mike B's answered your question, so I'll just comment on your code. If <code>TTF_OpenFont</code> doesn't return null, or if <code>TTF_CloseFont</code> can handle nulls harmlessly, you don't need a <code>CloseFont</code> class at all, just use <code>&amp;TTF_CloseFont</code>.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18265/" ]
I'm storing an object (`TTF_Font`) in a `shared_ptr` that is provided to me from a third-party API. I cannot use new or delete on the object, so the `shared_ptr` is also provided a "freeing" functor. ``` // Functor struct CloseFont { void operator()(TTF_Font* font) const { if(font != NULL) { TTF_CloseFont(font); } } }; boost::shared_ptr<TTF_Font> screenFont; screenFont = boost::shared_ptr<TTF_Font>( TTF_OpenFont("slkscr.ttf", 8), CloseFont() ); ``` If, later, I need to explicitly free this object is it correct to do this: ``` screenFont.reset(); ``` And then let `screenFont` (the actual `shared_ptr` object) be destroyed naturally?
shared\_ptr<>::reset() will drop the refcount by one. If that results in the count dropping to zero, the resource pointed to by the shared\_ptr<> will be freed. So I think the answer for you is, yes that will work. Or you can simply let the screenFont variable be destructed due to dropping out of scope or whatever, if that's what's about to happen. To be clear, the normal usage of shared\_ptr<> is that you let it be destructed naturally, and it will deal with the refcount and freeing the resource when it drops to zero naturally. reset() is only required if you need to release that particular instance of the shared resource before the shared\_ptr<> would be naturally destructed.
156,394
<p>How is it that Ruby allows a class access methods outside of the class implicitly?</p> <p>Example:</p> <pre><code>class Candy def land homer end end def homer puts "Hello" end Candy.new.land #Outputs Hello </code></pre>
[ { "answer_id": 156408, "author": "janm", "author_id": 7256, "author_profile": "https://Stackoverflow.com/users/7256", "pm_score": 6, "selected": true, "text": "<p>The definition of the \"homer\" method is adding the method to the Object class. It is not defining a free function.</p>\n\n<p>Class Candy implicitly inherits from Object, and so has access to the methods in Object. When you call \"homer\" in the \"land\" method, the method resolution can't find a definition in the current class, goes to the super class, finds the method you have added to Object, and calls it.</p>\n" }, { "answer_id": 161113, "author": "Grant Hutchins", "author_id": 6304, "author_profile": "https://Stackoverflow.com/users/6304", "pm_score": 2, "selected": false, "text": "<p><strike>Technically, the definition of the <code>homer</code> method is actually on the <code>Kernel</code> module which is mixed into <code>Object</code>, not on <code>Object</code> directly. So when <code>homer</code> is not a local variable or an instance method defined on <code>Candy</code>, the Ruby method inheritance chain is followed up through <code>Object</code> and then to the mixed-in <code>Kernel</code> module and then this code is run.</strike></p>\n\n<p><strong>Edit:</strong> Sorry, I don't know why I thought this. It appears that the method really lives on <code>Object</code>. Not sure it makes too much of a difference in practice but I should have confirmed things before posting.</p>\n" }, { "answer_id": 164862, "author": "user24631", "author_id": 24631, "author_profile": "https://Stackoverflow.com/users/24631", "pm_score": 3, "selected": false, "text": "<p>A simple way to find out what happens </p>\n\n<ol>\n<li><p>What classes/modules are searched to resolve methods used in Candy objects?</p>\n\n<p>p Candy.ancestors #=> [Candy, Object, Kernel]</p></li>\n<li><p>Does Candy have method called homer?</p>\n\n<p> p Candy.instance_methods(false).grep(\"homer\") #=> [] </p>\n\n<p> p Candy.private_instance_methods(false).grep(\"homer\") #=> [] </p></li>\n<li><p>OK Candy does not have any method called 'homer'. </p></li>\n<li><p>What's next in the lookup chain (see 1) => \"Object\"</p></li>\n<li><p>Does Object have a method called \"homer\" ?\n p Object.instance_methods(false).grep(\"homer\") #=> [] </p>\n\n<p> p Object.private_instance_methods(false).grep(\"homer\") #=> [\"homer\"] </p></li>\n</ol>\n\n<p><em>Candy has Object in its lookup chain which in turn has a private instance method \"homer\" so method resolution succeeds</em></p>\n\n<p>The <strong>def statement</strong> always defines the method in the class of whatever <strong>self</strong> is at the point of definition</p>\n\n<ol>\n<li><p>What is <em>self</em> just before homer is defined ?</p>\n\n<p> p self #=> main\n def homer\n puts \"Hello\"\n end </p></li>\n<li><p>So what is its type ? </p>\n\n<p> p self.class #=> Object</p></li>\n</ol>\n\n<p>Which is why <em>homer</em> ends up on <em>Object</em></p>\n" }, { "answer_id": 8286738, "author": "Linuxios", "author_id": 1008938, "author_profile": "https://Stackoverflow.com/users/1008938", "pm_score": 0, "selected": false, "text": "<p>Ruby has no free-floating functions. Every method belongs to some object. Methods that you <code>def</code> at the top level are actually becoming instance methods of class <code>Object</code>. Because everything is an <code>Object</code> at some level, all objects have access to <code>Object</code>'s instance methods.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How is it that Ruby allows a class access methods outside of the class implicitly? Example: ``` class Candy def land homer end end def homer puts "Hello" end Candy.new.land #Outputs Hello ```
The definition of the "homer" method is adding the method to the Object class. It is not defining a free function. Class Candy implicitly inherits from Object, and so has access to the methods in Object. When you call "homer" in the "land" method, the method resolution can't find a definition in the current class, goes to the super class, finds the method you have added to Object, and calls it.
156,395
<p>As a Java developer who is reading Apple's Objective-C 2.0 documentation: I wonder what "<em>sending a message to nil</em>" means - let alone how it is actually useful. Taking an excerpt from the documentation:</p> <blockquote> <p>There are several patterns in Cocoa that take advantage of this fact. The value returned from a message to nil may also be valid:</p> <ul> <li>If the method returns an object, any pointer type, any integer scalar of size less than or equal to sizeof(void*), a float, a double, a long double, or a long long, then a message sent to nil returns 0.</li> <li>If the method returns a struct, as defined by the Mac OS X ABI Function Call Guide to be returned in registers, then a message sent to nil returns 0.0 for every field in the data structure. Other struct data types will not be filled with zeros.</li> <li>If the method returns anything other than the aforementioned value types the return value of a message sent to nil is undefined.</li> </ul> </blockquote> <p>Has Java rendered my brain incapable of grokking the explanation above? Or is there something that I am missing that would make this as clear as glass?</p> <p>I do get the idea of messages/receivers in Objective-C, I am simply confused about a receiver that happens to be <code>nil</code>.</p>
[ { "answer_id": 156415, "author": "Rich", "author_id": 22003, "author_profile": "https://Stackoverflow.com/users/22003", "pm_score": 4, "selected": false, "text": "<p>What it means is that the runtime doesn't produce an error when objc_msgSend is called on the nil pointer; instead it returns some (often useful) value. Messages that might have a side effect do nothing.</p>\n\n<p>It's useful because most of the default values are more appropriate than an error. For example:</p>\n\n<pre><code>[someNullNSArrayReference count] =&gt; 0\n</code></pre>\n\n<p>I.e., nil appears to be the empty array. Hiding a nil NSView reference does nothing. Handy, eh?</p>\n" }, { "answer_id": 156463, "author": "Michael Buckley", "author_id": 22540, "author_profile": "https://Stackoverflow.com/users/22540", "pm_score": 8, "selected": true, "text": "<p>Well, I think it can be described using a very contrived example. Let's say you have a method in Java which prints out all of the elements in an ArrayList:</p>\n\n<pre><code>void foo(ArrayList list)\n{\n for(int i = 0; i &lt; list.size(); ++i){\n System.out.println(list.get(i).toString());\n }\n}\n</code></pre>\n\n<p>Now, if you call that method like so: someObject.foo(NULL); you're going to probably get a NullPointerException when it tries to access list, in this case in the call to list.size(); Now, you'd probably never call someObject.foo(NULL) with the NULL value like that. However, you may have gotten your ArrayList from a method which returns NULL if it runs into some error generating the ArrayList like someObject.foo(otherObject.getArrayList());</p>\n\n<p>Of course, you'll also have problems if you do something like this:</p>\n\n<pre><code>ArrayList list = NULL;\nlist.size();\n</code></pre>\n\n<p>Now, in Objective-C, we have the equivalent method:</p>\n\n<pre><code>- (void)foo:(NSArray*)anArray\n{\n int i;\n for(i = 0; i &lt; [anArray count]; ++i){\n NSLog(@\"%@\", [[anArray objectAtIndex:i] stringValue];\n }\n}\n</code></pre>\n\n<p>Now, if we have the following code:</p>\n\n<pre><code>[someObject foo:nil];\n</code></pre>\n\n<p>we have the same situation in which Java will produce a NullPointerException. The nil object will be accessed first at [anArray count] However, instead of throwing a NullPointerException, Objective-C will simply return 0 in accordance with the rules above, so the loop will not run. However, if we set the loop to run a set number of times, then we're first sending a message to anArray at [anArray objectAtIndex:i]; This will also return 0, but since objectAtIndex: returns a pointer, and a pointer to 0 is nil/NULL, NSLog will be passed nil each time through the loop. (Although NSLog is a function and not a method, it prints out (null) if passed a nil NSString.</p>\n\n<p>In some cases it's nicer to have a NullPointerException, since you can tell right away that something is wrong with the program, but unless you catch the exception, the program will crash. (In C, trying to dereference NULL in this way causes the program to crash.) In Objective-C, it instead just causes possibly incorrect run-time behavior. However, if you have a method that doesn't break if it returns 0/nil/NULL/a zeroed struct, then this saves you from having to check to make sure the object or parameters are nil.</p>\n" }, { "answer_id": 156498, "author": "Kendall Helmstetter Gelner", "author_id": 6330, "author_profile": "https://Stackoverflow.com/users/6330", "pm_score": 3, "selected": false, "text": "<p>It means often not having to check for nil objects everywhere for safety - particularly:</p>\n\n<pre><code>[someVariable release];\n</code></pre>\n\n<p>or, as noted, various count and length methods all return 0 when you've got a nil value, so you do not have to add extra checks for nil all over:</p>\n\n<pre><code>if ( [myString length] &gt; 0 )\n</code></pre>\n\n<p>or this:</p>\n\n<pre><code>return [myArray count]; // say for number of rows in a table\n</code></pre>\n" }, { "answer_id": 160432, "author": "benzado", "author_id": 10947, "author_profile": "https://Stackoverflow.com/users/10947", "pm_score": 3, "selected": false, "text": "<p>Don't think about \"the receiver being nil\"; I agree, that <em>is</em> pretty weird. If you're sending a message to nil, there is no receiver. You're just sending a message to nothing.</p>\n\n<p>How to deal with that is a philosophical difference between Java and Objective-C: in Java, that's an error; in Objective-C, it is a no-op.</p>\n" }, { "answer_id": 195944, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 4, "selected": false, "text": "<p>In the quotation from the documentation, there are two separate concepts -- perhaps it might be better if the documentation made that more clear:</p>\n\n<blockquote>\n <p>There are several patterns in Cocoa that take advantage of this fact.</p>\n \n <p>The value returned from a message to nil may also be valid:</p>\n</blockquote>\n\n<p>The former is probably more relevant here: typically being able to send messages to <code>nil</code> makes code more straightforward -- you don't have to check for null values everywhere. The canonical example is probably the accessor method:</p>\n\n<pre><code>- (void)setValue:(MyClass *)newValue {\n if (value != newValue) { \n [value release];\n value = [newValue retain];\n }\n}\n</code></pre>\n\n<p>If sending messages to <code>nil</code> were not valid, this method would be more complex -- you'd have to have two additional checks to ensure <code>value</code> and <code>newValue</code> are not <code>nil</code> before sending them messages.</p>\n\n<p>The latter point (that values returned from a message to <code>nil</code> are also typically valid), though, adds a multiplier effect to the former. For example:</p>\n\n<pre><code>if ([myArray count] &gt; 0) {\n // do something...\n}\n</code></pre>\n\n<p>This code again doesn't require a check for <code>nil</code> values, and flows naturally...</p>\n\n<p>All this said, the additional flexibility that being able to send messages to <code>nil</code> does come at some cost. There is the possibility that you will at some stage write code that fails in a peculiar way because you didn't take into account the possibility that a value might be <code>nil</code>.</p>\n" }, { "answer_id": 276943, "author": "Peter Hosey", "author_id": 30461, "author_profile": "https://Stackoverflow.com/users/30461", "pm_score": 6, "selected": false, "text": "<p>A message to <code>nil</code> does nothing and returns <code>nil</code>, <code>Nil</code>, <code>NULL</code>, <code>0</code>, or <code>0.0</code>.</p>\n" }, { "answer_id": 310215, "author": "Joe McMahon", "author_id": 39791, "author_profile": "https://Stackoverflow.com/users/39791", "pm_score": 5, "selected": false, "text": "<p>All of the other posts are correct, but maybe it's the concept that's the thing important here.</p>\n\n<p>In Objective-C method calls, any object reference that can accept a selector is a valid target for that selector. </p>\n\n<p>This saves a LOT of \"is the target object of type X?\" code - as long as the receiving object implements the selector, it makes <em>absolutely no difference</em> what class it is! <code>nil</code> is an NSObject that accepts any selector - it just doesn't <em>do</em> anything. This eliminates a lot of \"check for nil, don't send the message if true\" code as well. (The \"if it accepts it, it implements it\" concept is also what allows you to create <em>protocols</em>, which are sorta kinda like Java interfaces: a declaration that if a class implements the stated methods, then it conforms to the protocol.)</p>\n\n<p>The reason for this is to eliminate monkey code that doesn't do anything except keep the compiler happy. Yes, you get the overhead of one more method call, but you save <em>programmer time</em>, which is a far more expensive resource than CPU time. In addition, you're eliminating more code and more conditional complexity from your application.</p>\n\n<p>Clarifying for downvoters: you may think this is not a good way to go, but it's how the language is implemented, and it's the recommended programming idiom <em>in Objective-C</em> (see the Stanford iPhone programming lectures).</p>\n" }, { "answer_id": 646789, "author": "Nikita Zhuk", "author_id": 32045, "author_profile": "https://Stackoverflow.com/users/32045", "pm_score": 3, "selected": false, "text": "<p>ObjC messages which are sent to nil and whose return values have size larger than sizeof(void*) produce undefined values on PowerPC processors. In addition to that, these messages cause undefined values to be returned in fields of structs whose size is larger than 8 bytes on Intel processors as well. Vincent Gable has described this nicely in his <a href=\"http://vgable.com/blog/2008/05/31/messages-to-nowhere/\" rel=\"noreferrer\">blog post</a></p>\n" }, { "answer_id": 5530582, "author": "Rinzwind", "author_id": 276925, "author_profile": "https://Stackoverflow.com/users/276925", "pm_score": 3, "selected": false, "text": "<p>I don't think any of the other answers have mentioned this clearly: if you're used to Java, you should keep in mind that while Objective-C on Mac OS X has exception handling support, it's an optional language feature that can be turned on/off with a compiler flag. My guess is that this design of \"sending messages to <code>nil</code> is safe\" predates the inclusion of exception handling support in the language and was done with a similar goal in mind: methods can return <code>nil</code> to indicate errors, and since sending a message to <code>nil</code> usually returns <code>nil</code> in turn, this allows the error indication to propagate through your code so you don't have to check for it at every single message. You only have to check for it at points where it matters. I personally think exception propagation&amp;handling is a better way to address this goal, but not everyone may agree with that. (On the other hand, I for example don't like Java's requirement on you having to declare what exceptions a method may throw, which often forces you to <em>syntactically</em> propagate exception declarations throughout your code; but that's another discussion.)</p>\n\n<p>I've posted a similar, but longer, answer to the related question <a href=\"https://stackoverflow.com/questions/5450775/is-asserting-that-every-object-creation-succeeded-necessary-in-objective-c/5451243#5451243\">\"Is asserting that every object creation succeeded necessary in Objective C?\"</a> if you want more details.</p>\n" }, { "answer_id": 9507831, "author": "Heath Borders", "author_id": 9636, "author_profile": "https://Stackoverflow.com/users/9636", "pm_score": 4, "selected": false, "text": "<p>From <a href=\"https://twitter.com/gparker\">Greg Parker</a>'s <a href=\"http://www.sealiesoftware.com/blog/archive/2012/2/29/objc_explain_return_value_of_message_to_nil.html\">site</a>:</p>\n\n<p>If running LLVM Compiler 3.0 (Xcode 4.2) or later</p>\n\n<pre>\nMessages to nil with return type | return\nIntegers up to 64 bits | 0\nFloating-point up to long double | 0.0\nPointers | nil\nStructs | {0}\nAny _Complex type | {0, 0}\n</pre>\n" }, { "answer_id": 27105329, "author": "Zee", "author_id": 1210962, "author_profile": "https://Stackoverflow.com/users/1210962", "pm_score": 2, "selected": false, "text": "<p>C represents nothing as 0 for primitive values, and NULL for pointers (which is equivalent to 0 in a pointer context).</p>\n\n<p>Objective-C builds on C's representation of nothing by adding nil. nil is an object pointer to nothing. Although semantically distinct from NULL, they are technically equivalent to one another.</p>\n\n<p>Newly-alloc'd NSObjects start life with their contents set to 0. This means that all pointers that object has to other objects begin as nil, so it's unnecessary to, for instance, set self.(association) = nil in init methods.</p>\n\n<p><strong>The most notable behavior of nil, though, is that it can have messages sent to it.</strong></p>\n\n<p>In other languages, like C++ (or Java), this would crash your program, but in Objective-C, invoking a method on nil returns a zero value. This greatly simplifies expressions, as it obviates the need to check for nil before doing anything:</p>\n\n<pre><code>// For example, this expression...\nif (name != nil &amp;&amp; [name isEqualToString:@\"Steve\"]) { ... }\n\n// ...can be simplified to:\nif ([name isEqualToString:@\"Steve\"]) { ... }\n</code></pre>\n\n<p>Being aware of how nil works in Objective-C allows this convenience to be a feature, and not a lurking bug in your application. Make sure to guard against cases where nil values are unwanted, either by checking and returning early to fail silently, or adding a NSParameterAssert to throw an exception.</p>\n\n<p>Source: \n<a href=\"http://nshipster.com/nil/\" rel=\"nofollow\">http://nshipster.com/nil/</a> \n<a href=\"https://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/Chapters/ocObjectsClasses.html\" rel=\"nofollow\">https://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/Chapters/ocObjectsClasses.html</a> (Sending Message to nil).</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9931/" ]
As a Java developer who is reading Apple's Objective-C 2.0 documentation: I wonder what "*sending a message to nil*" means - let alone how it is actually useful. Taking an excerpt from the documentation: > > There are several patterns in Cocoa > that take advantage of this fact. The > value returned from a message to nil > may also be valid: > > > * If the method returns an object, any pointer type, any integer scalar > of size less than or equal to > sizeof(void\*), a float, a double, a > long double, or a long long, then a > message sent to nil returns 0. > * If the method returns a struct, as defined by the Mac OS X ABI Function > Call Guide to be returned in > registers, then a message sent to nil > returns 0.0 for every field in the > data structure. Other struct data > types will not be filled with zeros. > * If the method returns anything other than the aforementioned value > types the return value of a message > sent to nil is undefined. > > > Has Java rendered my brain incapable of grokking the explanation above? Or is there something that I am missing that would make this as clear as glass? I do get the idea of messages/receivers in Objective-C, I am simply confused about a receiver that happens to be `nil`.
Well, I think it can be described using a very contrived example. Let's say you have a method in Java which prints out all of the elements in an ArrayList: ``` void foo(ArrayList list) { for(int i = 0; i < list.size(); ++i){ System.out.println(list.get(i).toString()); } } ``` Now, if you call that method like so: someObject.foo(NULL); you're going to probably get a NullPointerException when it tries to access list, in this case in the call to list.size(); Now, you'd probably never call someObject.foo(NULL) with the NULL value like that. However, you may have gotten your ArrayList from a method which returns NULL if it runs into some error generating the ArrayList like someObject.foo(otherObject.getArrayList()); Of course, you'll also have problems if you do something like this: ``` ArrayList list = NULL; list.size(); ``` Now, in Objective-C, we have the equivalent method: ``` - (void)foo:(NSArray*)anArray { int i; for(i = 0; i < [anArray count]; ++i){ NSLog(@"%@", [[anArray objectAtIndex:i] stringValue]; } } ``` Now, if we have the following code: ``` [someObject foo:nil]; ``` we have the same situation in which Java will produce a NullPointerException. The nil object will be accessed first at [anArray count] However, instead of throwing a NullPointerException, Objective-C will simply return 0 in accordance with the rules above, so the loop will not run. However, if we set the loop to run a set number of times, then we're first sending a message to anArray at [anArray objectAtIndex:i]; This will also return 0, but since objectAtIndex: returns a pointer, and a pointer to 0 is nil/NULL, NSLog will be passed nil each time through the loop. (Although NSLog is a function and not a method, it prints out (null) if passed a nil NSString. In some cases it's nicer to have a NullPointerException, since you can tell right away that something is wrong with the program, but unless you catch the exception, the program will crash. (In C, trying to dereference NULL in this way causes the program to crash.) In Objective-C, it instead just causes possibly incorrect run-time behavior. However, if you have a method that doesn't break if it returns 0/nil/NULL/a zeroed struct, then this saves you from having to check to make sure the object or parameters are nil.
156,412
<p><code>GWT</code> gets locale from either the locale property or the locale query string. If neither is specified, it uses the "default" (ie <code>en_US</code>) locale.</p> <p>Why doesn't it get it from the browser settings?</p> <p>It seems the only solution to this is to replace your static html launch page with something like a JSP that reads the browser locales and sets the locale or redirects using the query string. There has to be a better solution than this or simply hard-coding a locale, surely?</p>
[ { "answer_id": 161313, "author": "Drejc", "author_id": 6482, "author_profile": "https://Stackoverflow.com/users/6482", "pm_score": 2, "selected": false, "text": "<p>If you put a list of available languages into your *.gwt.xml file it will by default switch to the first language listed.</p>\n\n<pre><code>&lt;!-- Slovenian in Slovenia --&gt;\n&lt;extend-property name=\"locale\" values=\"sl\"/&gt;\n\n&lt;!-- English language, independent of country --&gt;\n&lt;extend-property name=\"locale\" values=\"en\"/&gt;\n</code></pre>\n" }, { "answer_id": 7992504, "author": "ljader", "author_id": 498096, "author_profile": "https://Stackoverflow.com/users/498096", "pm_score": 3, "selected": false, "text": "<p>You can also put this switch in your *.gwt.xml</p>\n\n<pre><code>&lt;set-configuration-property name=\"locale.useragent\" value=\"Y\"/&gt;\n</code></pre>\n\n<p>this will add language selecting based on language selected in browser. You can also control search order for locale by setting</p>\n\n<pre><code> &lt;set-configuration-property name=\"locale.searchorder\" value=\"queryparam,cookie,meta,useragent\"/&gt;\n</code></pre>\n\n<p>But beware that in IE this doesn't work - you should develop server-side language pick based on 'Accept-Language' header send by the IE.</p>\n" }, { "answer_id": 8259725, "author": "johnstok", "author_id": 27929, "author_profile": "https://Stackoverflow.com/users/27929", "pm_score": 0, "selected": false, "text": "<p>If your entry page is a JSP you can inspect the request's <code>Accept-Language</code> header to dynamically set the locale.</p>\n" }, { "answer_id": 16627609, "author": "Jorge P.", "author_id": 1815133, "author_profile": "https://Stackoverflow.com/users/1815133", "pm_score": 1, "selected": false, "text": "<p>You can use a cookie to save and send this value, but for that you have to add in your <strong>*.gwt.xml</strong> first</p>\n\n<pre><code>&lt;set-configuration-property name=\"locale.cookie\" value=\"yourCookieName\"/&gt;\n&lt;set-configuration-property name=\"locale.searchorder\" value=\"queryparam,cookie,meta,useragent\"/&gt;\n</code></pre>\n\n<p>Note that \"<code>queryparam</code>\" has the biggest priority here, that allows to set a new locale using the <code>http</code> query and ignore the value on the cookie.</p>\n" }, { "answer_id": 17296508, "author": "Manish Prajapati", "author_id": 1651893, "author_profile": "https://Stackoverflow.com/users/1651893", "pm_score": 0, "selected": false, "text": "<p>add this entry in your <strong>*.gwt.xml</strong> file to see the effect!</p>\n\n<p>Please check the following line for more information!</p>\n\n<p><code>&lt;set-configuration-property name=\"locale.useragent\" value=\"Y\"/&gt;</code></p>\n" }, { "answer_id": 28435325, "author": "JuanFran Adame", "author_id": 1530949, "author_profile": "https://Stackoverflow.com/users/1530949", "pm_score": 0, "selected": false, "text": "<p>This worked for me, I hope it also works for you.</p>\n\n<p>My problem was that I have not declared any locale value in .gwt.xml module descriptor. In that case only the default locale is used. GWT does that way because any different supported locale means a new compilation iteration/permutation. Therefore only declared locales are used.</p>\n\n<p>Here you are an example:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;!-- Locales --&gt;\n&lt;extend-property name=\"locale\" values=\"en_US\"/&gt;\n&lt;extend-property name=\"locale\" values=\"es\"/&gt; \n&lt;set-property-fallback name=\"locale\" value=\"en_US\"/&gt;\n&lt;set-configuration-property name=\"locale.useragent\" value=\"Y\" /&gt;\n&lt;set-configuration-property name=\"locale.searchorder\" value=\"queryparam,cookie,meta,useragent\" /&gt;\n</code></pre>\n\n<p>The first and second lines set the available/supported locales (English from US and Spanish without specific country in my example). The third line sets the default locale in case no one is detected (this default declaration must be set after the default value is declared in a <code>extend-property</code> line). The fourth line enables the locale detection by means of the HTTP-Headers Accept-Language sent by browser (probably is enabled by default and not needed to set at all). The final line sets the order in which the different detection mechanisms try to detect the locale:</p>\n\n<ol>\n<li>As a parameter in the URL query</li>\n<li>From cookies</li>\n<li>As a meta value in the HTML page</li>\n<li>From the HTTP header sent by browser </li>\n</ol>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18393/" ]
`GWT` gets locale from either the locale property or the locale query string. If neither is specified, it uses the "default" (ie `en_US`) locale. Why doesn't it get it from the browser settings? It seems the only solution to this is to replace your static html launch page with something like a JSP that reads the browser locales and sets the locale or redirects using the query string. There has to be a better solution than this or simply hard-coding a locale, surely?
You can also put this switch in your \*.gwt.xml ``` <set-configuration-property name="locale.useragent" value="Y"/> ``` this will add language selecting based on language selected in browser. You can also control search order for locale by setting ``` <set-configuration-property name="locale.searchorder" value="queryparam,cookie,meta,useragent"/> ``` But beware that in IE this doesn't work - you should develop server-side language pick based on 'Accept-Language' header send by the IE.
156,436
<p>It's quite a simple question - how do I sort a collection?</p> <p>I've got a CSV file with rows in a random order. I'd like to sort the rows according to the date in one column. Do I add the rows to a recordset? Can I sort with a Scripting.Dictionary?</p> <p>I've clearly been spoilt with .NET and Linq, and now I find myself back in the land of classic asp, realising I must have known this 7 years ago, and missing generics immensely. I feel like a complete n00b.</p>
[ { "answer_id": 156485, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 0, "selected": false, "text": "<p>It's been a long time for me too. IIRC you don't have an option out of the box.</p>\n\n<p>If I were you I'd put all the data in an array and then sort the array. I found a QuickSort implementation here: <a href=\"https://web.archive.org/web/20210125130007/http://www.4guysfromrolla.com/webtech/012799-3.shtml\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20210125130007/http://www.4guysfromrolla.com/webtech/012799-3.shtml</a></p>\n" }, { "answer_id": 156488, "author": "Saif Khan", "author_id": 23667, "author_profile": "https://Stackoverflow.com/users/23667", "pm_score": 0, "selected": false, "text": "<p>Also look at the \"Bubble Sort\", works excellent with those classic asp tag cloud.</p>\n\n<p><a href=\"https://web.archive.org/web/20180927040044/http://www.4guysfromrolla.com:80/webtech/011001-1.shtml\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20180927040044/http://www.4guysfromrolla.com:80/webtech/011001-1.shtml</a></p>\n" }, { "answer_id": 156496, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 2, "selected": false, "text": "<p>I'd go with the RecordSet approach. Use the Text Driver. You'll need to change the directory in the connection string and the filename in the select statement. the Extended Property \"HDR=Yes\" specifies that there's a header row in the CSV which I suggest as it will make writing the psuedo SQL easier.</p>\n\n<pre><code>&lt;%\n\nDim strConnection, conn, rs, strSQL\n\nstrConnection = \"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\inetpub\\wwwroot\\;Extended Properties='text;HDR=Yes;FMT=Delimited';\"\n\nSet conn = Server.CreateObject(\"ADODB.Connection\")\nconn.Open strConnection\n\nSet rs = Server.CreateObject(\"ADODB.recordset\")\nstrSQL = \"SELECT * FROM test.csv order by date desc\"\nrs.open strSQL, conn, 3,3\n\nWHILE NOT rs.EOF\n Response.Write(rs(\"date\") &amp; \"&lt;br/&gt;\") \n rs.MoveNext\nWEND\n\nrs.Close\nSet rs = Nothing\n\nconn.Close\nSet conn = Nothing\n\n%&gt;\n</code></pre>\n" }, { "answer_id": 156611, "author": "Michal", "author_id": 21672, "author_profile": "https://Stackoverflow.com/users/21672", "pm_score": 5, "selected": true, "text": "<p>In this case I would get help from big brother .net. It's possible to use <strong>System.Collections.Sortedlist</strong> within your ASP app and get your key value pairs sorted. </p>\n\n<pre><code>set list = server.createObject(\"System.Collections.Sortedlist\")\nwith list\n .add \"something\", \"YY\"\n .add \"something else\", \"XX\"\nend with\n\nfor i = 0 to list.count - 1\n response.write(list.getKey(i) &amp; \" = \" &amp; list.getByIndex(i))\nnext\n</code></pre>\n\n<p>Btw if the following .net classes are available too:</p>\n\n<ul>\n<li>System.Collections.Queue</li>\n<li>System.Collections.Stack</li>\n<li>System.Collections.ArrayList</li>\n<li>System.Collections.SortedList</li>\n<li>System.Collections.Hashtable</li>\n<li>System.IO.StringWriter</li>\n<li>System.IO.MemoryStream;</li>\n</ul>\n\n<p>Also see: <a href=\"http://blog.opennetcf.com/afeinman/PermaLink,guid,aa53e23d-b8e5-4015-b00a-0c8ea9bc6dfe.aspx\" rel=\"noreferrer\">Marvels of COM .NET interop</a></p>\n" }, { "answer_id": 10835474, "author": "James Wiseman", "author_id": 144491, "author_profile": "https://Stackoverflow.com/users/144491", "pm_score": 0, "selected": false, "text": "<p>A late late answer to this, but still of value.</p>\n\n<p>I was working with small collections so could afford the approach where I inserted the item in the correct place on each occasion, effectively reconstructing the collection on each addition.</p>\n\n<p>The VBScript class is as follows:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>'Simple collection manager class.\n'Performs the opration of adding/setting a collection item.\n'Encapulated off here in order to delegate responsibility away from the collection class.\nClass clsCollectionManager\n Public Sub PopulateCollectionItem(collection, strKey, Value)\n If collection.Exists(strKey) Then\n If (VarType(Value) = vbObject) Then\n Set collection.Item(strKey) = Value\n Else\n collection.Item(strKey) = Value\n End If\n Else\n Call collection.Add(strKey, Value)\n End If\n End Sub\n\n 'take a collection and a new element as input parameters, an spit out a brand new collection \n 'with the new item iserted into the correct location by order\n 'This works on the assumption that the collection it is receiving is already ordered \n '(which it should be if we always use this method to populate the item)\n\n 'This mutates the passed collection, so we highlight this by marking it as byref \n '(this is not strictly necessary as objects are passed by reference anyway)\n Public Sub AddCollectionItemInOrder(byref existingCollection, strNewKey, Value)\n Dim orderedCollection: Set orderedCollection = Server.CreateObject(\"Scripting.Dictionary\")\n Dim strExistingKey\n\n 'If there is something already in our recordset then we need to add it in order.\n\n 'There is no sorting available for a collection (or an array) in VBScript. Therefore we have to do it ourself.\n 'First, iterate over eveything in our current collection. We have to assume that it is itself sorted.\n For Each strExistingKey In existingCollection\n\n 'if the new item doesn't exist AND it occurs after the current item, then add the new item in now \n '(before adding in the current item.)\n If (Not orderedCollection.Exists(strNewKey)) And (strExistingKey &gt; strNewKey) Then\n Call PopulateCollectionItem(orderedCollection, strNewKey, Value)\n End If\n Call PopulateCollectionItem(orderedCollection, strExistingKey, existingCollection.item(strExistingKey))\n Next\n\n 'Finally check to see if it still doesn't exist. \n 'It won't if the last place for it is at the very end, or the original collection was empty\n If (Not orderedCollection.Exists(strNewKey)) Then\n Call PopulateCollectionItem(orderedCollection, strNewKey, Value)\n End If\n\n Set existingCollection = orderedCollection\n End Sub\nEnd Class\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5744/" ]
It's quite a simple question - how do I sort a collection? I've got a CSV file with rows in a random order. I'd like to sort the rows according to the date in one column. Do I add the rows to a recordset? Can I sort with a Scripting.Dictionary? I've clearly been spoilt with .NET and Linq, and now I find myself back in the land of classic asp, realising I must have known this 7 years ago, and missing generics immensely. I feel like a complete n00b.
In this case I would get help from big brother .net. It's possible to use **System.Collections.Sortedlist** within your ASP app and get your key value pairs sorted. ``` set list = server.createObject("System.Collections.Sortedlist") with list .add "something", "YY" .add "something else", "XX" end with for i = 0 to list.count - 1 response.write(list.getKey(i) & " = " & list.getByIndex(i)) next ``` Btw if the following .net classes are available too: * System.Collections.Queue * System.Collections.Stack * System.Collections.ArrayList * System.Collections.SortedList * System.Collections.Hashtable * System.IO.StringWriter * System.IO.MemoryStream; Also see: [Marvels of COM .NET interop](http://blog.opennetcf.com/afeinman/PermaLink,guid,aa53e23d-b8e5-4015-b00a-0c8ea9bc6dfe.aspx)
156,467
<p>I've been looking at F# recently, and while I'm not likely to leap the fence any time soon, it definitely highlights some areas where C# (or library support) could make life easier.</p> <p>In particular, I'm thinking about the pattern matching capability of F#, which allows a very rich syntax - much more expressive than the current switch/conditional C# equivalents. I won't try to give a direct example (my F# isn't up to it), but in short it allows:</p> <ul> <li>match by type (with full-coverage checking for discriminated unions) [note this also infers the type for the bound variable, giving member access etc]</li> <li>match by predicate</li> <li>combinations of the above (and possibly some other scenarios I'm not aware of)</li> </ul> <p>While it would be lovely for C# to eventually borrow [ahem] some of this richness, in the interim I've been looking at what can be done at runtime - for example, it is fairly easy to knock together some objects to allow:</p> <pre><code>var getRentPrice = new Switch&lt;Vehicle, int&gt;() .Case&lt;Motorcycle&gt;(bike =&gt; 100 + bike.Cylinders * 10) // "bike" here is typed as Motorcycle .Case&lt;Bicycle&gt;(30) // returns a constant .Case&lt;Car&gt;(car =&gt; car.EngineType == EngineType.Diesel, car =&gt; 220 + car.Doors * 20) .Case&lt;Car&gt;(car =&gt; car.EngineType == EngineType.Gasoline, car =&gt; 200 + car.Doors * 20) .ElseThrow(); // or could use a Default(...) terminator </code></pre> <p>where getRentPrice is a Func&lt;Vehicle,int&gt;.</p> <p>[note - maybe Switch/Case here is the wrong terms... but it shows the idea]</p> <p>To me, this is a lot clearer than the equivalent using repeated if/else, or a composite ternary conditional (which gets very messy for non-trivial expressions - brackets galore). It also avoids a <em>lot</em> of casting, and allows for simple extension (either directly or via extension methods) to more-specific matches, for example an InRange(...) match comparable to the VB Select...Case "x To y" usage.</p> <p><strong>I'm just trying to gauge if people think there is much benefit from constructs like the above (in the absence of language support)?</strong></p> <p>Note additionally that I've been playing with 3 variants of the above:</p> <ul> <li>a Func&lt;TSource,TValue&gt; version for evaluation - comparable to composite ternary conditional statements</li> <li>an Action&lt;TSource&gt; version - comparable to if/else if/else if/else if/else</li> <li>an Expression&lt;Func&lt;TSource,TValue&gt;&gt; version - as the first, but usable by arbitrary LINQ providers</li> </ul> <p>Additionally, using the Expression-based version enables Expression-tree re-writing, essentially inlining all the branches into a single composite conditional Expression, rather than using repeated invocation. I haven't checked recently, but in some early Entity Framework builds I seem to recall this being necessary, as it didn't like InvocationExpression very much. It also allows more efficient usage with LINQ-to-Objects, since it avoids repeated delegate invocations - tests show a match like the above (using the Expression form) performing at the same speed [marginally quicker, in fact] compared to the equivalent C# composite conditional statement. For completeness, the Func&lt;...&gt; based-version took 4 times as long as the C# conditional statement, but is still very quick and is unlikely to be a major bottleneck in most use-cases.</p> <p>I welcome any thoughts / input / critique / etc on the above (or on the possibilities of richer C# language support... here's hoping ;-p).</p>
[ { "answer_id": 156535, "author": "Simon Buchan", "author_id": 20135, "author_profile": "https://Stackoverflow.com/users/20135", "pm_score": 2, "selected": false, "text": "<p>Although it's not very 'C-sharpey' to switch on type, I know that construct would be pretty helpful in general use - I have at least one personal project that could use it (although its managable ATM). Is there much of a compile performance problem, with the expression tree re-writing?</p>\n" }, { "answer_id": 156566, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 5, "selected": false, "text": "<p>I don't think these sorts of libraries (which act like language extensions) are likely to gain wide acceptance, but they are fun to play with, and can be really useful for small teams working in specific domains where this is useful. For instance, if you are writing tons of 'business rules/logic' that does arbitrary type tests like this and whatnot, I can see how it would be handy.</p>\n\n<p>I've no clue if this is ever likely to be a C# language feature (seems doubtful, but who can see the future?).</p>\n\n<p>For reference, the corresponding F# is approximately:</p>\n\n<pre><code>let getRentPrice (v : Vehicle) = \n match v with\n | :? Motorcycle as bike -&gt; 100 + bike.Cylinders * 10\n | :? Bicycle -&gt; 30\n | :? Car as car when car.EngineType = Diesel -&gt; 220 + car.Doors * 20\n | :? Car as car when car.EngineType = Gasoline -&gt; 200 + car.Doors * 20\n | _ -&gt; failwith \"blah\"\n</code></pre>\n\n<p>assuming you'd defined a class hierarchy along the lines of</p>\n\n<pre><code>type Vehicle() = class end\n\ntype Motorcycle(cyl : int) = \n inherit Vehicle()\n member this.Cylinders = cyl\n\ntype Bicycle() = inherit Vehicle()\n\ntype EngineType = Diesel | Gasoline\n\ntype Car(engType : EngineType, doors : int) = \n inherit Vehicle()\n member this.EngineType = engType\n member this.Doors = doors\n</code></pre>\n" }, { "answer_id": 156636, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 5, "selected": false, "text": "<p>Arguably the reason that C# doesn't make it simple to switch on type is because it is primarily an object-oriented language, and the 'correct' way to do this in object-oriented terms would be to define a GetRentPrice method on Vehicle and override it in derived classes.</p>\n\n<p>That said, I've spent a bit of time playing with multi-paradigm and functional languages like F# and Haskell which have this type of capability, and I've come across a number of places where it would be useful before (e.g. when you are not writing the types you need to switch on so you cannot implement a virtual method on them) and it's something I'd welcome into the language along with discriminated unions.</p>\n\n<p><em>[Edit: Removed part about performance as Marc indicated it could be short-circuited]</em></p>\n\n<p>Another potential problem is a usability one - it's clear from the final call what happens if the match fails to meet any conditions, but what is the behaviour if it matches two or more conditions? Should it throw an exception? Should it return the first or the last match?</p>\n\n<p>A way I tend to use to solve this kind of problem is to use a dictionary field with the type as the key and the lambda as the value, which is pretty terse to construct using object initializer syntax; however, this only accounts for the concrete type and doesn't allow additional predicates so may not be suitable for more complex cases. [Side note - if you look at the output of the C# compiler it frequently converts switch statements to dictionary-based jump tables, so there doesn't appear to be a good reason it couldn't support switching on types]</p>\n" }, { "answer_id": 156837, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 2, "selected": false, "text": "<p>One thing to be careful of: the C# compiler is pretty good at optimising switch statements. Not just for short circuiting - you get completely different IL depending on how many cases you have and so on.</p>\n<p>Your specific example does do something I'd find very useful - there is no syntax equivalent to case by type, as (for instance) <code>typeof(Motorcycle)</code> is not a constant.</p>\n<p>This gets more interesting in dynamic application - your logic here could be easily data-driven, giving 'rule-engine' style execution.</p>\n" }, { "answer_id": 195376, "author": "MichaelGG", "author_id": 27012, "author_profile": "https://Stackoverflow.com/users/27012", "pm_score": 5, "selected": false, "text": "<p>After trying to do such \"functional\" things in C# (and even attempting a book on it), I've come to the conclusion that no, with a few exceptions, such things don't help too much.</p>\n\n<p>The main reason is that languages such as F# get a lot of their power from truly supporting these features. Not \"you can do it\", but \"it's simple, it's clear, it's expected\". </p>\n\n<p>For instance, in pattern matching, you get the compiler telling you if there's an incomplete match or when another match will never be hit. This is less useful with open ended types, but when matching a discriminated union or tuples, it's very nifty. In F#, you expect people to pattern match, and it instantly makes sense. </p>\n\n<p>The \"problem\" is that once you start using some functional concepts, it's natural to want to continue. However, leveraging tuples, functions, partial method application and currying, pattern matching, nested functions, generics, monad support, etc. in C# gets <em>very</em> ugly, very quickly. It's fun, and some very smart people have done some very cool things in C#, but actually <em>using</em> it feels heavy.</p>\n\n<p>What I have ended up using often (across-projects) in C#:</p>\n\n<ul>\n<li>Sequence functions, via extension methods for IEnumerable. Things like ForEach or Process (\"Apply\"? -- do an action on a sequence item as it's enumerated) fit in because C# syntax supports it well.</li>\n<li>Abstracting common statement patterns. Complicated try/catch/finally blocks or other involved (often heavily generic) code blocks. Extending LINQ-to-SQL fits in here too. </li>\n<li>Tuples, to some extent.</li>\n</ul>\n\n<p>** But do note: The lack of automatic generalization and type inference really hinder the use of even these features. **</p>\n\n<p>All this said, as someone else mentioned, on a small team, for a specific purpose, yes, perhaps they can help if you're stuck with C#. But in my experience, they usually felt like more hassle than they were worth - YMMV.</p>\n\n<p>Some other links:</p>\n\n<ul>\n<li><a href=\"http://anonsvn.mono-project.com/viewvc/branches/rocks-playground/\" rel=\"noreferrer\">Mono.Rocks playground</a> has many similar things (as well as non-functional-programming-but-useful additions).</li>\n<li><a href=\"http://blogs.msdn.com/lucabol/archive/2008/04/01/a-c-library-to-write-functional-code-part-i-background.aspx\" rel=\"noreferrer\">Luca Bolognese's functional C# library</a> </li>\n<li><a href=\"http://code.msdn.microsoft.com/FunctionalCSharp\" rel=\"noreferrer\">Matthew Podwysocki's functional C# on MSDN</a></li>\n</ul>\n" }, { "answer_id": 999926, "author": "bacila", "author_id": 123511, "author_profile": "https://Stackoverflow.com/users/123511", "pm_score": 3, "selected": false, "text": "<p>In my humble opinion, the object oriented way of doing such things is the Visitor pattern. Your visitor member methods simply act as case constructs and you let the language itself handle the appropriate dispatch without having to &quot;peek&quot; at types.</p>\n" }, { "answer_id": 1270540, "author": "John Leidegren", "author_id": 58961, "author_profile": "https://Stackoverflow.com/users/58961", "pm_score": 3, "selected": false, "text": "<p>The purpose of pattern matching (as described <a href=\"http://en.wikibooks.org/wiki/Haskell/Pattern_matching\" rel=\"nofollow noreferrer\">here</a>) is to deconstruct values according to their type specification. However, the concept of a class (or type) in C# doesn't agree with you.</p>\n<p>There's nothing wrong with multi-paradigm language design, on the contrary, it's very nice to have lambdas in C#, and Haskell can do imperative stuff to e.g. IO. But it's not a very elegant solution, not in Haskell fashion.</p>\n<p>But since sequential procedural programming languages can be understood in terms of lambda calculus, and C# happens to fit well within the parameters of a sequential procedural language, it's a good fit. But, taking something from the pure functional context of, say, Haskell, and then putting that feature into a language which is not pure, well, doing just that will not guarantee a better outcome.</p>\n<p>My point is what makes pattern matching tick is tied to the language design and data model. Having said that, I don't believe pattern matching to be an useful feature of C# because it does not solve typical C# problems, nor does it fit well within the imperative programming paradigm.</p>\n" }, { "answer_id": 7301884, "author": "cdiggins", "author_id": 184528, "author_profile": "https://Stackoverflow.com/users/184528", "pm_score": 4, "selected": false, "text": "<p>Yes I think pattern matching syntactic constructs are useful. I for one would like to see syntactic support in C# for it.</p>\n<p>Here is my implementation of a class that provides (nearly) the same syntax as you describe</p>\n<pre><code>public class PatternMatcher&lt;Output&gt;\n{\n List&lt;Tuple&lt;Predicate&lt;Object&gt;, Func&lt;Object, Output&gt;&gt;&gt; cases = new List&lt;Tuple&lt;Predicate&lt;object&gt;,Func&lt;object,Output&gt;&gt;&gt;();\n\n public PatternMatcher() { } \n\n public PatternMatcher&lt;Output&gt; Case(Predicate&lt;Object&gt; condition, Func&lt;Object, Output&gt; function)\n {\n cases.Add(new Tuple&lt;Predicate&lt;Object&gt;, Func&lt;Object, Output&gt;&gt;(condition, function));\n return this;\n }\n\n public PatternMatcher&lt;Output&gt; Case&lt;T&gt;(Predicate&lt;T&gt; condition, Func&lt;T, Output&gt; function)\n {\n return Case(\n o =&gt; o is T &amp;&amp; condition((T)o), \n o =&gt; function((T)o));\n }\n\n public PatternMatcher&lt;Output&gt; Case&lt;T&gt;(Func&lt;T, Output&gt; function)\n {\n return Case(\n o =&gt; o is T, \n o =&gt; function((T)o));\n }\n\n public PatternMatcher&lt;Output&gt; Case&lt;T&gt;(Predicate&lt;T&gt; condition, Output o)\n {\n return Case(condition, x =&gt; o);\n }\n\n public PatternMatcher&lt;Output&gt; Case&lt;T&gt;(Output o)\n {\n return Case&lt;T&gt;(x =&gt; o);\n }\n\n public PatternMatcher&lt;Output&gt; Default(Func&lt;Object, Output&gt; function)\n {\n return Case(o =&gt; true, function);\n }\n\n public PatternMatcher&lt;Output&gt; Default(Output o)\n {\n return Default(x =&gt; o);\n }\n\n public Output Match(Object o)\n {\n foreach (var tuple in cases)\n if (tuple.Item1(o))\n return tuple.Item2(o);\n throw new Exception(&quot;Failed to match&quot;);\n }\n}\n</code></pre>\n<p>Here is some test code:</p>\n<pre><code> public enum EngineType\n {\n Diesel,\n Gasoline\n }\n\n public class Bicycle\n {\n public int Cylinders;\n }\n\n public class Car\n {\n public EngineType EngineType;\n public int Doors;\n }\n\n public class MotorCycle\n {\n public int Cylinders;\n }\n\n public void Run()\n {\n var getRentPrice = new PatternMatcher&lt;int&gt;()\n .Case&lt;MotorCycle&gt;(bike =&gt; 100 + bike.Cylinders * 10) \n .Case&lt;Bicycle&gt;(30) \n .Case&lt;Car&gt;(car =&gt; car.EngineType == EngineType.Diesel, car =&gt; 220 + car.Doors * 20)\n .Case&lt;Car&gt;(car =&gt; car.EngineType == EngineType.Gasoline, car =&gt; 200 + car.Doors * 20)\n .Default(0);\n\n var vehicles = new object[] {\n new Car { EngineType = EngineType.Diesel, Doors = 2 },\n new Car { EngineType = EngineType.Diesel, Doors = 4 },\n new Car { EngineType = EngineType.Gasoline, Doors = 3 },\n new Car { EngineType = EngineType.Gasoline, Doors = 5 },\n new Bicycle(),\n new MotorCycle { Cylinders = 2 },\n new MotorCycle { Cylinders = 3 },\n };\n\n foreach (var v in vehicles)\n {\n Console.WriteLine(&quot;Vehicle of type {0} costs {1} to rent&quot;, v.GetType(), getRentPrice.Match(v));\n }\n }\n</code></pre>\n" }, { "answer_id": 46201472, "author": "mcintyre321", "author_id": 2086, "author_profile": "https://Stackoverflow.com/users/2086", "pm_score": 1, "selected": false, "text": "<p>You can achieve what you are after by using a library I wrote, called <a href=\"https://github.com/mcintyre321/OneOf\" rel=\"nofollow noreferrer\">OneOf</a></p>\n\n<p>The major advantage over <code>switch</code> (and <code>if</code> and <code>exceptions as control flow</code>) is that it is compile-time safe - there is no default handler or fall through</p>\n\n<pre><code> OneOf&lt;Motorcycle, Bicycle, Car&gt; vehicle = ... //assign from one of those types\n var getRentPrice = vehicle\n .Match(\n bike =&gt; 100 + bike.Cylinders * 10, // \"bike\" here is typed as Motorcycle\n bike =&gt; 30, // returns a constant\n car =&gt; car.EngineType.Match(\n diesel =&gt; 220 + car.Doors * 20\n petrol =&gt; 200 + car.Doors * 20\n )\n );\n</code></pre>\n\n<p>It's on Nuget and targets net451 and netstandard1.6</p>\n" }, { "answer_id": 47795205, "author": "Marcus Pierce", "author_id": 5506486, "author_profile": "https://Stackoverflow.com/users/5506486", "pm_score": 6, "selected": true, "text": "<p>In C# 7, you can do:</p>\n<pre><code>switch(shape)\n{\n case Circle c:\n WriteLine($&quot;circle with radius {c.Radius}&quot;);\n break;\n case Rectangle s when (s.Length == s.Height):\n WriteLine($&quot;{s.Length} x {s.Height} square&quot;);\n break;\n case Rectangle r:\n WriteLine($&quot;{r.Length} x {r.Height} rectangle&quot;);\n break;\n default:\n WriteLine(&quot;&lt;unknown shape&gt;&quot;);\n break;\n case null:\n throw new ArgumentNullException(nameof(shape));\n}\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23354/" ]
I've been looking at F# recently, and while I'm not likely to leap the fence any time soon, it definitely highlights some areas where C# (or library support) could make life easier. In particular, I'm thinking about the pattern matching capability of F#, which allows a very rich syntax - much more expressive than the current switch/conditional C# equivalents. I won't try to give a direct example (my F# isn't up to it), but in short it allows: * match by type (with full-coverage checking for discriminated unions) [note this also infers the type for the bound variable, giving member access etc] * match by predicate * combinations of the above (and possibly some other scenarios I'm not aware of) While it would be lovely for C# to eventually borrow [ahem] some of this richness, in the interim I've been looking at what can be done at runtime - for example, it is fairly easy to knock together some objects to allow: ``` var getRentPrice = new Switch<Vehicle, int>() .Case<Motorcycle>(bike => 100 + bike.Cylinders * 10) // "bike" here is typed as Motorcycle .Case<Bicycle>(30) // returns a constant .Case<Car>(car => car.EngineType == EngineType.Diesel, car => 220 + car.Doors * 20) .Case<Car>(car => car.EngineType == EngineType.Gasoline, car => 200 + car.Doors * 20) .ElseThrow(); // or could use a Default(...) terminator ``` where getRentPrice is a Func<Vehicle,int>. [note - maybe Switch/Case here is the wrong terms... but it shows the idea] To me, this is a lot clearer than the equivalent using repeated if/else, or a composite ternary conditional (which gets very messy for non-trivial expressions - brackets galore). It also avoids a *lot* of casting, and allows for simple extension (either directly or via extension methods) to more-specific matches, for example an InRange(...) match comparable to the VB Select...Case "x To y" usage. **I'm just trying to gauge if people think there is much benefit from constructs like the above (in the absence of language support)?** Note additionally that I've been playing with 3 variants of the above: * a Func<TSource,TValue> version for evaluation - comparable to composite ternary conditional statements * an Action<TSource> version - comparable to if/else if/else if/else if/else * an Expression<Func<TSource,TValue>> version - as the first, but usable by arbitrary LINQ providers Additionally, using the Expression-based version enables Expression-tree re-writing, essentially inlining all the branches into a single composite conditional Expression, rather than using repeated invocation. I haven't checked recently, but in some early Entity Framework builds I seem to recall this being necessary, as it didn't like InvocationExpression very much. It also allows more efficient usage with LINQ-to-Objects, since it avoids repeated delegate invocations - tests show a match like the above (using the Expression form) performing at the same speed [marginally quicker, in fact] compared to the equivalent C# composite conditional statement. For completeness, the Func<...> based-version took 4 times as long as the C# conditional statement, but is still very quick and is unlikely to be a major bottleneck in most use-cases. I welcome any thoughts / input / critique / etc on the above (or on the possibilities of richer C# language support... here's hoping ;-p).
In C# 7, you can do: ``` switch(shape) { case Circle c: WriteLine($"circle with radius {c.Radius}"); break; case Rectangle s when (s.Length == s.Height): WriteLine($"{s.Length} x {s.Height} square"); break; case Rectangle r: WriteLine($"{r.Length} x {r.Height} rectangle"); break; default: WriteLine("<unknown shape>"); break; case null: throw new ArgumentNullException(nameof(shape)); } ```
156,478
<p>I'm implementing a cache in a class library that i'm using in an asp.net application. </p> <p>I created my cache object as a singleton pattern with a static method to update the cache which is really just loading a member variable/property with a collection of data i need cached (got some locking logic ofcourse). I figured it was a nice way to go since i can just access my data by calling </p> <pre><code>MyCacheObject.Instance.MyDataCollection </code></pre> <p>I'm creating a new cache object to store a pretty big amount of data partitioned by some key. What i'm saying is i'm creating a new cache but this one will not load all of the data at once, but rather store a collection for each key accessed.</p> <pre><code>MyOtherCacheObject.Instance.MyOtherDataCollection(indexkey) </code></pre> <p>This time the question about garbage collection was brought up. Since i'm storing a huge amount of data, wouldn't it be a waste if it got gc'ed all of a sudden? Since it's just a singleton pattern there is nothing ensuring data will stay in cache.</p> <p>So my question is - what is best practice for implemeting a cache to handle this situation? I really don't like a huge complex solution to this, and i know there is caching in System.Web but that seems a bit 'off' since this is just a class library, or what do you think?</p>
[ { "answer_id": 156481, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 1, "selected": false, "text": "<p>The data wouldn't get garbage collected as long as the cache still holds a reference to it.</p>\n\n<p>Also, don't ever use Singletons.</p>\n" }, { "answer_id": 156506, "author": "Sergio Acosta", "author_id": 2954, "author_profile": "https://Stackoverflow.com/users/2954", "pm_score": 4, "selected": true, "text": "<p>In my opinion, the best solution would have the following characteristics:</p>\n<ul>\n<li><p>Uses the available caching services provided by the platform trying to avoid writing your own.</p>\n</li>\n<li><p>Does not couple your class library to System.Web, in order to have the layers coherent.</p>\n</li>\n<li><p>But if the class library is running inside an ASP.NET application the solution should not require to bring another caching implementation on (for example, the Enterprise Library Caching Application Block), which requires additional configuration and setup.</p>\n</li>\n</ul>\n<p>So, I would use an IoC strategy in order to allow the class library to use different caching implementations, based on the environment it is running on.</p>\n<p>Suppose you define your abstract caching contract as:</p>\n<pre><code>public interface ICacheService \n{\n AddItem(...);\n}\n</code></pre>\n<p>You could provide an implementation based on System.Web:</p>\n<pre><code>public AspNetBasedCacheService : ICacheService\n{\n AddItem(...)\n {\n // Implementation that uses the HttpContext.Cache object\n }\n }\n</code></pre>\n<p>And then have that implementation 'published' as singleton. Note that the difference with your original approach is that the singleton is just a reference to the ASP.NET cache service based implementation, instead of the full 'cache object'.</p>\n<pre><code>public class CacheServiceProvider \n{\n public static ICacheService Instance {get; set;}\n\n}\n</code></pre>\n<p>You would have to initialize the caching implementation either by performing lazy initialization, or at application startup (in <code>Global.asax.cs</code>)</p>\n<p>And every domain component would be able to use the published caching service without knowing that it is implemented based on System.Web.</p>\n<pre><code>// inside your class library:\nICacheService cache = CacheServiceProvider.Instance;\ncache.AddItem(...);\n</code></pre>\n<p>I agree that it is probably not the simplest solution, but I'm aiming for taking advantage of the ASP.NET cache implementation without sacrificing code decoupling and flexibility.</p>\n<p>I hope I understood your question right.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11619/" ]
I'm implementing a cache in a class library that i'm using in an asp.net application. I created my cache object as a singleton pattern with a static method to update the cache which is really just loading a member variable/property with a collection of data i need cached (got some locking logic ofcourse). I figured it was a nice way to go since i can just access my data by calling ``` MyCacheObject.Instance.MyDataCollection ``` I'm creating a new cache object to store a pretty big amount of data partitioned by some key. What i'm saying is i'm creating a new cache but this one will not load all of the data at once, but rather store a collection for each key accessed. ``` MyOtherCacheObject.Instance.MyOtherDataCollection(indexkey) ``` This time the question about garbage collection was brought up. Since i'm storing a huge amount of data, wouldn't it be a waste if it got gc'ed all of a sudden? Since it's just a singleton pattern there is nothing ensuring data will stay in cache. So my question is - what is best practice for implemeting a cache to handle this situation? I really don't like a huge complex solution to this, and i know there is caching in System.Web but that seems a bit 'off' since this is just a class library, or what do you think?
In my opinion, the best solution would have the following characteristics: * Uses the available caching services provided by the platform trying to avoid writing your own. * Does not couple your class library to System.Web, in order to have the layers coherent. * But if the class library is running inside an ASP.NET application the solution should not require to bring another caching implementation on (for example, the Enterprise Library Caching Application Block), which requires additional configuration and setup. So, I would use an IoC strategy in order to allow the class library to use different caching implementations, based on the environment it is running on. Suppose you define your abstract caching contract as: ``` public interface ICacheService { AddItem(...); } ``` You could provide an implementation based on System.Web: ``` public AspNetBasedCacheService : ICacheService { AddItem(...) { // Implementation that uses the HttpContext.Cache object } } ``` And then have that implementation 'published' as singleton. Note that the difference with your original approach is that the singleton is just a reference to the ASP.NET cache service based implementation, instead of the full 'cache object'. ``` public class CacheServiceProvider { public static ICacheService Instance {get; set;} } ``` You would have to initialize the caching implementation either by performing lazy initialization, or at application startup (in `Global.asax.cs`) And every domain component would be able to use the published caching service without knowing that it is implemented based on System.Web. ``` // inside your class library: ICacheService cache = CacheServiceProvider.Instance; cache.AddItem(...); ``` I agree that it is probably not the simplest solution, but I'm aiming for taking advantage of the ASP.NET cache implementation without sacrificing code decoupling and flexibility. I hope I understood your question right.
156,492
<p>I have built a CFC designed to serve as a dynamic, aging cache intended for almost everything worth caching. LDAP queries, function results, arrays, ojects, you name it. Whatever takes time or resources to calculate and is needed more than once. I'd like to be able to do a few things:</p> <ul> <li><strong>share the CFC between applications</strong></li> <li><strong>define the scope of the cache (server / application / session / current request only)</strong></li> <li>use different cache instances at the same time, in the same request</li> <li>be independent from CFCs using the cache component</li> <li>generally adhere to common sense (decoupling, encapsulation, orthogonality, locking)</li> </ul> <p>I would of course be using a different cache instance for every distinct task, but I'd like to be able to use the same CFC across applications. The cache itself is (what else) a Struct, private to the cache instance. How would I properly implement caching and locking when the scope itself is subject to change?</p> <p>For locking, I use named locks (<code>'CacheRead'</code>, <code>'CacheWrite'</code>) currently, this is safe but strikes me as odd. Why would I want a server-wide lock for, say, a session-only operation? (Yes, maybe this <em>is</em> academic, but anyway.)</p> <p>Passing in the APPLICATION scope as a reference when I want application level caching also seems the wrong thing to do. Is there a better way?</p>
[ { "answer_id": 161777, "author": "JG.", "author_id": 7807, "author_profile": "https://Stackoverflow.com/users/7807", "pm_score": 2, "selected": false, "text": "<p>Okay - since I misunderstood your question initially I've deleted my previous answer as to not cause any further confusion.</p>\n\n<p>To answer your question about locking:</p>\n\n<p>Named locks should be fine because they don't have to always have the same name. You can name them dynamically depending on what cache you are accessing. When you need to access an element of the private struct you could do something like have the named lock use the key as its name.</p>\n\n<p>This way, the only time a lock would have an effect is if something was trying to access the same cache by name.</p>\n" }, { "answer_id": 240702, "author": "Adam Tuttle", "author_id": 751, "author_profile": "https://Stackoverflow.com/users/751", "pm_score": 2, "selected": true, "text": "<p>I understand your desire to avoid passing in the actual scope structure that you want to cache to, but your alternatives are limited. The first thing that comes to mind is just passing the name (a string) of the scope you want your cache stored in, and evaluating. By its nature, evaluation is inefficient and should be avoided. That said, I was curious how it might be accomplished. I don't have your code so I just made a dirt-simple \"storage\" abstraction CFC (skipped caching, as it's irrelevant to what I want to test) here:</p>\n\n<p><strong>cache.cfc:</strong></p>\n\n<pre><code>&lt;cfcomponent&gt;\n &lt;cfset variables.cacheScope = \"session\" /&gt;&lt;!--- default to session ---&gt;\n &lt;cfset variables.cache = \"\"/&gt;\n\n &lt;cfscript&gt;\n function init(scope){\n variables.cacheScope = arguments.scope;\n return this;\n }\n\n function cacheWrite(key, value){\n structInsert(evaluate(variables.cacheScope),arguments.key,arguments.value,true);\n return this;\n }\n\n function cacheRead(key){\n if (not structKeyExists(evaluate(variables.cacheScope), arguments.key)){\n return \"\";\n }else{\n variables.cache = evaluate(variables.cacheScope);\n return variables.cache[arguments.key];\n }\n } \n &lt;/cfscript&gt;\n&lt;/cfcomponent&gt;\n</code></pre>\n\n<p>And a view to test it:</p>\n\n<pre><code>&lt;!--- clear out any existing session vars ---&gt;\n&lt;cfset structClear(session)/&gt;\n&lt;!--- show empty session struct ---&gt;\n&lt;cfdump var=\"#session#\" label=\"session vars\"&gt;\n&lt;!--- create storage object ---&gt;\n&lt;cfset cacher = createObject(\"component\", \"cache\").init(\"session\")/&gt;\n&lt;!--- store a value ---&gt;\n&lt;cfset cacher.cacheWrite(\"foo\", \"bar\")/&gt;\n&lt;!--- read stored value ---&gt;\n&lt;cfset rtn = cacher.cacheRead(\"foo\")/&gt;\n&lt;!--- show values ---&gt;\n&lt;cfdump var=\"#rtn#\"&gt;\n&lt;cfdump var=\"#session#\" label=\"session vars\"&gt;\n</code></pre>\n\n<p><em>Off topic: I like to write my setter functions to return \"this\" [as seen above] so that I can chain method calls like jQuery. Part of the view could just as easily been written as:</em></p>\n\n<pre><code>&lt;cfset rtn = createObject(\"component\", \"cache\")\n .init(\"session\")\n .cacheWrite(\"foo\", \"bar\")\n .cacheRead(\"foo\")/&gt;\n</code></pre>\n\n<p>It's interesting that this is possible, but I probably wouldn't use it in production due to the overhead cost of Evaluate. I'd say that this is valid enough reason to pass in the scope you want to cache into.</p>\n\n<p>If you're still bothered by it (and maybe rightly so?), you could create another CFC that abstracts reading and writing from the desired scope and pass that into your caching CFC as the storage location (a task well-suited for <a href=\"http://coldspringframework.org/\" rel=\"nofollow noreferrer\">ColdSpring</a>), that way if you ever decide to move the cache into another scope, you don't have to edit 300 pages all using your cache CFC passing in \"session\" to init, and instead you can edit 1 CFC or your ColdSpring config.</p>\n\n<p>I'm not entirely sure why you would want to have single-request caching though, when you have the request scope. If what you're looking for is a way to cache something for the current request and have it die shortly afterward, request scope may be what you want. Caching is usually more valuable when it spans multiple requests.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18771/" ]
I have built a CFC designed to serve as a dynamic, aging cache intended for almost everything worth caching. LDAP queries, function results, arrays, ojects, you name it. Whatever takes time or resources to calculate and is needed more than once. I'd like to be able to do a few things: * **share the CFC between applications** * **define the scope of the cache (server / application / session / current request only)** * use different cache instances at the same time, in the same request * be independent from CFCs using the cache component * generally adhere to common sense (decoupling, encapsulation, orthogonality, locking) I would of course be using a different cache instance for every distinct task, but I'd like to be able to use the same CFC across applications. The cache itself is (what else) a Struct, private to the cache instance. How would I properly implement caching and locking when the scope itself is subject to change? For locking, I use named locks (`'CacheRead'`, `'CacheWrite'`) currently, this is safe but strikes me as odd. Why would I want a server-wide lock for, say, a session-only operation? (Yes, maybe this *is* academic, but anyway.) Passing in the APPLICATION scope as a reference when I want application level caching also seems the wrong thing to do. Is there a better way?
I understand your desire to avoid passing in the actual scope structure that you want to cache to, but your alternatives are limited. The first thing that comes to mind is just passing the name (a string) of the scope you want your cache stored in, and evaluating. By its nature, evaluation is inefficient and should be avoided. That said, I was curious how it might be accomplished. I don't have your code so I just made a dirt-simple "storage" abstraction CFC (skipped caching, as it's irrelevant to what I want to test) here: **cache.cfc:** ``` <cfcomponent> <cfset variables.cacheScope = "session" /><!--- default to session ---> <cfset variables.cache = ""/> <cfscript> function init(scope){ variables.cacheScope = arguments.scope; return this; } function cacheWrite(key, value){ structInsert(evaluate(variables.cacheScope),arguments.key,arguments.value,true); return this; } function cacheRead(key){ if (not structKeyExists(evaluate(variables.cacheScope), arguments.key)){ return ""; }else{ variables.cache = evaluate(variables.cacheScope); return variables.cache[arguments.key]; } } </cfscript> </cfcomponent> ``` And a view to test it: ``` <!--- clear out any existing session vars ---> <cfset structClear(session)/> <!--- show empty session struct ---> <cfdump var="#session#" label="session vars"> <!--- create storage object ---> <cfset cacher = createObject("component", "cache").init("session")/> <!--- store a value ---> <cfset cacher.cacheWrite("foo", "bar")/> <!--- read stored value ---> <cfset rtn = cacher.cacheRead("foo")/> <!--- show values ---> <cfdump var="#rtn#"> <cfdump var="#session#" label="session vars"> ``` *Off topic: I like to write my setter functions to return "this" [as seen above] so that I can chain method calls like jQuery. Part of the view could just as easily been written as:* ``` <cfset rtn = createObject("component", "cache") .init("session") .cacheWrite("foo", "bar") .cacheRead("foo")/> ``` It's interesting that this is possible, but I probably wouldn't use it in production due to the overhead cost of Evaluate. I'd say that this is valid enough reason to pass in the scope you want to cache into. If you're still bothered by it (and maybe rightly so?), you could create another CFC that abstracts reading and writing from the desired scope and pass that into your caching CFC as the storage location (a task well-suited for [ColdSpring](http://coldspringframework.org/)), that way if you ever decide to move the cache into another scope, you don't have to edit 300 pages all using your cache CFC passing in "session" to init, and instead you can edit 1 CFC or your ColdSpring config. I'm not entirely sure why you would want to have single-request caching though, when you have the request scope. If what you're looking for is a way to cache something for the current request and have it die shortly afterward, request scope may be what you want. Caching is usually more valuable when it spans multiple requests.
156,503
<p>How can I use JUnit idiomatically to test that some code throws an exception?</p> <p>While I can certainly do something like this:</p> <pre><code>@Test public void testFooThrowsIndexOutOfBoundsException() { boolean thrown = false; try { foo.doStuff(); } catch (IndexOutOfBoundsException e) { thrown = true; } assertTrue(thrown); } </code></pre> <p>I recall that there is an annotation or an Assert.xyz or <em>something</em> that is far less kludgy and far more in-the-spirit of JUnit for these sorts of situations.</p>
[ { "answer_id": 156515, "author": "Johan", "author_id": 11347, "author_profile": "https://Stackoverflow.com/users/11347", "pm_score": 5, "selected": false, "text": "<p>How about this: catch a very general exception, make sure it makes it out of the catch block, then assert that the class of the exception is what you expect it to be. This assert will fail if a) the exception is of the wrong type (eg. if you got a Null Pointer instead) and b) the exception wasn't ever thrown.</p>\n<pre><code>public void testFooThrowsIndexOutOfBoundsException() {\n Throwable e = null;\n\n try {\n foo.doStuff();\n } catch (Throwable ex) {\n e = ex;\n }\n\n assertTrue(e instanceof IndexOutOfBoundsException);\n}\n</code></pre>\n" }, { "answer_id": 156518, "author": "Mark Bessey", "author_id": 17826, "author_profile": "https://Stackoverflow.com/users/17826", "pm_score": 4, "selected": false, "text": "<p>JUnit has built-in support for this, with an <a href=\"http://junit.sourceforge.net/doc/faq/faq.htm#tests_7\" rel=\"nofollow noreferrer\">&quot;expected&quot; attribute</a>.</p>\n" }, { "answer_id": 156528, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 12, "selected": true, "text": "<p>It depends on the JUnit version and what assert libraries you use.</p>\n<ul>\n<li>For JUnit5 and 4.13 <a href=\"https://stackoverflow.com/a/2935935/2986984\">see answer</a></li>\n<li>If you use AssertJ or google-truth, <a href=\"https://stackoverflow.com/a/41019785/2986984\">see answer</a></li>\n</ul>\n<p>The original answer for <code>JUnit &lt;= 4.12</code> was:</p>\n<pre class=\"lang-java prettyprint-override\"><code> @Test(expected = IndexOutOfBoundsException.class)\n public void testIndexOutOfBoundsException() {\n\n ArrayList emptyList = new ArrayList();\n Object o = emptyList.get(0);\n\n }\n</code></pre>\n<p>Though <a href=\"https://stackoverflow.com/a/31826781/2986984\">answer</a> has more options for JUnit &lt;= 4.12.</p>\n<p>Reference:</p>\n<ul>\n<li><a href=\"https://junit.org/junit4/faq.html#atests_7\" rel=\"nofollow noreferrer\">JUnit Test-FAQ</a></li>\n</ul>\n" }, { "answer_id": 156868, "author": "daveb", "author_id": 11858, "author_profile": "https://Stackoverflow.com/users/11858", "pm_score": 9, "selected": false, "text": "<p>Be careful using expected exception, because it only asserts that the <strong>method</strong> threw that exception, not a <strong>particular line of code</strong> in the test.</p>\n\n<p>I tend to use this for testing parameter validation, because such methods are usually very simple, but more complex tests might better be served with:</p>\n\n<pre><code>try {\n methodThatShouldThrow();\n fail( \"My method didn't throw when I expected it to\" );\n} catch (MyException expectedException) {\n}\n</code></pre>\n\n<p>Apply judgement.</p>\n" }, { "answer_id": 2935935, "author": "NamshubWriter", "author_id": 95725, "author_profile": "https://Stackoverflow.com/users/95725", "pm_score": 10, "selected": false, "text": "<p><strong>Edit:</strong> Now that JUnit 5 and JUnit 4.13 have been released, the best option would be to use <a href=\"https://junit.org/junit5/docs/current/user-guide/#extensions-exception-handling\" rel=\"noreferrer\"><code>Assertions.assertThrows()</code></a> (for JUnit 5) and <a href=\"https://junit.org/junit4/javadoc/latest/org/junit/Assert.html#assertThrows(java.lang.Class,%20org.junit.function.ThrowingRunnable)\" rel=\"noreferrer\"><code>Assert.assertThrows()</code></a> (for JUnit 4.13+). See <a href=\"https://stackoverflow.com/a/46514550/95725\">my other answer</a> for details.</p>\n<p>If you haven't migrated to JUnit 5, but can use JUnit 4.7, you can use the <a href=\"http://junit.org/javadoc/latest/org/junit/rules/ExpectedException.html\" rel=\"noreferrer\"><code>ExpectedException</code></a> Rule:</p>\n<pre><code>public class FooTest {\n @Rule\n public final ExpectedException exception = ExpectedException.none();\n\n @Test\n public void doStuffThrowsIndexOutOfBoundsException() {\n Foo foo = new Foo();\n\n exception.expect(IndexOutOfBoundsException.class);\n foo.doStuff();\n }\n}\n</code></pre>\n<p>This is much better than <code>@Test(expected=IndexOutOfBoundsException.class)</code> because the test will fail if <code>IndexOutOfBoundsException</code> is thrown before <code>foo.doStuff()</code></p>\n<p>See <a href=\"http://www.infoq.com/news/2009/07/junit-4.7-rules\" rel=\"noreferrer\">this article</a> for details.</p>\n" }, { "answer_id": 7927418, "author": "rwitzel", "author_id": 998938, "author_profile": "https://Stackoverflow.com/users/998938", "pm_score": 5, "selected": false, "text": "<p>To solve the same problem I did set up a small project: \n<a href=\"http://code.google.com/p/catch-exception/\">http://code.google.com/p/catch-exception/</a></p>\n\n<p>Using this little helper you would write</p>\n\n<pre><code>verifyException(foo, IndexOutOfBoundsException.class).doStuff();\n</code></pre>\n\n<p>This is less verbose than the ExpectedException rule of JUnit 4.7.\nIn comparison to the solution provided by skaffman, you can specify in which line of code you expect the exception. I hope this helps.</p>\n" }, { "answer_id": 12822499, "author": "Hugh Perkins", "author_id": 212731, "author_profile": "https://Stackoverflow.com/users/212731", "pm_score": 4, "selected": false, "text": "<p>I tried many of the methods here, but they were either complicated or didn't quite meet my requirements. In fact, one can write a helper method quite simply:</p>\n\n<pre><code>public class ExceptionAssertions {\n public static void assertException(BlastContainer blastContainer ) {\n boolean caughtException = false;\n try {\n blastContainer.test();\n } catch( Exception e ) {\n caughtException = true;\n }\n if( !caughtException ) {\n throw new AssertionFailedError(\"exception expected to be thrown, but was not\");\n }\n }\n public static interface BlastContainer {\n public void test() throws Exception;\n }\n}\n</code></pre>\n\n<p>Use it like this:</p>\n\n<pre><code>assertException(new BlastContainer() {\n @Override\n public void test() throws Exception {\n doSomethingThatShouldExceptHere();\n }\n});\n</code></pre>\n\n<p>Zero dependencies: no need for mockito, no need powermock; and works just fine with final classes.</p>\n" }, { "answer_id": 16424903, "author": "John Mikic", "author_id": 1636207, "author_profile": "https://Stackoverflow.com/users/1636207", "pm_score": 5, "selected": false, "text": "<p>You can also do this:</p>\n\n<pre><code>@Test\npublic void testFooThrowsIndexOutOfBoundsException() {\n try {\n foo.doStuff();\n assert false;\n } catch (IndexOutOfBoundsException e) {\n assert true;\n }\n}\n</code></pre>\n" }, { "answer_id": 16948961, "author": "Tor P", "author_id": 1218054, "author_profile": "https://Stackoverflow.com/users/1218054", "pm_score": 3, "selected": false, "text": "<p>Just make a Matcher that can be turned off and on, like this:</p>\n\n<pre><code>public class ExceptionMatcher extends BaseMatcher&lt;Throwable&gt; {\n private boolean active = true;\n private Class&lt;? extends Throwable&gt; throwable;\n\n public ExceptionMatcher(Class&lt;? extends Throwable&gt; throwable) {\n this.throwable = throwable;\n }\n\n public void on() {\n this.active = true;\n }\n\n public void off() {\n this.active = false;\n }\n\n @Override\n public boolean matches(Object object) {\n return active &amp;&amp; throwable.isAssignableFrom(object.getClass());\n }\n\n @Override\n public void describeTo(Description description) {\n description.appendText(\"not the covered exception type\");\n }\n}\n</code></pre>\n\n<p>To use it:</p>\n\n<p>add <code>public ExpectedException exception = ExpectedException.none();</code>,\nthen:</p>\n\n<pre><code>ExceptionMatcher exMatch = new ExceptionMatcher(MyException.class);\nexception.expect(exMatch);\nsomeObject.somethingThatThrowsMyException();\nexMatch.off();\n</code></pre>\n" }, { "answer_id": 17421500, "author": "Macchiatow", "author_id": 1161494, "author_profile": "https://Stackoverflow.com/users/1161494", "pm_score": 3, "selected": false, "text": "<p>In my case I always get RuntimeException from db, but messages differ. And exception need to be handled respectively. Here is how I tested it:</p>\n\n<pre><code>@Test\npublic void testThrowsExceptionWhenWrongSku() {\n\n // Given\n String articleSimpleSku = \"999-999\";\n int amountOfTransactions = 1;\n Exception exception = null;\n\n // When\n try {\n createNInboundTransactionsForSku(amountOfTransactions, articleSimpleSku);\n } catch (RuntimeException e) {\n exception = e;\n }\n\n // Then\n shouldValidateThrowsExceptionWithMessage(exception, MESSAGE_NON_EXISTENT_SKU);\n}\n\nprivate void shouldValidateThrowsExceptionWithMessage(final Exception e, final String message) {\n assertNotNull(e);\n assertTrue(e.getMessage().contains(message));\n}\n</code></pre>\n" }, { "answer_id": 20008854, "author": "MariuszS", "author_id": 516167, "author_profile": "https://Stackoverflow.com/users/516167", "pm_score": 5, "selected": false, "text": "<h2><a href=\"http://guide.agilealliance.org/guide/gwt.html\" rel=\"nofollow noreferrer\">BDD</a> Style Solution: <a href=\"http://junit.org/\" rel=\"nofollow noreferrer\">JUnit 4</a> + <a href=\"https://github.com/Codearte/catch-exception\" rel=\"nofollow noreferrer\">Catch Exception</a> + <a href=\"http://joel-costigliola.github.io/assertj/\" rel=\"nofollow noreferrer\">AssertJ</a></h2>\n\n<pre><code>import static com.googlecode.catchexception.apis.BDDCatchException.*;\n\n@Test\npublic void testFooThrowsIndexOutOfBoundsException() {\n\n when(() -&gt; foo.doStuff());\n\n then(caughtException()).isInstanceOf(IndexOutOfBoundsException.class);\n\n}\n</code></pre>\n\n<h2>Dependencies</h2>\n\n<pre><code>eu.codearte.catch-exception:catch-exception:2.0\n</code></pre>\n" }, { "answer_id": 24621006, "author": "Rafal Borowiec", "author_id": 718515, "author_profile": "https://Stackoverflow.com/users/718515", "pm_score": 8, "selected": false, "text": "<p>As answered before, there are many ways of dealing with exceptions in JUnit. But with Java 8 there is another one: using Lambda Expressions. With Lambda Expressions we can achieve a syntax like this:</p>\n\n<pre><code>@Test\npublic void verifiesTypeAndMessage() {\n assertThrown(new DummyService()::someMethod)\n .isInstanceOf(RuntimeException.class)\n .hasMessage(\"Runtime exception occurred\")\n .hasMessageStartingWith(\"Runtime\")\n .hasMessageEndingWith(\"occurred\")\n .hasMessageContaining(\"exception\")\n .hasNoCause();\n}\n</code></pre>\n\n<p>assertThrown accepts a functional interface, whose instances can be created with lambda expressions, method references, or constructor references. assertThrown accepting that interface will expect and be ready to handle an exception.</p>\n\n<p>This is relatively simple yet powerful technique.</p>\n\n<p>Have a look at this blog post describing this technique: <a href=\"http://blog.codeleak.pl/2014/07/junit-testing-exception-with-java-8-and-lambda-expressions.html\" rel=\"noreferrer\">http://blog.codeleak.pl/2014/07/junit-testing-exception-with-java-8-and-lambda-expressions.html</a></p>\n\n<p>The source code can be found here: <a href=\"https://github.com/kolorobot/unit-testing-demo/tree/master/src/test/java/com/github/kolorobot/exceptions/java8\" rel=\"noreferrer\">https://github.com/kolorobot/unit-testing-demo/tree/master/src/test/java/com/github/kolorobot/exceptions/java8</a></p>\n\n<p><em>Disclosure: I am the author of the blog and the project.</em></p>\n" }, { "answer_id": 28940773, "author": "Shessuky", "author_id": 1387275, "author_profile": "https://Stackoverflow.com/users/1387275", "pm_score": 3, "selected": false, "text": "<p>We can use an assertion fail after the method that must return an exception:</p>\n\n<pre><code>try{\n methodThatThrowMyException();\n Assert.fail(\"MyException is not thrown !\");\n} catch (final Exception exception) {\n // Verify if the thrown exception is instance of MyException, otherwise throws an assert failure\n assertTrue(exception instanceof MyException, \"An exception other than MyException is thrown !\");\n // In case of verifying the error message\n MyException myException = (MyException) exception;\n assertEquals(\"EXPECTED ERROR MESSAGE\", myException.getMessage());\n}\n</code></pre>\n" }, { "answer_id": 28974751, "author": "Alex Collins", "author_id": 1055223, "author_profile": "https://Stackoverflow.com/users/1055223", "pm_score": 4, "selected": false, "text": "<p>IMHO, the best way to check for exceptions in JUnit is the try/catch/fail/assert pattern:</p>\n\n<pre><code>// this try block should be as small as possible,\n// as you want to make sure you only catch exceptions from your code\ntry {\n sut.doThing();\n fail(); // fail if this does not throw any exception\n} catch(MyException e) { // only catch the exception you expect,\n // otherwise you may catch an exception for a dependency unexpectedly\n // a strong assertion on the message, \n // in case the exception comes from anywhere an unexpected line of code,\n // especially important if your checking IllegalArgumentExceptions\n assertEquals(\"the message I get\", e.getMessage()); \n}\n</code></pre>\n\n<p>The <code>assertTrue</code> might be a bit strong for some people, so <code>assertThat(e.getMessage(), containsString(\"the message\");</code> might be preferable.</p>\n" }, { "answer_id": 30404203, "author": "Srini", "author_id": 3281476, "author_profile": "https://Stackoverflow.com/users/3281476", "pm_score": 3, "selected": false, "text": "<p>Additionally to what <a href=\"https://stackoverflow.com/users/95725/namshubwriter\">NamShubWriter</a> has said, make sure that: </p>\n\n<ul>\n<li>The ExpectedException instance is <strong>public</strong> (<a href=\"https://stackoverflow.com/questions/14335558/why-rule-annotated-fields-in-junit-has-to-be-public\">Related Question</a>)</li>\n<li>The ExpectedException <strong>isn't</strong> instantiated in say, the @Before method. This <a href=\"https://garygregory.wordpress.com/2011/09/25/understaning-junit-method-order-execution/\" rel=\"nofollow noreferrer\">post</a> clearly explains all the intricacies of JUnit's order of execution.</li>\n</ul>\n\n<p>Do <strong>not</strong> do this: </p>\n\n<pre><code>@Rule \npublic ExpectedException expectedException;\n\n@Before\npublic void setup()\n{\n expectedException = ExpectedException.none();\n}\n</code></pre>\n\n<p>Finally, <a href=\"http://jakegoulding.com/blog/2012/09/26/be-careful-when-using-junit-expected-exceptions/\" rel=\"nofollow noreferrer\">this</a> blog post clearly illustrates how to assert that a certain exception is thrown.</p>\n" }, { "answer_id": 31826781, "author": "walsh", "author_id": 4101415, "author_profile": "https://Stackoverflow.com/users/4101415", "pm_score": 8, "selected": false, "text": "<p>in junit, there are four ways to test exception. </p>\n\n<h2>junit5.x</h2>\n\n<ul>\n<li><p>for junit5.x, you can use <code>assertThrows</code> as following</p>\n\n<pre><code>@Test\npublic void testFooThrowsIndexOutOfBoundsException() {\n Throwable exception = assertThrows(IndexOutOfBoundsException.class, () -&gt; foo.doStuff());\n assertEquals(\"expected messages\", exception.getMessage());\n}\n</code></pre></li>\n</ul>\n\n<h2>junit4.x</h2>\n\n<ul>\n<li><p>for junit4.x, use the optional 'expected' attribute of Test annonation</p>\n\n<pre><code>@Test(expected = IndexOutOfBoundsException.class)\npublic void testFooThrowsIndexOutOfBoundsException() {\n foo.doStuff();\n}\n</code></pre></li>\n<li><p>for junit4.x, use the ExpectedException rule</p>\n\n<pre><code>public class XxxTest {\n @Rule\n public ExpectedException thrown = ExpectedException.none();\n\n @Test\n public void testFooThrowsIndexOutOfBoundsException() {\n thrown.expect(IndexOutOfBoundsException.class)\n //you can test the exception message like\n thrown.expectMessage(\"expected messages\");\n foo.doStuff();\n }\n}\n</code></pre></li>\n<li><p>you also can use the classic try/catch way widely used under junit 3 framework</p>\n\n<pre><code>@Test\npublic void testFooThrowsIndexOutOfBoundsException() {\n try {\n foo.doStuff();\n fail(\"expected exception was not occured.\");\n } catch(IndexOutOfBoundsException e) {\n //if execution reaches here, \n //it indicates this exception was occured.\n //so we need not handle it.\n }\n}\n</code></pre></li>\n<li><p>so</p>\n\n<ul>\n<li>if you like junit 5, then you should like the 1st one</li>\n<li>the 2nd way is used when you only want test the type of exception</li>\n<li>the first and last two are used when you want test exception message further</li>\n<li>if you use junit 3, then the 4th one is preferred</li>\n</ul></li>\n<li><p>for more info, you can read <a href=\"https://github.com/junit-team/junit/wiki/Exception-testing\" rel=\"noreferrer\">this document</a> and <a href=\"https://junit.org/junit5/docs/current/user-guide/\" rel=\"noreferrer\">junit5 user guide</a> for details.</p></li>\n</ul>\n" }, { "answer_id": 34362168, "author": "Mike Nakis", "author_id": 773113, "author_profile": "https://Stackoverflow.com/users/773113", "pm_score": 3, "selected": false, "text": "<h1>Java 8 solution</h1>\n<p>If you would like a solution which:</p>\n<ul>\n<li>Utilizes Java 8 lambdas</li>\n<li>Does <em>not</em> depend on any JUnit magic</li>\n<li>Allows you to check for multiple exceptions within a single test method</li>\n<li>Checks for an exception being thrown by a specific set of lines within your test method instead of any unknown line in the entire test method</li>\n<li>Yields the actual exception object that was thrown so that you can further examine it</li>\n</ul>\n<p>Here is a utility function that I wrote:</p>\n<pre><code>public final &lt;T extends Throwable&gt; T expectException( Class&lt;T&gt; exceptionClass, Runnable runnable )\n{\n try\n {\n runnable.run();\n }\n catch( Throwable throwable )\n {\n if( throwable instanceof AssertionError &amp;&amp; throwable.getCause() != null )\n throwable = throwable.getCause(); //allows testing for &quot;assert x != null : new IllegalArgumentException();&quot;\n assert exceptionClass.isInstance( throwable ) : throwable; //exception of the wrong kind was thrown.\n assert throwable.getClass() == exceptionClass : throwable; //exception thrown was a subclass, but not the exact class, expected.\n @SuppressWarnings( &quot;unchecked&quot; )\n T result = (T)throwable;\n return result;\n }\n assert false; //expected exception was not thrown.\n return null; //to keep the compiler happy.\n}\n</code></pre>\n<p>(<a href=\"http://blog.michael.gr/2014/09/assertions-and-testing.html\" rel=\"nofollow noreferrer\">taken from my blog</a>)</p>\n<p>Use it as follows:</p>\n<pre><code>@Test\npublic void testMyFunction()\n{\n RuntimeException e = expectException( RuntimeException.class, () -&gt; \n {\n myFunction();\n } );\n assert e.getMessage().equals( &quot;I haz fail!&quot; );\n}\n\npublic void myFunction()\n{\n throw new RuntimeException( &quot;I haz fail!&quot; );\n}\n</code></pre>\n" }, { "answer_id": 35813323, "author": "weston", "author_id": 360211, "author_profile": "https://Stackoverflow.com/users/360211", "pm_score": 5, "selected": false, "text": "<p>Using an <a href=\"http://joel-costigliola.github.io/assertj/\" rel=\"noreferrer\">AssertJ</a> assertion, which can be used alongside JUnit:</p>\n\n<pre><code>import static org.assertj.core.api.Assertions.*;\n\n@Test\npublic void testFooThrowsIndexOutOfBoundsException() {\n Foo foo = new Foo();\n\n assertThatThrownBy(() -&gt; foo.doStuff())\n .isInstanceOf(IndexOutOfBoundsException.class);\n}\n</code></pre>\n\n<p>It's better than <code>@Test(expected=IndexOutOfBoundsException.class)</code> because it guarantees the expected line in the test threw the exception and lets you check more details about the exception, such as message, easier:</p>\n\n<pre><code>assertThatThrownBy(() -&gt;\n {\n throw new Exception(\"boom!\");\n })\n .isInstanceOf(Exception.class)\n .hasMessageContaining(\"boom\");\n</code></pre>\n\n<p><a href=\"http://joel-costigliola.github.io/assertj/assertj-core-quick-start.html\" rel=\"noreferrer\">Maven/Gradle instructions here.</a></p>\n" }, { "answer_id": 35908056, "author": "Matt Welke", "author_id": 5051165, "author_profile": "https://Stackoverflow.com/users/5051165", "pm_score": -1, "selected": false, "text": "<p>I wanted to comment with my solution to this problem, which avoided needing any of the exception related JUnit code.</p>\n\n<p>I used assertTrue(boolean) combined with try/catch to look for my expected exception to be thrown. Here's an example:</p>\n\n<pre><code>public void testConstructor() {\n boolean expectedExceptionThrown;\n try {\n // Call constructor with bad arguments\n double a = 1;\n double b = 2;\n double c = a + b; // In my example, this is an invalid option for c\n new Triangle(a, b, c);\n expectedExceptionThrown = false; // because it successfully constructed the object\n }\n catch(IllegalArgumentException e) {\n expectedExceptionThrown = true; // because I'm in this catch block\n }\n catch(Exception e) {\n expectedExceptionThrown = false; // because it threw an exception but not the one expected\n }\n assertTrue(expectedExceptionThrown);\n}\n</code></pre>\n" }, { "answer_id": 38553412, "author": "Daniel Käfer", "author_id": 1079174, "author_profile": "https://Stackoverflow.com/users/1079174", "pm_score": 4, "selected": false, "text": "<h2>JUnit 5 Solution</h2>\n<pre><code>import static org.junit.jupiter.api.Assertions.assertThrows;\n\n@Test\nvoid testFooThrowsIndexOutOfBoundsException() { \n IndexOutOfBoundsException exception = expectThrows(IndexOutOfBoundsException.class, foo::doStuff);\n \n assertEquals(&quot;some message&quot;, exception.getMessage());\n}\n</code></pre>\n<p>More Infos about JUnit 5 on <a href=\"http://junit.org/junit5/docs/current/user-guide/#writing-tests-assertions\" rel=\"nofollow noreferrer\">http://junit.org/junit5/docs/current/user-guide/#writing-tests-assertions</a></p>\n" }, { "answer_id": 40317041, "author": "Shirsh Sinha", "author_id": 4840515, "author_profile": "https://Stackoverflow.com/users/4840515", "pm_score": 1, "selected": false, "text": "<p>Take for example, you want to write Junit for below mentioned code fragment</p>\n\n<pre><code>public int divideByZeroDemo(int a,int b){\n\n return a/b;\n}\n\npublic void exceptionWithMessage(String [] arr){\n\n throw new ArrayIndexOutOfBoundsException(\"Array is out of bound\");\n}\n</code></pre>\n\n<p>The above code is to test for some unknown exception that may occur and the below one is to assert some exception with custom message.</p>\n\n<pre><code> @Rule\npublic ExpectedException exception=ExpectedException.none();\n\nprivate Demo demo;\n@Before\npublic void setup(){\n\n demo=new Demo();\n}\n@Test(expected=ArithmeticException.class)\npublic void testIfItThrowsAnyException() {\n\n demo.divideByZeroDemo(5, 0);\n\n}\n\n@Test\npublic void testExceptionWithMessage(){\n\n\n exception.expectMessage(\"Array is out of bound\");\n exception.expect(ArrayIndexOutOfBoundsException.class);\n demo.exceptionWithMessage(new String[]{\"This\",\"is\",\"a\",\"demo\"});\n}\n</code></pre>\n" }, { "answer_id": 41019785, "author": "Brice", "author_id": 48136, "author_profile": "https://Stackoverflow.com/users/48136", "pm_score": 7, "selected": false, "text": "<p><strong>tl;dr</strong></p>\n\n<ul>\n<li><p>post-JDK8 : Use <strong>AssertJ</strong> or custom lambdas to assert <em>exceptional</em> behaviour.</p></li>\n<li><p>pre-JDK8 : I will recommend the old good <code>try</code>-<code>catch</code> block. (<em>Don't forget to add a <code>fail()</code> assertion before the <code>catch</code> block</em>)</p></li>\n</ul>\n\n<p><em>Regardless of Junit 4 or JUnit 5.</em></p>\n\n<p><strong>the long story</strong></p>\n\n<p>It is possible to write yourself a <em>do it yourself</em> <code>try</code>-<code>catch</code> block or use the JUnit tools (<code>@Test(expected = ...)</code> or the <code>@Rule ExpectedException</code> JUnit rule feature).</p>\n\n<p>But these ways are not so elegant and don't mix well <em>readability wise</em> with other tools. Moreover, JUnit tooling does have some pitfalls.</p>\n\n<ol>\n<li><p>The <code>try</code>-<code>catch</code> block you have to write the block around the tested behavior and write the assertion in the catch block, that may be fine but many find that this style interrupts the reading flow of a test. Also, you need to write an <code>Assert.fail</code> at the end of the <code>try</code> block. Otherwise, the test may miss one side of the assertions; <em>PMD</em>, <em>findbugs</em> or <em>Sonar</em> will spot such issues.</p></li>\n<li><p>The <code>@Test(expected = ...)</code> feature is interesting as you can write less code and then writing this test is supposedly less prone to coding errors. <strong>But</strong> this approach is lacking in some areas.</p>\n\n<ul>\n<li>If the test needs to check additional things on the exception like the cause or the message (good exception messages are really important, having a precise exception type may not be enough). </li>\n<li><p>Also as the expectation is placed around in the method, depending on how the tested code is written then the wrong part of the test code can throw the exception, leading to false-positive test and I'm not sure that <em>PMD</em>, <em>findbugs</em> or <em>Sonar</em> will give hints on such code.</p>\n\n<pre><code>@Test(expected = WantedException.class)\npublic void call2_should_throw_a_WantedException__not_call1() {\n // init tested\n tested.call1(); // may throw a WantedException\n\n // call to be actually tested\n tested.call2(); // the call that is supposed to raise an exception\n}\n</code></pre></li>\n</ul></li>\n<li><p>The <code>ExpectedException</code> rule is also an attempt to fix the previous caveats, but it feels a bit awkward to use as it uses an expectation style, <em>EasyMock</em> users know very well this style. It might be convenient for some, but if you follow <em>Behaviour Driven Development</em> (BDD) or <em>Arrange Act Assert</em> (AAA) principles the <code>ExpectedException</code> rule won't fit in those writing style. Aside from that it may suffer from the same issue as the <code>@Test</code> way, depending on where you place the expectation.</p>\n\n<pre><code>@Rule ExpectedException thrown = ExpectedException.none()\n\n@Test\npublic void call2_should_throw_a_WantedException__not_call1() {\n // expectations\n thrown.expect(WantedException.class);\n thrown.expectMessage(\"boom\");\n\n // init tested\n tested.call1(); // may throw a WantedException\n\n // call to be actually tested\n tested.call2(); // the call that is supposed to raise an exception\n}\n</code></pre>\n\n<p>Even the expected exception is placed before the test statement, it breaks your reading flow if the tests follow BDD or AAA.</p>\n\n<p>Also, see this <a href=\"https://github.com/junit-team/junit4/issues/706#issuecomment-21385116\" rel=\"noreferrer\">comment</a> issue on JUnit of the author of <code>ExpectedException</code>. <a href=\"https://github.com/junit-team/junit4/wiki/4.13-Release-Notes\" rel=\"noreferrer\">JUnit 4.13-beta-2</a> even deprecates this mechanism:</p>\n\n<blockquote>\n <p><a href=\"https://github.com/junit-team/junit4/pull/1519\" rel=\"noreferrer\">Pull request #1519</a>: Deprecate ExpectedException</p>\n \n <p>The method Assert.assertThrows provides a nicer way for verifying exceptions. In addition, the use of ExpectedException is error-prone when used with other rules like TestWatcher because the order of rules is important in that case.</p>\n</blockquote></li>\n</ol>\n\n<p>So these above options have all their load of caveats, and clearly not immune to coder errors.</p>\n\n<ol start=\"4\">\n<li><p>There's a project I became aware of after creating this answer that looks promising, it's <a href=\"https://github.com/Codearte/catch-exception\" rel=\"noreferrer\"><strong>catch-exception</strong></a>.</p>\n\n<p>As the description of the project says, it let a coder write in a fluent line of code catching the exception and offer this exception for the latter assertion. And you can use any assertion library like <a href=\"https://github.com/hamcrest/JavaHamcrest\" rel=\"noreferrer\">Hamcrest</a> or <a href=\"https://github.com/joel-costigliola/assertj-core\" rel=\"noreferrer\">AssertJ</a>.</p>\n\n<p>A rapid example taken from the home page : </p>\n\n<pre><code>// given: an empty list\nList myList = new ArrayList();\n\n// when: we try to get the first element of the list\nwhen(myList).get(1);\n\n// then: we expect an IndexOutOfBoundsException\nthen(caughtException())\n .isInstanceOf(IndexOutOfBoundsException.class)\n .hasMessage(\"Index: 1, Size: 0\") \n .hasNoCause();\n</code></pre>\n\n<p>As you can see the code is really straightforward, you catch the exception on a specific line, the <code>then</code> API is an alias that will use AssertJ APIs (similar to using <code>assertThat(ex).hasNoCause()...</code>). <em>At some point the project relied on FEST-Assert the ancestor of AssertJ</em>. <strong>EDIT:</strong> It seems the project is brewing a Java 8 Lambdas support.</p>\n\n<p>Currently, this library has two shortcomings : </p>\n\n<ul>\n<li><p>At the time of this writing, it is noteworthy to say this library is based on Mockito 1.x as it creates a mock of the tested object behind the scene. As Mockito is still not updated <strong>this library cannot work with final classes or final methods</strong>. And even if it was based on Mockito 2 in the current version, this would require to declare a global mock maker (<code>inline-mock-maker</code>), something that may not what you want, as this mock maker has different drawbacks that the regular mock maker.</p></li>\n<li><p>It requires yet another test dependency.</p></li>\n</ul>\n\n<p>These issues won't apply once the library supports lambdas. However, the functionality will be duplicated by the AssertJ toolset.</p>\n\n<p><strong>Taking all into account if you don't want to use the catch-exception tool, I will recommend the old good way of the <code>try</code>-<code>catch</code> block, at least up to the JDK7. And for JDK 8 users you might prefer to use AssertJ as it offers may more than just asserting exceptions.</strong></p></li>\n<li><p>With the JDK8, lambdas enter the test scene, and they have proved to be an interesting way to assert exceptional behaviour. AssertJ has been updated to provide a nice fluent API to assert exceptional behaviour.</p>\n\n<p>And a sample test with <a href=\"http://joel-costigliola.github.io/assertj/\" rel=\"noreferrer\">AssertJ</a> :</p>\n\n<pre><code>@Test\npublic void test_exception_approach_1() {\n ...\n assertThatExceptionOfType(IOException.class)\n .isThrownBy(() -&gt; someBadIOOperation())\n .withMessage(\"boom!\"); \n}\n\n@Test\npublic void test_exception_approach_2() {\n ...\n assertThatThrownBy(() -&gt; someBadIOOperation())\n .isInstanceOf(Exception.class)\n .hasMessageContaining(\"boom\");\n}\n\n@Test\npublic void test_exception_approach_3() {\n ...\n // when\n Throwable thrown = catchThrowable(() -&gt; someBadIOOperation());\n\n // then\n assertThat(thrown).isInstanceOf(Exception.class)\n .hasMessageContaining(\"boom\");\n}\n</code></pre></li>\n<li><p>With a near-complete rewrite of JUnit 5, assertions have been <a href=\"http://junit.org/junit5/docs/current/user-guide/#writing-tests-assertions\" rel=\"noreferrer\">improved</a> a bit, they may prove interesting as an out of the box way to assert properly exception. But really the assertion API is still a bit poor, there's nothing outside <a href=\"http://junit.org/junit5/docs/current/api/org/junit/jupiter/api/Assertions.html#assertThrows-java.lang.Class-org.junit.jupiter.api.function.Executable-\" rel=\"noreferrer\"><code>assertThrows</code></a>. </p>\n\n<pre><code>@Test\n@DisplayName(\"throws EmptyStackException when peeked\")\nvoid throwsExceptionWhenPeeked() {\n Throwable t = assertThrows(EmptyStackException.class, () -&gt; stack.peek());\n\n Assertions.assertEquals(\"...\", t.getMessage());\n}\n</code></pre>\n\n<p>As you noticed <code>assertEquals</code> is still returning <code>void</code>, and as such doesn't allow chaining assertions like AssertJ.</p>\n\n<p>Also if you remember name clash with <code>Matcher</code> or <code>Assert</code>, be prepared to meet the same clash with <code>Assertions</code>.</p></li>\n</ol>\n\n<p>I'd like to conclude that today (2017-03-03) <strong>AssertJ</strong>'s ease of use, discoverable API, the rapid pace of development and as a <em>de facto</em> test dependency is the best solution with JDK8 regardless of the test framework (JUnit or not), prior JDKs should instead rely on <strong><code>try</code>-<code>catch</code></strong> blocks even if they feel clunky.</p>\n\n<p><em>This answer has been copied from <a href=\"https://stackoverflow.com/a/17428439/48136\">another question</a> that don't have the same visibility, I am the same author.</em></p>\n" }, { "answer_id": 41032596, "author": "Jobin", "author_id": 2893693, "author_profile": "https://Stackoverflow.com/users/2893693", "pm_score": 3, "selected": false, "text": "<p>In JUnit 4 or later you can test the exceptions as follows</p>\n\n<pre><code>@Rule\npublic ExpectedException exceptions = ExpectedException.none();\n</code></pre>\n\n<p><br> this provides a lot of features which can be used to improve our JUnit tests. <br> If you see the below example I am testing 3 things on the exception.</p>\n\n<ol>\n<li>The Type of exception thrown</li>\n<li>The exception Message</li>\n<li>The cause of the exception</li>\n</ol>\n\n<p><br></p>\n\n<pre><code>public class MyTest {\n\n @Rule\n public ExpectedException exceptions = ExpectedException.none();\n\n ClassUnderTest classUnderTest;\n\n @Before\n public void setUp() throws Exception {\n classUnderTest = new ClassUnderTest();\n }\n\n @Test\n public void testAppleisSweetAndRed() throws Exception {\n\n exceptions.expect(Exception.class);\n exceptions.expectMessage(\"this is the exception message\");\n exceptions.expectCause(Matchers.&lt;Throwable&gt;equalTo(exceptionCause));\n\n classUnderTest.methodUnderTest(\"param1\", \"param2\");\n }\n\n}\n</code></pre>\n" }, { "answer_id": 41559786, "author": "Dilini Rajapaksha", "author_id": 679822, "author_profile": "https://Stackoverflow.com/users/679822", "pm_score": 6, "selected": false, "text": "<p><strong>Update:</strong> JUnit5 has an improvement for exceptions testing: <code>assertThrows</code>.</p>\n<p>The following example is from: <a href=\"http://junit.org/junit5/docs/current/user-guide/#extensions-exception-handling\" rel=\"noreferrer\">Junit 5 User Guide</a></p>\n<pre><code>import static org.junit.jupiter.api.Assertions.assertThrows;\n\n@Test\nvoid exceptionTesting() {\n IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -&gt; {\n throw new IllegalArgumentException(&quot;a message&quot;);\n });\n assertEquals(&quot;a message&quot;, exception.getMessage());\n}\n</code></pre>\n<p><strong>Original answer using JUnit 4.</strong></p>\n<p>There are several ways to test that an exception is thrown. I have also discussed the below options in my post <a href=\"https://javacodehouse.com/junit-tutorial\" rel=\"noreferrer\">How to write great unit tests with JUnit</a></p>\n<p>Set the <code>expected</code> parameter <code>@Test(expected = FileNotFoundException.class)</code>.</p>\n<pre><code>@Test(expected = FileNotFoundException.class) \npublic void testReadFile() { \n myClass.readFile(&quot;test.txt&quot;);\n}\n</code></pre>\n<p>Using <code>try</code> <code>catch</code></p>\n<pre><code>public void testReadFile() { \n try {\n myClass.readFile(&quot;test.txt&quot;);\n fail(&quot;Expected a FileNotFoundException to be thrown&quot;);\n } catch (FileNotFoundException e) {\n assertThat(e.getMessage(), is(&quot;The file test.txt does not exist!&quot;));\n }\n \n}\n</code></pre>\n<p>Testing with <code>ExpectedException</code> Rule.</p>\n<pre><code>@Rule\npublic ExpectedException thrown = ExpectedException.none();\n\n@Test\npublic void testReadFile() throws FileNotFoundException {\n \n thrown.expect(FileNotFoundException.class);\n thrown.expectMessage(startsWith(&quot;The file test.txt&quot;));\n myClass.readFile(&quot;test.txt&quot;);\n}\n</code></pre>\n<p>You could read more about exceptions testing in <a href=\"https://github.com/junit-team/junit4/wiki/Exception-testing\" rel=\"noreferrer\">JUnit4 wiki for Exception testing</a> and <a href=\"http://baddotrobot.com/blog/2012/03/27/expecting-exception-with-junit-rule/index.html\" rel=\"noreferrer\">bad.robot - Expecting Exceptions JUnit Rule</a>.</p>\n" }, { "answer_id": 46512202, "author": "fahrenx", "author_id": 1482358, "author_profile": "https://Stackoverflow.com/users/1482358", "pm_score": 1, "selected": false, "text": "<p>With Java 8 you can create a method taking a code to check and expected exception as parameters:</p>\n\n<pre><code>private void expectException(Runnable r, Class&lt;?&gt; clazz) { \n try {\n r.run();\n fail(\"Expected: \" + clazz.getSimpleName() + \" but not thrown\");\n } catch (Exception e) {\n if (!clazz.isInstance(e)) fail(\"Expected: \" + clazz.getSimpleName() + \" but \" + e.getClass().getSimpleName() + \" found\", e);\n }\n }\n</code></pre>\n\n<p>and then inside your test:</p>\n\n<pre><code>expectException(() -&gt; list.sublist(0, 2).get(2), IndexOutOfBoundsException.class);\n</code></pre>\n\n<p>Benefits:</p>\n\n<ul>\n<li>not relying on any library</li>\n<li>localised check - more precise and allows to have multiple assertions like this within one test if needed</li>\n<li>easy to use </li>\n</ul>\n" }, { "answer_id": 46514550, "author": "NamshubWriter", "author_id": 95725, "author_profile": "https://Stackoverflow.com/users/95725", "pm_score": 6, "selected": false, "text": "<p>Now that JUnit 5 and JUnit 4.13 have been released, the best option would be to use <code>Assertions.assertThrows()</code> (for JUnit 5) and <code>Assert.assertThrows()</code> (for JUnit 4.13). See\nthe <a href=\"http://junit.org/junit5/docs/current/user-guide/#extensions-exception-handling\" rel=\"noreferrer\">JUnit 5 User Guide</a>.</p>\n<p>Here is an example that verifies an exception is thrown, and uses <a href=\"http://google.github.io/truth/\" rel=\"noreferrer\">Truth</a> to make assertions on the exception message:</p>\n<pre><code>public class FooTest {\n @Test\n public void doStuffThrowsIndexOutOfBoundsException() {\n Foo foo = new Foo();\n\n IndexOutOfBoundsException e = assertThrows(\n IndexOutOfBoundsException.class, foo::doStuff);\n\n assertThat(e).hasMessageThat().contains(&quot;woops!&quot;);\n }\n}\n</code></pre>\n<p>The advantages over the approaches in the other answers are:</p>\n<ol>\n<li>Built into JUnit</li>\n<li>You get a useful exception message if the code in the lambda doesn't throw an exception, and a stacktrace if it throws a different exception</li>\n<li>Concise</li>\n<li>Allows your tests to follow Arrange-Act-Assert</li>\n<li>You can precisely indicate what code you are expecting to throw the exception</li>\n<li>You don't need to list the expected exception in the <code>throws</code> clause</li>\n<li>You can use the assertion framework of your choice to make assertions about the caught exception</li>\n</ol>\n" }, { "answer_id": 46563308, "author": "heio", "author_id": 4031101, "author_profile": "https://Stackoverflow.com/users/4031101", "pm_score": 0, "selected": false, "text": "<p>My solution using Java 8 lambdas:</p>\n\n<pre><code>public static &lt;T extends Throwable&gt; T assertThrows(Class&lt;T&gt; expected, ThrowingRunnable action) throws Throwable {\n try {\n action.run();\n Assert.fail(\"Did not throw expected \" + expected.getSimpleName());\n return null; // never actually\n } catch (Throwable actual) {\n if (!expected.isAssignableFrom(actual.getClass())) { // runtime '!(actual instanceof expected)'\n System.err.println(\"Threw \" + actual.getClass().getSimpleName() \n + \", which is not a subtype of expected \" \n + expected.getSimpleName());\n throw actual; // throw the unexpected Throwable for maximum transparency\n } else {\n return (T) actual; // return the expected Throwable for further examination\n }\n }\n}\n</code></pre>\n\n<p>You have to define a FunctionalInterface, because <code>Runnable</code> doesn't declare the required <code>throws</code>.</p>\n\n<pre><code>@FunctionalInterface\npublic interface ThrowingRunnable {\n void run() throws Throwable;\n}\n</code></pre>\n\n<p>The method can be used as follows:</p>\n\n<pre><code>class CustomException extends Exception {\n public final String message;\n public CustomException(final String message) { this.message = message;}\n}\nCustomException e = assertThrows(CustomException.class, () -&gt; {\n throw new CustomException(\"Lorem Ipsum\");\n});\nassertEquals(\"Lorem Ipsum\", e.message);\n</code></pre>\n" }, { "answer_id": 47195186, "author": "Mohit ladia", "author_id": 7750672, "author_profile": "https://Stackoverflow.com/users/7750672", "pm_score": 0, "selected": false, "text": "<p>There are two ways of writing test case </p>\n\n<ol>\n<li>Annotate the test with the exception which is thrown by the method. Something like this <code>@Test(expected = IndexOutOfBoundsException.class)</code></li>\n<li><p>You can simply catch the exception in the test class using the try catch block and assert on the message that is thrown from the method in test class.</p>\n\n<pre><code>try{\n}\ncatch(exception to be thrown from method e)\n{\n assertEquals(\"message\", e.getmessage());\n}\n</code></pre></li>\n</ol>\n\n<p>I hope this answers your query\nHappy learning...</p>\n" }, { "answer_id": 48441467, "author": "Dherik", "author_id": 2387977, "author_profile": "https://Stackoverflow.com/users/2387977", "pm_score": 4, "selected": false, "text": "<p>The most flexible and elegant answer for Junit 4 I found in the <a href=\"https://www.mkyong.com/unittest/junit-4-tutorial-2-expected-exception-test/\" rel=\"noreferrer\">Mkyong blog</a>. It has the flexibility of the <code>try/catch</code> using the <code>@Rule</code> annotation. I like this approach because you can read specific attributes of a customized exception.</p>\n\n<pre><code>package com.mkyong;\n\nimport com.mkyong.examples.CustomerService;\nimport com.mkyong.examples.exception.NameNotFoundException;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.ExpectedException;\n\nimport static org.hamcrest.CoreMatchers.containsString;\nimport static org.hamcrest.CoreMatchers.is;\nimport static org.hamcrest.Matchers.hasProperty;\n\npublic class Exception3Test {\n\n @Rule\n public ExpectedException thrown = ExpectedException.none();\n\n @Test\n public void testNameNotFoundException() throws NameNotFoundException {\n\n //test specific type of exception\n thrown.expect(NameNotFoundException.class);\n\n //test message\n thrown.expectMessage(is(\"Name is empty!\"));\n\n //test detail\n thrown.expect(hasProperty(\"errCode\")); //make sure getters n setters are defined.\n thrown.expect(hasProperty(\"errCode\", is(666)));\n\n CustomerService cust = new CustomerService();\n cust.findByName(\"\");\n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 49696649, "author": "Donatello", "author_id": 1034782, "author_profile": "https://Stackoverflow.com/users/1034782", "pm_score": 2, "selected": false, "text": "<p>Junit4 solution with Java8 is to use this function:</p>\n\n<pre><code>public Throwable assertThrows(Class&lt;? extends Throwable&gt; expectedException, java.util.concurrent.Callable&lt;?&gt; funky) {\n try {\n funky.call();\n } catch (Throwable e) {\n if (expectedException.isInstance(e)) {\n return e;\n }\n throw new AssertionError(\n String.format(\"Expected [%s] to be thrown, but was [%s]\", expectedException, e));\n }\n throw new AssertionError(\n String.format(\"Expected [%s] to be thrown, but nothing was thrown.\", expectedException));\n}\n</code></pre>\n\n<p>Usage is then:</p>\n\n<pre><code> assertThrows(ValidationException.class,\n () -&gt; finalObject.checkSomething(null));\n</code></pre>\n\n<p>Note that the only limitation is to use a <code>final</code> object reference in lambda expression.\nThis solution allows to continue test assertions instead of expecting thowable at method level using <code>@Test(expected = IndexOutOfBoundsException.class)</code> solution.</p>\n" }, { "answer_id": 51400976, "author": "Piotr Rogowski", "author_id": 3782729, "author_profile": "https://Stackoverflow.com/users/3782729", "pm_score": 2, "selected": false, "text": "<p>I recomend library <code>assertj-core</code> to handle exception in junit test</p>\n\n<p>In java 8, like this:</p>\n\n<pre><code>//given\n\n//when\nThrowable throwable = catchThrowable(() -&gt; anyService.anyMethod(object));\n\n//then\nAnyException anyException = (AnyException) throwable;\nassertThat(anyException.getMessage()).isEqualTo(\"........\");\nassertThat(exception.getCode()).isEqualTo(\".......);\n</code></pre>\n" }, { "answer_id": 51744696, "author": "Hossam Badri", "author_id": 1807373, "author_profile": "https://Stackoverflow.com/users/1807373", "pm_score": -1, "selected": false, "text": "<pre><code>try {\n my method();\n fail( \"This method must thrwo\" );\n} catch (Exception ex) {\n assertThat(ex.getMessage()).isEqual(myErrormsg);\n}\n</code></pre>\n" }, { "answer_id": 55708672, "author": "MangduYogii", "author_id": 9491394, "author_profile": "https://Stackoverflow.com/users/9491394", "pm_score": 1, "selected": false, "text": "<pre><code> @Test(expectedException=IndexOutOfBoundsException.class) \n public void testFooThrowsIndexOutOfBoundsException() throws Exception {\n doThrow(IndexOutOfBoundsException.class).when(foo).doStuff(); \n try {\n foo.doStuff(); \n } catch (IndexOutOfBoundsException e) {\n assertEquals(IndexOutOfBoundsException .class, ex.getCause().getClass());\n throw e;\n\n }\n\n }\n</code></pre>\n\n<p>Here is another way to check method thrown correct exception or not.</p>\n" }, { "answer_id": 61762605, "author": "Ilya Serbis", "author_id": 355438, "author_profile": "https://Stackoverflow.com/users/355438", "pm_score": 2, "selected": false, "text": "<p>JUnit framework has <strong><code>assertThrows()</code></strong> method:</p>\n\n<pre><code>ArithmeticException exception = assertThrows(ArithmeticException.class, () -&gt;\n calculator.divide(1, 0));\nassertEquals(\"/ by zero\", exception.getMessage());\n</code></pre>\n\n<ul>\n<li>for JUnit 5 it's in <a href=\"https://junit.org/junit5/docs/current/api/org.junit.jupiter.api/org/junit/jupiter/api/Assertions.html#assertThrows(java.lang.Class,org.junit.jupiter.api.function.Executable)\" rel=\"nofollow noreferrer\"><code>org.junit.jupiter.api.Assertions</code></a> class;</li>\n<li>for JUnit 4.13 it's in <a href=\"https://junit.org/junit4/javadoc/latest/org/junit/Assert.html#assertThrows(java.lang.Class,%20org.junit.function.ThrowingRunnable)\" rel=\"nofollow noreferrer\"><code>org.junit.Assert</code></a> class;</li>\n<li>for earlier versions of JUnit 4: just add reference on <a href=\"https://search.maven.org/artifact/org.junit.jupiter/junit-jupiter-api\" rel=\"nofollow noreferrer\"><code>org.junit.jupiter:junit-jupiter-api</code></a> to your project and you'll get perfectly well working version from JUnit 5.</li>\n</ul>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1666/" ]
How can I use JUnit idiomatically to test that some code throws an exception? While I can certainly do something like this: ``` @Test public void testFooThrowsIndexOutOfBoundsException() { boolean thrown = false; try { foo.doStuff(); } catch (IndexOutOfBoundsException e) { thrown = true; } assertTrue(thrown); } ``` I recall that there is an annotation or an Assert.xyz or *something* that is far less kludgy and far more in-the-spirit of JUnit for these sorts of situations.
It depends on the JUnit version and what assert libraries you use. * For JUnit5 and 4.13 [see answer](https://stackoverflow.com/a/2935935/2986984) * If you use AssertJ or google-truth, [see answer](https://stackoverflow.com/a/41019785/2986984) The original answer for `JUnit <= 4.12` was: ```java @Test(expected = IndexOutOfBoundsException.class) public void testIndexOutOfBoundsException() { ArrayList emptyList = new ArrayList(); Object o = emptyList.get(0); } ``` Though [answer](https://stackoverflow.com/a/31826781/2986984) has more options for JUnit <= 4.12. Reference: * [JUnit Test-FAQ](https://junit.org/junit4/faq.html#atests_7)
156,504
<p>I'm trying to insert some import lines into a python source file, but i would ideally like to place them right after the initial docstring. Let's say I load the file into the lines variable like this:</p> <pre><code>lines = open('filename.py').readlines() </code></pre> <p>How to find the line number, where the docstring ends?</p>
[ { "answer_id": 156513, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 3, "selected": true, "text": "<p>If you're using the standard docstring format, you can do something like this:</p>\n\n<pre><code>count = 0\nfor line in lines:\n if line.startswith ('\"\"\"'):\n count += 1\n if count &lt; 3:\n # Before or during end of the docstring\n continue\n # Line is after docstring\n</code></pre>\n\n<p>Might need some adaptation for files with no docstrings, but if your files are formatted consistently it should be easy enough.</p>\n" }, { "answer_id": 156973, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 4, "selected": false, "text": "<p>Rather than using a regex, or relying on specific formatting you could use python's tokenize module.</p>\n\n<pre><code>import tokenize\nf=open(filename)\ninsert_index = None\nfor tok, text, (srow, scol), (erow,ecol), l in tokenize.generate_tokens(f.readline):\n if tok == tokenize.COMMENT:\n continue\n elif tok == tokenize.STRING:\n insert_index = erow, ecol\n break\n else:\n break # No docstring found\n</code></pre>\n\n<p>This way you can even handle pathological cases like:</p>\n\n<pre><code># Comment\n# \"\"\"Not the real docstring\"\"\"\n' this is the module\\'s \\\ndocstring, containing:\\\n\"\"\" and having code on the same line following it:'; this_is_code=42\n</code></pre>\n\n<p>excactly as python would handle them.</p>\n" }, { "answer_id": 40376257, "author": "The Unfun Cat", "author_id": 992687, "author_profile": "https://Stackoverflow.com/users/992687", "pm_score": 0, "selected": false, "text": "<p>This is a function based on Brian's brilliant answer you can use to split a file into docstring and code:</p>\n\n<pre><code>def split_docstring_and_code(infile):\n\n import tokenize\n insert_index = None\n f = open(infile)\n for tok, text, (srow, scol), (erow,ecol), l in tokenize.generate_tokens(f.readline):\n if tok == tokenize.COMMENT:\n continue\n elif tok == tokenize.STRING:\n insert_index = erow, ecol\n break\n else:\n break # No docstring found\n\n lines = open(infile).readlines()\n if insert_index is not None:\n erow = insert_index[0]\n return \"\".join(lines[:erow]), \"\".join(lines[erow:])\n else:\n return \"\", \"\".join(lines)\n</code></pre>\n\n<p>It assumes that the line that ends the docstring does not contain additional code past the closing delimiter of the string.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/985/" ]
I'm trying to insert some import lines into a python source file, but i would ideally like to place them right after the initial docstring. Let's say I load the file into the lines variable like this: ``` lines = open('filename.py').readlines() ``` How to find the line number, where the docstring ends?
If you're using the standard docstring format, you can do something like this: ``` count = 0 for line in lines: if line.startswith ('"""'): count += 1 if count < 3: # Before or during end of the docstring continue # Line is after docstring ``` Might need some adaptation for files with no docstrings, but if your files are formatted consistently it should be easy enough.
156,508
<p>Alright, I have been doing the following (variable names have been changed):</p> <pre><code> FileInputStream fis = null; try { fis = new FileInputStream(file); ... process ... } catch (IOException e) { ... handle error ... } finally { if (fis != null) fis.close(); } </code> </pre> <p>Recently, I started using FindBugs, which suggests that I am not properly closing streams. I decide to see if there's anything that can be done with a finally{} block, and then I see, oh yeah, close() can throw IOException. What are people supposed to do here? The Java libraries throw too many checked exceptions.</p>
[ { "answer_id": 156520, "author": "Max Stewart", "author_id": 18338, "author_profile": "https://Stackoverflow.com/users/18338", "pm_score": 5, "selected": false, "text": "<p>Something like the following should do it, up to you whether you throw or swallow the IOException on attempting to close the stream.</p>\n\n<pre><code>FileInputStream fis = null;\ntry\n{\n fis = new FileInputStream(file);\n\n ... process ...\n\n\n}\ncatch (IOException e)\n{\n ... blah blah blah ...\n}\nfinally\n{\n try\n {\n if (fis != null)\n fis.close();\n }\n catch (IOException e)\n {\n }\n}\n</code></pre>\n" }, { "answer_id": 156526, "author": "squiddle", "author_id": 6554, "author_profile": "https://Stackoverflow.com/users/6554", "pm_score": 2, "selected": false, "text": "<p>You could also use a simple static Helper Method:</p>\n\n<pre><code>public static void closeQuietly(InputStream s) {\n if (null == s) {\n return;\n }\n try {\n s.close();\n } catch (IOException ioe) {\n //ignore exception\n }\n}\n</code></pre>\n\n<p>and use this from your finally block.</p>\n" }, { "answer_id": 156546, "author": "Lars Westergren", "author_id": 15627, "author_profile": "https://Stackoverflow.com/users/15627", "pm_score": 0, "selected": false, "text": "<p>Hopefully we will get closures in Java some day, and then we will lose lots of the verbosity.</p>\n\n<p>So instead there will be a helper method somwhere in javaIO that you can import, it will probably takes a \"Closable\" interface and also a block. Inside that helper method the try {closable.close() } catch (IOException ex){ //blah} is defined once and for all, and then you will be able to write</p>\n\n<pre><code> Inputstream s = ....;\n withClosable(s) {\n //your code here\n }\n</code></pre>\n" }, { "answer_id": 156674, "author": "serg10", "author_id": 1853, "author_profile": "https://Stackoverflow.com/users/1853", "pm_score": 2, "selected": false, "text": "<p>Nothing much to add, except for a very minor stylistic suggestion. <strong>The canonical example of self documenting code</strong> applies in this case - give a descriptive variable name to the ignored <code>IOException</code> that you must catch on <code>close()</code>.</p>\n\n<p>So squiddle's answer becomes:</p>\n\n<pre><code>public static void closeQuietly(InputStream s) {\n try {\n s.close();\n } catch (IOException ignored) {\n }\n}\n</code></pre>\n" }, { "answer_id": 156721, "author": "Dave Griffiths", "author_id": 15379, "author_profile": "https://Stackoverflow.com/users/15379", "pm_score": -1, "selected": false, "text": "<p>Are you concerned primarily with getting a clean report from FindBugs or with having code that works? These are not necessarily the same thing. Your original code is fine (although I would get rid of the redundant <code>if (fis != null)</code> check since an <code>OutOfMemoryException</code> would have been thrown otherwise). FileInputStream has a finalizer method which will close the stream for you in the unlikely event that you actually receive an IOException in your processing. It's simply not worth the bother of making your code more sophisticated to avoid the extremely unlikely scenario of</p>\n\n<ol>\n<li>you get an IOException and </li>\n<li>this happens so often that you start to run into finalizer backlog issues.</li>\n</ol>\n\n<p><strong>Edit:</strong> if you are getting so many IOExceptions that you are running into problems with the finalizer queue then you have far far bigger fish to fry! This is about getting a sense of perspective.</p>\n" }, { "answer_id": 156889, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 7, "selected": true, "text": "<p>For Java 7 and above <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"noreferrer\">try-with-resources</a> should be used:</p>\n\n<pre><code>try (InputStream in = new FileInputStream(file)) {\n // TODO: work\n} catch (IOException e) {\n // TODO: handle error\n}\n</code></pre>\n\n<p>If you're stuck on Java 6 or below...</p>\n\n<p>This pattern avoids mucking around with <strong>null</strong>:</p>\n\n<pre><code> try {\n InputStream in = new FileInputStream(file);\n try {\n // TODO: work\n } finally {\n in.close();\n }\n } catch (IOException e) {\n // TODO: error handling\n }\n</code></pre>\n\n<hr>\n\n<p>For a more detail on how to effectively deal with <em>close</em>, read this blog post: <a href=\"http://illegalargumentexception.blogspot.com/2008/10/java-how-not-to-make-mess-of-stream.html\" rel=\"noreferrer\">Java: how not to make a mess of stream handling</a>. It has more sample code, more depth and covers the pitfalls of wrapping <em>close</em> in a <em>catch</em> block.</p>\n" }, { "answer_id": 157084, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 2, "selected": false, "text": "<p>In most cases, I find it is just better <strong>not</strong> to catch the IO exceptions, and simply use try-finally:</p>\n\n<pre><code>final InputStream is = ... // (assuming some construction that can't return null)\ntry {\n // process is\n ...\n} finally {\n is.close();\n}\n</code></pre>\n\n<p>Except for <code>FileNotFoundException</code>, you generally can't \"work around\" an <code>IOException</code>. The only thing left to do is report an error, and you will typically handle that further up the call stack, so I find it better to propagate the exception.</p>\n\n<p>Since <code>IOException</code> is a checked exception, you will have to declare that this code (and any of its clients) <code>throws IOException</code>. That might be too noisy, or you might not want to reveal the implementation detail of using IO. In that case, you can wrap the entire block with an exception handler that wraps the <code>IOException</code> in a <code>RuntimeException</code> or an abstract exception type.</p>\n\n<p><strong>Detail:</strong> I am aware that the above code swallows any exception from the <code>try</code> block when the <code>close</code> operation in the <code>finally</code> block produces an <code>IOException</code>. I don't think that is a big problem: generally, the exception from the <code>try</code> block will be the same <code>IOException</code> that causes the <code>close</code> to fail (i.e. it is quite rare for IO to work fine and then fail at the point of closing). If this is a concern, it might be worth the trouble to \"silence\" the close.</p>\n" }, { "answer_id": 6802774, "author": "Olivier Cailloux", "author_id": 859604, "author_profile": "https://Stackoverflow.com/users/859604", "pm_score": 1, "selected": false, "text": "<p>The following solution correctly throws an exception if close fails without hiding a possible exception before the close.</p>\n\n<pre><code>try {\n InputStream in = new FileInputStream(file);\n try {\n // work\n in.close();\n } finally {\n Closeables.closeQuietly(in);\n }\n} catch(IOException exc) {\n // kernel panic\n}\n</code></pre>\n\n<p>This works because calling close a second time <a href=\"http://download.oracle.com/javase/6/docs/api/java/io/Closeable.html#close()\" rel=\"nofollow noreferrer\">has no effect</a>.</p>\n\n<p>This relies on guava <a href=\"http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/io/Closeables.html\" rel=\"nofollow noreferrer\">Closeables</a>, but one can write its own closeQuietly method if preferred, as shown by <a href=\"https://stackoverflow.com/questions/156508/closing-a-java-fileinputstream/156526#156526\">squiddle</a> (see also <a href=\"https://stackoverflow.com/questions/156508/closing-a-java-fileinputstream/156674#156674\">serg10</a>).</p>\n\n<p>Reporting a close error, in the general case, is important because close might write some final bytes to the stream, e.g. because of buffering. Hence, your user wants to know if it failed, or you probably want to act somehow. Granted, this might not be true in the specific case of a FileInputStream, I don't know (but for reasons already mentioned I think it is better to report a close error if it occurs anyway).</p>\n\n<p>The above code is a bit difficult to grasp because of the structure of the embedded try blocks. It might be considered clearer with two methods, one that throws an IOException and one that catches it. At least that is what I would opt for.</p>\n\n<pre><code>private void work() throws IOException {\n InputStream in = new FileInputStream(file);\n try {\n // work\n in.close();\n } finally {\n Closeables.closeQuietly(in);\n }\n}\n\npublic void workAndDealWithException() {\n try {\n work();\n } catch(IOException exc) {\n // kernel panic\n }\n}\n</code></pre>\n\n<p>Based on <a href=\"http://illegalargumentexception.blogspot.com/2008/10/java-how-not-to-make-mess-of-stream.html\" rel=\"nofollow noreferrer\">http://illegalargumentexception.blogspot.com/2008/10/java-how-not-to-make-mess-of-stream.html</a> (referenced by McDowell).</p>\n" }, { "answer_id": 10644404, "author": "Edwin Dalorzo", "author_id": 697630, "author_profile": "https://Stackoverflow.com/users/697630", "pm_score": 3, "selected": false, "text": "<p>You could use the <a href=\"http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html\" rel=\"noreferrer\">try-with-resources</a> feature added JDK7. It was created precisely to deal with this kind of things</p>\n\n<pre><code>static String readFirstLineFromFile(String path) throws IOException {\n try (BufferedReader br = new BufferedReader(new FileReader(path))) {\n return br.readLine();\n }\n}\n</code></pre>\n\n<p>The documenation says:</p>\n\n<blockquote>\n <p>The try-with-resources statement ensures that each resource is closed\n at the end of the statement.</p>\n</blockquote>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18049/" ]
Alright, I have been doing the following (variable names have been changed): ``` FileInputStream fis = null; try { fis = new FileInputStream(file); ... process ... } catch (IOException e) { ... handle error ... } finally { if (fis != null) fis.close(); } ``` Recently, I started using FindBugs, which suggests that I am not properly closing streams. I decide to see if there's anything that can be done with a finally{} block, and then I see, oh yeah, close() can throw IOException. What are people supposed to do here? The Java libraries throw too many checked exceptions.
For Java 7 and above [try-with-resources](http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) should be used: ``` try (InputStream in = new FileInputStream(file)) { // TODO: work } catch (IOException e) { // TODO: handle error } ``` If you're stuck on Java 6 or below... This pattern avoids mucking around with **null**: ``` try { InputStream in = new FileInputStream(file); try { // TODO: work } finally { in.close(); } } catch (IOException e) { // TODO: error handling } ``` --- For a more detail on how to effectively deal with *close*, read this blog post: [Java: how not to make a mess of stream handling](http://illegalargumentexception.blogspot.com/2008/10/java-how-not-to-make-mess-of-stream.html). It has more sample code, more depth and covers the pitfalls of wrapping *close* in a *catch* block.
156,514
<p>I am debugging some code in the Selenium-rc proxy server. It seems the culprit is the <code>HttpURLConnection</code> object, whose interface for getting at the HTTP headers does not cope with duplicate header names, such as:</p> <pre><code>Set-Cookie: foo=foo; Path=/ Set-Cookie: bar=bar; Path=/ </code></pre> <p>The way of getting at the headers through the <code>HttpURLConnection</code> (using <code>getHeaderField(int n)</code> and <code>getHeaderFieldKey(int n)</code>) seems to be causing my second cookie to be lost. My question is</p> <ol> <li>Is it true that <code>HttpURLConnection</code> itself can't cope with it, and</li> <li>If so, is there a workaround to it?</li> </ol>
[ { "answer_id": 156574, "author": "Olaf Kock", "author_id": 13447, "author_profile": "https://Stackoverflow.com/users/13447", "pm_score": 0, "selected": false, "text": "<p>Without actually having tried it (can't remember to have handled that topic myself), there's also getHeaderFields, inherited from <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/net/URLConnection.html#getHeaderFields()\" rel=\"nofollow noreferrer\">UrlConnection</a>. Does this do what you need?</p>\n" }, { "answer_id": 156591, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 1, "selected": false, "text": "<p>My recommended workaround is to not use HttpUtilConnection at all, which is crude and unintuitive, but use commons-httpclient instead. </p>\n\n<p><a href=\"http://hc.apache.org/httpclient-3.x/\" rel=\"nofollow noreferrer\">http://hc.apache.org/httpclient-3.x/</a> </p>\n" }, { "answer_id": 156677, "author": "airportyh", "author_id": 5304, "author_profile": "https://Stackoverflow.com/users/5304", "pm_score": 0, "selected": false, "text": "<p>Ok, I found the problem, and the answer to the original question. Basically, the Cookie implementation I used (python's default Cookie Lib) used \\r\\n to delimit the different Set-Cookie headers(as supposed to \\n), this confused HttpUrlConnection and caused it to stop at the first occurence of that delimiter(I am going to guess it stops at the first empty line). So the answer to the first question is: Yes, it can cope with duplicate header names, but is buggy in another way. Currently fixing the python library is a workable workaround, but it's not going to work long term because we don't own that library. I am sure using the httpclient library is a sensible way to go, but I am hoping for a solution that requires less work. So I don't know exactly what to do there yet.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5304/" ]
I am debugging some code in the Selenium-rc proxy server. It seems the culprit is the `HttpURLConnection` object, whose interface for getting at the HTTP headers does not cope with duplicate header names, such as: ``` Set-Cookie: foo=foo; Path=/ Set-Cookie: bar=bar; Path=/ ``` The way of getting at the headers through the `HttpURLConnection` (using `getHeaderField(int n)` and `getHeaderFieldKey(int n)`) seems to be causing my second cookie to be lost. My question is 1. Is it true that `HttpURLConnection` itself can't cope with it, and 2. If so, is there a workaround to it?
My recommended workaround is to not use HttpUtilConnection at all, which is crude and unintuitive, but use commons-httpclient instead. <http://hc.apache.org/httpclient-3.x/>
156,532
<p>I need to import largish (24MB) text files into a MySQL table. Each line looks like this:</p> <pre><code>1 1 0.008 0 0 0 0 0 </code></pre> <p>There are one or more spaces after each field, and the last field is tailed by about 36 spaces before the newline.</p> <p>How do I import such a file into MySQL? From the documentation it seems that LOAD DATA expects all fields to be terminated by exactly the same string. I have tried</p> <pre><code>LOAD DATA INFILE 'filename' INTO TABLE mytable FIELDS TERMINATED BY ' '; </code></pre> <p>but MySQL will interpret a sequence of more than one space as delimiting an empty field.</p> <p>Any ideas?</p>
[ { "answer_id": 156550, "author": "Jauco", "author_id": 6874, "author_profile": "https://Stackoverflow.com/users/6874", "pm_score": 4, "selected": true, "text": "<p>If you're on unix/linux then you can put it through sed.</p>\n\n<p>open a terminal and type:</p>\n\n<pre><code>sed 's/ \\+/ /g' thefile &gt; thefile.new\n</code></pre>\n\n<p>this replaces all sequences of multiple spaces with one space.</p>\n" }, { "answer_id": 156568, "author": "Swanand", "author_id": 18768, "author_profile": "https://Stackoverflow.com/users/18768", "pm_score": 0, "selected": false, "text": "<p>You can also use the same command posted by Jauco to change the delimiter to ';' or \\n.\nThat would also help.</p>\n" }, { "answer_id": 156578, "author": "Ian", "author_id": 4396, "author_profile": "https://Stackoverflow.com/users/4396", "pm_score": 0, "selected": false, "text": "<p>Is there no way you can do this pragmatically? A simple PHP script would be able to load the file in, split by spaces, and do an insert in no time at all:</p>\n\n<pre><code>&lt;?php\n\n$db = mysql_connect('host', 'user', 'password')\nor die('Failed to connect');\nmysql_select_db('database', $db);\n\n$fileHandle= @fopen(\"import.file\", \"r\");\nif ($fileHandle) {\n while (!feof($fileHandle)) {\n $rawLine = fgets($fileHandle, 4096);\n\n $columns = preg_split(\"/\\s+/\", $rawLine);\n\n //Construct and run an INSERT statement here ... \n\n }\n fclose($fileHandle);\n}\n\n?&gt;\n</code></pre>\n\n<p><strong>Edit</strong>\nThat being said, <a href=\"https://stackoverflow.com/questions/156532/how-do-i-import-a-whitespace-delimited-text-file-into-mysql#156550\">Jakal's</a> suggestion is far neater ;)</p>\n" }, { "answer_id": 5462898, "author": "Felix", "author_id": 680691, "author_profile": "https://Stackoverflow.com/users/680691", "pm_score": 2, "selected": false, "text": "<p>If you're on Windows, just use Excel.</p>\n\n<p>Excel will import a whitespace-delimited file (check the 'treat subsequent delimiters as one' box from the import menu).</p>\n\n<p>Then you can simply save the file as a CSV from Excel and import into MySQL using:</p>\n\n<pre><code>LOAD DATA INFILE 'filename' INTO TABLE mytable FIELDS TERMINATED BY ','; \n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1428/" ]
I need to import largish (24MB) text files into a MySQL table. Each line looks like this: ``` 1 1 0.008 0 0 0 0 0 ``` There are one or more spaces after each field, and the last field is tailed by about 36 spaces before the newline. How do I import such a file into MySQL? From the documentation it seems that LOAD DATA expects all fields to be terminated by exactly the same string. I have tried ``` LOAD DATA INFILE 'filename' INTO TABLE mytable FIELDS TERMINATED BY ' '; ``` but MySQL will interpret a sequence of more than one space as delimiting an empty field. Any ideas?
If you're on unix/linux then you can put it through sed. open a terminal and type: ``` sed 's/ \+/ /g' thefile > thefile.new ``` this replaces all sequences of multiple spaces with one space.
156,563
<p>How do you setup an asp.net sql membership role/membership provider on a production machine? I'm trying to setup BlogEngine.NET and all the documentation says to use the ASP.NET Website Administration tool from Visual Studio but that isn't available on a production machine. Am I the first BlogEngine user to use it on a non-development box?</p> <p>The SQL server is completely blocked off from everything but the production box, I do have SQL Management Studio on there though.</p> <p>EDIT: I mean, how do you add new users/roles, not how do you create the tables. I've already ran aspnet_regsql to create the schema.</p> <p>EDIT2: MyWSAT doesn't work because it requires an initial user in the database as well. I need an application that will allow me to create new users in the membership database without any authentication, just a connection string.</p>
[ { "answer_id": 156583, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 0, "selected": false, "text": "<p>You'll have to have .NET 2.0 installed on the machine, all the VS tool is is a GUI wrapper for a command line tool which is part of the framework.</p>\n\n<p>Check C:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727 for the app aspnet_regsql.exe</p>\n\n<p>/? for command line switches, /W for a wizard mode</p>\n" }, { "answer_id": 156624, "author": "Bartek Szabat", "author_id": 23774, "author_profile": "https://Stackoverflow.com/users/23774", "pm_score": 2, "selected": false, "text": "<p>Solution 1 (standard, poor): Visual Studio -> Website menu -> ASP.NET Configuration.</p>\n\n<p>Solution 2 (preffered): <a href=\"http://www.codeplex.com/AspNetWSAT\" rel=\"nofollow noreferrer\">AspNetWSAT</a> (easy to deploy, pretty powerfull)</p>\n" }, { "answer_id": 158161, "author": "Thomas Wagner", "author_id": 13997, "author_profile": "https://Stackoverflow.com/users/13997", "pm_score": 0, "selected": false, "text": "<p>Have you looked at the IIS capabilities to manage membership? Go to the ASP.NET tab on IIS of the production server and see if this may help you. </p>\n" }, { "answer_id": 158238, "author": "ThatBloke", "author_id": 7050, "author_profile": "https://Stackoverflow.com/users/7050", "pm_score": 4, "selected": true, "text": "<p>I solved this problem by setting up a default super user at application start up.</p>\n\n<p>By adding this to gobal.asax</p>\n\n<pre>\n<code>\n void Application_Start(object sender, EventArgs e) \n {\n // Code that runs on application startup\n\n // check that the minimal security settings are created\n Security.SetupSecurity();\n }\n</code>\n</pre>\n\n<p>Then in the security class:</p>\n\n<pre>\n\nusing System;\nusing System.Data;\nusing System.Configuration;\nusing System.Web;\nusing System.Web.Security;\nusing System.Web.UI;\nusing System.Web.UI.HtmlControls;\nusing System.Web.UI.WebControls;\nusing System.Web.UI.WebControls.WebParts;\n\n/// \n/// Creates minimum roles and user for application access.\n/// \npublic class Security\n{\n // application roles\n public static string[] applicationRoles = \n { \"Roles1\", \"Roles2\", \"Roles3\", \"Roles4\", \"Roles5\" };\n // super user\n private static string superUser = \"super\";\n // default password, should be changed on first connection\n private static string superUserPassword = \"default\";\n\n private Security()\n {\n //\n // TODO: Add constructor logic here\n //\n }\n\n /// \n /// Creates minimal membership environment.\n /// \n public static void SetupSecurity()\n {\n SetupRoles();\n SetupSuperuser();\n }\n\n /// \n /// Checks roles, creates missing.\n /// \n public static void SetupRoles()\n {\n // create roles\n for (int i = 0; i \n /// Checks if superuser account is created.\n /// Creates the account and assigns it to all roles.\n /// \n public static void SetupSuperuser()\n {\n // create super user\n MembershipUser user = Membership.GetUser(superUser);\n if (user == null)\n Membership.CreateUser(superUser, superUserPassword, \"[email protected]\");\n\n // assign superuser to roles\n for (int i = 0; i \n</pre>\n\n<p>Once you have a default user, you can use AspNetWSAT or other.</p>\n" }, { "answer_id": 686332, "author": "user83188", "author_id": 83188, "author_profile": "https://Stackoverflow.com/users/83188", "pm_score": 1, "selected": false, "text": "<p>The solution is simple, the WSAT tool is on the production machine, but it's unreachable, you can configure the site\n, and you can use it.</p>\n\n<p>The WSAT tool with source code is located in your C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\ASP.NETWebAdminFiles folder. To make it accessible on the network, all you have to do is go to IIS–>Create new virtual directory–>Point to the above folder and remove anonymous access from directory settings page.</p>\n\n<p>Then you need to access it the same way your local ASP.Net configuration tool is accessed i.e via a URL which resembles something like :<a href=\"http://SERVER/AdminTool/default.aspx?applicationPhysicalPath=C\" rel=\"nofollow noreferrer\">http://SERVER/AdminTool/default.aspx?applicationPhysicalPath=C</a>:\\Inetpub\\wwwrooot\\testsite\\&amp;applicationUrl=/testsite</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17176/" ]
How do you setup an asp.net sql membership role/membership provider on a production machine? I'm trying to setup BlogEngine.NET and all the documentation says to use the ASP.NET Website Administration tool from Visual Studio but that isn't available on a production machine. Am I the first BlogEngine user to use it on a non-development box? The SQL server is completely blocked off from everything but the production box, I do have SQL Management Studio on there though. EDIT: I mean, how do you add new users/roles, not how do you create the tables. I've already ran aspnet\_regsql to create the schema. EDIT2: MyWSAT doesn't work because it requires an initial user in the database as well. I need an application that will allow me to create new users in the membership database without any authentication, just a connection string.
I solved this problem by setting up a default super user at application start up. By adding this to gobal.asax ``` void Application_Start(object sender, EventArgs e) { // Code that runs on application startup // check that the minimal security settings are created Security.SetupSecurity(); } ``` Then in the security class: ``` using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; /// /// Creates minimum roles and user for application access. /// public class Security { // application roles public static string[] applicationRoles = { "Roles1", "Roles2", "Roles3", "Roles4", "Roles5" }; // super user private static string superUser = "super"; // default password, should be changed on first connection private static string superUserPassword = "default"; private Security() { // // TODO: Add constructor logic here // } /// /// Creates minimal membership environment. /// public static void SetupSecurity() { SetupRoles(); SetupSuperuser(); } /// /// Checks roles, creates missing. /// public static void SetupRoles() { // create roles for (int i = 0; i /// Checks if superuser account is created. /// Creates the account and assigns it to all roles. /// public static void SetupSuperuser() { // create super user MembershipUser user = Membership.GetUser(superUser); if (user == null) Membership.CreateUser(superUser, superUserPassword, "[email protected]"); // assign superuser to roles for (int i = 0; i ``` Once you have a default user, you can use AspNetWSAT or other.
156,582
<p>I started using <a href="http://www.codeplex.com/SHFB" rel="noreferrer">Sandcastle</a> some time ago to generate a Documentation Website for one of our projects. It's working quite well but we've always only written documentation for classes, methods, properties (...) in our project and had completely separate documentation for the overall project and project parts/modules/namespaces. It would be nice if I could merge that documentation together and add respective documentation to the generated helper files but I can't figure out how to do it.</p> <p>Just adding comments to the namespace declaration doesn't seem to work (C#):</p> <pre><code>/// &lt;summary&gt; /// My short namespace description /// &lt;/summary&gt; namespace MyNamespace { ... } </code></pre> <p>Does anyone know how to do this? I know it's possible somehow and it would be really nice to have... :)</p>
[ { "answer_id": 156682, "author": "Davy Landman", "author_id": 11098, "author_profile": "https://Stackoverflow.com/users/11098", "pm_score": 4, "selected": false, "text": "<p>If you use <a href=\"http://www.codeplex.com/SHFB\" rel=\"noreferrer\">Sandcastle Help File Builder</a> there is a dialog to enter the Namespace summaries. (Apparently also support for defining a specific class, but I wouldn't prefer it..)</p>\n\n<p>From the feature list:</p>\n\n<blockquote>\n <p>Definition of project summary and\n namespace summary comments that will\n appear in the help file. You can also\n easily indicate which namespaces to\n include or exclude from the help file.\n Support is also included for\n specifying namespace comments via a\n NamespaceDoc class within each\n namespace.</p>\n</blockquote>\n" }, { "answer_id": 156726, "author": "Rinat Abdullin", "author_id": 47366, "author_profile": "https://Stackoverflow.com/users/47366", "pm_score": 3, "selected": false, "text": "<p>Use <a href=\"http://www.codeplex.com/SHFB\" rel=\"noreferrer\">Sandcastle Help File Builder</a>. It allows to specify namespace descriptions in the XML project file</p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>&lt;namespaceSummaryItem name=\"System\" isDocumented=\"True\"&gt;\n Generic interfaces and helper classes.\n&lt;/namespaceSummaryItem&gt;\n</code></pre>\n\n<p><strong>References:</strong> </p>\n\n<ul>\n<li><a href=\"http://lokad.svn.sourceforge.net/viewvc/lokad/Platform/Trunk/Shared/\" rel=\"noreferrer\">example of Open Source project</a>\nthat generates documentation with\nevery build (all scripts are in the\ntrunk).</li>\n<li>That's <a href=\"http://build.lokad.com/doc/shared/\" rel=\"noreferrer\">how the documentation by\nSHFB looks like on the Web</a> (it\nis deployed on every forced build)</li>\n</ul>\n\n<p>.</p>\n" }, { "answer_id": 857062, "author": "Tuinstoelen", "author_id": 106145, "author_profile": "https://Stackoverflow.com/users/106145", "pm_score": 7, "selected": true, "text": "<p>Sandcastle also supports the ndoc-style namespace documentation, which allows you to stick the documentation in the source files:</p>\n\n<p>Simply create a non-public class called NamespaceDoc in the namespace you want to document, and the xml doc comment for that class will be used for the namespace. </p>\n\n<p>Adorn it with a [CompilerGenerated] attribute to prevent the class itself from showing up in the documentation.</p>\n\n<p>Example:</p>\n\n<pre><code>namespace Some.Test\n{\n /// &lt;summary&gt;\n /// The &lt;see cref=\"Some.Test\"/&gt; namespace contains classes for ....\n /// &lt;/summary&gt;\n\n [System.Runtime.CompilerServices.CompilerGenerated]\n class NamespaceDoc\n {\n }\n}\n</code></pre>\n\n<p>The work item in SandCastle is located \n<a href=\"http://www.codeplex.com/SHFB/WorkItem/View.aspx?WorkItemId=15516\" rel=\"noreferrer\">here.</a></p>\n" }, { "answer_id": 23339077, "author": "user1587804", "author_id": 1587804, "author_profile": "https://Stackoverflow.com/users/1587804", "pm_score": 1, "selected": false, "text": "<p>You cant add references that way - do it via NamespaceDoc.cs instances</p>\n\n<p>i.e</p>\n\n<p><code>/// &lt;summary&gt;\n /// Concrete implementation of see cref=\"IInterface\" using see cref=\"Concrete\"<br>\n /// &lt;/summary&gt;\n class NamespaceDoc\n {\n }</code></p>\n\n<p><a href=\"http://www.ewoodruff.us/shfbdocs/html/48f5a893-acde-4e50-8c17-72b83d9c3f9d.htm\" rel=\"nofollow\">see here</a></p>\n" }, { "answer_id": 38833652, "author": "Luis", "author_id": 884784, "author_profile": "https://Stackoverflow.com/users/884784", "pm_score": 2, "selected": false, "text": "<p>I know it's an old post, but this may be of help to someone else.</p>\n\n<p><a href=\"http://www.blackwasp.co.uk/DocumentingNamespaces.aspx\" rel=\"nofollow noreferrer\">Following this link</a>, you can set a description for the namespaces without the need of adding a non-public class to your project.</p>\n\n<blockquote>\n <p>To edit the namespace summaries, expand the Summaries section within the Project Properties tab in SHFB. You will see a setting named, \"NamespaceSummaries\", which initially shows the value, \"(None)\". Click the setting to select it and a button showing an ellipsis symbol (...) appears. Click this button to display the Namespace Summaries dialog box, pictured below:</p>\n</blockquote>\n\n<p><a href=\"https://i.stack.imgur.com/lZwWQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lZwWQ.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 48572464, "author": "JohnKoz", "author_id": 3368670, "author_profile": "https://Stackoverflow.com/users/3368670", "pm_score": 0, "selected": false, "text": "<p>I see documentation for an \"External XML Comments Files\". Showing a schema like:</p>\n\n<pre><code>&lt;doc&gt;\n &lt;assembly/&gt;\n &lt;members&gt;\n &lt;member/&gt;\n &lt;/members&gt;\n&lt;/doc&gt;\n</code></pre>\n\n<p>If this is placed in a separate file, what would the extension be (xml/aml) and can this be used in the Visual Studio project?</p>\n" }, { "answer_id": 61606330, "author": "B Pete", "author_id": 83781, "author_profile": "https://Stackoverflow.com/users/83781", "pm_score": 0, "selected": false, "text": "<p>Here is the VB.Net version of the C# code snippet shown in Tuinstoelen's accepted answer. </p>\n\n<p>I am leaving this answer for those who find this question vis Google and need the VB version, since there is a gotcha waiting if you try to translate form the C# directly.</p>\n\n<pre><code>Namespace Global.TestNamespace\n ''' &lt;summary&gt;\n ''' The &lt;see cref=\"TestNamespace\"/&gt; namespace contains classes for ....\n ''' &lt;/summary&gt;\n &lt;System.Runtime.CompilerServices.CompilerGeneratedAttribute()&gt;\n Class NamespaceDoc\n End Class\nEnd Namespace\n</code></pre>\n\n<p>Note the \"Global.\" prepended to namespace to be documented. At least for my VB project configuration, this was necessary so that the name of the namespace is not nested inside the root namespace, but is the name of the root namespace. Before I prepended the \"Global.\", the compiler was generating a summary for \"TestNamespace.TestNamespace\", rather than just \"TestNamespace\". Given that incorrect info in the compiler generated XML file, SandCastle was not recognizing the summary as belonging to the correct namespace.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5005/" ]
I started using [Sandcastle](http://www.codeplex.com/SHFB) some time ago to generate a Documentation Website for one of our projects. It's working quite well but we've always only written documentation for classes, methods, properties (...) in our project and had completely separate documentation for the overall project and project parts/modules/namespaces. It would be nice if I could merge that documentation together and add respective documentation to the generated helper files but I can't figure out how to do it. Just adding comments to the namespace declaration doesn't seem to work (C#): ``` /// <summary> /// My short namespace description /// </summary> namespace MyNamespace { ... } ``` Does anyone know how to do this? I know it's possible somehow and it would be really nice to have... :)
Sandcastle also supports the ndoc-style namespace documentation, which allows you to stick the documentation in the source files: Simply create a non-public class called NamespaceDoc in the namespace you want to document, and the xml doc comment for that class will be used for the namespace. Adorn it with a [CompilerGenerated] attribute to prevent the class itself from showing up in the documentation. Example: ``` namespace Some.Test { /// <summary> /// The <see cref="Some.Test"/> namespace contains classes for .... /// </summary> [System.Runtime.CompilerServices.CompilerGenerated] class NamespaceDoc { } } ``` The work item in SandCastle is located [here.](http://www.codeplex.com/SHFB/WorkItem/View.aspx?WorkItemId=15516)
156,584
<p>I've seen a few examples on how to do build deployment, however I have something unique that I'd like to do:</p> <ol> <li>Deploy the build to a folder that has the build number (eg. Project\Builds\8423)</li> <li>Alter the version number in the .NET AssmblyInfo.cs to match the build number</li> </ol> <p>Has anyone done this before with .NET projects using NAnt + CruiseControl.net?</p>
[ { "answer_id": 156612, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>i haven't done it with nant, but we have written a custom application in C# that reads the assembly and increments the release number.</p>\n\n<p>we call it from an exec block in the ccnet config.</p>\n\n<p>creating a folder and copying files would be trivial to add to that application</p>\n\n<p>our thinking was we use C# all day, so it would be quicker to fix/alter the build program written in C#, then if we had to learn the intracies of nant scripts on top of that</p>\n\n<p>obviously if you use nant all the time, there would be no reason not to build a custom nant plugin to do the job</p>\n" }, { "answer_id": 156643, "author": "ZombieSheep", "author_id": 377, "author_profile": "https://Stackoverflow.com/users/377", "pm_score": 0, "selected": false, "text": "<p>I agree with BumperBox, a separate assembly to do the heavy(?) lifting of incrementing the build number is the route I took a couple of years ago, too. It has the advantage of being able to cope with other external factors, too. For example, you might want to increment the release or build numbers if a certain criteria exists within a config file.</p>\n" }, { "answer_id": 156864, "author": "Rinat Abdullin", "author_id": 47366, "author_profile": "https://Stackoverflow.com/users/47366", "pm_score": 2, "selected": false, "text": "<p>Check out this <a href=\"http://code.google.com/p/photon-dot-net/\" rel=\"nofollow noreferrer\">open-source project</a>. Although, it uses MSBuild, the differences are minor.</p>\n\n<p>CC.NET passes the distrib directory and version to the <a href=\"http://code.google.com/p/photon-dot-net/source/browse/trunk/Photon.ccnet\" rel=\"nofollow noreferrer\">Photon.ccnet</a> script, which is a simple wrapper around <a href=\"http://code.google.com/p/photon-dot-net/source/browse/trunk/Photon.build\" rel=\"nofollow noreferrer\">Photon.build</a> script. Version number is used in folder and package naming and also in the assembly versions. </p>\n\n<p>Version numbers come from the <a href=\"http://code.google.com/p/svnrevisionlabeller/\" rel=\"nofollow noreferrer\">svnRevisionLabellerPlugin</a> for CC.NET</p>\n\n<p>And <a href=\"http://build.lokad.com/distrib/shared/\" rel=\"nofollow noreferrer\">that's how everything looks</a> in the end.</p>\n" }, { "answer_id": 163518, "author": "Mike", "author_id": 2848, "author_profile": "https://Stackoverflow.com/users/2848", "pm_score": 0, "selected": false, "text": "<p>You can use the CCNetLabel property that is passed into your NAnt script to set where it deploys to.</p>\n\n<p>As for the AssemblyInfo, for MSBuild there is a Task in <a href=\"http://msbuildtasks.tigris.org/\" rel=\"nofollow noreferrer\">MSBuildCommunityTasks</a> that works well. Don't know what the NAnt equivalent would be although you could run an MSBuild script before your NAnt script that changed it.</p>\n\n<p>Configuration is simple:</p>\n\n<pre><code>&lt;AssemblyInfo CodeLanguage=\"C#\"\n OutputFile=\"%(YourProjects.RootDir)%(Directory)Properties\\AssemblyInfo.cs\"\n AssemblyVersion=\"$(CCNetLabel)\"\n/&gt;\n</code></pre>\n\n<p>You will need to add whatever other attributes you need as well as this will overwrite the AssemblyInfo file.</p>\n" }, { "answer_id": 170239, "author": "scott.caligan", "author_id": 14814, "author_profile": "https://Stackoverflow.com/users/14814", "pm_score": 4, "selected": false, "text": "<p>Deploying a build to a folder with the build number is pretty straightforward. <a href=\"http://confluence.public.thoughtworks.org/display/CCNET/NAnt+Task\" rel=\"nofollow noreferrer\">CruiseControl.NET's NAnt task</a> automatically passes a number of properties to your NAnt script. The <em>CCNetLabel</em> property is the one you'd use to create your deployment directory. There's actually a slightly out of date example NAnt script in the CruiseControl.NET documentation that does just that. Here's a nicer version of it:</p>\n\n<pre><code>&lt;target name=\"publish\"&gt;\n &lt;if test=\"${not property::exists('CCNetLabel')}\"&gt;\n &lt;fail message=\"CCNetLabel property not set, so can't create labelled distribution files\" /&gt;\n &lt;/if&gt;\n\n &lt;property name=\"publishDirectory\" value=\"D:\\Public\\Project\\Builds\\${CCNetLabel}\" /&gt;\n\n &lt;mkdir dir=\"${publishDirectory}\" /&gt;\n &lt;copy todir=\"${publishDirectory}\"&gt;\n &lt;fileset basedir=\"${buildDirectory}\\bin\"&gt;\n &lt;include name=\"*.dll\" /&gt;\n &lt;/fileset&gt;\n &lt;/copy&gt; \n&lt;/target&gt;\n</code></pre>\n\n<p>As far as versioning your binaries goes, I find the following approach much cleaner and easier than trying to alter your AssemblyInfo.cs files. Basically I create a CommonAssemblyInfo.cs file that lives outside of any projects, in the same directory as your solution file. This file includes things that are common to all assemblies I'm building, like company name, copyright info, and of course - version. This file is <a href=\"http://dotnettipoftheday.org/tips/linking_file_in_visual_studio.aspx\" rel=\"nofollow noreferrer\">linked</a> in each project in Visual Studio, so each project includes this info (along with a much smaller AssemblyInfo.cs file that includes assembly-specific info like assembly title).</p>\n\n<p>When projects are built locally, either through Visual Studio or NAnt, that CommonAssemblyInfo.cs file is used. However, when projects are built by CruiseControl.NET, I use NAnt to replace that file via the <a href=\"http://nant.sourceforge.net/release/latest/help/tasks/asminfo.html\" rel=\"nofollow noreferrer\"><code>&lt;asminfo&gt;</code></a> task. Here's what the NAnt script looks like:</p>\n\n<pre><code>&lt;target name=\"version\"&gt;\n &lt;property name=\"commonAssemblyInfo\" value=\"${buildDirectory}\\CommonAssemblyInfo.cs\" /&gt;\n\n &lt;!-- If build is initiated manually, copy standard CommonAssemblyInfo.cs file. --&gt;\n &lt;if test=\"${not property::exists('CCNetLabel')}\"&gt;\n &lt;copy file=\".\\src\\CommonAssemblyInfo.cs\" tofile=\"${commonAssemblyInfo}\" /&gt;\n &lt;/if&gt;\n\n &lt;!-- If build is initiated by CC.NET, create a custom CommonAssemblyInfo.cs file. --&gt;\n &lt;if test=\"${property::exists('CCNetLabel')}\"&gt;\n &lt;asminfo output=\"${commonAssemblyInfo}\" language=\"CSharp\"&gt;\n &lt;imports&gt;\n &lt;import namespace=\"System\" /&gt;\n &lt;import namespace=\"System.Reflection\" /&gt;\n &lt;/imports&gt;\n &lt;attributes&gt;\n &lt;attribute type=\"AssemblyCompanyAttribute\" value=\"My Company\" /&gt;\n &lt;attribute type=\"AssemblyCopyrightAttribute\" value=\"Copyright © 2008 My Company\" /&gt;\n &lt;attribute type=\"AssemblyProductAttribute\" value=\"My Product\" /&gt;\n &lt;attribute type=\"AssemblyVersionAttribute\" value=\"1.0.0.${CCNetLabel}\" /&gt;\n &lt;attribute type=\"AssemblyInformationalVersionAttribute\" value=\"1.0.0.${CCNetLabel}\" /&gt;\n &lt;/attributes&gt;\n &lt;references&gt;\n &lt;include name=\"System.dll\" /&gt;\n &lt;/references&gt;\n &lt;/asminfo&gt;\n &lt;/if&gt;\n&lt;/target&gt;\n\n&lt;target name=\"build-my-project\" depends=\"version\"&gt;\n &lt;csc target=\"library\" output=\"${buildDirectory}\\bin\\MyProject.dll\"&gt;\n &lt;sources&gt;\n &lt;include name=\".\\src\\MyProject\\*.cs\"/&gt;\n &lt;include name=\".\\src\\MyProject\\**\\*.cs\"/&gt;\n &lt;include name=\"${commonAssemblyInfo}\"/&gt;\n &lt;/sources&gt;\n &lt;/csc&gt;\n&lt;/target&gt;\n</code></pre>\n\n<p>Note where the <em>AssemblyVersionAttribute</em> and <em>AssemblyInformationalVersionAttribute</em> values are set in the <em>version</em> target. The <em>CCNetLabel</em> property is inserted into the version numbers. For added benefit, you could use a CruiseControl.NET plugin like the previously mentioned <a href=\"http://code.google.com/p/svnrevisionlabeller/\" rel=\"nofollow noreferrer\">SvnRevisionLabeller</a>. Using that, we get builds with labels like \"2.1.8239.0\", where the \"8239\" corresponds to the Subversion revision number we're building from. We dump this build number directly into our <em>AssemblyVersionAttribute</em> and <em>AssemblyInformationalVersionAttributes</em>, and our build numbers and the version numbers on our assemblies can all be easily traced back to a specific revision in our version control system.</p>\n" }, { "answer_id": 238167, "author": "DilbertDave", "author_id": 31580, "author_profile": "https://Stackoverflow.com/users/31580", "pm_score": 2, "selected": false, "text": "<p>I'm quite new to Cruise Control and nAnt as well but I found <a href=\"http://www.hanselman.com/blog/BuildingMSIFilesFromNAntAndUpdatingTheVDProjsVersionInformationAndOtherSinsOnTuesday.aspx\" rel=\"nofollow noreferrer\">Scott Hanselman's Blog Post</a> very helpful.</p>\n\n<p>Not perfect and not pretty but it does get the job done.</p>\n\n<p>There is also an <a href=\"http://code.mattgriffith.net/UpdateVersion/\" rel=\"nofollow noreferrer\">UpdateVersion Utility</a> (which Scott also appears to have had a hand in).</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17222/" ]
I've seen a few examples on how to do build deployment, however I have something unique that I'd like to do: 1. Deploy the build to a folder that has the build number (eg. Project\Builds\8423) 2. Alter the version number in the .NET AssmblyInfo.cs to match the build number Has anyone done this before with .NET projects using NAnt + CruiseControl.net?
Deploying a build to a folder with the build number is pretty straightforward. [CruiseControl.NET's NAnt task](http://confluence.public.thoughtworks.org/display/CCNET/NAnt+Task) automatically passes a number of properties to your NAnt script. The *CCNetLabel* property is the one you'd use to create your deployment directory. There's actually a slightly out of date example NAnt script in the CruiseControl.NET documentation that does just that. Here's a nicer version of it: ``` <target name="publish"> <if test="${not property::exists('CCNetLabel')}"> <fail message="CCNetLabel property not set, so can't create labelled distribution files" /> </if> <property name="publishDirectory" value="D:\Public\Project\Builds\${CCNetLabel}" /> <mkdir dir="${publishDirectory}" /> <copy todir="${publishDirectory}"> <fileset basedir="${buildDirectory}\bin"> <include name="*.dll" /> </fileset> </copy> </target> ``` As far as versioning your binaries goes, I find the following approach much cleaner and easier than trying to alter your AssemblyInfo.cs files. Basically I create a CommonAssemblyInfo.cs file that lives outside of any projects, in the same directory as your solution file. This file includes things that are common to all assemblies I'm building, like company name, copyright info, and of course - version. This file is [linked](http://dotnettipoftheday.org/tips/linking_file_in_visual_studio.aspx) in each project in Visual Studio, so each project includes this info (along with a much smaller AssemblyInfo.cs file that includes assembly-specific info like assembly title). When projects are built locally, either through Visual Studio or NAnt, that CommonAssemblyInfo.cs file is used. However, when projects are built by CruiseControl.NET, I use NAnt to replace that file via the [`<asminfo>`](http://nant.sourceforge.net/release/latest/help/tasks/asminfo.html) task. Here's what the NAnt script looks like: ``` <target name="version"> <property name="commonAssemblyInfo" value="${buildDirectory}\CommonAssemblyInfo.cs" /> <!-- If build is initiated manually, copy standard CommonAssemblyInfo.cs file. --> <if test="${not property::exists('CCNetLabel')}"> <copy file=".\src\CommonAssemblyInfo.cs" tofile="${commonAssemblyInfo}" /> </if> <!-- If build is initiated by CC.NET, create a custom CommonAssemblyInfo.cs file. --> <if test="${property::exists('CCNetLabel')}"> <asminfo output="${commonAssemblyInfo}" language="CSharp"> <imports> <import namespace="System" /> <import namespace="System.Reflection" /> </imports> <attributes> <attribute type="AssemblyCompanyAttribute" value="My Company" /> <attribute type="AssemblyCopyrightAttribute" value="Copyright © 2008 My Company" /> <attribute type="AssemblyProductAttribute" value="My Product" /> <attribute type="AssemblyVersionAttribute" value="1.0.0.${CCNetLabel}" /> <attribute type="AssemblyInformationalVersionAttribute" value="1.0.0.${CCNetLabel}" /> </attributes> <references> <include name="System.dll" /> </references> </asminfo> </if> </target> <target name="build-my-project" depends="version"> <csc target="library" output="${buildDirectory}\bin\MyProject.dll"> <sources> <include name=".\src\MyProject\*.cs"/> <include name=".\src\MyProject\**\*.cs"/> <include name="${commonAssemblyInfo}"/> </sources> </csc> </target> ``` Note where the *AssemblyVersionAttribute* and *AssemblyInformationalVersionAttribute* values are set in the *version* target. The *CCNetLabel* property is inserted into the version numbers. For added benefit, you could use a CruiseControl.NET plugin like the previously mentioned [SvnRevisionLabeller](http://code.google.com/p/svnrevisionlabeller/). Using that, we get builds with labels like "2.1.8239.0", where the "8239" corresponds to the Subversion revision number we're building from. We dump this build number directly into our *AssemblyVersionAttribute* and *AssemblyInformationalVersionAttributes*, and our build numbers and the version numbers on our assemblies can all be easily traced back to a specific revision in our version control system.
156,585
<p>I'm just wondering if there can be a case where the hostname can be successfully resolved but the returned hostEntry.AddressList is empty.</p> <p>Currently I'm doing something like this:</p> <pre><code>IPHostEntry hostEntry = Dns.GetHostEntry("some.hostname.tld"); if (hostEntry.AddressList.Count() &lt; 1) { // can that ever happen? throw new ArgumentException("hostName has no assigned IP-Address"); } TcpClient client = new TcpClient(hostEntry.AddressList[0], 1234); </code></pre> <p>My assumption is that Dns.GetHostEntry either throws an exception if the hostname is not found or otherwise the AddressList is nonempty, but I'm not sure about that.</p>
[ { "answer_id": 156598, "author": "user17222", "author_id": 17222, "author_profile": "https://Stackoverflow.com/users/17222", "pm_score": 0, "selected": false, "text": "<p>You have three possible situations here:</p>\n\n<ol>\n<li><p>The hostname exists (DNS has an A Record) and resolves to an IP Address</p>\n\n<ul>\n<li>Condition is never hit</li>\n</ul></li>\n<li><p>The hostname exists (DNS knows about the domain) however no A records exists.</p>\n\n<ul>\n<li>This is an extremely unlikely scenario, and I think this can never happen in the first place.</li>\n</ul></li>\n<li><p>The hostname doesn't exist</p>\n\n<ul>\n<li>Exception is thrown, you never get there.</li>\n</ul></li>\n</ol>\n\n<p>So no, I don't think that can ever happen.</p>\n" }, { "answer_id": 156638, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 2, "selected": true, "text": "<p>No, you'll not see an empty address list: even if you query a DNS label that does exist, but has no A or AAAA (IPv6) records, a SocketException (\"No Such Host is Known\") will be thrown.</p>\n\n<p>You can verify this by looking at the function <code>InternalGetHostByName(string hostName, bool includeIPv6)</code> in DNS.cs from the .NET Reference Source release. With the exception of some platform-specific precautions, DNS lookups are a simple wrapper around the Winsock <a href=\"http://msdn.microsoft.com/en-us/library/ms738524.aspx\" rel=\"nofollow noreferrer\">gethostbyname</a> function.</p>\n\n<p>Gethostbyname will either fail, or return an address list. An empty address list is never returned, because the function will fail with WSANO_DATA (\"Valid name, no data record of requested type\") in this case, which translates to the socket exception we already saw in .NET.</p>\n\n<p><em>EDIT May 2012, prompted by responses stating that an empty list is returned anyway:</em> do note that this answer only applies to Win32, and that platforms like WinCE may behave quite differently. If you're seeing 'empty list' behavior on Win32, and the request you're making is against a publicly available DNS server, please post your code... </p>\n" }, { "answer_id": 157053, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 1, "selected": false, "text": "<p>Just for the records.</p>\n\n<p>Thanks to mdb's <a href=\"https://stackoverflow.com/questions/156585/can-dnsgethostentry-ever-return-an-iphostentry-with-an-empty-addresslist#156638\">accepted answer</a> I took a look at the <a href=\"http://msdn.microsoft.com/en-us/library/ms740668(VS.85).aspx\" rel=\"nofollow noreferrer\">description of the WSANO_DATA error</a>:</p>\n\n<blockquote>\n <p>The requested name is valid and was found in the database, but it does\n not have the correct associated data being resolved for. The usual example\n for this is a host name-to-address translation attempt (using gethostbyname or\n WSAAsyncGetHostByName) which uses the DNS (Domain Name Server). An MX record\n is returned but no A record—indicating the host itself exists, but is not\n directly reachable.</p>\n</blockquote>\n\n<p>So this pretty much answers my question :)</p>\n" }, { "answer_id": 38927065, "author": "Nassar Nimer", "author_id": 6660393, "author_profile": "https://Stackoverflow.com/users/6660393", "pm_score": 0, "selected": false, "text": "<p>The answer is <strong>YES</strong>.\nThe GetHostEntry method queries a DNS server for the IP addresses and aliases associated with an IP address.</p>\n\n<p><strong>IPv6 addresses are filtered from the results of the GetHostEntry method if the local computer does not have IPv6 installed. As a result, it is possible to get back an empty IPHostEntry instance if only IPv6 results where available for the address parameter.</strong></p>\n\n<p>The Aliases property of the IPHostEntry instance returned is not populated by this method and will always be empty.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21038/" ]
I'm just wondering if there can be a case where the hostname can be successfully resolved but the returned hostEntry.AddressList is empty. Currently I'm doing something like this: ``` IPHostEntry hostEntry = Dns.GetHostEntry("some.hostname.tld"); if (hostEntry.AddressList.Count() < 1) { // can that ever happen? throw new ArgumentException("hostName has no assigned IP-Address"); } TcpClient client = new TcpClient(hostEntry.AddressList[0], 1234); ``` My assumption is that Dns.GetHostEntry either throws an exception if the hostname is not found or otherwise the AddressList is nonempty, but I'm not sure about that.
No, you'll not see an empty address list: even if you query a DNS label that does exist, but has no A or AAAA (IPv6) records, a SocketException ("No Such Host is Known") will be thrown. You can verify this by looking at the function `InternalGetHostByName(string hostName, bool includeIPv6)` in DNS.cs from the .NET Reference Source release. With the exception of some platform-specific precautions, DNS lookups are a simple wrapper around the Winsock [gethostbyname](http://msdn.microsoft.com/en-us/library/ms738524.aspx) function. Gethostbyname will either fail, or return an address list. An empty address list is never returned, because the function will fail with WSANO\_DATA ("Valid name, no data record of requested type") in this case, which translates to the socket exception we already saw in .NET. *EDIT May 2012, prompted by responses stating that an empty list is returned anyway:* do note that this answer only applies to Win32, and that platforms like WinCE may behave quite differently. If you're seeing 'empty list' behavior on Win32, and the request you're making is against a publicly available DNS server, please post your code...
156,610
<p>I have a requirement to be able to provide a flex component in English and several asian languages. I have looked at the flex documentation and it seems that I have to build several swf's, which feels wrong. </p> <p>Does anyone know of a straightforward and practical way of bundling string resources in different languages and handling the fonts?</p>
[ { "answer_id": 156631, "author": "Nadav", "author_id": 23094, "author_profile": "https://Stackoverflow.com/users/23094", "pm_score": 0, "selected": false, "text": "<p>We use Flex for the client part of our application and support I18N via <a href=\"http://livedocs.adobe.com/flex/201/html/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Book_Parts&amp;file=l10n_076_4.html\" rel=\"nofollow noreferrer\"><code>ResourceBundle</code></a>s. </p>\n" }, { "answer_id": 156668, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 0, "selected": false, "text": "<p>In Flex 2.01 the language has to be built into the SWF - you can't change it at runtime. In Flex 3 you can switch language at runtime.</p>\n\n<p><a href=\"http://labs.adobe.com/wiki/index.php/Flex_3:Feature_Introductions:_Runtime_Localization\" rel=\"nofollow noreferrer\">http://labs.adobe.com/wiki/index.php/Flex_3:Feature_Introductions:_Runtime_Localization</a></p>\n" }, { "answer_id": 156718, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 4, "selected": true, "text": "<p>I guess you know the basics of how to localize a Flex application, but if you would like to know more there's a good and thorough description here: <a href=\"http://labs.adobe.com/wiki/index.php/Flex_3:Feature_Introductions:_Runtime_Localization\" rel=\"nofollow noreferrer\">Runtime Localization</a>.</p>\n\n<p>In Flex 3 you have three options on how to solve your problem:</p>\n\n<ol>\n<li>compile all languages into the SWF and switch language at runtime</li>\n<li>compile a separate SWF for each language</li>\n<li>compile no, or a default, language into the SWF and load additional languages at runtime</li>\n</ol>\n\n<p>The first option is probably the most common, the least complex and doesn't have many drawbacks. The other two can be used if you have special needs, like having to keep down the size of the SWF at all cost, or need to load all strings from a database at runtime.</p>\n\n<p>To implement the first option you create a resource bundle for each language (basically a number of <code>.properties</code> files that lives in a directory named after the locale, for example en_US for US English or sv_SE for Swedish). In the code you refer to strings by calling the resource manager:</p>\n\n<pre><code>&lt;Label text=\"{resourceManager.getString('mybundle', 'mystring\")'}/&gt;\n</code></pre>\n\n<p>That will retrieve a string called \"mystring\" in the resource bundle compiled from \"mybundle.properties\" in the current locale.</p>\n\n<p>To make sure each locale is actually compiled into the application you add <code>-locale=en_US,sv_SE</code> to the compiler flags (but change the <code>en_US,sv_SE</code> part to the languages you have resource bundles for). You also need to add the location of the directories to the source path: <code>-source-path+=locale/{locale}</code> (the \"<code>{locale}</code>\" part will automatically be replaced by the values of the <code>-locale</code> flag).</p>\n\n<p>Now you have compiled all your languages into the SWF and can change languages at runtime. The way to do that is to modify the <code>localeChain</code> property of the resource manager:</p>\n\n<pre><code>resourceManager.localeChain = [\"sv_SE\", \"en_US\"];\n</code></pre>\n\n<p>With the settings shown above the resource manager will first look in the Swedish resource bundle, and secondly in the one for US English. You can set another order at any time, and doing so will change all texts in the application then and there.</p>\n\n<p>I encourage you to read <a href=\"http://labs.adobe.com/wiki/index.php/Flex_3:Feature_Introductions:_Runtime_Localization\" rel=\"nofollow noreferrer\">the description I referred to above</a>, it explains this in greater detail, and most likely in a more understandable way. It also explains how to do some preparations you need to do before you can compile applications with locales other than en_US.</p>\n\n<p>The other problem you have is with fonts. That one is trickier. The best thing would be to have a font that had the full Unicode range of characters, that way you would only need to embed that and any text could be displayed. However, that means that your options are a bit more limited. I know that there is at least one version of Aria in Windows that has an enourmous number of characters, and on the Mac there is a Helvetica (I think, or it might be Lucida Grande, or both) that also has most of the ones you need to display many asian languages.</p>\n\n<p>Embedding all languages into the same SWF usually does very little to increase the file size, because text is very lightweight, but fonts are definitely not. Embedding a the whole Unicode version of Arial can increase the file size of a SWF by several megabyte, which kind of sucks for web applications. Depending on the situation you may have to compile one SWF per language, just because the font data would otherwise make the SWF unwieldy.</p>\n" }, { "answer_id": 157927, "author": "Brandon", "author_id": 23133, "author_profile": "https://Stackoverflow.com/users/23133", "pm_score": 0, "selected": false, "text": "<p>An important step left out above is to run the command:</p>\n\n<pre><code>copylocale.exe en_US sv_SE\n</code></pre>\n\n<p>from the bin folder of the sdk. This is in the article though.</p>\n" }, { "answer_id": 159503, "author": "Brian", "author_id": 1750627, "author_profile": "https://Stackoverflow.com/users/1750627", "pm_score": 1, "selected": false, "text": "<p>Beware of fonts. System fonts aren't the prettiest but Asian fonts are too large to embed. We resorted to embedding Latin fonts for English and switching to system fonts for Chinese.</p>\n\n<p>Be careful about rotating system fonts - your text will disappear. I think Flash 10 might have fixed this.</p>\n\n<p>Also, be very careful with the font string you specify for Chinese. </p>\n\n<p>Most OSes have nifty fall-back logic - if you specify Trebuchet and try to render a Chinese character, your OS might decide to use some Asian font instead. Flash seems to mess up this fall-back logic and switch between two or more Asian fonts dynamically. We had cases where mousing over a text block would switch the font.</p>\n\n<p>To fix this, specify a font which includes all the characters you need (without falling back to some other font). You will need to test this across OSes, etc.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24039/" ]
I have a requirement to be able to provide a flex component in English and several asian languages. I have looked at the flex documentation and it seems that I have to build several swf's, which feels wrong. Does anyone know of a straightforward and practical way of bundling string resources in different languages and handling the fonts?
I guess you know the basics of how to localize a Flex application, but if you would like to know more there's a good and thorough description here: [Runtime Localization](http://labs.adobe.com/wiki/index.php/Flex_3:Feature_Introductions:_Runtime_Localization). In Flex 3 you have three options on how to solve your problem: 1. compile all languages into the SWF and switch language at runtime 2. compile a separate SWF for each language 3. compile no, or a default, language into the SWF and load additional languages at runtime The first option is probably the most common, the least complex and doesn't have many drawbacks. The other two can be used if you have special needs, like having to keep down the size of the SWF at all cost, or need to load all strings from a database at runtime. To implement the first option you create a resource bundle for each language (basically a number of `.properties` files that lives in a directory named after the locale, for example en\_US for US English or sv\_SE for Swedish). In the code you refer to strings by calling the resource manager: ``` <Label text="{resourceManager.getString('mybundle', 'mystring")'}/> ``` That will retrieve a string called "mystring" in the resource bundle compiled from "mybundle.properties" in the current locale. To make sure each locale is actually compiled into the application you add `-locale=en_US,sv_SE` to the compiler flags (but change the `en_US,sv_SE` part to the languages you have resource bundles for). You also need to add the location of the directories to the source path: `-source-path+=locale/{locale}` (the "`{locale}`" part will automatically be replaced by the values of the `-locale` flag). Now you have compiled all your languages into the SWF and can change languages at runtime. The way to do that is to modify the `localeChain` property of the resource manager: ``` resourceManager.localeChain = ["sv_SE", "en_US"]; ``` With the settings shown above the resource manager will first look in the Swedish resource bundle, and secondly in the one for US English. You can set another order at any time, and doing so will change all texts in the application then and there. I encourage you to read [the description I referred to above](http://labs.adobe.com/wiki/index.php/Flex_3:Feature_Introductions:_Runtime_Localization), it explains this in greater detail, and most likely in a more understandable way. It also explains how to do some preparations you need to do before you can compile applications with locales other than en\_US. The other problem you have is with fonts. That one is trickier. The best thing would be to have a font that had the full Unicode range of characters, that way you would only need to embed that and any text could be displayed. However, that means that your options are a bit more limited. I know that there is at least one version of Aria in Windows that has an enourmous number of characters, and on the Mac there is a Helvetica (I think, or it might be Lucida Grande, or both) that also has most of the ones you need to display many asian languages. Embedding all languages into the same SWF usually does very little to increase the file size, because text is very lightweight, but fonts are definitely not. Embedding a the whole Unicode version of Arial can increase the file size of a SWF by several megabyte, which kind of sucks for web applications. Depending on the situation you may have to compile one SWF per language, just because the font data would otherwise make the SWF unwieldy.
156,641
<p>I have a table of users which has a username column consisting of a six digit number e.g 675381, I need to prepend a zero to each of these usernames e.g. 0675381 would be the final output of the previous example, is there a query that could handle this?</p>
[ { "answer_id": 156656, "author": "daniels", "author_id": 9789, "author_profile": "https://Stackoverflow.com/users/9789", "pm_score": 6, "selected": true, "text": "<pre><code>UPDATE Tablename SET Username = Concat('0', Username);\n</code></pre>\n" }, { "answer_id": 156657, "author": "f13o", "author_id": 20288, "author_profile": "https://Stackoverflow.com/users/20288", "pm_score": 3, "selected": false, "text": "<p>what type is the column of?</p>\n\n<p>if it's string type, try something like this:</p>\n\n<pre><code>UPDATE your_table SET column_name=concat('0',column_name);\n</code></pre>\n" }, { "answer_id": 156664, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 2, "selected": false, "text": "<p>You mean \"prepend\" ? i.e. add it on the front?</p>\n\n<p>Is the column numeric? Do you always want 7 characters output?</p>\n\n<p>Assuming that, something like this would work for a query:</p>\n\n<pre><code>select LPAD(CONVERT(username, CHAR), 7, '0')\n</code></pre>\n\n<p>If the column is characters, the CONVERT() part is unnecessary, just LPAD the username.</p>\n\n<p>If you want to permanently modify the value in the table, you'll need to ensure the column is a character type and UPDATE using the above.</p>\n" }, { "answer_id": 160102, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 0, "selected": false, "text": "<p>You might want to use CONCAT_WS('', '0', Username) because if there is a null value, then you'll end up with NULL instead of '0'. This probably isn't a problem, but something I've learnt the hard way.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13658/" ]
I have a table of users which has a username column consisting of a six digit number e.g 675381, I need to prepend a zero to each of these usernames e.g. 0675381 would be the final output of the previous example, is there a query that could handle this?
``` UPDATE Tablename SET Username = Concat('0', Username); ```
156,650
<p>When reviewing, I sometimes encounter this kind of loop:</p> <pre><code>i = begin while ( i != end ) { // ... do stuff if ( i == end-1 (the one-but-last element) ) { ... do other stuff } increment i } </code></pre> <p>Then I ask the question: would you write this?</p> <pre><code>i = begin mid = ( end - begin ) / 2 // (the middle element) while ( i != end ) { // ... do stuff if ( i &gt; mid ) { ... do other stuff } increment i } </code></pre> <p>In my opinion, this beats the intention of writing a loop: you loop because there is something common to be done for each of the elements. Using this construct, for some of the elements you do something different. So, I conclude, you need a separate loop for those elements:</p> <pre><code>i = begin mid = ( end - begin ) / 2 //(the middle element) while ( i != mid ) { // ... do stuff increment i } while ( i != end ) { // ... do stuff // ... do other stuff increment i } </code></pre> <p>Now I even saw a <a href="https://stackoverflow.com/questions/151046/c-last-loop-iteration-stl-map-iterator">question</a> on SO on how to write the <code>if</code>-clause in a nice way... And I got sad: something isn't right here.</p> <p>Am I wrong? If so, what's so good about cluttering the loop body with special cases, which you are aware of upfront, at coding time?</p>
[ { "answer_id": 156660, "author": "Dark Shikari", "author_id": 11206, "author_profile": "https://Stackoverflow.com/users/11206", "pm_score": 2, "selected": false, "text": "<p>Of course, special-casing things in a loop which can be pulled out is silly. I wouldn't duplicate the do_stuff either though; I'd either put it in a function or a macro so I don't copy-paste code.</p>\n" }, { "answer_id": 156667, "author": "Simon", "author_id": 24039, "author_profile": "https://Stackoverflow.com/users/24039", "pm_score": 2, "selected": false, "text": "<p>Which one performs better?</p>\n\n<p>If the number of items is very large then I would always loop once, especially if you are going to perform <em>some</em> operation on every item. The cost of evaluating the conditional is likely to be less than looping twice.</p>\n\n<p>Oops, of course you are not looping twice... In which case two loops is preferable. However, I maintain that the primary consideration should be performance. There's no need to incur the conditional in the loop (N times) if you can partition the work by a simple manipulation of the loop bounds (once).</p>\n" }, { "answer_id": 156669, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 4, "selected": false, "text": "<p>I know I've seen this when people tried to join elements of an array into a comma-seperated string:</p>\n\n<pre><code>for(i=0;i&lt;elements.size;i++) {\n if (i&gt;0) {\n string += ','\n }\n string += elements[i]\n}\n</code></pre>\n\n<p>You either have that if clause in there, or you have to duplicate the string += line again at the end.</p>\n\n<p>The obvious solution in this case is</p>\n\n<pre><code>string = elements.join(',')\n</code></pre>\n\n<p>But the join method does the same loop internally. And there isn't always a method to do what you want.</p>\n" }, { "answer_id": 156672, "author": "Michael Brown", "author_id": 14359, "author_profile": "https://Stackoverflow.com/users/14359", "pm_score": 3, "selected": false, "text": "<p>I came to a realization that when I put special cases in a for loop, I'm usually being too clever for my own good.</p>\n" }, { "answer_id": 156673, "author": "Scottm", "author_id": 22061, "author_profile": "https://Stackoverflow.com/users/22061", "pm_score": 2, "selected": false, "text": "<p>I think you are right about the loop being meant to deal with all elements equally. Unfortunately sometimes there are special cases though and these should be dealt with inside the loop construct via if statements.</p>\n\n<p>If there are lots of special cases though you should probably think about coming up with some way to deal with the two different sets of elements in separate constructs.</p>\n" }, { "answer_id": 156678, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 2, "selected": false, "text": "<p>Another thing I hate to see is the <a href=\"http://thedailywtf.com/Articles/The_FOR-CASE_paradigm.aspx\" rel=\"nofollow noreferrer\">for-case pattern</a>:</p>\n\n<pre><code>for (i=0; i&lt;5; i++)\n{\n switch(i)\n {\n case 0:\n // something\n break;\n case 1:\n // something else\n break;\n // etc...\n }\n}\n</code></pre>\n\n<p>I've seen this in real code.</p>\n" }, { "answer_id": 156681, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 4, "selected": true, "text": "<p>@xtofl,</p>\n\n<p>I agree with your concern. </p>\n\n<p>Million times I encountered similar problem. </p>\n\n<p>Either developer adds special handling for first or for last element.</p>\n\n<p>In most cases it is worth to just loop from <strong>startIdx + 1</strong> or to <strong>endIdx - 1</strong> element or even split one long loop into multiple shorter loops. </p>\n\n<p>In a very rare cases it's not possible to split loop.</p>\n\n<p>In my opinion <em>uncommon</em> things should be handled outside of the loop whenever possible.</p>\n" }, { "answer_id": 156773, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 5, "selected": false, "text": "<p>I don't think this question should be answered by a principle (e.g. \"in a loop, treat every element equally\"). Instead, you can look at two factors to evaluate if an implementation is good or bad:</p>\n\n<ol>\n<li>Runtime effectivity - does the compiled code run fast, or would it be faster doing it differently?</li>\n<li>Code maintainability - Is it easy (for another developer) to understand what is happening here? </li>\n</ol>\n\n<p>If it is faster and the code is more readable by doing everything in one loop, do it that way. If it is slower and less readable, do it another way. </p>\n\n<p>If it is faster and less readably, or slower but more readable, find out which of the factors matters more in your specific case, and then decide how to loop (or not to loop).</p>\n" }, { "answer_id": 156790, "author": "Swanand", "author_id": 18768, "author_profile": "https://Stackoverflow.com/users/18768", "pm_score": 3, "selected": false, "text": "<p>In the last snippet you posted, you are repeating code for // .... do stuff.</p>\n\n<p>It makes sense of keeping 2 loops when you have completely different set of operations on a different set of indices.</p>\n\n<pre><code>i = begin\nmid = ( end - begin ) / 2 //(the middle element)\nwhile ( i != mid ) { \n // ... do stuff\n increment i\n}\n\nwhile ( i != end ) {\n // ... do other stuff\n increment i\n}\n</code></pre>\n\n<p>This not being the case, you would still want to keep one single loop. However fact remains that you still save ( end - begin ) / 2 number of comparisons. So it boils down to whether you want your code to look neat or you want to save some CPU cycles. Call is yours.</p>\n" }, { "answer_id": 156801, "author": "John Ferguson", "author_id": 8312, "author_profile": "https://Stackoverflow.com/users/8312", "pm_score": 1, "selected": false, "text": "<p>The special case should be done outside the loop if it is only to be performed once.</p>\n\n<p>However, there may be an index or some other variable(s) that are just easier to keep inside the loop due to scoping. There may also be a contextual reason for keeping all the operations on the datastructure together inside the loop control structure, though I think that is a weak argument on its own.</p>\n" }, { "answer_id": 156814, "author": "Nrj", "author_id": 11614, "author_profile": "https://Stackoverflow.com/users/11614", "pm_score": 1, "selected": false, "text": "<p>Its just about using it as per need and convenience. There is as such no mentions to treat elements equally and there is certainly no harm clubbing the features which language provides.</p>\n" }, { "answer_id": 156932, "author": "Jonathan C Dickinson", "author_id": 24064, "author_profile": "https://Stackoverflow.com/users/24064", "pm_score": 3, "selected": false, "text": "<p>I think you have it entirely nailed. Most people fall into the trap of including conditional branches in loops, when they could do them outside: which is simply <em>faster</em>.</p>\n\n<p>For example:</p>\n\n<pre><code>if(items == null)\n return null;\n\nStringBuilder result = new StringBuilder();\nif(items.Length != 0)\n{\n result.Append(items[0]); // Special case outside loop.\n for(int i = 1; i &lt; items.Length; i++) // Note: we start at element one.\n {\n result.Append(\";\");\n result.Append(items[i]);\n }\n}\nreturn result.ToString();\n</code></pre>\n\n<p>And the middle case you described is just plain <strong>nasty</strong>. Imagine if that code grows and needs to be refactored into different methods.</p>\n\n<p>Unless you are parsing XML &lt;grin&gt; loops should be kept as simple and concise as possible.</p>\n" }, { "answer_id": 15847571, "author": "Angelin Nadar", "author_id": 412591, "author_profile": "https://Stackoverflow.com/users/412591", "pm_score": 2, "selected": false, "text": "<p>I prefer to simply, exclude the element from the loop\nand give a spearate treatment outside the loop</p>\n\n<p><strong>For eg: Lets consider the case of EOF</strong> </p>\n\n<pre><code>i = begin\nwhile ( i != end -1 ) { \n // ... do stuff for element from begn to second last element\n increment i\n}\n\nif(given_array(end -1) != ''){\n // do stuff for the EOF element in the array\n}\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6610/" ]
When reviewing, I sometimes encounter this kind of loop: ``` i = begin while ( i != end ) { // ... do stuff if ( i == end-1 (the one-but-last element) ) { ... do other stuff } increment i } ``` Then I ask the question: would you write this? ``` i = begin mid = ( end - begin ) / 2 // (the middle element) while ( i != end ) { // ... do stuff if ( i > mid ) { ... do other stuff } increment i } ``` In my opinion, this beats the intention of writing a loop: you loop because there is something common to be done for each of the elements. Using this construct, for some of the elements you do something different. So, I conclude, you need a separate loop for those elements: ``` i = begin mid = ( end - begin ) / 2 //(the middle element) while ( i != mid ) { // ... do stuff increment i } while ( i != end ) { // ... do stuff // ... do other stuff increment i } ``` Now I even saw a [question](https://stackoverflow.com/questions/151046/c-last-loop-iteration-stl-map-iterator) on SO on how to write the `if`-clause in a nice way... And I got sad: something isn't right here. Am I wrong? If so, what's so good about cluttering the loop body with special cases, which you are aware of upfront, at coding time?
@xtofl, I agree with your concern. Million times I encountered similar problem. Either developer adds special handling for first or for last element. In most cases it is worth to just loop from **startIdx + 1** or to **endIdx - 1** element or even split one long loop into multiple shorter loops. In a very rare cases it's not possible to split loop. In my opinion *uncommon* things should be handled outside of the loop whenever possible.
156,683
<p>I would like to know what of the many XSLT engines out there works well with Perl.</p> <p>I will use Apache (2.0) and Perl, and I want to obtain PDFs and XHTMLs.</p> <p>I'm new to this kind of projects so any comment or suggestion will be welcome.</p> <p>Thanks.</p> <hr> <p>Doing a simple search on Google I found a lot and I suppose that there are to many more.</p> <ul> <li><a href="http://www.mod-xslt2.com/" rel="noreferrer">http://www.mod-xslt2.com/</a></li> <li><a href="http://xml.apache.org/xalan-j/" rel="noreferrer">http://xml.apache.org/xalan-j/</a></li> <li><a href="http://saxon.sourceforge.net/" rel="noreferrer">http://saxon.sourceforge.net/</a></li> <li><a href="http://www.dopscripts.com/xslt_parser.html" rel="noreferrer">http://www.dopscripts.com/xslt_parser.html</a></li> </ul> <p>Any comment on your experiences will be welcome.</p>
[ { "answer_id": 156692, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>Can't really say which is the best solution because I didn't have a chance to try them all.<br>\nBut I can recommend you to try Perl module <a href=\"http://search.cpan.org/~pajas/XML-LibXSLT-1.66/LibXSLT.pm\" rel=\"nofollow noreferrer\">LibXSLT</a>.<br>\nIt's an interface to the gnome libxslt library. I used it on one of my recent project was satisfied with it.</p>\n" }, { "answer_id": 156717, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 2, "selected": false, "text": "<p>So far I'm very satisfied with <a href=\"http://search.cpan.org/perldoc?XML::LibXML\" rel=\"nofollow noreferrer\">XML::LibXML</a> for non-xslt tasks, and its documentation points to <a href=\"http://search.cpan.org/perldoc?XML::LibXSLT\" rel=\"nofollow noreferrer\">XML::LibXSLT</a>, which looks quite nice, but I have no experience with it so far</p>\n" }, { "answer_id": 156870, "author": "Penfold", "author_id": 11952, "author_profile": "https://Stackoverflow.com/users/11952", "pm_score": 6, "selected": true, "text": "<p>First mistake - <a href=\"http://search.cpan.org/search?query=XSLT&amp;mode=all\" rel=\"nofollow noreferrer\">search on CPAN</a>, not Google :)</p>\n\n<p>This throws up a bunch of results, but does rather highlight the problem of CPAN, that there's more than one solution, and it's not always clear which ones work, have been abandoned, are broken, slow or whatever.</p>\n\n<p>And disturbingly, the best answer (or at least, one of the best) comes up on page <strong>four</strong> of the results :( As other folks have suggested, <a href=\"http://search.cpan.org/dist/XML-LibXSLT/\" rel=\"nofollow noreferrer\">XML::LibXSLT</a> is robust and does the job:</p>\n\n<pre><code> use XML::LibXSLT;\n use XML::LibXML;\n\n my $parser = XML::LibXML-&gt;new();\n my $xslt = XML::LibXSLT-&gt;new();\n\n my $source = $parser-&gt;parse_file('foo.xml');\n my $style_doc = $parser-&gt;parse_file('bar.xsl');\n\n my $stylesheet = $xslt-&gt;parse_stylesheet($style_doc);\n\n my $results = $stylesheet-&gt;transform($source);\n\n print $stylesheet-&gt;output_string($results);\n</code></pre>\n\n<p>If you want to output results to a file then add this</p>\n\n<pre><code>#create output file\nopen(my $output_xml_file_name, '&gt;', 'test.xml');\nprint $output_xml_file_name \"$results\";\n</code></pre>\n\n<p>If you don't want to do anything fancy, though, there's <a href=\"http://search.cpan.org/dist/XML-LibXSLT-Easy/\" rel=\"nofollow noreferrer\">XML::LibXSLT::Easy</a>, which essentially just wraps the above in one method call (and does a bunch of clever stuff behind the scenes using <a href=\"http://search.cpan.org/dist/Moose/\" rel=\"nofollow noreferrer\">Moose</a>. Check the source for an education!).</p>\n\n<pre><code> use XML::LibXSLT::Easy;\n\n my $p = XML::LibXSLT::Easy-&gt;new;\n\n my $output = $p-&gt;process( xml =&gt; \"foo.xml\", xsl =&gt; \"foo.xsl\" );\n</code></pre>\n" }, { "answer_id": 157281, "author": "derby", "author_id": 11790, "author_profile": "https://Stackoverflow.com/users/11790", "pm_score": 0, "selected": false, "text": "<p>You don't say what OS but for most *nix platforms, <a href=\"http://search.cpan.org/perldoc?XML::LibXSLT\" rel=\"nofollow noreferrer\">XML::LibXML</a> is going to be the easiest to use and install.</p>\n" }, { "answer_id": 44009299, "author": "Paul Sweatte", "author_id": 1113772, "author_profile": "https://Stackoverflow.com/users/1113772", "pm_score": 0, "selected": false, "text": "<p>Here are a few Perl libraries intended to replace XSLT:</p>\n\n<ul>\n<li><a href=\"http://search.cpan.org/perldoc?XML%3A%3AXPathScript\" rel=\"nofollow noreferrer\">XPathScript</a></li>\n<li><a href=\"http://search.cpan.org/~dakkar/Tree-Transform-XSLTish-0.3/lib/Tree/Transform/XSLTish.pm\" rel=\"nofollow noreferrer\">XSLTish</a></li>\n<li><a href=\"https://metacpan.org/pod/XML::XSH2\" rel=\"nofollow noreferrer\">XSH2</a></li>\n</ul>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19689/" ]
I would like to know what of the many XSLT engines out there works well with Perl. I will use Apache (2.0) and Perl, and I want to obtain PDFs and XHTMLs. I'm new to this kind of projects so any comment or suggestion will be welcome. Thanks. --- Doing a simple search on Google I found a lot and I suppose that there are to many more. * <http://www.mod-xslt2.com/> * <http://xml.apache.org/xalan-j/> * <http://saxon.sourceforge.net/> * <http://www.dopscripts.com/xslt_parser.html> Any comment on your experiences will be welcome.
First mistake - [search on CPAN](http://search.cpan.org/search?query=XSLT&mode=all), not Google :) This throws up a bunch of results, but does rather highlight the problem of CPAN, that there's more than one solution, and it's not always clear which ones work, have been abandoned, are broken, slow or whatever. And disturbingly, the best answer (or at least, one of the best) comes up on page **four** of the results :( As other folks have suggested, [XML::LibXSLT](http://search.cpan.org/dist/XML-LibXSLT/) is robust and does the job: ``` use XML::LibXSLT; use XML::LibXML; my $parser = XML::LibXML->new(); my $xslt = XML::LibXSLT->new(); my $source = $parser->parse_file('foo.xml'); my $style_doc = $parser->parse_file('bar.xsl'); my $stylesheet = $xslt->parse_stylesheet($style_doc); my $results = $stylesheet->transform($source); print $stylesheet->output_string($results); ``` If you want to output results to a file then add this ``` #create output file open(my $output_xml_file_name, '>', 'test.xml'); print $output_xml_file_name "$results"; ``` If you don't want to do anything fancy, though, there's [XML::LibXSLT::Easy](http://search.cpan.org/dist/XML-LibXSLT-Easy/), which essentially just wraps the above in one method call (and does a bunch of clever stuff behind the scenes using [Moose](http://search.cpan.org/dist/Moose/). Check the source for an education!). ``` use XML::LibXSLT::Easy; my $p = XML::LibXSLT::Easy->new; my $output = $p->process( xml => "foo.xml", xsl => "foo.xsl" ); ```
156,686
<p>How do I initialize an automatic download of a file in Internet Explorer?</p> <p>For example, in the download page, I want the download link to appear and a message: "If you download doesn't start automatically .... etc". The download should begin shortly after the page loads.</p> <p>In Firefox this is easy, you just need to include a meta tag in the header, <code>&lt;meta http-equiv="Refresh" content="n;url"&gt;</code> where n is the number of seconds and <code>url</code> is the download URL. This does not work in Internet Explorer. How do I make this work in Internet Explorer browsers?</p>
[ { "answer_id": 156703, "author": "ullmark", "author_id": 23044, "author_profile": "https://Stackoverflow.com/users/23044", "pm_score": 5, "selected": false, "text": "<p>I recently solved it by placing the following script on the page. </p>\n\n<pre><code>setTimeout(function () { window.location = 'my download url'; }, 5000)\n</code></pre>\n\n<p>I agree that a meta-refresh would be nicer but if it doesn't work what do you do...</p>\n" }, { "answer_id": 156715, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 8, "selected": true, "text": "<p><a href=\"http://en.wikipedia.org/wiki/SourceForge\" rel=\"noreferrer\">SourceForge</a> uses an <code>&lt;iframe&gt;</code> element with the <code>src=\"\"</code> attribute pointing to the file to download.</p>\n\n<pre><code>&lt;iframe width=\"1\" height=\"1\" frameborder=\"0\" src=\"[File location]\"&gt;&lt;/iframe&gt;\n</code></pre>\n\n<p>(Side effect: no redirect, no JavaScript, original URL remains unchanged.)</p>\n" }, { "answer_id": 168152, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 2, "selected": false, "text": "<p>Be sure to serve up the file <strong>without</strong> a no-cache header! IE has issues with this, if user tries to \"open\" the download without saving first.</p>\n" }, { "answer_id": 300517, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 6, "selected": false, "text": "<p>I <em>hate</em> when sites complicate download so much and <a href=\"http://adactio.com/journal/6022/\" rel=\"noreferrer\">use hacks instead of a good old link</a>.</p>\n\n<h3>Dead simple version:</h3>\n\n<pre><code>&lt;a href=\"file.zip\"&gt;Start automatic download!&lt;/a&gt;\n</code></pre>\n\n<p>It works! In every browser!</p>\n\n<hr>\n\n<p>If you want to download a file that is usually displayed inline (such as an image) then HTML5 has a <code>download</code> attribute that forces download of the file. It also allows you to override filename (<a href=\"https://stackoverflow.com/a/216777/27009\">although there is a better way to do it</a>):</p>\n\n<pre><code>&lt;a href=\"report-generator.php\" download=\"result.xls\"&gt;Download&lt;/a&gt;\n</code></pre>\n\n<h3>Version with a \"thanks\" page:</h3>\n\n<p>If you want to display \"thanks\" after download, then use:</p>\n\n<pre><code>&lt;a href=\"file.zip\" \n onclick=\"if (event.button==0) \n setTimeout(function(){document.body.innerHTML='thanks!'},500)\"&gt;\n Start automatic download!\n&lt;/a&gt;\n</code></pre>\n\n<p>Function in that <code>setTimeout</code> might be more advanced and e.g. download full page via AJAX (but don't navigate away from the page — don't touch <code>window.location</code> or activate other links). </p>\n\n<p>The point is that link to download is real, can be copied, dragged, intercepted by download accelerators, gets <code>:visited</code> color, doesn't re-download if page is left open after browser restart, etc.</p>\n\n<p><a href=\"https://imageoptim.com\" rel=\"noreferrer\">That's what I use for ImageOptim</a></p>\n" }, { "answer_id": 3165255, "author": "Dan", "author_id": 230, "author_profile": "https://Stackoverflow.com/users/230", "pm_score": 1, "selected": false, "text": "<p>This seemed to work for me - across all browsers.</p>\n\n<pre><code> &lt;script type=\"text/javascript\"&gt;\n window.onload = function(){\n document.location = 'somefile.zip';\n }\n &lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 6475941, "author": "CameronK", "author_id": 815019, "author_profile": "https://Stackoverflow.com/users/815019", "pm_score": 3, "selected": false, "text": "<p>A simple bit of jQuery solved this problem for me.</p>\n\n<pre><code>$(function() {\n $(window).bind('load', function() {\n $(\"div.downloadProject\").delay(1500).append('&lt;iframe width=\"0\" height=\"0\" frameborder=\"0\" src=\"[YOUR FILE SRC]\"&gt;&lt;/iframe&gt;'); \n });\n});\n</code></pre>\n\n<p>In my HTML, I simply have</p>\n\n<pre><code>&lt;div class=\"downloadProject\"&gt;&lt;/div&gt;\n</code></pre>\n\n<p>All this does is wait a second and a half, then append the div with the iframe referring to the file that you want to download. When the iframe is updated onto the page, your browser downloads the file. Simple as that. :D</p>\n" }, { "answer_id": 8768260, "author": "raheel", "author_id": 1135710, "author_profile": "https://Stackoverflow.com/users/1135710", "pm_score": 1, "selected": false, "text": "<p>I think this will work for you. But visitors are easy if they got something in seconds without spending more time and hence they will also again visit your site.</p>\n<pre><code>&lt;a href=&quot;file.zip&quot; \n onclick=&quot;if (event.button==0) \n setTimeout(function(){document.body.innerHTML='thanks!'},500)&quot;&gt;\n Start automatic download!\n&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 9606541, "author": "kikito", "author_id": 312586, "author_profile": "https://Stackoverflow.com/users/312586", "pm_score": 5, "selected": false, "text": "<p>I had a similar issue and none of the above solutions worked for me. Here's my try (requires jquery):</p>\n\n<pre><code>$(function() {\n $('a[data-auto-download]').each(function(){\n var $this = $(this);\n setTimeout(function() {\n window.location = $this.attr('href');\n }, 2000);\n });\n});\n</code></pre>\n\n<p>Usage: Just add an attribute called <code>data-auto-download</code> to the link pointing to the download in question:</p>\n\n<pre><code>&lt;p&gt;The download should start shortly. If it doesn't, click\n&lt;a data-auto-download href=\"/your/file/url\"&gt;here&lt;/a&gt;.&lt;/p&gt;\n</code></pre>\n\n<p>It should work in all cases.</p>\n" }, { "answer_id": 11061162, "author": "Vandana", "author_id": 1250541, "author_profile": "https://Stackoverflow.com/users/1250541", "pm_score": 2, "selected": false, "text": "<p>I checked and found, it will work on button click via writing onclick event to Anchor tag or Input button</p>\n\n<pre><code>onclick='javascript:setTimeout(window.location=[File location], 1000);'\n</code></pre>\n" }, { "answer_id": 12718947, "author": "Tyler", "author_id": 539300, "author_profile": "https://Stackoverflow.com/users/539300", "pm_score": 3, "selected": false, "text": "<p>I used this, seems working and is just simple JS, no framework:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>Your file should start downloading in a few seconds. \nIf downloading doesn't start automatically\n&lt;a id=\"downloadLink\" href=\"[link to your file]\"&gt;click here to get your file&lt;/a&gt;.\n\n&lt;script&gt; \n var downloadTimeout = setTimeout(function () {\n window.location = document.getElementById('downloadLink').href;\n }, 2000);\n&lt;/script&gt;\n</code></pre>\n\n<p><strong>NOTE: this starts the timeout in the moment the page is loaded.</strong></p>\n" }, { "answer_id": 14565569, "author": "Rabi", "author_id": 438466, "author_profile": "https://Stackoverflow.com/users/438466", "pm_score": 3, "selected": false, "text": "<p>This is what I'm using in some sites (requires jQuery).:</p>\n\n<pre><code>$(document).ready(function() {\n var downloadUrl = \"your_file_url\";\n setTimeout(\"window.location.assign('\" + downloadUrl + \"');\", 1000);\n});\n</code></pre>\n\n<p>The file is downloaded automatically after 1 second.</p>\n" }, { "answer_id": 31279235, "author": "Nelu", "author_id": 1678614, "author_profile": "https://Stackoverflow.com/users/1678614", "pm_score": 1, "selected": false, "text": "<p>For those trying to trigger the download using a <strong>dynamic link</strong> it's tricky to get it working consistently across browsers. </p>\n\n<p>I had trouble in IE10+ downloading a PDF and used <a href=\"https://stackoverflow.com/questions/25121384/ie-download-file#comment39311404_25121384\">@dandavis'</a> <code>download</code> function (<a href=\"https://github.com/rndme/download\" rel=\"nofollow noreferrer\">https://github.com/rndme/download</a>).</p>\n\n<p>IE10+ needs <code>msSaveBlob</code>.</p>\n" }, { "answer_id": 34792341, "author": "Tom", "author_id": 2639688, "author_profile": "https://Stackoverflow.com/users/2639688", "pm_score": 2, "selected": false, "text": "<p>Back to the roots, i use this:</p>\n\n<pre><code>&lt;meta http-equiv=\"refresh\" content=\"0; url=YOURFILEURL\"/&gt;\n</code></pre>\n\n<p>Maybe not WC3 conform but works perfect on all browsers, no HTML5/JQUERY/Javascript.</p>\n\n<p>Greetings Tom :)</p>\n" }, { "answer_id": 36916680, "author": "EL missaoui habib", "author_id": 5039444, "author_profile": "https://Stackoverflow.com/users/5039444", "pm_score": 3, "selected": false, "text": "<p>Works on Chrome, firefox and IE8 and above:</p>\n\n<pre><code>var link = document.createElement('a');\ndocument.body.appendChild(link);\nlink.href = url;\nlink.click();\n</code></pre>\n" }, { "answer_id": 45430686, "author": "M. Lak", "author_id": 7250759, "author_profile": "https://Stackoverflow.com/users/7250759", "pm_score": 2, "selected": false, "text": "<p>I hope this will works all the browsers. You can also set the auto download timing.</p>\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n&lt;title&gt;Start Auto Download file&lt;/title&gt;\n&lt;script src=&quot;http://code.jquery.com/jquery-3.2.1.min.js&quot;&gt;&lt;/script&gt;\n&lt;script&gt;\n$(function() {\n$('a[data-auto-download]').each(function(){\nvar $this = $(this);\nsetTimeout(function() {\nwindow.location = $this.attr('href');\n}, 2000);\n});\n});\n&lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;div class=&quot;wrapper&quot;&gt;\n&lt;p&gt;The download should start shortly. If it doesn't, click\n&lt;a data-auto-download href=&quot;auto-download.zip&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;\n&lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 54759844, "author": "Somerussian", "author_id": 4472596, "author_profile": "https://Stackoverflow.com/users/4472596", "pm_score": 0, "selected": false, "text": "<p>Nice jquery solution:</p>\n\n<pre><code>jQuery('a.auto-start').get(0).click();\n</code></pre>\n\n<p>You can even set different file name for download inside <code>&lt;a&gt;</code> tag:</p>\n\n<pre><code>Your download should start shortly. If not - you can use\n&lt;a href=\"/attachments-31-3d4c8970.zip\" download=\"attachments-31.zip\" class=\"download auto-start\"&gt;direct link&lt;/a&gt;.\n</code></pre>\n" }, { "answer_id": 55686024, "author": "ZettaCircl", "author_id": 11094914, "author_profile": "https://Stackoverflow.com/users/11094914", "pm_score": 2, "selected": false, "text": "<p>One more : </p>\n\n<pre><code>var a = document.createElement('a');\na.setAttribute('href', dataUri);\na.setAttribute('download', filename);\n\nvar aj = $(a);\naj.appendTo('body');\naj[0].click();\naj.remove();\n</code></pre>\n" }, { "answer_id": 62286353, "author": "Benjamin Moser", "author_id": 13535592, "author_profile": "https://Stackoverflow.com/users/13535592", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;meta http-equiv=\"Refresh\" content=\"n;url\"&gt;\n</code></pre>\n\n<p>That's It. Easy, Right?</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;meta http-equiv=\"Refresh\" content=\"n;url\"&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 74417385, "author": "lator", "author_id": 16792256, "author_profile": "https://Stackoverflow.com/users/16792256", "pm_score": 0, "selected": false, "text": "<p>This is an old question but in case anyone wants to use automatic download of files with Flask, Python. You can do this:</p>\n<pre><code>from flask import Flask, make_response, send_from_directory\n\nfile_path = &quot;Path containing the file&quot; #e.g Uploads/images\n\[email protected](&quot;/download/&lt;file_name&gt;&quot;)\ndef download_file(file_name):\n resp = make_response(send_from_directory(file_path, file_name)\n resp.headers['Content-Disposition'] = f&quot;attachment; filename={file_name}&quot;\n return resp\n</code></pre>\n<p>Inside a template or html page, index for example</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div&gt;\n &lt;a class=\"btn btn-outline-warning\" href={{url_for( 'download_file', name='image.png' )}} \"&gt;Download Image&lt;/a&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Clicking on the link will download the file without opening another page.\nFor more info on:</p>\n<ul>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition\" rel=\"nofollow noreferrer\">Content-Disposition</a></li>\n<li><a href=\"https://stackoverflow.com/a/40211663/16792256\">Setting request headers in Flask</a></li>\n</ul>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4685/" ]
How do I initialize an automatic download of a file in Internet Explorer? For example, in the download page, I want the download link to appear and a message: "If you download doesn't start automatically .... etc". The download should begin shortly after the page loads. In Firefox this is easy, you just need to include a meta tag in the header, `<meta http-equiv="Refresh" content="n;url">` where n is the number of seconds and `url` is the download URL. This does not work in Internet Explorer. How do I make this work in Internet Explorer browsers?
[SourceForge](http://en.wikipedia.org/wiki/SourceForge) uses an `<iframe>` element with the `src=""` attribute pointing to the file to download. ``` <iframe width="1" height="1" frameborder="0" src="[File location]"></iframe> ``` (Side effect: no redirect, no JavaScript, original URL remains unchanged.)
156,688
<p>I have an error occuring frequently from our community server installation whenever the googlesitemap.ashx is traversed on a specific sectionID. I suspect that a username has been amended but the posts havn't recached to reflect this.</p> <p>Is there a way a can check the data integruity by performing a select statement on the database, alternatively is there a way to force the database to recache? </p>
[ { "answer_id": 156703, "author": "ullmark", "author_id": 23044, "author_profile": "https://Stackoverflow.com/users/23044", "pm_score": 5, "selected": false, "text": "<p>I recently solved it by placing the following script on the page. </p>\n\n<pre><code>setTimeout(function () { window.location = 'my download url'; }, 5000)\n</code></pre>\n\n<p>I agree that a meta-refresh would be nicer but if it doesn't work what do you do...</p>\n" }, { "answer_id": 156715, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 8, "selected": true, "text": "<p><a href=\"http://en.wikipedia.org/wiki/SourceForge\" rel=\"noreferrer\">SourceForge</a> uses an <code>&lt;iframe&gt;</code> element with the <code>src=\"\"</code> attribute pointing to the file to download.</p>\n\n<pre><code>&lt;iframe width=\"1\" height=\"1\" frameborder=\"0\" src=\"[File location]\"&gt;&lt;/iframe&gt;\n</code></pre>\n\n<p>(Side effect: no redirect, no JavaScript, original URL remains unchanged.)</p>\n" }, { "answer_id": 168152, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 2, "selected": false, "text": "<p>Be sure to serve up the file <strong>without</strong> a no-cache header! IE has issues with this, if user tries to \"open\" the download without saving first.</p>\n" }, { "answer_id": 300517, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 6, "selected": false, "text": "<p>I <em>hate</em> when sites complicate download so much and <a href=\"http://adactio.com/journal/6022/\" rel=\"noreferrer\">use hacks instead of a good old link</a>.</p>\n\n<h3>Dead simple version:</h3>\n\n<pre><code>&lt;a href=\"file.zip\"&gt;Start automatic download!&lt;/a&gt;\n</code></pre>\n\n<p>It works! In every browser!</p>\n\n<hr>\n\n<p>If you want to download a file that is usually displayed inline (such as an image) then HTML5 has a <code>download</code> attribute that forces download of the file. It also allows you to override filename (<a href=\"https://stackoverflow.com/a/216777/27009\">although there is a better way to do it</a>):</p>\n\n<pre><code>&lt;a href=\"report-generator.php\" download=\"result.xls\"&gt;Download&lt;/a&gt;\n</code></pre>\n\n<h3>Version with a \"thanks\" page:</h3>\n\n<p>If you want to display \"thanks\" after download, then use:</p>\n\n<pre><code>&lt;a href=\"file.zip\" \n onclick=\"if (event.button==0) \n setTimeout(function(){document.body.innerHTML='thanks!'},500)\"&gt;\n Start automatic download!\n&lt;/a&gt;\n</code></pre>\n\n<p>Function in that <code>setTimeout</code> might be more advanced and e.g. download full page via AJAX (but don't navigate away from the page — don't touch <code>window.location</code> or activate other links). </p>\n\n<p>The point is that link to download is real, can be copied, dragged, intercepted by download accelerators, gets <code>:visited</code> color, doesn't re-download if page is left open after browser restart, etc.</p>\n\n<p><a href=\"https://imageoptim.com\" rel=\"noreferrer\">That's what I use for ImageOptim</a></p>\n" }, { "answer_id": 3165255, "author": "Dan", "author_id": 230, "author_profile": "https://Stackoverflow.com/users/230", "pm_score": 1, "selected": false, "text": "<p>This seemed to work for me - across all browsers.</p>\n\n<pre><code> &lt;script type=\"text/javascript\"&gt;\n window.onload = function(){\n document.location = 'somefile.zip';\n }\n &lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 6475941, "author": "CameronK", "author_id": 815019, "author_profile": "https://Stackoverflow.com/users/815019", "pm_score": 3, "selected": false, "text": "<p>A simple bit of jQuery solved this problem for me.</p>\n\n<pre><code>$(function() {\n $(window).bind('load', function() {\n $(\"div.downloadProject\").delay(1500).append('&lt;iframe width=\"0\" height=\"0\" frameborder=\"0\" src=\"[YOUR FILE SRC]\"&gt;&lt;/iframe&gt;'); \n });\n});\n</code></pre>\n\n<p>In my HTML, I simply have</p>\n\n<pre><code>&lt;div class=\"downloadProject\"&gt;&lt;/div&gt;\n</code></pre>\n\n<p>All this does is wait a second and a half, then append the div with the iframe referring to the file that you want to download. When the iframe is updated onto the page, your browser downloads the file. Simple as that. :D</p>\n" }, { "answer_id": 8768260, "author": "raheel", "author_id": 1135710, "author_profile": "https://Stackoverflow.com/users/1135710", "pm_score": 1, "selected": false, "text": "<p>I think this will work for you. But visitors are easy if they got something in seconds without spending more time and hence they will also again visit your site.</p>\n<pre><code>&lt;a href=&quot;file.zip&quot; \n onclick=&quot;if (event.button==0) \n setTimeout(function(){document.body.innerHTML='thanks!'},500)&quot;&gt;\n Start automatic download!\n&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 9606541, "author": "kikito", "author_id": 312586, "author_profile": "https://Stackoverflow.com/users/312586", "pm_score": 5, "selected": false, "text": "<p>I had a similar issue and none of the above solutions worked for me. Here's my try (requires jquery):</p>\n\n<pre><code>$(function() {\n $('a[data-auto-download]').each(function(){\n var $this = $(this);\n setTimeout(function() {\n window.location = $this.attr('href');\n }, 2000);\n });\n});\n</code></pre>\n\n<p>Usage: Just add an attribute called <code>data-auto-download</code> to the link pointing to the download in question:</p>\n\n<pre><code>&lt;p&gt;The download should start shortly. If it doesn't, click\n&lt;a data-auto-download href=\"/your/file/url\"&gt;here&lt;/a&gt;.&lt;/p&gt;\n</code></pre>\n\n<p>It should work in all cases.</p>\n" }, { "answer_id": 11061162, "author": "Vandana", "author_id": 1250541, "author_profile": "https://Stackoverflow.com/users/1250541", "pm_score": 2, "selected": false, "text": "<p>I checked and found, it will work on button click via writing onclick event to Anchor tag or Input button</p>\n\n<pre><code>onclick='javascript:setTimeout(window.location=[File location], 1000);'\n</code></pre>\n" }, { "answer_id": 12718947, "author": "Tyler", "author_id": 539300, "author_profile": "https://Stackoverflow.com/users/539300", "pm_score": 3, "selected": false, "text": "<p>I used this, seems working and is just simple JS, no framework:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>Your file should start downloading in a few seconds. \nIf downloading doesn't start automatically\n&lt;a id=\"downloadLink\" href=\"[link to your file]\"&gt;click here to get your file&lt;/a&gt;.\n\n&lt;script&gt; \n var downloadTimeout = setTimeout(function () {\n window.location = document.getElementById('downloadLink').href;\n }, 2000);\n&lt;/script&gt;\n</code></pre>\n\n<p><strong>NOTE: this starts the timeout in the moment the page is loaded.</strong></p>\n" }, { "answer_id": 14565569, "author": "Rabi", "author_id": 438466, "author_profile": "https://Stackoverflow.com/users/438466", "pm_score": 3, "selected": false, "text": "<p>This is what I'm using in some sites (requires jQuery).:</p>\n\n<pre><code>$(document).ready(function() {\n var downloadUrl = \"your_file_url\";\n setTimeout(\"window.location.assign('\" + downloadUrl + \"');\", 1000);\n});\n</code></pre>\n\n<p>The file is downloaded automatically after 1 second.</p>\n" }, { "answer_id": 31279235, "author": "Nelu", "author_id": 1678614, "author_profile": "https://Stackoverflow.com/users/1678614", "pm_score": 1, "selected": false, "text": "<p>For those trying to trigger the download using a <strong>dynamic link</strong> it's tricky to get it working consistently across browsers. </p>\n\n<p>I had trouble in IE10+ downloading a PDF and used <a href=\"https://stackoverflow.com/questions/25121384/ie-download-file#comment39311404_25121384\">@dandavis'</a> <code>download</code> function (<a href=\"https://github.com/rndme/download\" rel=\"nofollow noreferrer\">https://github.com/rndme/download</a>).</p>\n\n<p>IE10+ needs <code>msSaveBlob</code>.</p>\n" }, { "answer_id": 34792341, "author": "Tom", "author_id": 2639688, "author_profile": "https://Stackoverflow.com/users/2639688", "pm_score": 2, "selected": false, "text": "<p>Back to the roots, i use this:</p>\n\n<pre><code>&lt;meta http-equiv=\"refresh\" content=\"0; url=YOURFILEURL\"/&gt;\n</code></pre>\n\n<p>Maybe not WC3 conform but works perfect on all browsers, no HTML5/JQUERY/Javascript.</p>\n\n<p>Greetings Tom :)</p>\n" }, { "answer_id": 36916680, "author": "EL missaoui habib", "author_id": 5039444, "author_profile": "https://Stackoverflow.com/users/5039444", "pm_score": 3, "selected": false, "text": "<p>Works on Chrome, firefox and IE8 and above:</p>\n\n<pre><code>var link = document.createElement('a');\ndocument.body.appendChild(link);\nlink.href = url;\nlink.click();\n</code></pre>\n" }, { "answer_id": 45430686, "author": "M. Lak", "author_id": 7250759, "author_profile": "https://Stackoverflow.com/users/7250759", "pm_score": 2, "selected": false, "text": "<p>I hope this will works all the browsers. You can also set the auto download timing.</p>\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n&lt;title&gt;Start Auto Download file&lt;/title&gt;\n&lt;script src=&quot;http://code.jquery.com/jquery-3.2.1.min.js&quot;&gt;&lt;/script&gt;\n&lt;script&gt;\n$(function() {\n$('a[data-auto-download]').each(function(){\nvar $this = $(this);\nsetTimeout(function() {\nwindow.location = $this.attr('href');\n}, 2000);\n});\n});\n&lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;div class=&quot;wrapper&quot;&gt;\n&lt;p&gt;The download should start shortly. If it doesn't, click\n&lt;a data-auto-download href=&quot;auto-download.zip&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;\n&lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 54759844, "author": "Somerussian", "author_id": 4472596, "author_profile": "https://Stackoverflow.com/users/4472596", "pm_score": 0, "selected": false, "text": "<p>Nice jquery solution:</p>\n\n<pre><code>jQuery('a.auto-start').get(0).click();\n</code></pre>\n\n<p>You can even set different file name for download inside <code>&lt;a&gt;</code> tag:</p>\n\n<pre><code>Your download should start shortly. If not - you can use\n&lt;a href=\"/attachments-31-3d4c8970.zip\" download=\"attachments-31.zip\" class=\"download auto-start\"&gt;direct link&lt;/a&gt;.\n</code></pre>\n" }, { "answer_id": 55686024, "author": "ZettaCircl", "author_id": 11094914, "author_profile": "https://Stackoverflow.com/users/11094914", "pm_score": 2, "selected": false, "text": "<p>One more : </p>\n\n<pre><code>var a = document.createElement('a');\na.setAttribute('href', dataUri);\na.setAttribute('download', filename);\n\nvar aj = $(a);\naj.appendTo('body');\naj[0].click();\naj.remove();\n</code></pre>\n" }, { "answer_id": 62286353, "author": "Benjamin Moser", "author_id": 13535592, "author_profile": "https://Stackoverflow.com/users/13535592", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;meta http-equiv=\"Refresh\" content=\"n;url\"&gt;\n</code></pre>\n\n<p>That's It. Easy, Right?</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;meta http-equiv=\"Refresh\" content=\"n;url\"&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 74417385, "author": "lator", "author_id": 16792256, "author_profile": "https://Stackoverflow.com/users/16792256", "pm_score": 0, "selected": false, "text": "<p>This is an old question but in case anyone wants to use automatic download of files with Flask, Python. You can do this:</p>\n<pre><code>from flask import Flask, make_response, send_from_directory\n\nfile_path = &quot;Path containing the file&quot; #e.g Uploads/images\n\[email protected](&quot;/download/&lt;file_name&gt;&quot;)\ndef download_file(file_name):\n resp = make_response(send_from_directory(file_path, file_name)\n resp.headers['Content-Disposition'] = f&quot;attachment; filename={file_name}&quot;\n return resp\n</code></pre>\n<p>Inside a template or html page, index for example</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div&gt;\n &lt;a class=\"btn btn-outline-warning\" href={{url_for( 'download_file', name='image.png' )}} \"&gt;Download Image&lt;/a&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Clicking on the link will download the file without opening another page.\nFor more info on:</p>\n<ul>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition\" rel=\"nofollow noreferrer\">Content-Disposition</a></li>\n<li><a href=\"https://stackoverflow.com/a/40211663/16792256\">Setting request headers in Flask</a></li>\n</ul>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5055/" ]
I have an error occuring frequently from our community server installation whenever the googlesitemap.ashx is traversed on a specific sectionID. I suspect that a username has been amended but the posts havn't recached to reflect this. Is there a way a can check the data integruity by performing a select statement on the database, alternatively is there a way to force the database to recache?
[SourceForge](http://en.wikipedia.org/wiki/SourceForge) uses an `<iframe>` element with the `src=""` attribute pointing to the file to download. ``` <iframe width="1" height="1" frameborder="0" src="[File location]"></iframe> ``` (Side effect: no redirect, no JavaScript, original URL remains unchanged.)
156,689
<p>Do you have a common base class for Hibernate entities, i.e. a MappedSuperclass with id, version and other common properties? Are there any drawbacks?</p> <p>Example:</p> <pre><code>@MappedSuperclass() public class BaseEntity { private Long id; private Long version; ... @Id @GeneratedValue(strategy = GenerationType.AUTO) public Long getId() {return id;} public void setId(Long id) {this.id = id;} @Version public Long getVersion() {return version;} ... // Common properties @Temporal(TemporalType.TIMESTAMP) public Date creationDate() {return creationDate;} ... } @Entity public class Customer extends BaseEntity { private String customerName; ... } </code></pre>
[ { "answer_id": 156986, "author": "Peter Hilton", "author_id": 2670, "author_profile": "https://Stackoverflow.com/users/2670", "pm_score": 4, "selected": true, "text": "<p>This works fine for us. As well as the ID and creation date, we also have a modified date. We also have an intermediate <em>TaggedBaseEntity</em> that implements a <em>Taggable</em> interface, because some of our web application's entities have tags, like questions on Stack Overflow.</p>\n" }, { "answer_id": 410827, "author": "Daniel Rikowski", "author_id": 23368, "author_profile": "https://Stackoverflow.com/users/23368", "pm_score": 1, "selected": false, "text": "<p>I wouldn't hesitate to use a common base class, after all that's the point of O/R mapping.</p>\n\n<p>I use common base classes, too, but only if the entities share at least some common properties. I won't use it, if the ID is the only common property. Until now I did not encounter any problems.</p>\n" }, { "answer_id": 414950, "author": "Matt Sidesinger", "author_id": 1481472, "author_profile": "https://Stackoverflow.com/users/1481472", "pm_score": 3, "selected": false, "text": "<p>The one that I use is primarily to implement hashCode() and equals(). I also added a method to pretty print the entity. In response to DR above, most of this can be overridden, but in my implementation you are stuck with an ID of type Long.</p>\n\n<pre><code>public abstract class BaseEntity implements Serializable {\n\n public abstract Long getId();\n public abstract void setId(Long id);\n\n /**\n * @see java.lang.Object#hashCode()\n */\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((getId() == null) ? 0 : getId().hashCode());\n return result;\n }\n\n /**\n * @see java.lang.Object#equals(Object)\n */\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n BaseEntity other = (BaseEntity) obj;\n if (getId() == null) {\n if (other.getId() != null)\n return false;\n } else if (!getId().equals(other.getId()))\n return false;\n return true;\n }\n\n /**\n * @see java.lang.Object#toString()\n */\n @Override\n public String toString() {\n return new StringBuilder(getClass().getSimpleName()).append(\":\").append(getId()).toString();\n }\n\n /**\n * Prints complete information by calling all public getters on the entity.\n */\n public String print() {\n\n final String EQUALS = \"=\";\n final String DELIMITER = \", \";\n final String ENTITY_FORMAT = \"(id={0})\";\n\n StringBuffer sb = new StringBuffer(\"{\");\n\n PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(this);\n PropertyDescriptor property = null;\n int i = 0;\n while ( i &lt; properties.length) {\n\n property = properties[i];\n sb.append(property.getName());\n sb.append(EQUALS);\n\n try {\n Object value = PropertyUtils.getProperty(this, property.getName());\n if (value instanceof BaseEntity) {\n BaseEntity entityValue = (BaseEntity) value;\n String objectValueString = MessageFormat.format(ENTITY_FORMAT, entityValue.getId());\n sb.append(objectValueString);\n } else {\n sb.append(value);\n }\n } catch (IllegalAccessException e) {\n // do nothing\n } catch (InvocationTargetException e) {\n // do nothing\n } catch (NoSuchMethodException e) {\n // do nothing\n }\n\n i++;\n if (i &lt; properties.length) {\n sb.append(DELIMITER);\n }\n }\n\n sb.append(\"}\");\n\n return sb.toString();\n }\n}\n</code></pre>\n" }, { "answer_id": 2065720, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>You can find some samples here</p>\n\n<p><a href=\"http://blogsprajeesh.blogspot.com/2010/01/nhibernate-defining-mappings-part-4.html\" rel=\"nofollow noreferrer\">http://blogsprajeesh.blogspot.com/2010/01/nhibernate-defining-mappings-part-4.html</a></p>\n" }, { "answer_id": 8525339, "author": "Sebastien Lorber", "author_id": 82609, "author_profile": "https://Stackoverflow.com/users/82609", "pm_score": 0, "selected": false, "text": "<p>It works well for me too.</p>\n\n<p>Notice that you can also in this entity add some event listeners / interceptors like the Hibernate Envers one or any custom one according to your need so that you can:\n- Track all modifications\n- Know which user made the last modification\n- Update automatically the last modification\n- Set automatically the first insertion date\nAnd ther stuff like that...</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18722/" ]
Do you have a common base class for Hibernate entities, i.e. a MappedSuperclass with id, version and other common properties? Are there any drawbacks? Example: ``` @MappedSuperclass() public class BaseEntity { private Long id; private Long version; ... @Id @GeneratedValue(strategy = GenerationType.AUTO) public Long getId() {return id;} public void setId(Long id) {this.id = id;} @Version public Long getVersion() {return version;} ... // Common properties @Temporal(TemporalType.TIMESTAMP) public Date creationDate() {return creationDate;} ... } @Entity public class Customer extends BaseEntity { private String customerName; ... } ```
This works fine for us. As well as the ID and creation date, we also have a modified date. We also have an intermediate *TaggedBaseEntity* that implements a *Taggable* interface, because some of our web application's entities have tags, like questions on Stack Overflow.
156,697
<p>In my environment here I use Java to serialize the result set to XML. It happens basically like this:</p> <pre><code>//foreach column of each row xmlHandler.startElement(uri, lname, "column", attributes); String chars = rs.getString(i); xmlHandler.characters(chars.toCharArray(), 0, chars.length()); xmlHandler.endElement(uri, lname, "column"); </code></pre> <p>The XML looks like this in Firefox:</p> <pre><code>&lt;row num="69004"&gt; &lt;column num="1"&gt;10069&lt;/column&gt; &lt;column num="2"&gt;sd&amp;#26;&lt;/column&gt; &lt;column num="3"&gt;FCVolume &lt;/column&gt; &lt;/row&gt; </code></pre> <p>But when I parse the XML I get the a</p> <blockquote> <p>org.xml.sax.SAXParseException: Character reference "<strong>&amp;#26</strong>" is an invalid XML character.</p> </blockquote> <p>My question now is: Which charactes do I have to replace or how do I have to encode my characters, that they will be valid XML?</p>
[ { "answer_id": 156741, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.w3.org/TR/REC-xml/#syntax\" rel=\"nofollow noreferrer\">Extensible Markup Language (XML) 1.0</a> says:</p>\n\n<blockquote>\n <p>The ampersand character (&amp;) and the\n left angle bracket (&lt;) must not appear\n in their literal form, except when\n used as markup delimiters, or within a\n comment, a processing instruction, or\n a CDATA section. If they are needed\n elsewhere, they must be escaped using\n either numeric character references or\n the strings \"&amp;\" and \"&lt;\"\n respectively. The right angle bracket\n (>) may be represented using the\n string \"&gt;\", and must, for\n compatibility, be escaped using either\n \"&gt;\" or a character reference when\n it appears in the string \"]]>\" in\n content, when that string is not\n marking the end of a CDATA section.</p>\n</blockquote>\n\n<p>You can skip the encoding if you use CDATA:</p>\n\n<pre><code>&lt;column num=\"1\"&gt;&lt;![CDATA[10069]]&gt;&lt;/column&gt;\n&lt;column num=\"2\"&gt;&lt;![CDATA[sd&amp;]]&gt;&lt;/column&gt;\n</code></pre>\n" }, { "answer_id": 156744, "author": "Andre Bossard", "author_id": 21027, "author_profile": "https://Stackoverflow.com/users/21027", "pm_score": 4, "selected": true, "text": "<p>I found an interesting list in the <a href=\"http://www.w3.org/TR/2006/REC-xml11-20060816/#charsets\" rel=\"noreferrer\">Xml Spec</a>:\nAccording to that List its discouraged to use the Character #26 (Hex: <em>#x1A</em>).</p>\n\n<blockquote>\n <p>The characters defined in the\n following ranges are also discouraged.\n They are either control characters or\n permanently undefined Unicode\n characters</p>\n</blockquote>\n\n<p>See the <a href=\"http://www.w3.org/TR/2006/REC-xml11-20060816/#charsets\" rel=\"noreferrer\">complete ranges</a>.</p>\n\n<p>This code replaces all non-valid Xml Utf8 from a String:</p>\n\n<pre><code>public String stripNonValidXMLCharacters(String in) {\n StringBuffer out = new StringBuffer(); // Used to hold the output.\n char current; // Used to reference the current character.\n\n if (in == null || (\"\".equals(in))) return \"\"; // vacancy test.\n for (int i = 0; i &lt; in.length(); i++) {\n current = in.charAt(i);\n if ((current == 0x9) ||\n (current == 0xA) ||\n (current == 0xD) ||\n ((current &gt;= 0x20) &amp;&amp; (current &lt;= 0xD7FF)) ||\n ((current &gt;= 0xE000) &amp;&amp; (current &lt;= 0xFFFD)) ||\n ((current &gt;= 0x10000) &amp;&amp; (current &lt;= 0x10FFFF)))\n out.append(current);\n }\n return out.toString();\n} \n</code></pre>\n\n<p>its taken from <a href=\"http://cse-mjmcl.cse.bris.ac.uk/blog/2007/02/14/1171465494443.html\" rel=\"noreferrer\">Invalid XML Characters: when valid UTF8 does not mean valid XML</a></p>\n\n<p>But with that I had the still UTF-8 compatility issue:</p>\n\n<pre><code>org.xml.sax.SAXParseException: Invalid byte 1 of 1-byte UTF-8 sequence\n</code></pre>\n\n<p>After reading <a href=\"http://www.velocityreviews.com/forums/t166758-returning-xml-as-utf8-from-a-servlet.html\" rel=\"noreferrer\">XML - returning XML as UTF-8 from a servlet</a> I just tried out what happens if I set the Contenttype like this:</p>\n\n<pre><code>response.setContentType(\"text/xml;charset=utf-8\");\n</code></pre>\n\n<p>And it worked ....</p>\n" }, { "answer_id": 156829, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 0, "selected": false, "text": "<p>Which version of JRE are you running? <a href=\"http://www.saxproject.org/faq.html\" rel=\"nofollow noreferrer\">Sax Project</a> says: </p>\n\n<blockquote>\n <p>J2SE 1.4 bundles an old version of\n SAX2. How do I make SAX2 r2 or later available?</p>\n</blockquote>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21027/" ]
In my environment here I use Java to serialize the result set to XML. It happens basically like this: ``` //foreach column of each row xmlHandler.startElement(uri, lname, "column", attributes); String chars = rs.getString(i); xmlHandler.characters(chars.toCharArray(), 0, chars.length()); xmlHandler.endElement(uri, lname, "column"); ``` The XML looks like this in Firefox: ``` <row num="69004"> <column num="1">10069</column> <column num="2">sd&#26;</column> <column num="3">FCVolume </column> </row> ``` But when I parse the XML I get the a > > org.xml.sax.SAXParseException: Character reference "**&#26**" is an > invalid XML character. > > > My question now is: Which charactes do I have to replace or how do I have to encode my characters, that they will be valid XML?
I found an interesting list in the [Xml Spec](http://www.w3.org/TR/2006/REC-xml11-20060816/#charsets): According to that List its discouraged to use the Character #26 (Hex: *#x1A*). > > The characters defined in the > following ranges are also discouraged. > They are either control characters or > permanently undefined Unicode > characters > > > See the [complete ranges](http://www.w3.org/TR/2006/REC-xml11-20060816/#charsets). This code replaces all non-valid Xml Utf8 from a String: ``` public String stripNonValidXMLCharacters(String in) { StringBuffer out = new StringBuffer(); // Used to hold the output. char current; // Used to reference the current character. if (in == null || ("".equals(in))) return ""; // vacancy test. for (int i = 0; i < in.length(); i++) { current = in.charAt(i); if ((current == 0x9) || (current == 0xA) || (current == 0xD) || ((current >= 0x20) && (current <= 0xD7FF)) || ((current >= 0xE000) && (current <= 0xFFFD)) || ((current >= 0x10000) && (current <= 0x10FFFF))) out.append(current); } return out.toString(); } ``` its taken from [Invalid XML Characters: when valid UTF8 does not mean valid XML](http://cse-mjmcl.cse.bris.ac.uk/blog/2007/02/14/1171465494443.html) But with that I had the still UTF-8 compatility issue: ``` org.xml.sax.SAXParseException: Invalid byte 1 of 1-byte UTF-8 sequence ``` After reading [XML - returning XML as UTF-8 from a servlet](http://www.velocityreviews.com/forums/t166758-returning-xml-as-utf8-from-a-servlet.html) I just tried out what happens if I set the Contenttype like this: ``` response.setContentType("text/xml;charset=utf-8"); ``` And it worked ....
156,724
<p>I'm having a problem with my Seam code and I can't seem to figure out what I'm doing wrong. It's doing my head in :) Here's an excerpt of the stack trace:</p> <pre><code>Caused by: java.lang.IllegalArgumentException: Can not set java.lang.Long field com.oobjects.sso.manager.home.PresenceHome.customerId to java.lang.String </code></pre> <p>I'm trying to get a parameter set on my URL passed into one of my beans. To do this, I've got the following set up in my pages.xml:</p> <pre><code>&lt;page view-id="/customer/presences.xhtml"&gt; &lt;begin-conversation flush-mode="MANUAL" join="true" /&gt; &lt;param name="customerId" value="#{presenceHome.customerId}" /&gt; &lt;raise-event type="PresenceHome.init" /&gt; &lt;navigation&gt; &lt;rule if-outcome="persisted"&gt; &lt;end-conversation /&gt; &lt;redirect view-id="/customer/presences.xhtml" /&gt; &lt;/rule&gt; &lt;/navigation&gt; &lt;/page&gt; </code></pre> <p>My bean starts like this:</p> <pre><code>@Name("presenceHome") @Scope(ScopeType.CONVERSATION) public class PresenceHome extends EntityHome&lt;Presence&gt; implements Serializable { @In private CustomerDao customerDao; @In(required = false) private Long presenceId; @In(required = false) private Long customerId; private Customer customer; // Getters, setters and other methods follow. They return the correct types defined above } </code></pre> <p>Finally the link I use to link one one page to the next looks like this:</p> <pre><code>&lt;s:link styleClass="#{selected == 'presences' ? 'selected' : ''}" view="/customer/presences.xhtml" title="Presences" propagation="none"&gt; &lt;f:param name="customerId" value="#{customerId}" /&gt; Presences &lt;/s:link&gt; </code></pre> <p>All this seems to work fine. When I hover over the link above in my page, I get a URL ending in something like "?customerId=123". So the parameter is being passed over and it's something that can be easily converted into a Long type. But for some reason, it's not. I've done similar things to this before in other projects and it's worked then. I just can't see what it isn't working now.</p> <p>If I remove the element from my page declaration, I get through to the page fine.</p> <p>So, does anyone have any thoughts?</p>
[ { "answer_id": 157090, "author": "Chobicus", "author_id": 1514822, "author_profile": "https://Stackoverflow.com/users/1514822", "pm_score": 0, "selected": false, "text": "<p>try:\n...\n<code>&lt;f:param name=\"customerId\" value=\"#{customerId.toString()}\" /&gt;</code>\n...</p>\n" }, { "answer_id": 157310, "author": "Peter Hilton", "author_id": 2670, "author_profile": "https://Stackoverflow.com/users/2670", "pm_score": 0, "selected": false, "text": "<p>Our code does something similar, but with the <em>customerId</em> property in the Java class as a <em>String</em>:</p>\n\n<pre><code>private String customerId;\n\npublic String getCustomerId() {\n return customerId;\n}\n\npublic void setCustomerId(final String customerId) {\n this.customerId = customerId;\n}\n</code></pre>\n" }, { "answer_id": 157383, "author": "MetroidFan2002", "author_id": 8026, "author_profile": "https://Stackoverflow.com/users/8026", "pm_score": 0, "selected": false, "text": "<p>You could try using a property editor.</p>\n\n<p>Put this into the same package as your bean:</p>\n\n<pre><code>import java.beans.PropertyEditorSupport;\n\npublic class PresenceHomeEditor extends PropertyEditorSupport {\n public void setAsText(final String text) throws IllegalArgumentException {\n try {\n final Long value = Long.decode(text);\n setValue(value);\n } catch (final NumberFormatException e) {\n super.setAsText(text);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 158611, "author": "Joe Dean", "author_id": 5917, "author_profile": "https://Stackoverflow.com/users/5917", "pm_score": 4, "selected": true, "text": "<p>You want to add a converter to your pages.xml file. Like this:</p>\n\n<pre><code>&lt;param name=\"customerId\" \n value=\"#{presenceHome.customerId}\" \nconverterId=\"javax.faces.Long\" /&gt;\n</code></pre>\n\n<p>See the seampay example provided with seam for more details. </p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1900/" ]
I'm having a problem with my Seam code and I can't seem to figure out what I'm doing wrong. It's doing my head in :) Here's an excerpt of the stack trace: ``` Caused by: java.lang.IllegalArgumentException: Can not set java.lang.Long field com.oobjects.sso.manager.home.PresenceHome.customerId to java.lang.String ``` I'm trying to get a parameter set on my URL passed into one of my beans. To do this, I've got the following set up in my pages.xml: ``` <page view-id="/customer/presences.xhtml"> <begin-conversation flush-mode="MANUAL" join="true" /> <param name="customerId" value="#{presenceHome.customerId}" /> <raise-event type="PresenceHome.init" /> <navigation> <rule if-outcome="persisted"> <end-conversation /> <redirect view-id="/customer/presences.xhtml" /> </rule> </navigation> </page> ``` My bean starts like this: ``` @Name("presenceHome") @Scope(ScopeType.CONVERSATION) public class PresenceHome extends EntityHome<Presence> implements Serializable { @In private CustomerDao customerDao; @In(required = false) private Long presenceId; @In(required = false) private Long customerId; private Customer customer; // Getters, setters and other methods follow. They return the correct types defined above } ``` Finally the link I use to link one one page to the next looks like this: ``` <s:link styleClass="#{selected == 'presences' ? 'selected' : ''}" view="/customer/presences.xhtml" title="Presences" propagation="none"> <f:param name="customerId" value="#{customerId}" /> Presences </s:link> ``` All this seems to work fine. When I hover over the link above in my page, I get a URL ending in something like "?customerId=123". So the parameter is being passed over and it's something that can be easily converted into a Long type. But for some reason, it's not. I've done similar things to this before in other projects and it's worked then. I just can't see what it isn't working now. If I remove the element from my page declaration, I get through to the page fine. So, does anyone have any thoughts?
You want to add a converter to your pages.xml file. Like this: ``` <param name="customerId" value="#{presenceHome.customerId}" converterId="javax.faces.Long" /> ``` See the seampay example provided with seam for more details.
156,748
<p>How do I go about using HTTPS for some of the pages in my ASP.NET MVC based site?</p> <p>Steve Sanderson has a pretty good tutorial on how to do this in a DRY way on Preview 4 at:</p> <p><a href="http://blog.codeville.net/2008/08/05/adding-httpsssl-support-to-aspnet-mvc-routing/" rel="noreferrer">http://blog.codeville.net/2008/08/05/adding-httpsssl-support-to-aspnet-mvc-routing/</a></p> <p>Is there a better / updated way with Preview 5?,</p>
[ { "answer_id": 156952, "author": "David Laing", "author_id": 13238, "author_profile": "https://Stackoverflow.com/users/13238", "pm_score": 2, "selected": false, "text": "<p>Some ActionLink extensions: <a href=\"http://www.squaredroot.com/post/2008/06/11/MVC-and-SSL.aspx\" rel=\"nofollow noreferrer\">http://www.squaredroot.com/post/2008/06/11/MVC-and-SSL.aspx</a>\nOr an controller action attribute that redirects to https:// <a href=\"http://forums.asp.net/p/1260198/2358380.aspx#2358380\" rel=\"nofollow noreferrer\">http://forums.asp.net/p/1260198/2358380.aspx#2358380</a></p>\n" }, { "answer_id": 771511, "author": "Robin Minto", "author_id": 1456, "author_profile": "https://Stackoverflow.com/users/1456", "pm_score": 1, "selected": false, "text": "<p>Here's a <a href=\"http://weblogs.asp.net/cibrax/archive/2009/01/19/running-a-partial-ssl-website-in-asp-net-mvc.aspx\" rel=\"nofollow noreferrer\">blog post by Pablo M. Cibrano</a> from January 2009 that gathers up a couple of techniques including a HttpModule and extension methods.</p>\n" }, { "answer_id": 771521, "author": "Robin Minto", "author_id": 1456, "author_profile": "https://Stackoverflow.com/users/1456", "pm_score": 1, "selected": false, "text": "<p>Here's a <a href=\"http://blog.salvoz.com/2009/03/14/PartialSSLAndAuthorizationWithAspNetMVC.aspx\" rel=\"nofollow noreferrer\">blog post by Adam Salvo</a> that uses an ActionFilter.</p>\n" }, { "answer_id": 1116780, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24471\" rel=\"nofollow noreferrer\">MVCFutures</a> has a 'RequireSSL' attribute.</p>\n\n<p>(thanks Adam for <a href=\"http://blog.salvoz.com/2009/04/25/PartialSSLAndAuthorizationWithAspNetMVCRevisited.aspx\" rel=\"nofollow noreferrer\">pointing that out</a> in your updated blogpost)</p>\n\n<p>Just apply it to your action method, with 'Redirect=true' if you want an http:// request to automatically become https:// :</p>\n\n<pre><code> [RequireSsl(Redirect = true)]\n</code></pre>\n\n<p>See also: <a href=\"https://stackoverflow.com/questions/1639707/asp-net-mvc-requirehttps-in-production-only/1639831#1639831\">ASP.NET MVC RequireHttps in Production Only</a></p>\n" }, { "answer_id": 1330736, "author": "Kevin LaBranche", "author_id": 149053, "author_profile": "https://Stackoverflow.com/users/149053", "pm_score": 3, "selected": false, "text": "<p>Here's a recent post from Dan Wahlin on this:</p>\n\n<p><a href=\"http://weblogs.asp.net/dwahlin/archive/2009/08/25/requiring-ssl-for-asp-net-mvc-controllers.aspx\" rel=\"noreferrer\">http://weblogs.asp.net/dwahlin/archive/2009/08/25/requiring-ssl-for-asp-net-mvc-controllers.aspx</a></p>\n\n<p>He uses an ActionFilter Attribute.</p>\n" }, { "answer_id": 2359061, "author": "Amadiere", "author_id": 7828, "author_profile": "https://Stackoverflow.com/users/7828", "pm_score": 8, "selected": true, "text": "<p>If you are using <a href=\"http://blogs.teamb.com/craigstuntz/2009/10/05/38476/\" rel=\"noreferrer\">ASP.NET MVC 2 Preview 2 or higher</a>, you can now simply use:</p>\n\n<pre><code>[RequireHttps]\npublic ActionResult Login()\n{\n return View();\n}\n</code></pre>\n\n<p>Though, the order parameter is worth noting, as <a href=\"http://bartwullems.blogspot.com/2010/01/using-ssl-with-aspnet-mvc-2.html\" rel=\"noreferrer\">mentioned here</a>.</p>\n" }, { "answer_id": 2513300, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>As <a href=\"https://stackoverflow.com/questions/156748/ssl-pages-under-asp-net-mvc/2359061#2359061\">Amadiere wrote</a>, [RequireHttps] works great in MVC 2 for <em>entering</em> HTTPS. But if you only want to use HTTPS for <em>some</em> pages as you said, MVC 2 doesn't give you any love - once it switches a user to HTTPS they're stuck there until you manually redirect them.</p>\n\n<p>The approach I used is to use another custom attribute, [ExitHttpsIfNotRequired]. When attached to a controller or action this will redirect to HTTP if:</p>\n\n<ol>\n<li>The request was HTTPS</li>\n<li>The [RequireHttps] attribute wasn't applied to the action (or controller)</li>\n<li>The request was a GET (redirecting a POST would lead to all sorts of trouble).</li>\n</ol>\n\n<p>It's a bit too big to post here, but you can see <a href=\"http://lukesampson.com/post/471548689/entering-and-exiting-https-with-asp-net-mvc\" rel=\"nofollow noreferrer\">the code here</a> plus some additional details.</p>\n" }, { "answer_id": 2997782, "author": "Steven Pena", "author_id": 256716, "author_profile": "https://Stackoverflow.com/users/256716", "pm_score": 1, "selected": false, "text": "<p>This isn't necessarily MVC specific, but this solution does work for both ASP.NET WebForms and MVC:</p>\n\n<p><a href=\"http://www.codeproject.com/KB/web-security/WebPageSecurity_v2.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/web-security/WebPageSecurity_v2.aspx</a></p>\n\n<p>I've used this for several years and like the separation of concerns and management via the web.config file.</p>\n" }, { "answer_id": 11570755, "author": "user1015515", "author_id": 1015515, "author_profile": "https://Stackoverflow.com/users/1015515", "pm_score": 2, "selected": false, "text": "<p>For those who are not a fan of attribute-oriented development approaches, here is a piece of code that could help:</p>\n\n<pre><code>public static readonly string[] SecurePages = new[] { \"login\", \"join\" };\nprotected void Application_AuthorizeRequest(object sender, EventArgs e)\n{\n var pageName = RequestHelper.GetPageNameOrDefault();\n if (!HttpContext.Current.Request.IsSecureConnection\n &amp;&amp; (HttpContext.Current.Request.IsAuthenticated || SecurePages.Contains(pageName)))\n {\n Response.Redirect(\"https://\" + Request.ServerVariables[\"HTTP_HOST\"] + HttpContext.Current.Request.RawUrl);\n }\n if (HttpContext.Current.Request.IsSecureConnection\n &amp;&amp; !HttpContext.Current.Request.IsAuthenticated\n &amp;&amp; !SecurePages.Contains(pageName))\n {\n Response.Redirect(\"http://\" + Request.ServerVariables[\"HTTP_HOST\"] + HttpContext.Current.Request.RawUrl);\n }\n}\n</code></pre>\n\n<p>There are several reasons to avoid attributes and one of them is if you want to look at the list of all secured pages you will have to jump over all controllers in solution. </p>\n" }, { "answer_id": 16225596, "author": "Gindi Bar Yahav", "author_id": 568867, "author_profile": "https://Stackoverflow.com/users/568867", "pm_score": 2, "selected": false, "text": "<p>I went accross this question and hope my solution can helps someone.</p>\n\n<p>We got few problems:\n - We need to secure specific actions, for instance \"LogOn\" in \"Account\". We can use the build in RequireHttps attribute, which is great - but it'll redirect us back with https://.\n - We should make our links, forms and such \"SSL aware\".</p>\n\n<p>Generally, my solution allows to specify routes that will use absolute url, in addition to the ability to specify the protocol. You can use this approch to specify the \"https\" protocol.</p>\n\n<p>So, firstly I've created an ConnectionProtocol enum:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Enum representing the available secure connection requirements\n/// &lt;/summary&gt;\npublic enum ConnectionProtocol\n{\n /// &lt;summary&gt;\n /// No secure connection requirement\n /// &lt;/summary&gt;\n Ignore,\n\n /// &lt;summary&gt;\n /// No secure connection should be used, use standard http request.\n /// &lt;/summary&gt;\n Http,\n\n /// &lt;summary&gt;\n /// The connection should be secured using SSL (https protocol).\n /// &lt;/summary&gt;\n Https\n}\n</code></pre>\n\n<p>Now, I've created hand-rolled version of RequireSsl. I've modified the original RequireSsl source code to allow redirection back to http:// urls. In addition, I've put a field that allows us to determine if we should require SSL or not (I'm using it with the DEBUG pre-processor).</p>\n\n<pre><code>/* Note:\n * This is hand-rolled version of the original System.Web.Mvc.RequireHttpsAttribute.\n * This version contains three improvements:\n * - Allows to redirect back into http:// addresses, based on the &lt;see cref=\"SecureConnectionRequirement\" /&gt; Requirement property.\n * - Allows to turn the protocol scheme redirection off based on given condition.\n * - Using Request.IsCurrentConnectionSecured() extension method, which contains fix for load-balanced servers.\n */\n[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\npublic sealed class RequireHttpsAttribute : FilterAttribute, IAuthorizationFilter\n{\n public RequireHttpsAttribute()\n {\n Protocol = ConnectionProtocol.Ignore;\n }\n\n /// &lt;summary&gt;\n /// Gets or sets the secure connection required protocol scheme level\n /// &lt;/summary&gt;\n public ConnectionProtocol Protocol { get; set; }\n\n /// &lt;summary&gt;\n /// Gets the value that indicates if secure connections are been allowed\n /// &lt;/summary&gt;\n public bool SecureConnectionsAllowed\n {\n get\n {\n#if DEBUG\n return false;\n#else\n return true;\n#endif\n }\n }\n\n public void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)\n {\n if (filterContext == null)\n {\n throw new ArgumentNullException(\"filterContext\");\n }\n\n /* Are we allowed to use secure connections? */\n if (!SecureConnectionsAllowed)\n return;\n\n switch (Protocol)\n {\n case ConnectionProtocol.Https:\n if (!filterContext.HttpContext.Request.IsCurrentConnectionSecured())\n {\n HandleNonHttpsRequest(filterContext);\n }\n break;\n case ConnectionProtocol.Http:\n if (filterContext.HttpContext.Request.IsCurrentConnectionSecured())\n {\n HandleNonHttpRequest(filterContext);\n }\n break;\n }\n }\n\n\n private void HandleNonHttpsRequest(AuthorizationContext filterContext)\n {\n // only redirect for GET requests, otherwise the browser might not propagate the verb and request\n // body correctly.\n\n if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, \"GET\", StringComparison.OrdinalIgnoreCase))\n {\n throw new InvalidOperationException(\"The requested resource can only be accessed via SSL.\");\n }\n\n // redirect to HTTPS version of page\n string url = \"https://\" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;\n filterContext.Result = new RedirectResult(url);\n }\n\n private void HandleNonHttpRequest(AuthorizationContext filterContext)\n {\n if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, \"GET\", StringComparison.OrdinalIgnoreCase))\n {\n throw new InvalidOperationException(\"The requested resource can only be accessed without SSL.\");\n }\n\n // redirect to HTTP version of page\n string url = \"http://\" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;\n filterContext.Result = new RedirectResult(url);\n }\n}\n</code></pre>\n\n<p>Now, this RequireSsl will do the following base on your Requirements attribute value:\n - Ignore: Won't do nothing.\n - Http: Will force redirection to http protocol.\n - Https: Will force redirection to https protocol.</p>\n\n<p>You should create your own base controller and set this attribute to Http.</p>\n\n<pre><code>[RequireSsl(Requirement = ConnectionProtocol.Http)]\npublic class MyController : Controller\n{\n public MyController() { }\n}\n</code></pre>\n\n<p>Now, in each cpntroller/action you'd like to require SSL - just set this attribute with ConnectionProtocol.Https.</p>\n\n<p>Now lets move to URLs: We got few problems with the url routing engine. You can read more about them at <a href=\"http://blog.stevensanderson.com/2008/08/05/adding-httpsssl-support-to-aspnet-mvc-routing/\" rel=\"nofollow\">http://blog.stevensanderson.com/2008/08/05/adding-httpsssl-support-to-aspnet-mvc-routing/</a>. The solution suggested in this post is theoreticly good, but old and I don't like the approch.</p>\n\n<p>My solutions is the following:\nCreate a subclass of the basic \"Route\" class:</p>\n\n<p>public class AbsoluteUrlRoute : Route\n {\n #region ctor</p>\n\n<pre><code> /// &lt;summary&gt;\n /// Initializes a new instance of the System.Web.Routing.Route class, by using\n /// the specified URL pattern and handler class.\n /// &lt;/summary&gt;\n /// &lt;param name=\"url\"&gt;The URL pattern for the route.&lt;/param&gt;\n /// &lt;param name=\"routeHandler\"&gt;The object that processes requests for the route.&lt;/param&gt;\n public AbsoluteUrlRoute(string url, IRouteHandler routeHandler)\n : base(url, routeHandler)\n {\n\n }\n\n /// &lt;summary&gt;\n /// Initializes a new instance of the System.Web.Routing.Route class, by using\n /// the specified URL pattern and handler class.\n /// &lt;/summary&gt;\n /// &lt;param name=\"url\"&gt;The URL pattern for the route.&lt;/param&gt;\n /// &lt;param name=\"defaults\"&gt;The values to use for any parameters that are missing in the URL.&lt;/param&gt;\n /// &lt;param name=\"routeHandler\"&gt;The object that processes requests for the route.&lt;/param&gt;\n public AbsoluteUrlRoute(string url, RouteValueDictionary defaults, IRouteHandler routeHandler)\n : base(url, defaults, routeHandler)\n {\n\n }\n\n /// &lt;summary&gt;\n /// Initializes a new instance of the System.Web.Routing.Route class, by using\n /// the specified URL pattern and handler class.\n /// &lt;/summary&gt;\n /// &lt;param name=\"url\"&gt;The URL pattern for the route.&lt;/param&gt;\n /// &lt;param name=\"defaults\"&gt;The values to use for any parameters that are missing in the URL.&lt;/param&gt;\n /// &lt;param name=\"constraints\"&gt;A regular expression that specifies valid values for a URL parameter.&lt;/param&gt;\n /// &lt;param name=\"routeHandler\"&gt;The object that processes requests for the route.&lt;/param&gt;\n public AbsoluteUrlRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints,\n IRouteHandler routeHandler)\n : base(url, defaults, constraints, routeHandler)\n {\n\n }\n\n /// &lt;summary&gt;\n /// Initializes a new instance of the System.Web.Routing.Route class, by using\n /// the specified URL pattern and handler class.\n /// &lt;/summary&gt;\n /// &lt;param name=\"url\"&gt;The URL pattern for the route.&lt;/param&gt;\n /// &lt;param name=\"defaults\"&gt;The values to use for any parameters that are missing in the URL.&lt;/param&gt;\n /// &lt;param name=\"constraints\"&gt;A regular expression that specifies valid values for a URL parameter.&lt;/param&gt;\n /// &lt;param name=\"dataTokens\"&gt;Custom values that are passed to the route handler, but which are not used\n /// to determine whether the route matches a specific URL pattern. These values\n /// are passed to the route handler, where they can be used for processing the\n /// request.&lt;/param&gt;\n /// &lt;param name=\"routeHandler\"&gt;The object that processes requests for the route.&lt;/param&gt;\n public AbsoluteUrlRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints,\n RouteValueDictionary dataTokens, IRouteHandler routeHandler)\n : base(url, defaults, constraints, dataTokens, routeHandler)\n {\n\n }\n\n #endregion\n\n public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)\n {\n var virtualPath = base.GetVirtualPath(requestContext, values);\n if (virtualPath != null)\n {\n var scheme = \"http\";\n if (this.DataTokens != null &amp;&amp; (string)this.DataTokens[\"scheme\"] != string.Empty)\n {\n scheme = (string) this.DataTokens[\"scheme\"];\n }\n\n virtualPath.VirtualPath = MakeAbsoluteUrl(requestContext, virtualPath.VirtualPath, scheme);\n return virtualPath;\n }\n\n return null;\n }\n\n #region Helpers\n\n /// &lt;summary&gt;\n /// Creates an absolute url\n /// &lt;/summary&gt;\n /// &lt;param name=\"requestContext\"&gt;The request context&lt;/param&gt;\n /// &lt;param name=\"virtualPath\"&gt;The initial virtual relative path&lt;/param&gt;\n /// &lt;param name=\"scheme\"&gt;The protocol scheme&lt;/param&gt;\n /// &lt;returns&gt;The absolute URL&lt;/returns&gt;\n private string MakeAbsoluteUrl(RequestContext requestContext, string virtualPath, string scheme)\n {\n return string.Format(\"{0}://{1}{2}{3}{4}\",\n scheme,\n requestContext.HttpContext.Request.Url.Host,\n requestContext.HttpContext.Request.ApplicationPath,\n requestContext.HttpContext.Request.ApplicationPath.EndsWith(\"/\") ? \"\" : \"/\",\n virtualPath);\n }\n\n #endregion\n}\n</code></pre>\n\n<p>This version of \"Route\" class will create absolute url. The trick here, followed by the blog post author suggestion, is to use the DataToken to specify the scheme (example at the end :) ).</p>\n\n<p>Now, if we'll generate an url, for example for the route \"Account/LogOn\" we'll get \"/<a href=\"http://example.com/Account/LogOn\" rel=\"nofollow\">http://example.com/Account/LogOn</a>\" - that's since the UrlRoutingModule sees all the urls as relative. We can fix that using custom HttpModule:</p>\n\n<pre><code>public class AbsoluteUrlRoutingModule : UrlRoutingModule\n{\n protected override void Init(System.Web.HttpApplication application)\n {\n application.PostMapRequestHandler += application_PostMapRequestHandler;\n base.Init(application);\n }\n\n protected void application_PostMapRequestHandler(object sender, EventArgs e)\n {\n var wrapper = new AbsoluteUrlAwareHttpContextWrapper(((HttpApplication)sender).Context);\n }\n\n public override void PostResolveRequestCache(HttpContextBase context)\n {\n base.PostResolveRequestCache(new AbsoluteUrlAwareHttpContextWrapper(HttpContext.Current));\n }\n\n private class AbsoluteUrlAwareHttpContextWrapper : HttpContextWrapper\n {\n private readonly HttpContext _context;\n private HttpResponseBase _response = null;\n\n public AbsoluteUrlAwareHttpContextWrapper(HttpContext context)\n : base(context)\n {\n this._context = context;\n }\n\n public override HttpResponseBase Response\n {\n get\n {\n return _response ??\n (_response =\n new AbsoluteUrlAwareHttpResponseWrapper(_context.Response));\n }\n }\n\n\n private class AbsoluteUrlAwareHttpResponseWrapper : HttpResponseWrapper\n {\n public AbsoluteUrlAwareHttpResponseWrapper(HttpResponse response)\n : base(response)\n {\n\n }\n\n public override string ApplyAppPathModifier(string virtualPath)\n {\n int length = virtualPath.Length;\n if (length &gt; 7 &amp;&amp; virtualPath.Substring(0, 7) == \"/http:/\")\n return virtualPath.Substring(1);\n else if (length &gt; 8 &amp;&amp; virtualPath.Substring(0, 8) == \"/https:/\")\n return virtualPath.Substring(1);\n\n return base.ApplyAppPathModifier(virtualPath);\n }\n }\n }\n}\n</code></pre>\n\n<p>Since this module is overriding the base implementation of UrlRoutingModule, we should remove the base httpModule and register ours in web.config. So, under \"system.web\" set: </p>\n\n<pre><code>&lt;httpModules&gt;\n &lt;!-- Removing the default UrlRoutingModule and inserting our own absolute url routing module --&gt;\n &lt;remove name=\"UrlRoutingModule-4.0\" /&gt;\n &lt;add name=\"UrlRoutingModule-4.0\" type=\"MyApp.Web.Mvc.Routing.AbsoluteUrlRoutingModule\" /&gt;\n&lt;/httpModules&gt;\n</code></pre>\n\n<p>Thats it :).</p>\n\n<p>In order to register an absolute / protocol followed route, you should do:</p>\n\n<pre><code> routes.Add(new AbsoluteUrlRoute(\"Account/LogOn\", new MvcRouteHandler())\n {\n Defaults = new RouteValueDictionary(new {controller = \"Account\", action = \"LogOn\", area = \"\"}),\n DataTokens = new RouteValueDictionary(new {scheme = \"https\"})\n });\n</code></pre>\n\n<p>Will love to hear your feedback + improvements. Hope it can help! :)</p>\n\n<p>Edit:\nI forgot to include the IsCurrentConnectionSecured() extension method (too many snippets :P). This is an extension method that generally uses Request.IsSecuredConnection. However, this approch will not work when using load-balancing - so this method can bypass this (took from nopCommerce).</p>\n\n<pre><code> /// &lt;summary&gt;\n /// Gets a value indicating whether current connection is secured\n /// &lt;/summary&gt;\n /// &lt;param name=\"request\"&gt;The base request context&lt;/param&gt;\n /// &lt;returns&gt;true - secured, false - not secured&lt;/returns&gt;\n /// &lt;remarks&gt;&lt;![CDATA[ This method checks whether or not the connection is secured.\n /// There's a standard Request.IsSecureConnection attribute, but it won't be loaded correctly in case of load-balancer.\n /// See: &lt;a href=\"http://nopcommerce.codeplex.com/SourceControl/changeset/view/16de4a113aa9#src/Libraries/Nop.Core/WebHelper.cs\"&gt;nopCommerce WebHelper IsCurrentConnectionSecured()&lt;/a&gt;]]&gt;&lt;/remarks&gt;\n public static bool IsCurrentConnectionSecured(this HttpRequestBase request)\n {\n return request != null &amp;&amp; request.IsSecureConnection;\n\n // when your hosting uses a load balancer on their server then the Request.IsSecureConnection is never got set to true, use the statement below\n // just uncomment it\n //return request != null &amp;&amp; request.ServerVariables[\"HTTP_CLUSTER_HTTPS\"] == \"on\";\n }\n</code></pre>\n" }, { "answer_id": 38245809, "author": "Nick Niebling", "author_id": 1095493, "author_profile": "https://Stackoverflow.com/users/1095493", "pm_score": 0, "selected": false, "text": "<p><strong>MVC 6</strong> (ASP.NET Core 1.0) is working slightly different with Startup.cs.</p>\n\n<p>To use RequireHttpsAttribute (as mentioned in <a href=\"https://stackoverflow.com/a/2359061/1095493\">answer</a> by Amadiere) on all pages, you could add this in Startup.cs instead of using attribute style on each controller (or instead of creating a BaseController for all your controllers to inherit from).</p>\n\n<p><strong>Startup.cs</strong> - register filter:</p>\n\n<pre><code>public void ConfigureServices(IServiceCollection services)\n{\n // TODO: Register other services\n\n services.AddMvc(options =&gt;\n {\n options.Filters.Add(typeof(RequireHttpsAttribute));\n });\n}\n</code></pre>\n\n<p>For more info about design decisions for above approach, see my answer on similar question about <a href=\"https://stackoverflow.com/a/38244992/1095493\">how to exclude localhost requests from being handled by the RequireHttpsAttribute</a>.</p>\n" }, { "answer_id": 60494616, "author": "Chris Catignani", "author_id": 3072350, "author_profile": "https://Stackoverflow.com/users/3072350", "pm_score": 0, "selected": false, "text": "<p>Alternately add a filter to <strong>Global.asax.cs</strong></p>\n\n<blockquote>\n <p>GlobalFilters.Filters.Add(new RequireHttpsAttribute());</p>\n</blockquote>\n\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.requirehttpsattribute?view=aspnet-mvc-5.2\" rel=\"nofollow noreferrer\">RequireHttpsAttribute Class</a></p>\n\n<pre><code>using System.Web.Mvc;\nusing System.Web.Optimization;\nusing System.Web.Routing;\n\nnamespace xxxxxxxx\n{\n public class MvcApplication : System.Web.HttpApplication\n {\n protected void Application_Start()\n {\n AreaRegistration.RegisterAllAreas();\n FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);\n GlobalFilters.Filters.Add(new RequireHttpsAttribute());\n RouteConfig.RegisterRoutes(RouteTable.Routes);\n BundleConfig.RegisterBundles(BundleTable.Bundles);\n }\n }\n}\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13238/" ]
How do I go about using HTTPS for some of the pages in my ASP.NET MVC based site? Steve Sanderson has a pretty good tutorial on how to do this in a DRY way on Preview 4 at: <http://blog.codeville.net/2008/08/05/adding-httpsssl-support-to-aspnet-mvc-routing/> Is there a better / updated way with Preview 5?,
If you are using [ASP.NET MVC 2 Preview 2 or higher](http://blogs.teamb.com/craigstuntz/2009/10/05/38476/), you can now simply use: ``` [RequireHttps] public ActionResult Login() { return View(); } ``` Though, the order parameter is worth noting, as [mentioned here](http://bartwullems.blogspot.com/2010/01/using-ssl-with-aspnet-mvc-2.html).
156,767
<p>When verbally talking about methods, I'm never sure whether to use the word <em>argument</em> or <em>parameter</em> or something else. Either way the other people know what I mean, but what's correct, and what's the history of the terms?</p> <p>I'm a C# programmer, but I also wonder whether people use different terms in different languages.</p> <p>For the record I'm self-taught without a background in Computer Science. (Please don't tell me to read <a href="http://www.amazon.co.uk/Code-Complete-Practical-Handbook-Construction/dp/0735619670/" rel="noreferrer">Code Complete</a> because I'm asking this for the benefit of other people who don't already have a copy of <a href="http://www.stevemcconnell.com/" rel="noreferrer">Steve McConnell</a>'s marvellous book.)</p> <h3>Summary</h3> <p>The general consensus seems to be that it's OK to use these terms interchangeably in a team environment. Except perhaps when you're defining the precise terminology; then you can also use "<em>formal</em> argument/parameter" and "<em>actual</em> argument/parameter" to disambiguate.</p>
[ { "answer_id": 156778, "author": "Rinat Abdullin", "author_id": 47366, "author_profile": "https://Stackoverflow.com/users/47366", "pm_score": 9, "selected": false, "text": "<p><strong>Parameter</strong> is the variable in the declaration of the function.</p>\n<p><strong>Argument</strong> is the actual value of this variable that gets passed to the function.</p>\n" }, { "answer_id": 156785, "author": "Carra", "author_id": 21679, "author_profile": "https://Stackoverflow.com/users/21679", "pm_score": 5, "selected": false, "text": "<p>A parameter is something you have to fill in when you call a function. What you put in it is the argument. </p>\n\n<p>Simply set: the argument goes into the parameter, an argument is the value of the parameter.</p>\n\n<p>A bit more info on:\n<a href=\"http://en.wikipedia.org/wiki/Parameter_(computer_science)#Parameters_and_arguments\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Parameter_(computer_science)#Parameters_and_arguments</a></p>\n" }, { "answer_id": 156787, "author": "Torbjörn Hansson", "author_id": 22683, "author_profile": "https://Stackoverflow.com/users/22683", "pm_score": 11, "selected": true, "text": "<p>A parameter is a variable in a method definition. When a method is called, the arguments are the data you pass into the method's parameters.</p>\n\n<pre><code>public void MyMethod(string myParam) { }\n\n...\n\nstring myArg1 = \"this is my argument\";\nmyClass.MyMethod(myArg1);\n</code></pre>\n" }, { "answer_id": 156792, "author": "Johan", "author_id": 11347, "author_profile": "https://Stackoverflow.com/users/11347", "pm_score": 3, "selected": false, "text": "<p>The <strong>parameters</strong> of a function/method describe to you the values that it uses to calculate its result.</p>\n\n<p>The <strong>arguments</strong> of a function are the values assigned to these parameters during a particular call of the function/method.</p>\n" }, { "answer_id": 156859, "author": "Atif Aziz", "author_id": 6682, "author_profile": "https://Stackoverflow.com/users/6682", "pm_score": 6, "selected": false, "text": "<p>There is already a Wikipedia entry on the subject (see <a href=\"http://en.wikipedia.org/wiki/Parameter_(computer_science)\" rel=\"noreferrer\">Parameter</a>) that defines and distinguishes the terms <em>parameter</em> and <em>argument</em>. In short, a parameter is part of the function/procedure/method signature and an argument is the actual value supplied at run-time and/or call-site for the parameter. </p>\n\n<p>The Wikipedia article also states that the two terms are often used synonymously (especially when reasoning about code informally):</p>\n\n<blockquote>\n <p>Although parameters are also commonly\n referred to as arguments, arguments\n are more properly thought of as the\n actual values or references assigned\n to the parameter variables when the\n subroutine is called at runtime.</p>\n</blockquote>\n\n<p>Given the following example function in C that adds two integers, <code>x</code> and <code>y</code> would be referred to as its parameters:</p>\n\n<pre><code>int add(int x, int y) {\n return x + y;\n}\n</code></pre>\n\n<p>At a call-site using <code>add</code>, such as the example shown below, <em>123</em> and <em>456</em> would be referred to as the <em>arguments</em> of the call.</p>\n\n<pre><code>int result = add(123, 456);\n</code></pre>\n\n<p>Also, some language specifications (or formal documentation) choose to use <em>parameter</em> or <em>argument</em> exclusively and use adjectives like <em>formal</em> and <em>actual</em> instead to disambiguate between the two cases. For example, C/C++ documentation often refers to function <em>parameters</em> as <em>formal arguments</em> and function call <em>arguments</em> as <em>actual arguments</em>. For an example, see “<a href=\"http://msdn.microsoft.com/en-us/library/f81cdka5.aspx\" rel=\"noreferrer\">Formal and Actual Arguments</a>” in the <a href=\"http://msdn.microsoft.com/en-us/library/3bstk3k5.aspx\" rel=\"noreferrer\">Visual C++ Language Reference</a>. </p>\n" }, { "answer_id": 156875, "author": "Marcelo Cantos", "author_id": 9990, "author_profile": "https://Stackoverflow.com/users/9990", "pm_score": 3, "selected": false, "text": "<p>The terms are somewhat interchangeable. The distinction described in other answers is more properly expressed with the terms <em>formal parameter</em> for the name used inside the body of the function and <em>parameter</em> for the value supplied at the call site (<em>formal argument</em> and <em>argument</em> are also common).</p>\n\n<p>Also note that, in mathematics, the term <em>argument</em> is far more common and <em>parameter</em> usually means something quite different (though the <em>parameter</em> in a parametric equation is essentially the <em>argument</em> to two or more functions).</p>\n" }, { "answer_id": 17120743, "author": "jpillora", "author_id": 977939, "author_profile": "https://Stackoverflow.com/users/977939", "pm_score": 1, "selected": false, "text": "<p>Or even simpler...</p>\n\n<p><strong>Arguments in !</strong></p>\n\n<p><strong>Parameters out !</strong></p>\n" }, { "answer_id": 18447280, "author": "Saurabh Rana", "author_id": 1458328, "author_profile": "https://Stackoverflow.com/users/1458328", "pm_score": 3, "selected": false, "text": "<p>This example might help.</p>\n\n<pre><code>int main () {\n int x = 5; \n int y = 4;\n\n sum(x, y); // **x and y are arguments**\n}\n\nint sum(int one, int two) { // **one and two are parameters**\n return one + two;\n}\n</code></pre>\n" }, { "answer_id": 19619127, "author": "Bevin Sunth", "author_id": 2917148, "author_profile": "https://Stackoverflow.com/users/2917148", "pm_score": 2, "selected": false, "text": "<p>They both dont have much difference in usage in C, both the terms are used\nin practice.\n Mostly arguments are often used with functions. The value passed with the function calling statement is called the argument, And the parameter would be the variable which copies the value in the function definition (called as formal parameter). </p>\n\n<pre><code>int main ()\n{\n /* local variable definition */\n int a = 100;\n int b = 200;\n int ret;\n\n /* calling a function to get max value */\n ret = max(a, b);\n\n printf( \"Max value is : %d\\n\", ret );\n\n return 0;\n}\n\n/* function returning the max between two numbers */\nint max(int num1, int num2) \n{\n /* local variable declaration */\n int result;\n\n if (num1 &gt; num2)\n result = num1;\n else\n result = num2;\n\n return result; \n}\n</code></pre>\n\n<p>In the above code <code>num1</code> and <code>num2</code> are formal parameters and <code>a</code> and <code>b</code> are actual arguments.</p>\n" }, { "answer_id": 20726232, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 4, "selected": false, "text": "<p>Or maybe it's even simpler to remember like this, in case of optional arguments for a method:</p>\n<pre><code>public void Method(string parameter = &quot;argument&quot;) \n{\n\n}\n</code></pre>\n<p><code>parameter</code> is the parameter, its value, <code>&quot;argument&quot;</code> is the argument :)</p>\n" }, { "answer_id": 21067354, "author": "XML", "author_id": 800457, "author_profile": "https://Stackoverflow.com/users/800457", "pm_score": 5, "selected": false, "text": "<p>Let's say you're an airline. You build an airplane. You install seats in it. Then, you fill the plane up with passengers and send it somewhere. The passengers disembark. Next day, you re-use the same plane, and same seats, but with different passengers this time.</p>\n<p>The plane is your function.</p>\n<p>The parameters are the seats.</p>\n<p>The arguments are the passengers that go in those seats.</p>\n<pre><code>function fly(seat1, seat2) {\n seat1.sayMyName();\n // Estraven\n seat2.sayMyName();\n\n etc.\n}\n\nvar passenger1 = &quot;Estraven&quot;;\nvar passenger2 = &quot;Genly Ai&quot;;\n\nfly(passenger1, passenger2); \n</code></pre>\n" }, { "answer_id": 22472316, "author": "Paul Richter", "author_id": 316698, "author_profile": "https://Stackoverflow.com/users/316698", "pm_score": 3, "selected": false, "text": "<p>An argument is an instantiation of a parameter.</p>\n" }, { "answer_id": 23992345, "author": "Wolfpack'08", "author_id": 445651, "author_profile": "https://Stackoverflow.com/users/445651", "pm_score": 4, "selected": false, "text": "<p>In editing, I'm often put off at how people forget: structure languages are based on natural languages. </p>\n\n<h2>In English</h2>\n\n<p>A \"parameter\" is a placeholder. They set the response format, in spoken language. By definition, it's party to the call, limiting the response.</p>\n\n<p>An \"argument\" is a position that is being considered. You argue your opinion: you consider an argument. </p>\n\n<h2>Main difference</h2>\n\n<p>The thematic role of an argument is agent. The thematic role of parameter is recipient. </p>\n\n<h2>Interactions</h2>\n\n<p>Think of the argument as the male part, making the parameter the female part. The argument goes into the parameter. </p>\n\n<h2>Usage</h2>\n\n<p>A parameter is <em>usually</em> used in definitions. An argument is <em>usually</em> used in invocations. </p>\n\n<h2>Questions</h2>\n\n<p><strong>Finish the sentence to make it less dissonant.</strong></p>\n\n<p>(A) Speaking of a definition:</p>\n\n<ol>\n<li>What argument will be used []?</li>\n<li>What [] will this parameter []?</li>\n</ol>\n\n<p>(B) Speaking of an invocation:</p>\n\n<ol>\n<li>What parameter will you use, []?</li>\n<li>What [] will be [] this parameter? </li>\n</ol>\n\n<h2>Answers</h2>\n\n<p>(A) </p>\n\n<ol>\n<li>on/in/against/with this parameter</li>\n<li>argument(s) ... take </li>\n</ol>\n\n<p>(B) </p>\n\n<ol>\n<li>and what are some example arguments</li>\n<li>argument(s) ... used on/in/against/with</li>\n</ol>\n\n<h2>Overlaps</h2>\n\n<p>As you can imagine, after answering: in spoken language, these words will sometimes produce identical responses! </p>\n\n<p>So, as a rule: </p>\n\n<ul>\n<li><p>Usually if someone wants parameter information, they want to know more about the type, the variable name, etc. They may become confused if you only give example arguments. </p>\n\n<ul>\n<li>Usually if someone wants argument information, they want to know what value you passed to a function or its parameter(s).</li>\n</ul></li>\n</ul>\n" }, { "answer_id": 24367269, "author": "Jämes", "author_id": 2780334, "author_profile": "https://Stackoverflow.com/users/2780334", "pm_score": 5, "selected": false, "text": "<blockquote>\n <p>The use of the terms parameters and arguments have been misused\n somewhat among programmers and even authors. When dealing with\n methods, the term <em>parameter</em> is used to identify the placeholders in\n the method signature, whereas the term <em>arguments</em> are the actual\n values that you pass in to the method.</p>\n</blockquote>\n\n<p><em>MCSD Cerfification Toolkit (Exam 70-483) Programming in C#</em>, 1st edition, Wrox, 2013</p>\n\n<p><strong>Real-world case scenario</strong></p>\n\n<pre><code>// Define a method with two parameters\nint Sum(int num1, int num2)\n{\n return num1 + num2;\n}\n\n// Call the method using two arguments\nvar ret = Sum(2, 3);\n</code></pre>\n" }, { "answer_id": 33401833, "author": "BenKoshy", "author_id": 4880924, "author_profile": "https://Stackoverflow.com/users/4880924", "pm_score": 3, "selected": false, "text": "<h1>Simple Explanations without code</h1>\n\n<p>A \"parameter\" is a very general, broad thing, but an \"argument: is a very specific, concrete thing. This is best illustrated via everyday examples:</p>\n\n<h3>Example 1: Vending Machines - Money is the parameter, $2.00 is the argument</h3>\n\n<p>Most machines take an input and return an output. For example a vending machine takes as an input: money, and returns: fizzy drinks as the output. In that particular case, it accepts as a parameter: money. </p>\n\n<p>What then is the argument? Well if I put $2.00 into the machine, then the argument is: $2.00 - it is the very specific input used.</p>\n\n<h3>Example 2: Cars - Petrol is the parameter</h3>\n\n<p>Let's consider a car: they accept petrol (unleaded gasoline) as an input. It can be said that these machines accept <strong><em>parameters</em></strong> of type: petrol. The argument would be the exact and concrete input I put into my car. e.g. In my case, the argument would be: 40 litres of unleaded petrol/gasoline.</p>\n\n<h3>Example 3 - Elaboration on Arguments</h3>\n\n<p>An argument is a particular and specific example of an input. Suppose my machine takes a person as an input and turns them into someone who isn't a liar.</p>\n\n<p>What then is an argument? The argument will be the particular person who is actually put into the machine. e.g. if Colin Powell is put into the machine then the argument would be Colin Powell. </p>\n\n<p>So the parameter would be a person as an abstract concept, but the argument would always be a <strong><em>particular person</em></strong> with a <strong><em>particular name</em></strong> who is put into the machine. The argument is specific and concrete.</p>\n\n<p>That's the difference. Simple.</p>\n\n<h3>Confused?</h3>\n\n<p>Post a comment and I'll fix up the explanation.</p>\n" }, { "answer_id": 35923448, "author": "J. Clarke", "author_id": 6046183, "author_profile": "https://Stackoverflow.com/users/6046183", "pm_score": 2, "selected": false, "text": "<p>Oracle's Java tutorials define this distinction thusly:\n\"Parameters refers to the list of variables in a method declaration. Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order.\"</p>\n\n<p>A more detailed discussion of parameters and arguments: \n<a href=\"https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html\" rel=\"nofollow\">https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html</a></p>\n" }, { "answer_id": 36172609, "author": "Summra Umair", "author_id": 6066658, "author_profile": "https://Stackoverflow.com/users/6066658", "pm_score": 2, "selected": false, "text": "<p>When we create the method (function) in Java, the method like this..</p>\n\n<p><code>data-type name of the method (data-type variable-name)</code></p>\n\n<p>In the parenthesis, these are the parameters, and when we call the method (function) we pass the value of this parameter, which are called the arguments.</p>\n" }, { "answer_id": 40832360, "author": "shreesh katti", "author_id": 7217096, "author_profile": "https://Stackoverflow.com/users/7217096", "pm_score": 0, "selected": false, "text": "<p>Parameters are the variables received by a function.Hence they are visible in function declaration.They contain the variable name with their data type.\nArguments are actual values which are passed to another function. thats why we can see them in function call. They are just values without their datatype </p>\n" }, { "answer_id": 43252753, "author": "Soner from The Ottoman Empire", "author_id": 4990642, "author_profile": "https://Stackoverflow.com/users/4990642", "pm_score": 3, "selected": false, "text": "<p><em>Parameters and Arguments</em></p>\n\n<blockquote>\n <p>All the different terms that have to do with parameters and arguments\n can be confusing. However, if you keep a few simple points in mind,\n you will be able to easily handle these terms.</p>\n \n <ol>\n <li>The <em>formal parameters</em> for a function are listed in the function declaration and are used in the body of the function definition. A\n formal parameter (of any sort) is a kind of blank or placeholder that\n is filled in with something when the function is called.</li>\n <li>An <em>argument</em> is something that is used to fill in a formal parameter.\n When you write down a function call, the arguments are listed in\n parentheses after the function name. When the function call is\n executed, the arguments are plugged in for the formal parameters.</li>\n <li>The terms <em>call-by-value</em> and <em>call-by-reference</em> refer to the mechanism\n that is used in the plugging-in process. In the call-by-value method\n only the value of the argument is used. In this call-by-value\n mechanism, the formal parameter is a local variable that is\n initialized to the value of the corresponding argument. In the\n call-by-reference mechanism the argument is a variable and the\n entire variable is used. In the call- by-reference mechanism the\n argument variable is substituted for the formal parameter so that\n any change that is made to the formal parameter is actually made to\n the argument variable.</li>\n </ol>\n</blockquote>\n\n<p>Source: Absolute C++, Walter Savitch</p>\n\n<p>That is,</p>\n\n<p><a href=\"https://i.stack.imgur.com/ZohYJ.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/ZohYJ.jpg\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 43602455, "author": "Duc Filan", "author_id": 3286605, "author_profile": "https://Stackoverflow.com/users/3286605", "pm_score": 7, "selected": false, "text": "<p>Simple:</p>\n\n<ul>\n<li><strong>P</strong>ARAMETER → <strong>P</strong>LACEHOLDER (This means a placeholder belongs to the function naming and be used in the function body)</li>\n<li><strong>A</strong>RGUMENT → <strong>A</strong>CTUAL VALUE (This means an actual value which is passed by the function calling)</li>\n</ul>\n" }, { "answer_id": 43695598, "author": "Nuwan Jayawardene", "author_id": 7838048, "author_profile": "https://Stackoverflow.com/users/7838048", "pm_score": 2, "selected": false, "text": "<p>Logically speaking,we're actually talking about the same thing.\nBut I think a simple metaphor would be helpful to solve this dilemma. </p>\n\n<p>If the metaphors can be called various connection point we can equate them to plug points on a wall.\nIn this case we can consider parameters and arguments as follows;</p>\n\n<p><strong><em>Parameters</strong> are the sockets of the plug-point which may take various different shapes. But only certain types of plugs fit them.</em><br>\n<strong><em>Arguments</strong> will be the actual plugs that would be plugged into the plug points/sockets to activate certain equipments.</em></p>\n" }, { "answer_id": 44516192, "author": "gay", "author_id": 8153387, "author_profile": "https://Stackoverflow.com/users/8153387", "pm_score": 0, "selected": false, "text": "<p>The formal parameters for a function are listed in the function declaration and are used in the body of the function definition. A formal <strong>parameter</strong> (of any sort) is a kind of blank or placeholder that is filled in with something when the function is called.</p>\n\n<p>An <strong>argument</strong> is something that is used to fill in a formal parameter. When you write down a function call, the arguments are listed in parentheses after the function name. When the function call is executed, the arguments are plugged in for the formal parameters.</p>\n\n<p>The terms <strong>call-by-value</strong> and <strong>call-by-reference</strong> refer to the mechanism that is used in the plugging-in process. In the call-by-value method only the value of the argument is used. In this call-by-value mechanism, the formal parameter is a local variable that is initialized to the value of the corresponding argument. In the call-by-reference mechanism the argument is a variable and the entire variable is used. In the call- by-reference mechanism the argument variable is substituted for the formal parameter so that any change that is made to the formal parameter is actually made to the argument variable.</p>\n" }, { "answer_id": 44798271, "author": "Harshal", "author_id": 7697425, "author_profile": "https://Stackoverflow.com/users/7697425", "pm_score": 3, "selected": false, "text": "<p>Yes! Parameters and Arguments have different meanings, which can be easily explained as follows:</p>\n\n<p>Function <strong>Parameters</strong> are the names listed in the function definition.</p>\n\n<p>Function <strong>Arguments</strong> are the real values passed to (and received by) the function.</p>\n" }, { "answer_id": 45325837, "author": "Md. Rejaul Karim", "author_id": 7574266, "author_profile": "https://Stackoverflow.com/users/7574266", "pm_score": 0, "selected": false, "text": "<p><strong>Parameters</strong> are variables that are used to store the data that's passed into a function for the function to use. <strong>Arguments</strong> are the actual data that's passed into a function when it is invoked:</p>\n\n<pre><code>// x and y are parameters in this function declaration\nfunction add(x, y) {\n // function body\n var sum = x + y;\n return sum; // return statement\n}\n\n// 1 and 2 are passed into the function as arguments\nvar sum = add(1, 2);\n</code></pre>\n" }, { "answer_id": 46360559, "author": "HEMANT GIRI", "author_id": 8654442, "author_profile": "https://Stackoverflow.com/users/8654442", "pm_score": 4, "selected": false, "text": "<p>Always Remember that:<br />\nArguments are passed while parameters are received.</p>\n" }, { "answer_id": 47738789, "author": "marcusjetson", "author_id": 9022146, "author_profile": "https://Stackoverflow.com/users/9022146", "pm_score": 1, "selected": false, "text": "<p>I thought it through and realized my previous answer was wrong. Here's a much better definition</p>\n\n<p>{<em>Imagine a carton of eggs: A pack of sausage links: And a maid</em> } These represent elements of a Function needed for preparation called : (use any name: Lets say Cooking is the name of my function). </p>\n\n<p>A Maid is a method . </p>\n\n<p>( You must __call_ or ask this <em>method</em> to make breakfast)(The act of making breakfast is a <em>Function</em> called <em>Cooking</em>)_</p>\n\n<p>Eggs and sausages are Parameters :</p>\n\n<p>(because the number of eggs and the number of sausages you want to eat is __variable_ .)_</p>\n\n<p>Your decision is an Argument : </p>\n\n<p>It represents the __Value_ of the chosen number of eggs and/or sausages you are Cooking ._</p>\n\n<p>{<em>Mnemonic</em>}</p>\n\n<p>_\" When you call the maid and ask her to make breakfast, she __argues_ with you about how many eggs and sausages you should eating. She's concerned about your cholesterol\" __</p>\n\n<p>( Arguments , then, are the values for the combination of Parameters you have declared and decided to pass to your Function )</p>\n" }, { "answer_id": 48330590, "author": "Maxim Kitsenko", "author_id": 3607337, "author_profile": "https://Stackoverflow.com/users/3607337", "pm_score": 2, "selected": false, "text": "<p>According to Joseph's Alabahari book \"C# in a Nutshell\" (C# 7.0, p. 49) :</p>\n\n<pre><code>static void Foo (int x)\n{\n x = x + 1; // When you're talking in context of this method x is parameter\n Console.WriteLine (x);\n}\nstatic void Main()\n{\n Foo (8); // an argument of 8. \n // When you're talking from the outer scope point of view\n}\n</code></pre>\n\n<p>In some human languages (afaik Italian, Russian) synonyms are widely used for these terms.</p>\n\n<ul>\n<li><strong>parameter</strong> = <strong>formal parameter</strong></li>\n<li><strong>argument</strong> = <strong>actual parameter</strong></li>\n</ul>\n\n<p>In my university professors use both kind of names.</p>\n" }, { "answer_id": 49361685, "author": "AbstProcDo", "author_id": 7301792, "author_profile": "https://Stackoverflow.com/users/7301792", "pm_score": 1, "selected": false, "text": "<p>It's explained perfectly in <a href=\"https://en.wikipedia.org/wiki/Parameter_(computer_programming)#Parameters_and_arguments\" rel=\"nofollow noreferrer\">Parameter (computer programming) - Wikipedia</a></p>\n\n<p>Loosely, a parameter is a type, and an argument is an instance.</p>\n\n<p>In the function definition <code>f(x) = x*x</code> the variable <code>x</code> is a parameter; in the function call <code>f(2)</code> the value ``2 is the argument of the function. </p>\n\n<p>And <a href=\"https://en.wikipedia.org/wiki/Parameter\" rel=\"nofollow noreferrer\">Parameter - Wikipedia</a></p>\n\n<p>In <a href=\"https://en.wikipedia.org/wiki/Computer_programming\" rel=\"nofollow noreferrer\">computer programming</a>, two notions of <a href=\"https://en.wikipedia.org/wiki/Parameter_(computer_programming)\" rel=\"nofollow noreferrer\">parameter</a> are commonly used, and are referred to as <a href=\"https://en.wikipedia.org/wiki/Parameter_(computer_programming)#Parameters_and_arguments\" rel=\"nofollow noreferrer\">parameters and arguments</a>—or more formally as a <strong>formal parameter</strong> and an <strong>actual parameter</strong>.</p>\n\n<p>For example, in the definition of a function such as</p>\n\n<p><code>y = f(x) = x + 2,</code></p>\n\n<p><em>x</em> is the <em>formal parameter</em> (the <em>parameter</em>) of the defined function.</p>\n\n<p>When the function is evaluated for a given value, as in</p>\n\n<p><code>f(3): or, y = f(3) = 3 + 2 = 5,</code></p>\n\n<p>is the <em>actual parameter</em> (the <em>argument</em>) for evaluation by the defined function; it is a given value (actual value) that is substituted for the <em>formal parameter</em> of the defined function. (In casual usage the terms <em>parameter</em> and <em>argument</em> might inadvertently be interchanged, and thereby used incorrectly.)</p>\n" }, { "answer_id": 50638397, "author": "Manas Singh", "author_id": 9051139, "author_profile": "https://Stackoverflow.com/users/9051139", "pm_score": 0, "selected": false, "text": "<p>You need to get back to basics.Both constructors and methods have parameters and arguments.Many people even call constructors special kind of methods.This is how a method is declared <strong>parameters are used</strong>:</p>\n\n<pre><code> type name(parameters){\n //body of method\n }\n</code></pre>\n\n<p>And this is how a constructor is declared <strong>parameters are used</strong>:</p>\n\n<pre><code>classname(parameters){\n//body\n}\n</code></pre>\n\n<p>Now lets see an example code using which we calculate the volume of a cube:</p>\n\n<pre><code>public class cuboid {\n double width;\n double height;\n double depth;\n\n cuboid(double w,double h,double d) { \n //Here w,h and d are parameters of constructor\n this.width=w;\n this.height=h;\n this.depth=d;\n }\n\n public double volume() {\n double v;\n v=width*height*depth;\n return v;\n }\n public static void main(String args[]){\n cuboid c1=new cuboid(10,20,30);\n //Here 10,20 and 30 are arguments of a constructor\n double vol;\n vol=c1.volume();\n System.out.println(\"Volume is:\"+vol);\n\n }\n }\n</code></pre>\n\n<p>So now you understand that when we call a constructor/method on an object at some place later in the code we pass arguments and not parameters.Hence parameters are limited to the place where the logical object is defined but arguments come into play when a physical object gets actually created.</p>\n" }, { "answer_id": 51231722, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "<p>A <strong>parameter</strong> is a variable in the declaration of the function.</p>\n<p>An <strong>argument</strong> is the actual value of the variable that gets passed to the function.</p>\n<p><a href=\"https://i.stack.imgur.com/9lg1H.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/9lg1H.png\" alt=\"Image of a code sample. Function sum takes parameters param1 and param2. It returns param1 plus param2. The function sum is called with the arguments 5 and 6. The image points out that param1 and param2 are parameters, whereas 5 and 6 are arguments.\" /></a></p>\n" }, { "answer_id": 53567855, "author": "antelove", "author_id": 7656367, "author_profile": "https://Stackoverflow.com/users/7656367", "pm_score": 2, "selected": false, "text": "<p>Parameter is a <strong>variable</strong> in a function definition<br />\nArgument is a <strong>value</strong> of parameter</p>\n\n<pre><code>&lt;?php\n\n /* define function */\n function myFunction($parameter1, $parameter2)\n {\n echo \"This is value of paramater 1: {$parameter1} &lt;br /&gt;\";\n echo \"This is value of paramater 2: {$parameter2} &lt;br /&gt;\";\n }\n\n /* call function with arguments*/\n myFunction(1, 2);\n\n?&gt;\n</code></pre>\n" }, { "answer_id": 59480969, "author": "RobertS supports Monica Cellio", "author_id": 12139179, "author_profile": "https://Stackoverflow.com/users/12139179", "pm_score": 1, "selected": false, "text": "<p>As my background and main environment is C, I will provide some statements/citations to that topic from the actual C standard and an important reference book, from also one of the developers of C, which is often cited and common treated as the first unofficial standard of C:</p>\n<hr />\n<p>The C Programming Language (2nd Edition) by Brian W. Kernighan and Dennis M. Ritchie (April 1988):</p>\n<blockquote>\n<p>Page 25, Section 1.7 - Functions</p>\n<p>We will generally use <em>parameter</em> for a variable named in the parenthesized list in a function definition, and <em>argument</em> for the value used in the call of the function. The terms <em>formal argument</em> and <em>actual argument</em> are sometimes used for the same distinction.</p>\n</blockquote>\n<p>ISO/IEC 9899:2018 (C18):</p>\n<blockquote>\n<p>3.3</p>\n<p><strong>argument</strong></p>\n<p>actual argument</p>\n<p>DEPRECATED: actual parameter</p>\n<p>expression in the comma-separated list bounded by the parentheses in a function call expression, or a sequence of preprocessing tokens in the comma-separated list bounded by the parentheses in a function-like macro invocation.</p>\n</blockquote>\n<hr />\n<blockquote>\n<p>3.16</p>\n<p><strong>parameter</strong></p>\n<p>formal parameter</p>\n<p>DEPRECATED: formal argument</p>\n<p>object declared as part of a function declaration or definition that acquires a value on entry to the function, or an identifier from the comma-separated list bounded by the parentheses immediately following the macro name in a function-like macro definition.</p>\n</blockquote>\n" }, { "answer_id": 59928588, "author": "Tiago Martins Peres", "author_id": 5675325, "author_profile": "https://Stackoverflow.com/users/5675325", "pm_score": 4, "selected": false, "text": "<p>Generally speaking, the terms parameter and argument are used interchangeably to mean information that is passed into a function.</p>\n\n<p>Yet, from a function's perspective:</p>\n\n<ul>\n<li>A <strong>parameter</strong> is the variable listed inside the parentheses in the function definition.</li>\n<li>An <strong>argument</strong> is the value that is sent to the function when it is called.</li>\n</ul>\n" }, { "answer_id": 61764546, "author": "Premraj", "author_id": 1697099, "author_profile": "https://Stackoverflow.com/users/1697099", "pm_score": 0, "selected": false, "text": "<ul>\n<li><strong>Parameter</strong>:\n<ul>\n<li>A value that is already &quot;built in&quot; to a function.</li>\n<li>Parameters can be changed so that the function can be used for other things.</li>\n</ul>\n</li>\n<li><strong>Argument</strong>:\n<ul>\n<li>An input to a function</li>\n<li>A variable that affects a functions result.</li>\n</ul>\n</li>\n</ul>\n<p><a href=\"https://www.mathsisfun.com/definitions/parameter.html\" rel=\"nofollow noreferrer\">Source</a></p>\n" }, { "answer_id": 66705994, "author": "user3857864", "author_id": 3857864, "author_profile": "https://Stackoverflow.com/users/3857864", "pm_score": -1, "selected": false, "text": "<p>This is a <strong>key:value</strong> issue...</p>\n<p>The <strong>parameter</strong> is the key</p>\n<p>The <strong>argument</strong> is the value</p>\n<p>/****************************************/</p>\n<p>Example:</p>\n<p>name: &quot;Peter&quot;</p>\n<p>/********/</p>\n<p>let printName = (<strong>name</strong>) =&gt; console.log(<strong>name</strong>)</p>\n<p>printName(<strong>&quot;Peter&quot;</strong>)</p>\n<p>/********/</p>\n<p>In this case, the <strong>parameter</strong> is &quot;name&quot;, the <strong>argument</strong> is &quot;Peter&quot;</p>\n" }, { "answer_id": 71307720, "author": "Aditya Bhuyan", "author_id": 5256668, "author_profile": "https://Stackoverflow.com/users/5256668", "pm_score": 0, "selected": false, "text": "<p>Consider the below java code.</p>\n<pre><code>public class Test{\n public String hello(String name){\n return &quot;Hello Mr.&quot;+name;\n }\n\n public static void main(String args[]){\n Test test = new Test();\n String myName = &quot;James Bond&quot;;\n test.hello(myName);\n }\n}\n</code></pre>\n<p>The method definition of hello(String name) declares a String <strong>parameter</strong> called name.\nIn the main method we are calling the hello method by passing the <strong>argument</strong> myName.</p>\n<p>So parameter is the placeholder where as argument is the actual value for a method.</p>\n" }, { "answer_id": 72799457, "author": "icc97", "author_id": 327074, "author_profile": "https://Stackoverflow.com/users/327074", "pm_score": 2, "selected": false, "text": "<p>I'm still not happy with all these answers. They all start talking about 'function declarations' and my monkey brain has already wandered off and started thinking about unicorns. That doesn't help me remember at all, it's just the definition.</p>\n<p>I want something that I can immediately and forever hold in my head.</p>\n<p>The <a href=\"https://stackoverflow.com/a/156778/327074\">only answer here</a> that I quickly understand is:</p>\n<blockquote>\n<p>&quot;<strong>A</strong>rguments are <strong>a</strong>ctual values that are passed in&quot;.</p>\n</blockquote>\n<p>Arguments are easier to define and as long as you know what they are then you know parameters are the other.</p>\n<p>The other way I can think of it is:</p>\n<ul>\n<li><strong>Arguments</strong> are the variables <strong>outside</strong> the function</li>\n<li><strong>Parameters</strong> are the variables <strong>inside</strong> the function</li>\n</ul>\n<p>Simplified down to:</p>\n<blockquote>\n<p>Arguments outside, parameters inside</p>\n</blockquote>\n<p>If any one wants to disagree with me, you can leave your arguments outside and bring your parameters in ;)</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5351/" ]
When verbally talking about methods, I'm never sure whether to use the word *argument* or *parameter* or something else. Either way the other people know what I mean, but what's correct, and what's the history of the terms? I'm a C# programmer, but I also wonder whether people use different terms in different languages. For the record I'm self-taught without a background in Computer Science. (Please don't tell me to read [Code Complete](http://www.amazon.co.uk/Code-Complete-Practical-Handbook-Construction/dp/0735619670/) because I'm asking this for the benefit of other people who don't already have a copy of [Steve McConnell](http://www.stevemcconnell.com/)'s marvellous book.) ### Summary The general consensus seems to be that it's OK to use these terms interchangeably in a team environment. Except perhaps when you're defining the precise terminology; then you can also use "*formal* argument/parameter" and "*actual* argument/parameter" to disambiguate.
A parameter is a variable in a method definition. When a method is called, the arguments are the data you pass into the method's parameters. ``` public void MyMethod(string myParam) { } ... string myArg1 = "this is my argument"; myClass.MyMethod(myArg1); ```
156,777
<p>This is a followup question of <a href="https://stackoverflow.com/questions/156697/how-to-encode-characters-from-oracle-to-xml">How to encode characters from Oracle to Xml?</a></p> <p>In my environment here I use Java to serialize the result set to xml. I have no access to the output stream itself, only to a org.xml.sax.ContentHandler.</p> <p>When I try to output characters in a CDATA Section:</p> <p>It happens basically like this:</p> <pre><code>xmlHandler.startElement(uri, lname, "column", attributes); String chars = "&lt;![CDATA["+rs.getString(i)+"]]&gt;"; xmlHandler.characters(chars.toCharArray(), 0, chars.length()); xmlHandler.endElement(uri, lname, "column"); </code></pre> <p>I get this:</p> <pre><code>&lt;column&gt;&amp;lt;![CDATA[33665]]&amp;gt;&lt;/column&gt; </code></pre> <p>But I want this:</p> <pre><code>&lt;column&gt;&lt;![CDATA[33665]]&gt;&lt;/column&gt; </code></pre> <p>So how can I output a CDATA section with a Sax ContentHandler?</p>
[ { "answer_id": 157635, "author": "Josh", "author_id": 2204759, "author_profile": "https://Stackoverflow.com/users/2204759", "pm_score": 4, "selected": true, "text": "<p>It is getting escaped because the handler.characters function is designed to escape and the <code>&lt;![CDATA[</code> part isn't considered part of the value.</p>\n\n<p>You need to use the newly exposed methods in <code>DefaultHandler2</code> or use the <code>TransformerHandler</code> approach where you can set the output key <code>CDATA_SECTION_ELEMENTS</code>, which takes a whitespace delimited list of tag names that should output sub text sections enclosed in CDATA.</p>\n\n<pre><code>StreamResult streamResult = new StreamResult(out);\nSAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();\nTransformerHandler hd = tf.newTransformerHandler();\nTransformer serializer = hd.getTransformer();\nserializer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, \"column\");\nhd.setResult(streamResult);\nhd.startDocument();\nhd.startElement(\"\",\"\",\"column\",atts);\nhd.characters(asdf,0, asdf.length());\nhd.endElement(\"\",\"\",\"column\");\nhd.endDocument();\n</code></pre>\n" }, { "answer_id": 3594066, "author": "Dani", "author_id": 434140, "author_profile": "https://Stackoverflow.com/users/434140", "pm_score": 2, "selected": false, "text": "<p>You should use <code>startCDATA()</code> and <code>endCData()</code> as delimiters, i.e.</p>\n\n<pre><code>xmlHandler.startElement(uri, lname, \"column\", attributes);\nxmlHandler.startCDATA();\nString chars = rs.getString(i);\nxmlHandler.characters(chars.toCharArray(), 0, chars.length());\nxmlHandler.endCDATA();\nxmlHandler.endElement(uri, lname, \"column\");\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21027/" ]
This is a followup question of [How to encode characters from Oracle to Xml?](https://stackoverflow.com/questions/156697/how-to-encode-characters-from-oracle-to-xml) In my environment here I use Java to serialize the result set to xml. I have no access to the output stream itself, only to a org.xml.sax.ContentHandler. When I try to output characters in a CDATA Section: It happens basically like this: ``` xmlHandler.startElement(uri, lname, "column", attributes); String chars = "<![CDATA["+rs.getString(i)+"]]>"; xmlHandler.characters(chars.toCharArray(), 0, chars.length()); xmlHandler.endElement(uri, lname, "column"); ``` I get this: ``` <column>&lt;![CDATA[33665]]&gt;</column> ``` But I want this: ``` <column><![CDATA[33665]]></column> ``` So how can I output a CDATA section with a Sax ContentHandler?
It is getting escaped because the handler.characters function is designed to escape and the `<![CDATA[` part isn't considered part of the value. You need to use the newly exposed methods in `DefaultHandler2` or use the `TransformerHandler` approach where you can set the output key `CDATA_SECTION_ELEMENTS`, which takes a whitespace delimited list of tag names that should output sub text sections enclosed in CDATA. ``` StreamResult streamResult = new StreamResult(out); SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerHandler hd = tf.newTransformerHandler(); Transformer serializer = hd.getTransformer(); serializer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "column"); hd.setResult(streamResult); hd.startDocument(); hd.startElement("","","column",atts); hd.characters(asdf,0, asdf.length()); hd.endElement("","","column"); hd.endDocument(); ```
156,779
<p>I've written a simple SessionItem management class to handle all those pesky null checks and insert a default value if none exists. Here is my GetItem method:</p> <pre><code>public static T GetItem&lt;T&gt;(string key, Func&lt;T&gt; defaultValue) { if (HttpContext.Current.Session[key] == null) { HttpContext.Current.Session[key] = defaultValue.Invoke(); } return (T)HttpContext.Current.Session[key]; } </code></pre> <p>Now, how do I actually use this, passing in the Func&lt;T&gt; as an inline method parameter?</p>
[ { "answer_id": 156789, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "<p>Why don't you pass the default value directly? What use is the functor?</p>\n\n<p>By the way, <code>defaultValue.Invoke()</code> is quite verbose. It's also possible to just write <code>defaultValue()</code>.</p>\n" }, { "answer_id": 156802, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": true, "text": "<p>Since that is a func, a lambda would be the simplest way:</p>\n\n<pre><code>Foo foo = GetItem&lt;Foo&gt;(\"abc\", () =&gt; new Foo(\"blah\"));\n</code></pre>\n\n<p>Where [new Foo(\"blah\")] is the func that is invoked as a default. </p>\n\n<p>You could also simplify to:</p>\n\n<pre><code>return ((T)HttpContext.Current.Session[key]) ?? defaultValue();\n</code></pre>\n\n<p>Where ?? is the null-coalescing operator - if the first arg is non-null, it is returned; otherwise the right hand is evaluated and returned (so defaultValue() isn't invoked unless the item is null).</p>\n\n<p>Finally, if you just want to use the default constructor, then you could add a \"new()\" constraint:</p>\n\n<pre><code>public static T GetItem&lt;T&gt;(string key)\n where T : new()\n{\n return ((T)HttpContext.Current.Session[key]) ?? new T();\n}\n</code></pre>\n\n<p>This is still lazy - the new() is only used if the item was null.</p>\n" }, { "answer_id": 156804, "author": "Rinat Abdullin", "author_id": 47366, "author_profile": "https://Stackoverflow.com/users/47366", "pm_score": 1, "selected": false, "text": "<pre><code>var log = SessionItem.GetItem(\"logger\", () =&gt; NullLog.Instance)\n</code></pre>\n\n<p><strong>Note,</strong> than normally you can skip {T} specification in the GetItem{T} call (if Func{T} returns object of the same type)</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192/" ]
I've written a simple SessionItem management class to handle all those pesky null checks and insert a default value if none exists. Here is my GetItem method: ``` public static T GetItem<T>(string key, Func<T> defaultValue) { if (HttpContext.Current.Session[key] == null) { HttpContext.Current.Session[key] = defaultValue.Invoke(); } return (T)HttpContext.Current.Session[key]; } ``` Now, how do I actually use this, passing in the Func<T> as an inline method parameter?
Since that is a func, a lambda would be the simplest way: ``` Foo foo = GetItem<Foo>("abc", () => new Foo("blah")); ``` Where [new Foo("blah")] is the func that is invoked as a default. You could also simplify to: ``` return ((T)HttpContext.Current.Session[key]) ?? defaultValue(); ``` Where ?? is the null-coalescing operator - if the first arg is non-null, it is returned; otherwise the right hand is evaluated and returned (so defaultValue() isn't invoked unless the item is null). Finally, if you just want to use the default constructor, then you could add a "new()" constraint: ``` public static T GetItem<T>(string key) where T : new() { return ((T)HttpContext.Current.Session[key]) ?? new T(); } ``` This is still lazy - the new() is only used if the item was null.
156,800
<p>I have created a nice silverlight control doing exactly what I want it to do, and it looks great :) When I host it in the test projects ASPX sample file or the HTML sample file it shows up nicely.</p> <p>I now have to use the control in my existing ASP.NET 2.0 project, which has a fancy design. The problem I'm having is that the control don't show up exactly how it should:</p> <ul> <li>The loading progress don't show</li> <li>The control usually don't become visible before I move my mouse over the aria where it's contained</li> </ul> <p>Obviously it's something with my HTML/CSS design causing this, but it will be extremely time consuming to find the issue - so does anyone have knowledge in this area? What are the rules around how to make sure the control is displayed properly? What CSS properties should be used?</p> <p>PS: Since I have a 2.0 app, I'm using the object tag approach to Silverlight, and it's contained in a DIV with height and width set in style.</p> <p>Code snippet was requested. It's something like this (basically a copy of the HTML test page from the silverlight test project (which work perfectly)):</p> <pre><code>&lt;div id="silverlightControlHost" style="height: 300px; width: 750px;"&gt; &lt;object data="data:application/x-silverlight," type="application/x-silverlight-2-b2" width="100%" height="100%"&gt; &lt;param name="source" value="Contiki.SilverLight.FileUploader.xap" /&gt; &lt;param name="onerror" value="onSilverlightError" /&gt; &lt;param name="background" value="white" /&gt; &lt;a href="http://go.microsoft.com/fwlink/?LinkID=115261" style="text-decoration: none;"&gt; &lt;img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none" /&gt; &lt;/a&gt; &lt;/object&gt; &lt;iframe style='visibility: hidden; height: 0; width: 0; border: 0px'&gt;&lt;/iframe&gt; &lt;/div&gt; </code></pre> <p>This DIV is contained in a cell in a table, which again is part of a larger design. There's a lot of CSS as mentioned. Don't know if this helps...</p>
[ { "answer_id": 158377, "author": "Adam Kinney", "author_id": 1973, "author_profile": "https://Stackoverflow.com/users/1973", "pm_score": 0, "selected": false, "text": "<p>CSS issues can be difficult to debug sometimes. Is the behavior the same in different browsers? Is your CSS using \"float\"s anywhere? Does the app work properly on the same page outside of the table and then outside of the div?</p>\n" }, { "answer_id": 163349, "author": "Bryant", "author_id": 10893, "author_profile": "https://Stackoverflow.com/users/10893", "pm_score": 0, "selected": false, "text": "<p>As Adam says, CSS issues are a real PITA. Typically when I run into something like this I start by pointing to a blank CSS instead of the \"fancy\" one and then start adding the styles back in until I'm able to reproduce the issue. </p>\n" }, { "answer_id": 225662, "author": "Torbjørn", "author_id": 22621, "author_profile": "https://Stackoverflow.com/users/22621", "pm_score": 3, "selected": true, "text": "<p>Found the cause myself...</p>\n\n<p>It turns out Silverlight has a display problem when the control is placed in a html table. <a href=\"http://silverlight.net/forums/p/20863/72280.aspx\" rel=\"nofollow noreferrer\">Found information about this on the silverlight forum</a>. It was about the beta 2, but I have upgraded to the release version, and it's still a problem.</p>\n\n<blockquote>\n <p>Try this. Add a height and a width to\n the table containing the Silverlight\n control. You may also want to add a\n single character of white space inside\n the TD containing the control.</p>\n \n <p>Basically when the table was rendered\n it couldn't 'see' the size of the\n contents so it either didn't render at\n all or only rendered to the size of a\n single white-space character.</p>\n \n <p>-- John Stockton</p>\n</blockquote>\n\n<p>My design is quite complex with nested tables, so I haven't actually been able to make it work yet.</p>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>The actual fix I ended up implementing was a small JavaScript that \"refreshes\" the containing &lt;DIV&gt;. Here it is:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n function refreshSL()\n {\n var div = document.getElementById('silverlightControlHost');\n div.style.display = 'block';\n }\n refreshSL();\n&lt;/script&gt;\n</code></pre>\n\n<p>I placed this in my HTML below the actual SL markup, and then it worked (I guess calling it on the page loaded event would be the proper thing to do.</p>\n" }, { "answer_id": 741205, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>LOL</p>\n\n<p>I had the same exact problem and it was driving me mad. The problem was isolated to Internet Explorer. Works fine in all other browsers (even Opera).</p>\n\n<p>Your solution is a hack for sure. Since this is really a work around for a bug in IE you can officially get away with it.</p>\n\n<p>Technically we should not be using tables for layout but in the real world it is the only way to get things to work consistantly cross browsers.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22621/" ]
I have created a nice silverlight control doing exactly what I want it to do, and it looks great :) When I host it in the test projects ASPX sample file or the HTML sample file it shows up nicely. I now have to use the control in my existing ASP.NET 2.0 project, which has a fancy design. The problem I'm having is that the control don't show up exactly how it should: * The loading progress don't show * The control usually don't become visible before I move my mouse over the aria where it's contained Obviously it's something with my HTML/CSS design causing this, but it will be extremely time consuming to find the issue - so does anyone have knowledge in this area? What are the rules around how to make sure the control is displayed properly? What CSS properties should be used? PS: Since I have a 2.0 app, I'm using the object tag approach to Silverlight, and it's contained in a DIV with height and width set in style. Code snippet was requested. It's something like this (basically a copy of the HTML test page from the silverlight test project (which work perfectly)): ``` <div id="silverlightControlHost" style="height: 300px; width: 750px;"> <object data="data:application/x-silverlight," type="application/x-silverlight-2-b2" width="100%" height="100%"> <param name="source" value="Contiki.SilverLight.FileUploader.xap" /> <param name="onerror" value="onSilverlightError" /> <param name="background" value="white" /> <a href="http://go.microsoft.com/fwlink/?LinkID=115261" style="text-decoration: none;"> <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none" /> </a> </object> <iframe style='visibility: hidden; height: 0; width: 0; border: 0px'></iframe> </div> ``` This DIV is contained in a cell in a table, which again is part of a larger design. There's a lot of CSS as mentioned. Don't know if this helps...
Found the cause myself... It turns out Silverlight has a display problem when the control is placed in a html table. [Found information about this on the silverlight forum](http://silverlight.net/forums/p/20863/72280.aspx). It was about the beta 2, but I have upgraded to the release version, and it's still a problem. > > Try this. Add a height and a width to > the table containing the Silverlight > control. You may also want to add a > single character of white space inside > the TD containing the control. > > > Basically when the table was rendered > it couldn't 'see' the size of the > contents so it either didn't render at > all or only rendered to the size of a > single white-space character. > > > -- John Stockton > > > My design is quite complex with nested tables, so I haven't actually been able to make it work yet. **UPDATE:** The actual fix I ended up implementing was a small JavaScript that "refreshes" the containing <DIV>. Here it is: ``` <script type="text/javascript"> function refreshSL() { var div = document.getElementById('silverlightControlHost'); div.style.display = 'block'; } refreshSL(); </script> ``` I placed this in my HTML below the actual SL markup, and then it worked (I guess calling it on the page loaded event would be the proper thing to do.
156,810
<p>What is the best way to download files to local hard drive when logged in to another computer using ssh in bash. I'm aware of sftp, but it is not convienent, e.g. it lacks tab completion of directory names. I'm using Ubuntu 8.04.1 . I don't have a public IP and would not like to setup dynamic Dynamic DNS solution.</p>
[ { "answer_id": 156822, "author": "Ronny Brendel", "author_id": 14114, "author_profile": "https://Stackoverflow.com/users/14114", "pm_score": 0, "selected": false, "text": "<p>I don't know.</p>\n\n<p>I'd $ scp host:file locallocation</p>\n" }, { "answer_id": 156850, "author": "Horst Gutmann", "author_id": 22312, "author_profile": "https://Stackoverflow.com/users/22312", "pm_score": 0, "selected": false, "text": "<p>As far as I know there is no simply scp-on-steroids that lets you autocomplete on remote folder-structures. If you just want to basically mount a remote folder, take a look at <a href=\"http://fuse.sourceforge.net/sshfs.html\" rel=\"nofollow noreferrer\">sshfs</a>. Or just try mounting a remote directory with ssh://... within Nautilus. </p>\n" }, { "answer_id": 156878, "author": "hangy", "author_id": 11963, "author_profile": "https://Stackoverflow.com/users/11963", "pm_score": 0, "selected": false, "text": "<p>I actually like to use the command line SCP client. :) I do not know how it does this, but my SCP on Ubuntu (from openssh-client 1:4.7p1-8ubuntu1.2) actually does tab-completion of remote directories and files on hosts where I usually auth via public key.</p>\n" }, { "answer_id": 156881, "author": "Sam Stokes", "author_id": 20131, "author_profile": "https://Stackoverflow.com/users/20131", "pm_score": 4, "selected": true, "text": "<p>I'm also running Ubuntu 8.04.1, and if I type</p>\n\n<pre><code>$ scp [email protected]:.bashr&lt;TAB&gt;\n</code></pre>\n\n<p>I do indeed get tab completion (i.e. bash is sshing to my server and getting completion results from the filesystem there). Then</p>\n\n<pre><code>$ scp [email protected]:.bashrc .\n</code></pre>\n\n<p>copies my .bashrc from my server to the current directory on my local machine.</p>\n\n<p>If you don't get this, try <code>sudo apt-get install bash-completion</code>, and check that your .bashrc contains the following lines (mine did by default):</p>\n\n<pre><code># enable programmable completion features (you don't need to enable\n# this, if it's already enabled in /etc/bash.bashrc and /etc/profile\n# sources /etc/bash.bashrc).\nif [ -f /etc/bash_completion ]; then\n . /etc/bash_completion\nfi\n</code></pre>\n" }, { "answer_id": 185600, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://matt.ucc.asn.au/ssh-xfer/\" rel=\"nofollow noreferrer\">ssh-xfer</a> is what you are looking for. Once you have it set up, you can type (from within the <code>ssh</code> session on the remote machine):</p>\n\n<pre>$ ssh-xfer foo.txt</pre>\n\n<p>and foo.txt will magically show up on your local machine.</p>\n" }, { "answer_id": 303400, "author": "Derick Schoonbee", "author_id": 39114, "author_profile": "https://Stackoverflow.com/users/39114", "pm_score": 1, "selected": false, "text": "<p>How about FISH? ***Fi***le transfer over ***Sh***ell -\nYou can use Midnight Commander in your console:</p>\n\n<pre><code>$ sudo apt-get install mc\n$ mc\n</code></pre>\n\n<p>Then hit <strong><em>F9</em></strong>; Right (for the Right panel) -> Shell link\nType in the ssh link of the remote host. At the prompt <strong><em>enter machine name</em></strong> specify:</p>\n\n<pre><code>user@host\n</code></pre>\n\n<p>The system will prompt for the password (or auto login if your SSH keys are setup for that)</p>\n\n<p>Now you can browse the remote filesystem, select and copy over (F5) as you wish.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11439/" ]
What is the best way to download files to local hard drive when logged in to another computer using ssh in bash. I'm aware of sftp, but it is not convienent, e.g. it lacks tab completion of directory names. I'm using Ubuntu 8.04.1 . I don't have a public IP and would not like to setup dynamic Dynamic DNS solution.
I'm also running Ubuntu 8.04.1, and if I type ``` $ scp [email protected]:.bashr<TAB> ``` I do indeed get tab completion (i.e. bash is sshing to my server and getting completion results from the filesystem there). Then ``` $ scp [email protected]:.bashrc . ``` copies my .bashrc from my server to the current directory on my local machine. If you don't get this, try `sudo apt-get install bash-completion`, and check that your .bashrc contains the following lines (mine did by default): ``` # enable programmable completion features (you don't need to enable # this, if it's already enabled in /etc/bash.bashrc and /etc/profile # sources /etc/bash.bashrc). if [ -f /etc/bash_completion ]; then . /etc/bash_completion fi ```
156,815
<p>In a <a href="https://stackoverflow.com/questions/9033#9099">question answer</a> I find the following coding tip:-</p> <p>2) simple lambdas with one parameter:</p> <pre><code>x =&gt; x.ToString() //simplify so many calls </code></pre> <p>As someone who has not yet used 3.0 I don't really understand this tip but it looks interesting so I would appreciate an expantion on how this simplifies calls with a few examples.</p> <p>I've researched lambdas so I <strong>think</strong> I know what they do, however I <strong>may</strong> not fully understand so a <strong>little</strong> unpacking might also be in order.</p>
[ { "answer_id": 156823, "author": "Jacob", "author_id": 22107, "author_profile": "https://Stackoverflow.com/users/22107", "pm_score": 2, "selected": false, "text": "<p>This basically expands to:</p>\n\n<pre><code>private string Lambda(object x) {\n return x.ToString();\n}\n</code></pre>\n" }, { "answer_id": 156838, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "<p>When you need to create an instance of a delegate which has a single parameter, lambda expressions allow you to create that delegate \"inline\" in a very concise manner. For instance, here's code to find a particular person in a list, by their name:</p>\n\n<pre><code>List&lt;Person&gt; list = new List&lt;Person&gt;();\n// [..] Populate list here\nPerson jon = list.Find(p =&gt; p.Name == \"Jon\");\n</code></pre>\n\n<p>In C# 2.0 you could use an anonymous method which was a little bit more longwinded, but not <em>too</em> bad:</p>\n\n<pre><code>List&lt;Person&gt; list = new List&lt;Person&gt;();\n// [..] Populate list here\nPerson jon = list.Find(delegate(Person p) { return p.Name == \"Jon\"; });\n</code></pre>\n\n<p>In C# 1.0 you'd have to create a whole extra method. In addition, if you wanted to parameterise it, you'd have to create a different type, whereas anonymous methods and lambda expressions capture their executing environment (local variables etc) so they act like closures:</p>\n\n<pre><code>public Person FindByName(List&lt;Person&gt; list, String name)\n{\n return list.Find(p =&gt; p.Name == name); // The \"name\" variable is captured\n}\n</code></pre>\n\n<p>There's more about this in <a href=\"http://csharpindepth.com/Articles/Chapter5/Closures.aspx\" rel=\"nofollow noreferrer\">my article about closures</a>.</p>\n\n<p>While passing delegates into methods isn't terribly common in C# 2.0 and .NET 2.0, it's a large part of the basis of LINQ - so you tend to use it a lot in C# 3.0 with .NET 3.5.</p>\n" }, { "answer_id": 156839, "author": "Rinat Abdullin", "author_id": 47366, "author_profile": "https://Stackoverflow.com/users/47366", "pm_score": 0, "selected": false, "text": "<pre><code>string delegate(TypeOfX x)\n{\n return x.ToString();\n}\n</code></pre>\n" }, { "answer_id": 156845, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "<p>Are you familiar with C# 2.0 anonymous methods? These two calls are equivalent (assuming SomeMethod accepts a delegate etc):</p>\n\n<pre><code>SomeMethod(x =&gt; x.ToString());\n\nSomeMethod(delegate (SomeType x) { return x.ToString();});\n</code></pre>\n\n<p>I know which I'd rather type...</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22284/" ]
In a [question answer](https://stackoverflow.com/questions/9033#9099) I find the following coding tip:- 2) simple lambdas with one parameter: ``` x => x.ToString() //simplify so many calls ``` As someone who has not yet used 3.0 I don't really understand this tip but it looks interesting so I would appreciate an expantion on how this simplifies calls with a few examples. I've researched lambdas so I **think** I know what they do, however I **may** not fully understand so a **little** unpacking might also be in order.
When you need to create an instance of a delegate which has a single parameter, lambda expressions allow you to create that delegate "inline" in a very concise manner. For instance, here's code to find a particular person in a list, by their name: ``` List<Person> list = new List<Person>(); // [..] Populate list here Person jon = list.Find(p => p.Name == "Jon"); ``` In C# 2.0 you could use an anonymous method which was a little bit more longwinded, but not *too* bad: ``` List<Person> list = new List<Person>(); // [..] Populate list here Person jon = list.Find(delegate(Person p) { return p.Name == "Jon"; }); ``` In C# 1.0 you'd have to create a whole extra method. In addition, if you wanted to parameterise it, you'd have to create a different type, whereas anonymous methods and lambda expressions capture their executing environment (local variables etc) so they act like closures: ``` public Person FindByName(List<Person> list, String name) { return list.Find(p => p.Name == name); // The "name" variable is captured } ``` There's more about this in [my article about closures](http://csharpindepth.com/Articles/Chapter5/Closures.aspx). While passing delegates into methods isn't terribly common in C# 2.0 and .NET 2.0, it's a large part of the basis of LINQ - so you tend to use it a lot in C# 3.0 with .NET 3.5.
156,833
<p>I need to consume a wcf service dynamically when all i know is its URL. I do not have the option of creating a service reference or web reference as my client side code picks up the URL from a config file. What classes and methods can i use from the System.ServiceModel namespace for doing so.</p>
[ { "answer_id": 156848, "author": "Rinat Abdullin", "author_id": 47366, "author_profile": "https://Stackoverflow.com/users/47366", "pm_score": 1, "selected": false, "text": "<p>If you know the contract then you can do something like:</p>\n\n<pre><code>using (WebChannelFactory&lt;IService&gt; wcf = new WebChannelFactory&lt;IService&gt;(new Uri(\"http://localhost:8000/Web\")))\n</code></pre>\n\n<p>More <a href=\"http://msdn.microsoft.com/en-us/library/bb412196.aspx\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 157390, "author": "tomasr", "author_id": 10292, "author_profile": "https://Stackoverflow.com/users/10292", "pm_score": 2, "selected": false, "text": "<p>If you don't have the service interface, you must, at the very least, have an idea as to what the messages the server expects look like; otherwise it be pretty hard to do :)</p>\n\n<p>But there is certainly a way to do that. You can start by creating the raw message the server expects as input, and create it in a Message object (I mean System.ServiceModel.Channels.Message). Make sure that you set all the necessary headers to it, depending on what binding you expect to use to call the client (like setting the right credentials, the right MessageVersion and so on).</p>\n\n<p>Then you can simply create a channel factory using one of the standard, generic channel shapes like IRequestChannel or IInputChannel (for one-way services), and use the channel factory to create a new channel and invoke the service. I.e. something like:</p>\n\n<pre><code>Message input = Message.CreateMessage( .... );\n\nChannelFactory&lt;IRequestChannel&gt; factory = new ChannelFactory&lt;IRequestChannel&gt;(binding, endpoint);\nIRequestChannel channel - factory.CreateChannel();\n\nMessage output = channel.Send(input);\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16439/" ]
I need to consume a wcf service dynamically when all i know is its URL. I do not have the option of creating a service reference or web reference as my client side code picks up the URL from a config file. What classes and methods can i use from the System.ServiceModel namespace for doing so.
If you don't have the service interface, you must, at the very least, have an idea as to what the messages the server expects look like; otherwise it be pretty hard to do :) But there is certainly a way to do that. You can start by creating the raw message the server expects as input, and create it in a Message object (I mean System.ServiceModel.Channels.Message). Make sure that you set all the necessary headers to it, depending on what binding you expect to use to call the client (like setting the right credentials, the right MessageVersion and so on). Then you can simply create a channel factory using one of the standard, generic channel shapes like IRequestChannel or IInputChannel (for one-way services), and use the channel factory to create a new channel and invoke the service. I.e. something like: ``` Message input = Message.CreateMessage( .... ); ChannelFactory<IRequestChannel> factory = new ChannelFactory<IRequestChannel>(binding, endpoint); IRequestChannel channel - factory.CreateChannel(); Message output = channel.Send(input); ```
156,835
<p>I have inherited some code for a custom CMS that is a little out of my league and keep stumbling over the same errors, Notice: Undefined variable: media in /Applications/MAMP/htdocs/Chapman/Chapman_cms/admin/team-2.php on line 48. This is supposed to create new users and edit old users. However, it does not work when I try and add a new user.</p> <p>Below is the pertinant code:</p> <pre><code>$db = new database("mysql",$dbHost,$dbName,$dbUser,$dbPass); $target = 'add'; if ($_GET['task'] == 'edit') { $media = $db-&gt;get_row(edit_media_item($db, $_GET['team_id'])); $target = 'update'; &lt;p&gt;&lt;label for="copy"&gt;Full Name:&lt;/label&gt; &lt;input type="text" name="title" value="&lt;?=$media['title']?&gt;" /&gt; &lt;textarea name="media" id="media" cols="30" rows="5" style="width: 100%"&gt;&lt;?=$media['copy']?&gt;&lt;/textarea&gt;&lt;/p&gt; &lt;input type="hidden" name="process" value="&lt;?=$target.",copy,4,team-1,".$media['id'].""?&gt;"&gt; &lt;p&gt;&lt;input type="submit" name="save" value="Submit" /&gt; &lt;input type="reset" name="reset" value="Reset" /&gt;&lt;/p&gt; &lt;/form&gt; </code></pre> <p>Any help would be much appreciated.</p>
[ { "answer_id": 156841, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 1, "selected": false, "text": "<p>The notice is irrelevant, but this code doesn't create anything. That happens on the page it is submitted to. Look at the if statement on the first few lines. I guess you need to call it with task=edit in the URL.</p>\n" }, { "answer_id": 156846, "author": "f13o", "author_id": 20288, "author_profile": "https://Stackoverflow.com/users/20288", "pm_score": 2, "selected": false, "text": "<p>It may be hard to help you like this, but, I would see where this $db->get_row() call goes and what it returns (using var_dump() or something...)</p>\n\n<p>As general tip, I would recommend setting up debugger in your system, so you can trace calls. On windows platform I use xdebug with WinCacheGrind to trace call when I am unsure about call hierarchy. On Linux, setup is similar (xdebug,kcachegrind...).</p>\n" }, { "answer_id": 156882, "author": "Lasar", "author_id": 9438, "author_profile": "https://Stackoverflow.com/users/9438", "pm_score": 0, "selected": false, "text": "<p>The code you posted does not do any creating, so that problem does not stemfrom this bit of code.</p>\n\n<p>The undefined notice is from the <code>&lt;?=$media['copy']?&gt;</code> bit. $media was never defined. If this is not an issue, ignore it and tell PHP to not output notices. This isn't exactly good practice, but if you're not getting paid to fix every little thing, I'd say it's a feasible alternative.</p>\n\n<p>To suppress notices add this code anywhere before the notices occur or better yet into a global include:</p>\n\n<pre><code>error_reporting(E_ERROR | E_WARNING | E_PARSE);\n</code></pre>\n\n<p>For more info: <a href=\"http://www.php.net/error_reporting\" rel=\"nofollow noreferrer\">http://www.php.net/error_reporting</a></p>\n" }, { "answer_id": 156909, "author": "Ólafur Waage", "author_id": 22459, "author_profile": "https://Stackoverflow.com/users/22459", "pm_score": 3, "selected": false, "text": "<p>To remove the notice in the right way is to do this with the code</p>\n\n<pre><code>&lt;?php if(isset($media['copy'])){ echo $media['copy']; } ?&gt;\n</code></pre>\n" }, { "answer_id": 159415, "author": "SeanDowney", "author_id": 5261, "author_profile": "https://Stackoverflow.com/users/5261", "pm_score": 1, "selected": false, "text": "<p>you can also use the at symbol like this:</p>\n\n<pre><code>if($_GET['undefined_key']) {\n // blah...\n}\n\nif(@$_GET['undefined_key']) {\n // blah...\n}\n</code></pre>\n\n<p>it suppresses warnings, however some will argue that the best time to use the at symbol is to avoid warnings you couldn't do otherwise.</p>\n" }, { "answer_id": 161297, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 0, "selected": false, "text": "<p>That error message is not from this code.</p>\n\n<p><code>$media</code> is assigned in line 6 of the code you provided (<code>$media = $db-&gt;get_row(..)</code>). I'm guessing that you either have stripped out the relevant code (Which is line 48, give/take), or it's the wrong file (Is this from <code>/Applications/MAMP/htdocs/Chapman/Chapman_cms/admin/team-2.php</code>?).</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have inherited some code for a custom CMS that is a little out of my league and keep stumbling over the same errors, Notice: Undefined variable: media in /Applications/MAMP/htdocs/Chapman/Chapman\_cms/admin/team-2.php on line 48. This is supposed to create new users and edit old users. However, it does not work when I try and add a new user. Below is the pertinant code: ``` $db = new database("mysql",$dbHost,$dbName,$dbUser,$dbPass); $target = 'add'; if ($_GET['task'] == 'edit') { $media = $db->get_row(edit_media_item($db, $_GET['team_id'])); $target = 'update'; <p><label for="copy">Full Name:</label> <input type="text" name="title" value="<?=$media['title']?>" /> <textarea name="media" id="media" cols="30" rows="5" style="width: 100%"><?=$media['copy']?></textarea></p> <input type="hidden" name="process" value="<?=$target.",copy,4,team-1,".$media['id'].""?>"> <p><input type="submit" name="save" value="Submit" /> <input type="reset" name="reset" value="Reset" /></p> </form> ``` Any help would be much appreciated.
To remove the notice in the right way is to do this with the code ``` <?php if(isset($media['copy'])){ echo $media['copy']; } ?> ```
156,852
<p>Ok, here's one for the Java/JavaScript gurus:</p> <p>In my app, one of the controllers passes a TreeMap to it's JSP. This map has car manufacturer's names as keys and Lists of Car objects as values. These Car objects are simple beans containing the car's name, id, year of production etc. So, the map looks something like this (this is just an example, to clarify things a bit):</p> <p>Key: Porsche<br/> Value: List containing three Car objects(for example 911,Carrera,Boxter with their respectable years of production and ids)<br/> Key: Fiat<br/> Value: List containing two Car objects(for example, Punto and Uno)<br/> etc...</p> <p>Now, in my JSP i have two comboboxes. One should receive a list of car manufacturers(keys from the map - this part I know how to do), and the other one should <strong>dynamicaly change</strong> to display the names of the cars when the user selects a certain manufacturer from the first combobox. So, for example, user selects a "Porsche" in the first combobox, and the second immediately displays "911, Carrera, Boxter"...</p> <p>After spending a couple of days trying to find out how to do this, I'm ready to admit defeat. I tried out a lot of different things but every time I hit a wall somewehere along the way. Can anybody suggest how I should approach this one? Yes, I'm a JavaScript newbie, if anybody was wondering... <br/></p> <p>EDIT: I've retagged this as a code-challenge. Kudos to anybody who solves this one without using any JavaScript framework (like JQuery).</p>
[ { "answer_id": 156865, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Are you using Struts?</p>\n\n<p>You will need some JavaScript trickery (or AJAX) to accomplish this.</p>\n\n<p>What you'd need to do is, somewhere in your JavaScript code (leaving aside how you generate it for the minute):</p>\n\n<pre><code>var map = {\n 'porsche': [ 'boxter', '911', 'carrera' ],\n 'fiat': ['punto', 'uno']\n};\n</code></pre>\n\n<p>This is basically a copy of your server-side data structure, i.e. a map keyed by manufacturer, each value having an array of car types.</p>\n\n<p>Then, in your onchange event for the manufacturers, you'd need to get the array from the map defined above, and then create a list of options from that. (Check out devguru.com - it has a lot of helpful information about standard JavaScript objects).</p>\n\n<p>Depending on how big your list of cars is, though, it might be best to go the AJAX route.</p>\n\n<p>You'd need to create a new controller which looked up the list of cars types given a manufacturer, and then forward on to a JSP which returned <a href=\"http://www.json.org/\" rel=\"nofollow noreferrer\">JSON</a> (it doesn't have to be JSON, but it works quite well for me).</p>\n\n<p>Then, use a library such as <a href=\"http://jquery.com/\" rel=\"nofollow noreferrer\">jQuery</a> to retrieve the list of cars in your onchange event for the list of manufacturers. (jQuery is an excellent JavaScript framework to know - it does make development with JavaScript much easier. The documentation is very good).</p>\n\n<p>I hope some of that makes sense?</p>\n" }, { "answer_id": 160603, "author": "Chase Seibert", "author_id": 7679, "author_profile": "https://Stackoverflow.com/users/7679", "pm_score": 0, "selected": false, "text": "<p>How about something like this, using prototype? First, your select box of categories:</p>\n\n<pre><code>&lt;SELECT onchange=\"changeCategory(this.options[this.selectedIndex].value); return false;\"&gt;\n &lt;OPTION value=\"#categoryID#\"&gt;#category#&lt;/OPTION&gt;\n ...\n</code></pre>\n\n<p>Then, you output N different select boxes, one for each of the sub-categories:</p>\n\n<pre><code>&lt;SELECT name=\"myFormVar\" class=\"categorySelect\"&gt;\n... \n</code></pre>\n\n<p>Your changeCategory javascript function disables all selects with class categorySelect, and then enables just the one for your current categoryID. </p>\n\n<pre><code>// Hide all category select boxes except the new one\nfunction changeCategory(categoryID) {\n\n $$(\"select.categorySelect\").each(function (select) {\n select.hide();\n select.disable();\n });\n\n $(categoryID).show();\n $(categoryID).enable();\n}\n</code></pre>\n\n<p>When you hide/disable like this in prototype, it not only hides it on the page, but it will keep that FORM variable from posting. So even though you have N selects with the same FORM variable name (myFormVar), only the active one posts.</p>\n" }, { "answer_id": 166365, "author": "extraneon", "author_id": 24582, "author_profile": "https://Stackoverflow.com/users/24582", "pm_score": 0, "selected": false, "text": "<p>Not that long ago I thought about something similar.</p>\n\n<p>Using jQuery and the TexoTela add-on it wasn't all that difficult.</p>\n\n<p>First, you have a data structure like the map mentioned above:</p>\n\n<pre><code>var map = {\n 'porsche': [ 'boxter', '911', 'carrera' ],\n 'fiat': ['punto', 'uno']\n}; \n</code></pre>\n\n<p>Your HTML should look comparable to:</p>\n\n<pre><code>&lt;select size=\"4\" id=\"manufacturers\"&gt;\n&lt;/select&gt;\n&lt;select size=\"4\" id=\"models\"&gt;\n&lt;/select&gt;\n</code></pre>\n\n<p>Then, you fill the first combo with jQuery code like:</p>\n\n<pre><code>$(document).ready(\n function() {\n $(\"#bronsysteem\").change( manufacturerSelected() );\n } );\n);\n</code></pre>\n\n<p>where manufacturerSelected is the callback registered on the onChange event</p>\n\n<pre><code>function manufacturerSelected() {\n newSelection = $(\"#manufacturers\").selectedValues();\n if (newSelection.length != 1) {\n alert(\"Expected a selection!\");\n return; \n }\n newSelection = newSelection[0];\n fillModels(newSelection); \n}\n\nfunction fillModels(manufacterer) {\n var models = map[manufacturer];\n\n $(\"models\").removeOption(/./); // Empty combo\n\n for(modelId in models) {\n model = models[modelId];\n $(\"models\").addOption(model,model); // Value, Text\n }\n}\n</code></pre>\n\n<p>This should do the trick. </p>\n\n<p>Please note that there may be syntax errors in there; I have edited my code to reflect your use case and had to strip\nquite a lot out.</p>\n\n<p>If this helps I would appreciate a comment. </p>\n" }, { "answer_id": 170323, "author": "extraneon", "author_id": 24582, "author_profile": "https://Stackoverflow.com/users/24582", "pm_score": 0, "selected": false, "text": "<p>As an add-on on my previous post; You can put a script tag in your JSP where you iterate over your map. An example about iterating over maps can be found in <a href=\"http://www.onjava.com/pub/a/onjava/2003/07/30/jakartastruts.html?page=2\" rel=\"nofollow noreferrer\">Maps in Struts</a>.</p>\n\n<p>What you would like to achieve (if you don't care about form submission) is I think something like:</p>\n\n<pre><code>&lt;script&gt;\n var map = {\n &lt;logic:iterate id=\"entry\" name=\"myForm\" property=\"myMap\"&gt;\n '&lt;bean:write name=\" user\" property=\"key\"/&gt;' : [\n &lt;logic:iterate id=\"model\" name=\"entry\" property=\"value\"&gt;\n '&lt;bean:write name=\" model\" property=\"name\"/&gt;' ,\n &lt;/logic:iterate&gt;\n ] ,\n &lt;/logic:iterate&gt;\n };\n&lt;/script&gt;\n</code></pre>\n\n<p>You still have some superfuous \",\" which you might wish to prevent, but I think this should do the trick.</p>\n" }, { "answer_id": 179171, "author": "extraneon", "author_id": 24582, "author_profile": "https://Stackoverflow.com/users/24582", "pm_score": 2, "selected": false, "text": "<p>I just love a challenge.</p>\n\n<p>No jQuery, just plain javascript, tested on Safari.</p>\n\n<p>I'd like to add the following remarks in advance:</p>\n\n<ul>\n<li>It's faily long due to the error\nchecking. </li>\n<li>Two parts are generated;\nthe first script node with the Map\nand the contents of the manufacterer\nSELECT </li>\n<li>Works on My Machine (TM)\n(Safari/OS X) </li>\n<li>There is no (css)\nstyling applied. I have bad taste so\nit's no use anyway.</li>\n</ul>\n\n<p>.</p>\n\n<pre><code>&lt;body&gt;\n &lt;script&gt;\n // DYNAMIC\n // Generate in JSP\n // You can put the script tag in the body\n var modelsPerManufacturer = {\n 'porsche' : [ 'boxter', '911', 'carrera' ],\n 'fiat': [ 'punto', 'uno' ] \n };\n &lt;/script&gt;\n\n &lt;script&gt;\n // STATIC\n function setSelectOptionsForModels(modelArray) {\n var selectBox = document.myForm.models;\n\n for (i = selectBox.length - 1; i&gt;= 0; i--) {\n // Bottom-up for less flicker\n selectBox.remove(i); \n }\n\n for (i = 0; i&lt; modelArray.length; i++) {\n var text = modelArray[i];\n var opt = new Option(text,text, false, false);\n selectBox.add(opt);\n } \n }\n\n function setModels() {\n var index = document.myForm.manufacturer.selectedIndex;\n if (index == -1) {\n return;\n }\n\n var manufacturerOption = document.myForm.manufacturer.options[index];\n if (!manufacturerOption) {\n // Strange, the form does not have an option with given index.\n return;\n }\n manufacturer = manufacturerOption.value;\n\n var modelsForManufacturer = modelsPerManufacturer[manufacturer];\n if (!modelsForManufacturer) {\n // This modelsForManufacturer is not in the modelsPerManufacturer map\n return; // or alert\n } \n setSelectOptionsForModels(modelsForManufacturer);\n }\n\n function modelSelected() {\n var index = document.myForm.models.selectedIndex;\n if (index == -1) {\n return;\n }\n alert(\"You selected \" + document.myForm.models.options[index].value);\n }\n &lt;/script&gt;\n &lt;form name=\"myForm\"&gt;\n &lt;select onchange=\"setModels()\" id=\"manufacturer\" size=\"5\"&gt;\n &lt;!-- Options generated by the JSP --&gt;\n &lt;!-- value is index of the modelsPerManufacturer map --&gt;\n &lt;option value=\"porsche\"&gt;Porsche&lt;/option&gt;\n &lt;option value=\"fiat\"&gt;Fiat&lt;/option&gt;\n &lt;/select&gt;\n\n &lt;select onChange=\"modelSelected()\" id=\"models\" size=\"5\"&gt;\n &lt;!-- Filled dynamically by setModels --&gt;\n &lt;/select&gt;\n &lt;/form&gt;\n\n&lt;/body&gt;\n</code></pre>\n" }, { "answer_id": 183922, "author": "extraneon", "author_id": 24582, "author_profile": "https://Stackoverflow.com/users/24582", "pm_score": 1, "selected": false, "text": "<p>Here is a working, cut-and-paste answer in jsp without any tag libraries or external dependencies whatsoever. The map with models is hardcoded but shouldn't pose any problems.</p>\n\n<p>I separated this answer from my previous answer as the added JSP does not improve readability. And in 'real life' I would not burden my JSP with all the embedded logic but put it in a class somewhere. Or use tags.</p>\n\n<p>All that \"first\" stuff is to prevent superfluos \",\" in the generated code. Using a foreach dosn't give you any knowledge about the amount of elements, so you check for last. You can also skip the first-element handling and strip the last \",\" afterwards by decreasing the builder length by 1.</p>\n\n<pre><code>&lt;%@ page language=\"java\" contentType=\"text/html; charset=ISO-8859-1\"\n pageEncoding=\"ISO-8859-1\"%&gt;\n&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"&gt;\n\n&lt;%@page import=\"java.util.Map\"%&gt;\n&lt;%@page import=\"java.util.TreeMap\"%&gt;\n&lt;%@page import=\"java.util.Arrays\"%&gt;\n&lt;%@page import=\"java.util.Collection\"%&gt;\n&lt;%@page import=\"java.util.List\"%&gt;\n&lt;html&gt;\n&lt;head&gt;\n&lt;meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\"&gt;\n&lt;title&gt;Challenge&lt;/title&gt;\n&lt;/head&gt;\n&lt;body onload=\"setModels()\"&gt;\n&lt;% // You would get your map some other way.\n Map&lt;String,List&lt;String&gt;&gt; map = new TreeMap&lt;String,List&lt;String&gt;&gt;();\n map.put(\"porsche\", Arrays.asList(new String[]{\"911\", \"Carrera\"}));\n map.put(\"mercedes\", Arrays.asList(new String[]{\"foo\", \"bar\"}));\n%&gt;\n\n&lt;%! // You may wish to put this in a class\n public String modelsToJavascriptList(Collection&lt;String&gt; items) {\n StringBuilder builder = new StringBuilder();\n builder.append('[');\n boolean first = true;\n for (String item : items) {\n if (!first) {\n builder.append(',');\n } else {\n first = false;\n }\n builder.append('\\'').append(item).append('\\'');\n }\n builder.append(']');\n return builder.toString();\n }\n\n public String mfMapToString(Map&lt;String,List&lt;String&gt;&gt; mfmap) {\n StringBuilder builder = new StringBuilder();\n builder.append('{');\n boolean first = true;\n for (String mf : mfmap.keySet()) {\n if (!first) {\n builder.append(',');\n } else {\n first = false;\n }\n builder.append('\\'').append(mf).append('\\'');\n builder.append(\" : \");\n builder.append( modelsToJavascriptList(mfmap.get(mf)) );\n }\n builder.append(\"};\");\n return builder.toString();\n }\n%&gt;\n\n&lt;script&gt;\nvar modelsPerManufacturer =&lt;%= mfMapToString(map) %&gt;\n function setSelectOptionsForModels(modelArray) {\n var selectBox = document.myForm.models;\n\n for (i = selectBox.length - 1; i&gt;= 0; i--) {\n // Bottom-up for less flicker\n selectBox.remove(i);\n }\n\n for (i = 0; i&lt; modelArray.length; i++) {\n var text = modelArray[i];\n var opt = new Option(text,text, false, false);\n selectBox.add(opt);\n }\n }\n\n function setModels() {\n var index = document.myForm.manufacturer.selectedIndex;\n if (index == -1) {\n return;\n }\n\n var manufacturerOption = document.myForm.manufacturer.options[index];\n if (!manufacturerOption) {\n // Strange, the form does not have an option with given index.\n return;\n }\n manufacturer = manufacturerOption.value;\n\n var modelsForManufacturer = modelsPerManufacturer[manufacturer];\n if (!modelsForManufacturer) {\n // This modelsForManufacturer is not in the modelsPerManufacturer map\n return; // or alert\n }\n setSelectOptionsForModels(modelsForManufacturer);\n }\n\n function modelSelected() {\n var index = document.myForm.models.selectedIndex;\n if (index == -1) {\n return;\n }\n alert(\"You selected \" + document.myForm.models.options[index].value);\n }\n &lt;/script&gt;\n &lt;form name=\"myForm\"&gt;\n &lt;select onchange=\"setModels()\" id=\"manufacturer\" size=\"5\"&gt;\n &lt;% boolean first = true;\n for (String mf : map.keySet()) { %&gt;\n &lt;option value=\"&lt;%= mf %&gt;\" &lt;%= first ? \"SELECTED\" : \"\" %&gt;&gt;&lt;%= mf %&gt;&lt;/option&gt;\n &lt;% first = false;\n } %&gt;\n &lt;/select&gt;\n\n &lt;select onChange=\"modelSelected()\" id=\"models\" size=\"5\"&gt;\n &lt;!-- Filled dynamically by setModels --&gt;\n &lt;/select&gt;\n &lt;/form&gt;\n\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 187272, "author": "Sandman", "author_id": 19911, "author_profile": "https://Stackoverflow.com/users/19911", "pm_score": 3, "selected": true, "text": "<p>Well anyway, as i said, i finally managed to do it by myself, so here's my answer... </p>\n\n<p>I receive the map from my controller like this (I'm using Spring, don't know how this works with other frameworks):</p>\n\n<pre><code>&lt;c:set var=\"manufacturersAndModels\" scope=\"page\" value=\"${MANUFACTURERS_AND_MODELS_MAP}\"/&gt;\n</code></pre>\n\n<p>These are my combos:</p>\n\n<pre><code>&lt;select id=\"manufacturersList\" name=\"manufacturersList\" onchange=\"populateModelsCombo(this.options[this.selectedIndex].index);\" &gt;\n &lt;c:forEach var=\"manufacturersItem\" items=\"&lt;%= manufacturers%&gt;\"&gt;\n &lt;option value='&lt;c:out value=\"${manufacturersItem}\" /&gt;'&gt;&lt;c:out value=\"${manufacturersItem}\" /&gt;&lt;/option&gt;\n &lt;/c:forEach&gt;\n &lt;/select&gt;\n</code></pre>\n\n<p><br/></p>\n\n<pre><code>select id=\"modelsList\" name=\"modelsList\"\n &lt;c:forEach var=\"model\" items=\"&lt;%= models %&gt;\" &gt;\n &lt;option value='&lt;c:out value=\"${model}\" /&gt;'&gt;&lt;c:out value=\"${model}\" /&gt;&lt;/option&gt;\n &lt;/c:forEach&gt;\n &lt;/select&gt;\n</code></pre>\n\n<p>I imported the following classes (some names have, of course, been changed):</p>\n\n<pre><code>&lt;%@ page import=\"org.mycompany.Car,java.util.Map,java.util.TreeMap,java.util.List,java.util.ArrayList,java.util.Set,java.util.Iterator;\" %&gt;\n</code></pre>\n\n<p>And here's the code that does all the hard work:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n&lt;% \n Map mansAndModels = new TreeMap();\n mansAndModels = (TreeMap) pageContext.getAttribute(\"manufacturersAndModels\");\n Set manufacturers = mansAndModels.keySet(); //We'll use this one to populate the first combo\n Object[] manufacturersArray = manufacturers.toArray();\n\n List cars;\n List models = new ArrayList(); //We'll populate the second combo the first time the page is displayed with this list\n\n\n //initial second combo population\n cars = (List) mansAndModels.get(manufacturersArray[0]);\n\n for(Iterator iter = cars.iterator(); iter.hasNext();) {\n\n Car car = (Car) iter.next();\n models.add(car.getModel());\n }\n%&gt;\n\n\nfunction populateModelsCombo(key) {\n var modelsArray = new Array();\n\n //Here goes the tricky part, we populate a two-dimensional javascript array with values from the map\n&lt;% \n for(int i = 0; i &lt; manufacturersArray.length; i++) {\n\n cars = (List) mansAndModels.get(manufacturersArray[i]);\n Iterator carsIterator = cars.iterator(); \n%&gt;\n singleManufacturerModelsArray = new Array();\n&lt;%\n for(int j = 0; carsIterator.hasNext(); j++) {\n\n Car car = (Car) carsIterator.next();\n\n %&gt; \n singleManufacturerModelsArray[&lt;%= j%&gt;] = \"&lt;%= car.getModel()%&gt;\";\n &lt;%\n }\n %&gt;\n modelsArray[&lt;%= i%&gt;] = singleManufacturerModelsArray;\n &lt;%\n } \n %&gt; \n\n var modelsList = document.getElementById(\"modelsList\");\n\n //Empty the second combo\n while(modelsList.hasChildNodes()) {\n modelsList.removeChild(modelsList.childNodes[0]);\n }\n\n //Populate the second combo with new values\n for (i = 0; i &lt; modelsArray[key].length; i++) {\n\n modelsList.options[i] = new Option(modelsArray[key][i], modelsArray[key][i]);\n } \n}\n</code></pre>\n\n<p></p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19911/" ]
Ok, here's one for the Java/JavaScript gurus: In my app, one of the controllers passes a TreeMap to it's JSP. This map has car manufacturer's names as keys and Lists of Car objects as values. These Car objects are simple beans containing the car's name, id, year of production etc. So, the map looks something like this (this is just an example, to clarify things a bit): Key: Porsche Value: List containing three Car objects(for example 911,Carrera,Boxter with their respectable years of production and ids) Key: Fiat Value: List containing two Car objects(for example, Punto and Uno) etc... Now, in my JSP i have two comboboxes. One should receive a list of car manufacturers(keys from the map - this part I know how to do), and the other one should **dynamicaly change** to display the names of the cars when the user selects a certain manufacturer from the first combobox. So, for example, user selects a "Porsche" in the first combobox, and the second immediately displays "911, Carrera, Boxter"... After spending a couple of days trying to find out how to do this, I'm ready to admit defeat. I tried out a lot of different things but every time I hit a wall somewehere along the way. Can anybody suggest how I should approach this one? Yes, I'm a JavaScript newbie, if anybody was wondering... EDIT: I've retagged this as a code-challenge. Kudos to anybody who solves this one without using any JavaScript framework (like JQuery).
Well anyway, as i said, i finally managed to do it by myself, so here's my answer... I receive the map from my controller like this (I'm using Spring, don't know how this works with other frameworks): ``` <c:set var="manufacturersAndModels" scope="page" value="${MANUFACTURERS_AND_MODELS_MAP}"/> ``` These are my combos: ``` <select id="manufacturersList" name="manufacturersList" onchange="populateModelsCombo(this.options[this.selectedIndex].index);" > <c:forEach var="manufacturersItem" items="<%= manufacturers%>"> <option value='<c:out value="${manufacturersItem}" />'><c:out value="${manufacturersItem}" /></option> </c:forEach> </select> ``` ``` select id="modelsList" name="modelsList" <c:forEach var="model" items="<%= models %>" > <option value='<c:out value="${model}" />'><c:out value="${model}" /></option> </c:forEach> </select> ``` I imported the following classes (some names have, of course, been changed): ``` <%@ page import="org.mycompany.Car,java.util.Map,java.util.TreeMap,java.util.List,java.util.ArrayList,java.util.Set,java.util.Iterator;" %> ``` And here's the code that does all the hard work: ``` <script type="text/javascript"> <% Map mansAndModels = new TreeMap(); mansAndModels = (TreeMap) pageContext.getAttribute("manufacturersAndModels"); Set manufacturers = mansAndModels.keySet(); //We'll use this one to populate the first combo Object[] manufacturersArray = manufacturers.toArray(); List cars; List models = new ArrayList(); //We'll populate the second combo the first time the page is displayed with this list //initial second combo population cars = (List) mansAndModels.get(manufacturersArray[0]); for(Iterator iter = cars.iterator(); iter.hasNext();) { Car car = (Car) iter.next(); models.add(car.getModel()); } %> function populateModelsCombo(key) { var modelsArray = new Array(); //Here goes the tricky part, we populate a two-dimensional javascript array with values from the map <% for(int i = 0; i < manufacturersArray.length; i++) { cars = (List) mansAndModels.get(manufacturersArray[i]); Iterator carsIterator = cars.iterator(); %> singleManufacturerModelsArray = new Array(); <% for(int j = 0; carsIterator.hasNext(); j++) { Car car = (Car) carsIterator.next(); %> singleManufacturerModelsArray[<%= j%>] = "<%= car.getModel()%>"; <% } %> modelsArray[<%= i%>] = singleManufacturerModelsArray; <% } %> var modelsList = document.getElementById("modelsList"); //Empty the second combo while(modelsList.hasChildNodes()) { modelsList.removeChild(modelsList.childNodes[0]); } //Populate the second combo with new values for (i = 0; i < modelsArray[key].length; i++) { modelsList.options[i] = new Option(modelsArray[key][i], modelsArray[key][i]); } } ```
156,873
<p>I'm writing a shell for a project of mine, which by design parses commands that looks like this:</p> <p>COMMAND_NAME ARG1="Long Value" ARG2=123 [email protected]</p> <p>My problem is that Python's command line parsing libraries (getopt and optparse) forces me to use '-' or '--' in front of the arguments. This behavior doesn't match my requirements.</p> <p>Any ideas how can this be solved? Any existing library for this?</p>
[ { "answer_id": 156901, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 0, "selected": false, "text": "<p>Without fairly intensive surgery on optparse or getopt, I don't believe you can sensibly make them parse your format. You can easily parse your own format, though, or translate it into something optparse could handle:</p>\n\n<pre><code>parser = optparse.OptionParser()\nparser.add_option(\"--ARG1\", dest=\"arg1\", help=\"....\")\nparser.add_option(...)\n...\nnewargs = sys.argv[:1]\nfor idx, arg in enumerate(sys.argv[1:])\n parts = arg.split('=', 1)\n if len(parts) &lt; 2:\n # End of options, don't translate the rest. \n newargs.extend(sys.argv[idx+1:])\n break\n argname, argvalue = parts\n newargs.extend([\"--%s\" % argname, argvalue])\n\nparser.parse_args(newargs)\n</code></pre>\n" }, { "answer_id": 156949, "author": "ironfroggy", "author_id": 19687, "author_profile": "https://Stackoverflow.com/users/19687", "pm_score": 4, "selected": true, "text": "<p>You could split them up with shlex.split(), which can handle the quoted values you have, and pretty easily parse this with a very simple regular expression. Or, you can just use regular expressions for both splitting and parsing. Or simply use split().</p>\n\n<pre><code>args = {}\nfor arg in shlex.split(cmdln_args):\n key, value = arg.split('=', 1)\n args[key] = value\n</code></pre>\n" }, { "answer_id": 157076, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 2, "selected": false, "text": "<p>A small pythonic variation on Ironforggy's shlex answer:</p>\n\n<pre><code>args = dict( arg.split('=', 1) for arg in shlex.split(cmdln_args) )\n</code></pre>\n\n<p>oops... - corrected.</p>\n\n<p>thanks, J.F. Sebastian \n (got to remember those single argument generator expressions).</p>\n" }, { "answer_id": 157100, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 3, "selected": false, "text": "<ol>\n<li><p>Try to follow \"<a href=\"http://www.gnu.org/prep/standards/standards.html#Command_002dLine-Interfaces\" rel=\"nofollow noreferrer\">Standards for Command Line Interfaces</a>\"</p></li>\n<li><p>Convert your arguments (as Thomas suggested) to OptionParser format.</p>\n\n<pre><code>parser.parse_args([\"--\"+p if \"=\" in p else p for p in sys.argv[1:]])\n</code></pre></li>\n</ol>\n\n<p>If command-line arguments are not in sys.argv or a similar list but in a string then (as ironfroggy suggested) use <code>shlex.split()</code>.</p>\n\n<pre><code>parser.parse_args([\"--\"+p if \"=\" in p else p for p in shlex.split(argsline)])\n</code></pre>\n" }, { "answer_id": 1760133, "author": "Luic Pend", "author_id": 214213, "author_profile": "https://Stackoverflow.com/users/214213", "pm_score": 1, "selected": false, "text": "<p>What about optmatch (<a href=\"http://www.coderazzi.net/python/optmatch/index.htm\" rel=\"nofollow noreferrer\">http://www.coderazzi.net/python/optmatch/index.htm</a>)? Is not standard, but takes a different approach to options parsing, and it supports any prefix:</p>\n\n<p>OptionMatcher.setMode(optionPrefix='-')</p>\n" }, { "answer_id": 2653583, "author": "James", "author_id": 318565, "author_profile": "https://Stackoverflow.com/users/318565", "pm_score": 0, "selected": false, "text": "<p>Little late to the party... but <a href=\"http://www.python.org/dev/peps/pep-0389/\" rel=\"nofollow noreferrer\">PEP 389</a> allows for this and much more.</p>\n\n<p>Here's a little nice library should your version of Python need it code.google.com/p/argparse</p>\n\n<p>Enjoy.</p>\n" }, { "answer_id": 4913806, "author": "Mufasa", "author_id": 605326, "author_profile": "https://Stackoverflow.com/users/605326", "pm_score": 0, "selected": false, "text": "<p>You may be interested in a little Python module I wrote to make handling of command line arguments even easier (open source and free to use) - <a href=\"http://freshmeat.net/projects/commando\" rel=\"nofollow\">http://freshmeat.net/projects/commando</a></p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9941/" ]
I'm writing a shell for a project of mine, which by design parses commands that looks like this: COMMAND\_NAME ARG1="Long Value" ARG2=123 [email protected] My problem is that Python's command line parsing libraries (getopt and optparse) forces me to use '-' or '--' in front of the arguments. This behavior doesn't match my requirements. Any ideas how can this be solved? Any existing library for this?
You could split them up with shlex.split(), which can handle the quoted values you have, and pretty easily parse this with a very simple regular expression. Or, you can just use regular expressions for both splitting and parsing. Or simply use split(). ``` args = {} for arg in shlex.split(cmdln_args): key, value = arg.split('=', 1) args[key] = value ```
156,913
<p><strong>Concrete use case:</strong> In the Eclipse IDE, new 'plugins' can be added by copying a plugin's file(s) into the <code>$ECLIPSE_HOME/plugins</code> directory. However, I want to keep my original Eclipse installation 'clean' without additional plugins because I want to run this basic installation on its own at times. </p> <p>What is a way of avoiding having to copy the files (and hence therefore not being able to run a clean version) and instead logically 'overlaying' the contents of another directory so that it appears to be in the directory at runtime?</p> <p>e.g. something like:</p> <pre><code>gravelld@gravelld-laptop:~$ ls $ECLIPSE_HOME/plugins/ org.junit_3.8.2.v200706111738 org.junit4_4.3.1 org.junit.source_3.8.2.v200706111738 gravelld@gravelld-laptop:~$ ls myplugins/ org.dangravell.myplugin.jar gravelld@gravelld-laptop:~$ overlay myplugins/ $ECLIPSE_HOME/plugins gravelld@gravelld-laptop:~$ ls $ECLIPSE_HOME/plugins/ org.dangravell.myplugin.jar org.junit_3.8.2.v200706111738 org.junit4_4.3.1 org.junit.source_3.8.2.v200706111738 </code></pre> <p>Another use case may be around patching and so on...</p> <p>Can something be done with symbolic links or mnt for this?</p> <p>Thanks!</p>
[ { "answer_id": 157180, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 1, "selected": false, "text": "<p>Have a look at <strong><a href=\"http://www.ibm.com/developerworks/library/os-ecl-manage/\" rel=\"nofollow noreferrer\">Manage your eclipse environment</a></strong> article, especially the Method 3</p>\n<blockquote>\n<p>Creating a links folder to manage product extensions</p>\n<p>If you have product extensions sitting on your file system, like the one we made in Method 1, you can create a few simple files in your Eclipse program directory to notify Eclipse that it needs to check these directories for plug-ins.</p>\n<p>First, create a directory inside your Eclipse installation folder (for example, /opt/eclipse) called links. Within this folder, you can create *.link files (for example, emfPlugins.link). Each link file points to a product extension location. Eclipse will scan this links folder on startup and find the plug-ins in each product extension pointed to by a link file.</p>\n</blockquote>\n<p>This is still supported in eclipse3.4 even though the new p2 provisioning system is quite different.</p>\n<hr />\n<p>Now that the &quot;'links' directory mechanism&quot; is known, it means the difference between a vanilla eclipse and an eclipse with custom common plugins is just the presence of that 'links' directory.</p>\n<p>So, why not have a 'vanilla eclipse distribution' with a symbolic link inside, 'links', pointing to ../links ?</p>\n<p>Any user getting that vanilla eclipse would have at first no 'links' directory alongside it, so it will run as a vanilla distribution. But as soon the user creates a links directory or make another symbolic link to a common remote 'links' directory, that same distribution will pick up the common plugins remote directory...</p>\n<pre><code>/path/links -&gt; /remote/links/commonPlugins\n/eclipse/links -&gt; ../links\n</code></pre>\n<hr />\n<p>Finally, if you create the &quot;/remote/links/commonPlugins&quot; with a given group &quot;aGroup&quot;, and protect it with a '750' mask, you have yourself <em>one</em> eclipse setup which will be:</p>\n<ul>\n<li>vanilla eclipse for any user whom 'id -a' does not include 'aGroup'</li>\n<li>eclipse with plugins for any user part of &quot;aGroup&quot;</li>\n</ul>\n" }, { "answer_id": 171443, "author": "Robᵩ", "author_id": 8747, "author_profile": "https://Stackoverflow.com/users/8747", "pm_score": 2, "selected": false, "text": "<p>You could use an overlay filesystem for this. The three overlay filesystems that I know of in Linux are <a href=\"http://en.wikipedia.org/wiki/UnionFS\" rel=\"nofollow noreferrer\">unionfs</a>, <a href=\"http://aufs.sourceforge.net/\" rel=\"nofollow noreferrer\">aufs</a>, and <a href=\"http://www.denx.de/wiki/Know.MiniFOHome\" rel=\"nofollow noreferrer\">minifo</a>.</p>\n\n<p>Unionfs is included in recent Ubuntu kernels.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
**Concrete use case:** In the Eclipse IDE, new 'plugins' can be added by copying a plugin's file(s) into the `$ECLIPSE_HOME/plugins` directory. However, I want to keep my original Eclipse installation 'clean' without additional plugins because I want to run this basic installation on its own at times. What is a way of avoiding having to copy the files (and hence therefore not being able to run a clean version) and instead logically 'overlaying' the contents of another directory so that it appears to be in the directory at runtime? e.g. something like: ``` gravelld@gravelld-laptop:~$ ls $ECLIPSE_HOME/plugins/ org.junit_3.8.2.v200706111738 org.junit4_4.3.1 org.junit.source_3.8.2.v200706111738 gravelld@gravelld-laptop:~$ ls myplugins/ org.dangravell.myplugin.jar gravelld@gravelld-laptop:~$ overlay myplugins/ $ECLIPSE_HOME/plugins gravelld@gravelld-laptop:~$ ls $ECLIPSE_HOME/plugins/ org.dangravell.myplugin.jar org.junit_3.8.2.v200706111738 org.junit4_4.3.1 org.junit.source_3.8.2.v200706111738 ``` Another use case may be around patching and so on... Can something be done with symbolic links or mnt for this? Thanks!
You could use an overlay filesystem for this. The three overlay filesystems that I know of in Linux are [unionfs](http://en.wikipedia.org/wiki/UnionFS), [aufs](http://aufs.sourceforge.net/), and [minifo](http://www.denx.de/wiki/Know.MiniFOHome). Unionfs is included in recent Ubuntu kernels.
156,916
<p>I need to list all files whose names start with 'SomeLongString'. But the case of 'SomeLongString' can vary. How?</p> <p>I am using zsh, but a bash solution is also welcome.</p>
[ { "answer_id": 156953, "author": "Horst Gutmann", "author_id": 22312, "author_profile": "https://Stackoverflow.com/users/22312", "pm_score": 4, "selected": false, "text": "<p>Depending on how deep you want to have this listing, <code>find</code> offers quite a lot\nin this regard:</p>\n\n<pre><code>find . -iname 'SomeLongString*' -maxdepth 1\n</code></pre>\n\n<p>This will only give you the files in the current directory. Important here is\nthe <code>-iname</code> parameter instead of <code>-name</code>.</p>\n" }, { "answer_id": 156958, "author": "Jacek Szymański", "author_id": 23242, "author_profile": "https://Stackoverflow.com/users/23242", "pm_score": 5, "selected": false, "text": "<p>bash:</p>\n\n<pre><code>shopt -s nocaseglob\n</code></pre>\n" }, { "answer_id": 157425, "author": "jkramer", "author_id": 12523, "author_profile": "https://Stackoverflow.com/users/12523", "pm_score": 6, "selected": true, "text": "<p>ZSH:</p>\n\n<pre><code>$ unsetopt CASE_GLOB\n</code></pre>\n\n<p>Or, if you don't want to enable case-insensitive globbing in general, you can activate it for only the varying part:</p>\n\n<pre><code>$ print -l (#i)(somelongstring)*\n</code></pre>\n\n<p>This will match any file that starts with \"somelongstring\" (in any combination of lower/upper case). The case-insensitive flag applies for everything between the parentheses and can be used multiple times. Read the manual <code>zshexpn(1)</code> for more information.</p>\n\n<p><strong>UPDATE</strong>\nAlmost forgot, you have to enable extendend globbing for this to work:</p>\n\n<pre><code>setopt extendedglob\n</code></pre>\n" }, { "answer_id": 7618091, "author": "Modern Hacker", "author_id": 423486, "author_profile": "https://Stackoverflow.com/users/423486", "pm_score": 2, "selected": false, "text": "<pre><code>\n$ function i () {\n> shopt -s nocaseglob; $*; shopt -u nocaseglob\n> }\n$ ls *jtweet*\nls: cannot access *jtweet*: No such file or directory\n$ i ls *jtweet*\nJTweet.pm JTweet.pm~ JTweet2.pm JTweet2.pm~\n</code></pre>\n" }, { "answer_id": 58704597, "author": "michael", "author_id": 127971, "author_profile": "https://Stackoverflow.com/users/127971", "pm_score": 1, "selected": false, "text": "<p>For completeness (and frankly surprised it's not mentioned yet, even though all the other answers are better and/or \"more correct\"), obviously one can also use (especially for <code>grep</code> aficionados):</p>\n\n<pre><code>$ ls | egrep -i '^SomeLongString'\n</code></pre>\n\n<p>One might also stick in a redundant <code>ls -1</code> (that's option \"one\", not \"ell\"), but when passed to a pipe, each entry is already going to be one per line, anyway. I'd typically use something like this (vs <code>set</code>) in shell scripts, eg in a <code>for</code>/<code>while</code> loop: <code>for i in $(ls | grep -i ...)</code> . However, the other answer using <code>find</code> would be preferable &amp; more flexible in that circumstance, because you can, for example, omit directories (or set other restrictions): <code>for i in $(find . -type f -iname 'SomeString*' -print -maxdepth 1)...</code> or even forgo the loop altogether and just use the power of <code>find</code> all by itself, eg: <code>find ... -exec do_stuff {} \\; ...</code> , but I do digress (again, for completeness.)</p>\n" }, { "answer_id": 72838992, "author": "AnrDaemon", "author_id": 1449366, "author_profile": "https://Stackoverflow.com/users/1449366", "pm_score": 1, "selected": false, "text": "<p>For completeness, a long, full solution (creating thumbnails from a list of camera images):</p>\n<pre class=\"lang-bash prettyprint-override\"><code>_shopt=&quot;$( shopt -p )&quot;\nshopt -s nocaseglob\nfor f in *.jpg; do\n convert &quot;$f&quot; -auto-orient -resize &quot;1280x1280&gt;&quot; -sharpen 8 jpeg:&quot;$( basename &quot;$f&quot; &quot;.${f##*.}&quot; ).shelf.jpg&quot;\ndone\neval &quot;$_shopt&quot;\n</code></pre>\n<p>Since we don't know exact extension case (.jpg or .JPG), we create it from the name itself by stripping the prefix up to (and including) the last dot.\nThe -auto-orient option will take care of image orientation so that thumbnails would be viewed correctly on any device.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45603/" ]
I need to list all files whose names start with 'SomeLongString'. But the case of 'SomeLongString' can vary. How? I am using zsh, but a bash solution is also welcome.
ZSH: ``` $ unsetopt CASE_GLOB ``` Or, if you don't want to enable case-insensitive globbing in general, you can activate it for only the varying part: ``` $ print -l (#i)(somelongstring)* ``` This will match any file that starts with "somelongstring" (in any combination of lower/upper case). The case-insensitive flag applies for everything between the parentheses and can be used multiple times. Read the manual `zshexpn(1)` for more information. **UPDATE** Almost forgot, you have to enable extendend globbing for this to work: ``` setopt extendedglob ```
156,930
<p>We have an existing classic ASP intranet consisting of hundreds of pages. Its directory structure looks like this...</p> <pre><code>/root app_1 app_2 ... img js style </code></pre> <p>Obviously app_1 and so on have better names in the actual directory structure.</p> <p>Even though the many applications have different behaviour, they are all part of the same intranet and therefore share a common look and feel by including stylesheets via /style, images via /img and client script via /js.</p> <p>The trouble (for me at least) comes when I want to add an intranet application in ASP.NET.</p> <p>Ultimately, I'd like this structure:</p> <pre><code>/root app_1 app_2 dotnetapp_1 dotnetapp_2 ... img js style </code></pre> <p>It seems to me that ASP.NET "applications" like to think of themselves as separate from everything around them (this may just be my comprehension of how they are). You create a new "project" in Visual Studio and it's like you have a new "root" a level below the actual root I want to use. It's like this new application is a thing, standing alone, with its own images and style and whatnot. However, I want it to be a sub-part of the existing intranet.</p> <p>Ultimately I want to be able to make my whole classic ASP intranet the "root" and have ASP.NET "sub-applications" that can still access /style and /img and, I guess for ASP.NET I'll have /masterpages.</p> <p>I've tried this before, but I think VS choked on the couple of hundred classic ASP pages that it added to the "project" when I made my existing intranet root directory the ASP.NET project root (via File->Open->Web Site). I'd be nice to edit my existing classic ASP intranet using VS 2008 SP1 (I currently use the excellent <a href="http://notepad-plus.sourceforge.net/uk/site.htm" rel="nofollow noreferrer">Notepad++</a>) because I'd like to get more hands on with VS but I guess this isn't absolutely necessary.</p> <p>I also tried treating each new ASP.NET application as an application in its own right, effectively making the /dotnetapp_1 directory the "root" of the application (again, via File->Open->Web Site in VS2008). However, VS then complained when I tried to reference /masterpages because it "belonged to another application." I think I kludged it by adding a virtual directory inside each ASP.NET directory that "pointed" to the root /masterpages but I'm not sure VS was able to happily provide WYSIWYG editing when I did this, as opposed to making a copy of the masterpage in every ASP.NET application I add to the intranet.</p> <p>I'm also quite likely to visit the .NET MVC framework so please offer any answers with that framework in mind. I'm hoping "projects" aren't quite to important with MVC and that rather it's just a bunch of files that creates an application that contributes to the whole (that being the intranet).</p> <p>So, the question is: <strong>How I can best add-on ASP.NET applications to an existing classic ASP intranet (I'm not concerned about the technicalities of session sharing between classic ASP and ASP.NET, only the structural layout of directories and projects) and be able to edit these separate applications in Visual Studio 2008 SP1 and yet have these application "related" to each other by a common, intranet look and feel*?</strong></p> <ul> <li>Please don't just post the answer "use MasterPages." I appreciate MasterPages are .NET's method of sharing styles (and more probably) between related pages in the <em>same</em> application. I get that. What I'm looking for is the best method of adding ASP.NET applications into the existing intranet as smoothly as I can that makes editing each application simple and where each application can share (if possible) an intranet-common style.</li> </ul>
[ { "answer_id": 157244, "author": "rohancragg", "author_id": 5351, "author_profile": "https://Stackoverflow.com/users/5351", "pm_score": 2, "selected": false, "text": "<p>One solution would be to use IIS Manager to configure the website (created for your ASP.NET app by Visual Studio) and add a virtual directory for each of the common folders so that (by the 'virtual' nature of the virtual directory) they will 'appear' to be in the same root folder as your ASP.NET app.</p>\n\n<pre><code>/root\n app_1\n app_2\n dotnetapp_1\n &lt;virtual&gt;img\n &lt;virtual&gt;js\n ...\n img\n js\n style\n</code></pre>\n\n<p>You can probably script IIS or edit an XML file if you need to do this in bulk, and I'm sure there must be an even more elegant way to do something similar that doesn't require to much mouse work!</p>\n" }, { "answer_id": 157326, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 2, "selected": false, "text": "<p>Since ASP.NET is now the Microsoft standard web development platform, <strong>you might be better off starting with a brand-new ASP.NET web site and importing your existing ASP pages and folders</strong> into it. Once you have that set up and running, adding new functionality in ASP.NET will be a snap.</p>\n\n<p>Microsoft understood that some customers would be mixing classic ASP and ASP.NET for awhile, and they accomodated this need by making classic ASP pages work within an ASP.NET site. What you're trying to do is the reverse of this (get ASP.NET to work within ASP, sorta), and you're already running into difficulties.</p>\n" }, { "answer_id": 363755, "author": "Armstrongest", "author_id": 26931, "author_profile": "https://Stackoverflow.com/users/26931", "pm_score": 0, "selected": false, "text": "<p>Can't you run the asp.net site as a Virtual Directory?</p>\n\n<pre><code>www.site.com/dotnetapp/\n</code></pre>\n\n<p>Where dotnetapp is a virtual directory completely separate?</p>\n" }, { "answer_id": 909100, "author": "sliderhouserules", "author_id": 31385, "author_profile": "https://Stackoverflow.com/users/31385", "pm_score": 0, "selected": false, "text": "<p>Couple different ways to go about this:</p>\n\n<ol>\n<li>If your listed folder structure is the desired web folder structure, then any of your ASP.NET applications can simply reference /root/js/whatever.js or ../js/whatever.js and it'll get to the folders you already have at the root. This is an alternative to the virtual directories solution already mentioned. This is a rather messy solution, which some of the projects I've inherited at my current job do.</li>\n<li>At a previous job I managed a hybrid Classic ASP/ASP.NET application for a couple years and I did it by making an ASP.NET Web Application at the root and moving all my ASP pages into it. Any \"sub-applications\" you want to make should just be folders in this single project. [ASP pages don't have color-coding in VS2008 anymore though, which was really annoying.]</li>\n</ol>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7508/" ]
We have an existing classic ASP intranet consisting of hundreds of pages. Its directory structure looks like this... ``` /root app_1 app_2 ... img js style ``` Obviously app\_1 and so on have better names in the actual directory structure. Even though the many applications have different behaviour, they are all part of the same intranet and therefore share a common look and feel by including stylesheets via /style, images via /img and client script via /js. The trouble (for me at least) comes when I want to add an intranet application in ASP.NET. Ultimately, I'd like this structure: ``` /root app_1 app_2 dotnetapp_1 dotnetapp_2 ... img js style ``` It seems to me that ASP.NET "applications" like to think of themselves as separate from everything around them (this may just be my comprehension of how they are). You create a new "project" in Visual Studio and it's like you have a new "root" a level below the actual root I want to use. It's like this new application is a thing, standing alone, with its own images and style and whatnot. However, I want it to be a sub-part of the existing intranet. Ultimately I want to be able to make my whole classic ASP intranet the "root" and have ASP.NET "sub-applications" that can still access /style and /img and, I guess for ASP.NET I'll have /masterpages. I've tried this before, but I think VS choked on the couple of hundred classic ASP pages that it added to the "project" when I made my existing intranet root directory the ASP.NET project root (via File->Open->Web Site). I'd be nice to edit my existing classic ASP intranet using VS 2008 SP1 (I currently use the excellent [Notepad++](http://notepad-plus.sourceforge.net/uk/site.htm)) because I'd like to get more hands on with VS but I guess this isn't absolutely necessary. I also tried treating each new ASP.NET application as an application in its own right, effectively making the /dotnetapp\_1 directory the "root" of the application (again, via File->Open->Web Site in VS2008). However, VS then complained when I tried to reference /masterpages because it "belonged to another application." I think I kludged it by adding a virtual directory inside each ASP.NET directory that "pointed" to the root /masterpages but I'm not sure VS was able to happily provide WYSIWYG editing when I did this, as opposed to making a copy of the masterpage in every ASP.NET application I add to the intranet. I'm also quite likely to visit the .NET MVC framework so please offer any answers with that framework in mind. I'm hoping "projects" aren't quite to important with MVC and that rather it's just a bunch of files that creates an application that contributes to the whole (that being the intranet). So, the question is: **How I can best add-on ASP.NET applications to an existing classic ASP intranet (I'm not concerned about the technicalities of session sharing between classic ASP and ASP.NET, only the structural layout of directories and projects) and be able to edit these separate applications in Visual Studio 2008 SP1 and yet have these application "related" to each other by a common, intranet look and feel\*?** * Please don't just post the answer "use MasterPages." I appreciate MasterPages are .NET's method of sharing styles (and more probably) between related pages in the *same* application. I get that. What I'm looking for is the best method of adding ASP.NET applications into the existing intranet as smoothly as I can that makes editing each application simple and where each application can share (if possible) an intranet-common style.
One solution would be to use IIS Manager to configure the website (created for your ASP.NET app by Visual Studio) and add a virtual directory for each of the common folders so that (by the 'virtual' nature of the virtual directory) they will 'appear' to be in the same root folder as your ASP.NET app. ``` /root app_1 app_2 dotnetapp_1 <virtual>img <virtual>js ... img js style ``` You can probably script IIS or edit an XML file if you need to do this in bulk, and I'm sure there must be an even more elegant way to do something similar that doesn't require to much mouse work!
156,936
<p>I have been using C# for a while now, and going back to C++ is a headache. I am trying to get some of my practices from C# with me to C++, but I am finding some resistance and I would be glad to accept your help.</p> <p>I would like to expose an iterator for a class like this:</p> <pre><code>template &lt;class T&gt; class MyContainer { public: // Here is the problem: // typedef for MyIterator without exposing std::vector publicly? MyIterator Begin() { return mHiddenContainerImpl.begin(); } MyIterator End() { return mHiddenContainerImpl.end(); } private: std::vector&lt;T&gt; mHiddenContainerImpl; }; </code></pre> <p>Am I trying at something that isn't a problem? Should I just typedef std::vector&lt; T >::iterator? I am hoping on just depending on the iterator, not the implementing container...</p>
[ { "answer_id": 156995, "author": "Sébastien RoccaSerra", "author_id": 2797, "author_profile": "https://Stackoverflow.com/users/2797", "pm_score": 1, "selected": false, "text": "<p>This should do what you want:</p>\n\n<pre><code>typedef typename std::vector&lt;T&gt;::iterator MyIterator;\n</code></pre>\n\n<p>From <a href=\"http://www.acceleratedcpp.com/\" rel=\"nofollow noreferrer\">Accelerated C++</a>:</p>\n\n<blockquote>\n <p>Whenever you have a type, such as <code>vector&lt;T&gt;</code>, that depends on a template parameter, and you want to use a member of that type, such as <code>size_type</code>, that is itself a type, you must precede the entire name by <code>typename</code> to let the implementation know to treat the name as a type.</p>\n</blockquote>\n" }, { "answer_id": 157010, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 1, "selected": false, "text": "<p>I am unsure about what you mean by \"not exposing std::vector publicly\" but indeed, you can just define your typedef like that:</p>\n\n<pre><code>typedef typename std::vector&lt;T&gt;::iterator iterator;\ntypedef typename std::vector&lt;T&gt;::const_iterator const_iterator; // To work with constant references\n</code></pre>\n\n<p>You will be able to change these typedefs later without the user noticing anything ...</p>\n\n<p>By the way, it is considered good practice to also expose a few other types if you want your class to behave as a container:</p>\n\n<pre><code>typedef typename std::vector&lt;T&gt;::size_type size_type;\ntypedef typename std::vector&lt;T&gt;::difference_type difference_type;\ntypedef typename std::vector&lt;T&gt;::pointer pointer;\ntypedef typename std::vector&lt;T&gt;::reference reference;\n</code></pre>\n\n<p>And if needed by your class:</p>\n\n<pre><code> typedef typename std::vector&lt;T&gt;::const_pointer const_pointer;\n typedef typename std::vector&lt;T&gt;::const_reference const_reference;\n</code></pre>\n\n<p>You'll find the meaning of all these typedef's here: <a href=\"http://www.sgi.com/tech/stl/Vector.html\" rel=\"nofollow noreferrer\">STL documentation on vectors</a></p>\n\n<p>Edit: Added the <code>typename</code> as suggested in the comments</p>\n" }, { "answer_id": 157098, "author": "jonner", "author_id": 78437, "author_profile": "https://Stackoverflow.com/users/78437", "pm_score": 5, "selected": true, "text": "<p>You may find the following article interesting as it addresses exactly the problem you have posted: <a href=\"http://www.artima.com/cppsource/type_erasure.html\" rel=\"noreferrer\">On the Tension Between Object-Oriented and Generic Programming in C++ and What Type Erasure Can Do About It</a></p>\n" }, { "answer_id": 157769, "author": "Jeroen Dirks", "author_id": 7743, "author_profile": "https://Stackoverflow.com/users/7743", "pm_score": 2, "selected": false, "text": "<p>I have done the following before so that I got an iterator that was independent of the container. This may have been overkill since I could also have used an API where the caller passes in a <code>vector&lt;T*&gt;&amp;</code> that should be populated with all the elements and then the caller can just iterate from the vector directly.</p>\n\n<pre><code>template &lt;class T&gt;\nclass IterImpl\n{\npublic:\n virtual T* next() = 0;\n};\n\ntemplate &lt;class T&gt;\nclass Iter\n{\npublic:\n Iter( IterImpl&lt;T&gt;* pImpl ):mpImpl(pImpl) {};\n Iter( Iter&lt;T&gt;&amp; rIter ):mpImpl(pImpl) \n {\n rIter.mpImpl = 0; // take ownership\n }\n ~Iter() {\n delete mpImpl; // does nothing if it is 0\n }\n T* next() {\n return mpImpl-&gt;next(); \n }\nprivate:\n IterImpl&lt;T&gt;* mpImpl; \n};\n\ntemplate &lt;class C, class T&gt;\nclass IterImplStl : public IterImpl&lt;T&gt;\n{\npublic:\n IterImplStl( C&amp; rC )\n :mrC( rC ),\n curr( rC.begin() )\n {}\n virtual T* next()\n {\n if ( curr == mrC.end() ) return 0;\n typename T* pResult = &amp;*curr;\n ++curr;\n return pResult;\n }\nprivate:\n C&amp; mrC;\n typename C::iterator curr;\n};\n\n\nclass Widget;\n\n// in the base clase we do not need to include widget\nclass TestBase\n{\npublic:\n virtual Iter&lt;Widget&gt; getIter() = 0;\n};\n\n\n#include &lt;vector&gt;\n\nclass Widget\n{\npublic:\n int px;\n int py;\n};\n\nclass Test : public TestBase\n{\npublic:\n typedef std::vector&lt;Widget&gt; WidgetVec;\n\n virtual Iter&lt;Widget&gt; getIter() {\n return Iter&lt;Widget&gt;( new IterImplStl&lt;WidgetVec, Widget&gt;( mVec ) ); \n }\n\n void add( int px, int py )\n {\n mVec.push_back( Widget() );\n mVec.back().px = px;\n mVec.back().py = py;\n }\nprivate:\n WidgetVec mVec;\n};\n\n\nvoid testFn()\n{\n Test t;\n t.add( 3, 4 );\n t.add( 2, 5 );\n\n TestBase* tB = &amp;t;\n Iter&lt;Widget&gt; iter = tB-&gt;getIter();\n Widget* pW;\n while ( pW = iter.next() )\n {\n std::cout &lt;&lt; \"px: \" &lt;&lt; pW-&gt;px &lt;&lt; \" py: \" &lt;&lt; pW-&gt;py &lt;&lt; std::endl;\n }\n}\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2166173/" ]
I have been using C# for a while now, and going back to C++ is a headache. I am trying to get some of my practices from C# with me to C++, but I am finding some resistance and I would be glad to accept your help. I would like to expose an iterator for a class like this: ``` template <class T> class MyContainer { public: // Here is the problem: // typedef for MyIterator without exposing std::vector publicly? MyIterator Begin() { return mHiddenContainerImpl.begin(); } MyIterator End() { return mHiddenContainerImpl.end(); } private: std::vector<T> mHiddenContainerImpl; }; ``` Am I trying at something that isn't a problem? Should I just typedef std::vector< T >::iterator? I am hoping on just depending on the iterator, not the implementing container...
You may find the following article interesting as it addresses exactly the problem you have posted: [On the Tension Between Object-Oriented and Generic Programming in C++ and What Type Erasure Can Do About It](http://www.artima.com/cppsource/type_erasure.html)
156,941
<p>I have a scenario like this which I want to use capistrano to deploy my ruby on rails application:</p> <ol> <li>The web application is on a thin cluster with the config file stored under /etc/thin. also an init script is in /etc/init.d/thin, so it would start automatically whenever my server needs a reboot</li> <li>Also nginx is executed the same way (as an init script daemon)</li> <li>To make sure in case if somebody hacked my webserver I don't want them to do something too horrible, so the web user is not allowed to sudo. </li> <li>Thin and nginx both runs as the webuser to enforce such security</li> </ol> <p>Now when I need to do the deployment, I would need the files to be installed under /home/webuser/railsapps/helloworld, and I need the cap script restart my thin afterwards. I want to keep all files owned by the webuser, so the cap script primary user is running as webuser. Now the problem arise when I want to restart the thin daemon because webuser can't sudo. </p> <p>I am thinking if its possible to invoke two separate sessions- webuser for file deployment, and then a special sudoer to restart the daemon. Can anyone give me a sample script on this?</p>
[ { "answer_id": 156957, "author": "Dre", "author_id": 23033, "author_profile": "https://Stackoverflow.com/users/23033", "pm_score": 2, "selected": false, "text": "<p>This might not be what you want, but you can actually do something like this in your sudoers file:</p>\n\n<pre><code>someuser ALL=NOPASSWD: /etc/init.d/apache2\n</code></pre>\n\n<p>that lets someuser run /etc/init.d/apache2</p>\n\n<p>If you try to do something else:</p>\n\n<pre><code>$ sudo ls\n[sudo] password for someuser: \nSorry, user someuser is not allowed to execute '/bin/ls' as root on ...\n</code></pre>\n" }, { "answer_id": 169914, "author": "Dave Cheney", "author_id": 6449, "author_profile": "https://Stackoverflow.com/users/6449", "pm_score": 0, "selected": false, "text": "<p>An alternative to this would be running nginx as a normal user, say on port 8080 then using IPTables to redirect requests from port 80 to port 8080, from memory</p>\n\n<pre>iptables -A PREROUTING -t tcp -m tcp -p 80 -j DNAT --dport 8080</pre>\n\n<p>Will send all packets destined to port 80 to port 8080, which can be bound as a normal user.</p>\n" }, { "answer_id": 194884, "author": "danpickett", "author_id": 21788, "author_profile": "https://Stackoverflow.com/users/21788", "pm_score": 1, "selected": false, "text": "<p>why not use sudo for the deployment routine and then chown -R on the RAILS_ROOT? You could tell Capistrano to change the ownership prior to aliasing the release as current.</p>\n" }, { "answer_id": 1149140, "author": "deau", "author_id": 121737, "author_profile": "https://Stackoverflow.com/users/121737", "pm_score": 0, "selected": false, "text": "<p>If you are running Thin as the webuser then can the webuser not end the process? You could restart Thin again without the daemon, so long as you pass the server everything in /etc/thin it should be fine. The daemon, as far as I understand it, is just a convenient way to bypass having to manually launch a program at boot.</p>\n\n<p>The only time you'll come unstuck is when you have to edit the contents of /etc/thin. Assuming you're using aliases to your webuser's thin.yml bits, this will only happen when you want to add / remove a program. When this happens, it might be worth just manually adding/deleting the alias.</p>\n\n<p>This is all assuming the webuser can end the Thin process to start with. I don't know otherwise. Last time it was an issue for me was when I didn't have a way to run the app on my local machine because it's implementation was pretty much tied to the server's layout. Every time I edited something, I had to send it to SVN, switch tabs in the terminal to an ssh shell, pull it from SVN, switch tabs to another ssh and restart the daemon and see whether or not i'd broken it. It got me down, so I installed Thin locally, got the app to read config files, and now I only have to upload once every few days.</p>\n" }, { "answer_id": 6385966, "author": "Morgz", "author_id": 351018, "author_profile": "https://Stackoverflow.com/users/351018", "pm_score": 0, "selected": false, "text": "<p><strong>Just noticed you don't allow user to sudo :-) Well this answer will help others:</strong></p>\n\n<p>A little late the party but I've just done this:</p>\n\n<pre><code>namespace :deploy do\n desc \"Start the Thin processes\"\n task :start do\n run \"cd #{current_path} &amp;&amp; bundle exec sudo thin start -C /etc/thin/dankit.yml\"\n end\n\n desc \"Stop the Thin processes\"\n task :stop do\n run \"cd #{current_path} &amp;&amp; bundle exec sudo thin stop -C /etc/thin/dankit.yml\"\n end\n\n desc \"Restart the Thin processes\"\n task :restart do\n run \"cd #{current_path} &amp;&amp; bundle exec sudo thin restart -C /etc/thin/dankit.yml\"\n end\n\nend\n</code></pre>\n\n<p>Adding sudo to the <code>bundle exec sudo thin start</code> works.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16371/" ]
I have a scenario like this which I want to use capistrano to deploy my ruby on rails application: 1. The web application is on a thin cluster with the config file stored under /etc/thin. also an init script is in /etc/init.d/thin, so it would start automatically whenever my server needs a reboot 2. Also nginx is executed the same way (as an init script daemon) 3. To make sure in case if somebody hacked my webserver I don't want them to do something too horrible, so the web user is not allowed to sudo. 4. Thin and nginx both runs as the webuser to enforce such security Now when I need to do the deployment, I would need the files to be installed under /home/webuser/railsapps/helloworld, and I need the cap script restart my thin afterwards. I want to keep all files owned by the webuser, so the cap script primary user is running as webuser. Now the problem arise when I want to restart the thin daemon because webuser can't sudo. I am thinking if its possible to invoke two separate sessions- webuser for file deployment, and then a special sudoer to restart the daemon. Can anyone give me a sample script on this?
This might not be what you want, but you can actually do something like this in your sudoers file: ``` someuser ALL=NOPASSWD: /etc/init.d/apache2 ``` that lets someuser run /etc/init.d/apache2 If you try to do something else: ``` $ sudo ls [sudo] password for someuser: Sorry, user someuser is not allowed to execute '/bin/ls' as root on ... ```
156,954
<p>I need something in between a full text search and an index search:<br> I want to search for text in one column of my table (probably there will be an index on the column, too, if that matters).</p> <p>Problem is, I want to search for words in the column, but I don't want to match parts. </p> <p>For example, my column might contain business names:<br> <em>Mighty Muck Miller and Partners Inc.<br> Boy &amp; Butter Breakfast company</em> </p> <p>Now if I search for "<em>Miller</em>" I want to find the first line. But if I search for "<em>iller</em>" I don't want to find it, because there is no word starting with "iller". Searching for "<em>Break</em>" should find "<em>Boy &amp; Butter Breakfast company</em>", though, since one word is starting with "<em>Break</em>".</p> <p>So if I try and use </p> <pre><code>WHERE BusinessName LIKE %Break% </code></pre> <p>it will find too many hits.</p> <p>Is there any way to Search for Words separated by whitespace <strong>or other delimiters</strong>? </p> <p>(LINQ would be best, plain SQL would do, too)</p> <p><strong>Important:</strong> Spaces are by far not the only delimiters! Slashes, colons, dots, all non-alphanumerical characters should be considered for this to work!</p>
[ { "answer_id": 156978, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 2, "selected": false, "text": "<pre><code>where BusinessName like 'Break%' -- to find if it is beginning with the word\nor BusinessName like '% Break%' -- to find if it contains the word anywhere but the beginning\n</code></pre>\n" }, { "answer_id": 156980, "author": "Hannes Ovrén", "author_id": 13565, "author_profile": "https://Stackoverflow.com/users/13565", "pm_score": 1, "selected": false, "text": "<pre><code>WHERE BusinessName LIKE '% Break%'\n</code></pre>\n" }, { "answer_id": 157031, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 1, "selected": false, "text": "<p>You mentioned LINQ - you could do something like...</p>\n\n<pre><code>string myPattern = \"% Break%\";\n\nvar query =\n from b in Business\n where SqlMethods.Like(b.BusinessName, myPattern) \n select b;\n</code></pre>\n\n<p>Note that this uses the <code>System.Linq.Data.SqlClient</code> namespace which translates directly to the <code>LIKE</code> operator with no additional processing.</p>\n" }, { "answer_id": 157037, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 3, "selected": false, "text": "<p>Your word delimiters are going to be many: space, tab, beginning of line, parentheses, periods, commas, exclamation/question marks etc. So, a pretty simple solution is to use a regex in your WHERE clause. (And it's going to be a lot more efficient than just ORing every possible delimiter you can think of.)</p>\n\n<p>Since you mentioned LINQ, here's an article that describes how to do <a href=\"http://msdn.microsoft.com/en-us/magazine/cc163473.aspx\" rel=\"nofollow noreferrer\">efficient regex querying with SQL Server</a>.</p>\n\n<p>Complicated WHERE clauses like this always raise a red flag with me as far as performance is concerned, so I definitely suggest benchmarking whatever you end up with, you may decide to build a search index for the column after all.</p>\n\n<p><strong>EDIT:</strong> Saw you edited your question. When <a href=\"http://regexlib.com/CheatSheet.aspx\" rel=\"nofollow noreferrer\">writing your regex</a>, it's easy to just have it use any non-alphanum character as a delimiter, i.e. [^0-9a-zA-Z], or \\W for any non-word character, \\b for any word boundary and \\B for any non-word boundary. Or, instead of matching delimiters, just match any word, i.e. \\w+. Here's <a href=\"http://www.sqlteam.com/article/regular-expressions-in-t-sql\" rel=\"nofollow noreferrer\">another example</a> of someone doing regex searches with SQL Server (more complicated than what you'd need). </p>\n" }, { "answer_id": 160602, "author": "Ricardo C", "author_id": 232589, "author_profile": "https://Stackoverflow.com/users/232589", "pm_score": 3, "selected": true, "text": "<p>SQL Server 2000 or above.</p>\n\n<pre><code>SELECT *\n FROM dbo.TblBusinessNames\n WHERE BusinessName like '%[^A-z^0-9]Break%' -- In the middle of a sentence\n OR BusinessName like 'Break%' -- At the beginning of a sentence\n</code></pre>\n\n<p>Keyword Reference for <strong>LIKE</strong>: <a href=\"http://msdn.microsoft.com/en-us/library/aa933232(SQL.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa933232(SQL.80).aspx</a></p>\n" }, { "answer_id": 2410352, "author": "jasp", "author_id": 289783, "author_profile": "https://Stackoverflow.com/users/289783", "pm_score": 0, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>declare @vSearch nvarchar(100)\n\nset @vSearch = 'About'\n\nselect * from btTab where ' ' + vText + ' ' LIKE '%[^A-z^0-9]' + @vSearch + '[^A-z^0-9]%'\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7021/" ]
I need something in between a full text search and an index search: I want to search for text in one column of my table (probably there will be an index on the column, too, if that matters). Problem is, I want to search for words in the column, but I don't want to match parts. For example, my column might contain business names: *Mighty Muck Miller and Partners Inc. Boy & Butter Breakfast company* Now if I search for "*Miller*" I want to find the first line. But if I search for "*iller*" I don't want to find it, because there is no word starting with "iller". Searching for "*Break*" should find "*Boy & Butter Breakfast company*", though, since one word is starting with "*Break*". So if I try and use ``` WHERE BusinessName LIKE %Break% ``` it will find too many hits. Is there any way to Search for Words separated by whitespace **or other delimiters**? (LINQ would be best, plain SQL would do, too) **Important:** Spaces are by far not the only delimiters! Slashes, colons, dots, all non-alphanumerical characters should be considered for this to work!
SQL Server 2000 or above. ``` SELECT * FROM dbo.TblBusinessNames WHERE BusinessName like '%[^A-z^0-9]Break%' -- In the middle of a sentence OR BusinessName like 'Break%' -- At the beginning of a sentence ``` Keyword Reference for **LIKE**: <http://msdn.microsoft.com/en-us/library/aa933232(SQL.80).aspx>
156,975
<p>I have a JLabel (actually, it is a JXLabel).</p> <p>I have put an icon and text on it.</p> <p><code>&lt;icon&gt;&lt;text&gt;</code></p> <p>Now I wand to add some spacing on the left side of the component, like this:</p> <p><code>&lt;space&gt;&lt;icon&gt;&lt;text&gt;</code></p> <p>I DON'T accept suggestion to move the JLabel or add spacing by modifying the image.</p> <p>I just want to know how to do it with plain java code.</p>
[ { "answer_id": 156993, "author": "Jasper", "author_id": 18702, "author_profile": "https://Stackoverflow.com/users/18702", "pm_score": 2, "selected": false, "text": "<p>The like this: is not very clear, but you can add spacing by adding a transparent border of a certain width to the label</p>\n" }, { "answer_id": 157017, "author": "rjohnston", "author_id": 246, "author_profile": "https://Stackoverflow.com/users/246", "pm_score": 2, "selected": false, "text": "<p>If you're trying to push the label to one side of it's container, you can add a glue. Something like this:</p>\n\n<pre><code>JPanel panel = new JPanel();\npanel.setLayoutManager(new BoxLayout(panel, BoxLayout.LINE_AXIS);\n\npanel.add(new JLabel(\"this is your label with it's image and text\"));\n\npanel.add(Box.createHorizontalGlue());\n</code></pre>\n\n<p>Though your question isn't very clear.</p>\n" }, { "answer_id": 157032, "author": "Telcontar", "author_id": 518, "author_profile": "https://Stackoverflow.com/users/518", "pm_score": 1, "selected": false, "text": "<p>You dont need to modify the preferredSize of the JLabel, you can use the <a href=\"http://java.sun.com/javase/6/docs/api/java/awt/GridBagLayout.html\" rel=\"nofollow noreferrer\">GridBagLayout</a> Manager to specify separations between components, you only have to use the GridBagLayout in the container and add the JXLabel to it with a <a href=\"http://java.sun.com/javase/6/docs/api/java/awt/GridBagConstraints.html\" rel=\"nofollow noreferrer\">GridBagConstraints</a> object specifiying the insets to the left:</p>\n\n<pre><code>JPanel panel=new JPanel(new GridBagLayout());\nJLabel label=new JLabel(\"xxxxx\");\n\nGridBagConstraints constraints=new GridBagConstraints();\n\nconstraints.insest.left=X; // X= number of pixels of separation from the left component\n\npanel.add(label,constraints);\n</code></pre>\n\n<p>Note that i have omitted a lot of configuration properties in the setup of the constraints, you better read the documentacion of <a href=\"http://java.sun.com/javase/6/docs/api/java/awt/GridBagLayout.html\" rel=\"nofollow noreferrer\">GridBagLayout</a></p>\n" }, { "answer_id": 157046, "author": "michelemarcon", "author_id": 15173, "author_profile": "https://Stackoverflow.com/users/15173", "pm_score": 5, "selected": true, "text": "<p>I have found the solution!</p>\n\n<pre><code>setBorder(new EmptyBorder(0,10,0,0));\n</code></pre>\n\n<p>Thanks everyone!</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15173/" ]
I have a JLabel (actually, it is a JXLabel). I have put an icon and text on it. `<icon><text>` Now I wand to add some spacing on the left side of the component, like this: `<space><icon><text>` I DON'T accept suggestion to move the JLabel or add spacing by modifying the image. I just want to know how to do it with plain java code.
I have found the solution! ``` setBorder(new EmptyBorder(0,10,0,0)); ``` Thanks everyone!
157,005
<p>In HTML forms, buttons can be disabled by defining the "disabled" attribute on them, with any value:</p> <pre><code>&lt;button name="btn1" disabled="disabled"&gt;Hello&lt;/button&gt; </code></pre> <p>If a button is to be enabled, the attribute should not exist as there is no defined value that the disabled attribute can be set to that would leave the button enabled.</p> <p>This is causing me problems when I want to enable / disable buttons when using JSP Documents (jspx). As JSP documents have to be well-formed XML documents, I can't see any way of conditionally including this attribute, as something like the following isn't legal:</p> <pre><code>&lt;button name="btn1" &lt;%= (isDisabled) ? "disabled" : "" %/&gt; &gt;Hello&lt;/button&gt; </code></pre> <p>While I could replicate the tag twice using a JSTL if tag to get the desired effect, in my specific case I have over 15 attributes declared on the button (lots of javascript event handler attributes for AJAX) so duplicating the tag is going to make the JSP very messy.</p> <p>How can I solve this problem, without sacrificing the readability of the JSP? Are there any custom tags that can add attributes to the parent by manipulating the output DOM?</p>
[ { "answer_id": 157064, "author": "Marcus Downing", "author_id": 1000, "author_profile": "https://Stackoverflow.com/users/1000", "pm_score": -1, "selected": false, "text": "<p>I don't really use JSP (and I replied once, then deleted it when I understood the \"must by valid XML\" thing). The cleanest I can come up with is this:</p>\n\n<pre><code>&lt;% if (isDisabled) { %&gt;\n &lt;button name=\"btn1\" disabled=\"disabled\"&gt;Hello&lt;/button&gt;\n&lt;% } else { %&gt;\n &lt;button name=\"btn1\"&gt;Hello&lt;/button&gt;\n&lt;% } %&gt;\n</code></pre>\n" }, { "answer_id": 169823, "author": "Eric Wendelin", "author_id": 25066, "author_profile": "https://Stackoverflow.com/users/25066", "pm_score": 0, "selected": false, "text": "<p>The &lt;%= blah %> syntax is not legal XML needed for JSP Documents. You have 2 options:</p>\n\n<ol>\n<li>Replace &lt;%= (isDisabled) ? \"disabled\" : \"\" %&gt; with &lt;jsp.expression&gt;(isDisabled) ? \"disabled\" : \"\"&lt;/jsp.expression&gt;</li>\n<li>Use the Core taglib and EL (make sure isDisabled is put into page scope) like so:</li>\n</ol>\n\n<pre>\n&lt;c:choose&gt;\n &lt;c:when test=\"${isDisabled}\"&gt;\"disabled\"&lt;/c:when&gt;\n &lt;c:otherwise&gt;\"\"&lt;/c:otherwise&gt;\n&lt;/c:choose&gt;\n</pre>\n\n<p>Hope that helps :)</p>\n" }, { "answer_id": 204348, "author": "agnul", "author_id": 6069, "author_profile": "https://Stackoverflow.com/users/6069", "pm_score": 2, "selected": false, "text": "<p>Reading about an automatic <a href=\"http://diaryproducts.net/about/programming_languages/java/convert_jsp_pages_to_jsp_documents_jspx_with_jsp2x\" rel=\"nofollow noreferrer\">jsp to jspx converter</a> I came across the <code>&lt;jsp:element&gt;</code> and <code>&lt;jsp:attribute&gt;</code> tags. If I understand that correctly you should be able to do something like</p>\n\n<pre><code>&lt;jsp:element name=\"button\"&gt;\n &lt;jsp:attribute name=\"someAttribute\"&gt;value&lt;/jsp:attribute&gt;\n&lt;/jsp:element&gt;\n</code></pre>\n\n<p>and have the jsp engine output</p>\n\n<pre><code>&lt;button someAttribute=\"value\"/&gt;\n</code></pre>\n\n<p>or something like that. The only problem, pointed out in the page above, is that this doesn't seem to work well with conditional constructs. The author of the converter worked around that creating some helper tags, which you can have a look at downloading the source code I guess. Hope that helps.</p>\n" }, { "answer_id": 207882, "author": "alex", "author_id": 26787, "author_profile": "https://Stackoverflow.com/users/26787", "pm_score": 5, "selected": true, "text": "<p>I use a custom JSP tag with dynamic attributes. You use it like this:</p>\n\n<pre><code>&lt;util:element elementName=\"button\" name=\"btn1\" disabled=\"$(isDisabled ? 'disabled' : '')\"/&gt;\n</code></pre>\n\n<p>Basically, what this tag does is generate an XML element with elementName and puts all attributes present in the tag, but skips the empty ones.</p>\n\n<p>The tag itself is pretty easy to implement, my implementation is just 44 lines long.</p>\n" }, { "answer_id": 775295, "author": "Bennett McElwee", "author_id": 61754, "author_profile": "https://Stackoverflow.com/users/61754", "pm_score": 3, "selected": false, "text": "<p>You can use the <code>&lt;jsp:text&gt;</code> tag to solve this problem using valid XML:</p>\n\n<pre><code>&lt;jsp:text&gt;&lt;![CDATA[&lt;button name=\"btn1\"]]&gt;&lt;/jsp:text&gt;\n &lt;c:if test=\"${isDisabled}\"&gt; disabled=\"disabled\"&lt;/c:if&gt;\n &gt;\n Hello!\n&lt;jsp:text&gt;&lt;![CDATA[&lt;/button&gt;]]&gt;&lt;/jsp:text&gt;\n</code></pre>\n\n<p>This is obviously more verbose than some other solutions. But it's <strong>completely self-contained</strong>: no custom tags required. Also, it <strong>scales easily</strong> to as many attributes as you need.</p>\n" }, { "answer_id": 2353204, "author": "Darren Bishop", "author_id": 133330, "author_profile": "https://Stackoverflow.com/users/133330", "pm_score": 2, "selected": false, "text": "<p>i guess some time has passed since the last post on this, but I came up against the exact same problem with <code>&lt;select&gt;&lt;option selected=\"selected\"&gt;</code> tags, i.e. dynamically declaring which option is selected. To solve that one I made a custom tagx; I posted the details over in another <a href=\"https://stackoverflow.com/questions/1761479/how-to-output-option-selectedtrue-from-jspx/2353187#2353187\">answer here</a></p>\n\n<p>I came to the conclusion that there is no nice shortcut; EL and JSP expressions can only exist inside XML element attributes (and in body content). So you have to do the following;</p>\n\n<pre><code>&lt;c:choose&gt;\n &lt;c:when test=\"${isDisabled}\"&gt;&lt;button name=\"btn1\" disabled=\"disabled\"&gt;Hello&lt;/button&gt;&lt;/c:when&gt;\n &lt;c:otherwise&gt;&lt;button name=\"btn1\"&gt;Hello&lt;/button&gt;&lt;/c:otherwise&gt;\n&lt;/c:choose&gt;\n</code></pre>\n\n<p>Using the scriptlet notation won't work for JSP documents (.jspx)</p>\n" }, { "answer_id": 6352543, "author": "mclase", "author_id": 798820, "author_profile": "https://Stackoverflow.com/users/798820", "pm_score": 0, "selected": false, "text": "<p>I've just been struggling with the same problem. I tried using <code>&lt;jsp:attribute name=\"disabled\"/&gt;</code> inside <code>&lt;c:if&gt;</code>, but the compiler tries to attach the disabled attribute to the <code>c:if</code> element which fails. But I found that this does work (<code>stripes:submit</code> is an element for creating a button of type submit in stripes):</p>\n\n<pre><code>&lt;stripes:submit name=\"process\" value=\"Hello\"&gt;\n &lt;jsp:attribute name=\"disabled\"&gt;\n &lt;c:if test=\"${x == 0}\"&gt;disabled&lt;/disabled&gt;\n &lt;/jsp:attribute&gt;\n&lt;/stripes:submit&gt;\n</code></pre>\n\n<p>It seems that <code>jsp:attribute</code> will not create an attribute at all if the body contains only whitespace, so you either get <code>disabled=\"disabled\"</code> or nothing at all.</p>\n\n<p>This will only work if you are using some sort of taglib to generate the button, and the tag element must support the disabled attribute (passing it through to the underlying HTML element). You can't use <code>jsp:attribute</code> to add an attribute to a raw HTML element.</p>\n" }, { "answer_id": 6713994, "author": "Adam Gent", "author_id": 318174, "author_profile": "https://Stackoverflow.com/users/318174", "pm_score": 2, "selected": false, "text": "<p>Make a tag library (.tagx) then use the scriptlet tag.</p>\n\n<p>See <a href=\"http://code.google.com/p/jatl/wiki/JSPExample\" rel=\"nofollow\">http://code.google.com/p/jatl/wiki/JSPExample</a></p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\" ?&gt;\n&lt;jsp:root xmlns:jsp=\"http://java.sun.com/JSP/Page\" version=\"2.1\"&gt;\n&lt;jsp:directive.page import=\"com.googlecode.jatl.Html\"/&gt;\n&lt;jsp:directive.page import=\"com.evocatus.product.data.AttributeValue\"/&gt;\n&lt;jsp:directive.page import=\"com.evocatus.domain.Product\"/&gt;\n\n&lt;jsp:scriptlet&gt;\n//&lt;![CDATA[\n final Product p = (Product) request.getAttribute(\"product\");\n new Html(out) {{\n for (AttributeValue v : p.summaryAttributeValues()) {\n p();\n strong().text(v.getLabel()).end();\n text(\": \" + v.getValue());\n endAll();\n }\n }};\n//]]&gt;\n&lt;/jsp:scriptlet&gt;\n\n&lt;/jsp:root&gt;\n</code></pre>\n\n<p>Yeah this is cheating ... but it gets the job done. Plus can you do really nasty complicated recursion for tree structures this way.</p>\n\n<p>I also posted another solution on my blog and gist.github that uses a bunch of tagx libraries: <a href=\"http://adamgent.com/post/8083703288/conditionally-set-an-attribute-on-an-element-with-jspx\" rel=\"nofollow\">http://adamgent.com/post/8083703288/conditionally-set-an-attribute-on-an-element-with-jspx</a></p>\n" }, { "answer_id": 33298678, "author": "pagurix", "author_id": 3270066, "author_profile": "https://Stackoverflow.com/users/3270066", "pm_score": 3, "selected": false, "text": "<p>@alex\ngreat solution to use the ternary operator. I add some of my example, that thanks to you, I just changed the result of the condition, if true, writes the attribute, otherwise not write anything </p>\n\n<p>to populate the list and select the value used, avoiding c:if</p>\n\n<pre><code>&lt;select id=\"selectLang\" name=\"selectLang\" &gt;\n&lt;c:forEach var=\"language\" items=\"${alLanguages}\" &gt;\n &lt;option value=\"${language.id}\" ${language.code == usedLanguage ? 'selected' : ''} &gt;${language.description}&lt;/option&gt;\n&lt;/c:forEach&gt;\n</code></pre>\n\n<p></p>\n\n<p>to check at start a radio button to avoiding c:if:</p>\n\n<pre><code>&lt;input type=\"radio\" id=\"id0\" value=\"0\" name=\"radio\" ${modelVar == 0 ? 'checked' : ''} /&gt;\n&lt;input type=\"radio\" id=\"id1\" value=\"1\" name=\"radio\" ${modelVar == 1 ? 'checked' : ''} /&gt;\n&lt;input type=\"radio\" id=\"id2\" value=\"2\" name=\"radio\" ${modelVar == 2 ? 'checked' : ''} /&gt;\n</code></pre>\n" }, { "answer_id": 60641980, "author": "Archimedes Trajano", "author_id": 242042, "author_profile": "https://Stackoverflow.com/users/242042", "pm_score": 0, "selected": false, "text": "<p>I implemented it like <a href=\"https://stackoverflow.com/a/207882/242042\">https://stackoverflow.com/a/207882/242042</a> and encapsulated <a href=\"https://stackoverflow.com/a/775295/242042\">https://stackoverflow.com/a/775295/242042</a> so that it can be reused as a tag.</p>\n\n<pre><code>&lt;%@ tag\n display-name=\"element\"\n pageEncoding=\"utf-8\"\n description=\"similar to jsp:element with the capability of removing attributes that are blank, additional features depending on the key are documented in the tag.\"\n trimDirectiveWhitespaces=\"true\"\n dynamic-attributes=\"attrs\"\n%&gt;\n&lt;%@ attribute\n name=\"tag\"\n description=\"Element tag name. Used in place of `name` which is a common attribute in HTML\"\n required=\"true\"\n%&gt;\n&lt;%-- key ends with Key, use i18n --%&gt;\n&lt;%-- key starts with x-bool- and value is true, add the key attribute, no value --%&gt;\n&lt;%-- key starts with x-nc- for no check and value is empty, add the key attribute, no value --%&gt;\n&lt;%@ taglib prefix=\"c\" uri=\"http://java.sun.com/jsp/jstl/core\" %&gt;\n&lt;%@ taglib prefix=\"fn\" uri=\"http://java.sun.com/jsp/jstl/functions\" %&gt;\n&lt;%@ taglib prefix=\"fmt\" uri=\"http://java.sun.com/jsp/jstl/fmt\" %&gt;\n&lt;jsp:text&gt;&lt;![CDATA[&lt;]]&gt;&lt;/jsp:text&gt;\n&lt;c:out value=\"${tag} \" /&gt;\n&lt;c:forEach var=\"attr\" begin=\"0\" items=\"${attrs}\"&gt;\n &lt;c:choose&gt;\n &lt;c:when test='${fn:endsWith(attr.key, \"Key\")}'&gt;\n ${attr.key}=&lt;fmt:message key=\"${attr.value}\" /&gt;\n &lt;/c:when&gt;\n &lt;c:when test='${fn:startsWith(attr.key, \"x-bool-\") &amp;&amp; attr.value == \"true\"}'&gt;\n &lt;c:out value=\"${fn:substringAfter(attr.key, 'x-bool-')}\" /&gt;\n &lt;/c:when&gt;\n &lt;c:when test='${fn:startsWith(attr.key, \"x-bool-\") &amp;&amp; attr.value != \"true\"}'&gt;\n &lt;/c:when&gt;\n &lt;c:when test='${fn:startsWith(attr.key, \"x-nc-\")}'&gt;\n &lt;c:out value=\"${fn:substringAfter(attr.key, 'x-nc-')}\" /&gt;=\"&lt;c:out value='${attr.value}' /&gt;\"\n &lt;/c:when&gt;\n &lt;c:when test='${not empty attr.value}'&gt;\n &lt;c:out value=\"${attr.key}\" /&gt;=\"&lt;c:out value='${attr.value}' /&gt;\"\n &lt;/c:when&gt;\n &lt;/c:choose&gt;\n &lt;c:out value=\" \" /&gt;\n&lt;/c:forEach&gt;\n&lt;jsp:doBody var=\"bodyText\" /&gt;\n&lt;c:choose&gt;\n &lt;c:when test=\"${not empty fn:trim(bodyText)}\"&gt;\n &lt;jsp:text&gt;&lt;![CDATA[&gt;]]&gt;&lt;/jsp:text&gt;\n ${bodyText}\n &lt;jsp:text&gt;&lt;![CDATA[&lt;]]&gt;&lt;/jsp:text&gt;\n &lt;c:out value=\"/${tag}\" /&gt;\n &lt;jsp:text&gt;&lt;![CDATA[&gt;]]&gt;&lt;/jsp:text&gt;\n &lt;/c:when&gt;\n &lt;c:otherwise&gt;\n &lt;jsp:text&gt;&lt;![CDATA[/&gt;]]&gt;&lt;/jsp:text&gt;\n &lt;/c:otherwise&gt;\n&lt;/c:choose&gt;\n</code></pre>\n\n<p>To use it put it in a taglib tagdir.</p>\n\n<pre><code>&lt;%@ taglib tagdir=\"/WEB-INF/tags\" prefix=\"xyz\"%&gt;\n...\n&lt;xyz:element tag=\"input\"\n type=\"date\"\n id=\"myDate\"\n name=\"myDate\"\n x-bool-required=\"true\"\n/&gt;\n</code></pre>\n\n<p>The output would render as</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;input \n name=\"myDate\"\n id=\"myDate\"\n type=\"date\"\n required/&gt;\n</code></pre>\n" }, { "answer_id": 60810578, "author": "Ales Dolecek", "author_id": 2956532, "author_profile": "https://Stackoverflow.com/users/2956532", "pm_score": 1, "selected": false, "text": "<p>Correct way to do it with <strong>pure</strong> JSP is this way:</p>\n\n<pre><code>&lt;jsp:element name=\"button\"&gt;\n &lt;jsp:attribute name=\"name\"&gt;btn1&lt;/jsp:attribute&gt;\n &lt;jsp:attribute name=\"disabled\" omit=\"${not isDisabled}\"&gt;disabled&lt;/jsp:attribute&gt;\n &lt;jsp:body&gt;Hello&lt;/jsp:body&gt;\n&lt;/jsp:element&gt;\n</code></pre>\n\n<p>The key is to use <code>omit</code> attribute on <code>&lt;jsp:attribute&gt;</code> - if the expression evaluates to <code>true</code> then the attribute won't be renreder at all.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24068/" ]
In HTML forms, buttons can be disabled by defining the "disabled" attribute on them, with any value: ``` <button name="btn1" disabled="disabled">Hello</button> ``` If a button is to be enabled, the attribute should not exist as there is no defined value that the disabled attribute can be set to that would leave the button enabled. This is causing me problems when I want to enable / disable buttons when using JSP Documents (jspx). As JSP documents have to be well-formed XML documents, I can't see any way of conditionally including this attribute, as something like the following isn't legal: ``` <button name="btn1" <%= (isDisabled) ? "disabled" : "" %/> >Hello</button> ``` While I could replicate the tag twice using a JSTL if tag to get the desired effect, in my specific case I have over 15 attributes declared on the button (lots of javascript event handler attributes for AJAX) so duplicating the tag is going to make the JSP very messy. How can I solve this problem, without sacrificing the readability of the JSP? Are there any custom tags that can add attributes to the parent by manipulating the output DOM?
I use a custom JSP tag with dynamic attributes. You use it like this: ``` <util:element elementName="button" name="btn1" disabled="$(isDisabled ? 'disabled' : '')"/> ``` Basically, what this tag does is generate an XML element with elementName and puts all attributes present in the tag, but skips the empty ones. The tag itself is pretty easy to implement, my implementation is just 44 lines long.
157,020
<p>I have an script that falls over if any of the procedures it is trying to create already exists. How can I check/drop if this procedure is already created?</p>
[ { "answer_id": 157248, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 1, "selected": false, "text": "<p>I would guess something along the lines of:</p>\n\n<pre><code>IF EXISTS\n(\n SELECT *\n FROM SYSPROCS\n WHERE SPECIFIC_SCHEMA = ???\n AND SPECIFIC_NAME = ???\n AND ROUTINE_SCHEMA = ???\n AND ROUTINE_NAME = ???\n)\n DROP PROCEDURE ???\n</code></pre>\n\n<p>I don't know if you actually need the SPECIFIC_* information or not and I don't know how to handle cases where you have two procedures with the same name but different call signatures, but hopefully this gets you on the right track.</p>\n" }, { "answer_id": 413022, "author": "ANIL MANE", "author_id": 51635, "author_profile": "https://Stackoverflow.com/users/51635", "pm_score": 1, "selected": false, "text": "<pre><code>IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Procedure_Name]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)\nDROP PROCEDURE [dbo].[Procedure_Name]\n</code></pre>\n\n<p>I think this would help you</p>\n" }, { "answer_id": 18755080, "author": "cjkoontz", "author_id": 2687374, "author_profile": "https://Stackoverflow.com/users/2687374", "pm_score": 0, "selected": false, "text": "<p>You might check for existence this way (note - make sure of case):</p>\n\n<pre><code>SELECT * \nFROM QSYS2/PROCEDURES \nWHERE PROCNAME LIKE 'your-procedure-name'\nAND PROCSCHEMA = 'your-procedure-library' \n</code></pre>\n" }, { "answer_id": 22590213, "author": "user2338816", "author_id": 2338816, "author_profile": "https://Stackoverflow.com/users/2338816", "pm_score": 0, "selected": false, "text": "<p><code>DROP PROCEDURE xxx ;\nCREATE PROCEDURE XXX\n.\n.\n. ;</code></p>\n\n<p>Include a <code>DROP PROCEDURE</code> as the first statement in the script. If you run with RUNSQLSTM, use ERRLVL(20) to allow the DROP to fail. If you run through 'Run SQL Scripts', use the 'Ignore \"Object not found\" on DROP' option.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have an script that falls over if any of the procedures it is trying to create already exists. How can I check/drop if this procedure is already created?
I would guess something along the lines of: ``` IF EXISTS ( SELECT * FROM SYSPROCS WHERE SPECIFIC_SCHEMA = ??? AND SPECIFIC_NAME = ??? AND ROUTINE_SCHEMA = ??? AND ROUTINE_NAME = ??? ) DROP PROCEDURE ??? ``` I don't know if you actually need the SPECIFIC\_\* information or not and I don't know how to handle cases where you have two procedures with the same name but different call signatures, but hopefully this gets you on the right track.
157,034
<p>I have column that contains strings. The strings in that column look like this:</p> <p>FirstString/SecondString/ThirdString</p> <p>I need to parse this so I have two values:</p> <p>Value 1: FirstString/SecondString Value 2: ThirdString</p> <p>I could have actually longer strings but I always nee it seperated like [string1/string2/string3/...][stringN]</p> <p>What I need to end up with is this:</p> <p>Column1: [string1/string2/string3/etc....] Column2: [stringN]</p> <p>I can't find anyway in access to do this. Any suggestions? Do i need regular expressions? If so, is there a way to do this in the query designer?</p> <p><strong>Update</strong>: Both of the expressions give me this error: "The expression you entered contains invalid syntax, or you need to enclose your text data in quotes."</p> <pre><code>expr1: Left( [Property] , InStrRev( [Property] , "/") - 1), Mid( [Property] , InStrRev( [Property] , "/") + 1) expr1: mid( [Property] , 1, instr( [Property] , "/", -1)) , mid( [Property] , instr( [Property] , "/", -1)+1, length( [Property] )) </code></pre>
[ { "answer_id": 157049, "author": "pappes", "author_id": 19494, "author_profile": "https://Stackoverflow.com/users/19494", "pm_score": 0, "selected": false, "text": "<p>mid(col, 1, instr(col, \"/\", -1)) , mid(col, instr(col, \"/\", -1)+1, length(col)) </p>\n" }, { "answer_id": 157135, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 2, "selected": true, "text": "<p>In a query, use the following two expressions as columns:</p>\n\n<pre><code>Left(col, InStrRev(col, \"/\") - 1), Mid(col, InStrRev(col, \"/\") + 1) \n</code></pre>\n\n<p>col is your column.</p>\n\n<p>If in VBA, use the following:</p>\n\n<pre><code>last_index= InStrRev(your_string, \"/\")\n\nfirst_part= Left$(your_string, last_index - 1)\nlast_part= Mid$(your_string, last_index + 1)\n</code></pre>\n" }, { "answer_id": 168558, "author": "David-W-Fenton", "author_id": 9787, "author_profile": "https://Stackoverflow.com/users/9787", "pm_score": 0, "selected": false, "text": "<p>Is there any chance you can fix the underlying data structure to be properly normalized so that you can avoid the problem in the first place? Along with retrieving the data comes a whole host or problems with maintaining it accurately, and that would all be ameliorated if you weren't storing multiple values in a single field.</p>\n" }, { "answer_id": 493545, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 0, "selected": false, "text": "<p>I know you're trying to do this inside a query so the SQL string functions are probably your best bet.</p>\n\n<p>However, it's worth mentioning that there's a regular expression COM object accessible from VBA. Just add a reference to the Microsoft VBScript Regular Expressions library inside of your macro code.</p>\n\n<p>Then you can do stuff like this</p>\n\n<pre><code>Dim szLine As String\nDim regex As New RegExp\nDim colregmatch As MatchCollection\n\nWith regex\n .MultiLine = False\n .Global = True\n .IgnoreCase = False\nEnd With\n\nszLine = \"FirstString/SecondString/ThirdString\"\n\nregex.Pattern = \"^(.*?\\/.*?)/(.*?)$\"\nSet colregmatch = regex.Execute(szLine)\n\n'FirstString/SecondString\nDebug.Print colregmatch.Item(0).submatches.Item(0)\n'ThirdString\nDebug.Print colregmatch.Item(0).submatches.Item(1)\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17744/" ]
I have column that contains strings. The strings in that column look like this: FirstString/SecondString/ThirdString I need to parse this so I have two values: Value 1: FirstString/SecondString Value 2: ThirdString I could have actually longer strings but I always nee it seperated like [string1/string2/string3/...][stringN] What I need to end up with is this: Column1: [string1/string2/string3/etc....] Column2: [stringN] I can't find anyway in access to do this. Any suggestions? Do i need regular expressions? If so, is there a way to do this in the query designer? **Update**: Both of the expressions give me this error: "The expression you entered contains invalid syntax, or you need to enclose your text data in quotes." ``` expr1: Left( [Property] , InStrRev( [Property] , "/") - 1), Mid( [Property] , InStrRev( [Property] , "/") + 1) expr1: mid( [Property] , 1, instr( [Property] , "/", -1)) , mid( [Property] , instr( [Property] , "/", -1)+1, length( [Property] )) ```
In a query, use the following two expressions as columns: ``` Left(col, InStrRev(col, "/") - 1), Mid(col, InStrRev(col, "/") + 1) ``` col is your column. If in VBA, use the following: ``` last_index= InStrRev(your_string, "/") first_part= Left$(your_string, last_index - 1) last_part= Mid$(your_string, last_index + 1) ```
157,039
<p>I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three.</p> <p>My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the <a href="http://www.refactoring.com/catalog/splitLoop.html" rel="noreferrer">split loop</a> refactoring in mind), looks rather bloated:</p> <p>(alt 1)</p> <pre><code>r = xrange(1, 10) twos = 0 threes = 0 for v in r: if v % 2 == 0: twos+=1 if v % 3 == 0: threes+=1 print twos print threes </code></pre> <p>This looks rather nice, but has the drawback of expanding the expression to a list:</p> <p>(alt 2)</p> <pre><code>r = xrange(1, 10) print len([1 for v in r if v % 2 == 0]) print len([1 for v in r if v % 3 == 0]) </code></pre> <p>What I would really like is something like a function like this:</p> <p>(alt 3)</p> <pre><code>def count(iterable): n = 0 for i in iterable: n += 1 return n r = xrange(1, 10) print count(1 for v in r if v % 2 == 0) print count(1 for v in r if v % 3 == 0) </code></pre> <p>But this looks a lot like something that could be done without a function. The final variant is this:</p> <p>(alt 4)</p> <pre><code>r = xrange(1, 10) print sum(1 for v in r if v % 2 == 0) print sum(1 for v in r if v % 3 == 0) </code></pre> <p>and while the smallest (and in my book probably the most elegant) it doesn't feel like it expresses the intent very well.</p> <p>So, my question to you is:</p> <p>Which alternative do you like best to gather these types of stats? Feel free to supply your own alternative if you have something better.</p> <p>To clear up some confusion below:</p> <ul> <li>In reality my filter predicates are more complex than just this simple test.</li> <li>The objects I iterate over are larger and more complex than just numbers</li> <li>My filter functions are more different and hard to parameterize into one predicate</li> </ul>
[ { "answer_id": 157080, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 2, "selected": false, "text": "<p>You could use the <a href=\"http://docs.python.org/lib/built-in-funcs.html\" rel=\"nofollow noreferrer\"><code>filter</code></a> function.</p>\n\n<p>It filters a list (or strictly an iterable) producing a new list containing only the items for which the specified function evaluates to true.</p>\n\n<pre><code>r = xrange(1, 10)\n\ndef is_div_two(n):\n return n % 2 == 0\n\ndef is_div_three(n):\n return n % 3 == 0\n\nprint len(filter(is_div_two,r))\nprint len(filter(is_div_three,r))\n</code></pre>\n\n<p>This is good as it allows you keep your statistics logic contained in a function and the intent of the <code>filter</code> should be pretty clear.</p>\n" }, { "answer_id": 157088, "author": "Simon", "author_id": 24039, "author_profile": "https://Stackoverflow.com/users/24039", "pm_score": 0, "selected": false, "text": "<p>I would definitely be looking at a <a href=\"http://www.numpy.org/\" rel=\"nofollow noreferrer\">numpy</a> array instead of an iterable list if you just have numbers. You will almost certainly be able to do what you want with some terse arithmetic on the array.</p>\n" }, { "answer_id": 157094, "author": "John Montgomery", "author_id": 5868, "author_profile": "https://Stackoverflow.com/users/5868", "pm_score": 1, "selected": false, "text": "<p>Well you could do one list comprehension/expression to get a set of tuples with that stat test in them and then reduce that down to get the sums.</p>\n\n<pre><code>\nr=xrange(10)\ns=( (v % 2 == 0, v % 3 == 0) for v in r )\ndef add_tuples(t1,t2):\n return tuple(x+y for x,y in zip(t1, t2))\nsums=reduce(add_tuples, s, (0,0)) # (0,0) is starting amount\n\nprint sums[0] # sum of numbers divisible by 2\nprint sums[1] # sum of numbers divisible by 3\n</code>\n</pre>\n\n<p>Using generator expression etc should mean you'll only run through the iterator once (unless reduce does anything odd?). Basically you'd be doing map/reduce...</p>\n" }, { "answer_id": 157099, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 0, "selected": false, "text": "<p>Not as terse as you are looking for, but more efficient, it actually works with any iterable, not just iterables you can loop over multiple times, and you can expand the things to check for without complicating it further:</p>\n\n<pre><code>r = xrange(1, 10)\n\ncounts = {\n 2: 0,\n 3: 0,\n}\n\nfor v in r:\n for q in counts:\n if not v % q:\n counts[q] += 1\n # Or, more obscure:\n #counts[q] += not v % q\n\nfor q in counts:\n print \"%s's: %s\" % (q, counts[q])\n</code></pre>\n" }, { "answer_id": 157121, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Alt 4! But maybe you should refactor the code to a function that takes an argument which should contain the divisible number (two and three). And then you could have a better functionname.</p>\n\n<pre><code>def methodName(divNumber, r):\n return sum(1 for v in r if v % divNumber == 0)\n\n\nprint methodName(2, xrange(1, 10))\nprint methodName(3, xrange(1, 10))\n</code></pre>\n" }, { "answer_id": 157141, "author": "Anders Waldenborg", "author_id": 24082, "author_profile": "https://Stackoverflow.com/users/24082", "pm_score": 5, "selected": true, "text": "<p>Having to iterate over the list multiple times isn't elegant IMHO.</p>\n\n<p>I'd probably create a function that allows doing:</p>\n\n<pre><code>twos, threes = countmatching(xrange(1,10),\n lambda a: a % 2 == 0,\n lambda a: a % 3 == 0)\n</code></pre>\n\n<p>A starting point would be something like this:</p>\n\n<pre><code>def countmatching(iterable, *predicates):\n v = [0] * len(predicates)\n for e in iterable:\n for i,p in enumerate(predicates):\n if p(e):\n v[i] += 1\n return tuple(v)\n</code></pre>\n\n<p>Btw, \"itertools recipes\" has a recipe for doing much like your alt4.</p>\n\n<pre><code>def quantify(seq, pred=None):\n \"Count how many times the predicate is true in the sequence\"\n return sum(imap(pred, seq))\n</code></pre>\n" }, { "answer_id": 157181, "author": "ironfroggy", "author_id": 19687, "author_profile": "https://Stackoverflow.com/users/19687", "pm_score": 0, "selected": false, "text": "<pre><code>from itertools import groupby\nfrom collections import defaultdict\n\ndef multiples(v):\n return 2 if v%2==0 else 3 if v%3==0 else None\nd = defaultdict(list)\n\nfor k, values in groupby(range(10), multiples):\n if k is not None:\n d[k].extend(values)\n</code></pre>\n" }, { "answer_id": 157620, "author": "seuvitor", "author_id": 23477, "author_profile": "https://Stackoverflow.com/users/23477", "pm_score": 0, "selected": false, "text": "<p>The idea here is to use reduction to avoid repeated iterations. Also, this does not create any extra data structures, if memory is an issue for you. You start with a dictionary with your counters (<code>{'div2': 0, 'div3': 0}</code>) and increment them along the iteration.</p>\n\n<pre><code>def increment_stats(stats, n):\n if n % 2 == 0: stats['div2'] += 1\n if n % 3 == 0: stats['div3'] += 1\n return stats\n\nr = xrange(1, 10)\nstats = reduce(increment_stats, r, {'div2': 0, 'div3': 0})\nprint stats\n</code></pre>\n\n<p>If you want to count anything more complicated than divisors, it would be appropriate to use a more object-oriented approach (with the same advantages), encapsulating the logic for stats extraction.</p>\n\n<pre><code>class Stats:\n\n def __init__(self, div2=0, div3=0):\n self.div2 = div2\n self.div3 = div3\n\n def increment(self, n):\n if n % 2 == 0: self.div2 += 1\n if n % 3 == 0: self.div3 += 1\n return self\n\n def __repr__(self):\n return 'Stats(%d, %d)' % (self.div2, self.div3)\n\nr = xrange(1, 10)\nstats = reduce(lambda stats, n: stats.increment(n), r, Stats())\nprint stats\n</code></pre>\n\n<p>Please point out any mistakes.</p>\n\n<p>@Henrik: I think the first approach is less maintainable since you have to control initialization of the dictionary in one place and update in another, as well as having to use strings to refer to each stat (instead of having attributes). And I do not think OO is overkill in this case, for you said the predicates and objects will be complex in your application. In fact if the predicates were really simple, I wouldn't even bother to use a dictionary, a single fixed size list would be just fine. Cheers :)</p>\n" }, { "answer_id": 158250, "author": "Henrik Gustafsson", "author_id": 2010, "author_profile": "https://Stackoverflow.com/users/2010", "pm_score": 0, "selected": false, "text": "<p>Inspired by the OO-stab above, I had to try my hands on one as well (although this is way overkill for the problem I'm trying to solve :)</p>\n\n<pre><code>class Stat(object):\n def update(self, n):\n raise NotImplementedError\n\n def get(self):\n raise NotImplementedError\n\n\nclass TwoStat(Stat):\n def __init__(self):\n self._twos = 0\n\n def update(self, n):\n if n % 2 == 0: self._twos += 1\n\n def get(self):\n return self._twos\n\n\nclass ThreeStat(Stat):\n def __init__(self):\n self._threes = 0\n\n def update(self, n):\n if n % 3 == 0: self._threes += 1\n\n def get(self):\n return self._threes\n\n\nclass StatCalculator(object):\n def __init__(self, stats):\n self._stats = stats\n\n def calculate(self, r):\n for v in r:\n for stat in self._stats:\n stat.update(v)\n return tuple(stat.get() for stat in self._stats)\n\n\ns = StatCalculator([TwoStat(), ThreeStat()])\n\nr = xrange(1, 10)\nprint s.calculate(r)\n</code></pre>\n" }, { "answer_id": 158587, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 1, "selected": false, "text": "<p>True booleans are coerced to unit integers, and false booleans to zero integers. So if you're happy to use scipy or numpy, make an array of integers for each element of your sequence, each array containing one element for each of your tests, and sum over the arrays. E.g.</p>\n\n<pre><code>&gt;&gt;&gt; sum(scipy.array([c % 2 == 0, c % 3 == 0]) for c in xrange(10))\narray([5, 4])\n</code></pre>\n" }, { "answer_id": 158632, "author": "Kirk Strauser", "author_id": 32538, "author_profile": "https://Stackoverflow.com/users/32538", "pm_score": 0, "selected": false, "text": "<p>Alt 3, for the reason that it doesn't use memory proportional to the number of \"hits\". Given a pathological case like xrange(one_trillion), many of the other offered solutions would fail badly.</p>\n" }, { "answer_id": 163273, "author": "Sébastien RoccaSerra", "author_id": 2797, "author_profile": "https://Stackoverflow.com/users/2797", "pm_score": 2, "selected": false, "text": "<p>I would choose a small variant of your (alt 4):</p>\n\n<pre><code>def count(predicate, list):\n print sum(1 for x in list if predicate(x))\n\nr = xrange(1, 10)\n\ncount(lambda x: x % 2 == 0, r)\ncount(lambda x: x % 3 == 0, r)\n# ...\n</code></pre>\n\n<p>If you want to change what count does, change its implementation in one place.</p>\n\n<p>Note: since your predicates are complex, you'll probably want to define them in functions instead of lambdas. And so you'll probably want to put all this in a class rather than the global namespace.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2010/" ]
I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three. My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the [split loop](http://www.refactoring.com/catalog/splitLoop.html) refactoring in mind), looks rather bloated: (alt 1) ``` r = xrange(1, 10) twos = 0 threes = 0 for v in r: if v % 2 == 0: twos+=1 if v % 3 == 0: threes+=1 print twos print threes ``` This looks rather nice, but has the drawback of expanding the expression to a list: (alt 2) ``` r = xrange(1, 10) print len([1 for v in r if v % 2 == 0]) print len([1 for v in r if v % 3 == 0]) ``` What I would really like is something like a function like this: (alt 3) ``` def count(iterable): n = 0 for i in iterable: n += 1 return n r = xrange(1, 10) print count(1 for v in r if v % 2 == 0) print count(1 for v in r if v % 3 == 0) ``` But this looks a lot like something that could be done without a function. The final variant is this: (alt 4) ``` r = xrange(1, 10) print sum(1 for v in r if v % 2 == 0) print sum(1 for v in r if v % 3 == 0) ``` and while the smallest (and in my book probably the most elegant) it doesn't feel like it expresses the intent very well. So, my question to you is: Which alternative do you like best to gather these types of stats? Feel free to supply your own alternative if you have something better. To clear up some confusion below: * In reality my filter predicates are more complex than just this simple test. * The objects I iterate over are larger and more complex than just numbers * My filter functions are more different and hard to parameterize into one predicate
Having to iterate over the list multiple times isn't elegant IMHO. I'd probably create a function that allows doing: ``` twos, threes = countmatching(xrange(1,10), lambda a: a % 2 == 0, lambda a: a % 3 == 0) ``` A starting point would be something like this: ``` def countmatching(iterable, *predicates): v = [0] * len(predicates) for e in iterable: for i,p in enumerate(predicates): if p(e): v[i] += 1 return tuple(v) ``` Btw, "itertools recipes" has a recipe for doing much like your alt4. ``` def quantify(seq, pred=None): "Count how many times the predicate is true in the sequence" return sum(imap(pred, seq)) ```
157,044
<p>I'm attempting to check for the existence of a node using the following .NET code:</p> <pre><code>xmlDocument.SelectSingleNode( String.Format("//ErrorTable/ProjectName/text()='{0}'", projectName)); </code></pre> <p>This always raises:</p> <blockquote> <p>XPathException: Expression must evaluate to a node-set. </p> </blockquote> <p>Why am I getting this error and how can I resolve it? Thank you.</p>
[ { "answer_id": 157085, "author": "rjohnston", "author_id": 246, "author_profile": "https://Stackoverflow.com/users/246", "pm_score": 1, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>Node node = xmlDocument.SelectSingleNode(String.Format(\"//ErrorTable/ProjectName = '{0}'\", projectName));\n\nif (node != null) {\n // and so on\n}\n</code></pre>\n\n<p>Edit: silly error</p>\n" }, { "answer_id": 157152, "author": "Alex Angas", "author_id": 6651, "author_profile": "https://Stackoverflow.com/users/6651", "pm_score": 1, "selected": false, "text": "<p>The XPath expression contained a subtle error. It should have been:</p>\n\n<pre><code>xmlDocument.SelectSingleNode(String.Format(\"//ErrorTable/ProjectName[text()='{0}']\", projectName));\n</code></pre>\n\n<p>The previous expression was evaluating to a boolean, which explains the exception error. Thanks for the help!</p>\n" }, { "answer_id": 157177, "author": "TToni", "author_id": 20703, "author_profile": "https://Stackoverflow.com/users/20703", "pm_score": 5, "selected": true, "text": "<p>The expression given evaluates to a boolean, not a node-set. I assume you want to check whether the ProjectName equals the parametrized text. In this case you need to write</p>\n\n<pre><code>//ErrorTable/ProjectName[text()='{0}']\n</code></pre>\n\n<p>This gives you a list of all nodes (a nodeset) matching the given condition. This list may be empty, in which case the C#-Expression in your sample will return null.</p>\n\n<p>As an afterthought: You <strong>can</strong> use the original xpath expression, but not with SelectSingleNode, but with Evaluate, like this:</p>\n\n<pre><code>(bool)xmlDocument.CreateNavigator().Evaluate(String.Format(\"//ErrorTable/ProjectName/text()='{0}'\", projectName));\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6651/" ]
I'm attempting to check for the existence of a node using the following .NET code: ``` xmlDocument.SelectSingleNode( String.Format("//ErrorTable/ProjectName/text()='{0}'", projectName)); ``` This always raises: > > XPathException: Expression must evaluate to a node-set. > > > Why am I getting this error and how can I resolve it? Thank you.
The expression given evaluates to a boolean, not a node-set. I assume you want to check whether the ProjectName equals the parametrized text. In this case you need to write ``` //ErrorTable/ProjectName[text()='{0}'] ``` This gives you a list of all nodes (a nodeset) matching the given condition. This list may be empty, in which case the C#-Expression in your sample will return null. As an afterthought: You **can** use the original xpath expression, but not with SelectSingleNode, but with Evaluate, like this: ``` (bool)xmlDocument.CreateNavigator().Evaluate(String.Format("//ErrorTable/ProjectName/text()='{0}'", projectName)); ```
157,058
<p>I have a list of tuples eg. [{1,40},{2,45},{3,54}....{7,23}] where 1...7 are days of the week (calculated by finding calendar:day_of_the_week()). So now I want to change the list to [{Mon,40},{Tue,45},{Wed,54}...{Sun,23}]. Is there an easier way to do it than lists:keyreplace?</p>
[ { "answer_id": 157112, "author": "Jon Gretar", "author_id": 5601, "author_profile": "https://Stackoverflow.com/users/5601", "pm_score": 3, "selected": true, "text": "<p>Simple. Use map and a handy tool from the httpd module.</p>\n\n<pre><code>lists:map(fun({A,B}) -&gt; {httpd_util:day(A),B} end, [{1,40},{2,45},{3,54},{7,23}]).\n</code></pre>\n" }, { "answer_id": 173536, "author": "uwiger", "author_id": 6834, "author_profile": "https://Stackoverflow.com/users/6834", "pm_score": 4, "selected": false, "text": "<p>... or using a different syntax:</p>\n\n<pre><code>[{httpd_util:day(A), B} || {A,B} &lt;- L]\n</code></pre>\n\n<p>where:</p>\n\n<pre><code>L = [{1,40},{2,45},{3,54}....{7,23}]\n</code></pre>\n\n<p>The construct is called a <em><a href=\"http://www.erlang.org/doc/programming_examples/list_comprehensions.html#3\" rel=\"nofollow noreferrer\">list comprehension</a></em>, and reads as:</p>\n\n<blockquote>\n <p>\"Build a list of <code>{httpd_util:day(A),B}</code> tuples, where <code>{A,B}</code> is taken from the list <code>L</code>\"</p>\n</blockquote>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2727/" ]
I have a list of tuples eg. [{1,40},{2,45},{3,54}....{7,23}] where 1...7 are days of the week (calculated by finding calendar:day\_of\_the\_week()). So now I want to change the list to [{Mon,40},{Tue,45},{Wed,54}...{Sun,23}]. Is there an easier way to do it than lists:keyreplace?
Simple. Use map and a handy tool from the httpd module. ``` lists:map(fun({A,B}) -> {httpd_util:day(A),B} end, [{1,40},{2,45},{3,54},{7,23}]). ```
157,070
<p>When you're adding javaDoc comments to your code and you're outlining the structure of an XML document that you're passing back, what's the best way to represent attributes? Is there a best practice for this?</p> <p>My general structure for my javaDoc comments is like this:</p> <pre><code>/** * ... * * @return XML document in the form: * * &lt;pre&gt; * &amp;lt;ROOT_ELEMENT&amp;gt; * &amp;lt;AN_ELEMENT&amp;gt; * &amp;lt;MULTIPLE_ELEMENTS&amp;gt;* * &amp;lt;/ROOT_ELEMENT&amp;gt; * &lt;/pre&gt; */ </code></pre>
[ { "answer_id": 157109, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 2, "selected": true, "text": "<p>Not sure I clearly understand your question.</p>\n\n<p>My preferred solution would be to embed the schema XSD or DTC in the description of the return parameter. Your solution seems to lead to personal idioms on how to represent things like multiple elements or others. Using a standard like XSD or DTD allows you to have a well know and recognized language on how to describe the structure of a XML document.</p>\n\n<p>Regarding the JavaDoc representation if you are using Eclipse you can specify under Save Actions to format your document. This way you can write normally with &gt; and &lt; and see it converted to the escaped HTML codes.</p>\n" }, { "answer_id": 166205, "author": "Philip Morton", "author_id": 21709, "author_profile": "https://Stackoverflow.com/users/21709", "pm_score": 0, "selected": false, "text": "<p>In the end, I just went with:</p>\n\n<pre><code>/**\n * ...\n * \n * @return XML document in the form:\n * \n * &lt;pre&gt;\n * &amp;lt;ROOT_ELEMENT&amp;gt;\n * &amp;lt;AN_ELEMENT attribute1 attribute2&amp;gt;\n * &amp;lt;MULTIPLE_ELEMENTS&amp;gt;*\n * &amp;lt;/ROOT_ELEMENT&amp;gt;\n * &lt;/pre&gt;\n */\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21709/" ]
When you're adding javaDoc comments to your code and you're outlining the structure of an XML document that you're passing back, what's the best way to represent attributes? Is there a best practice for this? My general structure for my javaDoc comments is like this: ``` /** * ... * * @return XML document in the form: * * <pre> * &lt;ROOT_ELEMENT&gt; * &lt;AN_ELEMENT&gt; * &lt;MULTIPLE_ELEMENTS&gt;* * &lt;/ROOT_ELEMENT&gt; * </pre> */ ```
Not sure I clearly understand your question. My preferred solution would be to embed the schema XSD or DTC in the description of the return parameter. Your solution seems to lead to personal idioms on how to represent things like multiple elements or others. Using a standard like XSD or DTD allows you to have a well know and recognized language on how to describe the structure of a XML document. Regarding the JavaDoc representation if you are using Eclipse you can specify under Save Actions to format your document. This way you can write normally with > and < and see it converted to the escaped HTML codes.
157,114
<p>I made a view to abstract columns of different tables and pre-filter and pre-sort them. There is one column whose content I don't care about but I need to know whether the content is null or not. So my view should pass an alias as "<em>true</em>" in case the value of this specified column <strong>isn't null</strong> and "<em>false</em>" in case the value <strong>is null</strong>.</p> <p>How can I select such a boolean with T-SQL?</p>
[ { "answer_id": 157136, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 7, "selected": true, "text": "<p>You have to use a <strong>CASE</strong> statement for this:</p>\n\n<pre><code>SELECT CASE WHEN columnName IS NULL THEN 'false' ELSE 'true' END FROM tableName;\n</code></pre>\n" }, { "answer_id": 157148, "author": "tocsoft", "author_id": 234855, "author_profile": "https://Stackoverflow.com/users/234855", "pm_score": 3, "selected": false, "text": "<p>for the column in the view you can use something like</p>\n\n<pre><code>CASE WHEN ColumnName is not null THEN 'True' ELSE 'False' END\n</code></pre>\n\n<p>or in a statement </p>\n\n<pre><code>SELECT \ns.ID,\ns.[Name],\nCASE WHEN s.AchievedDate is not null THEN 'True' ELSE 'False' END [IsAchieved]\nFROM Schools s\n</code></pre>\n\n<p>or for further processing afterwards I would personally use</p>\n\n<pre><code>SELECT \ns.ID,\ns.[Name],\nCASE WHEN s.AchievedDate is not null THEN 1 ELSE 0 END [IsAchieved]\nFROM Schools s\n</code></pre>\n" }, { "answer_id": 6181829, "author": "lcrepas", "author_id": 396845, "author_profile": "https://Stackoverflow.com/users/396845", "pm_score": 3, "selected": false, "text": "<p>I had a similar issue where I wanted a view to return a boolean column type based on if an actual column as null or not. I created a user defined function like so:</p>\n\n<pre><code>CREATE FUNCTION IsDatePopulated(@DateColumn as datetime)\nRETURNS bit\nAS\nBEGIN\n DECLARE @ReturnBit bit;\n\n SELECT @ReturnBit = \n CASE WHEN @DateColumn IS NULL \n THEN 0 \n ELSE 1 \n END\n\n RETURN @ReturnBit\nEND\n</code></pre>\n\n<p>Then the view that I created returns a bit column, instead of an integer.</p>\n\n<pre><code>CREATE VIEW testView\nAS\n SELECT dbo.IsDatePopulated(DateDeleted) as [IsDeleted] \n FROM Company\n</code></pre>\n" }, { "answer_id": 6385371, "author": "Schnapz", "author_id": 789012, "author_profile": "https://Stackoverflow.com/users/789012", "pm_score": 5, "selected": false, "text": "<p>Or you can do like this:</p>\n\n<pre><code> SELECT RealColumn, CAST(0 AS bit) AS FakeBitColumn FROM tblTable\n</code></pre>\n" }, { "answer_id": 28335292, "author": "Mahesh", "author_id": 446154, "author_profile": "https://Stackoverflow.com/users/446154", "pm_score": 4, "selected": false, "text": "<p>If you need a output as boolean</p>\n\n<pre><code>CAST(CASE WHEN colName IS NULL THEN 0 ELSE 1 END as BIT) aIsBooked\n</code></pre>\n" }, { "answer_id": 35187298, "author": "Steve Sether", "author_id": 4071806, "author_profile": "https://Stackoverflow.com/users/4071806", "pm_score": 3, "selected": false, "text": "<p>You asked for boolean, which we call bit in t-sql.</p>\n\n<p>Other answers have either given you a varchar 'true' and 'false' or 1 and 0. 'true' and 'false' are obviously varchar, not boolean. I believe 1 and 0 would be cast as an integer, but it's certainly not a bit. This may seem nit-picky, but types matter quite often.</p>\n\n<p>To get an actual bit value, you need to cast your output explicitly as a bit like:</p>\n\n<pre><code>select case when tableName.columnName IS NULL then cast(0 as bit) else cast(1\nas bit) END as ColumnLabel from tableName\n</code></pre>\n" }, { "answer_id": 62957831, "author": "todji", "author_id": 12647728, "author_profile": "https://Stackoverflow.com/users/12647728", "pm_score": 1, "selected": false, "text": "<p>I think this is slightly simpler then the other solutions:</p>\n<p>SELECT Cast(ISNULL([column name], 0) AS BIT) AS IsWhatever</p>\n" }, { "answer_id": 71574433, "author": "Mirek Michalak", "author_id": 2047471, "author_profile": "https://Stackoverflow.com/users/2047471", "pm_score": 0, "selected": false, "text": "<p>Since SQL server 2012 you can use <code>IIF</code></p>\n<pre><code>IIF(columnName IS NULL, 'false', 'true')\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5703/" ]
I made a view to abstract columns of different tables and pre-filter and pre-sort them. There is one column whose content I don't care about but I need to know whether the content is null or not. So my view should pass an alias as "*true*" in case the value of this specified column **isn't null** and "*false*" in case the value **is null**. How can I select such a boolean with T-SQL?
You have to use a **CASE** statement for this: ``` SELECT CASE WHEN columnName IS NULL THEN 'false' ELSE 'true' END FROM tableName; ```
157,119
<p>As far as i know it is not possible to do the following in C# 2.0</p> <pre><code>public class Father { public virtual Father SomePropertyName { get { return this; } } } public class Child : Father { public override Child SomePropertyName { get { return this; } } } </code></pre> <p>I workaround the problem by creating the property in the derived class as "new", but of course that is not polymorphic.</p> <pre><code>public new Child SomePropertyName </code></pre> <p>Is there any solution in 2.0? What about any features in 3.5 that address this matter? </p>
[ { "answer_id": 157128, "author": "Anthony", "author_id": 5599, "author_profile": "https://Stackoverflow.com/users/5599", "pm_score": 1, "selected": false, "text": "<p>No. C# does not support this idea (it's called \"return type covariance\"). \nYou can however do this:</p>\n\n<pre><code>public class FatherProp\n{\n}\n\npublic class ChildProp: FatherProp\n{\n}\n\n\npublic class Father\n{\n public virtual FatherProp SomePropertyName\n {\n get\n {\n return new FatherProp();\n }\n }\n}\n\n\npublic class Child : Father\n{\n public override FatherProp SomePropertyName\n {\n get\n {\n // override to return a derived type instead\n return new ChildProp();\n }\n }\n}\n</code></pre>\n\n<p>i.e. use the contract defined by the base class, but return a derived type. I have made a more detailed sample to make this point clearer - returning \"this\" again wouldn't change anything.</p>\n\n<p>It is possible (but messy) to test the returned object for it's actual type (i.e. \"if someObject is ChildProp\"), but it is better to call a virtual method on it that does the right thing for its type.</p>\n\n<p>The base class virtual method (in this case, virtual property) not only has an implementation, but also defines a contract: that a child class can supply a different implementation of SomePropertyName if it meets this contract (i.e. SomePropertyName returns an object of type \"FatherProp\"). Returning an object of type \"ChildProp\" derived from \"FatherProp\" meets this contract. But you can't change the contract in \"Child\" - this contract applies to all classes descended from \"Father\".</p>\n\n<p>If you take a step back and look at your broader design, there are other language constructs in the C# toolkit that you may also want to think about instead - Generics, or interfaces.</p>\n" }, { "answer_id": 157137, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": false, "text": "<p>You can re-declare (new), but you can't re-declare and override at the same time (with the same name).\nOne option is to use a protected method to hide the detail - this allows both polymorphism and hiding at the same time:</p>\n\n<pre><code>public class Father\n{\n public Father SomePropertyName\n {\n get {\n return SomePropertyImpl();\n }\n }\n protected virtual Father SomePropertyImpl()\n {\n // base-class version\n }\n}\n\npublic class Child : Father\n{\n public new Child SomePropertyName\n {\n get\n { // since we know our local SomePropertyImpl actually returns a Child\n return (Child)SomePropertyImpl();\n }\n }\n protected override Father SomePropertyImpl()\n {\n // do something different, might return a Child\n // but typed as Father for the return\n }\n}\n</code></pre>\n" }, { "answer_id": 157138, "author": "dalle", "author_id": 19100, "author_profile": "https://Stackoverflow.com/users/19100", "pm_score": 3, "selected": false, "text": "<p>From <a href=\"http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)#C.23\" rel=\"noreferrer\">Wikipedia</a>:</p>\n\n<blockquote>\n <p>In the C# programming language, support for both return-type\n covariance and parameter\n contravariance for delegates was added\n in version 2.0 of the language.\n Neither covariance nor contravariance\n are supported for method overriding.</p>\n</blockquote>\n\n<p>It doesn't explicitly say anything about covariance of properties though.</p>\n" }, { "answer_id": 157142, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 4, "selected": false, "text": "<p>No, but you can use generics in 2 and above:</p>\n\n<pre><code>public class MyClass&lt;T&gt; where T: Person\n{\n public virtual T SomePropertyName\n {\n get\n {\n return ...;\n }\n }\n}\n</code></pre>\n\n<p>Then Father and Child are generic versions of the same class</p>\n" }, { "answer_id": 157164, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 2, "selected": false, "text": "<p>You can create a common interface for father and child and return a type of that interface.</p>\n" }, { "answer_id": 157255, "author": "Micah", "author_id": 17744, "author_profile": "https://Stackoverflow.com/users/17744", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>No. C# does not support this idea\n (it's called \"return type\n covariance\").</p>\n \n <p>From Wikipedia:</p>\n \n <p>In the C# programming language,\n support for both return-type\n covariance and parameter\n contravariance for delegates was added\n in version 2.0 of the language.\n Neither covariance nor contravariance\n are supported for method overriding.</p>\n \n <p>You can re-declare (new), but you\n can't re-declare and override at the\n same time (with the same name). One\n option is to use a protected method to\n hide the detail - this allows both\n polymorphism and hiding at the same\n time:</p>\n</blockquote>\n\n<p>The best solutions would be to use generics:</p>\n\n<pre><code>public class MyClass&lt;T&gt; where T: Person\n{\n public virtual T SomePropertyNameA\n { \n get { return ...; } \n }\n}//Then the Father and Child are generic versions of the same class\n</code></pre>\n" }, { "answer_id": 157263, "author": "Alex Lyman", "author_id": 5897, "author_profile": "https://Stackoverflow.com/users/5897", "pm_score": 6, "selected": true, "text": "<p>This is not possible in any .NET language because of type-safety concerns. In type-safe languages, you must provide covariance for return values, and contravariance for parameters. Take this code:</p>\n\n<pre><code>class B {\n S Get();\n Set(S);\n}\nclass D : B {\n T Get();\n Set(T);\n}\n</code></pre>\n\n<p>For the <code>Get</code> methods, covariance means that <code>T</code> must either be <code>S</code> or a type derived from <code>S</code>. Otherwise, if you had a reference to an object of type <code>D</code> stored in a variable typed <code>B</code>, when you called <code>B.Get()</code> you wouldn't get an object representable as an <code>S</code> back -- breaking the type system.</p>\n\n<p>For the <code>Set</code> methods, contravariance means that <code>T</code> must either be <code>S</code> or a type that <code>S</code> derives from. Otherwise, if you had a reference to an object of type <code>D</code> stored in a variable typed <code>B</code>, when you called <code>B.Set(X)</code>, where <code>X</code> was of type <code>S</code> but not of type <code>T</code>, <code>D::Set(T)</code> would get an object of a type it did not expect.</p>\n\n<p>In C#, there was a conscious decision to disallow changing the type when overloading properties, even when they have only one of the getter/setter pair, because it would otherwise have very inconsistent behavior (<em>\"You mean, I can change the type on the one with a getter, but not one with both a getter and setter? Why not?!?\"</em> -- Anonymous Alternate Universe Newbie).</p>\n" }, { "answer_id": 189636, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "<p>This is the closest I could come (so far):</p>\n<pre><code>public sealed class JustFather : Father&lt;JustFather&gt; {}\n\npublic class Father&lt;T&gt; where T : Father&lt;T&gt;\n{ \n public virtual T SomePropertyName\n { get { return (T) this; }\n }\n}\n\npublic class Child : Father&lt;Child&gt;\n{ \n public override Child SomePropertyName\n { get { return this; }\n }\n}\n</code></pre>\n<p>Without the <code>JustFather</code> class, you couldn't instantiate a <code>Father&lt;T&gt;</code> unless it was some other derived type.</p>\n" }, { "answer_id": 68627108, "author": "MarredCheese", "author_id": 5405967, "author_profile": "https://Stackoverflow.com/users/5405967", "pm_score": 3, "selected": false, "text": "<h1>Modern answer</h1>\n<p>As of <strong>C# 9</strong>, <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/covariant-returns\" rel=\"noreferrer\">return type covariance is supported</a>. Here's a basic example copied from that link:</p>\n<pre><code>class Compilation ...\n{\n public virtual Compilation WithOptions(Options options)...\n}\n\nclass CSharpCompilation : Compilation\n{\n public override CSharpCompilation WithOptions(Options options)...\n}\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20335/" ]
As far as i know it is not possible to do the following in C# 2.0 ``` public class Father { public virtual Father SomePropertyName { get { return this; } } } public class Child : Father { public override Child SomePropertyName { get { return this; } } } ``` I workaround the problem by creating the property in the derived class as "new", but of course that is not polymorphic. ``` public new Child SomePropertyName ``` Is there any solution in 2.0? What about any features in 3.5 that address this matter?
This is not possible in any .NET language because of type-safety concerns. In type-safe languages, you must provide covariance for return values, and contravariance for parameters. Take this code: ``` class B { S Get(); Set(S); } class D : B { T Get(); Set(T); } ``` For the `Get` methods, covariance means that `T` must either be `S` or a type derived from `S`. Otherwise, if you had a reference to an object of type `D` stored in a variable typed `B`, when you called `B.Get()` you wouldn't get an object representable as an `S` back -- breaking the type system. For the `Set` methods, contravariance means that `T` must either be `S` or a type that `S` derives from. Otherwise, if you had a reference to an object of type `D` stored in a variable typed `B`, when you called `B.Set(X)`, where `X` was of type `S` but not of type `T`, `D::Set(T)` would get an object of a type it did not expect. In C#, there was a conscious decision to disallow changing the type when overloading properties, even when they have only one of the getter/setter pair, because it would otherwise have very inconsistent behavior (*"You mean, I can change the type on the one with a getter, but not one with both a getter and setter? Why not?!?"* -- Anonymous Alternate Universe Newbie).
157,132
<p>I'd like to limit the size of the file that can be uploaded to an application. To achieve this, I'd like to abort the upload process from the server side when the size of the file being uploaded exceeds a limit.</p> <p>Is there a way to abort an upload process from the server side without waiting the HTTP request to finish?</p>
[ { "answer_id": 157188, "author": "Nikhil Kashyap", "author_id": 11299, "author_profile": "https://Stackoverflow.com/users/11299", "pm_score": 1, "selected": false, "text": "<p>You might try doing this in the doPost() method of your servlet </p>\n\n<pre><code>multi = new MultipartRequest(request, dirName, FILE_SIZE_LIMIT); \n\nif(submitButton.equals(multi.getParameter(\"Submit\")))\n{\n out.println(\"Files:\");\n Enumeration files = multi.getFileNames();\n while (files.hasMoreElements()) {\n String name = (String)files.nextElement();\n String filename = multi.getFilesystemName(name);\n String type = multi.getContentType(name);\n File f = multi.getFile(name);\n if (f.length() &gt; FILE_SIZE_LIMIT)\n {\n //show error message or\n //return;\n return;\n }\n}\n</code></pre>\n\n<p>This way you don't have to wait to completely process your HttpRequest and can return or show an error message back to the client side. HTH</p>\n" }, { "answer_id": 157322, "author": "Drejc", "author_id": 6482, "author_profile": "https://Stackoverflow.com/users/6482", "pm_score": 3, "selected": true, "text": "<p>You can do something like this (using the <a href=\"http://commons.apache.org/fileupload/\" rel=\"nofollow noreferrer\">Commons</a> library):</p>\n\n<pre><code> public class UploadFileServiceImpl extends HttpServlet\n {\n protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException\n {\n response.setContentType(\"text/plain\");\n\n try\n {\n FileItem uploadItem = getFileItem(request);\n if (uploadItem == null)\n {\n // ERROR\n } \n\n // Add logic here\n }\n catch (Exception ex)\n {\n response.getWriter().write(\"Error: file upload failure: \" + ex.getMessage()); \n }\n }\n\n private FileItem getFileItem(HttpServletRequest request) throws FileUploadException\n {\n DiskFileItemFactory factory = new DiskFileItemFactory(); \n\n // Add here your own limit \n factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);\n\n ServletFileUpload upload = new ServletFileUpload(factory);\n\n // Add here your own limit\n upload.setSizeMax(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);\n\n\n List&lt;?&gt; items = upload.parseRequest(request);\n Iterator&lt;?&gt; it = items.iterator();\n while (it.hasNext())\n {\n FileItem item = (FileItem) it.next();\n // Search here for file item\n if (!item.isFormField() &amp;&amp; \n // Check field name to get to file item ... \n {\n return item;\n }\n }\n\n return null;\n }\n }\n</code></pre>\n" }, { "answer_id": 158478, "author": "dcave555", "author_id": 23968, "author_profile": "https://Stackoverflow.com/users/23968", "pm_score": 1, "selected": false, "text": "<p>You can use apache commons fileupload library, this library permits to limir file size also.</p>\n\n<p><a href=\"http://commons.apache.org/fileupload/\" rel=\"nofollow noreferrer\">http://commons.apache.org/fileupload/</a></p>\n" }, { "answer_id": 16866983, "author": "Oleg Mikheev", "author_id": 513342, "author_profile": "https://Stackoverflow.com/users/513342", "pm_score": 2, "selected": false, "text": "<p>With JavaEE 6 / Servlet 3.0 the preferred way of doing that would be to use the <a href=\"http://docs.oracle.com/javaee/6/tutorial/doc/gmhal.html\" rel=\"nofollow\">@MultipartConfig annotation</a> on your servlet like this:</p>\n\n<pre><code>@MultipartConfig(location=\"/tmp\", fileSizeThreshold=1024*1024, \n maxFileSize=1024*1024*5, maxRequestSize=1024*1024*5*5)\npublic class UploadFileServiceImpl extends HttpServlet ...\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/686/" ]
I'd like to limit the size of the file that can be uploaded to an application. To achieve this, I'd like to abort the upload process from the server side when the size of the file being uploaded exceeds a limit. Is there a way to abort an upload process from the server side without waiting the HTTP request to finish?
You can do something like this (using the [Commons](http://commons.apache.org/fileupload/) library): ``` public class UploadFileServiceImpl extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/plain"); try { FileItem uploadItem = getFileItem(request); if (uploadItem == null) { // ERROR } // Add logic here } catch (Exception ex) { response.getWriter().write("Error: file upload failure: " + ex.getMessage()); } } private FileItem getFileItem(HttpServletRequest request) throws FileUploadException { DiskFileItemFactory factory = new DiskFileItemFactory(); // Add here your own limit factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD); ServletFileUpload upload = new ServletFileUpload(factory); // Add here your own limit upload.setSizeMax(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD); List<?> items = upload.parseRequest(request); Iterator<?> it = items.iterator(); while (it.hasNext()) { FileItem item = (FileItem) it.next(); // Search here for file item if (!item.isFormField() && // Check field name to get to file item ... { return item; } } return null; } } ```
157,149
<p>Is it possible to split the information in a .csproj across more than one file? A bit like a project version of the <code>partial class</code> feature.</p>
[ { "answer_id": 157156, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": -1, "selected": false, "text": "<p>Well you can have multiple projects combined into one large solution, but I don't think that is quite what you had in mind as each project has to be a complete project in that case.</p>\n" }, { "answer_id": 157165, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 3, "selected": false, "text": "<p>Yes, you can split information across several files. You can use <a href=\"http://msdn.microsoft.com/en-us/library/92x05xfs.aspx\" rel=\"noreferrer\">Import Element (MSBuild)</a>. </p>\n\n<p>Note that Visual Studio will give you <a href=\"http://msdn.microsoft.com/en-us/library/ms228217.aspx\" rel=\"noreferrer\">annoying security warning</a> if you will try to open project file that includes other project files.</p>\n\n<p>Useful linky from MSDN:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms171464.aspx\" rel=\"noreferrer\">How to: Use the Same Target in Multiple Project Files</a></p>\n\n<p>Note that external files have <strong>.targets</strong> extension by conventions.</p>\n" }, { "answer_id": 157175, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 6, "selected": true, "text": "<p>You can not have more than one master csproj. But because the underneath wiring of the csproj is done using msbuild you can simply have multiple partial csproj that import each other. The solution file would see the most <em>derived</em> csproj.</p>\n\n<p><strong>project1.csproj</strong></p>\n\n<pre><code>&lt;Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\"&gt;\n ....\n&lt;/Project&gt;\n</code></pre>\n\n<p><strong>project2.csproj</strong></p>\n\n<pre><code>&lt;Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\"&gt;\n &lt;Import Project=\"project1.csproj\" /&gt;\n ...\n&lt;/Project&gt;\n</code></pre>\n\n<p><strong>project.csproj</strong> - this is the main project that is referred by the solution file.</p>\n\n<pre><code>&lt;Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\"&gt;\n &lt;Import Project=\"project2.csproj\" /&gt;\n ...\n&lt;/Project&gt;\n</code></pre>\n\n<p>Bottom line is that using msbuild <strong>Import</strong> feature you can have partial csproj files where each one would contain definitions that the main project (project.csproj in my example) would use.</p>\n\n<hr>\n\n<p>Visual Studio will show a <strong>Security Warning for <em>project</em></strong> dialog when you open your changed solution or project file. Choose the option <strong>Load Project Normally</strong> and press <strong>OK</strong>. When opening the solution again later the warning will not be shown because the configuration to <strong>Load Project Normally</strong> is stored in the <strong>suo</strong> file.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24092/" ]
Is it possible to split the information in a .csproj across more than one file? A bit like a project version of the `partial class` feature.
You can not have more than one master csproj. But because the underneath wiring of the csproj is done using msbuild you can simply have multiple partial csproj that import each other. The solution file would see the most *derived* csproj. **project1.csproj** ``` <Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> .... </Project> ``` **project2.csproj** ``` <Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="project1.csproj" /> ... </Project> ``` **project.csproj** - this is the main project that is referred by the solution file. ``` <Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="project2.csproj" /> ... </Project> ``` Bottom line is that using msbuild **Import** feature you can have partial csproj files where each one would contain definitions that the main project (project.csproj in my example) would use. --- Visual Studio will show a **Security Warning for *project*** dialog when you open your changed solution or project file. Choose the option **Load Project Normally** and press **OK**. When opening the solution again later the warning will not be shown because the configuration to **Load Project Normally** is stored in the **suo** file.
157,163
<p>I want to run a command as soon as a certain text appears in a log file. How do I do that in Bash?</p>
[ { "answer_id": 157171, "author": "ketorin", "author_id": 24094, "author_profile": "https://Stackoverflow.com/users/24094", "pm_score": 5, "selected": true, "text": "<p>Use command</p>\n\n<pre><code>tail -f file.log | grep --line-buffered \"my pattern\" | while read line\ndo\n echo $line\ndone\n</code></pre>\n\n<p>The <code>--line-buffered</code> is the key here, otherwise the read will fail.</p>\n" }, { "answer_id": 157191, "author": "matli", "author_id": 23896, "author_profile": "https://Stackoverflow.com/users/23896", "pm_score": 1, "selected": false, "text": "<p>This should work even without GNU grep:</p>\n\n<pre><code>tail -f -n 0 logfile.out | nawk '/pattern/ {system(\"echo do something here\")}'\n</code></pre>\n\n<p>edit: Added \"-n 0\" so that only new occurences of the text will be matched.</p>\n" }, { "answer_id": 157197, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 3, "selected": false, "text": "<p>Using only <code>tail</code>:</p>\n\n<pre><code>tail -f file.log | while read line; do if [[ $line == *text* ]]; then\n mycommand\nfi; done\n</code></pre>\n" }, { "answer_id": 159238, "author": "mxg", "author_id": 11157, "author_profile": "https://Stackoverflow.com/users/11157", "pm_score": 0, "selected": false, "text": "<p>I like matli's answer. Bruno De Fraine's answer is also good in that it uses only shell ccommands, not other programs (like awk). It suffers from the problem that the entire line must match the magic string. It's not clear from the question that's part of the requirment.</p>\n\n<p>I would modify it a tiny bit to deal with the \"as soon as\" clause in the original question</p>\n\n<pre><code>logfile_generator | tee logfile.out | nawk '/pattern/ {system(\"echo do something here\")}'\n</code></pre>\n\n<p>where logfile_generator is the program that is generating the log file in the first place. This modification executes the \"something\" as soon as the magic string is located.</p>\n" }, { "answer_id": 171925, "author": "tialaramex", "author_id": 9654, "author_profile": "https://Stackoverflow.com/users/9654", "pm_score": 1, "selected": false, "text": "<p>Also you might look at <code>inotail</code>, a replacement for <code>tail -f</code> which uses the <code>inotify</code> framework to wake up only when the file you're interested in has changed. The usual <code>tail -f</code> just sleeps for short periods of time between polling, which is an effective but not very efficient solution.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24094/" ]
I want to run a command as soon as a certain text appears in a log file. How do I do that in Bash?
Use command ``` tail -f file.log | grep --line-buffered "my pattern" | while read line do echo $line done ``` The `--line-buffered` is the key here, otherwise the read will fail.
157,198
<p>I was reading <a href="http://www.ibm.com/developerworks/java/library/j-dcl.html" rel="nofollow noreferrer">this article</a> about "Double-Checked locking" and out of the main topic of the article I was wondering why at some point of the article the author uses the next Idiom: </p> <blockquote> <p>Listing 7. Attempting to solve the out-of-order write problem </p> <pre><code>public static Singleton getInstance() { if (instance == null) { synchronized(Singleton.class) { //1 Singleton inst = instance; //2 if (inst == null) { synchronized(Singleton.class) { //3 inst = new Singleton(); //4 } instance = inst; //5 } } } return instance; } </code></pre> </blockquote> <p>And my question is: Is there any reason to synchronize twice some code with the same lock? Have this any purpose it?</p> <p>Many thanks in advance.</p>
[ { "answer_id": 157213, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "<p>The point of locking twice was to <em>attempt</em> to prevent out-of-order writes. The memory model specifies where reorderings can occur, partly in terms of locks. The lock ensures that no writes (including any within the singleton constructor) appear to happen after the \"instance = inst;\" line.</p>\n\n<p>However, to go deeper into the subject I'd recommend <a href=\"http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html\" rel=\"nofollow noreferrer\">Bill Pugh's article</a>. And then never attempt it :)</p>\n" }, { "answer_id": 157240, "author": "David Santamaria", "author_id": 24097, "author_profile": "https://Stackoverflow.com/users/24097", "pm_score": 0, "selected": false, "text": "<p>All right, but the article said that </p>\n\n<blockquote>\n <p>The code in Listing 7 doesn't work because of the current definition of the memory model. The Java Language Specification (JLS) demands that code within a synchronized block not be moved out of a synchronized block. However, it does not say that code not in a synchronized block cannot be moved into a synchronized block.</p>\n</blockquote>\n\n<p>And also seems like the JVM makes the next translation to \"pseudo-code\" in ASM:</p>\n\n<blockquote>\n<pre><code>public static Singleton getInstance()\n{\n if (instance == null)\n {\n synchronized(Singleton.class) { //1\n Singleton inst = instance; //2\n if (inst == null)\n {\n synchronized(Singleton.class) { //3\n //inst = new Singleton(); //4\n instance = new Singleton(); \n }\n //instance = inst; //5\n }\n }\n }\n return instance;\n}\n</code></pre>\n</blockquote>\n\n<p>So far, the point of no writes after the \"instance=inst\" is not accomplished? </p>\n\n<p>I will read now the article, thanks for the link.</p>\n" }, { "answer_id": 157284, "author": "Bart Read", "author_id": 17786, "author_profile": "https://Stackoverflow.com/users/17786", "pm_score": 3, "selected": false, "text": "<p>Jon Skeet is right: read <a href=\"http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html\" rel=\"nofollow noreferrer\">Bill Pugh's</a> article. The idiom that Hans uses is the precise form that <em>won't work</em>, and should not be used.</p>\n\n<p>This is unsafe:</p>\n\n<pre><code>private static Singleton instance;\n\npublic static Singleton getInstance() {\n if (instance == null) {\n synchronized(Singleton.class) {\n if (instance == null) {\n instance = new Singleton();\n }\n }\n }\n return instance;\n}\n</code></pre>\n\n<p>This is also unsafe:</p>\n\n<pre><code>public static Singleton getInstance() \n{\n if (instance == null)\n {\n synchronized(Singleton.class) { //1\n Singleton inst = instance; //2\n if (inst == null)\n {\n synchronized(Singleton.class) { //3\n inst = new Singleton(); //4\n }\n instance = inst; //5\n }\n }\n }\n return instance;\n}\n</code></pre>\n\n<p>Don't do either of them, ever.</p>\n\n<p>Instead, synchronise the whole method:</p>\n\n<pre><code> public static synchronized Singleton getInstance() {\n if (instance == null) {\n instance = new Singleton();\n }\n return instance;\n }\n</code></pre>\n\n<p>Unless you're retrieving this object a zillion times a second the performance hit, in real terms, is negligible.</p>\n" }, { "answer_id": 157367, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 4, "selected": false, "text": "<p>The article refers to the pre-5.0 Java memory model (JMM). Under that model leaving a synchronised block forced writes out to main memory. So it appears to be an attempt to make sure that the Singleton object is pushed out before the reference to it. However, it doesn't quite work because the write to instance can be moved up into the block - the roach motel.</p>\n\n<p>However, the pre-5.0 model was never correctly implemented. 1.4 should follow the 5.0 model. Classes are initialised lazily, so you might as well just write</p>\n\n<pre><code>public static final Singleton instance = new Singleton();\n</code></pre>\n\n<p>Or better, don't use singletons for they are evil.</p>\n" }, { "answer_id": 157404, "author": "Tom", "author_id": 22850, "author_profile": "https://Stackoverflow.com/users/22850", "pm_score": 0, "selected": false, "text": "<p>Since Java 5, you can make double-checked locking work by declaring the field volatile.</p>\n\n<p>See <a href=\"http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html\" rel=\"nofollow noreferrer\">http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html</a> for a full explanation.</p>\n" }, { "answer_id": 157564, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Regarding this idiom there is a very advisable and clarifying article:</p>\n\n<p><a href=\"http://www.javaworld.com/javaworld/jw-02-2001/jw-0209-double.html?page=1\" rel=\"nofollow noreferrer\">http://www.javaworld.com/javaworld/jw-02-2001/jw-0209-double.html?page=1</a></p>\n\n<p>On the other hand, I think what dhighwayman.myopenid means is why the writer has put one synchronized block referring to the same class (synchronized(Singleton.class)) within another synchronized block referring to the same class. It may happen as a new instance (Singleton inst = instance;) is created within that block and to guarantee it to be thread-safe it's necessary to write another synchronized.</p>\n\n<p>Otherwise, I can't see any sense.</p>\n" }, { "answer_id": 157678, "author": "David Santamaria", "author_id": 24097, "author_profile": "https://Stackoverflow.com/users/24097", "pm_score": 1, "selected": false, "text": "<p>Following the <a href=\"https://stackoverflow.com/users/22656/jon-skeet\">John Skeet</a> Recommendation:</p>\n\n<blockquote>\n <p>However, to go deeper into the subject\n I'd recommend Bill Pugh's article. And\n then never attempt it :)</p>\n</blockquote>\n\n<p>And here is the key for the second sync block:</p>\n\n<blockquote>\n <p>This code puts construction of the\n Helper object inside an inner\n synchronized block. The intuitive idea\n here is that there should be a memory\n barrier at the point where\n synchronization is released, and that\n should prevent the reordering of the\n initialization of the Helper object\n and the assignment to the field\n helper.</p>\n</blockquote>\n\n<p>So basically, with the Inner sync block, we are trying to \"cheat\" the JMM creating the Instance inside the sync block, to force the JMM to execute that allocation before the sync block finished. But the problem here is that the JMM is heading us up and is moving the assigment that is before the sync block inside the sync block, moving our problem back to the beginnig.</p>\n\n<p>This is what i understood from those articles, really interesting and once more thanks for the replies.</p>\n" }, { "answer_id": 158291, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 2, "selected": false, "text": "<p>I cover a bunch of this here:</p>\n\n<p><a href=\"http://tech.puredanger.com/2007/06/15/double-checked-locking/\" rel=\"nofollow noreferrer\">http://tech.puredanger.com/2007/06/15/double-checked-locking/</a></p>\n" }, { "answer_id": 395151, "author": "Henrik Gustafsson", "author_id": 2010, "author_profile": "https://Stackoverflow.com/users/2010", "pm_score": 0, "selected": false, "text": "<p>See the Google Tech Talk on the <a href=\"http://www.youtube.com/watch?v=1FX4zco0ziY\" rel=\"nofollow noreferrer\">Java Memory Model</a> for a really nice introduction to the finer points of the JMM. Since it is missing here, I would also like to point out Jeremy Mansons blog <a href=\"http://jeremymanson.blogspot.com/\" rel=\"nofollow noreferrer\">'Java Concurrency'</a> esp. the post on <a href=\"http://jeremymanson.blogspot.com/2008/05/double-checked-locking.html\" rel=\"nofollow noreferrer\">Double Checked locking</a> (anyone who is anything in the Java world seems to have an article on this :).</p>\n" }, { "answer_id": 2131910, "author": "Hans-Peter Störr", "author_id": 21499, "author_profile": "https://Stackoverflow.com/users/21499", "pm_score": 0, "selected": false, "text": "<p>For Java 5 and better there is actually a doublechecked variant that can be better than synchronizing the whole accessor. This is also mentioned in the <a href=\"http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html\" rel=\"nofollow noreferrer\">Double-Checked Locking Declaration</a> :</p>\n\n<pre><code>class Foo {\n private volatile Helper helper = null;\n public Helper getHelper() {\n if (helper == null) {\n synchronized(this) {\n if (helper == null)\n helper = new Helper();\n }\n }\n return helper;\n }\n}\n</code></pre>\n\n<p>The key difference here is the use of <strong>volatile</strong> in the variable declaration - otherwise it does not work, and it does not work in Java 1.4 or less, anyway.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24097/" ]
I was reading [this article](http://www.ibm.com/developerworks/java/library/j-dcl.html) about "Double-Checked locking" and out of the main topic of the article I was wondering why at some point of the article the author uses the next Idiom: > > Listing 7. Attempting to solve the out-of-order write problem > > > > ``` > public static Singleton getInstance() > { > if (instance == null) > { > synchronized(Singleton.class) { //1 > Singleton inst = instance; //2 > if (inst == null) > { > synchronized(Singleton.class) { //3 > inst = new Singleton(); //4 > } > instance = inst; //5 > } > } > } > return instance; > } > > ``` > > And my question is: Is there any reason to synchronize twice some code with the same lock? Have this any purpose it? Many thanks in advance.
The point of locking twice was to *attempt* to prevent out-of-order writes. The memory model specifies where reorderings can occur, partly in terms of locks. The lock ensures that no writes (including any within the singleton constructor) appear to happen after the "instance = inst;" line. However, to go deeper into the subject I'd recommend [Bill Pugh's article](http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html). And then never attempt it :)
157,232
<p>I have wrapped Log4net in a static wrapper and want to log </p> <pre><code>loggingEvent.LocationInformation.MethodName loggingEvent.LocationInformation.ClassName </code></pre> <p>However all I get is the name of my wrapper.</p> <p>How can I log that info using a forwardingappender and a static wrapper class like </p> <pre><code>Logger.Debug("Logging to Debug"); Logger.Info("Logging to Info"); Logger.Warn("Logging to Warn"); Logger.Error(ex); Logger.Fatal(ex); </code></pre>
[ { "answer_id": 157261, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 0, "selected": false, "text": "<p>The only thing I can think of doing (as I dont currently use log4net) is to request a stacktrace(new StackTrace), and go back a frame to get the info you need. However, I am unsure of the runtime performance impact of this.</p>\n" }, { "answer_id": 157891, "author": "Claus Thomsen", "author_id": 15555, "author_profile": "https://Stackoverflow.com/users/15555", "pm_score": 6, "selected": true, "text": "<p>Well the error was somewhere in my appender but for completeness ill include the answer to the best of my knowledge:</p>\n\n<p>the Facade you need should wrap ILogger and NOT ILog</p>\n\n<pre><code> public static class Logger\n {\n private readonly static Type ThisDeclaringType = typeof(Logger);\n private static readonly ILogger defaultLogger;\n\n static Logger()\n {\n defaultLogger =\n LoggerManager.GetLogger(Assembly.GetCallingAssembly(),\"MyDefaultLoggger\");\n</code></pre>\n\n<p>...</p>\n\n<pre><code> public static void Info(string message)\n {\n if (defaultLogger.IsEnabledFor(infoLevel))\n {\n defaultLogger.Log(typeof(Logger), infoLevel, message, null);\n }\n }\n</code></pre>\n" }, { "answer_id": 157897, "author": "Fred", "author_id": 9012, "author_profile": "https://Stackoverflow.com/users/9012", "pm_score": 3, "selected": false, "text": "<p>Just declare your log variable like this...</p>\n\n<pre><code>private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);\n</code></pre>\n\n<p>Then you can use it normaly. </p>\n" }, { "answer_id": 2027533, "author": "Stu", "author_id": 178362, "author_profile": "https://Stackoverflow.com/users/178362", "pm_score": 2, "selected": false, "text": "<p>This post helped me work out how to write my own wrapper so in return, thought you might like my complete class to wrap the logger which seems to work quite nicely and actually takes just over half as much time as using an ILog directly!</p>\n\n<p>All that's required is the appropriate xml to set up the logging in the config file and </p>\n\n<pre><code>[assembly: log4net.Config.XmlConfigurator(Watch = true)] \n</code></pre>\n\n<p>in your AssemblyInfo.cs and it should work easily.</p>\n\n<p>One note: I'm using Log4NetDash with a seriously simple set-up so have cheated and put some information in the wrong fields (eg stack trace in Domain field), this still works for me as I don't care where the information is shown but you might want to fix this if you're setting stuff up properly if you spare time!</p>\n\n<pre><code>using System;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Reflection;\nusing System.Threading;\nusing log4net;\nusing log4net.Core;\n\nnamespace Utility\n{\n public class Logger\n {\n static Logger()\n {\n LogManager.GetLogger(typeof(Logger));\n }\n\n public static void Debug(string message, params object[] parameters)\n {\n Log(message, Level.Debug, null, parameters);\n }\n\n public static void Info(string message, params object[] parameters)\n {\n Log(message, Level.Info, null, parameters);\n }\n\n public static void Warn(string message, params object[] parameters)\n {\n Log(message, Level.Warn, null, parameters);\n }\n\n public static void Error(string message, params object[] parameters)\n {\n Error(message, null, parameters);\n }\n\n public static void Error(Exception exception)\n {\n if (exception==null)\n return;\n Error(exception.Message, exception);\n }\n\n public static void Error(string message, Exception exception, params object[] parameters)\n {\n string exceptionStack = \"\";\n\n if (exception != null)\n {\n exceptionStack = exception.GetType().Name + \" : \" + exception.Message + Environment.NewLine;\n Exception loopException = exception;\n while (loopException.InnerException != null)\n {\n loopException = loopException.InnerException;\n exceptionStack += loopException.GetType().Name + \" : \" + loopException.Message + Environment.NewLine;\n }\n }\n\n Log(message, Level.Error, exceptionStack, parameters);\n }\n\n\n\n private static void Log(string message, Level logLevel, string exceptionMessage, params object[] parameters)\n {\n BackgroundWorker worker = new BackgroundWorker();\n worker.DoWork += LogEvent;\n worker.RunWorkerAsync(new LogMessageSpec\n {\n ExceptionMessage = exceptionMessage,\n LogLevel = logLevel,\n Message = message,\n Parameters = parameters,\n Stack = new StackTrace(),\n LogTime = DateTime.Now\n });\n }\n\n private static void LogEvent(object sender, DoWorkEventArgs e)\n {\n try\n {\n LogMessageSpec messageSpec = (LogMessageSpec) e.Argument;\n\n StackFrame frame = messageSpec.Stack.GetFrame(2);\n MethodBase method = frame.GetMethod();\n Type reflectedType = method.ReflectedType;\n\n ILogger log = LoggerManager.GetLogger(reflectedType.Assembly, reflectedType);\n Level currenLoggingLevel = ((log4net.Repository.Hierarchy.Logger) log).Parent.Level;\n\n if (messageSpec.LogLevel&lt;currenLoggingLevel)\n return;\n\n messageSpec.Message = string.Format(messageSpec.Message, messageSpec.Parameters);\n string stackTrace = \"\";\n StackFrame[] frames = messageSpec.Stack.GetFrames();\n if (frames != null)\n {\n foreach (StackFrame tempFrame in frames)\n {\n\n MethodBase tempMethod = tempFrame.GetMethod();\n stackTrace += tempMethod.Name + Environment.NewLine;\n }\n }\n string userName = Thread.CurrentPrincipal.Identity.Name;\n LoggingEventData evdat = new LoggingEventData\n {\n Domain = stackTrace,\n Identity = userName,\n Level = messageSpec.LogLevel,\n LocationInfo = new LocationInfo(reflectedType.FullName,\n method.Name,\n frame.GetFileName(),\n frame.GetFileLineNumber().ToString()),\n LoggerName = reflectedType.Name,\n Message = messageSpec.Message,\n TimeStamp = messageSpec.LogTime,\n UserName = userName,\n ExceptionString = messageSpec.ExceptionMessage\n };\n log.Log(new LoggingEvent(evdat));\n }\n catch (Exception)\n {}//don't throw exceptions on background thread especially about logging!\n }\n\n private class LogMessageSpec\n {\n public StackTrace Stack { get; set; }\n public string Message { get; set; }\n public Level LogLevel { get; set; }\n public string ExceptionMessage { get; set; }\n public object[] Parameters { get; set; }\n public DateTime LogTime { get; set; }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 3488846, "author": "Magnus Johansson", "author_id": 3584, "author_profile": "https://Stackoverflow.com/users/3584", "pm_score": 5, "selected": false, "text": "<p>What about the <code>%M</code> and <code>%C</code> variables?\n<a href=\"http://logging.apache.org/log4net/log4net-1.2.11/release/sdk/log4net.Layout.PatternLayout.html\" rel=\"noreferrer\">http://logging.apache.org/log4net/log4net-1.2.11/release/sdk/log4net.Layout.PatternLayout.html</a></p>\n\n<p>Usage, something like:</p>\n\n<pre><code>&lt;layout type=\"log4net.Layout.PatternLayout\"&gt;\n &lt;conversionPattern value=\"%date [%thread] %-5level %logger [%M %C] - %message%newline\" /&gt;\n&lt;/layout&gt;\n</code></pre>\n\n<p>Doesn't that do what you are after?</p>\n" }, { "answer_id": 24156363, "author": "HydPhani", "author_id": 852225, "author_profile": "https://Stackoverflow.com/users/852225", "pm_score": 2, "selected": false, "text": "<p>How about C#4.5 feature callerinfo - <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.callermembernameattribute.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.callermembernameattribute.aspx</a> </p>\n" }, { "answer_id": 30062853, "author": "nightcoder", "author_id": 94990, "author_profile": "https://Stackoverflow.com/users/94990", "pm_score": 3, "selected": false, "text": "<p>I would simply use something like <code>%stacktrace{2}</code> as a conversion pattern.</p>\n\n<p>Example of output:</p>\n\n<blockquote>\n <p>MyNamespace.ClassName.Method > Common.Log.Warning</p>\n</blockquote>\n\n<p>where <code>MyNamespace.ClassName.Method</code> is a method that is calling my wrapper and <code>Common.Log.Warning</code> is a method of the wrapper class.</p>\n\n<p>Conversion patterns can be found <a href=\"http://logging.apache.org/log4net/release/sdk/log4net.Layout.PatternLayout.html\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 33745689, "author": "Dark_Knight", "author_id": 888548, "author_profile": "https://Stackoverflow.com/users/888548", "pm_score": 0, "selected": false, "text": "<p>I will just write more code of the correct answer of Claus</p>\n\n<blockquote>\n <p>In the wrapper class</p>\n</blockquote>\n\n<pre><code>public static class Logger\n{\n private static readonly ILogger DefaultLogger;\n\n static Logger()\n {\n defaultLogger = LoggerManager.GetLogger(Assembly.GetCallingAssembly(), \"MyDefaultLoggger\"); // MyDefaultLoggger is the name of Logger\n }\n\n public static void LogError(object message)\n {\n Level errorLevel = Level.Error;\n if (DefaultLogger.IsEnabledFor(errorLevel))\n {\n DefaultLogger.Log(typeof(Logger), errorLevel, message, null);\n }\n }\n\n public static void LogError(object message, Exception exception)\n {\n Level errorLevel = Level.Error;\n if (DefaultLogger.IsEnabledFor(errorLevel))\n {\n DefaultLogger.Log(typeof(Logger), errorLevel, message, exception);\n }\n }\n</code></pre>\n\n<p>and so on for the rest of methods.</p>\n\n<blockquote>\n <p>in web.config or app.config <strong>log4net.Layout.PatternLayout</strong>\n you can use some Conversion Patterns like:</p>\n</blockquote>\n\n<pre><code>%location %method %line\n\n&lt;layout type=\"log4net.Layout.PatternLayout\"&gt;\n &lt;conversionPattern value=\"%date{dd/MM/yyyy hh:mm:ss.fff tt} [%thread] %level %logger [%location %method %line] [%C %M] - %newline%message%newline%exception\"/&gt;\n &lt;/layout&gt;\n</code></pre>\n" }, { "answer_id": 56463601, "author": "Shani Bhati", "author_id": 9887735, "author_profile": "https://Stackoverflow.com/users/9887735", "pm_score": 0, "selected": false, "text": "<p>Click <a href=\"https://github.com/shani11/Log4Net-with-Log4Net_Logging-nuget/tree/master/Log4NetLogging_Project\" rel=\"nofollow noreferrer\">here</a> to learn how to implement log4net in .NET Core 2.2</p>\n\n<p>The following steps are taken from the above link, and break down how to add log4net to a .NET Core 2.2 project.</p>\n\n<p>First, run the following command in the Package-Manager console:</p>\n\n<pre><code>Install-Package Log4Net_Logging -Version 1.0.0\n</code></pre>\n\n<p>Then add a log4net.config with the following information (please edit it to match your set up):</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\" ?&gt;\n&lt;configuration&gt;\n &lt;configSections&gt;\n &lt;section name=\"log4net\" type=\"log4net.Config.Log4NetConfigurationSectionHandler, log4net\" /&gt;\n &lt;/configSections&gt;\n &lt;log4net&gt;\n &lt;appender name=\"FileAppender\" type=\"log4net.Appender.FileAppender\"&gt;\n &lt;file value=\"logfile.log\" /&gt;\n &lt;appendToFile value=\"true\" /&gt;\n &lt;layout type=\"log4net.Layout.PatternLayout\"&gt;\n &lt;conversionPattern value=\"%d [%t] %-5p - %m%n\" /&gt;\n &lt;/layout&gt;\n &lt;/appender&gt;\n &lt;root&gt;\n &lt;!--LogLevel: OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL --&gt;\n &lt;level value=\"ALL\" /&gt;\n &lt;appender-ref ref=\"FileAppender\" /&gt;\n &lt;/root&gt;\n &lt;/log4net&gt;\n&lt;/configuration&gt;\n</code></pre>\n\n<p>Then, add the following code into a controller (this is an example, please edit it before adding it to your controller):</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public ValuesController()\n{\n LogFourNet.SetUp(Assembly.GetEntryAssembly(), \"log4net.config\");\n}\n// GET api/values\n[HttpGet]\npublic ActionResult&lt;IEnumerable&lt;string&gt;&gt; Get()\n{\n LogFourNet.Info(this, \"This is Info logging\");\n LogFourNet.Debug(this, \"This is Debug logging\");\n LogFourNet.Error(this, \"This is Error logging\"); \n return new string[] { \"value1\", \"value2\" };\n}\n</code></pre>\n\n<p>Then call the relevant controller action (using the above example, call <code>/Values/Get</code> with an HTTP GET), and you will receive the output matching the following:</p>\n\n<blockquote>\n <p>2019-06-05 19:58:45,103 [9] INFO-[Log4NetLogging_Project.Controllers.ValuesController.Get:23] - This is Info logging</p>\n</blockquote>\n" }, { "answer_id": 56874683, "author": "Quantum_Joe", "author_id": 7142327, "author_profile": "https://Stackoverflow.com/users/7142327", "pm_score": 2, "selected": false, "text": "<p>I implemented the following solution for this (.Net framework 4.5+) : the log4net wrapper methods (e.g. Info, Warn, Error) could make use of CallerMemberName and CallerFilePath to fetch the class and method name of the code from where the logs are being called. You can then aggregate these into a custom log4net property.</p>\n<p>Feel free to use your log4net own wrapper implementation, the only important things here are:\nthe signature of the Info and Error methods, and the implementation of the GetLogger method.</p>\n<p>The 'memberName' and 'sourceFilePath' args should never be specified when calling the Logger.Info or Logger.Error methods, they are auto-filled-in by .Net.</p>\n<pre><code>public static class Logger\n{\n private class LogSingletonWrapper\n {\n public ILog Log { get; set; }\n public LogSingletonWrapper()\n {\n Log = LogManager.GetLogger(GetType());\n }\n }\n\n private static readonly Lazy&lt;LogSingletonWrapper&gt; _logger = new Lazy&lt;LogSingletonWrapper&gt;();\n\n public static void Info(string message, [CallerMemberName] string memberName = &quot;&quot;, [CallerFilePath] string sourceFilePath = &quot;&quot;) \n =&gt; GetLogger(memberName, sourceFilePath).Info(message);\n \n public static void Error(string message,Exception ex, [CallerMemberName] string memberName = &quot;&quot;, [CallerFilePath] string sourceFilePath = &quot;&quot;) \n =&gt; GetLogger(memberName, sourceFilePath).Error(message, ex);\n\n private static ILog GetLogger(string memberName, string sourceFilePath)\n {\n var classname = sourceFilePath.Split('\\\\').Last().Split('.').First();\n log4net.ThreadContext.Properties[&quot;Source&quot;] = $&quot;{classname}.{memberName.Replace(&quot;.&quot;, &quot;&quot;)}&quot;;\n return _logger.Value.Log;\n }\n}\n</code></pre>\n<p>Then you would could use a log conversion pattern like this in your .config file :</p>\n<pre><code>&lt;conversionPattern value=&quot;[%level][%date][Thd%thread: %property{Source}][Message: %message]%newline&quot; /&gt;\n</code></pre>\n<p>This would result in logs looking like this:</p>\n<blockquote>\n<p>[INFO][2019-07-03 16:42:00,936][Thd1: Application.Start][Message: The application is starting up ...]</p>\n<p>[ERROR][2019-07-03 16:42:44,145][Thd6: DataProcessor.ProcessDataBatch][Message: Attempted to divide by zero.]</p>\n</blockquote>\n<p>The following methods were called in the above example: the Start method of the Application class, and the ProcessDataBatch method of the DataProcessor class.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15555/" ]
I have wrapped Log4net in a static wrapper and want to log ``` loggingEvent.LocationInformation.MethodName loggingEvent.LocationInformation.ClassName ``` However all I get is the name of my wrapper. How can I log that info using a forwardingappender and a static wrapper class like ``` Logger.Debug("Logging to Debug"); Logger.Info("Logging to Info"); Logger.Warn("Logging to Warn"); Logger.Error(ex); Logger.Fatal(ex); ```
Well the error was somewhere in my appender but for completeness ill include the answer to the best of my knowledge: the Facade you need should wrap ILogger and NOT ILog ``` public static class Logger { private readonly static Type ThisDeclaringType = typeof(Logger); private static readonly ILogger defaultLogger; static Logger() { defaultLogger = LoggerManager.GetLogger(Assembly.GetCallingAssembly(),"MyDefaultLoggger"); ``` ... ``` public static void Info(string message) { if (defaultLogger.IsEnabledFor(infoLevel)) { defaultLogger.Log(typeof(Logger), infoLevel, message, null); } } ```
157,260
<p>In the past and with most my current projects I tend to use a for loop like this:</p> <pre><code>var elements = document.getElementsByTagName('div'); for (var i=0; i&lt;elements.length; i++) { doSomething(elements[i]); } </code></pre> <p>I've heard that using a "reverse while" loop is quicker but I have no real way to confirm this:</p> <pre><code>var elements = document.getElementsByTagName('div'), length = elements.length; while(length--) { doSomething(elements[length]); } </code></pre> <p>What is considered as best practice when it comes to looping though elements in JavaScript, or any array for that matter?</p>
[ { "answer_id": 157264, "author": "Per Hornshøj-Schierbeck", "author_id": 11619, "author_profile": "https://Stackoverflow.com/users/11619", "pm_score": 3, "selected": false, "text": "<p>At the risk of getting yelled at, i would get a javascript helper library like <a href=\"http://jquery.com\" rel=\"nofollow noreferrer\">jquery</a> or <a href=\"http://prototypejs.org\" rel=\"nofollow noreferrer\">prototype</a> they encapsulate the logic in nice methods - both have an .each method/iterator to do it - and they both strive to make it cross-browser compatible</p>\n\n<p>EDIT: This answer was posted in 2008. Today much better constructs exist. This particular case could be solved with a <code>.forEach</code>.</p>\n" }, { "answer_id": 157266, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 3, "selected": false, "text": "<p>I think using the first form is probably the way to go, since it's probably by far the most common loop structure in the known universe, and since I don't believe the reverse loop saves you any time in reality (still doing an increment/decrement and a comparison on each iteration). </p>\n\n<p>Code that is recognizable and readable to others is definitely a good thing.</p>\n" }, { "answer_id": 157270, "author": "Georgi", "author_id": 13209, "author_profile": "https://Stackoverflow.com/users/13209", "pm_score": 2, "selected": false, "text": "<p>I know that you don't want to hear that, but: I consider the best practice is the most readable in this case. As long as the loop is not counting from here to the moon, the performance-gain will not be uhge enough.</p>\n" }, { "answer_id": 157286, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 3, "selected": false, "text": "<p>I too advise to use the simple way (KISS !-)</p>\n\n<p>-- but some optimization could be found, namely not to test the length of an array more than once:</p>\n\n<pre><code>var elements = document.getElementsByTagName('div');\nfor (var i=0, im=elements.length; im&gt;i; i++) {\n doSomething(elements[i]);\n}\n</code></pre>\n" }, { "answer_id": 157298, "author": "Gene", "author_id": 22673, "author_profile": "https://Stackoverflow.com/users/22673", "pm_score": 0, "selected": false, "text": "<p>I prefer the for loop as it's more readable. Looping from length to 0 would be more efficient than looping from 0 to length. And using a reversed while loop is more efficient than a foor loop as you said. I don't have the link to the page with comparison results anymore but I remember that the difference varied on different browsers. For some browser the reversed while loop was twice as fast. However it makes no difference if you're looping \"small\" arrays. In your example case the length of elements will be \"small\"</p>\n" }, { "answer_id": 157323, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 5, "selected": false, "text": "<p>Note that in some cases, you <em>need</em> to loop in reverse order (but then you can use i-- too).</p>\n\n<p>For example somebody wanted to use the new <code>getElementsByClassName</code> function to loop on elements of a given class and change this class. He found that only one out of two elements was changed (in FF3).<br>\nThat's because the function returns a live NodeList, which thus reflects the changes in the Dom tree. Walking the list in reverse order avoided this issue.</p>\n\n<pre><code>var menus = document.getElementsByClassName(\"style2\");\nfor (var i = menus.length - 1; i &gt;= 0; i--)\n{\n menus[i].className = \"style1\";\n}\n</code></pre>\n\n<p>In increasing index progression, when we ask the index 1, FF inspects the Dom and skips the first item with style2, which is the 2nd of the original Dom, thus it returns the 3rd initial item!</p>\n" }, { "answer_id": 157479, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I like doing:<pre> <code>\nvar menu = document.getElementsByTagName('div');\nfor (var i = 0; menu[i]; i++) {\n ...\n}\n</code></pre></p>\n\n<p>There is no call to the length of the array on every iteration. </p>\n" }, { "answer_id": 161664, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 2, "selected": false, "text": "<p>Also see my comment on Andrew Hedges' test ...</p>\n\n<p>I just tried to run a test to compare a simple iteration, the optimization I introduced and the reverse do/while, where the elements in an array was tested in every loop.</p>\n\n<p>And alas, no surprise, the three browsers I tested had very different results, though the optimized simple iteration was fastest in all !-)</p>\n\n<h2>Test:</h2>\n\n<p>An array with 500,000 elements build outside the real test, for every iteration the value of the specific array-element is revealed.</p>\n\n<p>Test run 10 times.</p>\n\n<h2>IE6:</h2>\n\n<p>Results:</p>\n\n<p>Simple: 984,922,937,984,891,907,906,891,906,906</p>\n\n<p>Average: 923.40 ms.</p>\n\n<p>Optimized: 766,766,844,797,750,750,765,765,766,766</p>\n\n<p>Average: 773.50 ms.</p>\n\n<p>Reverse do/while: 3375,1328,1516,1344,1375,1406,1688,1344,1297,1265</p>\n\n<p>Average: 1593.80 ms. (Note one especially awkward result)</p>\n\n<h2>Opera 9.52:</h2>\n\n<p>Results: </p>\n\n<p>Simple: 344,343,344,359,343,359,344,359,359,359</p>\n\n<p>Average: 351.30 ms.</p>\n\n<p>Optimized: 281,297,297,297,297,281,281,297,281,281</p>\n\n<p>Average: 289.00 ms</p>\n\n<p>Reverse do/while: 391,407,391,391,500,407,407,406,406,406</p>\n\n<p>Average: 411.20 ms.</p>\n\n<h2>FireFox 3.0.1:</h2>\n\n<p>Results:</p>\n\n<p>Simple: 278,251,259,245,243,242,259,246,247,256</p>\n\n<p>Average: 252.60 ms.</p>\n\n<p>Optimized: 267,222,223,226,223,230,221,231,224,230</p>\n\n<p>Average: 229.70 ms.</p>\n\n<p>Reverse do/while: 414,381,389,383,388,389,381,387,400,379</p>\n\n<p>Average: 389.10 ms.</p>\n" }, { "answer_id": 161680, "author": "David Robbins", "author_id": 19799, "author_profile": "https://Stackoverflow.com/users/19799", "pm_score": 0, "selected": false, "text": "<p>I think you have two alternatives. For dom elements such as jQuery and like frameworks give you a good method of iteration. The second approach is the for loop.</p>\n" }, { "answer_id": 4620350, "author": "Ruan Mendes", "author_id": 227299, "author_profile": "https://Stackoverflow.com/users/227299", "pm_score": 6, "selected": false, "text": "<p>Here's a nice form of a loop I often use. You create the iterated variable from the for statement and you don't need to check the length property, which can be expensive specially when iterating through a NodeList. However, <strong>you must be careful</strong>, you <strong>can't use it if any of the values in array could be &quot;falsy&quot;</strong>. In practice, I only use it when iterating over an array of objects that does not contain nulls (like a NodeList). But I love its syntactic sugar.</p>\n<pre><code>var list = [{a:1,b:2}, {a:3,b:5}, {a:8,b:2}, {a:4,b:1}, {a:0,b:8}];\n\nfor (var i=0, item; item = list[i]; i++) {\n // Look no need to do list[i] in the body of the loop\n console.log(&quot;Looping: index &quot;, i, &quot;item&quot; + item);\n}\n</code></pre>\n<p>Note that this can also be used to loop backwards.</p>\n<pre><code>var list = [{a:1,b:2}, {a:3,b:5}, {a:8,b:2}, {a:4,b:1}, {a:0,b:8}];\n \nfor (var i = list.length - 1, item; item = list[i]; i--) {\n console.log(&quot;Looping: index &quot;, i, &quot;item&quot;, item);\n}\n</code></pre>\n<p><strong>ES6 Update</strong></p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for...of</code></a> gives you the name but not the index, available since <a href=\"https://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements\" rel=\"nofollow noreferrer\">ES6</a></p>\n<pre><code>for (const item of list) {\n console.log(&quot;Looping: index &quot;, &quot;Sorry!!!&quot;, &quot;item&quot; + item);\n}\n</code></pre>\n" }, { "answer_id": 26232175, "author": "GijsjanB", "author_id": 997941, "author_profile": "https://Stackoverflow.com/users/997941", "pm_score": -1, "selected": false, "text": "<p>I like to use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker\" rel=\"nofollow\">TreeWalker</a> if the set of elements are children of a root node.</p>\n" }, { "answer_id": 27763575, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Form of loop provided by <strong>Juan Mendez</strong> is very useful and practical,\nI changed it a little bit, so that now it works with - false, null, zero and empty strings too.</p>\n\n<pre><code>var items = [\n true,\n false,\n null,\n 0,\n \"\"\n];\n\nfor(var i = 0, item; (item = items[i]) !== undefined; i++)\n{\n console.log(\"Index: \" + i + \"; Value: \" + item);\n}\n</code></pre>\n" }, { "answer_id": 36025074, "author": "Chris Impicciche", "author_id": 6069128, "author_profile": "https://Stackoverflow.com/users/6069128", "pm_score": 3, "selected": false, "text": "<p>I had a very similar problem earlier with document.getElementsByClassName(). I didn't know what a nodelist was at the time.</p>\n\n<pre><code>var elements = document.getElementsByTagName('div');\nfor (var i=0; i&lt;elements.length; i++) {\n doSomething(elements[i]);\n}\n</code></pre>\n\n<p>My issue was that I expected that elements would be an array, but it isn't. The nodelist Document.getElementsByTagName() returns is iterable, but you can't call array.prototype methods on it.</p>\n\n<p>You <em>can</em> however populate an array with nodelist elements like this:</p>\n\n<pre><code>var myElements = [];\nfor (var i=0; i&lt;myNodeList.length; i++) { \n var element = myNodeList[i];\n myElements.push(element);\n};\n</code></pre>\n\n<p>After that you can feel free to call .innerHTML or .style or something on the elements of your array.</p>\n" }, { "answer_id": 49243461, "author": "Dustin Halstead", "author_id": 8592465, "author_profile": "https://Stackoverflow.com/users/8592465", "pm_score": 2, "selected": false, "text": "<p>I know this question is old -- but here's another, extremely simple solution ... </p>\n\n<pre><code>var elements = Array.from(document.querySelectorAll(\"div\"));\n</code></pre>\n\n<p>Then it can be used like any, standard array.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21677/" ]
In the past and with most my current projects I tend to use a for loop like this: ``` var elements = document.getElementsByTagName('div'); for (var i=0; i<elements.length; i++) { doSomething(elements[i]); } ``` I've heard that using a "reverse while" loop is quicker but I have no real way to confirm this: ``` var elements = document.getElementsByTagName('div'), length = elements.length; while(length--) { doSomething(elements[length]); } ``` What is considered as best practice when it comes to looping though elements in JavaScript, or any array for that matter?
Here's a nice form of a loop I often use. You create the iterated variable from the for statement and you don't need to check the length property, which can be expensive specially when iterating through a NodeList. However, **you must be careful**, you **can't use it if any of the values in array could be "falsy"**. In practice, I only use it when iterating over an array of objects that does not contain nulls (like a NodeList). But I love its syntactic sugar. ``` var list = [{a:1,b:2}, {a:3,b:5}, {a:8,b:2}, {a:4,b:1}, {a:0,b:8}]; for (var i=0, item; item = list[i]; i++) { // Look no need to do list[i] in the body of the loop console.log("Looping: index ", i, "item" + item); } ``` Note that this can also be used to loop backwards. ``` var list = [{a:1,b:2}, {a:3,b:5}, {a:8,b:2}, {a:4,b:1}, {a:0,b:8}]; for (var i = list.length - 1, item; item = list[i]; i--) { console.log("Looping: index ", i, "item", item); } ``` **ES6 Update** [`for...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) gives you the name but not the index, available since [ES6](https://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements) ``` for (const item of list) { console.log("Looping: index ", "Sorry!!!", "item" + item); } ```
157,318
<p>We are using a PHP scripting for tunnelling file downloads, since we don't want to expose the absolute path of downloadable file:</p> <pre><code>header("Content-Type: $ctype"); header("Content-Length: " . filesize($file)); header("Content-Disposition: attachment; filename=\"$fileName\""); readfile($file); </code></pre> <p>Unfortunately we noticed that downloads passed through this script can't be resumed by the end user. </p> <p>Is there any way to support resumable downloads with such a PHP-based solution?</p>
[ { "answer_id": 157352, "author": "Sietse", "author_id": 6400, "author_profile": "https://Stackoverflow.com/users/6400", "pm_score": 4, "selected": false, "text": "<p>Yes. Support byteranges. See <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35\" rel=\"noreferrer\">RFC 2616 section 14.35</a> .</p>\n\n<p>It basically means that you should read the <code>Range</code> header, and start serving the file from the specified offset.</p>\n\n<p>This means that you can't use readfile(), since that serves the whole file. Instead, use <a href=\"http://nl3.php.net/manual/en/function.fopen.php\" rel=\"noreferrer\">fopen()</a> first, then <a href=\"http://nl3.php.net/manual/en/function.fseek.php\" rel=\"noreferrer\">fseek()</a> to the correct position, and then use <a href=\"http://nl3.php.net/manual/en/function.fpassthru.php\" rel=\"noreferrer\">fpassthru()</a> to serve the file.</p>\n" }, { "answer_id": 157355, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 1, "selected": false, "text": "<p>Resuming downloads in HTTP is done through the <code>Range</code> header. If the request contains a <code>Range</code> header, and if other indicators (e.g. <code>If-Match</code>, <code>If-Unmodified-Since</code>) indicate that the content hasn't changed since the download was started, you give a 206 response code (rather than 200), indicate the range of bytes you're returning in the <code>Content-Range</code> header, then provide that range in the response body.</p>\n\n<p>I don't know how to do that in PHP, though.</p>\n" }, { "answer_id": 157394, "author": "Zsolt Szeberenyi", "author_id": 15440, "author_profile": "https://Stackoverflow.com/users/15440", "pm_score": 2, "selected": false, "text": "<p>Yes, you can use the Range header for that. You need to give 3 more headers to the client for a full download:</p>\n\n<pre><code>header (\"Accept-Ranges: bytes\");\nheader (\"Content-Length: \" . $fileSize);\nheader (\"Content-Range: bytes 0-\" . $fileSize - 1 . \"/\" . $fileSize . \";\");\n</code></pre>\n\n<p>Than for an interrupted download you need to check the Range request header by:</p>\n\n<pre><code>$headers = getAllHeaders ();\n$range = substr ($headers['Range'], '6');\n</code></pre>\n\n<p>And in this case don't forget to serve the content with 206 status code:</p>\n\n<pre><code>header (\"HTTP/1.1 206 Partial content\");\nheader (\"Accept-Ranges: bytes\");\nheader (\"Content-Length: \" . $remaining_length);\nheader (\"Content-Range: bytes \" . $start . \"-\" . $to . \"/\" . $fileSize . \";\");\n</code></pre>\n\n<p>You'll get the $start and $to variables from the request header, and use fseek() to seek to the correct position in the file.</p>\n" }, { "answer_id": 157447, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 7, "selected": false, "text": "<p>The first thing you need to do is to send the <code>Accept-Ranges: bytes</code> header in all responses, to tell the client that you support partial content. Then, if request with a <code>Range: bytes=x-y</code> header is received (with <code>x</code> and <code>y</code> being numbers) you parse the range the client is requesting, open the file as usual, seek <code>x</code> bytes ahead and send the next <code>y</code> - <code>x</code> bytes. Also set the response to <code>HTTP/1.0 206 Partial Content</code>.</p>\n\n<p>Without having tested anything, this could work, more or less:</p>\n\n<pre><code>$filesize = filesize($file);\n\n$offset = 0;\n$length = $filesize;\n\nif ( isset($_SERVER['HTTP_RANGE']) ) {\n // if the HTTP_RANGE header is set we're dealing with partial content\n\n $partialContent = true;\n\n // find the requested range\n // this might be too simplistic, apparently the client can request\n // multiple ranges, which can become pretty complex, so ignore it for now\n preg_match('/bytes=(\\d+)-(\\d+)?/', $_SERVER['HTTP_RANGE'], $matches);\n\n $offset = intval($matches[1]);\n $length = intval($matches[2]) - $offset;\n} else {\n $partialContent = false;\n}\n\n$file = fopen($file, 'r');\n\n// seek to the requested offset, this is 0 if it's not a partial content request\nfseek($file, $offset);\n\n$data = fread($file, $length);\n\nfclose($file);\n\nif ( $partialContent ) {\n // output the right headers for partial content\n\n header('HTTP/1.1 206 Partial Content');\n\n header('Content-Range: bytes ' . $offset . '-' . ($offset + $length) . '/' . $filesize);\n}\n\n// output the regular HTTP headers\nheader('Content-Type: ' . $ctype);\nheader('Content-Length: ' . $filesize);\nheader('Content-Disposition: attachment; filename=\"' . $fileName . '\"');\nheader('Accept-Ranges: bytes');\n\n// don't forget to send the data too\nprint($data);\n</code></pre>\n\n<p>I may have missed something obvious, and I have most definitely ignored some potential sources of errors, but it should be a start.</p>\n\n<p>There's a <a href=\"http://tools.ietf.org/id/draft-ietf-http-range-retrieval-00.txt\" rel=\"noreferrer\">description of partial content here</a> and I found some info on partial content on the documentation page for <a href=\"http://se.php.net/manual/en/function.fread.php\" rel=\"noreferrer\">fread</a>.</p>\n" }, { "answer_id": 1316639, "author": "Jonathan Hawkes", "author_id": 48793, "author_profile": "https://Stackoverflow.com/users/48793", "pm_score": 4, "selected": false, "text": "<p>A really nice way to solve this without having to \"roll your own\" PHP code is to use the mod_xsendfile Apache module. Then in PHP, you just set the appropriate headers. Apache gets to do its thing.</p>\n\n<pre><code>header(\"X-Sendfile: /path/to/file\");\nheader(\"Content-Type: application/octet-stream\");\nheader(\"Content-Disposition: attachment; file=\\\"filename\\\"\");\n</code></pre>\n" }, { "answer_id": 4451376, "author": "DaveRandom", "author_id": 889949, "author_profile": "https://Stackoverflow.com/users/889949", "pm_score": 6, "selected": false, "text": "<p><strong>EDIT</strong> 2017/01 - I wrote a library to do this in PHP >=7.0 <a href=\"https://github.com/DaveRandom/Resume\" rel=\"noreferrer\">https://github.com/DaveRandom/Resume</a></p>\n\n<p><strong>EDIT</strong> 2016/02 - Code completely rewritten to a set of modular tools an an example usage, rather than a monolithic function. Corrections mentioned in comments below have been incorporated.</p>\n\n<hr>\n\n<p>A tested, working solution (based heavily on Theo's answer above) which deals with resumable downloads, in a set of a few standalone tools. This code requires PHP 5.4 or later.</p>\n\n<p>This solution can still only cope with one range per request, but under any circumstance with a standard browser that I can think of, this should not cause a problem.</p>\n\n<pre><code>&lt;?php\n\n/**\n * Get the value of a header in the current request context\n *\n * @param string $name Name of the header\n * @return string|null Returns null when the header was not sent or cannot be retrieved\n */\nfunction get_request_header($name)\n{\n $name = strtoupper($name);\n\n // IIS/Some Apache versions and configurations\n if (isset($_SERVER['HTTP_' . $name])) {\n return trim($_SERVER['HTTP_' . $name]);\n }\n\n // Various other SAPIs\n foreach (apache_request_headers() as $header_name =&gt; $value) {\n if (strtoupper($header_name) === $name) {\n return trim($value);\n }\n }\n\n return null;\n}\n\nclass NonExistentFileException extends \\RuntimeException {}\nclass UnreadableFileException extends \\RuntimeException {}\nclass UnsatisfiableRangeException extends \\RuntimeException {}\nclass InvalidRangeHeaderException extends \\RuntimeException {}\n\nclass RangeHeader\n{\n /**\n * The first byte in the file to send (0-indexed), a null value indicates the last\n * $end bytes\n *\n * @var int|null\n */\n private $firstByte;\n\n /**\n * The last byte in the file to send (0-indexed), a null value indicates $start to\n * EOF\n *\n * @var int|null\n */\n private $lastByte;\n\n /**\n * Create a new instance from a Range header string\n *\n * @param string $header\n * @return RangeHeader\n */\n public static function createFromHeaderString($header)\n {\n if ($header === null) {\n return null;\n }\n\n if (!preg_match('/^\\s*(\\S+)\\s*(\\d*)\\s*-\\s*(\\d*)\\s*(?:,|$)/', $header, $info)) {\n throw new InvalidRangeHeaderException('Invalid header format');\n } else if (strtolower($info[1]) !== 'bytes') {\n throw new InvalidRangeHeaderException('Unknown range unit: ' . $info[1]);\n }\n\n return new self(\n $info[2] === '' ? null : $info[2],\n $info[3] === '' ? null : $info[3]\n );\n }\n\n /**\n * @param int|null $firstByte\n * @param int|null $lastByte\n * @throws InvalidRangeHeaderException\n */\n public function __construct($firstByte, $lastByte)\n {\n $this-&gt;firstByte = $firstByte === null ? $firstByte : (int)$firstByte;\n $this-&gt;lastByte = $lastByte === null ? $lastByte : (int)$lastByte;\n\n if ($this-&gt;firstByte === null &amp;&amp; $this-&gt;lastByte === null) {\n throw new InvalidRangeHeaderException(\n 'Both start and end position specifiers empty'\n );\n } else if ($this-&gt;firstByte &lt; 0 || $this-&gt;lastByte &lt; 0) {\n throw new InvalidRangeHeaderException(\n 'Position specifiers cannot be negative'\n );\n } else if ($this-&gt;lastByte !== null &amp;&amp; $this-&gt;lastByte &lt; $this-&gt;firstByte) {\n throw new InvalidRangeHeaderException(\n 'Last byte cannot be less than first byte'\n );\n }\n }\n\n /**\n * Get the start position when this range is applied to a file of the specified size\n *\n * @param int $fileSize\n * @return int\n * @throws UnsatisfiableRangeException\n */\n public function getStartPosition($fileSize)\n {\n $size = (int)$fileSize;\n\n if ($this-&gt;firstByte === null) {\n return ($size - 1) - $this-&gt;lastByte;\n }\n\n if ($size &lt;= $this-&gt;firstByte) {\n throw new UnsatisfiableRangeException(\n 'Start position is after the end of the file'\n );\n }\n\n return $this-&gt;firstByte;\n }\n\n /**\n * Get the end position when this range is applied to a file of the specified size\n *\n * @param int $fileSize\n * @return int\n * @throws UnsatisfiableRangeException\n */\n public function getEndPosition($fileSize)\n {\n $size = (int)$fileSize;\n\n if ($this-&gt;lastByte === null) {\n return $size - 1;\n }\n\n if ($size &lt;= $this-&gt;lastByte) {\n throw new UnsatisfiableRangeException(\n 'End position is after the end of the file'\n );\n }\n\n return $this-&gt;lastByte;\n }\n\n /**\n * Get the length when this range is applied to a file of the specified size\n *\n * @param int $fileSize\n * @return int\n * @throws UnsatisfiableRangeException\n */\n public function getLength($fileSize)\n {\n $size = (int)$fileSize;\n\n return $this-&gt;getEndPosition($size) - $this-&gt;getStartPosition($size) + 1;\n }\n\n /**\n * Get a Content-Range header corresponding to this Range and the specified file\n * size\n *\n * @param int $fileSize\n * @return string\n */\n public function getContentRangeHeader($fileSize)\n {\n return 'bytes ' . $this-&gt;getStartPosition($fileSize) . '-'\n . $this-&gt;getEndPosition($fileSize) . '/' . $fileSize;\n }\n}\n\nclass PartialFileServlet\n{\n /**\n * The range header on which the data transmission will be based\n *\n * @var RangeHeader|null\n */\n private $range;\n\n /**\n * @param RangeHeader $range Range header on which the transmission will be based\n */\n public function __construct(RangeHeader $range = null)\n {\n $this-&gt;range = $range;\n }\n\n /**\n * Send part of the data in a seekable stream resource to the output buffer\n *\n * @param resource $fp Stream resource to read data from\n * @param int $start Position in the stream to start reading\n * @param int $length Number of bytes to read\n * @param int $chunkSize Maximum bytes to read from the file in a single operation\n */\n private function sendDataRange($fp, $start, $length, $chunkSize = 8192)\n {\n if ($start &gt; 0) {\n fseek($fp, $start, SEEK_SET);\n }\n\n while ($length) {\n $read = ($length &gt; $chunkSize) ? $chunkSize : $length;\n $length -= $read;\n echo fread($fp, $read);\n }\n }\n\n /**\n * Send the headers that are included regardless of whether a range was requested\n *\n * @param string $fileName\n * @param int $contentLength\n * @param string $contentType\n */\n private function sendDownloadHeaders($fileName, $contentLength, $contentType)\n {\n header('Content-Type: ' . $contentType);\n header('Content-Length: ' . $contentLength);\n header('Content-Disposition: attachment; filename=\"' . $fileName . '\"');\n header('Accept-Ranges: bytes');\n }\n\n /**\n * Send data from a file based on the current Range header\n *\n * @param string $path Local file system path to serve\n * @param string $contentType MIME type of the data stream\n */\n public function sendFile($path, $contentType = 'application/octet-stream')\n {\n // Make sure the file exists and is a file, otherwise we are wasting our time\n $localPath = realpath($path);\n if ($localPath === false || !is_file($localPath)) {\n throw new NonExistentFileException(\n $path . ' does not exist or is not a file'\n );\n }\n\n // Make sure we can open the file for reading\n if (!$fp = fopen($localPath, 'r')) {\n throw new UnreadableFileException(\n 'Failed to open ' . $localPath . ' for reading'\n );\n }\n\n $fileSize = filesize($localPath);\n\n if ($this-&gt;range == null) {\n // No range requested, just send the whole file\n header('HTTP/1.1 200 OK');\n $this-&gt;sendDownloadHeaders(basename($localPath), $fileSize, $contentType);\n\n fpassthru($fp);\n } else {\n // Send the request range\n header('HTTP/1.1 206 Partial Content');\n header('Content-Range: ' . $this-&gt;range-&gt;getContentRangeHeader($fileSize));\n $this-&gt;sendDownloadHeaders(\n basename($localPath),\n $this-&gt;range-&gt;getLength($fileSize),\n $contentType\n );\n\n $this-&gt;sendDataRange(\n $fp,\n $this-&gt;range-&gt;getStartPosition($fileSize),\n $this-&gt;range-&gt;getLength($fileSize)\n );\n }\n\n fclose($fp);\n }\n}\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>&lt;?php\n\n$path = '/local/path/to/file.ext';\n$contentType = 'application/octet-stream';\n\n// Avoid sending unexpected errors to the client - we should be serving a file,\n// we don't want to corrupt the data we send\nini_set('display_errors', '0');\n\ntry {\n $rangeHeader = RangeHeader::createFromHeaderString(get_request_header('Range'));\n (new PartialFileServlet($rangeHeader))-&gt;sendFile($path, $contentType);\n} catch (InvalidRangeHeaderException $e) {\n header(\"HTTP/1.1 400 Bad Request\");\n} catch (UnsatisfiableRangeException $e) {\n header(\"HTTP/1.1 416 Range Not Satisfiable\");\n} catch (NonExistentFileException $e) {\n header(\"HTTP/1.1 404 Not Found\");\n} catch (UnreadableFileException $e) {\n header(\"HTTP/1.1 500 Internal Server Error\");\n}\n\n// It's usually a good idea to explicitly exit after sending a file to avoid sending any\n// extra data on the end that might corrupt the file\nexit;\n</code></pre>\n" }, { "answer_id": 5302134, "author": "Barbatrux", "author_id": 657596, "author_profile": "https://Stackoverflow.com/users/657596", "pm_score": 1, "selected": false, "text": "<p>Thanks Theo! your method did not directly work for streaming divx because i found the divx player was sending ranges like bytes=9932800-</p>\n\n<p>but it showed me how to do it so thanks :D</p>\n\n<pre><code>if(isset($_SERVER['HTTP_RANGE']))\n{\n file_put_contents('showrange.txt',$_SERVER['HTTP_RANGE']);\n</code></pre>\n" }, { "answer_id": 10517451, "author": "Justin T.", "author_id": 1093649, "author_profile": "https://Stackoverflow.com/users/1093649", "pm_score": 3, "selected": false, "text": "<p>If you're willing to install a new PECL module, the <strong>easiest way to support resumeable downloads with PHP</strong> is through <code>http_send_file()</code>, like this</p>\n\n<pre><code>&lt;?php\nhttp_send_content_disposition(\"document.pdf\", true);\nhttp_send_content_type(\"application/pdf\");\nhttp_throttle(0.1, 2048);\nhttp_send_file(\"../report.pdf\");\n?&gt;\n</code></pre>\n\n<p>source : <a href=\"http://www.php.net/manual/en/function.http-send-file.php\" rel=\"nofollow noreferrer\">http://www.php.net/manual/en/function.http-send-file.php</a></p>\n\n<p>We use it to serve database-stored content and it works like a charm !</p>\n" }, { "answer_id": 13821992, "author": "LifeInstructor", "author_id": 1524615, "author_profile": "https://Stackoverflow.com/users/1524615", "pm_score": 4, "selected": false, "text": "<p>This works 100% super check it \nI am using it and no problems any more.\n \n\n<pre><code> /* Function: download with resume/speed/stream options */\n\n\n /* List of File Types */\n function fileTypes($extension){\n $fileTypes['swf'] = 'application/x-shockwave-flash';\n $fileTypes['pdf'] = 'application/pdf';\n $fileTypes['exe'] = 'application/octet-stream';\n $fileTypes['zip'] = 'application/zip';\n $fileTypes['doc'] = 'application/msword';\n $fileTypes['xls'] = 'application/vnd.ms-excel';\n $fileTypes['ppt'] = 'application/vnd.ms-powerpoint';\n $fileTypes['gif'] = 'image/gif';\n $fileTypes['png'] = 'image/png';\n $fileTypes['jpeg'] = 'image/jpg';\n $fileTypes['jpg'] = 'image/jpg';\n $fileTypes['rar'] = 'application/rar';\n\n $fileTypes['ra'] = 'audio/x-pn-realaudio';\n $fileTypes['ram'] = 'audio/x-pn-realaudio';\n $fileTypes['ogg'] = 'audio/x-pn-realaudio';\n\n $fileTypes['wav'] = 'video/x-msvideo';\n $fileTypes['wmv'] = 'video/x-msvideo';\n $fileTypes['avi'] = 'video/x-msvideo';\n $fileTypes['asf'] = 'video/x-msvideo';\n $fileTypes['divx'] = 'video/x-msvideo';\n\n $fileTypes['mp3'] = 'audio/mpeg';\n $fileTypes['mp4'] = 'audio/mpeg';\n $fileTypes['mpeg'] = 'video/mpeg';\n $fileTypes['mpg'] = 'video/mpeg';\n $fileTypes['mpe'] = 'video/mpeg';\n $fileTypes['mov'] = 'video/quicktime';\n $fileTypes['swf'] = 'video/quicktime';\n $fileTypes['3gp'] = 'video/quicktime';\n $fileTypes['m4a'] = 'video/quicktime';\n $fileTypes['aac'] = 'video/quicktime';\n $fileTypes['m3u'] = 'video/quicktime';\n return $fileTypes[$extention];\n };\n\n /*\n Parameters: downloadFile(File Location, File Name,\n max speed, is streaming\n If streaming - videos will show as videos, images as images\n instead of download prompt\n */\n\n function downloadFile($fileLocation, $fileName, $maxSpeed = 100, $doStream = false) {\n if (connection_status() != 0)\n return(false);\n // in some old versions this can be pereferable to get extention\n // $extension = strtolower(end(explode('.', $fileName)));\n $extension = pathinfo($fileName, PATHINFO_EXTENSION);\n\n $contentType = fileTypes($extension);\n header(\"Cache-Control: public\");\n header(\"Content-Transfer-Encoding: binary\\n\");\n header('Content-Type: $contentType');\n\n $contentDisposition = 'attachment';\n\n if ($doStream == true) {\n /* extensions to stream */\n $array_listen = array('mp3', 'm3u', 'm4a', 'mid', 'ogg', 'ra', 'ram', 'wm',\n 'wav', 'wma', 'aac', '3gp', 'avi', 'mov', 'mp4', 'mpeg', 'mpg', 'swf', 'wmv', 'divx', 'asf');\n if (in_array($extension, $array_listen)) {\n $contentDisposition = 'inline';\n }\n }\n\n if (strstr($_SERVER['HTTP_USER_AGENT'], \"MSIE\")) {\n $fileName = preg_replace('/\\./', '%2e', $fileName, substr_count($fileName, '.') - 1);\n header(\"Content-Disposition: $contentDisposition;\n filename=\\\"$fileName\\\"\");\n } else {\n header(\"Content-Disposition: $contentDisposition;\n filename=\\\"$fileName\\\"\");\n }\n\n header(\"Accept-Ranges: bytes\");\n $range = 0;\n $size = filesize($fileLocation);\n\n if (isset($_SERVER['HTTP_RANGE'])) {\n list($a, $range) = explode(\"=\", $_SERVER['HTTP_RANGE']);\n str_replace($range, \"-\", $range);\n $size2 = $size - 1;\n $new_length = $size - $range;\n header(\"HTTP/1.1 206 Partial Content\");\n header(\"Content-Length: $new_length\");\n header(\"Content-Range: bytes $range$size2/$size\");\n } else {\n $size2 = $size - 1;\n header(\"Content-Range: bytes 0-$size2/$size\");\n header(\"Content-Length: \" . $size);\n }\n\n if ($size == 0) {\n die('Zero byte file! Aborting download');\n }\n set_magic_quotes_runtime(0);\n $fp = fopen(\"$fileLocation\", \"rb\");\n\n fseek($fp, $range);\n\n while (!feof($fp) and ( connection_status() == 0)) {\n set_time_limit(0);\n print(fread($fp, 1024 * $maxSpeed));\n flush();\n ob_flush();\n sleep(1);\n }\n fclose($fp);\n\n return((connection_status() == 0) and ! connection_aborted());\n }\n\n /* Implementation */\n // downloadFile('path_to_file/1.mp3', '1.mp3', 1024, false);\n</code></pre>\n" }, { "answer_id": 22398156, "author": "user3418767", "author_id": 3418767, "author_profile": "https://Stackoverflow.com/users/3418767", "pm_score": 2, "selected": false, "text": "<p>This worked very well for me: <a href=\"https://github.com/pomle/php-serveFilePartial\" rel=\"nofollow\">https://github.com/pomle/php-serveFilePartial</a></p>\n" }, { "answer_id": 23297385, "author": "Mygod", "author_id": 2245107, "author_profile": "https://Stackoverflow.com/users/2245107", "pm_score": 2, "selected": false, "text": "<p>The top answer has various bugs.</p>\n\n<ol>\n<li>The major bug: It doesn't handle Range header correctly. <code>bytes a-b</code> should mean <code>[a, b]</code> instead of <code>[a, b)</code>, and <code>bytes a-</code> is not handled.</li>\n<li>The minor bug: It doesn't use buffer to handle output. This may consume too much memory and cause low speed for large files.</li>\n</ol>\n\n<p>Here's my modified code:</p>\n\n<pre><code>// TODO: configurations here\n$fileName = \"File Name\";\n$file = \"File Path\";\n$bufferSize = 2097152;\n\n$filesize = filesize($file);\n$offset = 0;\n$length = $filesize;\nif (isset($_SERVER['HTTP_RANGE'])) {\n // if the HTTP_RANGE header is set we're dealing with partial content\n // find the requested range\n // this might be too simplistic, apparently the client can request\n // multiple ranges, which can become pretty complex, so ignore it for now\n preg_match('/bytes=(\\d+)-(\\d+)?/', $_SERVER['HTTP_RANGE'], $matches);\n $offset = intval($matches[1]);\n $end = $matches[2] || $matches[2] === '0' ? intval($matches[2]) : $filesize - 1;\n $length = $end + 1 - $offset;\n // output the right headers for partial content\n header('HTTP/1.1 206 Partial Content');\n header(\"Content-Range: bytes $offset-$end/$filesize\");\n}\n// output the regular HTTP headers\nheader('Content-Type: ' . mime_content_type($file));\nheader(\"Content-Length: $filesize\");\nheader(\"Content-Disposition: attachment; filename=\\\"$fileName\\\"\");\nheader('Accept-Ranges: bytes');\n\n$file = fopen($file, 'r');\n// seek to the requested offset, this is 0 if it's not a partial content request\nfseek($file, $offset);\n// don't forget to send the data too\nini_set('memory_limit', '-1');\nwhile ($length &gt;= $bufferSize)\n{\n print(fread($file, $bufferSize));\n $length -= $bufferSize;\n}\nif ($length) print(fread($file, $length));\nfclose($file);\n</code></pre>\n" }, { "answer_id": 29048353, "author": "dennis", "author_id": 464549, "author_profile": "https://Stackoverflow.com/users/464549", "pm_score": 2, "selected": false, "text": "<p>Small composer enabled class which works the same way as pecl http_send_file. This means support for resumable downloads and throttle. <a href=\"https://github.com/diversen/http-send-file\" rel=\"nofollow\">https://github.com/diversen/http-send-file</a></p>\n" }, { "answer_id": 46545812, "author": "smurf", "author_id": 3086360, "author_profile": "https://Stackoverflow.com/users/3086360", "pm_score": 2, "selected": false, "text": "<p>You could use the below code for byte range request support across any browser</p>\n\n<pre><code> &lt;?php\n$file = 'YouTube360p.mp4';\n$fileLoc = $file;\n$filesize = filesize($file);\n$offset = 0;\n$fileLength = $filesize;\n$length = $filesize - 1;\n\nif ( isset($_SERVER['HTTP_RANGE']) ) {\n // if the HTTP_RANGE header is set we're dealing with partial content\n\n $partialContent = true;\n preg_match('/bytes=(\\d+)-(\\d+)?/', $_SERVER['HTTP_RANGE'], $matches);\n\n $offset = intval($matches[1]);\n $tempLength = intval($matches[2]) - 0;\n if($tempLength != 0)\n {\n $length = $tempLength;\n }\n $fileLength = ($length - $offset) + 1;\n} else {\n $partialContent = false;\n $offset = $length;\n}\n\n$file = fopen($file, 'r');\n\n// seek to the requested offset, this is 0 if it's not a partial content request\nfseek($file, $offset);\n\n$data = fread($file, $length);\n\nfclose($file);\n\nif ( $partialContent ) {\n // output the right headers for partial content\n header('HTTP/1.1 206 Partial Content');\n}\n\n// output the regular HTTP headers\nheader('Content-Type: ' . mime_content_type($fileLoc));\nheader('Content-Length: ' . $fileLength);\nheader('Content-Disposition: inline; filename=\"' . $file . '\"');\nheader('Accept-Ranges: bytes');\nheader('Content-Range: bytes ' . $offset . '-' . $length . '/' . $filesize);\n\n// don't forget to send the data too\nprint($data);\n?&gt;\n</code></pre>\n" }, { "answer_id": 69132264, "author": "Magnar Myrtveit", "author_id": 2459228, "author_profile": "https://Stackoverflow.com/users/2459228", "pm_score": 0, "selected": false, "text": "<p>I've created a library for serving files with support for conditional (don't download file again unless it has changed) and ranged (pause and resume download) requests. It even works with virtual file systems, such as <a href=\"https://flysystem.thephpleague.com\" rel=\"nofollow noreferrer\">Flysystem</a>.</p>\n<p>Check it out here: <a href=\"https://github.com/Stadly/FileWaiter\" rel=\"nofollow noreferrer\"><strong>FileWaiter</strong></a></p>\n<p>Example usage:</p>\n<pre class=\"lang-php prettyprint-override\"><code>use Stadly\\FileWaiter\\Adapter\\Local;\nuse Stadly\\FileWaiter\\File;\nuse Stadly\\FileWaiter\\Waiter;\n\n$streamFactory = new \\GuzzleHttp\\Psr7\\HttpFactory(); // Any PSR-17 compatible stream factory.\n$file = new File(new Local('filename.txt', $streamFactory)); // Or another file adapter. See below.\n$responseFactory = new \\GuzzleHttp\\Psr7\\HttpFactory(); // Any PSR-17 compatible response factory.\n\n$waiter = new Waiter($file, $responseFactory);\n\n$request = \\GuzzleHttp\\Psr7\\ServerRequest::fromGlobals(); // Any PSR-7 compatible server request.\n\n$response = $waiter-&gt;handle($request); // The response is created by the response factory.\n\n$emitter = new \\Laminas\\HttpHandlerRunner\\Emitter\\SapiEmitter(); // Any way of emitting PSR-7 responses.\n$emitter-&gt;emit($response);\ndie();\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
We are using a PHP scripting for tunnelling file downloads, since we don't want to expose the absolute path of downloadable file: ``` header("Content-Type: $ctype"); header("Content-Length: " . filesize($file)); header("Content-Disposition: attachment; filename=\"$fileName\""); readfile($file); ``` Unfortunately we noticed that downloads passed through this script can't be resumed by the end user. Is there any way to support resumable downloads with such a PHP-based solution?
The first thing you need to do is to send the `Accept-Ranges: bytes` header in all responses, to tell the client that you support partial content. Then, if request with a `Range: bytes=x-y` header is received (with `x` and `y` being numbers) you parse the range the client is requesting, open the file as usual, seek `x` bytes ahead and send the next `y` - `x` bytes. Also set the response to `HTTP/1.0 206 Partial Content`. Without having tested anything, this could work, more or less: ``` $filesize = filesize($file); $offset = 0; $length = $filesize; if ( isset($_SERVER['HTTP_RANGE']) ) { // if the HTTP_RANGE header is set we're dealing with partial content $partialContent = true; // find the requested range // this might be too simplistic, apparently the client can request // multiple ranges, which can become pretty complex, so ignore it for now preg_match('/bytes=(\d+)-(\d+)?/', $_SERVER['HTTP_RANGE'], $matches); $offset = intval($matches[1]); $length = intval($matches[2]) - $offset; } else { $partialContent = false; } $file = fopen($file, 'r'); // seek to the requested offset, this is 0 if it's not a partial content request fseek($file, $offset); $data = fread($file, $length); fclose($file); if ( $partialContent ) { // output the right headers for partial content header('HTTP/1.1 206 Partial Content'); header('Content-Range: bytes ' . $offset . '-' . ($offset + $length) . '/' . $filesize); } // output the regular HTTP headers header('Content-Type: ' . $ctype); header('Content-Length: ' . $filesize); header('Content-Disposition: attachment; filename="' . $fileName . '"'); header('Accept-Ranges: bytes'); // don't forget to send the data too print($data); ``` I may have missed something obvious, and I have most definitely ignored some potential sources of errors, but it should be a start. There's a [description of partial content here](http://tools.ietf.org/id/draft-ietf-http-range-retrieval-00.txt) and I found some info on partial content on the documentation page for [fread](http://se.php.net/manual/en/function.fread.php).
157,342
<p>Cron installation is vixie-cron</p> <p><code>/etc/cron.daily/rmspam.cron</code></p> <pre><code>#!/bin/bash /usr/bin/rm /home/user/Maildir/.SPAM/cur/*; </code></pre> <p>I Have this simple bash script that I want to add to a cron job (also includes spam learning commands before) but this part always fails with "File or directory not found" From what I figure is the metachar isn't being interperted correctly when run as a cron job. If I execute the script from the commandline it works fine.</p> <p>I'd like a why for this not working and of course a working solution :)</p> <p>Thanks</p> <p>edit #1 came back to this question when I got popular question badge for it. I first did this,</p> <pre><code>#!/bin/bash find /home/user/Maildir/.SPAM/cur/ -t file | xargs rm </code></pre> <p>and just recently was reading through the xargs man page and changed it to this</p> <pre><code>#!/bin/bash find /home/user/Maildir/.SPAM/cur/ -t file | xargs --no-run-if-empty rm </code></pre> <p>short xargs option is -r</p>
[ { "answer_id": 157350, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 0, "selected": false, "text": "<p>Are you specifying the full path to the script in the cronjob?</p>\n\n<pre><code>00 3 * * * /home/me/myscript.sh\n</code></pre>\n\n<p>rather than</p>\n\n<pre><code>00 3 * * * myscript.sh\n</code></pre>\n\n<hr>\n\n<p>On another note, it's <strong>/bin/rm</strong> on all of the linux boxes I have access to. Have you double-checked that it really is <strong>/usr/bin/rm</strong> on your machine?</p>\n" }, { "answer_id": 157369, "author": "janm", "author_id": 7256, "author_profile": "https://Stackoverflow.com/users/7256", "pm_score": 5, "selected": true, "text": "<p>If there are no files in the directory, then the wildcard will not be expanded and will be passed to the command directly. There is no file called \"*\", and then the command fails with \"File or directory not found.\" Try this instead:</p>\n\n<pre><code>if [ -f /home/user/Maildir/.SPAM/cur/* ]; then\n rm /home/user/Maildir/.SPAM/cur/*\nfi\n</code></pre>\n\n<p>Or just use the \"-f\" flag to rm. The other problem with this command is what happens when there is too much spam for the maximum length of the command line. Something like this is probably better overall:</p>\n\n<pre><code>find /home/user/Maildir/.SPAM/cur -type f -exec rm '{}' +\n</code></pre>\n\n<p>If you have an old find that only execs rm one file at a time:</p>\n\n<pre><code>find /home/user/Maildir/.SPAM/cur -type f | xargs rm\n</code></pre>\n\n<p>That handles too many files as well as no files. Thanks to Charles Duffy for pointing out the + option to -exec in find.</p>\n" }, { "answer_id": 157388, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 0, "selected": false, "text": "<p>try adding</p>\n\n<pre><code>[email protected]\n</code></pre>\n\n<p>to the top of your cron file and you should get any input/errors mailed to you.</p>\n\n<p>Also consider adding the command as a cronjob</p>\n\n<pre><code>0 30 * * * /usr/bin/rm /home/user/Maildir/.SPAM/cur/*\n</code></pre>\n" }, { "answer_id": 157396, "author": "bcelary", "author_id": 15165, "author_profile": "https://Stackoverflow.com/users/15165", "pm_score": 0, "selected": false, "text": "<p>Try using a force option and forget about adding a path to rm command. I think it should not be needed...</p>\n\n<pre><code>rm -f\n</code></pre>\n\n<p>This will ensure that even if there are no files in the directory, rm command will not fail. If this is a part of a shell script, the * should work. It looks to me that you might have an empty dir...</p>\n\n<p>I understand that the rest of the script is being executed, right?</p>\n" }, { "answer_id": 4723959, "author": "ulidtko", "author_id": 531179, "author_profile": "https://Stackoverflow.com/users/531179", "pm_score": 0, "selected": false, "text": "<p>Is <code>rm</code> really located in <code>/usr/bin/</code> on your system? I have always thought that <code>rm</code> should reside in <code>/bin/</code>.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4275/" ]
Cron installation is vixie-cron `/etc/cron.daily/rmspam.cron` ``` #!/bin/bash /usr/bin/rm /home/user/Maildir/.SPAM/cur/*; ``` I Have this simple bash script that I want to add to a cron job (also includes spam learning commands before) but this part always fails with "File or directory not found" From what I figure is the metachar isn't being interperted correctly when run as a cron job. If I execute the script from the commandline it works fine. I'd like a why for this not working and of course a working solution :) Thanks edit #1 came back to this question when I got popular question badge for it. I first did this, ``` #!/bin/bash find /home/user/Maildir/.SPAM/cur/ -t file | xargs rm ``` and just recently was reading through the xargs man page and changed it to this ``` #!/bin/bash find /home/user/Maildir/.SPAM/cur/ -t file | xargs --no-run-if-empty rm ``` short xargs option is -r
If there are no files in the directory, then the wildcard will not be expanded and will be passed to the command directly. There is no file called "\*", and then the command fails with "File or directory not found." Try this instead: ``` if [ -f /home/user/Maildir/.SPAM/cur/* ]; then rm /home/user/Maildir/.SPAM/cur/* fi ``` Or just use the "-f" flag to rm. The other problem with this command is what happens when there is too much spam for the maximum length of the command line. Something like this is probably better overall: ``` find /home/user/Maildir/.SPAM/cur -type f -exec rm '{}' + ``` If you have an old find that only execs rm one file at a time: ``` find /home/user/Maildir/.SPAM/cur -type f | xargs rm ``` That handles too many files as well as no files. Thanks to Charles Duffy for pointing out the + option to -exec in find.
157,359
<p>I've been building an error logging app recently and was after a way of accurately timestamping the incoming data. When I say accurately I mean each timestamp should be accurate relative to each other (no need to sync to an atomic clock or anything like that).</p> <p>I've been using datetime.now() as a first stab, but this isn't perfect:</p> <pre><code>&gt;&gt;&gt; for i in range(0,1000): ... datetime.datetime.now() ... datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) etc. </code></pre> <p>The changes between clocks for the first second of samples looks like this:</p> <pre><code>uSecs difference 562000 578000 16000 609000 31000 625000 16000 640000 15000 656000 16000 687000 31000 703000 16000 718000 15000 750000 32000 765000 15000 781000 16000 796000 15000 828000 32000 843000 15000 859000 16000 890000 31000 906000 16000 921000 15000 937000 16000 968000 31000 984000 16000 </code></pre> <p>So it looks like the timer data is only updated every ~15-32ms on my machine. The problem comes when we come to analyse the data because sorting by something other than the timestamp and then sorting by timestamp again can leave the data in the wrong order (chronologically). It would be nice to have the time stamps accurate to the point that any call to the time stamp generator gives a unique timestamp.</p> <p>I had been considering some methods involving using a time.clock() call added to a starting datetime, but would appreciate a solution that would work accurately across threads on the same machine. Any suggestions would be very gratefully received.</p>
[ { "answer_id": 157439, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 4, "selected": false, "text": "<p>time.clock() only measures wallclock time on Windows. On other systems, time.clock() actually measures CPU-time. On those systems time.time() is more suitable for wallclock time, and it has as high a resolution as Python can manage -- which is as high as the OS can manage; usually using gettimeofday(3) (microsecond resolution) or ftime(3) (millisecond resolution.) Other OS restrictions actually make the real resolution a lot higher than that. datetime.datetime.now() uses time.time(), so time.time() directly won't be better.</p>\n\n<p>For the record, if I use datetime.datetime.now() in a loop, I see about a 1/10000 second resolution. From looking at your data, you have much, much coarser resolution than that. I'm not sure if there's anything Python as such can do, although you may be able to convince the OS to do better through other means.</p>\n\n<p>I seem to recall that on Windows, time.clock() is actually (slightly) more accurate than time.time(), but it measures wallclock since the first call to time.clock(), so you have to remember to 'initialize' it first.</p>\n" }, { "answer_id": 157656, "author": "Corey Goldberg", "author_id": 16148, "author_profile": "https://Stackoverflow.com/users/16148", "pm_score": 2, "selected": false, "text": "<p>Here is a thread about Python timing accuracy:<br><br>\n<a href=\"https://stackoverflow.com/questions/85451/python-timeclock-vs-timetime-accuracy\">Python - time.clock() vs. time.time() - accuracy?</a></p>\n" }, { "answer_id": 157711, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 4, "selected": true, "text": "<p>You're unlikely to get sufficiently fine-grained control that you can completely eliminate the possibility\nof duplicate timestamps - you'd need resolution smaller than the time it takes to generate a datetime object. There are a couple of other approaches you might take to deal with it:</p>\n\n<ol>\n<li><p>Deal with it. Leave your timestamps non-unique as they are, but rely on python's sort being stable to deal with reordering problems. Sorting on timestamp <em>first</em>, then something else will retain the timestamp ordering - you just have to be careful to always start from the timestamp ordered list every time, rather than doing multiple sorts on the same list.</p></li>\n<li><p>Append your own value to enforce uniqueness. Eg. include an incrementing integer value as part of the key, or append such a value only if timestamps are different. Eg.</p></li>\n</ol>\n\n<p>The following will guarantee unique timestamp values:</p>\n\n<pre><code> class TimeStamper(object):\n def __init__(self):\n self.lock = threading.Lock()\n self.prev = None\n self.count = 0\n\n def getTimestamp(self):\n with self.lock:\n ts = str(datetime.now())\n if ts == self.prev:\n ts +='.%04d' % self.count\n self.count += 1\n else:\n self.prev = ts\n self.count = 1\n return ts\n</code></pre>\n\n<p>For multiple processes (rather than threads), it gets a bit trickier though.</p>\n" }, { "answer_id": 157871, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "<p>\"timestamp should be accurate relative to each other \"</p>\n\n<p>Why time? Why not a sequence number? If it's any client of client-server application, network latency makes timestamps kind of random.</p>\n\n<p>Are you matching some external source of information? Say a log on another application? Again, if there's a network, those times won't be too close.</p>\n\n<p>If you must match things between separate apps, consider passing GUID's around so that both apps log the GUID value. Then you could be absolutely sure they match, irrespective of timing differences.</p>\n\n<p>If you want the <em>relative</em> order to be exactly right, maybe it's enough for your logger to assign a sequence number to each message in the order they were received.</p>\n" }, { "answer_id": 160208, "author": "Jon Cage", "author_id": 15369, "author_profile": "https://Stackoverflow.com/users/15369", "pm_score": 3, "selected": false, "text": "<p>Thank you all for your contributions - they've all be very useful. Brian's answer seems closest to what I eventually went with (i.e. deal with it but use a sort of unique identifier - see below) so I've accepted his answer. I managed to consolidate all the various data receivers into a single thread which is where the timestamping is now done using my new <strong>AccurrateTimeStamp</strong> class. What I've done works as long as the time stamp is the first thing to use the clock.</p>\n\n<p>As S.Lott stipulates, without a realtime OS, they're never going to be absolutely perfect. I really only wanted something that would let me see relative to each incoming chunk of data, when things were being received so what I've got below will work well.</p>\n\n<p>Thanks again everyone!</p>\n\n<pre><code>import time\n\nclass AccurateTimeStamp():\n \"\"\"\n A simple class to provide a very accurate means of time stamping some data\n \"\"\"\n\n # Do the class-wide initial time stamp to synchronise calls to \n # time.clock() to a single time stamp\n initialTimeStamp = time.time()+ time.clock()\n\n def __init__(self):\n \"\"\"\n Constructor for the AccurateTimeStamp class.\n This makes a stamp based on the current time which should be more \n accurate than anything you can get out of time.time().\n NOTE: This time stamp will only work if nothing has called clock() in\n this instance of the Python interpreter.\n \"\"\"\n # Get the time since the first of call to time.clock()\n offset = time.clock()\n\n # Get the current (accurate) time\n currentTime = AccurateTimeStamp.initialTimeStamp+offset\n\n # Split the time into whole seconds and the portion after the fraction \n self.accurateSeconds = int(currentTime)\n self.accuratePastSecond = currentTime - self.accurateSeconds\n\n\ndef GetAccurateTimeStampString(timestamp):\n \"\"\"\n Function to produce a timestamp of the form \"13:48:01.87123\" representing \n the time stamp 'timestamp'\n \"\"\"\n # Get a struct_time representing the number of whole seconds since the \n # epoch that we can use to format the time stamp\n wholeSecondsInTimeStamp = time.localtime(timestamp.accurateSeconds)\n\n # Convert the whole seconds and whatever fraction of a second comes after\n # into a couple of strings \n wholeSecondsString = time.strftime(\"%H:%M:%S\", wholeSecondsInTimeStamp)\n fractionAfterSecondString = str(int(timestamp.accuratePastSecond*1000000))\n\n # Return our shiny new accurate time stamp \n return wholeSecondsString+\".\"+fractionAfterSecondString\n\n\nif __name__ == '__main__':\n for i in range(0,500):\n timestamp = AccurateTimeStamp()\n print GetAccurateTimeStampString(timestamp)\n</code></pre>\n" }, { "answer_id": 284375, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I wanted to thank J. Cage for this last post. </p>\n\n<p>For my work, \"reasonable\" timing of events across processes and platforms is essential. There are obviously lots of places where things can go askew (clock drift, context switching, etc.), however this accurate timing solution will, I think, help to ensure that the time stamps recorded are sufficiently accurate to see the other sources of error. </p>\n\n<p>That said, there are a couple of details I wonder about that are explained in <a href=\"http://www.ibm.com/developerworks/library/i-seconds/\" rel=\"nofollow noreferrer\" title=\"When Microseconds Matter\">When MicroSeconds Matter</a>. For example, I think time.clock() will eventually wrap. I think for this to work for a long running process, you might have to handle that.</p>\n" }, { "answer_id": 22194015, "author": "Jonathan Livni", "author_id": 348545, "author_profile": "https://Stackoverflow.com/users/348545", "pm_score": 2, "selected": false, "text": "<p>A few years past since the question has been asked and answered, and this has been dealt with, at least for CPython on Windows. Using the script below on both Win7 64bit and Windows Server 2008 R2, I got the same results:</p>\n\n<ul>\n<li><code>datetime.now()</code> gives a resolution of 1ms and a jitter smaller than 1ms</li>\n<li><code>time.clock()</code> gives a resolution of better than 1us and a jitter much smaller than 1ms</li>\n</ul>\n\n<p>The script:</p>\n\n<pre><code>import time\nimport datetime\n\nt1_0 = time.clock()\nt2_0 = datetime.datetime.now()\n\nwith open('output.csv', 'w') as f:\n for i in xrange(100000):\n t1 = time.clock()\n t2 = datetime.datetime.now()\n td1 = t1-t1_0\n td2 = (t2-t2_0).total_seconds()\n f.write('%.6f,%.6f\\n' % (td1, td2))\n</code></pre>\n\n<p>The results visualized:\n<img src=\"https://i.stack.imgur.com/PHaYA.jpg\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 38840918, "author": "Gabriel Staples", "author_id": 4561887, "author_profile": "https://Stackoverflow.com/users/4561887", "pm_score": 0, "selected": false, "text": "<p>If you want microsecond-<em>resolution</em> (NOT accuracy) timestamps in Python, in <em>Windows,</em> you can use Windows's QPC timer, as demonstrated in my answer here: <a href=\"https://stackoverflow.com/questions/38319606/how-to-get-millisecond-and-microsecond-resolution-timestamps-in-python\">How to get millisecond and microsecond-resolution timestamps in Python</a>. I'm not sure how to do this in Linux yet, so if anyone knows, please comment or answer in the link above.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15369/" ]
I've been building an error logging app recently and was after a way of accurately timestamping the incoming data. When I say accurately I mean each timestamp should be accurate relative to each other (no need to sync to an atomic clock or anything like that). I've been using datetime.now() as a first stab, but this isn't perfect: ``` >>> for i in range(0,1000): ... datetime.datetime.now() ... datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) etc. ``` The changes between clocks for the first second of samples looks like this: ``` uSecs difference 562000 578000 16000 609000 31000 625000 16000 640000 15000 656000 16000 687000 31000 703000 16000 718000 15000 750000 32000 765000 15000 781000 16000 796000 15000 828000 32000 843000 15000 859000 16000 890000 31000 906000 16000 921000 15000 937000 16000 968000 31000 984000 16000 ``` So it looks like the timer data is only updated every ~15-32ms on my machine. The problem comes when we come to analyse the data because sorting by something other than the timestamp and then sorting by timestamp again can leave the data in the wrong order (chronologically). It would be nice to have the time stamps accurate to the point that any call to the time stamp generator gives a unique timestamp. I had been considering some methods involving using a time.clock() call added to a starting datetime, but would appreciate a solution that would work accurately across threads on the same machine. Any suggestions would be very gratefully received.
You're unlikely to get sufficiently fine-grained control that you can completely eliminate the possibility of duplicate timestamps - you'd need resolution smaller than the time it takes to generate a datetime object. There are a couple of other approaches you might take to deal with it: 1. Deal with it. Leave your timestamps non-unique as they are, but rely on python's sort being stable to deal with reordering problems. Sorting on timestamp *first*, then something else will retain the timestamp ordering - you just have to be careful to always start from the timestamp ordered list every time, rather than doing multiple sorts on the same list. 2. Append your own value to enforce uniqueness. Eg. include an incrementing integer value as part of the key, or append such a value only if timestamps are different. Eg. The following will guarantee unique timestamp values: ``` class TimeStamper(object): def __init__(self): self.lock = threading.Lock() self.prev = None self.count = 0 def getTimestamp(self): with self.lock: ts = str(datetime.now()) if ts == self.prev: ts +='.%04d' % self.count self.count += 1 else: self.prev = ts self.count = 1 return ts ``` For multiple processes (rather than threads), it gets a bit trickier though.
157,392
<p>I want to find out, with an SQL query, whether an index is UNIQUE or not. I'm using SQLite 3.</p> <p>I have tried two approaches:</p> <pre><code>SELECT * FROM sqlite_master WHERE name = 'sqlite_autoindex_user_1' </code></pre> <p>This returns information about the index ("type", "name", "tbl_name", "rootpage" and "sql"). Note that the sql column is empty when the index is automatically created by SQLite.</p> <pre><code>PRAGMA index_info(sqlite_autoindex_user_1); </code></pre> <p>This returns the columns in the index ("seqno", "cid" and "name").</p> <p>Any other suggestions?</p> <p><strong>Edit:</strong> The above example is for an auto-generated index, but my question is about indexes in general. For example, I can create an index with "CREATE UNIQUE INDEX index1 ON visit (user, date)". It seems no SQL command will show if my new index is UNIQUE or not.</p>
[ { "answer_id": 157636, "author": "dland", "author_id": 18625, "author_profile": "https://Stackoverflow.com/users/18625", "pm_score": 2, "selected": false, "text": "<p>you can programmatically build a select statement to see if any tuples point to more than one row. If you get back three columns, foo, bar and baz, create the following query</p>\n\n<pre><code>select count(*) from t\ngroup by foo, bar, baz\nhaving count(*) &gt; 1\n</code></pre>\n\n<p>If that returns any rows, your index is not unique, since more than one row maps to the given tuple. If sqlite3 supports derived tables (I've yet to have the need, so I don't know off-hand), you can make this even more succinct:</p>\n\n<pre><code>select count(*) from (\n select count(*) from t\n group by foo, bar, baz\n having count(*) &gt; 1\n)\n</code></pre>\n\n<p>This will return a single row result set, denoting the number of duplicate tuple sets. If positive, your index is not unique.</p>\n" }, { "answer_id": 165970, "author": "Christian Davén", "author_id": 12534, "author_profile": "https://Stackoverflow.com/users/12534", "pm_score": 3, "selected": false, "text": "<p>Since noone's come up with a good answer, I think the best solution is this:</p>\n\n<ul>\n<li>If the index starts with \"sqlite_autoindex\", it is an auto-generated index for a single UNIQUE column</li>\n<li><p>Otherwise, look for the UNIQUE keyword in the sql column in the table sqlite_master, with something like this:</p>\n\n<p>SELECT * FROM sqlite_master WHERE type = 'index' AND sql LIKE '%UNIQUE%'</p></li>\n</ul>\n" }, { "answer_id": 459512, "author": "Noah", "author_id": 12113, "author_profile": "https://Stackoverflow.com/users/12113", "pm_score": 1, "selected": false, "text": "<p>You are close:</p>\n\n<p>1) If the index starts with <code>\"sqlite_autoindex\"</code>, it is an auto-generated index for the primary key . However, this will be in the <code>sqlite_master</code> or <code>sqlite_temp_master</code> tables depending depending on whether the table being indexed is temporary. </p>\n\n<p>2) You need to watch out for table names and columns that contain the substring <code>unique</code>, so you want to use:</p>\n\n<pre><code>SELECT * FROM sqlite_master WHERE type = 'index' AND sql LIKE 'CREATE UNIQUE INDEX%'\n</code></pre>\n\n<p>See the sqlite website documentation on <a href=\"http://sqlite.org/lang_createindex.html\" rel=\"nofollow noreferrer\">Create Index</a></p>\n" }, { "answer_id": 1453761, "author": "finnw", "author_id": 12048, "author_profile": "https://Stackoverflow.com/users/12048", "pm_score": 6, "selected": true, "text": "<pre><code>PRAGMA INDEX_LIST('table_name');\n</code></pre>\n\n<p>Returns a table with 3 columns:</p>\n\n<ol>\n<li><code>seq</code> Unique numeric ID of index</li>\n<li><code>name</code> Name of the index</li>\n<li><code>unique</code> Uniqueness flag (nonzero if <code>UNIQUE</code> index.)</li>\n</ol>\n\n<p><strong>Edit</strong></p>\n\n<p>Since SQLite 3.16.0 you can also use table-valued pragma functions which have the advantage that you can <code>JOIN</code> them to search for a specific table and column. See <a href=\"https://stackoverflow.com/a/53629321/12048\">@mike-scotty's answer</a>.</p>\n" }, { "answer_id": 53629321, "author": "Mike Scotty", "author_id": 4349415, "author_profile": "https://Stackoverflow.com/users/4349415", "pm_score": 1, "selected": false, "text": "<p>As of sqlite 3.16.0 you could also use pragma functions:</p>\n\n<pre><code>SELECT distinct il.name\n FROM sqlite_master AS m,\n pragma_index_list(m.name) AS il,\n pragma_index_info(il.name) AS ii\n WHERE m.type='table' AND il.[unique] = 1;\n</code></pre>\n\n<p>The above statement will list all names of unique indexes.</p>\n\n<pre><code>SELECT DISTINCT m.name as table_name, ii.name as column_name\n FROM sqlite_master AS m,\n pragma_index_list(m.name) AS il,\n pragma_index_info(il.name) AS ii\n WHERE m.type='table' AND il.[unique] = 1;\n</code></pre>\n\n<p>The above statement will return all tables and their columns if the column is part of a unique index.</p>\n\n<p>From the <a href=\"https://www.sqlite.org/pragma.html\" rel=\"nofollow noreferrer\">docs</a>:</p>\n\n<blockquote>\n <p>The table-valued functions for PRAGMA feature was added in SQLite version 3.16.0 (2017-01-02). Prior versions of SQLite cannot use this feature. </p>\n</blockquote>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12534/" ]
I want to find out, with an SQL query, whether an index is UNIQUE or not. I'm using SQLite 3. I have tried two approaches: ``` SELECT * FROM sqlite_master WHERE name = 'sqlite_autoindex_user_1' ``` This returns information about the index ("type", "name", "tbl\_name", "rootpage" and "sql"). Note that the sql column is empty when the index is automatically created by SQLite. ``` PRAGMA index_info(sqlite_autoindex_user_1); ``` This returns the columns in the index ("seqno", "cid" and "name"). Any other suggestions? **Edit:** The above example is for an auto-generated index, but my question is about indexes in general. For example, I can create an index with "CREATE UNIQUE INDEX index1 ON visit (user, date)". It seems no SQL command will show if my new index is UNIQUE or not.
``` PRAGMA INDEX_LIST('table_name'); ``` Returns a table with 3 columns: 1. `seq` Unique numeric ID of index 2. `name` Name of the index 3. `unique` Uniqueness flag (nonzero if `UNIQUE` index.) **Edit** Since SQLite 3.16.0 you can also use table-valued pragma functions which have the advantage that you can `JOIN` them to search for a specific table and column. See [@mike-scotty's answer](https://stackoverflow.com/a/53629321/12048).
157,424
<p>I have a dictionary of 200,000 items (the keys are strings and the values are integers).</p> <p>What is the best/most pythonic way to print the items sorted by descending value then ascending key (i.e. a 2 key sort)?</p> <pre><code> a={ 'keyC':1, 'keyB':2, 'keyA':1 } b = a.items() b.sort( key=lambda a:a[0]) b.sort( key=lambda a:a[1], reverse=True ) print b &gt;&gt;&gt;[('keyB', 2), ('keyA', 1), ('keyC', 1)] </code></pre>
[ { "answer_id": 157445, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 5, "selected": true, "text": "<p>You can't sort dictionaries. You have to sort the list of items.</p>\n\n<p>Previous versions were wrong. When you have a numeric value, it's easy to sort in reverse order. These will do that. But this isn't general. This only works because the value is numeric.</p>\n\n<pre><code>a = { 'key':1, 'another':2, 'key2':1 }\n\nb= a.items()\nb.sort( key=lambda a:(-a[1],a[0]) )\nprint b\n</code></pre>\n\n<p>Here's an alternative, using an explicit function instead of a lambda and the cmp instead of the key option.</p>\n\n<pre><code>def valueKeyCmp( a, b ):\n return cmp( (-a[1], a[0]), (-b[1], b[0] ) )\n\nb.sort( cmp= valueKeyCmp )\nprint b\n</code></pre>\n\n<p>The more general solution is actually two separate sorts</p>\n\n<pre><code>b.sort( key=lambda a:a[1], reverse=True )\nb.sort( key=lambda a:a[0] )\nprint b\n</code></pre>\n" }, { "answer_id": 157462, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 1, "selected": false, "text": "<p>The most pythonic way to do it would be to know a little more about the actual data -- specifically, the maximum value you can have -- and then do it like this:</p>\n\n<pre><code>def sortkey((k, v)): \n return (maxval - v, k)\n\nitems = thedict.items()\nitems.sort(key=sortkey)\n</code></pre>\n\n<p>but unless you already know the maximum value, searching for the maximum value means looping through the dict an extra time (with <code>max(thedict.itervalues())</code>), which may be expensive. Alternatively, a keyfunc version of S.Lott's solution:</p>\n\n<pre><code>def sortkey((k, v)): \n return (-v, k)\n\nitems = thedict.items()\nitems.sort(key=sortkey)\n</code></pre>\n\n<p>An alternative that doesn't care about the types would be a comparison function:</p>\n\n<pre><code>def sortcmp((ak, av), (bk, bv)):\n # compare values 'in reverse' \n r = cmp(bv, av)\n if not r:\n # and then keys normally\n r = cmp(ak, bk)\n return r\n\nitems = thedict.items()\nitems.sort(cmp=sortcmp) \n</code></pre>\n\n<p>and this solution actually works for any type of key and value that you want to mix ascending and descending sorting with in the same key. If you value brevity you can write sortcmp as:</p>\n\n<pre><code>def sortcmp((ak, av), (bk, bv)):\n return cmp((bk, av), (ak, bv))\n</code></pre>\n" }, { "answer_id": 157494, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 0, "selected": false, "text": "<p>You can use something like this:</p>\n\n<pre><code>dic = {'aaa':1, 'aab':3, 'aaf':3, 'aac':2, 'aad':2, 'aae':4}\n\ndef sort_compare(a, b):\n c = cmp(dic[b], dic[a])\n if c != 0:\n return c\n return cmp(a, b)\n\nfor k in sorted(dic.keys(), cmp=sort_compare):\n print k, dic[k]\n</code></pre>\n\n<p>Don't know how pythonic it is however :)</p>\n" }, { "answer_id": 157792, "author": "Ricardo Reyes", "author_id": 3399, "author_profile": "https://Stackoverflow.com/users/3399", "pm_score": 3, "selected": false, "text": "<pre><code>data = { 'keyC':1, 'keyB':2, 'keyA':1 }\n\nfor key, value in sorted(data.items(), key=lambda x: (-1*x[1], x[0])):\n print key, value\n</code></pre>\n" }, { "answer_id": 158022, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 0, "selected": false, "text": "<p>Building on Thomas Wouters and Ricardo Reyes solutions:</p>\n\n<pre><code>def combine(*cmps):\n \"\"\"Sequence comparisons.\"\"\"\n def comparator(a, b):\n for cmp in cmps:\n result = cmp(a, b):\n if result:\n return result\n return 0\n return comparator\n\ndef reverse(cmp):\n \"\"\"Invert a comparison.\"\"\"\n def comparator(a, b):\n return cmp(b, a)\n return comparator\n\ndef compare_nth(cmp, n):\n \"\"\"Compare the n'th item from two sequences.\"\"\"\n def comparator(a, b):\n return cmp(a[n], b[n])\n return comparator\n\nrev_val_key_cmp = combine(\n # compare values, decreasing\n reverse(compare_nth(1, cmp)),\n\n # compare keys, increasing\n compare_nth(0, cmp)\n )\n\ndata = { 'keyC':1, 'keyB':2, 'keyA':1 }\n\nfor key, value in sorted(data.items(), cmp=rev_val_key_cmp):\n print key, value\n</code></pre>\n" }, { "answer_id": 280027, "author": "A. Coady", "author_id": 36433, "author_profile": "https://Stackoverflow.com/users/36433", "pm_score": 0, "selected": false, "text": "<pre><code>&gt;&gt;&gt; keys = sorted(a, key=lambda k: (-a[k], k))\n</code></pre>\n\n<p>or</p>\n\n<pre><code>&gt;&gt;&gt; keys = sorted(a)\n&gt;&gt;&gt; keys.sort(key=a.get, reverse=True)\n</code></pre>\n\n<p>then</p>\n\n<pre><code>print [(key, a[key]) for key in keys]\n[('keyB', 2), ('keyA', 1), ('keyC', 1)]\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a dictionary of 200,000 items (the keys are strings and the values are integers). What is the best/most pythonic way to print the items sorted by descending value then ascending key (i.e. a 2 key sort)? ``` a={ 'keyC':1, 'keyB':2, 'keyA':1 } b = a.items() b.sort( key=lambda a:a[0]) b.sort( key=lambda a:a[1], reverse=True ) print b >>>[('keyB', 2), ('keyA', 1), ('keyC', 1)] ```
You can't sort dictionaries. You have to sort the list of items. Previous versions were wrong. When you have a numeric value, it's easy to sort in reverse order. These will do that. But this isn't general. This only works because the value is numeric. ``` a = { 'key':1, 'another':2, 'key2':1 } b= a.items() b.sort( key=lambda a:(-a[1],a[0]) ) print b ``` Here's an alternative, using an explicit function instead of a lambda and the cmp instead of the key option. ``` def valueKeyCmp( a, b ): return cmp( (-a[1], a[0]), (-b[1], b[0] ) ) b.sort( cmp= valueKeyCmp ) print b ``` The more general solution is actually two separate sorts ``` b.sort( key=lambda a:a[1], reverse=True ) b.sort( key=lambda a:a[0] ) print b ```
157,431
<p>I have created a Web Application in asp.net 2.0. which is working fine on my Local machine. However when trying to deploy it on sever that has windows 2003 sever, I get the error:</p> <h1>Server Error in '/' Application.</h1> <hr> <h2><em>Parser Error</em></h2> <p><strong>Description:</strong> An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately. </p> <p><strong>Parser Error Message:</strong> The file '/MasterPage.master' does not exist.</p> <p><strong>Source Error:</strong> </p> <pre><code>Line 1: &lt;%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Title="LinkChecker Home " %&gt; Line 2: &lt;asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server"&gt; Line 3: </code></pre> <p><strong>Source File:</strong> /LinkChecker/Default.aspx <strong>Line</strong>: 1</p> <p>Any idea how this can be fixed?</p>
[ { "answer_id": 157440, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": true, "text": "<p>Is the folder on the web server (IIS presumably) marked as an ASP.NET application? If not, ~/ will point to the next application up, or the site root.</p>\n\n<p>It should have a cog icon in the IIS/MMC snap-in. Also ensure that it is running the right version of ASP.NET (v2.blah usually).</p>\n\n<p>In the IIS/MMC view, find the folder that is your project; right-click; Properties.\nCheck it has an Application Name; if it doesn't, click Create. You might also want to tweak the app-pool if you want it to run in a different identity than default. Also check the ASP.NET tab - for example, it might be 2.0.50727.</p>\n" }, { "answer_id": 157483, "author": "Mephisztoe", "author_id": 23369, "author_profile": "https://Stackoverflow.com/users/23369", "pm_score": 0, "selected": false, "text": "<p>There are other possible issues that could result in the error message stated above, like permission problems on the server for instance.</p>\n\n<p>Look <a href=\"http://forums.asp.net/p/972609/1228020.aspx\" rel=\"nofollow noreferrer\">here</a> for a thread in which this topic is also discussed.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6621/" ]
I have created a Web Application in asp.net 2.0. which is working fine on my Local machine. However when trying to deploy it on sever that has windows 2003 sever, I get the error: Server Error in '/' Application. ================================ --- *Parser Error* -------------- **Description:** An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately. **Parser Error Message:** The file '/MasterPage.master' does not exist. **Source Error:** ``` Line 1: <%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Title="LinkChecker Home " %> Line 2: <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server"> Line 3: ``` **Source File:** /LinkChecker/Default.aspx **Line**: 1 Any idea how this can be fixed?
Is the folder on the web server (IIS presumably) marked as an ASP.NET application? If not, ~/ will point to the next application up, or the site root. It should have a cog icon in the IIS/MMC snap-in. Also ensure that it is running the right version of ASP.NET (v2.blah usually). In the IIS/MMC view, find the folder that is your project; right-click; Properties. Check it has an Application Name; if it doesn't, click Create. You might also want to tweak the app-pool if you want it to run in a different identity than default. Also check the ASP.NET tab - for example, it might be 2.0.50727.
157,459
<p>I have a products table...</p> <p><a href="http://img357.imageshack.us/img357/6393/productscx5.gif" rel="nofollow noreferrer">alt text http://img357.imageshack.us/img357/6393/productscx5.gif</a></p> <p>and a revisions table, which is supposed to track changes to product info</p> <p><a href="http://img124.imageshack.us/img124/1139/revisionslz5.gif" rel="nofollow noreferrer">alt text http://img124.imageshack.us/img124/1139/revisionslz5.gif</a></p> <p>I try to query the database for all products, with their most recent revision...</p> <pre><code>select * from `products` as `p` left join `revisions` as `r` on `r`.`product_id` = `p`.`product_id` group by `p`.`product_id` order by `r`.`modified` desc </code></pre> <p>but I always just get the first revision. I need to do this in <strong>one</strong> select (ie no sub queries). I can manage it in mssql, is this even possible in mysql?</p>
[ { "answer_id": 157475, "author": "ctrlShiftBryan", "author_id": 6161, "author_profile": "https://Stackoverflow.com/users/6161", "pm_score": 1, "selected": false, "text": "<p>Begin and end dates on your history table would make this possible.(leaving the most recent end date null and stamping end dates on the previous record as you insert a new one)</p>\n\n<p>Otherwise you will have to use a sub-query.</p>\n" }, { "answer_id": 157523, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 0, "selected": false, "text": "<p>That same query is parsable in MySQL.</p>\n\n<p>Why are you using a Left JOIN instead of an INNER join or a RIGHT join? </p>\n\n<p>Also if you want to go about this in a different way, you have the MAX function at your disposal.</p>\n" }, { "answer_id": 159621, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": true, "text": "<p>Here's how I'd do it:</p>\n\n<pre><code>SELECT p.*, r.*\nFROM products AS p\n JOIN revisions AS r USING (product_id)\n LEFT OUTER JOIN revisions AS r2 \n ON (r.product_id = r2.product_id AND r.modified &lt; r2.modified)\nWHERE r2.revision_id IS NULL;\n</code></pre>\n\n<p>In other words: find the revision for which no other revision exists with the same product_id and a greater modified value.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18856/" ]
I have a products table... [alt text http://img357.imageshack.us/img357/6393/productscx5.gif](http://img357.imageshack.us/img357/6393/productscx5.gif) and a revisions table, which is supposed to track changes to product info [alt text http://img124.imageshack.us/img124/1139/revisionslz5.gif](http://img124.imageshack.us/img124/1139/revisionslz5.gif) I try to query the database for all products, with their most recent revision... ``` select * from `products` as `p` left join `revisions` as `r` on `r`.`product_id` = `p`.`product_id` group by `p`.`product_id` order by `r`.`modified` desc ``` but I always just get the first revision. I need to do this in **one** select (ie no sub queries). I can manage it in mssql, is this even possible in mysql?
Here's how I'd do it: ``` SELECT p.*, r.* FROM products AS p JOIN revisions AS r USING (product_id) LEFT OUTER JOIN revisions AS r2 ON (r.product_id = r2.product_id AND r.modified < r2.modified) WHERE r2.revision_id IS NULL; ``` In other words: find the revision for which no other revision exists with the same product\_id and a greater modified value.
157,480
<p>How can this line in Java be translated to Ruby:<br> String className = "java.util.Vector";<br> ...<br> Object o = Class.forName(className).newInstance(); </p> <p>Thanks!</p>
[ { "answer_id": 157499, "author": "Ken", "author_id": 20621, "author_profile": "https://Stackoverflow.com/users/20621", "pm_score": 7, "selected": true, "text": "<pre><code>Object::const_get('String').new()\n</code></pre>\n" }, { "answer_id": 158145, "author": "Ian Terrell", "author_id": 9269, "author_profile": "https://Stackoverflow.com/users/9269", "pm_score": 5, "selected": false, "text": "<p>If you're using ActiveSupport (i.e. Rails), there is a method added to <code>String</code> that does this:</p>\n\n<pre><code>\"String\".constantize.new\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How can this line in Java be translated to Ruby: String className = "java.util.Vector"; ... Object o = Class.forName(className).newInstance(); Thanks!
``` Object::const_get('String').new() ```
157,504
<p>I have object A which in turn has a property of type Object B</p> <pre><code>Class A property x as Object B End Class </code></pre> <p>On my ASP.NET page when I select a gridview item which maps to an object of type A I serialize the object onto the QueryString and pass it to the next page. </p> <p>However I run into problems if property x actually has some value as it looks like I exceed the QueryString capacity length of 4k (although I didn't think the objects were that large) </p> <p>I have already considered the following approaches to do this</p> <ul> <li>Session Variables</li> </ul> <p><strong>Approach not used as I have read that this is bad practice.</strong></p> <ul> <li>Using a unique key for the object and retrieving it on the next page. </li> </ul> <p><strong>Approach not used as the objects do not map to a single instance in a table, they arte composed of data from different databases.</strong> </p> <p>So I guess my question is two fold</p> <ul> <li>Is it worth using GKZip to compress the querystring further (is this possible??)</li> <li>What other methods would people suggest to do this?</li> </ul>
[ { "answer_id": 157527, "author": "CodeRedick", "author_id": 17145, "author_profile": "https://Stackoverflow.com/users/17145", "pm_score": 2, "selected": false, "text": "<p>I don't understand why you wouldn't use session state but...</p>\n\n<p>Option 1: Viewstate</p>\n\n<p>Option 2: Form parameters instead of querystring</p>\n\n<p>But also be aware that you do not get the same object back when you serialize/deserialize. You get a new object initialized with the values of the original that were serialized out. You're going to end up with two of the object.</p>\n\n<p>EDIT: You can store values in viewstate using the same syntax as Session state</p>\n\n<p>ViewState[\"key\"] = val;</p>\n\n<p>The value has to be serializeable though.</p>\n" }, { "answer_id": 157593, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 1, "selected": false, "text": "<p>Cache is probably not the answer here either. As Telos mentioned, I'm not sure why you're not considering session.</p>\n\n<p>If you have a page that depends on this data being available, then you just throw a guard clause in the page load...</p>\n\n<pre><code>public void Page_Load()\n{\n\n if(!IsPostBack)\n { \n const string key = \"FunkyObject\";\n if(Session[key] == null)\n Response.Redirect(\"firstStep.aspx\");\n\n var obj = (FunkyObject)Session[key];\n DoSomething(obj);\n }\n}\n</code></pre>\n\n<p>If session is absolutely out of the quesiton, then you'll have to re-materialize this object on the other page. Just send the unique identifier in the querystring so you can pull it back again.</p>\n" }, { "answer_id": 157597, "author": "Aheho", "author_id": 21155, "author_profile": "https://Stackoverflow.com/users/21155", "pm_score": 2, "selected": false, "text": "<p>While storing objects in session might be considered bad practice, it's lightyears better than passing them via serialized querystrings. </p>\n\n<p>Back in classic asp, storing objects in session was considered bad practice because you created thread-affinity, and you also limited your ability to scale the site by adding other web servers. This is no longer a problem with asp.net (as long as you use an external stateserver).</p>\n\n<p>There are other reasons to avoid session variables, but in your case I think that's the way to go. </p>\n\n<p>Another option is to combine the 2 pages that need access to this object into one page, using panels to hide and display the needed \"sub-pages\" and use viewstate to store the object.</p>\n" }, { "answer_id": 157613, "author": "Max Schmeling", "author_id": 3226, "author_profile": "https://Stackoverflow.com/users/3226", "pm_score": 2, "selected": false, "text": "<p>I don't think passing it in the query string, or storing it in the session, is a good idea.</p>\n\n<p>You need one of the following:</p>\n\n<p>a) A caching layer. Something like Microsoft Velocity would work, but I doubt you need something on that scale.</p>\n\n<p>b) Put the keys to each object in the databases that you need in the query string and retrieve them the next time around. (E.g. myurl.com/mypage.aspx?db1objectkey=123&amp;db2objectkey=345&amp;db3objectkey=456) </p>\n" }, { "answer_id": 165148, "author": "Chad Braun-Duin", "author_id": 5458, "author_profile": "https://Stackoverflow.com/users/5458", "pm_score": 3, "selected": true, "text": "<p>If displaying the url of the next page in the browser does not matter, you could use the context.items collection.</p>\n\n<pre><code>context.items.add(\"keyA\", objectA)\nserver.transfer(\"nextPage.aspx\")\n</code></pre>\n\n<p>Then on the next page:</p>\n\n<pre><code>public sub page_load(...)\n dim objectA as A = ctype(context.items(\"keyA\"), objectA)\n dim objectB as B = objectA.B\nend sub\n</code></pre>\n\n<p>One reason to use this is if you want the users to believe that the next page is really a part of the first page. To them, it only appears as if a PostBack has occurred.</p>\n\n<p>Also, you don't really need a unique key using this approach if the only way to use \"next page\" is if you first came from \"first page\". The scope for the context items collections is specific to just this particular request.</p>\n\n<p>I agree with the other posters who mentioned that serialized objects on the querystring is a much worse evil than using session state. If you do use session state, just remember to clear the key you use immediately after using it.</p>\n" }, { "answer_id": 1107321, "author": "JNappi", "author_id": 135996, "author_profile": "https://Stackoverflow.com/users/135996", "pm_score": 2, "selected": false, "text": "<p>Using session state seems like the most practical way to do this, its exactly what its designed for.</p>\n" }, { "answer_id": 1834782, "author": "Hodge", "author_id": 223127, "author_profile": "https://Stackoverflow.com/users/223127", "pm_score": 0, "selected": false, "text": "<p>Here is what I do:</p>\n\n<p>Page1.aspx - Add a public property of an instance of my object. Add a button (Button1) with the PostBackURL property set to ~/Page2.aspx</p>\n\n<pre><code>Private _RP as ReportParameters\nPublic ReadOnly Property ReportParams() as ReportParameters\n Get\n Return _RP\n End Get\nEnd Property\n\nProtected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click\n _RP = New ReportParameters \n _RP.Name = \"Report 1\"\n _RP.Param = \"42\" \nEnd Sub\n</code></pre>\n\n<p>Now, on the second page, Page2.aspx add the following to the Markup at the top of the page under the first directive:</p>\n\n<pre><code>&lt;%@ PreviousPageType VirtualPath=\"~/Default.aspx\" %&gt;\n</code></pre>\n\n<p>Then for the Page_Load in the code behind for Page2.aspx, add the following</p>\n\n<pre><code>If Not Page.PreviousPage is Nothing Then\n Response.write (PreviousPage.ReportParams.Name &amp; \" \" &amp; PreviousPage.ReportParams.Param)\nEnd If\n</code></pre>\n" }, { "answer_id": 4486305, "author": "GlennG", "author_id": 196285, "author_profile": "https://Stackoverflow.com/users/196285", "pm_score": 0, "selected": false, "text": "<p>Session isn't always available. For instance when XSS (cross-site-scripting) security settings on IE prevent the storage of third-party cookies. If your site is being called within an IFrame from a site that's not your DNS domain, your cookies are going to be blocked by default. No cookies = no session.</p>\n\n<p>Another example is where you have to pass control to another website that will make the callback to your site as a pure URL, not a post. In this case you have to store your session parameters in a querystring parameter, something that's tough to do given the 4k size constraint and URL encoding, not to mention encryption, etc.</p>\n\n<p>The issue is that most of the built-in serialisation methods are pretty verbose, thus one has to resort to a roll-your-own method, probably using reflection.</p>\n\n<p>Another reason for not using sessions is simply to give a better user experience; sessions get cleared after N minutes and when the server restarts. OK, in this case a viewstate is preferable, but sometimes it's not possible to use a form. OK, one could rely on JavaScript to do a postback, but again, that's not always possible.</p>\n\n<p>These are the problems I'm currently coding around.</p>\n" }, { "answer_id": 15236799, "author": "Denny Jacob", "author_id": 2127505, "author_profile": "https://Stackoverflow.com/users/2127505", "pm_score": 0, "selected": false, "text": "<p>Faced with a similar situation what I did, is to XML serialize the object and pass it around as query string parameter. The difficulty with this approach was that despite encoding, the receiving form throws exception saying \"potentially dangerous request...\". The way I got around was to encrypt the serialized object and then encode to pass it around as query string parameter. Which in turn made the query string tamper proof (bonus wandering into the HMAC territory)!</p>\n\n<p>FormA XML serializes an object > encrypts the serialized string > encode > pass as query string to FormB FormB decrypts the query parameter value (as request.querystring decodes also) > deserialize the resulting XML string to object using XmlSerializer.</p>\n\n<p>I can share my VB.NET code upon request to howIdidit-at-applecart-dot-net </p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11802/" ]
I have object A which in turn has a property of type Object B ``` Class A property x as Object B End Class ``` On my ASP.NET page when I select a gridview item which maps to an object of type A I serialize the object onto the QueryString and pass it to the next page. However I run into problems if property x actually has some value as it looks like I exceed the QueryString capacity length of 4k (although I didn't think the objects were that large) I have already considered the following approaches to do this * Session Variables **Approach not used as I have read that this is bad practice.** * Using a unique key for the object and retrieving it on the next page. **Approach not used as the objects do not map to a single instance in a table, they arte composed of data from different databases.** So I guess my question is two fold * Is it worth using GKZip to compress the querystring further (is this possible??) * What other methods would people suggest to do this?
If displaying the url of the next page in the browser does not matter, you could use the context.items collection. ``` context.items.add("keyA", objectA) server.transfer("nextPage.aspx") ``` Then on the next page: ``` public sub page_load(...) dim objectA as A = ctype(context.items("keyA"), objectA) dim objectB as B = objectA.B end sub ``` One reason to use this is if you want the users to believe that the next page is really a part of the first page. To them, it only appears as if a PostBack has occurred. Also, you don't really need a unique key using this approach if the only way to use "next page" is if you first came from "first page". The scope for the context items collections is specific to just this particular request. I agree with the other posters who mentioned that serialized objects on the querystring is a much worse evil than using session state. If you do use session state, just remember to clear the key you use immediately after using it.
157,511
<p>I have a <code>Dictionary&lt;string, someobject&gt;</code>.</p> <p>EDIT: It was pointed out to me, that my example was bad. My whole intention was not to update the references in a loop but to update different values based on differnt threads need to update/get the data. I changed the loop to a method.</p> <p>I need to update items in my dictionary - one key at a time and i was wondering if there are any problems in using the lock on the .key value of my Dictionary object?</p> <pre><code>private static Dictionary&lt;string, MatrixElement&gt; matrixElements = new Dictionary&lt;string, MatrixElement&gt;(); //Pseudo-code public static void UpdateValue(string key) { KeyValuePair&lt;string, MatrixElement&gt; keyValuePair = matrixElements[key]; lock (keyValuePair.Key) { keyValuePair.Value = SomeMeanMethod(); } } </code></pre> <p>Would that hold up in court or fail? I just want each value in the dictionary to be locked independantly so locking (and updating) one value does not lock the others. Also i'm aware the locking will be holding for a long time - but the data will be invalid untill updated fully.</p>
[ { "answer_id": 157536, "author": "Sander", "author_id": 2928, "author_profile": "https://Stackoverflow.com/users/2928", "pm_score": 3, "selected": false, "text": "<p>No, this would not work.</p>\n\n<p>The reason is <a href=\"http://en.wikipedia.org/wiki/String_intern_pool\" rel=\"noreferrer\">string interning</a>. This means that:</p>\n\n<pre><code>string a = \"Something\";\nstring b = \"Something\";\n</code></pre>\n\n<p>are both the same object! Therefore, you should never lock on strings because if some other part of the program (e.g. another instance of this same object) also wants to lock on the same string, you could accidentally create lock contention where there is no need for it; possibly even a deadlock.</p>\n\n<p>Feel free to do this with non-strings, though. For best clarity, I make it a personal habit to always create a separate lock object:</p>\n\n<pre><code>class Something\n{\n bool threadSafeBool = true;\n object threadSafeBoolLock = new object(); // Always lock this to use threadSafeBool\n}\n</code></pre>\n\n<p>I recommend you do the same. Create a Dictionary with the lock objects for every matrix cell. Then, lock these objects when needed.</p>\n\n<p>PS. Changing the collection you are iterating over is not considered very nice. It will even throw an exception with most collection types. Try to refactor this - e.g. iterate over a list of keys, if it will always be constant, not the pairs.</p>\n" }, { "answer_id": 157570, "author": "Philip Rieck", "author_id": 12643, "author_profile": "https://Stackoverflow.com/users/12643", "pm_score": 5, "selected": true, "text": "<p>Locking on an object that is accessible outside of the code locking it is a big risk. If any other code (anywhere) ever locks that object you could be in for some deadlocks that are hard to debug. Also note that you lock the <em>object</em>, not the reference, so if I gave you a dictionary, I may still hold references to the keys and lock on them - causing us to lock on the same object.</p>\n\n<p><em>If</em> you completely encapsulate the dictionary, and generate the keys yourself (they aren't ever passed in, then you may be safe. </p>\n\n<p>However, try to stick to one rule - limit the visibility of the objects you lock on to the locking code itself whenever possible.</p>\n\n<p>That's why you see this:</p>\n\n<pre><code>public class Something\n{\n private readonly object lockObj = new object();\n\n public SomethingReentrant()\n {\n lock(lockObj) // Line A\n {\n // ...\n }\n }\n}\n</code></pre>\n\n<p>rather than seeing line A above replaced by</p>\n\n<pre><code> lock(this)\n</code></pre>\n\n<p>That way, a separate object is locked on, and the visibility is limited.</p>\n\n<p><strong>Edit</strong> <a href=\"https://stackoverflow.com/users/22656/jon-skeet\">Jon Skeet</a> correctly observed that lockObj above should be readonly.</p>\n" }, { "answer_id": 157580, "author": "Ray Hayes", "author_id": 7093, "author_profile": "https://Stackoverflow.com/users/7093", "pm_score": 0, "selected": false, "text": "<p>In your example, you can not do what you want to do! </p>\n\n<p>You will get a <strong>System.InvalidOperationException</strong> with a message of <strong>Collection was modified; enumeration operation may not execute.</strong></p>\n\n<p>Here is an example to prove:</p>\n\n<pre><code>using System.Collections.Generic;\nusing System;\n\npublic class Test\n{\n private Int32 age = 42;\n\n static public void Main()\n {\n (new Test()).TestMethod();\n }\n\n public void TestMethod()\n {\n Dictionary&lt;Int32, string&gt; myDict = new Dictionary&lt;Int32, string&gt;();\n\n myDict[age] = age.ToString();\n\n foreach(KeyValuePair&lt;Int32, string&gt; pair in myDict)\n {\n Console.WriteLine(\"{0} : {1}\", pair.Key, pair.Value);\n ++age;\n Console.WriteLine(\"{0} : {1}\", pair.Key, pair.Value);\n myDict[pair.Key] = \"new\";\n Console.WriteLine(\"Changed!\");\n }\n } \n}\n</code></pre>\n\n<p>The output would be:</p>\n\n<pre><code>42 : 42\n42 : 42\n\nUnhandled Exception: System.InvalidOperationException: Collection was modified; enumeration operation may not execute.\n at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)\n at System.Collections.Generic.Dictionary`2.Enumerator.MoveNext()\n at Test.TestMethod()\n at Test.Main()\n</code></pre>\n" }, { "answer_id": 157612, "author": "babackman", "author_id": 16604, "author_profile": "https://Stackoverflow.com/users/16604", "pm_score": 0, "selected": false, "text": "<p>I can see a few potential issues there:<br></p>\n\n<ol>\n<li>strings can be shared, so you don't necessarily know who else might be locking on that key object for what other reason</li>\n<li>strings might <em>not</em> be shared: you may be locking on one string key with the value \"Key1\" and some other piece of code may have a different string object that also contains the characters \"Key1\". To the dictionary they're the same key but as far as locking is concerned they are different objects.</li>\n<li>That locking won't prevent changes to the value objects themselves, i.e. <code>matrixElements[someKey].ChangeAllYourContents()</code></li>\n</ol>\n" }, { "answer_id": 158361, "author": "Ilya Ryzhenkov", "author_id": 18575, "author_profile": "https://Stackoverflow.com/users/18575", "pm_score": 2, "selected": false, "text": "<p><em>Note: I assume exception when modifying collection during iteration is already fixed</em></p>\n\n<p>Dictionary is not thread-safe collection, which means it is <strong>not</strong> safe to modify and read collection from different threads without external synchronization. Hashtable is (was?) thread-safe for one-writer-many-readers scenario, but Dictionary has different internal data structure and doesn't inherit this guarantee. </p>\n\n<p>This means that you cannot modify your dictionary while you accessing it for read or write from the other thread, it can just broke internal data structures. Locking on the key doesn't protect internal data structure, because while you modify that very key someone could be reading different key of your dictionary in another thread. Even if you can guarantee that all your keys are same objects (like said about string interning), this doesn't bring you on safe side. Example:</p>\n\n<ol>\n<li>You lock the key and begin to modify dictionary</li>\n<li>Another thread attempts to get value for the key which happens to fall into the same bucket as locked one. This is not only when hashcodes of two objects are the same, but more frequently when hashcode%tableSize is the same. </li>\n<li>Both threads are accessing the same bucket (linked list of keys with same hashcode%tableSize value)</li>\n</ol>\n\n<p>If there is no such key in dictionary, first thread will start modifying the list, and the second thread will likely to read incomplete state. </p>\n\n<p>If such key already exists, implementation details of dictionary could still modify data structure, for example move recently accessed keys to the head of the list for faster retrieval. You cannot rely on implementation details.</p>\n\n<p>There are many cases like that, when you will have corrupted dictionary. So you have to have external synchronization object (or use Dictionary itself, if it is not exposed to public) and lock on it during entire operation. If you need more granular locks when operation can take some long time, you can copy keys you need to update, iterate over it, lock entire dictionary during single key update (don't forget to verify key is still there) and release it to let other threads run. </p>\n" }, { "answer_id": 535809, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>If I'm not mistaken, the original intention was to lock on a single element, rather than locking the whole dictionary (like table-level lock vs. row level lock in a DB)</p>\n\n<p>you can't lock on the dictionary's key as many here explained. </p>\n\n<p>What you can do, is to keep an internal dictionary of lock objects, that corresponds to the actual dictionary. So when you'd want to write to YourDictionary[Key1], you'll first lock on InternalLocksDictionary[Key1] - so only a single thread will write to YourDictionary.</p>\n\n<p>a (not too clean) example can be <a href=\"http://kenegozi.com/blog/2008/08/24/keylevel-locked-cache-real-life-implementation/\" rel=\"nofollow noreferrer\">found here</a>.</p>\n" }, { "answer_id": 36621353, "author": "Mark", "author_id": 245052, "author_profile": "https://Stackoverflow.com/users/245052", "pm_score": 1, "selected": false, "text": "<p>Just came across this and thought id share some code I wrote a few years ago where I needed to a dictionary on a key basis</p>\n\n<pre><code> using (var lockObject = new Lock(hashedCacheID))\n {\n var lockedKey = lockObject.GetLock();\n //now do something with the dictionary\n }\n</code></pre>\n\n<p>the lock class</p>\n\n<pre><code>class Lock : IDisposable\n {\n private static readonly Dictionary&lt;string, string&gt; Lockedkeys = new Dictionary&lt;string, string&gt;();\n\n private static readonly object CritialLock = new object();\n\n private readonly string _key;\n private bool _isLocked;\n\n public Lock(string key)\n {\n _key = key;\n\n lock (CritialLock)\n {\n //if the dictionary doesnt contain the key add it\n if (!Lockedkeys.ContainsKey(key))\n {\n Lockedkeys.Add(key, String.Copy(key)); //enusre that the two objects have different references\n }\n }\n }\n\n public string GetLock()\n {\n var key = Lockedkeys[_key];\n\n if (!_isLocked)\n {\n Monitor.Enter(key);\n }\n _isLocked = true;\n\n return key;\n }\n\n public void Dispose()\n {\n var key = Lockedkeys[_key];\n\n if (_isLocked)\n {\n Monitor.Exit(key);\n }\n _isLocked = false;\n }\n }\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11619/" ]
I have a `Dictionary<string, someobject>`. EDIT: It was pointed out to me, that my example was bad. My whole intention was not to update the references in a loop but to update different values based on differnt threads need to update/get the data. I changed the loop to a method. I need to update items in my dictionary - one key at a time and i was wondering if there are any problems in using the lock on the .key value of my Dictionary object? ``` private static Dictionary<string, MatrixElement> matrixElements = new Dictionary<string, MatrixElement>(); //Pseudo-code public static void UpdateValue(string key) { KeyValuePair<string, MatrixElement> keyValuePair = matrixElements[key]; lock (keyValuePair.Key) { keyValuePair.Value = SomeMeanMethod(); } } ``` Would that hold up in court or fail? I just want each value in the dictionary to be locked independantly so locking (and updating) one value does not lock the others. Also i'm aware the locking will be holding for a long time - but the data will be invalid untill updated fully.
Locking on an object that is accessible outside of the code locking it is a big risk. If any other code (anywhere) ever locks that object you could be in for some deadlocks that are hard to debug. Also note that you lock the *object*, not the reference, so if I gave you a dictionary, I may still hold references to the keys and lock on them - causing us to lock on the same object. *If* you completely encapsulate the dictionary, and generate the keys yourself (they aren't ever passed in, then you may be safe. However, try to stick to one rule - limit the visibility of the objects you lock on to the locking code itself whenever possible. That's why you see this: ``` public class Something { private readonly object lockObj = new object(); public SomethingReentrant() { lock(lockObj) // Line A { // ... } } } ``` rather than seeing line A above replaced by ``` lock(this) ``` That way, a separate object is locked on, and the visibility is limited. **Edit** [Jon Skeet](https://stackoverflow.com/users/22656/jon-skeet) correctly observed that lockObj above should be readonly.
157,554
<p>I've got a XmlNodeList which I need to have it in a format that I can then re-use within a XSLT stylesheet by calling it from a C# extension method.</p> <p>Can anyone help? I have read that it might have something to do with using a XPathNavigator but I'm still a bit stuck.</p>
[ { "answer_id": 157624, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 4, "selected": true, "text": "<p>I had to solve this issue myself a couple of years ago. The only way I managed it was to create an XML fragment containing the nodes in the node list and then passing in the children of the fragment.</p>\n\n<pre><code>XsltArgumentList arguments = new XsltArgumentList();\nXmlNodeList nodelist;\nXmlDocument nodesFrament = new XmlDocument();\nXmlNode root = nodesFragment.CreateElement(\"root\");\nforeach (XmlNode node in nodeList)\n{\n root.AppendChild(node);\n}\nnodesFragment.AppendChild(root);\n\narguments.AddParam(\"argumentname\", string.Empty, nodesFragment.CreateNavigator().SelectChildren(XPathNodeType.All));\n</code></pre>\n\n<p>Then you need to make sure you have the corresponding argument in your XSLT, of course.</p>\n\n<p>Note that you probably don't need the additional XmlDocument. You could just call CreateNavigator() on the root XmlNode instance and use your existing XmlDocument for creating the element (I wrote this code some time ago and I've learned more since then - but I know the code above works, I haven't tried any alternatives).</p>\n" }, { "answer_id": 157676, "author": "chrisntr", "author_id": 4455, "author_profile": "https://Stackoverflow.com/users/4455", "pm_score": 0, "selected": false, "text": "<p>The note at the end was the most useful, I had infact transformed the XmlNodeList into a XmlDocument already so could just use the Navigator on there and create it as a XPathNodeIterator. </p>\n\n<p>Thanks for you help!</p>\n" }, { "answer_id": 9773708, "author": "soletan", "author_id": 278069, "author_profile": "https://Stackoverflow.com/users/278069", "pm_score": 0, "selected": false, "text": "<p>Didn't succeed with the answer provided before.</p>\n\n<p>Using AppendChild() to add previously selected nodes of XmlNodeList to a new document resulted in exception on trying to append nodes originating from a different document context. Several trials to fix this included adding my custom default namespace selected nodes in list are bound to. Finally I dropped the approach completely and switched the way I select nodes into XmlNodeList instances.</p>\n\n<p>Instead of</p>\n\n<pre><code>myXmlNode.SelectNodes( xpath, nsmgr )\n</code></pre>\n\n<p>I'm using</p>\n\n<pre><code>myXmlNode.CreateNavigator().Select( xpath, nsmgr )\n</code></pre>\n\n<p>to get an XPathNodeIterator instead of XmlNodeList. The resulting XPathNodeIterator of second code is now properly added as parameter value to XsltArgumentsList.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4455/" ]
I've got a XmlNodeList which I need to have it in a format that I can then re-use within a XSLT stylesheet by calling it from a C# extension method. Can anyone help? I have read that it might have something to do with using a XPathNavigator but I'm still a bit stuck.
I had to solve this issue myself a couple of years ago. The only way I managed it was to create an XML fragment containing the nodes in the node list and then passing in the children of the fragment. ``` XsltArgumentList arguments = new XsltArgumentList(); XmlNodeList nodelist; XmlDocument nodesFrament = new XmlDocument(); XmlNode root = nodesFragment.CreateElement("root"); foreach (XmlNode node in nodeList) { root.AppendChild(node); } nodesFragment.AppendChild(root); arguments.AddParam("argumentname", string.Empty, nodesFragment.CreateNavigator().SelectChildren(XPathNodeType.All)); ``` Then you need to make sure you have the corresponding argument in your XSLT, of course. Note that you probably don't need the additional XmlDocument. You could just call CreateNavigator() on the root XmlNode instance and use your existing XmlDocument for creating the element (I wrote this code some time ago and I've learned more since then - but I know the code above works, I haven't tried any alternatives).
157,557
<p>In VB.Net, I can declare a variable in a function as Static, like this:</p> <pre><code>Function EncodeForXml(ByVal data As String) As String Static badAmpersand As Regex = new Regex("&amp;(?![a-zA-Z]{2,6};|#[0-9]{2,4};)") data = badAmpersand.Replace(data, "&amp;amp;") ''// more processing return data End Function </code></pre> <p>Note that I need to use the keyword <code>Static</code>, rather than <code>Shared</code>, which is the normal way to express this in VB.Net. How can I do this in C#? I can't find its equivalent.</p>
[ { "answer_id": 157571, "author": "Max Schmeling", "author_id": 3226, "author_profile": "https://Stackoverflow.com/users/3226", "pm_score": 2, "selected": false, "text": "<p>There is no equivalent in C# unfortunately.</p>\n\n<p>You will need to use a class level variable.</p>\n\n<p>This is one of the few things that VB has that I wish C# had.</p>\n" }, { "answer_id": 157575, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 5, "selected": true, "text": "<p>Ha! In posting the question, I found the answer! Rather than googling for C# I should have been looking for details on how VB.Net implements it, and typing up the question made that apparent to me. After applying that insight, I found this:<br>\n<a href=\"http://weblogs.asp.net/psteele/articles/7717.aspx\" rel=\"noreferrer\">http://weblogs.asp.net/psteele/articles/7717.aspx</a></p>\n\n<p>That article explains that it's not really supported by the CLR, and the VB compiler creates a static (shared) variable \"under the hood\" in the method's class. To do the same in C#, I have to create the variable myself.</p>\n\n<p>More than that, it uses the <code>Monitor</code> class to make sure the static member is thread-safe as well. Nice.</p>\n\n<p>As a side note: I'd expect to see this in C# sometime soon. The general tactic I've observed from MS is that it doesn't like VB.Net and C# to get too far apart feature-wise. If one language has a feature not supported by the other it tends to become a priority for the language team for the next version.</p>\n" }, { "answer_id": 157654, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>Personally I'm glad that C# <em>doesn't</em> have this. Logically, methods don't have state: types and instances do. C# makes that logical model clearer, IMO.</p>\n" }, { "answer_id": 157733, "author": "Rinat Abdullin", "author_id": 47366, "author_profile": "https://Stackoverflow.com/users/47366", "pm_score": 1, "selected": false, "text": "<p>You have to declare this on the class level:</p>\n\n<pre><code>private static readonly RegEx badAmpersand = new RegEx(\"...\");\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ]
In VB.Net, I can declare a variable in a function as Static, like this: ``` Function EncodeForXml(ByVal data As String) As String Static badAmpersand As Regex = new Regex("&(?![a-zA-Z]{2,6};|#[0-9]{2,4};)") data = badAmpersand.Replace(data, "&amp;") ''// more processing return data End Function ``` Note that I need to use the keyword `Static`, rather than `Shared`, which is the normal way to express this in VB.Net. How can I do this in C#? I can't find its equivalent.
Ha! In posting the question, I found the answer! Rather than googling for C# I should have been looking for details on how VB.Net implements it, and typing up the question made that apparent to me. After applying that insight, I found this: <http://weblogs.asp.net/psteele/articles/7717.aspx> That article explains that it's not really supported by the CLR, and the VB compiler creates a static (shared) variable "under the hood" in the method's class. To do the same in C#, I have to create the variable myself. More than that, it uses the `Monitor` class to make sure the static member is thread-safe as well. Nice. As a side note: I'd expect to see this in C# sometime soon. The general tactic I've observed from MS is that it doesn't like VB.Net and C# to get too far apart feature-wise. If one language has a feature not supported by the other it tends to become a priority for the language team for the next version.
157,599
<p>I am working on converting a CVS repository that has the following symbols (among others):</p> <p><code>tcm-6.1.0-branch</code> -- a branch<br> <code>tcm-6.1.0</code> -- a tag</p> <p>Using the standard transformations cvs2svn identifies them properly. However, I'd like to do some clean up during the conversion. Specifically I'd like to drop the redundant '-branch' portion of the branch symbol, since it will be in the 'branches' dir in svn. I added the following to the symbol_transforms of the project:</p> <pre><code>RegexpSymbolTransform(r'(.*)-branch', r'\1') </code></pre> <p>Now I end up with " ERROR: Multiple definitions of the symbol 'tcm-6.1.0' in ..." for every file because <code>tcm-6.1.0</code> is both a branch and a tag. I have several CVS symbol pairs that result in this problem.</p> <p>It seems to me that since the source symbols are different and the destination directories are different this operation should be possible. Is there something I'm missing or is this simply a shortcoming of cvs2svn?</p> <p>How can I rename these symbols such that they remain separate and result in a branch and a tag with the same name?</p> <p>--</p> <p>If there is no work around I will try to exclude the problem symbols from the conversion rules and move them by hand afterwards, though I'd rather do it at conversion time.</p>
[ { "answer_id": 157626, "author": "ctrlShiftBryan", "author_id": 6161, "author_profile": "https://Stackoverflow.com/users/6161", "pm_score": 2, "selected": false, "text": "<p>What about emailing the report to the user. All the asp page should do is send the request to generate the report and return a message that the report will be emailed after is has finished running.</p>\n" }, { "answer_id": 157634, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 2, "selected": false, "text": "<p>I would consider making this report somehow a little bit more offline from the processing point of view.</p>\n\n<p>Like creating a queue to put report requests into, process the reports from there and after finish, it can send a message to the user.</p>\n\n<p>Maybe I would even create a separate Windows Service for the queue handling.</p>\n\n<p><strong>Update:</strong> sending to the user can be email or they can have a 'reports' page, where they can check their reports' status and download them if they are ready.</p>\n" }, { "answer_id": 157640, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 2, "selected": false, "text": "<p>Your users may not accept this approach, but:</p>\n\n<p>When they request a report (by clicking a button or a link or whatever), you could start the report generation process on a separate thread, and re-direct the user to a page that says \"thank you, your report will be emailed to you in a few minutes\".</p>\n\n<p>When the thread is done generating the report, you could email the PDF directly (probably won't work because of size), or save the report on the server and email a link to the user.</p>\n\n<p>Alternatively, you could go into IIS and raise the timeout to > 3 minutes.</p>\n" }, { "answer_id": 157641, "author": "user7375", "author_id": 7375, "author_profile": "https://Stackoverflow.com/users/7375", "pm_score": 4, "selected": true, "text": "<p>Using the filesystem here is probably a good bet. Have a request that immediately returns a url to the report pdf location. Your server can then either kick off an external process or send a request to itself to perform the reporting. The client can poll the server (using http HEAD) for the PDF at the supplied url. If you make the filename of the PDF derive from the report parameters, either by using a hash or directly putting the parameters into the name you will get instant server side caching too.</p>\n" }, { "answer_id": 157721, "author": "matdumsa", "author_id": 1775, "author_profile": "https://Stackoverflow.com/users/1775", "pm_score": 2, "selected": false, "text": "<p>Here is some of the things I would do if I would be presented this problem:</p>\n\n<p>1- Stop those timeout! They are a total waste of resources. (bring up the timeout value of asp pages)</p>\n\n<p>2- Centralize all the db access in one single point, then gather stats about what reports ran when by whom and how much time it took. Investigate why it takes so long, is it because of report complexity? data range? server load? (you could actually all write that on a .csv file on the server and import this file periodically in the sql server to analyze later).</p>\n\n<p>Eventually, it's going to be easier for you to \"cache\" reports if you go through this single access point (example, same query same date will return same PDF previously generated)</p>\n\n<p>3- I know this really wasn't the question but have you tried diving into those queries to see why they are so long to run? Query tuning maybe?</p>\n\n<p>4- Email/SMS/on screen message when report is ready seems great... if your user generally send a batch of report to be generated maybe a little dashboard indicating progression of \"their\" queue could be built in the app. A little ajax control would periodically refresh the status..\n Hint: If you used that central db access and you have sufficient information about what runs when why and how-long you will eventually be able to roughly estimates the time it will take for a report to run.</p>\n\n<p>If the response time is mission critical, should certain users be limited in the data range (date range for example) during some hours of the day?</p>\n\n<p>Good luck and please post more details about your scenario if you want to get more accurate hints...</p>\n" }, { "answer_id": 157920, "author": "AlexCuse", "author_id": 794, "author_profile": "https://Stackoverflow.com/users/794", "pm_score": 2, "selected": false, "text": "<p>Query tuning is probably your best place to start. Though I don't know you are generating the report, that step shouldn't really take all that long. A poorly performing query on the other hand could absolutely kill your performance. </p>\n\n<p>Depending on what you find in looking at the query, you may need to add some indexes, or possibly even set up a table to store the information for your report in a denormalized way, to make it available faster. This denormalized table could then be refreshed (through a SQL Server Job) every hour, or with whatever frequency your requirements dictate (within reason).</p>\n\n<p>If its' a relatively static report, without varying user input parameters, then caching the report run earlier in the day would be a good idea as well, but its' hard to say any more about this without knowing your situation. </p>\n\n<p>For a problem like this you really need to start at the database unless you have reason to suspect your report generating code of being the culprit. There are various band-aids you could use that might help for a while, but if your db is the root cause then those solutions will not scale well, and you'll likely run into similar problems (or worse) some time in the future.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4356/" ]
I am working on converting a CVS repository that has the following symbols (among others): `tcm-6.1.0-branch` -- a branch `tcm-6.1.0` -- a tag Using the standard transformations cvs2svn identifies them properly. However, I'd like to do some clean up during the conversion. Specifically I'd like to drop the redundant '-branch' portion of the branch symbol, since it will be in the 'branches' dir in svn. I added the following to the symbol\_transforms of the project: ``` RegexpSymbolTransform(r'(.*)-branch', r'\1') ``` Now I end up with " ERROR: Multiple definitions of the symbol 'tcm-6.1.0' in ..." for every file because `tcm-6.1.0` is both a branch and a tag. I have several CVS symbol pairs that result in this problem. It seems to me that since the source symbols are different and the destination directories are different this operation should be possible. Is there something I'm missing or is this simply a shortcoming of cvs2svn? How can I rename these symbols such that they remain separate and result in a branch and a tag with the same name? -- If there is no work around I will try to exclude the problem symbols from the conversion rules and move them by hand afterwards, though I'd rather do it at conversion time.
Using the filesystem here is probably a good bet. Have a request that immediately returns a url to the report pdf location. Your server can then either kick off an external process or send a request to itself to perform the reporting. The client can poll the server (using http HEAD) for the PDF at the supplied url. If you make the filename of the PDF derive from the report parameters, either by using a hash or directly putting the parameters into the name you will get instant server side caching too.
157,628
<p>I have a helper method has been created which allows a MovieClip-based class in code and have the constructor called. Unfortunately the solution is not complete because the MovieClip callback <b>onLoad()</b> is never called. </p> <p>(Link to the <a href="http://www.flashdevelop.org/community/viewtopic.php?f=13&amp;t=458" rel="nofollow noreferrer">Flashdevelop thread</a> which created the method .)</p> <p>How can the following function be modified so both the <b>constructor</b> and <b>onLoad()</b> is properly called.</p> <pre><code> //------------------------------------------------------------------------ // - Helper to create a strongly typed class that subclasses MovieClip. // - You do not use "new" when calling as it is done internally. // - The syntax requires the caller to cast to the specific type since // the return type is an object. (See example below). // // classRef, Class to create // id, Instance name // ..., (optional) Arguments to pass to MovieClip constructor // RETURNS Reference to the created object // // e.g., var f:Foo = Foo( newClassMC(Foo, "foo1") ); // public function newClassMC( classRef:Function, id:String ):Object { var mc:MovieClip = this.createEmptyMovieClip(id, this.getNextHighestDepth()); mc.__proto__ = classRef.prototype; if (arguments.length &gt; 2) { // Duplicate only the arguments to be passed to the constructor of // the movie clip we are constructing. var a:Array = new Array(arguments.length - 2); for (var i:Number = 2; i &lt; arguments.length; i++) a[Number(i) - 2] = arguments[Number(i)]; classRef.apply(mc, a); } else { classRef.apply(mc); } return mc; } </code></pre> <p>An example of a class that I may want to create:</p> <pre><code>class Foo extends MovieClip </code></pre> <p>And some examples of how I would currently create the class in code:</p> <pre><code>// The way I most commonly create one: var f:Foo = Foo( newClassMC(Foo, "foo1") ); // Another example... var obj:Object = newClassMC(Foo, "foo2") ); var myFoo:Foo = Foo( obj ); </code></pre>
[ { "answer_id": 164928, "author": "Luke", "author_id": 21406, "author_profile": "https://Stackoverflow.com/users/21406", "pm_score": 2, "selected": false, "text": "<p>Do I understand correctly that you want to create an instance of an empty movie clip with class behavior attached and without having to define an empty clip symbol in the library?</p>\n\n<p>If that's the case you need to use the packages trick. This is my base class (called View) that I've been using over the years and on hundreds of projects:</p>\n\n<pre><code>import mx.events.EventDispatcher;\n\nclass com.tequila.common.View extends MovieClip\n{\n private static var _symbolClass : Function = View;\n private static var _symbolPackage : String = \"__Packages.com.tequila.common.View\";\n\n public var dispatchEvent : Function;\n public var addEventListener : Function;\n public var removeEventListener : Function;\n\n private function View()\n {\n super();\n\n EventDispatcher.initialize( this );\n\n onEnterFrame = __$_init;\n }\n\n private function onInitialize() : Void\n {\n // called on the first frame. Event dispatchers are\n // ready and initialized at this point.\n }\n\n private function __$_init() : Void\n {\n delete onEnterFrame;\n\n onInitialize();\n }\n\n private static function createInstance(symbolClass, parent : View, instance : String, depth : Number, init : Object) : MovieClip\n {\n if( symbolClass._symbolPackage.indexOf(\"__Packages\") &gt;= 0 )\n {\n Object.registerClass(symbolClass._symbolPackage, symbolClass);\n }\n\n if( depth == undefined )\n {\n depth = parent.getNextHighestDepth();\n }\n\n if( instance == undefined )\n {\n instance = \"__$_\" + depth;\n }\n\n return( parent.attachMovie(symbolClass._symbolPackage, instance, depth, init) );\n }\n\n public static function create(parent : View, instance : String, depth : Number, init : Object) : View\n {\n return( View( createInstance(_symbolClass, parent, instance, depth, init) ) );\n }\n}\n</code></pre>\n\n<p>So, all you have to do to use this class is to subclass it:</p>\n\n<pre><code>class Foo extends View\n{\n private static var _symbolClass : Function = Foo;\n private static var _symbolPackage : String = \"__Packages.Foo\";\n\n private function Foo()\n {\n // constructor private\n }\n\n private function onInitialize() : Void\n {\n // implement this to add listeners etc.\n }\n\n public static function create(parent : View, instance : String, depth : Number, init : Object) : Foo\n {\n return( Foo( createInstance(_symbolClass, parent, instance, depth, init) ) );\n }\n}\n</code></pre>\n\n<p>You can now create an instance of Foo like this;</p>\n\n<pre><code>var foo : Foo = Foo.create( this );\n</code></pre>\n\n<p>Assuming that 'this' is some type of MovieClip or View.</p>\n\n<p>If you need to use this with a library symbol then just leave out the __Packages prefix on the _symbolPackage member.</p>\n\n<p>Hope this helps...</p>\n" }, { "answer_id": 6170371, "author": "Lenka", "author_id": 775473, "author_profile": "https://Stackoverflow.com/users/775473", "pm_score": 2, "selected": false, "text": "<p>If you want to create an instance of the Foo class with additional parameters, you can extend the create method. In my implementation , I am creating Nodes with objectIds:</p>\n\n<pre><code>var node : Node = Node.create(1,_root );\n</code></pre>\n\n<p>The Node class looks like this:</p>\n\n<pre><code>class Node extends View {\n\nprivate static var _symbolClass : Function = Node;\nprivate static var _symbolPackage : String = \"Node\";\n\nprivate var objectId : Number;\n\n\nprivate function Node() {\n // constructor private\n trace(\"node created \");\n}\n\nprivate function onInitialize() : Void {\n //add listeners\n}\n\npublic static function create(id_:Number, parent : MovieClip, instance : String, depth : Number, init : Object) : Node {\n var node :Node = Node( createInstance(_symbolClass, parent, instance, depth, init) )\n node.setObjectId(id_);\n return(node);\n} \n\n//=========================== GETTERS / SETTERS\nfunction setObjectId(id_:Number) : Void {\n objectId = id_;\n}\nfunction getObjectId() : Number {\n return objectId;\n}}\n</code></pre>\n\n<p>Please note that the objectId is undefined in the private constructor Node() but defined in onInitialize().</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14747/" ]
I have a helper method has been created which allows a MovieClip-based class in code and have the constructor called. Unfortunately the solution is not complete because the MovieClip callback **onLoad()** is never called. (Link to the [Flashdevelop thread](http://www.flashdevelop.org/community/viewtopic.php?f=13&t=458) which created the method .) How can the following function be modified so both the **constructor** and **onLoad()** is properly called. ``` //------------------------------------------------------------------------ // - Helper to create a strongly typed class that subclasses MovieClip. // - You do not use "new" when calling as it is done internally. // - The syntax requires the caller to cast to the specific type since // the return type is an object. (See example below). // // classRef, Class to create // id, Instance name // ..., (optional) Arguments to pass to MovieClip constructor // RETURNS Reference to the created object // // e.g., var f:Foo = Foo( newClassMC(Foo, "foo1") ); // public function newClassMC( classRef:Function, id:String ):Object { var mc:MovieClip = this.createEmptyMovieClip(id, this.getNextHighestDepth()); mc.__proto__ = classRef.prototype; if (arguments.length > 2) { // Duplicate only the arguments to be passed to the constructor of // the movie clip we are constructing. var a:Array = new Array(arguments.length - 2); for (var i:Number = 2; i < arguments.length; i++) a[Number(i) - 2] = arguments[Number(i)]; classRef.apply(mc, a); } else { classRef.apply(mc); } return mc; } ``` An example of a class that I may want to create: ``` class Foo extends MovieClip ``` And some examples of how I would currently create the class in code: ``` // The way I most commonly create one: var f:Foo = Foo( newClassMC(Foo, "foo1") ); // Another example... var obj:Object = newClassMC(Foo, "foo2") ); var myFoo:Foo = Foo( obj ); ```
Do I understand correctly that you want to create an instance of an empty movie clip with class behavior attached and without having to define an empty clip symbol in the library? If that's the case you need to use the packages trick. This is my base class (called View) that I've been using over the years and on hundreds of projects: ``` import mx.events.EventDispatcher; class com.tequila.common.View extends MovieClip { private static var _symbolClass : Function = View; private static var _symbolPackage : String = "__Packages.com.tequila.common.View"; public var dispatchEvent : Function; public var addEventListener : Function; public var removeEventListener : Function; private function View() { super(); EventDispatcher.initialize( this ); onEnterFrame = __$_init; } private function onInitialize() : Void { // called on the first frame. Event dispatchers are // ready and initialized at this point. } private function __$_init() : Void { delete onEnterFrame; onInitialize(); } private static function createInstance(symbolClass, parent : View, instance : String, depth : Number, init : Object) : MovieClip { if( symbolClass._symbolPackage.indexOf("__Packages") >= 0 ) { Object.registerClass(symbolClass._symbolPackage, symbolClass); } if( depth == undefined ) { depth = parent.getNextHighestDepth(); } if( instance == undefined ) { instance = "__$_" + depth; } return( parent.attachMovie(symbolClass._symbolPackage, instance, depth, init) ); } public static function create(parent : View, instance : String, depth : Number, init : Object) : View { return( View( createInstance(_symbolClass, parent, instance, depth, init) ) ); } } ``` So, all you have to do to use this class is to subclass it: ``` class Foo extends View { private static var _symbolClass : Function = Foo; private static var _symbolPackage : String = "__Packages.Foo"; private function Foo() { // constructor private } private function onInitialize() : Void { // implement this to add listeners etc. } public static function create(parent : View, instance : String, depth : Number, init : Object) : Foo { return( Foo( createInstance(_symbolClass, parent, instance, depth, init) ) ); } } ``` You can now create an instance of Foo like this; ``` var foo : Foo = Foo.create( this ); ``` Assuming that 'this' is some type of MovieClip or View. If you need to use this with a library symbol then just leave out the \_\_Packages prefix on the \_symbolPackage member. Hope this helps...
157,629
<p>Hi im new to MVC and I've fished around with no luck on how to build MVC User Controls that have ViewData returned to them. I was hoping someone would post a step by step solution on how to approach this problem. If you could make your solution very detailed that would help out greatly.</p> <p>Sorry for being so discrete with my question, I would just like to clarify that what Im ultimatly trying to do is pass an id to a controller actionresult method and wanting to render it to a user control directly from the controller itself. Im unsure on how to begin with this approach and wondering if this is even possible. It will essentially in my mind look like this</p> <pre><code>public ActionResult RTest(int id){ RTestDataContext db = new RTestDataContext(); var table = db.GetTable&lt;tRTest&gt;(); var record = table.SingleOrDefault(m=&gt; m.id = id); return View("RTest", record); } </code></pre> <p>and in my User Control I would like to render the objects of that record and thats my issue.</p>
[ { "answer_id": 157743, "author": "stimms", "author_id": 361, "author_profile": "https://Stackoverflow.com/users/361", "pm_score": 0, "selected": false, "text": "<p>I am pretty sure view data is accessible inside user controls so long as you extend System.Web.Mvc.ViewUserControl and pass it in. I have a snippet of code:</p>\n\n<pre><code>&lt;%Html.RenderPartial(\"~/UserControls/CategoryChooser.ascx\", ViewData);%&gt;\n</code></pre>\n\n<p>and from within my CategoryChooser ViewData is accessible. </p>\n" }, { "answer_id": 157745, "author": "Ricky", "author_id": 653, "author_profile": "https://Stackoverflow.com/users/653", "pm_score": 4, "selected": true, "text": "<p>If I understand your question, you are trying to pass ViewData into the user control. A user control is essentially a partial view, so you would do this:</p>\n\n<pre><code>&lt;% Html.RenderPartial(\"someUserControl.ascx\", viewData); %&gt;\n</code></pre>\n\n<p>Now in your usercontrol, ViewData will be whatever you passed in...</p>\n" }, { "answer_id": 157758, "author": "Casper", "author_id": 18729, "author_profile": "https://Stackoverflow.com/users/18729", "pm_score": 0, "selected": false, "text": "<p>Not sure if I understand your problem completely, but here's my answer to \"How to add a User Control to your ASP.NET MVC Project\".</p>\n\n<p>In Visual Studio 2008, you can choose Add Item. In the categories at the left side, you can choose Visual C# > Web > MVC. There's an option MVC View User Control. Select it, choose a name, select the desired master page and you're good to go.</p>\n" }, { "answer_id": 157791, "author": "Brad8118", "author_id": 7617, "author_profile": "https://Stackoverflow.com/users/7617", "pm_score": 1, "selected": false, "text": "<p>OK here it goes --\nWe use Json data</p>\n\n<p>In the aspx page we have an ajax call that calls the controller. Look up the available option parameters for ajax calls.</p>\n\n<p>url: This calls the function in the class.(obviously) Our class name is JobController, function name is updateJob and it takes no parameters. The url drops the controllerPortion from the classname. For example to call the updateJob function the url would be '/Job/UpdateJob/'.</p>\n\n<pre><code>var data = {x:1, y:2};\n$.ajax({\ndata: data,\ncache: false,\nurl: '/ClassName/functionName/parameter',\ndataType: \"json\",\ntype: \"post\",\nsuccess: function(result) {\n//do something\n},\nerror: function(errorData) {\nalert(errorData.responseText);\n}\n}\n);\n</code></pre>\n\n<p>In the JobController Class:</p>\n\n<pre><code>public ActionResult UpdateJob(string id)\n{\n string x_Value_from_ajax = Request.Form[\"x\"];\n string y_Value_from_ajax = Request.Form[\"y\"];\n return Json(dataContextClass.UpdateJob(x_Value_from_ajax, y_Value_from_ajax));\n}\n</code></pre>\n\n<p>We have a Global.asax.cs page that maps the ajax calls.</p>\n\n<pre><code>public class GlobalApplication : System.Web.HttpApplication\n {\n public static void RegisterRoutes(RouteCollection routes)\n {\n routes.IgnoreRoute(\"{resource}.axd/{*pathInfo}\");\nroutes.MapRoute(\"Default\", // Route name\n \"{controller}/{action}/{id}\", // URL with parameters\n new { controller = \"EnterTime\", action = \"Index\", id = \"\" } // Parameter defaults (EnterTime is our default controller class, index is our default function and it takes no parameters.)\n );\n }\n}\n</code></pre>\n\n<p>I hope this gets you off to a good start.\nGood luck</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24130/" ]
Hi im new to MVC and I've fished around with no luck on how to build MVC User Controls that have ViewData returned to them. I was hoping someone would post a step by step solution on how to approach this problem. If you could make your solution very detailed that would help out greatly. Sorry for being so discrete with my question, I would just like to clarify that what Im ultimatly trying to do is pass an id to a controller actionresult method and wanting to render it to a user control directly from the controller itself. Im unsure on how to begin with this approach and wondering if this is even possible. It will essentially in my mind look like this ``` public ActionResult RTest(int id){ RTestDataContext db = new RTestDataContext(); var table = db.GetTable<tRTest>(); var record = table.SingleOrDefault(m=> m.id = id); return View("RTest", record); } ``` and in my User Control I would like to render the objects of that record and thats my issue.
If I understand your question, you are trying to pass ViewData into the user control. A user control is essentially a partial view, so you would do this: ``` <% Html.RenderPartial("someUserControl.ascx", viewData); %> ``` Now in your usercontrol, ViewData will be whatever you passed in...
157,646
<p>I was looking for a generic method in .Net to encode a string for use in an Xml element or attribute, and was surprised when I didn't immediately find one. So, before I go too much further, could I just be missing the built-in function? </p> <p>Assuming for a moment that it really doesn't exist, I'm putting together my own generic <code>EncodeForXml(string data)</code> method, and I'm thinking about the best way to do this. </p> <p>The data I'm using that prompted this whole thing could contain bad characters like &amp;, &lt;, &quot;, etc. It could also contains on occasion the properly escaped entities: &amp;amp;, &amp;lt;, and &amp;quot;, which means just using a CDATA section may not be the best idea. That seems kinda klunky anyay; I'd much rather end up with a nice string value that can be used directly in the xml.</p> <p>I've used a regular expression in the past to just catch bad ampersands, and I'm thinking of using it to catch them in this case as well as the first step, and then doing a simple replace for other characters. </p> <p>So, could this be optimized further without making it too complex, and is there anything I'm missing? :</p> <pre class="lang-vb prettyprint-override"><code>Function EncodeForXml(ByVal data As String) As String Static badAmpersand As new Regex("&amp;(?![a-zA-Z]{2,6};|#[0-9]{2,4};)") data = badAmpersand.Replace(data, "&amp;amp;") return data.Replace("&lt;", "&amp;lt;").Replace("""", "&amp;quot;").Replace("&gt;", "gt;") End Function </code></pre> <p><em>Sorry for all you C# -only folks-- I don't really care which language I use, but I wanted to make the Regex static and you can't do that in C# without declaring it outside the method, so this will be VB.Net</em></p> <p>Finally, we're still on .Net 2.0 where I work, but if someone could take the final product and turn it into an extension method for the string class, that'd be pretty cool too.</p> <p><strong>Update</strong> The first few responses indicate that .Net does indeed have built-in ways of doing this. But now that I've started, I kind of want to finish my EncodeForXml() method just for the fun of it, so I'm still looking for ideas for improvement. Notably: a more complete list of characters that should be encoded as entities (perhaps stored in a list/map), and something that gets better performance than doing a .Replace() on immutable strings in serial.</p>
[ { "answer_id": 157663, "author": "Kilhoffer", "author_id": 5469, "author_profile": "https://Stackoverflow.com/users/5469", "pm_score": 5, "selected": false, "text": "<p>In the past I have used HttpUtility.HtmlEncode to encode text for xml. It performs the same task, really. I haven't run into any issues with it yet, but that's not to say I won't in the future. As the name implies, it was made for HTML, not XML.</p>\n<p>You've probably already read it, but <a href=\"http://msdn.microsoft.com/en-us/library/wkc3acws(VS.71).aspx\" rel=\"nofollow noreferrer\">here is an article</a> on xml encoding and decoding.</p>\n<p>EDIT: Of course, if you use an xmlwriter or one of the new XElement classes, this encoding is done for you. In fact, you could just take the text, place it in a new XElement instance, then return the string (.tostring) version of the element. I've heard that <a href=\"http://msdn.microsoft.com/en-us/library/system.security.securityelement.escape(VS.80).aspx\" rel=\"nofollow noreferrer\">SecurityElement.Escape</a> will perform the same task as your utility method as well, but havent read much about it or used it.</p>\n<p>EDIT2: Disregard my comment about XElement, since you're still on 2.0</p>\n" }, { "answer_id": 157668, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 2, "selected": false, "text": "<p>If this is an ASP.NET app why not use Server.HtmlEncode() ?</p>\n" }, { "answer_id": 157669, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 3, "selected": true, "text": "<p>System.XML handles the encoding for you, so you don't need a method like this.</p>\n" }, { "answer_id": 157672, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 5, "selected": false, "text": "<p>SecurityElement.Escape</p>\n\n<p>documented <a href=\"https://msdn.microsoft.com/en-us/library/system.security.securityelement.escape(v=vs.110).aspx\" rel=\"noreferrer\">here</a></p>\n" }, { "answer_id": 157674, "author": "GSerg", "author_id": 11683, "author_profile": "https://Stackoverflow.com/users/11683", "pm_score": 3, "selected": false, "text": "<p><code>XmlTextWriter.WriteString()</code> does the escaping.</p>\n" }, { "answer_id": 421938, "author": "Dscoduc", "author_id": 51949, "author_profile": "https://Stackoverflow.com/users/51949", "pm_score": 2, "selected": false, "text": "<p>This might be the case where you could benefit from using the WriteCData method.</p>\n\n<pre><code>public override void WriteCData(string text)\n Member of System.Xml.XmlTextWriter\n\nSummary:\nWrites out a &lt;![CDATA[...]]&gt; block containing the specified text.\n\nParameters:\ntext: Text to place inside the CDATA block.\n</code></pre>\n\n<p>A simple example would look like the following:</p>\n\n<pre><code>writer.WriteStartElement(\"name\");\nwriter.WriteCData(\"&lt;unsafe characters&gt;\");\nwriter.WriteFullEndElement();\n</code></pre>\n\n<p>The result looks like:</p>\n\n<pre><code>&lt;name&gt;&lt;![CDATA[&lt;unsafe characters&gt;]]&gt;&lt;/name&gt;\n</code></pre>\n\n<p>When reading the node values the XMLReader automatically strips out the CData part of the innertext so you don't have to worry about it. The only catch is that you have to store the data as an innerText value to an XML node. In other words, you can't insert CData content into an attribute value.</p>\n" }, { "answer_id": 732135, "author": "Michael Kropat", "author_id": 27581, "author_profile": "https://Stackoverflow.com/users/27581", "pm_score": 6, "selected": false, "text": "<p>Depending on how much you know about the input, you may have to take into account that <a href=\"http://www.w3.org/TR/xml11/#charsets\" rel=\"noreferrer\">not all Unicode characters are valid XML characters</a>.</p>\n\n<p>Both <em>Server.HtmlEncode</em> and <em>System.Security.SecurityElement.Escape</em> seem to ignore illegal XML characters, while <em>System.XML.XmlWriter.WriteString</em> throws an <em>ArgumentException</em> when it encounters illegal characters (unless you disable that check in which case it ignores them). An overview of library functions is available <a href=\"http://weblogs.sqlteam.com/mladenp/archive/2008/10/21/Different-ways-how-to-escape-an-XML-string-in-C.aspx\" rel=\"noreferrer\">here</a>.</p>\n\n<p><strong>Edit 2011/8/14:</strong> seeing that at least a few people have consulted this answer in the last couple years, I decided to completely rewrite the original code, which had numerous issues, including <a href=\"https://stackoverflow.com/questions/1049947/should-utf-16-be-considered-harmful\">horribly mishandling UTF-16</a>.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\n/// &lt;summary&gt;\n/// Encodes data so that it can be safely embedded as text in XML documents.\n/// &lt;/summary&gt;\npublic class XmlTextEncoder : TextReader {\n public static string Encode(string s) {\n using (var stream = new StringReader(s))\n using (var encoder = new XmlTextEncoder(stream)) {\n return encoder.ReadToEnd();\n }\n }\n\n /// &lt;param name=\"source\"&gt;The data to be encoded in UTF-16 format.&lt;/param&gt;\n /// &lt;param name=\"filterIllegalChars\"&gt;It is illegal to encode certain\n /// characters in XML. If true, silently omit these characters from the\n /// output; if false, throw an error when encountered.&lt;/param&gt;\n public XmlTextEncoder(TextReader source, bool filterIllegalChars=true) {\n _source = source;\n _filterIllegalChars = filterIllegalChars;\n }\n\n readonly Queue&lt;char&gt; _buf = new Queue&lt;char&gt;();\n readonly bool _filterIllegalChars;\n readonly TextReader _source;\n\n public override int Peek() {\n PopulateBuffer();\n if (_buf.Count == 0) return -1;\n return _buf.Peek();\n }\n\n public override int Read() {\n PopulateBuffer();\n if (_buf.Count == 0) return -1;\n return _buf.Dequeue();\n }\n\n void PopulateBuffer() {\n const int endSentinel = -1;\n while (_buf.Count == 0 &amp;&amp; _source.Peek() != endSentinel) {\n // Strings in .NET are assumed to be UTF-16 encoded [1].\n var c = (char) _source.Read();\n if (Entities.ContainsKey(c)) {\n // Encode all entities defined in the XML spec [2].\n foreach (var i in Entities[c]) _buf.Enqueue(i);\n } else if (!(0x0 &lt;= c &amp;&amp; c &lt;= 0x8) &amp;&amp;\n !new[] { 0xB, 0xC }.Contains(c) &amp;&amp;\n !(0xE &lt;= c &amp;&amp; c &lt;= 0x1F) &amp;&amp;\n !(0x7F &lt;= c &amp;&amp; c &lt;= 0x84) &amp;&amp;\n !(0x86 &lt;= c &amp;&amp; c &lt;= 0x9F) &amp;&amp;\n !(0xD800 &lt;= c &amp;&amp; c &lt;= 0xDFFF) &amp;&amp;\n !new[] { 0xFFFE, 0xFFFF }.Contains(c)) {\n // Allow if the Unicode codepoint is legal in XML [3].\n _buf.Enqueue(c);\n } else if (char.IsHighSurrogate(c) &amp;&amp;\n _source.Peek() != endSentinel &amp;&amp;\n char.IsLowSurrogate((char) _source.Peek())) {\n // Allow well-formed surrogate pairs [1].\n _buf.Enqueue(c);\n _buf.Enqueue((char) _source.Read());\n } else if (!_filterIllegalChars) {\n // Note that we cannot encode illegal characters as entity\n // references due to the \"Legal Character\" constraint of\n // XML [4]. Nor are they allowed in CDATA sections [5].\n throw new ArgumentException(\n String.Format(\"Illegal character: '{0:X}'\", (int) c));\n }\n }\n }\n\n static readonly Dictionary&lt;char,string&gt; Entities =\n new Dictionary&lt;char,string&gt; {\n { '\"', \"&amp;quot;\" }, { '&amp;', \"&amp;amp;\"}, { '\\'', \"&amp;apos;\" },\n { '&lt;', \"&amp;lt;\" }, { '&gt;', \"&amp;gt;\" },\n };\n\n // References:\n // [1] http://en.wikipedia.org/wiki/UTF-16/UCS-2\n // [2] http://www.w3.org/TR/xml11/#sec-predefined-ent\n // [3] http://www.w3.org/TR/xml11/#charsets\n // [4] http://www.w3.org/TR/xml11/#sec-references\n // [5] http://www.w3.org/TR/xml11/#sec-cdata-sect\n}\n</code></pre>\n\n<p>Unit tests and full code can be found <a href=\"https://github.com/mkropat/.NET-Snippets/blob/master/XmlTextEncoder.cs\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 1351597, "author": "Luke Quinane", "author_id": 18437, "author_profile": "https://Stackoverflow.com/users/18437", "pm_score": 4, "selected": false, "text": "<p>Microsoft's <strike><a href=\"http://www.codeplex.com/AntiXSS\" rel=\"nofollow noreferrer\">AntiXss library</a></strike> <a href=\"https://msdn.microsoft.com/en-us/library/system.web.security.antixss.antixssencoder%28v=vs.110%29.aspx\" rel=\"nofollow noreferrer\">AntiXssEncoder Class</a> in System.Web.dll has methods for this:</p>\n\n<pre><code>AntiXss.XmlEncode(string s)\nAntiXss.XmlAttributeEncode(string s)\n</code></pre>\n\n<p>it has HTML as well:</p>\n\n<pre><code>AntiXss.HtmlEncode(string s)\nAntiXss.HtmlAttributeEncode(string s)\n</code></pre>\n" }, { "answer_id": 8178580, "author": "nepaluz", "author_id": 1053242, "author_profile": "https://Stackoverflow.com/users/1053242", "pm_score": 0, "selected": false, "text": "<p>Brilliant! That's all I can say.</p>\n\n<p>Here is a VB variant of the updated code (not in a class, just a function) that will clean up and also sanitize the xml</p>\n\n<pre><code>Function cXML(ByVal _buf As String) As String\n Dim textOut As New StringBuilder\n Dim c As Char\n If _buf.Trim Is Nothing OrElse _buf = String.Empty Then Return String.Empty\n For i As Integer = 0 To _buf.Length - 1\n c = _buf(i)\n If Entities.ContainsKey(c) Then\n textOut.Append(Entities.Item(c))\n ElseIf (AscW(c) = &amp;H9 OrElse AscW(c) = &amp;HA OrElse AscW(c) = &amp;HD) OrElse ((AscW(c) &gt;= &amp;H20) AndAlso (AscW(c) &lt;= &amp;HD7FF)) _\n OrElse ((AscW(c) &gt;= &amp;HE000) AndAlso (AscW(c) &lt;= &amp;HFFFD)) OrElse ((AscW(c) &gt;= &amp;H10000) AndAlso (AscW(c) &lt;= &amp;H10FFFF)) Then\n textOut.Append(c)\n End If\n Next\n Return textOut.ToString\n\nEnd Function\n\nShared ReadOnly Entities As New Dictionary(Of Char, String)() From {{\"\"\"\"c, \"&amp;quot;\"}, {\"&amp;\"c, \"&amp;amp;\"}, {\"'\"c, \"&amp;apos;\"}, {\"&lt;\"c, \"&amp;lt;\"}, {\"&gt;\"c, \"&amp;gt;\"}}\n</code></pre>\n" }, { "answer_id": 9387943, "author": "Ronnie Overby", "author_id": 64334, "author_profile": "https://Stackoverflow.com/users/64334", "pm_score": 4, "selected": false, "text": "<p><strike>In .net 3.5+</p>\n\n<pre><code>new XText(\"I &lt;want&gt; to &amp; encode this for XML\").ToString();\n</code></pre>\n\n<p>Gives you:</p>\n\n<p><code>I &amp;lt;want&amp;gt; to &amp;amp; encode this for XML</code>\n</strike></p>\n\n<p>Turns out that this method doesn't encode some things that it should (like quotes).</p>\n\n<p><code>SecurityElement.Escape</code> (<a href=\"https://stackoverflow.com/a/157672/64334\">workmad3's answer</a>) seems to do a better job with this and it's included in earlier versions of .net.</p>\n\n<p>If you don't mind 3rd party code and want to ensure no illegal characters make it into your XML, I would recommend <a href=\"https://stackoverflow.com/a/732135/64334\">Michael Kropat's answer</a>.</p>\n" }, { "answer_id": 29821556, "author": "Cosmin", "author_id": 626533, "author_profile": "https://Stackoverflow.com/users/626533", "pm_score": 0, "selected": false, "text": "<p>You can use the built-in class <a href=\"https://msdn.microsoft.com/en-us/library/system.xml.linq.xattribute%28v=vs.110%29.aspx\" rel=\"nofollow\">XAttribute</a>, which handles the encoding automatically:</p>\n\n<pre><code>using System.Xml.Linq;\n\nXDocument doc = new XDocument();\n\nList&lt;XAttribute&gt; attributes = new List&lt;XAttribute&gt;();\nattributes.Add(new XAttribute(\"key1\", \"val1&amp;val11\"));\nattributes.Add(new XAttribute(\"key2\", \"val2\"));\n\nXElement elem = new XElement(\"test\", attributes.ToArray());\n\ndoc.Add(elem);\n\nstring xmlStr = doc.ToString();\n</code></pre>\n" }, { "answer_id": 43114385, "author": "Phillip", "author_id": 621594, "author_profile": "https://Stackoverflow.com/users/621594", "pm_score": 0, "selected": false, "text": "<p>Here is a single line solution using the XElements. I use it in a very small tool. I don't need it a second time so I keep it this way. (Its dirdy doug)</p>\n\n<pre><code>StrVal = (&lt;x a=&lt;%= StrVal %&gt;&gt;END&lt;/x&gt;).ToString().Replace(\"&lt;x a=\"\"\", \"\").Replace(\"&gt;END&lt;/x&gt;\", \"\")\n</code></pre>\n\n<p>Oh and it only works in VB not in C#</p>\n" }, { "answer_id": 49367938, "author": "Granger", "author_id": 530545, "author_profile": "https://Stackoverflow.com/users/530545", "pm_score": 2, "selected": false, "text": "<p>If you're serious about handling <strong>all</strong> of the invalid characters (not just the few \"html\" ones), and you have access to <code>System.Xml</code>, here's the simplest way to do proper Xml encoding of <em>value data</em>:</p>\n\n<pre><code>string theTextToEscape = \"Something \\x1d else \\x1D &lt;script&gt;alert('123');&lt;/script&gt;\";\nvar x = new XmlDocument();\nx.LoadXml(\"&lt;r/&gt;\"); // simple, empty root element\nx.DocumentElement.InnerText = theTextToEscape; // put in raw string\nstring escapedText = x.DocumentElement.InnerXml; // Returns: Something &amp;#x1D; else &amp;#x1D; &amp;lt;script&amp;gt;alert('123');&amp;lt;/script&amp;gt;\n\n// Repeat the last 2 lines to escape additional strings.\n</code></pre>\n\n<p>It's important to know that <code>XmlConvert.EncodeName()</code> is not appropriate, because that's for entity/tag names, not values. Using that would be like Url-encoding when you needed to Html-encode.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ]
I was looking for a generic method in .Net to encode a string for use in an Xml element or attribute, and was surprised when I didn't immediately find one. So, before I go too much further, could I just be missing the built-in function? Assuming for a moment that it really doesn't exist, I'm putting together my own generic `EncodeForXml(string data)` method, and I'm thinking about the best way to do this. The data I'm using that prompted this whole thing could contain bad characters like &, <, ", etc. It could also contains on occasion the properly escaped entities: &amp;, &lt;, and &quot;, which means just using a CDATA section may not be the best idea. That seems kinda klunky anyay; I'd much rather end up with a nice string value that can be used directly in the xml. I've used a regular expression in the past to just catch bad ampersands, and I'm thinking of using it to catch them in this case as well as the first step, and then doing a simple replace for other characters. So, could this be optimized further without making it too complex, and is there anything I'm missing? : ```vb Function EncodeForXml(ByVal data As String) As String Static badAmpersand As new Regex("&(?![a-zA-Z]{2,6};|#[0-9]{2,4};)") data = badAmpersand.Replace(data, "&amp;") return data.Replace("<", "&lt;").Replace("""", "&quot;").Replace(">", "gt;") End Function ``` *Sorry for all you C# -only folks-- I don't really care which language I use, but I wanted to make the Regex static and you can't do that in C# without declaring it outside the method, so this will be VB.Net* Finally, we're still on .Net 2.0 where I work, but if someone could take the final product and turn it into an extension method for the string class, that'd be pretty cool too. **Update** The first few responses indicate that .Net does indeed have built-in ways of doing this. But now that I've started, I kind of want to finish my EncodeForXml() method just for the fun of it, so I'm still looking for ideas for improvement. Notably: a more complete list of characters that should be encoded as entities (perhaps stored in a list/map), and something that gets better performance than doing a .Replace() on immutable strings in serial.
System.XML handles the encoding for you, so you don't need a method like this.
157,685
<p>I'm trying to change the background color of a single subplot in a MATLAB figure.</p> <p>It's clearly feasible since the UI allows it, but I cannot find the function to automate it.</p> <p>I've looked into <code>whitebg</code>, but it changes the color scheme of the whole figure, not just the current subplot. </p> <p>(I'm using MATLAB Version 6.1 by the way)</p>
[ { "answer_id": 157719, "author": "Douglas F Shearer", "author_id": 13831, "author_profile": "https://Stackoverflow.com/users/13831", "pm_score": 2, "selected": false, "text": "<p>I've not used Matlab in several years, but I think it might well be the whitebg method called after the subplot declaration, similar to the way in which you would set a title.</p>\n\n<pre><code>subplot(3, 2, 4), hist(rand(50)), whitebg('y');\n</code></pre>\n" }, { "answer_id": 157725, "author": "Doug Trojan", "author_id": 6982, "author_profile": "https://Stackoverflow.com/users/6982", "pm_score": 5, "selected": true, "text": "<p>You can use the set command.</p>\n\n<pre><code>set(subplot(2,2,1),'Color','Red')\n</code></pre>\n\n<p>That will give you a red background in the subplot location 2,2,1.</p>\n" }, { "answer_id": 1230869, "author": "gnovice", "author_id": 52738, "author_profile": "https://Stackoverflow.com/users/52738", "pm_score": 2, "selected": false, "text": "<p>I know you mentioned that you are using MATLAB 6.1, but it bears mentioning that in the newer versions of MATLAB you can specify additional property-value pair arguments in the initial call to <a href=\"http://www.mathworks.com/access/helpdesk/help/techdoc/ref/subplot.html\" rel=\"nofollow noreferrer\">SUBPLOT</a>, allowing for a more compact syntax. The following creates an axes with a red background in the top left corner of a 2-by-2 layout:</p>\n\n<pre><code>subplot(2,2,1,'Color','r');\n</code></pre>\n\n<p>I'm not certain in which version of MATLAB this syntax was introduced, since the <a href=\"http://www.mathworks.com/access/helpdesk/help/techdoc/rn/rn_intro.html\" rel=\"nofollow noreferrer\">release notes going back to Version 7 (R14)</a> don't seem to mention it.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8027/" ]
I'm trying to change the background color of a single subplot in a MATLAB figure. It's clearly feasible since the UI allows it, but I cannot find the function to automate it. I've looked into `whitebg`, but it changes the color scheme of the whole figure, not just the current subplot. (I'm using MATLAB Version 6.1 by the way)
You can use the set command. ``` set(subplot(2,2,1),'Color','Red') ``` That will give you a red background in the subplot location 2,2,1.
157,689
<p>How do I use the ofstream to write text to the end of a file without erasing its content inside?</p>
[ { "answer_id": 157698, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "<p>You can pass the flag <code>ios::app</code> when opening the file:</p>\n\n<pre><code>ofstream ofs(\"filename\", ios::app);\n</code></pre>\n" }, { "answer_id": 157699, "author": "KernelM", "author_id": 22328, "author_profile": "https://Stackoverflow.com/users/22328", "pm_score": 0, "selected": false, "text": "<p>Use ios::app as the file mode.</p>\n" }, { "answer_id": 157707, "author": "Ed Haber", "author_id": 2926, "author_profile": "https://Stackoverflow.com/users/2926", "pm_score": 1, "selected": false, "text": "<p>You want to append to the file. Use ios::app as the file mode when creating the ofstream.</p>\n\n<p>Appending will automatically seek to the end of the file.</p>\n" }, { "answer_id": 1488730, "author": "Nona Urbiz", "author_id": 135056, "author_profile": "https://Stackoverflow.com/users/135056", "pm_score": 0, "selected": false, "text": "<p>The <code>seekp()</code> function allows you to arbitrarily set the position of the file pointer, for open files.</p>\n" }, { "answer_id": 38056872, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>As people have mentioned above, opening the file in the following manner will do:</p>\n\n<p><code>ofstream out(\"path_to_file\",ios::app);</code></p>\n\n<p>It will do the trick, if you want to append data to the file by default.</p>\n\n<p>But, if you want to go to the end of the file, in the middle of the program, with the default mode not being <code>ios::app</code>, you can use the following statement:</p>\n\n<p><code>out.seekp(0,ios::end)</code>\nThis will place the put pointer 0 bytes from the end of file. <a href=\"http://www.cplusplus.com/reference/ostream/ostream/seekp\" rel=\"nofollow\">http://www.cplusplus.com/reference/ostream/ostream/seekp</a></p>\n\n<p>Make sure you use the correct seekp(), as there are 2 overloads of seekp(). The one with 2 parameters is favored in this situation.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do I use the ofstream to write text to the end of a file without erasing its content inside?
You can pass the flag `ios::app` when opening the file: ``` ofstream ofs("filename", ios::app); ```
157,705
<p>I've got some XML, for example purposes it looks like this:</p> <pre><code>&lt;root&gt; &lt;field1&gt;test&lt;/field1&gt; &lt;f2&gt;t2&lt;/f2&gt; &lt;f2&gt;t3&lt;/f2&gt; &lt;/root&gt; </code></pre> <p>I want to transform it with XSLT, but I want to suppress the second f2 element in the output - how do I check inside my template to see if the f2 element already exists in the output when the second f2 element in the source is processed? My XSLT looks something like this at present:</p> <pre><code>&lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt; &lt;xsl:output method="xml" indent="no" omit-xml-declaration="yes" standalone="no" /&gt; &lt;xsl:template match="/"&gt; &lt;xsl:for-each select="./root"&gt; &lt;output&gt; &lt;xsl:apply-templates /&gt; &lt;/output&gt; &lt;/xsl:for-each&gt; &lt;/xsl:template&gt; &lt;xsl:template match="*" &gt; &lt;xsl:element name="{name(.)}"&gt; &lt;xsl:value-of select="." /&gt; &lt;/xsl:element&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p>I need to do some sort of check around the xsl:element in the template I think, but I'm not sure how to interrogate the output document to see if the element is already present.</p> <p>Edit: Forgot the pre tags, code should be visible now!</p>
[ { "answer_id": 158125, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 4, "selected": true, "text": "<p>It depends how system wide you want to be.</p>\n\n<p>i.e. Are you only concerned with elements that are children of the same parent, or all elements at the same level ('cousins' if you like) or elements anywhere in the document...</p>\n\n<p>In the first situation you could check the preceding-sibling axis to see if any other elements exist with the same name.</p>\n\n<pre><code>&lt;xsl:if test=\"count(preceding-sibling::node()[name()=name(current())])=0\"&gt;\n ... do stuff in here.\n&lt;/xsl:if&gt;\n</code></pre>\n" }, { "answer_id": 158267, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 1, "selected": false, "text": "<p>To only check (and warn you of a duplicate), you may find an <a href=\"http://www.biglist.com/lists/lists.mulberrytech.com/xsl-list/archives/200807/msg00444.html\" rel=\"nofollow noreferrer\">example here</a></p>\n\n<p>Something along the lines of:</p>\n\n<pre><code>&lt;xsl:for-each-group select=\"collection(...)//@id\" group-by=\".\"&gt;\n &lt;xsl:if test=\"count(current-group()) ne 1\"&gt;\n &lt;xsl:message&gt;Id value &lt;xsl:value-of select=\"current-grouping-key()\"/&gt; is \n duplicated in files\n &lt;xsl:value-of select=\"current-group()/document-uri(/)\" separator=\" and\n \"/&gt;&lt;/xsl:message&gt;\n &lt;/xsl:if&gt;\n &lt;/xsl:for-each-group&gt;\n</code></pre>\n\n<p>To be modified to select all nodes within 'root' element.</p>\n\n<p>As to remove the duplicate lines, you have another <a href=\"http://graflex.org/klotz/weblog/2005/02/xslt-duplicate-elimination.html\" rel=\"nofollow noreferrer\">example here</a></p>\n\n<p>That would look like:</p>\n\n<pre><code>&lt;xsl:stylesheet&gt;\n &lt;xsl:key name=\"xyz\" match=\"record[x/y/z]\" use=\"x/y/z\" /&gt;\n &lt;xsl:variable name=\"noxyzdups\" select=\"/path/to/record[generate-id(.) = generate-id(key('xyz', x/y/z))]\" /&gt;\n...\n &lt;xsl:template ... &gt;\n &lt;xsl:copy-of \"exslt:node-set($noxyzdups)\" /&gt;\n &lt;/xsl:template&gt;\n&lt;/xsl:stylesheet&gt;\n</code></pre>\n\n<p>x/y/z is the xpath expression that you want made unique. It can be concat(x,'-',@y,'-',z) or whatever you want. </p>\n\n<p>Now I am not sure those two examples can easily be adapted to your case, but I just wanted to point out those two sources, in case it helps.</p>\n" }, { "answer_id": 160383, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 1, "selected": false, "text": "<p>It's not possible to interrogate the output of your transform. It's also not possible to track the current state of your transform (i.e. keep track of what nodes you've emitted in a variable). Fundamentally, that's not how XSLT works. One of the costs of a side-effect-free programming environment is that you can't do things that have side effects. Oh well.</p>\n\n<p>In your case, one way of accomplishing this would be to build a variable that contained a list of all of the source elements that could be transformed into the output element that you want to emit only once. Then check every node you're transforming against this list. If it's not in the list, emit it. If it's the first item in the list, emit it. Otherwise, don't.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22073/" ]
I've got some XML, for example purposes it looks like this: ``` <root> <field1>test</field1> <f2>t2</f2> <f2>t3</f2> </root> ``` I want to transform it with XSLT, but I want to suppress the second f2 element in the output - how do I check inside my template to see if the f2 element already exists in the output when the second f2 element in the source is processed? My XSLT looks something like this at present: ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="no" omit-xml-declaration="yes" standalone="no" /> <xsl:template match="/"> <xsl:for-each select="./root"> <output> <xsl:apply-templates /> </output> </xsl:for-each> </xsl:template> <xsl:template match="*" > <xsl:element name="{name(.)}"> <xsl:value-of select="." /> </xsl:element> </xsl:template> </xsl:stylesheet> ``` I need to do some sort of check around the xsl:element in the template I think, but I'm not sure how to interrogate the output document to see if the element is already present. Edit: Forgot the pre tags, code should be visible now!
It depends how system wide you want to be. i.e. Are you only concerned with elements that are children of the same parent, or all elements at the same level ('cousins' if you like) or elements anywhere in the document... In the first situation you could check the preceding-sibling axis to see if any other elements exist with the same name. ``` <xsl:if test="count(preceding-sibling::node()[name()=name(current())])=0"> ... do stuff in here. </xsl:if> ```
157,747
<p>I want to use VBScript to catch errors and log them (ie on error "log something") then resume the next line of the script.</p> <p>For example,</p> <pre> On Error Resume Next 'Do Step 1 'Do Step 2 'Do Step 3 </pre> <p>When an error occurs on step 1, I want it to log that error (or perform other custom functions with it) then resume at step 2. Is this possible? and how can I implement it?</p> <p>EDIT: Can I do something like this?</p> <pre> On Error Resume myErrCatch 'Do step 1 'Do step 2 'Do step 3 myErrCatch: 'log error Resume Next </pre>
[ { "answer_id": 157785, "author": "Dylan Beattie", "author_id": 5017, "author_profile": "https://Stackoverflow.com/users/5017", "pm_score": 8, "selected": true, "text": "<p>VBScript has no notion of throwing or catching exceptions, but the runtime provides a global Err object that contains the results of the last operation performed. You have to explicitly check whether the Err.Number property is non-zero after each operation.</p>\n\n<pre><code>On Error Resume Next\n\nDoStep1\n\nIf Err.Number &lt;&gt; 0 Then\n WScript.Echo \"Error in DoStep1: \" &amp; Err.Description\n Err.Clear\nEnd If\n\nDoStep2\n\nIf Err.Number &lt;&gt; 0 Then\n WScript.Echo \"Error in DoStop2:\" &amp; Err.Description\n Err.Clear\nEnd If\n\n'If you no longer want to continue following an error after that block's completed,\n'call this.\nOn Error Goto 0\n</code></pre>\n\n<p>The \"On Error Goto [label]\" syntax is supported by Visual Basic and Visual Basic for Applications (VBA), but VBScript doesn't support this language feature so you have to use On Error Resume Next as described above.</p>\n" }, { "answer_id": 29906239, "author": "omegastripes", "author_id": 2165759, "author_profile": "https://Stackoverflow.com/users/2165759", "pm_score": 4, "selected": false, "text": "<p>Note that <code>On Error Resume Next</code> is not set globally. You can put your unsafe part of code eg into a function, which will interrupted immediately if error occurs, and call this function from sub containing precedent <code>OERN</code> statement.</p>\n\n<pre><code>ErrCatch()\n\nSub ErrCatch()\n Dim Res, CurrentStep\n\n On Error Resume Next\n\n Res = UnSafeCode(20, CurrentStep)\n MsgBox \"ErrStep \" &amp; CurrentStep &amp; vbCrLf &amp; Err.Description\n\nEnd Sub\n\nFunction UnSafeCode(Arg, ErrStep)\n\n ErrStep = 1\n UnSafeCode = 1 / (Arg - 10)\n\n ErrStep = 2\n UnSafeCode = 1 / (Arg - 20)\n\n ErrStep = 3\n UnSafeCode = 1 / (Arg - 30)\n\n ErrStep = 0\nEnd Function\n</code></pre>\n" }, { "answer_id": 54582309, "author": "MistyDawn", "author_id": 3085172, "author_profile": "https://Stackoverflow.com/users/3085172", "pm_score": 0, "selected": false, "text": "<p>I'm exceptionally new to VBScript, so this may not be considered best practice or there may be a reason it shouldn't be done this that way I'm not yet aware of, but this is the solution I came up with to trim down the amount of error logging code in my main code block.</p>\n\n<pre><code>Dim oConn, connStr\nSet oConn = Server.CreateObject(\"ADODB.Connection\")\nconnStr = \"Provider=SQLOLEDB;Server=XX;UID=XX;PWD=XX;Databse=XX\"\n\nON ERROR RESUME NEXT\n\noConn.Open connStr\nIf err.Number &lt;&gt; 0 Then : showError() : End If\n\n\nSub ShowError()\n\n 'You could write the error details to the console...\n errDetail = \"&lt;script&gt;\" &amp; _\n \"console.log('Description: \" &amp; err.Description &amp; \"');\" &amp; _\n \"console.log('Error number: \" &amp; err.Number &amp; \"');\" &amp; _\n \"console.log('Error source: \" &amp; err.Source &amp; \"');\" &amp; _\n \"&lt;/script&gt;\"\n\n Response.Write(errDetail) \n\n '...you could display the error info directly in the page...\n Response.Write(\"Error Description: \" &amp; err.Description)\n Response.Write(\"Error Source: \" &amp; err.Source)\n Response.Write(\"Error Number: \" &amp; err.Number)\n\n '...or you could execute additional code when an error is thrown...\n 'Insert error handling code here\n\n err.clear\nEnd Sub\n</code></pre>\n" }, { "answer_id": 56733983, "author": "Cid", "author_id": 8398549, "author_profile": "https://Stackoverflow.com/users/8398549", "pm_score": 3, "selected": false, "text": "<p>You can regroup your steps functions calls in a facade function :</p>\n\n<pre><code>sub facade()\n call step1()\n call step2()\n call step3()\n call step4()\n call step5()\nend sub\n</code></pre>\n\n<p>Then, let your error handling be in an upper function that calls the facade :</p>\n\n<pre><code>sub main()\n On error resume next\n\n call facade()\n\n If Err.Number &lt;&gt; 0 Then\n ' MsgBox or whatever. You may want to display or log your error there\n msgbox Err.Description\n Err.Clear\n End If\n\n On Error Goto 0\nend sub\n</code></pre>\n\n<p>Now, let's suppose <code>step3()</code> raises an error. Since <code>facade()</code> doesn't handle errors (there is <strong>no</strong> <code>On error resume next</code> in <code>facade()</code>), the error will be returned to <code>main()</code> and <code>step4()</code> and <code>step5()</code> won't be executed.</p>\n\n<p>Your error handling is now refactored in 1 code block</p>\n" }, { "answer_id": 72972032, "author": "PravyNandas", "author_id": 1751166, "author_profile": "https://Stackoverflow.com/users/1751166", "pm_score": 0, "selected": false, "text": "<p>What @cid provided is a great answer. I took the liberty to extend it to next level by adding custom throw handler (like in javascript). Hope someone finds its useful.</p>\n<pre><code>option Explicit\n\nDim ErrorCodes\nSet ErrorCodes = CreateObject(&quot;Scripting.Dictionary&quot;)\nErrorCodes.Add &quot;100&quot;, &quot;a should not be 1&quot;\nErrorCodes.Add &quot;110&quot;, &quot;a should not be 2 either.&quot;\nErrorCodes.Add &quot;120&quot;, &quot;a should not be anything at all.&quot;\n\nSub throw(iNum)\n Err.Clear\n\n Dim key\n key = CStr(iNum)\n If ErrorCodes.Exists(key) Then\n Err.Description = ErrorCodes(key)\n Else\n Err.Description = &quot;Error description missing.&quot;\n End If\n Err.Source = &quot;Dummy stage&quot;\n \n Err.Raise iNum 'raise a user-defined error\nEnd Sub\n\n\nSub facade(a)\n if a=1 then\n throw 100\n end if\n\n if a = 2 then\n throw 110\n end if\n\n throw 120\nEnd Sub\n\nSub Main\n on error resume next\n\n facade(3)\n\n if err.number &lt;&gt; 0 then\n Wscript.Echo Err.Number, Err.Description\n end if\n on error goto 0\nEnd Sub\n\nMain\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6128/" ]
I want to use VBScript to catch errors and log them (ie on error "log something") then resume the next line of the script. For example, ``` On Error Resume Next 'Do Step 1 'Do Step 2 'Do Step 3 ``` When an error occurs on step 1, I want it to log that error (or perform other custom functions with it) then resume at step 2. Is this possible? and how can I implement it? EDIT: Can I do something like this? ``` On Error Resume myErrCatch 'Do step 1 'Do step 2 'Do step 3 myErrCatch: 'log error Resume Next ```
VBScript has no notion of throwing or catching exceptions, but the runtime provides a global Err object that contains the results of the last operation performed. You have to explicitly check whether the Err.Number property is non-zero after each operation. ``` On Error Resume Next DoStep1 If Err.Number <> 0 Then WScript.Echo "Error in DoStep1: " & Err.Description Err.Clear End If DoStep2 If Err.Number <> 0 Then WScript.Echo "Error in DoStop2:" & Err.Description Err.Clear End If 'If you no longer want to continue following an error after that block's completed, 'call this. On Error Goto 0 ``` The "On Error Goto [label]" syntax is supported by Visual Basic and Visual Basic for Applications (VBA), but VBScript doesn't support this language feature so you have to use On Error Resume Next as described above.
157,770
<p>I'm trying to format a column in a <code>&lt;table/&gt;</code> using a <code>&lt;col/&gt;</code> element. I can set <code>background-color</code>, <code>width</code>, etc., but can't set the <code>font-weight</code>. Why doesn't it work?</p> <pre><code>&lt;table&gt; &lt;col style="font-weight:bold; background-color:#CCC;"&gt; &lt;col&gt; &lt;tr&gt; &lt;td&gt;1&lt;/td&gt; &lt;td&gt;2&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;3&lt;/td&gt; &lt;td&gt;4&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre>
[ { "answer_id": 157798, "author": "Philip Morton", "author_id": 21709, "author_profile": "https://Stackoverflow.com/users/21709", "pm_score": -1, "selected": false, "text": "<p>A <code>col</code> tag must be inside of a <code>colgroup</code> tag, This may be something to do with the problem.</p>\n" }, { "answer_id": 157836, "author": "mwilliams", "author_id": 23909, "author_profile": "https://Stackoverflow.com/users/23909", "pm_score": 1, "selected": false, "text": "<p>Have you tried applying the style through a CSS class?</p>\n\n<p>The following appears to work:</p>\n\n<pre><code>&lt;style type=\"text/css\"&gt; \n .xx {\n background: yellow;\n color: red;\n font-weight: bold;\n padding: 0 30px;\n text-align: right;\n}\n\n&lt;table border=\"1\"&gt;\n &lt;col width=\"150\" /&gt;\n &lt;col width=\"50\" class=\"xx\" /&gt;\n &lt;col width=\"80\" /&gt;\n&lt;thead&gt;\n &lt;tr&gt;\n &lt;th&gt;1&lt;/th&gt;\n &lt;th&gt;2&lt;/th&gt;\n &lt;th&gt;3&lt;/th&gt;\n &lt;th&gt;4&lt;/th&gt;\n &lt;/tr&gt;\n&lt;/thead&gt;\n&lt;tbody&gt;\n &lt;tr&gt;\n &lt;td&gt;1&lt;/td&gt;\n &lt;td&gt;2&lt;/td&gt;\n &lt;td&gt;3&lt;/td&gt;\n &lt;td&gt;4&lt;/td&gt;\n &lt;/tr&gt;\n&lt;/tbody&gt;\n&lt;/table&gt;\n</code></pre>\n\n<p><a href=\"http://reference.sitepoint.com/html/col\" rel=\"nofollow noreferrer\">Reference for the col element</a></p>\n" }, { "answer_id": 158045, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 3, "selected": false, "text": "<p>Your best bet is to apply your styling directly to the <code>&lt;td&gt;</code> tags. I've never used the <code>&lt;col&gt;</code> tag, but most browsers let you apply formatting at the <code>&lt;table&gt;</code> and <code>&lt;td&gt;</code>/<code>&lt;th&gt;</code> level, but not at an intermediate level. For example if you have</p>\n\n<pre><code>&lt;table&gt;\n &lt;tr class=\"Highlight\"&gt;\n &lt;td&gt;One&lt;/td&gt;\n &lt;td&gt;Two&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;A&lt;/td&gt;\n &lt;td&gt;B&lt;/td&gt;\n &lt;/tr&gt;\n&lt;/table&gt;\n</code></pre>\n\n<p>then this CSS won't work</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>tr.Highlight { background:yellow }\n</code></pre>\n\n<p>but this will</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>tr.Highlight td { background:yellow }\n</code></pre>\n\n<p>Also: I assume your code above is just for demonstration purposes and you're not actually going to apply styles inline.</p>\n" }, { "answer_id": 159848, "author": "Bill", "author_id": 24190, "author_profile": "https://Stackoverflow.com/users/24190", "pm_score": 6, "selected": true, "text": "<p>As far as I know, you can only format the following using CSS on the <code>&lt;col&gt;</code> element: </p>\n\n<ul>\n<li>background-color</li>\n<li>border</li>\n<li>width</li>\n<li>visibility</li>\n</ul>\n\n<p>This <a href=\"http://www.quirksmode.org/css/columns.html\" rel=\"noreferrer\">page</a> has more info.</p>\n\n<p>Herb is right - it's better to style the <code>&lt;td&gt;</code>'s directly. What I do is the following:</p>\n\n<pre><code>&lt;style type=\"text/css\"&gt;\n #mytable tr &gt; td:first-child { color: red;} /* first column */\n #mytable tr &gt; td:first-child + td { color: green;} /* second column */\n #mytable tr &gt; td:first-child + td + td { color: blue;} /* third column */\n &lt;/style&gt;\n &lt;/head&gt;\n &lt;body&gt; \n &lt;table id=\"mytable\"&gt;\n &lt;tr&gt;\n &lt;td&gt;text 1&lt;/td&gt;\n &lt;td&gt;text 2&lt;/td&gt;\n &lt;td&gt;text 3&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;text 4&lt;/td&gt;\n &lt;td&gt;text 5&lt;/td&gt;\n &lt;td&gt;text 6&lt;/td&gt;\n &lt;/tr&gt;\n &lt;/table&gt;\n</code></pre>\n\n<p>This won't work in IE however.</p>\n" }, { "answer_id": 2078938, "author": "Herbt", "author_id": 252352, "author_profile": "https://Stackoverflow.com/users/252352", "pm_score": 1, "selected": false, "text": "<p>Reading through this as I was attempting to style a table such that the first column would be bold text and the the other four columns would be normal text.\nUsing col tag seemed like the way to go but while I could set the widths of the columns with the width attribute the font-weight: bold wouldn't work\nThanks for pointing me in the direction of the solution.\nBy styling all the td elements <code>td {font-weight: bold;}</code> and then using an adjacent sibling selector to select columns 2-5 and style them back to normal <code>td + td {font-weight: normal;}</code>\nVoila, alls good :)</p>\n" }, { "answer_id": 26913129, "author": "Paul", "author_id": 4249003, "author_profile": "https://Stackoverflow.com/users/4249003", "pm_score": 2, "selected": false, "text": "<p>You might have just needed this:</p>\n\n<pre><code>tr td:first-child label {\n font-weight: bold;\n}\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/157770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15788/" ]
I'm trying to format a column in a `<table/>` using a `<col/>` element. I can set `background-color`, `width`, etc., but can't set the `font-weight`. Why doesn't it work? ``` <table> <col style="font-weight:bold; background-color:#CCC;"> <col> <tr> <td>1</td> <td>2</td> </tr> <tr> <td>3</td> <td>4</td> </tr> </table> ```
As far as I know, you can only format the following using CSS on the `<col>` element: * background-color * border * width * visibility This [page](http://www.quirksmode.org/css/columns.html) has more info. Herb is right - it's better to style the `<td>`'s directly. What I do is the following: ``` <style type="text/css"> #mytable tr > td:first-child { color: red;} /* first column */ #mytable tr > td:first-child + td { color: green;} /* second column */ #mytable tr > td:first-child + td + td { color: blue;} /* third column */ </style> </head> <body> <table id="mytable"> <tr> <td>text 1</td> <td>text 2</td> <td>text 3</td> </tr> <tr> <td>text 4</td> <td>text 5</td> <td>text 6</td> </tr> </table> ``` This won't work in IE however.