qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
242,565
<p>I have MainViewController calling WebViewController (From UICatalog sample application) In WebViewController I make some function setValue(){...} to set some value passed as parameter to the variable (NSString *value) from WebViewController.h but when I try from MainViewController something like WebViewController targetViewController... targetViewController.setValue(value), it says: "<strong>error: request for member 'setValue' in something not s structure or union</strong>"...</p>
[ { "answer_id": 242638, "author": "Kendall Helmstetter Gelner", "author_id": 6330, "author_profile": "https://Stackoverflow.com/users/6330", "pm_score": 1, "selected": false, "text": "targetViewController.value = whatever;\n [targetViewController setValue:whatever];\n" }, { "answer_id": 242839, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 1, "selected": false, "text": "targetViewController.value = whatever;\n [targetViewController setValue: whatever];\n targetViewController.setValue(value);\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16066/" ]
242,568
<p>By default, .NET application's configuration file is named after "exe file name".config. I'm wondering whether it is possible to have one application's configuration specified dynamically.</p> <p>For example, the built application is "foo.exe". At runtime, the config file is "foo.exe.config". Is it possible to have it accept command line arguments to use other config file. So, the application can use other configuration like below.</p> <blockquote> <p>foo.exe /config:bar.config</p> </blockquote> <p>bar.config is used as config file insteand of foo.exe.config.</p>
[ { "answer_id": 242612, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 2, "selected": false, "text": "static void DisplayMappedExeConfigurationFileSections()\n{\n // Get the application configuration file path.\n string exeFilePath = System.IO.Path.Combine(\n Environment.CurrentDirectory, \"ConfigurationManager.exe.config\");\n // HERE !!! \n // Map to the application configuration file.\n ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();\n configFile.ExeConfigFilename = exeFilePath;\n\n Configuration config =\n ConfigurationManager.OpenMappedExeConfiguration(configFile,\n ConfigurationUserLevel.None);\n\n // Display the configuration file sections.\n ConfigurationSectionCollection sections = config.Sections;\n\n Console.WriteLine();\n Console.WriteLine(\"Sections in machine.config:\");\n\n // Loop to get the sections machine.config.\n foreach (ConfigurationSection section in sections)\n {\n string name = section.SectionInformation.Name;\n Console.WriteLine(\"Name: {0}\", name);\n }\n\n}\n" }, { "answer_id": 242613, "author": "faulty", "author_id": 20007, "author_profile": "https://Stackoverflow.com/users/20007", "pm_score": 2, "selected": false, "text": "ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();\nfileMap.ExeConfigFilename = @\"C:\\Inetpub\\Test\\Config\\Dev.config\";\nConfiguration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);\nAppSettingsSection section = (AppSettingsSection)config.GetSection(\"appSettings\");\nstring ConfigVersion = section.Settings[\"ConfigVersion\"].Value;\n" }, { "answer_id": 305711, "author": "Slav", "author_id": 22680, "author_profile": "https://Stackoverflow.com/users/22680", "pm_score": 4, "selected": false, "text": " AppDomainSetup setup = new AppDomainSetup();\n setup.ApplicationBase = \"file://\" + System.Environment.CurrentDirectory;\n setup.DisallowBindingRedirects = true;\n setup.DisallowCodeDownload = true;\n\n if (args.Length != 0 && args[0].Equals(\"-test\"))\n {\n setup.ConfigurationFile = \"PATH_TO_YOUR_TEST_CONFIG_FILE\";\n }\n else {\n setup.ConfigurationFile = \"PATH_TO_YOUR_LIVE_CONFIG_FILE\";\n }\n\n AppDomain domain = AppDomain.CreateDomain(\"FRIENDLY_NAME\", null, setup);\n domain.ExecuteAssembly(\"YourMainApp.exe\");\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26349/" ]
242,570
<p>I need to copy the content of a window (BitBlt) which is hidden, to another window. The problem is that once I hide the source window, the device context I got isn't painted anymore.</p>
[ { "answer_id": 242809, "author": "Anthony Williams", "author_id": 5597, "author_profile": "https://Stackoverflow.com/users/5597", "pm_score": 1, "selected": false, "text": "WM_PRINT" }, { "answer_id": 242837, "author": "elifiner", "author_id": 15109, "author_profile": "https://Stackoverflow.com/users/15109", "pm_score": 3, "selected": false, "text": "// Takes a snapshot of the window hwnd, stored in the memory device context hdcMem\nHDC hdc = GetWindowDC(hwnd);\nif (hdc)\n{\n HDC hdcMem = CreateCompatibleDC(hdc);\n if (hdcMem)\n {\n RECT rc;\n GetWindowRect(hwnd, &rc);\n\n HBITMAP hbitmap = CreateCompatibleBitmap(hdc, RECTWIDTH(rc), RECTHEIGHT(rc));\n if (hbitmap)\n {\n SelectObject(hdcMem, hbitmap);\n\n PrintWindow(hwnd, hdcMem, 0);\n\n DeleteObject(hbitmap);\n }\n DeleteObject(hdcMem);\n }\n ReleaseDC(hwnd, hdc);\n}\n" }, { "answer_id": 8728689, "author": "Orwellophile", "author_id": 912236, "author_profile": "https://Stackoverflow.com/users/912236", "pm_score": 0, "selected": false, "text": "Orwellophile.TakeScreenShotOfWindow(\"window.jpg\", Form.Handle);\n using System;\nusing System.Drawing;\nusing System.Threading;\nusing System.Runtime.InteropServices;\nusing System.Windows.Forms;\n\npublic class Orwellophile {\n public static void TakeScreenshotOfWindow(String strFilename, IntPtr hTargetWindow)\n {\n Rectangle objRectangle;\n RECT r;\n IntPtr hForegroundWindow = GetForegroundWindow();\n\n GetWindowRect(hTargetWindow, out r);\n objRectangle = r.ToRectangle();\n\n if (hTargetWindow != hForegroundWindow)\n {\n ShowWindow(hTargetWindow, SW_SHOWNOACTIVATE);\n SetWindowPos(hTargetWindow.ToInt32(), HWND_TOPMOST, r.X, r.Y, r.Width, r.Height, SWP_NOACTIVATE);\n Thread.Sleep(500);\n }\n\n TakeScreenshotPrivate(strFilename, objRectangle);\n }\n\n private static void TakeScreenshotPrivate(string strFilename, Rectangle objRectangle)\n {\n Bitmap objBitmap = new Bitmap(objRectangle.Width, objRectangle.Height);\n Graphics objGraphics = default(Graphics);\n IntPtr hdcDest = default(IntPtr);\n int hdcSrc = 0;\n\n objGraphics = Graphics.FromImage(objBitmap);\n\n\n hdcSrc = GetDC(0); // Get a device context to the windows desktop and our destination bitmaps\n hdcDest = objGraphics.GetHdc(); // Copy what is on the desktop to the bitmap\n BitBlt(hdcDest.ToInt32(), 0, 0, objRectangle.Width, objRectangle.Height, hdcSrc, objRectangle.X, objRectangle.Y, SRCCOPY);\n objGraphics.ReleaseHdc(hdcDest); // Release DC\n ReleaseDC(0, hdcSrc);\n\n objBitmap.Save(strFilename);\n }\n\n\n [DllImport(\"gdi32.dll\", SetLastError = true)]\n static extern IntPtr CreateCompatibleDC(IntPtr hdc);\n [DllImport(\"user32.dll\")]\n static extern IntPtr GetWindowDC(IntPtr hWnd);\n [DllImport(\"gdi32.dll\")]\n static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight);\n [DllImport(\"gdi32.dll\", ExactSpelling = true, PreserveSig = true, SetLastError = true)]\n static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj);\n [DllImport(\"User32.dll\", SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n static extern bool PrintWindow(IntPtr hwnd, IntPtr hDC, uint nFlags); // To capture only the client area of window, use PW_CLIENTONLY = 0x1 as nFlags\n [DllImport(\"gdi32.dll\")]\n static extern bool DeleteObject(IntPtr hObject);\n [DllImport(\"user32.dll\")]\n static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDC);\n\n [DllImport(\"user32.dll\", EntryPoint = \"SetWindowPos\")]\n static 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 [DllImport(\"user32.dll\")]\n static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);\n [DllImport(\"user32.dll\")]\n [return: MarshalAs(UnmanagedType.Bool)]\n public static extern bool GetWindowRect(IntPtr hwnd, out RECT lpRect);\n [DllImport(\"user32.dll\", CharSet = CharSet.Auto, ExactSpelling = true)]\n static public extern IntPtr GetForegroundWindow();\n private const int SW_SHOWNOACTIVATE = 4;\n private const int HWND_TOPMOST = -1;\n private const uint SWP_NOACTIVATE = 0x0010;\n private const int SRCCOPY = 0xcc0020;\n}\n [StructLayout(LayoutKind.Sequential)]\npublic struct RECT\n{\n private int _Left;\n private int _Top;\n private int _Right;\n private int _Bottom;\n\n public RECT(System.Drawing.Rectangle Rectangle)\n : this(Rectangle.Left, Rectangle.Top, Rectangle.Right, Rectangle.Bottom)\n {\n }\n public RECT(int Left, int Top, int Right, int Bottom)\n {\n _Left = Left;\n _Top = Top;\n _Right = Right;\n _Bottom = Bottom;\n }\n\n public int X\n {\n get { return _Left; }\n set { _Left = value; }\n }\n public int Y\n {\n get { return _Top; }\n set { _Top = value; }\n }\n public int Left\n {\n get { return _Left; }\n set { _Left = value; }\n }\n public int Top\n {\n get { return _Top; }\n set { _Top = value; }\n }\n public int Right\n {\n get { return _Right; }\n set { _Right = value; }\n }\n public int Bottom\n {\n get { return _Bottom; }\n set { _Bottom = value; }\n }\n public int Height\n {\n get { return _Bottom - _Top; }\n set { _Bottom = value - _Top; }\n }\n public int Width\n {\n get { return _Right - _Left; }\n set { _Right = value + _Left; }\n }\n public Point Location\n {\n get { return new Point(Left, Top); }\n set\n {\n _Left = value.X;\n _Top = value.Y;\n }\n }\n public Size Size\n {\n get { return new Size(Width, Height); }\n set\n {\n _Right = value.Height + _Left;\n _Bottom = value.Height + _Top;\n }\n }\n\n public Rectangle ToRectangle()\n {\n return new Rectangle(this.Left, this.Top, this.Width, this.Height);\n }\n static public Rectangle ToRectangle(RECT Rectangle)\n {\n return Rectangle.ToRectangle();\n }\n static public RECT FromRectangle(Rectangle Rectangle)\n {\n return new RECT(Rectangle.Left, Rectangle.Top, Rectangle.Right, Rectangle.Bottom);\n }\n\n static public implicit operator Rectangle(RECT Rectangle)\n {\n return Rectangle.ToRectangle();\n }\n static public implicit operator RECT(Rectangle Rectangle)\n {\n return new RECT(Rectangle);\n }\n static public bool operator ==(RECT Rectangle1, RECT Rectangle2)\n {\n return Rectangle1.Equals(Rectangle2);\n }\n static public bool operator !=(RECT Rectangle1, RECT Rectangle2)\n {\n return !Rectangle1.Equals(Rectangle2);\n }\n\n public override string ToString()\n {\n return \"{Left: \" + _Left + \"; \" + \"Top: \" + _Top + \"; Right: \" + _Right + \"; Bottom: \" + _Bottom + \"}\";\n }\n\n public bool Equals(RECT Rectangle)\n {\n return Rectangle.Left == _Left && Rectangle.Top == _Top && Rectangle.Right == _Right && Rectangle.Bottom == _Bottom;\n }\n public override bool Equals(object Object)\n {\n if (Object is RECT)\n {\n return Equals((RECT)Object);\n }\n else if (Object is Rectangle)\n {\n return Equals(new RECT((Rectangle)Object));\n }\n\n return false;\n }\n\n public override int GetHashCode()\n {\n return Left.GetHashCode() ^ Right.GetHashCode() ^ Top.GetHashCode() ^ Bottom.GetHashCode();\n }\n}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
242,577
<p>I've tried reading a JPG file using the <code>StreamReader</code> class' <code>ReadToEnd()</code> method which returns a string.</p> <p>For some reason though, when I write this string out to a file, it doesn't open.</p> <p>Is something lost when reading data into a string?</p>
[ { "answer_id": 242583, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "byte[] Stream Image StreamReader TextReader TextReader Stream" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17211/" ]
242,579
<p>I have a long URL with tons of parameters that I want to open in the default browser from Java on a Windows system using</p> <pre><code>Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler "+url) </code></pre> <p>For short URLs like "<a href="http://www.google.com" rel="nofollow noreferrer">http://www.google.com</a>" this works fine. But for long URLs (say, 2000 characters), this simply does absolutely nothing at all: no exception or anything of the sort, it is simply ignored.</p> <p>Is there a character limit a) for a Runtime.exec command or b) for the rundll32 url.dll command? If so, what is the limit?</p>
[ { "answer_id": 244342, "author": "John Gardner", "author_id": 13687, "author_profile": "https://Stackoverflow.com/users/13687", "pm_score": 0, "selected": false, "text": "MAX_PATH" }, { "answer_id": 248384, "author": "James Van Huis", "author_id": 31828, "author_profile": "https://Stackoverflow.com/users/31828", "pm_score": 0, "selected": false, "text": "Runtime.getRuntime().exec(new String [] {\"rundll32\", \"url.dll,FileProtocolHandler\", \"urlarg1\", \"urlarg2\"});" }, { "answer_id": 301710, "author": "jamesh", "author_id": 4737, "author_profile": "https://Stackoverflow.com/users/4737", "pm_score": 2, "selected": false, "text": "Desktop.open() Desktop.browse() rundll32" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
242,600
<p>This is probably a simple question but how can I best use an AJAX loader in ASP.NET to provide a loading dialog whilst the page is being built?</p> <p>I currently have an UpdatePanel with an associated UpdateProgressPanel which contains the loading message and gif in a ProgressTemplate. </p> <p>Currently I have a page that onLoad() goes and gets the business entities and then displays them. While it is doing this I would like to display an AJAX loader. </p> <p>Would it be better to have nothing in the page load and have a hidden button that is triggered onLoadComplete or unLoad() which would then wait for the button click method to complete displaying the UpdateProgressPanel? </p>
[ { "answer_id": 2891484, "author": "Shripad Krishna", "author_id": 277537, "author_profile": "https://Stackoverflow.com/users/277537", "pm_score": 0, "selected": false, "text": "div div width div" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11802/" ]
242,602
<p>Is it possible to make a POST request from Ruby with open-uri?</p>
[ { "answer_id": 242637, "author": "Martin Kenny", "author_id": 6111, "author_profile": "https://Stackoverflow.com/users/6111", "pm_score": 6, "selected": true, "text": "open-uri GET net/http rest-open-uri POST gem install rest-open-uri" }, { "answer_id": 8495402, "author": "Venkat D.", "author_id": 67655, "author_profile": "https://Stackoverflow.com/users/67655", "pm_score": 4, "selected": false, "text": "require 'open-uri'\nrequire 'net/http'\nparams = {'param1' => 'value1', 'param2' => 'value2'}\nurl = URI.parse('http://thewebsite.com/thepath')\nresp, data = Net::HTTP.post_form(url, params)\nputs resp.inspect\nputs data.inspect\n" }, { "answer_id": 43646320, "author": "Dorian", "author_id": 407213, "author_profile": "https://Stackoverflow.com/users/407213", "pm_score": 1, "selected": false, "text": "require 'open-uri'\nrequire 'net/http'\n\nresponse = Net::HTTP.post_form(URI.parse(\"https://httpbin.org/post\"), { a: 1 })\n\nputs response.code\nputs response.message\nputs response.body\n response.methods - Object.methods message header, puts Net::HTTP.new(\"httpbin.org\").post(\"/post\", \"a=1\").body\nputs Net::HTTP.new(\"httpbin.org\").delete(\"/delete\").body\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8338/" ]
242,608
<p>Is it possible to disable the browsers vertical and horizontal scrollbars using jQuery or javascript?</p>
[ { "answer_id": 242615, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 6, "selected": false, "text": "<body style=\"overflow: hidden\">\n" }, { "answer_id": 242684, "author": "Alexander Prokofyev", "author_id": 11256, "author_profile": "https://Stackoverflow.com/users/11256", "pm_score": 7, "selected": false, "text": "$(\"body\").css(\"overflow\", \"hidden\");\n $(\"body\").css(\"overflow\", \"auto\");\n" }, { "answer_id": 242805, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 5, "selected": false, "text": "<style>\n body {width:100%; height:100%; overflow:hidden; margin:0; }\n html {width:100%; height:100%; overflow:hidden; }\n</style>\n" }, { "answer_id": 3418851, "author": "Gawin", "author_id": 351659, "author_profile": "https://Stackoverflow.com/users/351659", "pm_score": 3, "selected": false, "text": "$(\"html\").css(\"overflow\", \"hidden\");\n $(\"html\").css(\"overflow\", \"auto\");\n" }, { "answer_id": 8504771, "author": "shafraz", "author_id": 1097822, "author_profile": "https://Stackoverflow.com/users/1097822", "pm_score": 4, "selected": false, "text": "overflow-x: hidden;\n overflow-y: hidden;\n" }, { "answer_id": 10811680, "author": "Lyncee", "author_id": 1425405, "author_profile": "https://Stackoverflow.com/users/1425405", "pm_score": 7, "selected": false, "text": "function reloadScrollBars() {\n document.documentElement.style.overflow = 'auto'; // firefox, chrome\n document.body.scroll = \"yes\"; // ie only\n}\n\nfunction unloadScrollBars() {\n document.documentElement.style.overflow = 'hidden'; // firefox, chrome\n document.body.scroll = \"no\"; // ie only\n}\n" }, { "answer_id": 16081832, "author": "Zeeshan Ali", "author_id": 1133785, "author_profile": "https://Stackoverflow.com/users/1133785", "pm_score": 3, "selected": false, "text": "overflow-x: hidden; overflow-y:scroll; overflow-y: hidden; overflow-x: scroll;" }, { "answer_id": 16226821, "author": "Qvcool", "author_id": 2016624, "author_profile": "https://Stackoverflow.com/users/2016624", "pm_score": 2, "selected": false, "text": "<div> overflow:hidden;" }, { "answer_id": 20801125, "author": "Lg102", "author_id": 775265, "author_profile": "https://Stackoverflow.com/users/775265", "pm_score": 3, "selected": false, "text": "-ms-overflow-style html {\n -ms-overflow-style: none;\n}\n ::-webkit-scrollbar {\n display: none;\n}\n overflow-y: scroll" }, { "answer_id": 32781413, "author": "Erasmus Cedernaes", "author_id": 4713758, "author_profile": "https://Stackoverflow.com/users/4713758", "pm_score": 2, "selected": false, "text": "document.documentElement.style.overflow = ...\n document.body.style.overflow = ...\n" }, { "answer_id": 37098825, "author": "gtzinos", "author_id": 4669968, "author_profile": "https://Stackoverflow.com/users/4669968", "pm_score": 2, "selected": false, "text": "$('body').on({\n 'mousewheel': function(e) {\n if (e.target.id == 'el') return;\n e.preventDefault();\n e.stopPropagation();\n }\n});\n $('body').unbind('mousewheel');\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17447/" ]
242,609
<p>As everyone knows, sometimes developers have to document stuff. Or capture some stuff for filing bug reports. </p> <p>My question is in MS Windows.</p> <p>I'm trying to capture the context menu (the popup menu that appears after right-clicking an item) of several areas of an application. Pressing <kbd>Alt</kbd> to start the <kbd>Alt</kbd>+<kbd>PrintScreen</kbd> process closes the context menu.</p> <p>(Only pressing <kbd>PrintScreen</kbd> helps, but it's painful to remove the non-window areas everytime).</p> <p>BONUS: For capturing menus, <kbd>Alt</kbd> also closes the menu. However, if you use the <kbd>Alt</kbd> key to open the menu in the first place, it works:</p> <ol> <li>Press <kbd>Alt</kbd>+<kbd>F</kbd> (for opening the "File" menu), don't release <kbd>Alt</kbd></li> <li>Press <kbd>PrintScreen</kbd></li> <li>Tada!</li> </ol>
[ { "answer_id": 26074872, "author": "Smile4ever", "author_id": 1798408, "author_profile": "https://Stackoverflow.com/users/1798408", "pm_score": 0, "selected": false, "text": "scrot -d 5 'contextmenuincluded.png' -e 'mv $f ~'\n sudo apt-get install scrot\n sudo pacman -S scrot\n" }, { "answer_id": 38007326, "author": "claudio", "author_id": 6507611, "author_profile": "https://Stackoverflow.com/users/6507611", "pm_score": 0, "selected": false, "text": "clipboard" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26374/" ]
242,614
<p>A classic ASP.NET app - AppSrv + MS SQL DB. Both servers are heavy-lifters 8 cores, 20 GB of RAM. When load testing, the throughput goes somewhere to 400 VirtualUsers (according to LoadRunner) with CPU being approximately 30% utilized an DB server primarily idling - response times go dramatically up, to the point of unresponsive.</p> <p>The usual suspects, such as Max Pool being exhausted and conn limit on ASP.NET set are not at fault: Max Pool is set to 200 and about 80 conns are used; conn limit is set to 0. </p> <p>I ran with ANTS profiler the code and it showed that Thread blocking did not contribute significantly. </p> <p>Ideas very very welcome!</p>
[ { "answer_id": 242631, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 1, "selected": true, "text": "An Application Pool -> Performance -> \nWeb Garden -> Max Number of worker processes\n" }, { "answer_id": 243460, "author": "zendar", "author_id": 25732, "author_profile": "https://Stackoverflow.com/users/25732", "pm_score": 1, "selected": false, "text": "machine.config maxconnection maxIoThreads maxWorkerThreads minFreeThreads minLocalRequestFreeThreads processModel processModel autoConfig true" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29573/" ]
242,617
<p>Posting a stack overflow question on stackoverflow.com, how amusing :-)</p> <p>I'm running some recursive Ruby code and I get the: <code>"Stack level too deep (SystemStackError)"</code></p> <p>(I'm quite sure the code works, that I'm not in an infinite recursive death spiral, but that is not the point anyway)</p> <p>Is there anyway to change the allowed stack depth/size for my Ruby app?</p> <p>I don't quite get it if this is a restriction in Ruby, since the error says "Stack level", which gives me the impression that Ruby somehow counts 'levels' of stack, or if it simply means that the stack is full.</p> <p>I have tried running this program under both Vista and Ubuntu with same result. Under Ubuntu i tried changing the stack size with 'ulimit -s' from 8192 to 16000, but that didn't change anything.</p> <p>Edit: Thanks for the feedback.<br> I do realize that using a recursive function perhaps isn't the most robust way to go. But that isn't the point either. I simply wonder if there is a way to increase the stack size.. period. And as I mentioned i did try running ulimit -s 16000 before running the ruby script.. with no improvement.. Am I using it wrong?</p> <p>Edit2: I was in fact having an infinite recursion in an edge case of the code. <br>The truncated ruby stack trace when you get the <code>"Stack level too deep"</code> error is a bit misleading. <br>When having a recursive behavior involving several functions, you get the impression that the numbers of recursions is much lower than it actually is. In this example one might thing that it crashes after little bit more than 190 calls, but it is actually around 15000 calls</p> <pre><code>tst.rb:8:in `p': stack level too deep (SystemStackError) from tst.rb:8:in `bar' from tst.rb:12:in `bar' from tst.rb:19:in `foo' from tst.rb:10:in `bar' from tst.rb:19:in `foo' from tst.rb:10:in `bar' from tst.rb:19:in `foo' from tst.rb:10:in `bar' ... 190 levels... from tst.rb:19:in `foo' from tst.rb:10:in `bar' from tst.rb:19:in `foo' from tst.rb:22 </code></pre> <p>-Andreas</p>
[ { "answer_id": 244348, "author": "Honza", "author_id": 8621, "author_profile": "https://Stackoverflow.com/users/8621", "pm_score": 4, "selected": false, "text": "def recursive(params)\n if some_conditions(params)\n recursive(update_params(params))\n end\nend\n\nrecursive(starting_params)\n stack = [starting_params]\nwhile !stack.empty?\n current_params = stack.delete_at(0)\n if some_conditions(current_params)\n stack << update_params(current_params)\n end\nend\n" }, { "answer_id": 8119686, "author": "Folke", "author_id": 230291, "author_profile": "https://Stackoverflow.com/users/230291", "pm_score": 2, "selected": false, "text": "ulimit -s 20000\n" }, { "answer_id": 27510458, "author": "gregspurrier", "author_id": 601798, "author_profile": "https://Stackoverflow.com/users/601798", "pm_score": 5, "selected": false, "text": "RUBY_THREAD_VM_STACK_SIZE" }, { "answer_id": 43838159, "author": "Kathryn", "author_id": 7948068, "author_profile": "https://Stackoverflow.com/users/7948068", "pm_score": 1, "selected": false, "text": "RubyVM::InstructionSequence.compile_option = {\n tailcall_optimization: true,\n trace_instruction: false\n}\n\nRubyVM::InstructionSequence.new(<<-EOF).eval\n def me_myself_and_i\n me_myself_and_i\n end\nEOF\nme_myself_and_i # Infinite loop, not stack overflow\n SystemStackError" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28625/" ]
242,621
<p>I'm having trouble running a complex query against our company LDAP server. I'm using the following Perl script:</p> <pre><code>use Data::Dumper; use Net::LDAP; die "Can't connect to LDAP-Server: $@\n" unless $ldap = Net::LDAP-&gt;new( 'xLDAPx' ); foreach my $filter ( 'ou=Personal', 'ou=BAR', 'ou=Personal,ou=BAR', 'ou=Personal,ou=FOO,o=FOO,dc=foo,dc=com' ) { $mesg = $ldap-&gt;search( base =&gt; "o=FOO,dc=foo,dc=com", filter =&gt; $filter ); print Dumper($mesg), "\n\n"; } </code></pre> <p>While the first two filters work (as in returning the expected values) the last and complex one doesn't. It returns an empty array. What really puzzles me is that exactly the same query string works when I use it with a tool like the Softerra LDAP Browser. </p> <p>I have also tried the same query using PHP's <code>ldap_search</code> &amp; co, no avail.</p> <p>Can somebody shed some light on this?</p> <p>Thanks for reading</p> <p>holli</p> <p>Edit: This is the structure of the server:</p> <pre><code>Server ou=FOO ou=... ou=Personal uid=something </code></pre> <p>I need a list of uids.</p>
[ { "answer_id": 242779, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 4, "selected": true, "text": "(&(ou=Personal)(ou=FOO)(o=FOO)(dc=foo)(dc=com)) (|(ou=Personal)(ou=FOO))" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18606/" ]
242,627
<pre><code>today1 = new Date(); today2 = Date.parse("2008-28-10"); </code></pre> <p>To compare the time (millisecond) values of these I have to do the following, because today2 is just a number.</p> <pre><code>if (today1.getTime() == today2) </code></pre> <p>Why is this?</p>
[ { "answer_id": 242632, "author": "Yuval Adam", "author_id": 24545, "author_profile": "https://Stackoverflow.com/users/24545", "pm_score": 2, "selected": false, "text": "var newDate = new Date();\nnewDate.setFullYear(2008,9,28);\n" }, { "answer_id": 242679, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 6, "selected": true, "text": "java.util.Date var today2 = new Date(Date.parse(\"2008-10-28\"));\n var today2 = new Date(\"2008-10-28\");\n var today2 = new Date(\"2008/10/28\");\n" }, { "answer_id": 242785, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "var d1 = new Date();\nvar n = Date.parse(\"28 Oct 2008\");\nvar d2 = new Date(n);\nvar d3 = new Date(\"28 october 2008\");\n\nalert(d1.toDateString() == d2.toDateString());\nalert(d2.toDateString() == d3.toDateString());\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]
242,629
<p>Whilst investigating a memory leak I discovered that it was caused by calling NewRow() on a Table inside a loop many times. However the DataRow created was never added to the Table Rows collection and the Table Rows Count never got above zero.</p> <p>My question is why does this use up more memory every time NewRow is called even though the newly created DataRow never gets added to the Rows collection and the DataRow returned from NewRow is always assigned to the same local variable (thereby apparently discarding the last new row).</p> <p>Please ignore the issue of why the code is creating DataRows that don't get added to the table!</p>
[ { "answer_id": 51299108, "author": "Ден Денис", "author_id": 5945461, "author_profile": "https://Stackoverflow.com/users/5945461", "pm_score": 0, "selected": false, "text": " var table = new DataTable();\n while (true)\n {\n var newRow = table.NewRow();\n table.Rows.Add(newRow); //Without this 2 rows you will have memory leak.\n table.Rows.Remove(newRow);//\n }\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1127460/" ]
242,640
<p>I wanna see if there is an approach to pack a few plugins together as a meta plugin that install everything together automatically, works like a project template.</p> <p>Why not a script? Because I want to put it in github so I don't have to worry about it when I am not with my own PC :) but of coz a script based solution is welcomed too.</p>
[ { "answer_id": 243330, "author": "Ricardo Acras", "author_id": 19224, "author_profile": "https://Stackoverflow.com/users/19224", "pm_score": 1, "selected": false, "text": "plugins = %w{\n http://url_to_plugin_1\n http://url_to_plugin_2\n http://url_to_plugin_3\n http://url_to_plugin_4\n http://url_to_plugin_5\n}\nplugins.each do | p |\n `ruby script/plugin install -x #{p}`\nend\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16371/" ]
242,646
<p>How can I use vimdiff to view the differences described in a diff file?</p>
[ { "answer_id": 242680, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 2, "selected": false, "text": "vimdiff original_file patched_file\n" }, { "answer_id": 244766, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 6, "selected": false, "text": "/usr/bin/vimdiff :vert diffpa vimdiff vim patch vim +command vim +123 +/abc vim patch patch" }, { "answer_id": 4169689, "author": "Adam Monsen", "author_id": 156060, "author_profile": "https://Stackoverflow.com/users/156060", "pm_score": 1, "selected": false, "text": "ALT-n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14437/" ]
242,647
<p>I have one aspx page with some controls. Also i have one DIV which is dynamically populated from AJAX call. This AJAX call return couple of controls, for example HtmlInputText1 and HtmlInputText2.</p> <p>When page is submitted, I can get values from this controls through Request.Form. If possible access to the attributes of this control on pege code behind (for example HtmlInputText1.Height, etc). </p> <p>I think that is impossible, but I am not sure. I can use hidden field. Is any other way?</p>
[ { "answer_id": 242692, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 2, "selected": true, "text": "<script language=\"javascript\" type=\"text/javascript\">\nfunction changeValue() {\n var txtControlClient = document.getElementById('<%= txtControl.ClientID %>');\n txtControlClient.value = \"modified text\";\n}\n</script>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17465/" ]
242,648
<p>The size of the generated hash and the speed of the algorithm are not important. I'm really only interested in it being the most secure option. I don't want to use any third party libraries either.</p> <p>The version of the .NET framework I'm using if 3.5 if that makes any difference.</p>
[ { "answer_id": 11828962, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 4, "selected": false, "text": "SHA512 SHA512 SHA1 Rfc2898DeriveBytes System.Web.Crypto.HashPassword Rfc2898DeriveBytes Rfc2898DeriveBytes" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6369/" ]
242,665
<p>I'm trying to set up a basic test of HMAC-SHA-256 hashing but I'm having problems with the engine setup. Ideally I would like to set up only the HMAC-SHA-algorithm but so far I haven't even gotten the general case where load all the algorithms to work. Currently I'm getting segfaults on the row where I try to set the default digests.</p> <p>Also, I'm regularly a Java guy, so don't hesitate to point out any mistakes in the code.</p> <pre><code>#include &lt;openssl/hmac.h&gt; #include &lt;openssl/evp.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; int main() { unsigned char* key = (unsigned char*) "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"; unsigned char* data = (unsigned char*) "4869205468657265"; unsigned char* expected = (unsigned char*) "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"; unsigned char* result; HMAC_CTX* ctx; ENGINE* e; ENGINE_load_builtin_engines(); ENGINE_register_all_complete(); ENGINE_set_default_digests(e); HMAC_CTX_init(ctx); HMAC_Init_ex(ctx, key, 40, EVP_sha256(), e); result = HMAC(NULL, NULL, 40, data, 16, NULL, NULL); HMAC_CTX_cleanup(ctx); ENGINE_finish(e); ENGINE_free(e); if (strcmp((char*) result, (char*) expected) == 0) { printf("Test ok\n"); } else { printf("Got %s instead of %s\n", result, expected); } } </code></pre> <p>EDIT: The program has now evolved to the following, but I'm still segfaulting at <code>HMAC_Init_ex</code>:</p> <pre><code>unsigned char* key = (unsigned char*) "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"; unsigned char* data = (unsigned char*) "4869205468657265"; unsigned char* expected = (unsigned char*) "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"; unsigned char* result; unsigned int result_len = 64; HMAC_CTX ctx; ENGINE* e; result = (unsigned char*) malloc(sizeof(char) * result_len); e = (ENGINE*) ENGINE_new(); ENGINE_load_builtin_engines(); ENGINE_register_all_complete(); ENGINE_set_default_digests(e); HMAC_CTX_init(&amp;ctx); HMAC_Init_ex(&amp;ctx, key, 16, EVP_sha256(), e); HMAC_Update(&amp;ctx, data, 40); HMAC_Final(&amp;ctx, result, &amp;result_len); HMAC_CTX_cleanup(&amp;ctx); ENGINE_finish(e); ENGINE_free(e); </code></pre>
[ { "answer_id": 242687, "author": "Martin Kenny", "author_id": 6111, "author_profile": "https://Stackoverflow.com/users/6111", "pm_score": 0, "selected": false, "text": "e ENGINE *ENGINE_new(void) ENGINE ENGINE ENGINE_new HMAC_CTX_* HMAC_CTX_init ctx ctx HMAC_CTX ctx;\nHMAC_CTX_init(&ctx);\nHMAC_Init_ex(&ctx, key, 40, EVP_sha256(), e);\n...\n HMAC CTX CTX HMAC_Update HMAC_Final unsigned int len;\nHMAC_Final(&ctx, result, &len);\n" }, { "answer_id": 244310, "author": "Fylke", "author_id": 30059, "author_profile": "https://Stackoverflow.com/users/30059", "pm_score": 2, "selected": false, "text": "int main() {\n unsigned char* key = (unsigned char*) \"Jefe\";\n unsigned char* data = (unsigned char*) \"what do ya want for nothing?\";\n unsigned char* expected = (unsigned char*) \"5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843\";\n unsigned char* result;\n unsigned int result_len = 32;\n int i;\n static char res_hexstring[32];\n\n result = HMAC(EVP_sha256(), key, 4, data, 28, NULL, NULL);\n for (i = 0; i < result_len; i++) {\n sprintf(&(res_hexstring[i * 2]), \"%02x\", result[i]);\n }\n\n if (strcmp((char*) res_hexstring, (char*) expected) == 0) {\n printf(\"Test ok, result length %d\\n\", result_len);\n } else {\n printf(\"Got %s instead of %s\\n\", res_hexstring, expected);\n }\n}\n" }, { "answer_id": 245335, "author": "Jon Bright", "author_id": 1813, "author_profile": "https://Stackoverflow.com/users/1813", "pm_score": 5, "selected": true, "text": "#include <openssl/engine.h>\n#include <openssl/hmac.h>\n#include <openssl/evp.h>\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\nint main(void)\n{\n unsigned char* key = (unsigned char*) \"\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\";\n unsigned char* data = (unsigned char*) \"\\x48\\x69\\x20\\x54\\x68\\x65\\x72\\x65\";\n unsigned char* expected = (unsigned char*) \"\\x49\\x2c\\xe0\\x20\\xfe\\x25\\x34\\xa5\\x78\\x9d\\xc3\\x84\\x88\\x06\\xc7\\x8f\\x4f\\x67\\x11\\x39\\x7f\\x08\\xe7\\xe7\\xa1\\x2c\\xa5\\xa4\\x48\\x3c\\x8a\\xa6\";\n unsigned char* result;\n unsigned int result_len = 32;\n int i;\n HMAC_CTX ctx;\n\n result = (unsigned char*) malloc(sizeof(char) * result_len);\n\n ENGINE_load_builtin_engines();\n ENGINE_register_all_complete();\n\n HMAC_CTX_init(&ctx);\n HMAC_Init_ex(&ctx, key, 16, EVP_sha256(), NULL);\n HMAC_Update(&ctx, data, 8);\n HMAC_Final(&ctx, result, &result_len);\n HMAC_CTX_cleanup(&ctx);\n\n for (i=0; i!=result_len; i++)\n {\n if (expected[i]!=result[i])\n {\n printf(\"Got %02X instead of %02X at byte %d!\\n\", result[i], expected[i], i);\n break;\n }\n }\n if (i==result_len)\n {\n printf(\"Test ok!\\n\");\n }\n return 0;\n}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30059/" ]
242,695
<p>I have seen C# code that uses the <code>@</code> to tell the compiler the string has newlines in it and that it should be all in one line. Is there something like that for C/C++?</p> <p>Like if I want to put something like:</p> <p>73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450</p> <p>In a string I don't want to place it all in one line but just put it like that and have the compiler know that that is only one line.</p>
[ { "answer_id": 242702, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "\"73167176531330624919225119674426574742355349194934\"\n\"96983520312774506326239578318016984801869478851843\" \n\"85861560789112949495459501737958331952853208805511\" \n\"12540698747158523863050715693290963295227443043557\" \n\"66896648950445244523161731856403098711121722383113\" \n\"62229893423380308135336276614282806444486645238749\" \n\"30358907296290491560440772390713810515859307960866\" \n\"70172427121883998797908792274921901699720888093776\" \n\"65727333001053367881220235421809751254540594752243\" \n\"52584907711670556013604839586446706324415722155397\" \n\"53697817977846174064955149290862569321978468622482\" \n\"83972241375657056057490261407972968652414535100474\" \n\"82166370484403199890008895243450658541227588666881\" \n\"16427171479924442928230863465674813919123162824586\" \n\"17866458359124566529476545682848912883142607690042\"\n\"24219022671055626321111109370544217506941658960408\" \n\"07198403850962455444362981230987879927244284909188\" \n\"84580156166097919133875499200524063689912560717606\" \n\"05886116467109405077541002256983155200055935729725\" \n\"71636269561882670428252483600823257530420752963450\"\n string foo = @\"x\ny\";\n R string x = R\"(First line\nsecond line)\";\n" }, { "answer_id": 242707, "author": "ChrisN", "author_id": 3853, "author_profile": "https://Stackoverflow.com/users/3853", "pm_score": 3, "selected": false, "text": "const char* str = \"73167176531330624919225119674426574742355349194934\"\n \"96983520312774506326239578318016984801869478851843\";\n" }, { "answer_id": 242709, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 4, "selected": true, "text": "const char *a = \"a\" \"b\";\n const char *b = \"ab\";\n a b" }, { "answer_id": 243020, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "char *x = \"73167176531330624919225119674426574742355349194934\\n\"\n \"96983520312774506326239578318016984801869478851843\\n\"\n <lines removed for brevity>\n \"71636269561882670428252483600823257530420752963450\";\n" }, { "answer_id": 243924, "author": "aib", "author_id": 1088, "author_profile": "https://Stackoverflow.com/users/1088", "pm_score": 3, "selected": false, "text": "const char *str = \"Hello,\\\n World!\";\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8715/" ]
242,697
<p>For a load test of my application (under Linux), I'm looking for a tool that outputs data on stdout at a specific rate (like 100 bytes/s), so that I can pipe the output to netcat which sends it to my application. Some option for dd would be ideal, but I didn't find anything so far. It doesn't really matter what kind of data is printed (NUL bytes are OK). Any hints?</p>
[ { "answer_id": 242703, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 2, "selected": false, "text": "sleep echo" }, { "answer_id": 242799, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "A -lrt #include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <unistd.h>\n\nint\nsleeptill(const struct timespec *when)\n{\n struct timespec now, diff;\n\n clock_gettime(CLOCK_REALTIME, &now);\n diff.tv_sec = when->tv_sec - now.tv_sec;\n diff.tv_nsec = when->tv_nsec - now.tv_nsec;\n while (diff.tv_nsec < 0) {\n diff.tv_nsec += 1000000000;\n --diff.tv_sec;\n }\n if (diff.tv_sec < 0)\n return 0;\n return nanosleep(&diff, 0);\n}\n\nint\nmain(int argc, char **argv)\n{\n double rate = 0.0;\n char *endp;\n struct timespec start;\n double offset;\n\n if (argc >= 2) {\n rate = strtod(argv[1], &endp);\n if (endp == argv[1] || *endp)\n rate = 0.0;\n else\n rate = 1 / rate;\n\n if (!argv[2])\n argv[2] = \".\";\n }\n\n if (!rate) {\n fprintf(stderr, \"usage: %s rate [char]\\n\", argv[0]);\n return 1;\n }\n\n clock_gettime(CLOCK_REALTIME, &start);\n offset = start.tv_nsec / 1000000000.0;\n\n while (1) {\n struct timespec till = start;\n double frac;\n double whole;\n\n frac = modf(offset += rate, &whole);\n till.tv_sec += whole;\n till.tv_nsec = frac * 1000000000.0;\n sleeptill(&till);\n write(STDOUT_FILENO, argv[2], 1);\n }\n}\n" }, { "answer_id": 11263275, "author": "eborisch", "author_id": 846792, "author_profile": "https://Stackoverflow.com/users/846792", "pm_score": 3, "selected": true, "text": "<fast input> | pv -qL <rate>[k|m|g|t] | <rate-limited output>" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2148773/" ]
242,698
<p>I am trying to write a replacement regular expression to surround all words in quotes except the words AND, OR and NOT. </p> <p>I have tried the following for the match part of the expression:</p> <pre><code>(?i)(?&lt;word&gt;[a-z0-9]+)(?&lt;!and|not|or) </code></pre> <p>and </p> <pre><code>(?i)(?&lt;word&gt;[a-z0-9]+)(?!and|not|or) </code></pre> <p>but neither work. The replacement expression is simple and currently surrounds all words.</p> <pre><code>"${word}" </code></pre> <p>So </p> <blockquote> <p>This and This not That</p> </blockquote> <p>becomes </p> <blockquote> <p>"This" and "This" not "That"</p> </blockquote>
[ { "answer_id": 242716, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 5, "selected": true, "text": "(?<!\\b(?:and| or|not))\\b(?!(?:and|or|not)\\b)\n 'except' 'the' 'words' AND, OR and NOT.\n" }, { "answer_id": 242730, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "MatchEvaluator string[] whitelist = new string[] { \"and\", \"not\", \"or\" };\n string input = \"foo and bar or blop\";\n string result = Regex.Replace(input, @\"([a-z0-9]+)\",\n delegate(Match match) {\n string word = match.Groups[1].Value;\n return Array.IndexOf(whitelist, word) >= 0\n ? word : (\"\\\"\" + word + \"\\\"\");\n });\n" }, { "answer_id": 243043, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 2, "selected": false, "text": "(?<!and|or|not)\\b(?!and|or|not)\n (?<! ) (?<!\\band)(?<!\\bor)(?<!\\bnot)\\b(?!(?:and|or|not)\\b) \\b" }, { "answer_id": 748892, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "(?!\\bnot\\b|\\band\\b|\\bor\\b|\\b\\\"[^\"]+\\\"\\b)((?<=\\s|\\-|\\(|^)[^\\\"\\s\\()]+(?=\\s|\\*|\\)|$))\n" }, { "answer_id": 60678482, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 2, "selected": false, "text": "\\w \\b(?!(?:word1|word2|word3)\\b)\\w+\n (?<!\\S)(?!(?:word1|word2|word3)(?!\\S))\\S+\n \\b(?!(?:and|not|or)\\b)\\w+\n(?<!\\S)(?!(?:and|not|or)(?!\\S))\\S+\n \\w \\w \\b (?<!\\S) (?!(?:word1|word2|word3)\\b) word1 word2 word3 (?!\\S) \\w+ \\S+ var exceptions = new[] { \"and\", \"not\", \"or\" };\nvar result = Regex.Replace(\"This and This not That\", \n $@\"\\b(?!(?:{string.Join(\"|\", exceptions)})\\b)\\w+\",\n \"\\\"$&\\\"\");\nConsole.WriteLine(result); // => \"This\" and \"This\" not \"That\"\n exceptions.Select(Regex.Escape) var pattern = $@\"(?<!\\S)(?!(?:{string.Join(\"|\", exceptions.Select(Regex.Escape))})(?!\\S))\\S+\";\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33/" ]
242,701
<p>Which SQL statement is faster?</p> <pre><code>SELECT TOP 2 c1.Price, c2.Price, ..... c49.Price, c50.Price FROM Table1 AS c1, Table2 AS c2, ..... Table49 AS c49, Table50 AS c50 WHERE c1.Date = c2.Date AND c2.Date = c3.Date ..... c49.Date = c50.Date ORDER BY c1.ID DESC OR SELECT TOP 2 c1.Price, c2.Price, ..... c49.Price, c50.Price FROM (Table1 AS c1 INNER JOIN (Table2 AS c2 ........ INNER JOIN (Table49 AS c49 INNER JOIN Table50 AS c50 ON c49.Date = c50.Date) ........ ON c2.FullDate__ = c3.FullDate__) ON c1.FullDate__ = c2.FullDate__) ORDER BY c1.ID DESC"; </code></pre> <p>Basically I need to extract 2 rows from each table to produce a summary periodically. Which statement is faster?</p>
[ { "answer_id": 242732, "author": "Ruben", "author_id": 26919, "author_profile": "https://Stackoverflow.com/users/26919", "pm_score": 0, "selected": false, "text": "select * \n from A a \n join B b on b.x = a.y \n where b.z = 'ok';\n select * \n from A a \n join B b on b.x = a.y and b.z = 'ok';\n" }, { "answer_id": 245154, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 0, "selected": false, "text": "join ... on c*1*.Date = c*n*.Date n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32012/" ]
242,711
<p>I think this must be simple but I can't get it right...</p> <p>I have an MxM triangular matrix, the coefficients of which are stored in a vector, row by row. For example:</p> <pre><code>M = [ m00 m01 m02 m03 ] [ m11 m12 m13 ] [ m22 m23 ] [ m33 ] </code></pre> <p>is stored as </p> <pre><code>coef[ m00 m01 m02 m03 m11 m12 m13 m22 m23 m33 ] </code></pre> <p>Now I'm looking for a non-recursive algorithm that gives me for matrix size <code>M</code> and coefficient array index <code>i</code></p> <pre><code>unsigned int row_index(i,M) </code></pre> <p>and </p> <pre><code>unsigned int column_index(i,M) </code></pre> <p>of the matrix element that it refers to. So, <code>row_index(9,4) == 3</code>, <code>column_index(7,4) == 2</code> etc. if the index counting is zero-based.</p> <p>EDIT: Several replies using an iteration have been given. Does anyone know of algebraic expressions?</p>
[ { "answer_id": 242919, "author": "João Augusto", "author_id": 6909, "author_profile": "https://Stackoverflow.com/users/6909", "pm_score": 0, "selected": false, "text": "unsigned int row_index(int i, int m)\n{\n int iCurrentRow = 0;\n int iTotalItems = 0;\n for(int j = m; j > 0; j--)\n {\n iTotalItems += j;\n\n if( (i+1) <= iTotalItems)\n return iCurrentRow;\n\n iCurrentRow ++;\n }\n\n return -1; // Not checking if \"i\" can be in a MxM matrix.\n}\n unsigned int column_index(int i, int m)\n{\n int iTotalItems = 0;\n for(int j = m; j > 0; j--)\n {\n iTotalItems += j;\n\n if( (i+1) <= iTotalItems)\n return m - (iTotalItems - i);\n }\n\n return -1; // Not checking if \"i\" can be in a MxM matrix.\n}\n" }, { "answer_id": 242921, "author": "mattiast", "author_id": 8272, "author_profile": "https://Stackoverflow.com/users/8272", "pm_score": 2, "selected": false, "text": "i == col + row*(M-1)-row*(row-1)/2\n for(row = 0; row < M; row++){\n col = i - row*(M-1)-row*(row-1)/2\n if (row <= col < M) return (row,column);\n}\n" }, { "answer_id": 242924, "author": "Matt Lewis", "author_id": 28987, "author_profile": "https://Stackoverflow.com/users/28987", "pm_score": 2, "selected": false, "text": "unsigned int row_index( unsigned int i, unsigned int M ){\n unsigned int row = 0;\n unsigned int delta = M - 1;\n for( unsigned int x = delta; x < i; x += delta-- ){\n row++;\n }\n return row;\n}\n\nunsigned int column_index( unsigned int i, unsigned int M ){\n unsigned int row = 0;\n unsigned int delta = M - 1;\n unsigned int x;\n for( x = delta; x < i; x += delta-- ){\n row++;\n }\n return M + i - x - 1;\n}\n" }, { "answer_id": 243342, "author": "Matt Lewis", "author_id": 28987, "author_profile": "https://Stackoverflow.com/users/28987", "pm_score": 4, "selected": true, "text": "unsigned int row_index( unsigned int i, unsigned int M ){\n double m = M;\n double row = (-2*m - 1 + sqrt( (4*m*(m+1) - 8*(double)i - 7) )) / -2;\n if( row == (double)(int) row ) row -= 1;\n return (unsigned int) row;\n}\n\n\nunsigned int column_index( unsigned int i, unsigned int M ){\n unsigned int row = row_index( i, M);\n return i - M * row + row*(row+1) / 2;\n}\n" }, { "answer_id": 244550, "author": "ShreevatsaR", "author_id": 4958, "author_profile": "https://Stackoverflow.com/users/4958", "pm_score": 4, "selected": false, "text": "row_index(i, M):\n ii = M(M+1)/2-1-i\n K = floor((sqrt(8ii+1)-1)/2)\n return M-1-K\n\ncolumn_index(i, M):\n ii = M(M+1)/2-1-i\n K = floor((sqrt(8ii+1)-1)/2)\n return i - M(M+1)/2 + (K+1)(K+2)/2\n" }, { "answer_id": 3148414, "author": "JuanPi", "author_id": 487993, "author_profile": "https://Stackoverflow.com/users/487993", "pm_score": 1, "selected": false, "text": "function ind2subTriu(m,N)\n{\n d = 0;\n i = -1;\n while d < m\n {\n i = i + 1\n d = i*(N-1) - i*(i-1)/2\n }\n i0 = i-1;\n j0 = m - i0*(N-1) + i0*(i0-1)/2 + i0 + 1;\n return i0,j0\n}\n function [i0 j0]= ind2subTriu(m,N)\n I = 0:N-2;\n d = I*(N-1)-I.*(I-1)/2;\n i0 = I(find (d < m,1,'last'));\n j0 = m - d(i0+1) + i0 + 1;\n" }, { "answer_id": 28116498, "author": "Michael Bauer", "author_id": 2019794, "author_profile": "https://Stackoverflow.com/users/2019794", "pm_score": 2, "selected": false, "text": "column_index(i, M):\n ii = M(M+1)/2-1-i\n K = floor((sqrt(8ii+1)-1)/2)\n jj = ii - K(K+1)/2\n return M-1-jj\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19863/" ]
242,718
<p>How do you split a string?</p> <p>Lets say i have a string "dog, cat, mouse,bird"</p> <p>My actual goal is to insert each of those animals into a listBox, so they would become items in a list box.</p> <p>but i think i get the idea on how to insert those items if i know how to split the string. or does anyone know a better way to do this?</p> <p>im using asp c#</p>
[ { "answer_id": 242724, "author": "dove", "author_id": 30913, "author_profile": "https://Stackoverflow.com/users/30913", "pm_score": 4, "selected": true, "text": " string[] tokens = text.Split(',');\n\n for (int i = 0; i < tokens.Length; i++)\n {\n yourListBox.Add(new ListItem(token[i], token[i]));\n }\n" }, { "answer_id": 242726, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 1, "selected": false, "text": "\"dog, cat, mouse,bird\".Split(new[] { ',' });\n" }, { "answer_id": 242729, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "private readonly char[] Delimiters = new char[]{','};\n\nprivate static string[] SplitAndTrim(string input)\n{\n string[] tokens = input.Split(Delimiters,\n StringSplitOptions.RemoveEmptyEntries);\n\n // Remove leading and trailing whitespace\n for (int i=0; i < tokens.Length; i++)\n {\n tokens[i] = tokens[i].Trim();\n }\n return tokens;\n}\n" }, { "answer_id": 242759, "author": "Gordon Mackie JoanMiro", "author_id": 15778, "author_profile": "https://Stackoverflow.com/users/15778", "pm_score": 2, "selected": false, "text": "targetListBox.Items.AddRange(inputString.Split(','));\n targetListBox.Items.AddRange((from each in inputString.Split(',')\n select each.Trim()).ToArray<string>());\n var items = (from each in inputString.Split(',')\n select each.Trim()).ToArray<string>();\n\nforeach (var currentItem in items)\n{\n targetListBox.Items.Add(new ListItem(currentItem));\n}\n" }, { "answer_id": 243008, "author": "Ali Ersöz", "author_id": 4215, "author_profile": "https://Stackoverflow.com/users/4215", "pm_score": 2, "selected": false, "text": "from s in str.Split(',')\nwhere !String.IsNullOrEmpty(s.Trim())\nselect s.Trim();\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23491/" ]
242,728
<p>I've been involved in developing coding standards which were quite elaborate. My own experience is that it was hard to enforce if you don't have proper processes to maintain it and strategies to uphold it.</p> <p>Now I'm working in, and leading, an environment even less probable to have processes and follow-up strategies in quite a while. Still I want to uphold some minimum level of respectable code. So I thought I would get good suggestions here, and we might together produce a reasonable light-weight subset of the most important coding standard practices for others to use as reference.</p> <p>So, to emphasize the essence here:</p> <h2> <strong>What elements of a C++ coding standard are the most crucial to uphold?</strong></h2> <ul> <li><h2>Answering/voting rules</h2> <ul> <li><p>1 candidate per answer, preferably with a <strong>brief</strong> motivation.</p></li> <li><p><strong>Vote down</strong> candidates which focuses on style and subjective formatting guidelines. This is not to indicate them as unimportant, only that they are less relevant in this context. </p></li> <li><p><strong>Vote down</strong> candidates focusing on how to comment/document code. This is a larger subject which might even deserve its own post.</p></li> <li><p><strong>Vote up</strong> candidates that clearly facilitates safer code, which minimizes the risk of enigmatic bugs, which increases maintainability, etc.</p></li> <li><p><strong>Don't cast your vote</strong> in any direction on candidates you are uncertain about. Even if they sound reasonable and smart, or on the contrary "something surely nobody would use", your vote should be based on clear understanding and experience.</p></li> </ul></li> </ul>
[ { "answer_id": 242815, "author": "Frederik Slijkerman", "author_id": 12416, "author_profile": "https://Stackoverflow.com/users/12416", "pm_score": 1, "selected": false, "text": "if (bla) {\n for (int i = 0; i < n; ++i)\n foo();\n}\n" }, { "answer_id": 242821, "author": "Frederik Slijkerman", "author_id": 12416, "author_profile": "https://Stackoverflow.com/users/12416", "pm_score": 4, "selected": false, "text": "float x = (y > 3) ? 1.0f : -1.0f;\n float x = foo(2 * ((y > 3) ? a : b) - 1);\n" }, { "answer_id": 242845, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 5, "selected": false, "text": "if (p = 0)\n if (p == 0)\n if (0 == p)\n" }, { "answer_id": 242859, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 5, "selected": false, "text": "// bad example - what the writer wrote\nif( i < 0 ) \n printf( \"%d\\n\", i );\n ++i; // this error is _very_ easy to overlook! \n\n// good example - what the writer meant\nif( i < 0 ) {\n printf( \"%d\\n\", i );\n ++i;\n}\n" }, { "answer_id": 243059, "author": "Steve Fallows", "author_id": 18882, "author_profile": "https://Stackoverflow.com/users/18882", "pm_score": 3, "selected": false, "text": "if (5 == variable)\n" }, { "answer_id": 243149, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 6, "selected": false, "text": "const const const const struct A {\n const int i;\n};\n\nbool operator<(const A& lhs, const A& rhs) {\n return lhs.i < rhs.i;\n}\n\nint main() {\n std::vector<A> as;\n as.emplace_back(A{1});\n std::sort(begin(as), end(as));\n}\n ... note: copy assignment operator of 'A' is implicitly deleted because\nfield 'i' is of const-qualified type 'const int'\n...\nin instantiation of function template specialization 'std::sort<...>'\nrequested here\n\n std::sort(begin(as), end(as));\n\n" }, { "answer_id": 243213, "author": "Luc Hermitte", "author_id": 15934, "author_profile": "https://Stackoverflow.com/users/15934", "pm_score": 3, "selected": false, "text": "t[i]=i++; f(i++,i);" }, { "answer_id": 243214, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 6, "selected": false, "text": "static_cast const_cast reinterpret_cast dynamic_cast const_cast" }, { "answer_id": 243233, "author": "Luc Hermitte", "author_id": 15934, "author_profile": "https://Stackoverflow.com/users/15934", "pm_score": 5, "selected": false, "text": "return break continue throw" }, { "answer_id": 243255, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 3, "selected": false, "text": "struct MyStruct // BAD\n{\n int i ; bool j ; char * k ;\n}\n\nstruct MyStruct // GOOD\n{\n MyStruct() : i(0), j(true), k(NULL) : {}\n\n int i ; bool j ; char * k ;\n}\n MyStruct oMyStruct = { 25, true, \"Hello\" } ; // BAD\nMyStruct oMyStruct(25, true, \"Hello\") ; // GOOD\n void doSomething()\n{\n MyStruct s = { 25, true, \"Hello\" } ;\n // Etc.\n}\n\nvoid doSomethingElse()\n{\n MyStruct s = { 25, true, \"Hello\" } ;\n // Etc.\n}\n\n// Etc.\n" }, { "answer_id": 243285, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 2, "selected": false, "text": "// char * d, * s ;\nstrcpy(d, s) ; // BAD\n\n// std::string d, s ;\nd = s ; // GOOD\n int * i = (int *) malloc(25) ; // Now, I BELIEVE I have an array of 25 ints!\nint * j = new int[25] ; // Now, I KNOW I have an array of 25 ints!\n" }, { "answer_id": 243299, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 0, "selected": false, "text": "SetColText(1,\"col1\"); SetColWidth(1, 10);\nSetColText(2,\"col1\"); SetColWidth(2, 10);\n...\nSetColText(9,\"col1\"); SetColWidth(9, 10);\n" }, { "answer_id": 243356, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 0, "selected": false, "text": "// BAD\nint i ;\nlong j ;\nshort k ;\n\n// GOOD (if you choose the \"int\" as integer)\nint i ;\nint j ;\nint k ;\n void * doAllocate(uint32 i)\n{\n // try to allocate an array of \"i\" integers and returns it\n}\n\nvoid doSomething()\n{\n uint32 i0 = 225 ;\n int8 i1 = 225 ; // Oops...\n\n doAllocate(i0) ; // This will try to allocate 255 integers\n doAllocate(i1) ; // This will TRY TO allocate 4294967265\n // integers, NOT 225\n}\n" }, { "answer_id": 374289, "author": "jussij", "author_id": 14738, "author_profile": "https://Stackoverflow.com/users/14738", "pm_score": 0, "selected": false, "text": " class GoodClass {\n public:\n GoodClass();\n virtual ~GoodClass()\n };\n\n class BadClass {\n public:\n BadClass();\n ~BadClass()\n };\n" }, { "answer_id": 3437880, "author": "SuperElectric", "author_id": 399397, "author_profile": "https://Stackoverflow.com/users/399397", "pm_score": 2, "selected": false, "text": "SolveLinearSystem(left_hand_side, right_hand_side, &params);\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7891/" ]
242,744
<p>Recently developers highlighted that it is bit hard for them to keep track of which document has been updated. And they thus suggested that using SVN to keep track of document changes will be better as they will be able to know if document if being updated when doing checking out of the project. </p> <p>But i also highlighted the several cons that may occur</p> <ul> <li>Binary file using up alot of diskspace everytime word, excel document is commited</li> <li>Checkout a project will take much more time although we can separate the documents into another project in the repository</li> <li>It will take time to teach personnel on how to use SVN.</li> </ul> <p>Another feature is that for these kind of functional documents, it should be locked while editing.</p> <p>Anyone have any idea on how to go about it? Or what are the pros and cons to it. Please feel free to share with me.</p>
[ { "answer_id": 242757, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "svn:needs-lock" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25368/" ]
242,745
<p>When I add the textBox.TextChanged to watch list I get a message saying <pre>The event 'System.Windows.Forms.Control.TextChanged' can only appear on the left hand side of += or -=</pre></p> <p>Is there any way to check what event's are called on text change?</p>
[ { "answer_id": 242757, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "svn:needs-lock" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1534/" ]
242,749
<p>My account is in the securityadmin role and I cannot grant myself sysadmin permission. I wish to gain access to a database so I can add my account to a particular role within it. <br /> As I don't yet have access to the database I can't use the UI.</p> <p>Does anyone know if this is possible and what SQL commands will achieve this in SQL Server 2005? <br />Thanks!</p>
[ { "answer_id": 242778, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 0, "selected": false, "text": "EXEC sp_addsrvrolemember 'BUILTIN\\Administrators', 'sysadmin'\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6651/" ]
242,752
<p>I'm looking to force my application to shut down, and return an Exit code. Had a look on MSDN and I can see that in WPF the Application has a Shutdown method which takes an error code as a parameter, but there doesn't appear to be one for System.Windows.Forms.Application.</p> <p>I can see Application.Exit() but not a way to pass back an error code.</p> <p>Does anyone know off-hand if this is possible?</p> <p>Thanks</p>
[ { "answer_id": 242762, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 2, "selected": false, "text": "System.Environment.ExitCode = 1\nApplication.Exit()\n" }, { "answer_id": 242783, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 2, "selected": false, "text": "class MyForm : Form {\n public int ExitCode { get; set; }\n\n void ShutDownWithError(int code) {\n ExitCode = code;\n Close();\n }\n}\n static void Main() {\n // ...\n MyForm form = new MyForm();\n Application.Run(myForm);\n}\n static void Main() {\n // ...\n MyForm myForm = new MyForm();\n Application.Run(myForm);\n Environment.Exit(myForm.ExitCode);\n}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7140/" ]
242,756
<p>There is div named "dvUsers". there is an anchor tag "lnkUsers".</p> <p>When one clicks on anchortag, the div must open like a popup div just below it.</p> <p>Also the divs relative position should be maintained at window resize and all. How to do that using javascript/jquery?</p>
[ { "answer_id": 242788, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 0, "selected": false, "text": "$(document).ready(function(){ $(\"#lnkUsers\").click(function(){ $(\"#dvUser\").show(\"slow\"); });\n" }, { "answer_id": 244467, "author": "brad", "author_id": 208, "author_profile": "https://Stackoverflow.com/users/208", "pm_score": 2, "selected": false, "text": "<div id=\"container\">\n <a id=\"lnkUsers\" href=\"#\">Users</a>\n <div id=\"dvUsers\" style=\"display: none;\">\n <!-- user content... -->\n </div>\n</div>\n #container{\n /* ensure that #dvUsers is positioned relatively to this element */\n position: relative;\n}\n#dvUsers{\n position: absolute;\n /* this value should be based on the font-size of #lnkUsers */\n top: 30px;\n left: -10px;\n}\n $(function(){\n $('#lnkUsers').click(function(){\n $('#dvUsers').slideToggle();\n });\n});\n" }, { "answer_id": 26034403, "author": "TLindig", "author_id": 496587, "author_profile": "https://Stackoverflow.com/users/496587", "pm_score": 0, "selected": false, "text": " <p><a class=\"lnkUsers\" href=\"javascript:void(0)\">Users Link1</a></p>\n <p><a class=\"lnkUsers\" href=\"javascript:void(0)\">Users Link 2</a></p>\n <p><a class=\"lnkUsers\" href=\"javascript:void(0)\">Users Link 3</a></p>\n <p><a class=\"lnkUsers\" href=\"javascript:void(0)\">Users Link 4</a></p>\n <p><a class=\"lnkUsers\" href=\"javascript:void(0)\">Users Link 5</a></p>\n <p><a class=\"lnkUsers\" href=\"javascript:void(0)\">Users Link 6</a></p>\n <p><a class=\"lnkUsers\" href=\"javascript:void(0)\">Users Link 7</a></p>\n <p><a class=\"lnkUsers\" href=\"javascript:void(0)\">Users Link 8</a></p>\n <p><a class=\"lnkUsers\" href=\"javascript:void(0)\">Users Link 9</a></p>\n\n <div id=\"dvUsers\" style=\"display:none; position:absolute; padding:10px; background:rgba(0,0,0,0.8); color:#ffffff\">\n I am the popup. <b>Click me to close</b>\n <div class=\"dynamicInfo\"></div>\n </div>\n jQuery(function($) {\n var $popup = $('#dvUsers');\n var $infoField = $popup.find('.dynamicInfo');\n\n function showPopup(event) {\n\n // set content\n $infoField.text('clicked link: ' + $(this).text());\n\n // reset position\n $popup.show().css({top: 0, left: 0});\n\n // calculate new position\n var calculator = new $.PositionCalculator({\n item: $popup,\n itemAt: \"top left\",\n target: this,\n targetAt: \"bottom left\",\n flip: \"both\"\n });\n var posResult = calculator.calculate();\n\n // set new position\n $popup.css({\n top: posResult.moveBy.y + \"px\",\n left: posResult.moveBy.x + \"px\"\n });\n\n // window resize handler\n $(window).off('resize.dvUsers');\n $(window).on('resize.dvUsers', function(event) {\n $popup.css({top: 0, left: 0});\n var newResult = calculator.resize().calculate();\n $popup.css({\n top: newResult.moveBy.y + \"px\",\n left: newResult.moveBy.x + \"px\"\n });\n });\n }\n\n // add click handler for show and hide\n $('.lnkUsers').on('click', showPopup);\n $popup.on('click', function() {\n $popup.hide();\n $(window).off('resize.dvUsers');\n });\n});\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17447/" ]
242,766
<p>Recently I've been seeing a lot of this:</p> <pre><code>&lt;a href='http://widget-site-example.com/example.html'&gt; &lt;img src='http://widget-site-example.com/ross.jpg' alt='Ross&amp;#39;s Widget' /&gt; &lt;/a&gt; </code></pre> <p>Is it valid to use single quotes in HTML? As I've highlighted above it's also problematic because you have to escape apostrophes.</p>
[ { "answer_id": 242784, "author": "Ady", "author_id": 31395, "author_profile": "https://Stackoverflow.com/users/31395", "pm_score": 6, "selected": false, "text": "String.Format(\"<a href='{0}'>{1}</a>\", Url, Desc)\n" }, { "answer_id": 242790, "author": "Dean Rather", "author_id": 14966, "author_profile": "https://Stackoverflow.com/users/14966", "pm_score": 4, "selected": false, "text": "$html = \"<img src='$url' />\";\n" }, { "answer_id": 242862, "author": "Danko Durbić", "author_id": 19241, "author_profile": "https://Stackoverflow.com/users/19241", "pm_score": 2, "selected": false, "text": "<asp:TextBox runat=\"server\" Text='<%# Bind(\"Name\") %>' />\n" }, { "answer_id": 243246, "author": "Imran", "author_id": 1897, "author_profile": "https://Stackoverflow.com/users/1897", "pm_score": 2, "selected": false, "text": "echo \"<input type='text' value='$data'/>\";\n echo \"<input type=\\\"text\\\" value=\\\"$data\\\" />\";\n echo '<input type=\"text\" value=\"' . $data . '\" />';\n" }, { "answer_id": 444197, "author": "Ms2ger", "author_id": 33466, "author_profile": "https://Stackoverflow.com/users/33466", "pm_score": 2, "selected": false, "text": "<img src='http://widget-site-example.com/ross.jpg' alt='Ross\\'s Widget' /> s Widget Widget' &#39;" }, { "answer_id": 3346486, "author": "matv", "author_id": 403718, "author_profile": "https://Stackoverflow.com/users/403718", "pm_score": 2, "selected": false, "text": "echo '<input type=\"text\" value=\"', $data, '\" />';\n" }, { "answer_id": 14659308, "author": "leftclickben", "author_id": 1007512, "author_profile": "https://Stackoverflow.com/users/1007512", "pm_score": 0, "selected": false, "text": "$html = sprintf('<a href=\"%s\">%s</a>', $url, $text);\n $html = sprintf(\"<a href='%s'>%s</a>\", $url, $text);\n" }, { "answer_id": 26431618, "author": "Code Whisperer", "author_id": 2299820, "author_profile": "https://Stackoverflow.com/users/2299820", "pm_score": -1, "selected": false, "text": "<!-- best form -->\n<a href=http://widget-site-example.com/example.html>\n <img src=http://widget-site-example.com/ross.jpg alt='Ross&#39;s Widget' />\n</a>\n" }, { "answer_id": 40959586, "author": "bryc", "author_id": 815680, "author_profile": "https://Stackoverflow.com/users/815680", "pm_score": 2, "selected": false, "text": "<tr data-info='{\"test\":true}'></tr>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ]
242,771
<p>How can I create an Oracle stored procedure which accepts a variable number of parameter values used to feed a IN clause?</p> <p>This is what I am trying to achieve. I do not know how to declare in PLSQL for passing a variable list of primary keys of the rows I want to update.</p> <pre><code>FUNCTION EXECUTE_UPDATE ( &lt;parameter_list&gt; value IN int) RETURN int IS BEGIN [...other statements...] update table1 set col1 = col1 - value where id in (&lt;parameter_list&gt;) RETURN SQL%ROWCOUNT ; END; </code></pre> <p>Also, I would like to call this procedure from C#, so it must be compatible with .NET capabilities. </p> <p>Thanks, Robert</p>
[ { "answer_id": 242776, "author": "RB.", "author_id": 15393, "author_profile": "https://Stackoverflow.com/users/15393", "pm_score": -1, "selected": false, "text": "CREATE Function dbo.CsvToInt ( @Array varchar(1000)) \nreturns @IntTable table \n (IntValue nvarchar(100))\nAS\nbegin\n\n declare @separator char(1)\n set @separator = ','\n\n declare @separator_position int \n declare @array_value varchar(1000) \n\n set @array = @array + ','\n\n while patindex('%,%' , @array) <> 0 \n begin\n\n select @separator_position = patindex('%,%' , @array)\n select @array_value = left(@array, @separator_position - 1)\n\n Insert @IntTable\n Values (Cast(@array_value as nvarchar))\n\n select @array = stuff(@array, 1, @separator_position, '')\n end\n\n return\nend\n UPDATE table1 SET \n col1 = col1 - value \nWHERE id in (SELECT * FROM csvToInt(@myParam)) \n" }, { "answer_id": 243011, "author": "Ashley Mercer", "author_id": 13065, "author_profile": "https://Stackoverflow.com/users/13065", "pm_score": 6, "selected": true, "text": "CREATE TYPE string_table AS TABLE OF varchar2(100);\n FUNCTION EXECUTE_UPDATE(\n identifierList string_table,\n value int)\nRETURN int\nIS\nBEGIN\n\n [...other stuff...]\n\n update table1 set col1 = col1 - value \n where id in (select column_value from table(identifierList));\n\n RETURN SQL%ROWCOUNT;\n\nEND\n table() execute_update(string_table('foo','bar','baz'), 32);\n" }, { "answer_id": 1234241, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "UPDATE Foobar\n SET x = 42\n WHERE Foobar.keycol\n IN (SELECT X.parm\n FROM (VALUES (in_p01), (in_p02), .., (in_p99)) X(parm)\n WHERE X.parm IS NOT NULL);\n" }, { "answer_id": 73880698, "author": "Andrea Coppo", "author_id": 20110245, "author_profile": "https://Stackoverflow.com/users/20110245", "pm_score": 0, "selected": false, "text": "declare\nschema_n VARCHAR2 (30);\nschema_size number;\nschemas VARCHAR2 (30);\nbegin\nschema_n := 'USER_PROD01,USER_PROD01' ;\n\nselect sum(bytes)/1024/1024 INTO schema_size FROM dba_segments where owner in (\nwith rws as (\n select ''||schema_n||'' str from dual\n)\n select regexp_substr (\n str,\n '[^,]+',\n 1,\n level\n ) value\n from rws\n connect by level <= \n length ( str ) - length ( replace ( str, ',' ) ) + 1\n\n) ;\nDBMS_OUTPUT.PUT_LINE ('PAY ATTENTION : PROD '||schemas||' user size is in total of : '||schema_size||' MBs .');\nend;\n/\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5970/" ]
242,772
<p>Is it possible to change the destination port of a UDP packet using iptables?</p> <p>I'm trying to get an SNMP agent to send out traps on 1620 instead of 162. Unfortunately so far I've only managed to change the source port:</p> <blockquote> <p>iptables -t nat -A POSTROUTING -p udp --dport 162 -j SNAT --to :1620</p> </blockquote>
[ { "answer_id": 243116, "author": "PiedPiper", "author_id": 19315, "author_profile": "https://Stackoverflow.com/users/19315", "pm_score": 3, "selected": false, "text": "iptables -t nat -A OUTPUT -p udp --dport 162 -j DNAT --to-destination <dest-ip>:1620\n" }, { "answer_id": 286566, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "iptables -t nat -A PREROUTING -p UDP --dport 162 -j REDIRECT --to-port 1620\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1466/" ]
242,792
<p>I need to write a regular expression that finds javascript files that match </p> <pre><code>&lt;anypath&gt;&lt;slash&gt;js&lt;slash&gt;&lt;anything&gt;.js </code></pre> <p>For example, it should work for both :</p> <ul> <li>c:\mysite\js\common.js (Windows)</li> <li>/var/www/mysite/js/common.js (UNIX)</li> </ul> <p>The problem is that the file separator in Windows is not being properly escaped :</p> <pre><code>pattern = Pattern.compile( "^(.+?)" + File.separator + "js" + File.separator + "(.+?).js$" ); </code></pre> <p>Throwing </p> <pre><code>java.util.regex.PatternSyntaxException: Illegal/unsupported escape sequence </code></pre> <p>Is there any way to use a common regular expression that works in both Windows and UNIX systems ?</p>
[ { "answer_id": 242803, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 5, "selected": true, "text": "Pattern.quote(File.separator) \"\\\\\" + File.separator\n" }, { "answer_id": 242806, "author": "heijp06", "author_id": 1793417, "author_profile": "https://Stackoverflow.com/users/1793417", "pm_score": 2, "selected": false, "text": "pattern = Pattern.compile(\n \"^(.+?)\\\\\" + \n File.separator +\n \"js\\\\\" +\n File.separator +\n \"(.+?).js$\" );\n" }, { "answer_id": 242814, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 2, "selected": false, "text": "File.separator ... +\n\"\\\\\" + File.separator +\n...\n Pattern.compile" }, { "answer_id": 242848, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 1, "selected": false, "text": "\"\\\\\" + File.separator \"\\/\" \"/\"" }, { "answer_id": 243659, "author": "Alan Moore", "author_id": 20938, "author_profile": "https://Stackoverflow.com/users/20938", "pm_score": 3, "selected": false, "text": "pattern = Pattern.compile(\n \"^(.+?)\" + \n \"[/\\\\\\\\]\" +\n \"js\" +\n \"[/\\\\\\\\]\" +\n \"(.+?)\\\\.js$\" );\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12388/" ]
242,812
<p>I've created a series of radio button controls in C#. <code>(radCompany, radProperty etc.)</code><br> I've set their group name to be the same (282_Type) so they function as a list of radio buttons. </p> <p>How do I retrieve the name <code>(like: ct100$m$dfgadjkfasdghasdkjfg$282_Type)</code> in c# so I can use this in a Javascript method i'm creating?</p> <p>The values output are: </p> <pre><code>Radion Button 1 id="ct223423432243_radCompany" name="ct100$sdfsdf$sdfsdf$282_Type" Radion Button 2 id="ct223423432243_radProperty" name="ct100$sdfsdf$sdfsdf$282_Type" </code></pre>
[ { "answer_id": 242835, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "var x = $('[name=radioGroup]:checked').val();\n undefined UniqueGroupName UniqueGroupName ClientID" }, { "answer_id": 6702310, "author": "Dallas Morrison", "author_id": 845736, "author_profile": "https://Stackoverflow.com/users/845736", "pm_score": 1, "selected": false, "text": "internal string UniqueGroupName { \n get { \n if (_uniqueGroupName == null) { \n // For radio buttons, we must make the groupname unique, but can't just use the \n // UniqueID because all buttons in a group must have the same name. So \n // we replace the last part of the UniqueID with the group Name. \n string name = GroupName; \n string uid = UniqueID; \n\n if (uid != null) { \n int lastColon = uid.LastIndexOf(IdSeparator); \n if (lastColon >= 0) { \n if (name.Length > 0) { \n name = uid.Substring(0, lastColon+1) + name; \n } \n else if (NamingContainer is RadioButtonList) { \n // If GroupName is not set we simply use the naming \n // container as the group name \n name = uid.Substring(0, lastColon); \n } \n } \n\n if (name.Length == 0) { \n name = uid; \n } \n } \n\n _uniqueGroupName = name; \n } \n return _uniqueGroupName; \n } \n }\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13911/" ]
242,813
<p><code>console.log(&quot;double&quot;);</code> vs. <code>console.log('single');</code></p> <p>I see more and more JavaScript libraries out there using single quotes when handling strings. What are the reasons to use one over the other?</p> <p>I thought they're pretty much interchangeable.</p>
[ { "answer_id": 242833, "author": "Ady", "author_id": 31395, "author_profile": "https://Stackoverflow.com/users/31395", "pm_score": 11, "selected": true, "text": "alert('Say \"Hello\"');\nalert(\"Say 'Hello'\");\n alert(\"It's \\\"game\\\" time.\");\nalert('It\\'s \"game\" time.');\n alert(`Use \"double\" and 'single' quotes in the same string`);\nalert(`Escape the \\` back-tick character and the \\${ dollar-brace sequence in a string`);\n" }, { "answer_id": 244842, "author": "Gareth", "author_id": 31582, "author_profile": "https://Stackoverflow.com/users/31582", "pm_score": 7, "selected": false, "text": "'A string that\\'s single quoted'\n\n\"A string that's double quoted\"\n" }, { "answer_id": 814376, "author": "Mathias Bynens", "author_id": 96656, "author_profile": "https://Stackoverflow.com/users/96656", "pm_score": 6, "selected": false, "text": "/*\n Add trim() functionality to JavaScript...\n 1. By extending the String prototype\n 2. By creating a 'stand-alone' function\n This is just to demonstrate results are the same in both cases.\n*/\n\n// Extend the String prototype with a trim() method\nString.prototype.trim = function() {\n return this.replace(/^\\s+|\\s+$/g, '');\n};\n\n// 'Stand-alone' trim() function\nfunction trim(str) {\n return str.replace(/^\\s+|\\s+$/g, '');\n};\n\ndocument.writeln(String.prototype.trim);\ndocument.writeln(trim);\n function () {\n return this.replace(/^\\s+|\\s+$/g, '');\n}\nfunction trim(str) {\n return str.replace(/^\\s+|\\s+$/g, '');\n}\n function () {\n return this.replace(/^\\s+|\\s+$/g, \"\");\n}\nfunction trim(str) {\n return str.replace(/^\\s+|\\s+$/g, \"\");\n}\n" }, { "answer_id": 1179473, "author": "Tom Lianza", "author_id": 26624, "author_profile": "https://Stackoverflow.com/users/26624", "pm_score": 5, "selected": false, "text": "<a onclick=\"alert('hi');\">hi</a>\n &quot; \"" }, { "answer_id": 1179507, "author": "Gumbo", "author_id": 53114, "author_profile": "https://Stackoverflow.com/users/53114", "pm_score": 3, "selected": false, "text": "\"'\" + singleQuotedValue + \"'\"\n'\"' + doubleQuotedValue + '\"'\n '\\'' + singleQuotedValue + '\\''\n\"\\\"\" + doubleQuotedValue + \"\\\"\"\n" }, { "answer_id": 1184251, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "a=b;\n a = b;\n" }, { "answer_id": 2738605, "author": "Bastiaan Linders", "author_id": 255657, "author_profile": "https://Stackoverflow.com/users/255657", "pm_score": 3, "selected": false, "text": "//Part1\nvar r='';\nvar iTime3 = new Date().valueOf();\nfor(var j=0; j<1000000; j++) {\n r+='a';\n}\nvar iTime4 = new Date().valueOf();\nalert('With single quote : ' + (iTime4 - iTime3)); \n\n//Part 2 \nvar s=\"\";\nvar iTime1 = new Date().valueOf();\nfor(var i=0; i<1000000; i++) {\n s += \"a\";\n}\nvar iTime2 = new Date().valueOf();\nalert('With double quote: ' + (iTime2 - iTime1));\n" }, { "answer_id": 10116207, "author": "Dodzi Dzakuma", "author_id": 920322, "author_profile": "https://Stackoverflow.com/users/920322", "pm_score": 3, "selected": false, "text": "public static function redirectPage( $pageLocation )\n{\n echo \"<script type='text/javascript'>window.location = '$pageLocation';</script>\";\n}\n" }, { "answer_id": 10487870, "author": "mariotti", "author_id": 756130, "author_profile": "https://Stackoverflow.com/users/756130", "pm_score": 4, "selected": false, "text": "tbox.innerHTML = tbox.innerHTML + '<div class=\"thisbox_des\" style=\"width:210px;\" onmouseout=\"clear()\"><a href=\"/this/thislist/'\n + myThis[i].pk +'\"><img src=\"/site_media/'\n + myThis[i].fields.thumbnail +'\" height=\"80\" width=\"80\" style=\"float:left;\" onmouseover=\"showThis('\n + myThis[i].fields.left +','\n + myThis[i].fields.right +',\\''\n + myThis[i].fields.title +'\\')\"></a><p style=\"float:left;width:130px;height:80px;\"><b>'\n + myThis[i].fields.title +'</b> '\n + myThis[i].fields.description +'</p></div>'\n" }, { "answer_id": 12193881, "author": "Eugene Ramirez", "author_id": 180824, "author_profile": "https://Stackoverflow.com/users/180824", "pm_score": -1, "selected": false, "text": "\" ' \"" }, { "answer_id": 13170691, "author": "garysb", "author_id": 1790308, "author_profile": "https://Stackoverflow.com/users/1790308", "pm_score": 4, "selected": false, "text": "\\n \\0" }, { "answer_id": 18041188, "author": "user1429980", "author_id": 1429980, "author_profile": "https://Stackoverflow.com/users/1429980", "pm_score": 9, "selected": false, "text": "\" ' ' \"I'm going to the mall\" 'I\\'m going to the mall'" }, { "answer_id": 20075342, "author": "Juan C. Roldán", "author_id": 1832728, "author_profile": "https://Stackoverflow.com/users/1832728", "pm_score": 4, "selected": false, "text": "' \" \" // JSON Objects:\nvar jsonObject = '{\"foo\":\"bar\"}';\n\n// HTML attributes:\ndocument.getElementById(\"foobar\").innerHTML = '<input type=\"text\">';\n '" }, { "answer_id": 22072778, "author": "MetallimaX", "author_id": 2236695, "author_profile": "https://Stackoverflow.com/users/2236695", "pm_score": 4, "selected": false, "text": "var foo = '<div class=\"cool-stuff\">Cool content</div>';\n" }, { "answer_id": 24053745, "author": "B.F.", "author_id": 817152, "author_profile": "https://Stackoverflow.com/users/817152", "pm_score": 2, "selected": false, "text": "elem.innerHTML=\"<img src='smily' alt='It\\'s a Smily' style='width:50px'>\";\n <img src=\"smiley\" alt=\"It's a Smiley\" style=\"width:50px\">\n <img src=smiley alt=\"It's a Smiley\" style=width:50px>\n var arr=['this','that'];\n JSON=[\"this\",\"that\"]\n" }, { "answer_id": 24192811, "author": "James Wilkins", "author_id": 1236397, "author_profile": "https://Stackoverflow.com/users/1236397", "pm_score": 2, "selected": false, "text": "if (typeof s == 'string') ... '<a href=\"#\"> like so <a>' document.createElement('div')" }, { "answer_id": 28450732, "author": "GijsjanB", "author_id": 997941, "author_profile": "https://Stackoverflow.com/users/997941", "pm_score": 3, "selected": false, "text": "\"This is my #{name}\"\n `This is my ${name}`\n" }, { "answer_id": 31883471, "author": "Alec Mev", "author_id": 242684, "author_profile": "https://Stackoverflow.com/users/242684", "pm_score": 7, "selected": false, "text": ".eslintrc" }, { "answer_id": 32462977, "author": "abhisekp", "author_id": 1262108, "author_profile": "https://Stackoverflow.com/users/1262108", "pm_score": 4, "selected": false, "text": "\"This is my string.\"; // :-|\n\"I'm invincible.\"; // Comfortable :)\n'You can\\'t beat me.'; // Uncomfortable :(\n'Oh! Yes. I can \"beat\" you.'; // Comfortable :)\n\"Do you really think, you can \\\"beat\\\" me?\"; // Uncomfortable :(\n\"You're my guest. I can \\\"beat\\\" you.\"; // Sometimes, you've to :P\n'You\\'re my guest too. I can \"beat\" you too.'; // Sometimes, you've to :P\n `Be \"my\" guest. You're in complete freedom.`; // Most comfort :D\n" }, { "answer_id": 35870563, "author": "Divyesh Kanzariya", "author_id": 5246706, "author_profile": "https://Stackoverflow.com/users/5246706", "pm_score": 4, "selected": false, "text": "elem.innerHTML = '<a href=\"' + url + '\">Hello</a>'; elem.innerHTML = \"<a href='\" + url + \"'>Hello</a>\"; myJson = '{ \"hello world\": true }'; \"He said: \\\"Let's go!\\\"\"\n 'He said: \"Let\\'s go!\"'\n \"He said: \\\"Let\\'s go!\\\"\"\n 'He said: \\\"Let\\'s go!\\\"'" }, { "answer_id": 40283674, "author": "ovidb", "author_id": 1828653, "author_profile": "https://Stackoverflow.com/users/1828653", "pm_score": 2, "selected": false, "text": "\" ' ' \\' console.log('Don\\'t lose time'); // \"Don't lose time\"" }, { "answer_id": 45612369, "author": "Bruno Jennrich", "author_id": 1557690, "author_profile": "https://Stackoverflow.com/users/1557690", "pm_score": 2, "selected": false, "text": "echo \"$xyz\";\n ' \" '' \"\"" }, { "answer_id": 48703923, "author": "Gordon", "author_id": 4870698, "author_profile": "https://Stackoverflow.com/users/4870698", "pm_score": 1, "selected": false, "text": "let value = \"<?php echo 'This is my message, \"double quoted\" - \\'single quoted\\' ?>\";\n This is my message, \"double quoted\" - 'single quoted'\n var value = 'This is my message';\ndocument.getElementById('sample-text').innerHTML = value; <span id=\"sample-text\"></span>" }, { "answer_id": 59977360, "author": "lolol", "author_id": 941072, "author_profile": "https://Stackoverflow.com/users/941072", "pm_score": 1, "selected": false, "text": "' const message = 'That\\'s a \\'magic\\' shoe.' // This is wrong\nconst message = 'That’s a ‘magic’ shoe.' // This is correct\n" }, { "answer_id": 70415062, "author": "Artfaith", "author_id": 5113030, "author_profile": "https://Stackoverflow.com/users/5113030", "pm_score": 0, "selected": false, "text": "U+005C (REVERSE SOLIDUS) U+000D (CARRIAGE RETURN) U+000A (LINE FEED)" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28150/" ]
242,822
<p>Why would someone use <code>WHERE 1=1 AND &lt;conditions&gt;</code> in a SQL clause (Either SQL obtained through concatenated strings, either view definition)</p> <p>I've seen somewhere that this would be used to protect against SQL Injection, but it seems very weird.</p> <p>If there is injection <code>WHERE 1 = 1 AND injected OR 1=1</code> would have the same result as <code>injected OR 1=1</code>.</p> <p>Later edit: What about the usage in a view definition?</p> <hr> <p>Thank you for your answers.</p> <p>Still, I don't understand why would someone use this construction for defining a view, or use it inside a stored procedure.</p> <p>Take this for example:</p> <pre><code>CREATE VIEW vTest AS SELECT FROM Table WHERE 1=1 AND table.Field=Value </code></pre>
[ { "answer_id": 242831, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 10, "selected": true, "text": "and <condition>\n 1=1 and 1=1" }, { "answer_id": 242867, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": 7, "selected": false, "text": "dim sqlstmt as new StringBuilder\nsqlstmt.add(\"SELECT * FROM Products\")\nsqlstmt.add(\" WHERE 1=1\") \n\n''// From now on you don't have to worry if you must \n''// append AND or WHERE because you know the WHERE is there\nIf ProductCategoryID <> 0 then\n sqlstmt.AppendFormat(\" AND ProductCategoryID = {0}\", trim(ProductCategoryID))\nend if\nIf MinimunPrice > 0 then\n sqlstmt.AppendFormat(\" AND Price >= {0}\", trim(MinimunPrice))\nend if\n" }, { "answer_id": 243050, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 4, "selected": false, "text": "select a,b,c from t where a = ?\n select distinct a from t\nunion all\nselect '*' from sysibm.sysdummy1\n * * select a,b,c from t where ((a = ?) or (1==1))\n select * from t select * from t where name = 'Bob' and salary > 20000\n select * from t where 1=1 select * from t where 1=1 and name = 'Bob' and salary > 20000\n" }, { "answer_id": 517307, "author": "jackberry", "author_id": 45131, "author_profile": "https://Stackoverflow.com/users/45131", "pm_score": 0, "selected": false, "text": "Select * from tablename Where 1=1" }, { "answer_id": 2021633, "author": "sanbikinoraion", "author_id": 22715, "author_profile": "https://Stackoverflow.com/users/22715", "pm_score": 3, "selected": false, "text": "implode (\" AND \", $clauses);\n" }, { "answer_id": 8164877, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 3, "selected": false, "text": "MERGE MERGE INTO Circles\n USING \n (\n SELECT pi\n FROM Constants\n ) AS SourceTable\n ON 1 = 1\nWHEN MATCHED THEN \n UPDATE\n SET circumference = 2 * SourceTable.pi * radius;\n" }, { "answer_id": 11905143, "author": "Big Al", "author_id": 1399422, "author_profile": "https://Stackoverflow.com/users/1399422", "pm_score": 0, "selected": false, "text": "1=1" }, { "answer_id": 14982466, "author": "milso", "author_id": 633865, "author_profile": "https://Stackoverflow.com/users/633865", "pm_score": 5, "selected": false, "text": "CREATE TABLE New_table_name \nas \nselect * \nFROM Old_table_name \nWHERE 1 = 2;\n" }, { "answer_id": 22497243, "author": "Zo Has", "author_id": 521201, "author_profile": "https://Stackoverflow.com/users/521201", "pm_score": 1, "selected": false, "text": "where 1=1 select column1, column2 from my table where 1=1 {name} {age};\n string name_whereClause= ddlName.SelectedIndex > 0 ? \"AND name ='\"+ ddlName.SelectedValue+ \"'\" : \"\";\n 'AND' or 'WHERE'." }, { "answer_id": 27622738, "author": "StuartLC", "author_id": 314291, "author_profile": "https://Stackoverflow.com/users/314291", "pm_score": 3, "selected": false, "text": "<proper conditions> WHERE AND string builder var sqlQuery = \"SELECT * FROM FOOS WHERE 1 = 1\"\nif (shouldFilterForBars)\n{\n sqlQuery = sqlQuery + \" AND Bars > 3\";\n}\nif (shouldFilterForBaz)\n{\n sqlQuery = sqlQuery + \" AND Baz < 12\";\n}\n WHERE 1 = 1 AND 1 = 1 AND WHERE" }, { "answer_id": 36427261, "author": "Yogesh Umesh Vaity", "author_id": 5925259, "author_profile": "https://Stackoverflow.com/users/5925259", "pm_score": 3, "selected": false, "text": "WHERE 1 WHERE 1 WHERE 1=1 WHERE 1 WHERE 1" }, { "answer_id": 37310766, "author": "Carlos Toledo", "author_id": 4146766, "author_profile": "https://Stackoverflow.com/users/4146766", "pm_score": 4, "selected": false, "text": "CREATE VIEW vTest AS\nSELECT FROM Table WHERE 1=1 \nAND Table.Field=Value\nAND Table.IsValid=true\n CREATE VIEW vTest AS\nSELECT FROM Table WHERE 1=1 \n--AND Table.Field=Value\n--AND Table.IsValid=true\n" }, { "answer_id": 48821888, "author": "Eliseo Jr", "author_id": 8311491, "author_profile": "https://Stackoverflow.com/users/8311491", "pm_score": 2, "selected": false, "text": "Declare @SearchValue varchar(8) \nDeclare @SQLQuery varchar(max) = '\nSelect [FirstName]\n ,[LastName]\n ,[MiddleName]\n ,[BirthDate]\n,Case\n when [Status] = 0 then ''Inactive''\n when [Status] = 1 then ''Active''\nend as [Status]'\n\nDeclare @SearchOption nvarchar(100)\nIf (@SearchValue = 'Active')\nBegin\n Set @SearchOption = ' Where a.[Status] = 1'\nEnd\n\nIf (@SearchValue = 'Inactive')\nBegin\n Set @SearchOption = ' Where a.[Status] = 0'\nEnd\n\nIf (@SearchValue = 'All')\nBegin\n Set @SearchOption = ' Where 1=1'\nEnd\n\nSet @SQLQuery = @SQLQuery + @SearchOption\n\nExec(@SQLQuery);\n" }, { "answer_id": 49323891, "author": "JonWay", "author_id": 5300021, "author_profile": "https://Stackoverflow.com/users/5300021", "pm_score": 2, "selected": false, "text": "SELECT\n*\nFROM MyTable\n\nWHERE 1=1\n WHERE 2=2\nWHERE 10=10\nWHERE 99=99\n" }, { "answer_id": 62336566, "author": "SMS", "author_id": 11262056, "author_profile": "https://Stackoverflow.com/users/11262056", "pm_score": 0, "selected": false, "text": "where if _where == '': _where = '1=1'\n...\n...\n...\ncur.execute(f'select {predicate} from {table_name} where {_where}')\n" }, { "answer_id": 67129874, "author": "Bora Çolakoğlu", "author_id": 14253710, "author_profile": "https://Stackoverflow.com/users/14253710", "pm_score": 2, "selected": false, "text": "and <condition>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23795/" ]
242,841
<p>Do you think there is a big difference in for...in and for loops? What kind of "for" do you prefer to use and why?</p> <p>Let's say we have an array of associative arrays:</p> <pre><code>var myArray = [{'key': 'value'}, {'key': 'value1'}]; </code></pre> <p>So we can iterate:</p> <pre><code>for (var i = 0; i &lt; myArray.length; i++) </code></pre> <p>And:</p> <pre><code>for (var i in myArray) </code></pre> <p>I don't see a big difference. Are there any performance issues?</p>
[ { "answer_id": 242888, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 10, "selected": true, "text": "for (var i = 0; i < a.length; i++)\n //do stuff with a[i]\n for (var key in o)\n //do stuff with o[key]\n" }, { "answer_id": 242893, "author": "Gene", "author_id": 22673, "author_profile": "https://Stackoverflow.com/users/22673", "pm_score": 5, "selected": false, "text": "for (var i = myArray.length-1; i >= 0; i--)\n for (var i = 0; i < myArray.length; i++)\n" }, { "answer_id": 243755, "author": "Damir Zekić", "author_id": 401510, "author_profile": "https://Stackoverflow.com/users/401510", "pm_score": 4, "selected": false, "text": "Array for in for in l = ''; for (m in obj) { l += m + ' => ' + obj[m] + '\\n' } console.log(l);\n" }, { "answer_id": 243778, "author": "Benno Richters", "author_id": 3565, "author_profile": "https://Stackoverflow.com/users/3565", "pm_score": 7, "selected": false, "text": "for in for in .hasOwnProperty for (var name in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, name)) {\n // DO STUFF\n }\n}\n" }, { "answer_id": 1176454, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "function foreach(o, f) {\n for(var i = 0; i < o.length; i++) { // simple for loop\n f(o[i], i); // execute a function and make the obj, objIndex available\n }\n}\n foreach(o, function(obj, i) { // for each obj in o\n alert(obj); // obj\n alert(i); // obj index\n /*\n say if you were dealing with an html element may be you have a collection of divs\n */\n if(typeof obj == 'object') { \n obj.style.marginLeft = '20px';\n }\n});\n" }, { "answer_id": 1229010, "author": "Jason", "author_id": 26860, "author_profile": "https://Stackoverflow.com/users/26860", "pm_score": 6, "selected": false, "text": "each(callback) for( ; ; ) for( in ) undefined $(['a','b','c']).each(function() {\n alert(this);\n});\n//Outputs \"a\" then \"b\" then \"c\"\n each() for( ; ; )" }, { "answer_id": 3122212, "author": "fabjoa", "author_id": 376741, "author_profile": "https://Stackoverflow.com/users/376741", "pm_score": 2, "selected": false, "text": "for( var i=0,j=null; j=array[i++]; foo(j) );\n" }, { "answer_id": 6443017, "author": "Mike Samuel", "author_id": 20394, "author_profile": "https://Stackoverflow.com/users/20394", "pm_score": 4, "selected": false, "text": "var array = [0, 1, 2, , , 5];\n\nfor (var k in array) {\n // Not guaranteed by the language spec to iterate in order.\n alert(k); // Outputs 0, 1, 2, 5.\n // Behavior when loop body adds to the array is unclear.\n}\n\nfor (var i = 0; i < array.length; ++i) {\n // Iterates in order.\n // i is a number, not a string.\n alert(i); // Outputs 0, 1, 2, 3, 4, 5\n // Behavior when loop body modifies array is clearer.\n}\n" }, { "answer_id": 8826575, "author": "mikemaccana", "author_id": 123671, "author_profile": "https://Stackoverflow.com/users/123671", "pm_score": 5, "selected": false, "text": "myArray.forEach(function(item, index) {\n console.log(item, index);\n});\n" }, { "answer_id": 9669705, "author": "meloncholy", "author_id": 648802, "author_profile": "https://Stackoverflow.com/users/648802", "pm_score": 4, "selected": false, "text": "var Base = function () {\n this.coming = \"hey\";\n};\n\nvar Sub = function () {\n this.leaving = \"bye\";\n};\n\nSub.prototype = new Base();\nvar tst = new Sub();\n\nfor (var i in tst) {\n console.log(tst.hasOwnProperty(i) + i + tst[i]);\n}\n\nObject.keys(tst).forEach(function (val) {\n console.log(val + tst[val]);\n});\n" }, { "answer_id": 10504109, "author": "baptx", "author_id": 1176454, "author_profile": "https://Stackoverflow.com/users/1176454", "pm_score": 2, "selected": false, "text": "var scriptTags = document.getElementsByTagName(\"script\");\n\nfor(var i = 0; i < scriptTags.length; i++)\nalert(i); // Will print all your elements index (you can get src attribute value using scriptTags[i].attributes[0].value)\n\nfor(var i in scriptTags)\nalert(i); // Will print \"length\", \"item\" and \"namedItem\" in addition to your elements!\n" }, { "answer_id": 12806509, "author": "Paulo Cheque", "author_id": 1163081, "author_profile": "https://Stackoverflow.com/users/1163081", "pm_score": 0, "selected": false, "text": "var MyTest = {\n a:string = \"a\",\n b:string = \"b\"\n};\n\nmyfunction = function(dicts) {\n for (var dict in dicts) {\n alert(dict);\n alert(typeof dict); // print 'string' (incorrect)\n }\n\n for (var i = 0; i < dicts.length; i++) {\n alert(dicts[i]);\n alert(typeof dicts[i]); // print 'object' (correct, it must be {abc: \"xyz\"})\n }\n};\n\nMyObj = function() {\n this.aaa = function() {\n myfunction([MyTest]);\n };\n};\nnew MyObj().aaa(); // This does not work\n\nmyfunction([MyTest]); // This works\n" }, { "answer_id": 30140279, "author": "bormat", "author_id": 4237897, "author_profile": "https://Stackoverflow.com/users/4237897", "pm_score": 2, "selected": false, "text": "keys = Object.keys(obj);\nfor (var i = keys.length; i--;){\n value = obj[keys[i]];// or other action\n}\n" }, { "answer_id": 40723365, "author": "achecopar", "author_id": 2646253, "author_profile": "https://Stackoverflow.com/users/2646253", "pm_score": 0, "selected": false, "text": "for (var i = 0; i < myArray.length; i++) { \n console.log(i) \n}\n\n//Output\n0\n1\n\nfor (var i in myArray) { \n console.log(i) \n} \n\n// Output\n0 \n1 \nremove\n if(myArray.hasOwnProperty(i))" }, { "answer_id": 48063455, "author": "Yash Srivastava", "author_id": 5791180, "author_profile": "https://Stackoverflow.com/users/5791180", "pm_score": 0, "selected": false, "text": "var array = [\"a\", \"b\", \"c\"];\narray[\"abc\"] = 123;\nconsole.log(\"Standard for loop:\");\nfor (var index = 0; index < array.length; index++)\n{\n console.log(\" array[\" + index + \"] = \" + array[index]); //Standard for loop\n}\n console.log(\"For-in loop:\");\nfor (var key in array)\n{\n console.log(\" array[\" + key + \"] = \" + array[key]); //For-in loop output\n}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17375/" ]
242,908
<p>Due to the nature of the live server I deploy to, my mail settings are using deliveryMethod="PickupDirectoryFromIis". I'm using log4net to send logs via email and I need find a way of getting it to do the same thing.</p> <p>I can see from the docs that there is an SmtpPickupDirAppender, which has a pickupDir setting. If I set this to whatever pickup directory IIS uses, I'm sure everything will work OK. However what I really want is to just tell log4net to use IIS's setting and leave it there. That way if it ever changes we won't have to change the log4net config too, something we're likely to forget. Is there a way to do this?</p>
[ { "answer_id": 242964, "author": "Leandro López", "author_id": 22695, "author_profile": "https://Stackoverflow.com/users/22695", "pm_score": 0, "selected": false, "text": "SmtpClient.DeliveryMethod PickupDirectoryFromIis" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12277/" ]
242,913
<p>We can see in a directory files ordered by Name in Windows Explorer.</p> <p>If I try the same thing in the Windows command prompt it orders by name differently - <em>correctly</em>:</p> <pre><code>dir *.jpg /ON /B cubierta.jpg pag00.jpg pag06.jpg pag08.jpg pag09.jpg pag100.jpg pag101.jpg pag102.jpg pag103.jpg pag104.jpg pag105.jpg pag106.jpg pag107.jpg pag108.jpg pag109.jpg pag11.jpg, etc, etc, etc, ... </code></pre> <p>Is there a way to get <code>dir</code> to order by Name where it reads the numbers as a human would do?</p>
[ { "answer_id": 243575, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "sort ls -1 | /<cygwin>bin/sort -g dir /b | \\cygwin\\bin\\sort -g" }, { "answer_id": 352087, "author": "ian_scho", "author_id": 15530, "author_profile": "https://Stackoverflow.com/users/15530", "pm_score": -1, "selected": false, "text": "dir *.jpg /ODN /B > files.txt\n\nfor /f \"tokens=*\" %%a in ('dir *.jpg /ODN /B') do (\n echo ^<page^>%%a^</page^> >>pages.xml.fragment\n)\n dir *.jpg /OD" }, { "answer_id": 51874902, "author": "phuclv", "author_id": 995714, "author_profile": "https://Stackoverflow.com/users/995714", "pm_score": 1, "selected": false, "text": "powershell -Command \"(Get-ChildItem | Sort-Object { [regex]::Replace($_.Name, '\\d+', { $args[0].Value.PadLeft(20) }) }).Name\"\n PadLeft(20) @echo off\nsetlocal enabledelayedexpansion\nfor %%a in (*.txt) do (\n set num=00000000000000000000%%a\n set num=!num:~-20!\n set $!num!=%%a\n)\nfor /f \"tokens=1,* delims==\" %%a in ('set $0') do echo %%b\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15530/" ]
242,914
<p>Is it possible in plain JPA or JPA+Hibernate extensions to declare a composite key, where an element of the composite key is a sequence?</p> <p>This is my composite class:</p> <pre><code>@Embeddable public class IntegrationEJBPk implements Serializable { //... @ManyToOne(cascade = {}, fetch = FetchType.EAGER) @JoinColumn(name = "APPLICATION") public ApplicationEJB getApplication() { return application; } @Column(name = "ENTITY", unique = false, nullable = false, insertable = true, updatable = true) public String getEntity() { return entity; } @GeneratedValue(strategy = GenerationType.AUTO, generator = "INTEGRATION_ID_GEN") @SequenceGenerator(name = "INTEGRATION_ID_GEN", sequenceName = "OMP_INTEGRATION_CANONICAL_SEQ") @Column(name = "CANONICAL_ID", unique = false, nullable = false, insertable = true, updatable = true) public String getCanonicalId() { return canonicalId; } @Column(name = "NATIVE_ID", unique = false, nullable = false, insertable = true, updatable = true) public String getNativeId() { return nativeId; } @Column(name = "NATIVE_KEY", unique = false, nullable = false, insertable = true, updatable = true) public String getNativeKey() { return nativeKey; } //... } </code></pre> <p>I already supply the values for <code>application</code>, <code>entity</code>, <code>nativeId</code> and <code>nativeKey</code>. I want to construct an entity like the one below:</p> <pre><code>IntegrationEJB i1 = new IntegrationEJB(); i1.setIntegrationId(new IntegrationEJBPk()); i1.getIntegrationId().setApplication(app1); i1.getIntegrationId().setEntity("Entity"); i1.getIntegrationId().setNativeId("Nid"); i1.getIntegrationId().setNativeKey("NK"); </code></pre> <p>And when I call <code>em.persist(i1</code>), I want that the <code>canonicalId</code> is generated and the integration is inserted.</p> <p>Is this possible? If so, what's the simple way? (I prefer not to use application-provided keys or native sql).</p>
[ { "answer_id": 244051, "author": "sakana", "author_id": 28921, "author_profile": "https://Stackoverflow.com/users/28921", "pm_score": 1, "selected": false, "text": "@TableGenerator(name = \"canonicalKeys\", allocationSize = 1, initialValue = 1)\n@GeneratedValue(strategy = GenerationType.TABLE, generator = \"canonicalKeys\")\n@Column(name = \"CANONICAL_ID\", unique = false, nullable = false, insertable = true, updatable = true)\npublic String getCanonicalId() {\n return canonicalId;\n}\n" }, { "answer_id": 697578, "author": "Petriborg", "author_id": 2815, "author_profile": "https://Stackoverflow.com/users/2815", "pm_score": 1, "selected": false, "text": "select nextval ('hibernate_sequence')" }, { "answer_id": 12888458, "author": "Glen Best", "author_id": 1528401, "author_profile": "https://Stackoverflow.com/users/1528401", "pm_score": 2, "selected": false, "text": "@Entity\npublic class ParentEntity {\n @Id\n @GenerateValue(IDENTITY) // If using DB auto-increment or similar\n int id;\n\n // ...\n}\n @Entity\n@IdClass(ChildId.class)\npublic class ChildEntity {\n // The child table will have a composite PK:\n // (parent_ID, child_name)\n @Id \n @ManyToOne\n int parentEntity;\n @Id\n String childName;\n\n String favoriteColor; // plus other columns\n\n // ...\n\n}\n // child Id attributes have the same name as the child entity\n// however the types change to match the underlying PK attributes \n// (change ParentEntity to int)\n public class ChildId implements Serializable {\n int parentEntity;\n String childName;\n\n public ChildId() { //... }\n\n // Add extra constructor & remove setter methods so Id objects are immutable\n public ChildId(int parentEntity, String childName) { //... }\n\n\n public int getParentEntity() { //... }\n // make Id objects immutable:\n // public void setParentEntity(int parentEntity) { //... }\n public String getChildName() { //... }\n // public void setChildName(String childName) { //... }\n}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22992/" ]
242,926
<p>I know there are already a few questions regarding recommendations for C++ unit test frameworks, but all the answers did not help as they just recommend one of the frameworks but do not provide any information about a (feature) comparison.</p> <p>I think the most interesting frameworks are CppUnit, Boost and the new Google testing framework. Has anybody done any comparison yet?</p>
[ { "answer_id": 3565689, "author": "Wernight", "author_id": 167897, "author_profile": "https://Stackoverflow.com/users/167897", "pm_score": 7, "selected": false, "text": "#include <gtest/gtest.h>\n\nTEST(MyTestSuitName, MyTestCaseName) {\n int actual = 1;\n EXPECT_GT(actual, 0);\n EXPECT_EQ(1, actual) << \"Should be equal to one\";\n}\n ASSERT_EQ(5, Foo(i)) << \" where i = \" << i; SCOPED_TRACE" }, { "answer_id": 3565742, "author": "Wernight", "author_id": 167897, "author_profile": "https://Stackoverflow.com/users/167897", "pm_score": 6, "selected": false, "text": "// TODO: Include your class to test here.\n#define BOOST_TEST_MODULE MyTest\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_CASE(MyTestCase)\n{\n // To simplify this example test, let's suppose we'll test 'float'.\n // Some test are stupid, but all should pass.\n float x = 9.5f;\n\n BOOST_CHECK(x != 0.0f);\n BOOST_CHECK_EQUAL((int)x, 9);\n BOOST_CHECK_CLOSE(x, 9.5f, 0.0001f); // Checks differ no more then 0.0001%\n}\n" }, { "answer_id": 6710436, "author": "Roger", "author_id": 846848, "author_profile": "https://Stackoverflow.com/users/846848", "pm_score": 2, "selected": false, "text": "#include <cpunit>\n\nnamespace MyAssetTest {\n using namespace cpunit;\n\n CPUNIT_FUNC(MyAssetTest, test_stuff) {\n int some_value = 42;\n assert_equals(\"Wrong value!\", 666, some_value);\n }\n\n // Fixtures go as follows:\n CPUNIT_SET_UP(MyAssetTest) {\n // Setting up suite here...\n // And the same goes for tear-down.\n }\n\n}\n" }, { "answer_id": 13061831, "author": "moswald", "author_id": 8368, "author_profile": "https://Stackoverflow.com/users/8368", "pm_score": 4, "selected": false, "text": "#include \"xUnit++/xUnit++.h\"\n\nFACT(\"Foo and Blah should always return the same value\")\n{\n Check.Equal(\"0\", Foo()) << \"Calling Foo() with no parameters should always return \\\"0\\\".\";\n Assert.Equal(Foo(), Blah());\n}\n\nTHEORY(\"Foo should return the same value it was given, converted to string\", (int input, std::string expected),\n std::make_tuple(0, \"0\"),\n std::make_tuple(1, \"1\"),\n std::make_tuple(2, \"2\"))\n{\n Assert.Equal(expected, Foo(input));\n}\n Assert.Equal(-1, foo(i)) << \"Failed with i = \" << i; Log.Debug << \"Starting test\"; Log.Warn << \"Here's a warning\";" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32030/" ]
242,975
<p>I have a problem, and was hoping I could rely on some of the experience here for advice and a push in the right direction. I have an MS Access file made by propietary software. I only want to take half the columns from this table, and import into new(not yet setup)mysql database.</p> <p>I have no idea how to do this or what the best way is. New data will be obtained each night, and again imported, as an automatic task.</p> <p>One of the columns in the access database is a url to a jpeg file, I want to download this file and import into the database as a BLOB type automatically.</p> <p>Is there a way to do this automatically? This will be on a windows machine, so perhaps it could be scripted with WSH?</p>
[ { "answer_id": 243069, "author": "Luis Melgratti", "author_id": 17032, "author_profile": "https://Stackoverflow.com/users/17032", "pm_score": 4, "selected": true, "text": "#!/bin/bash\n\nMDBFILE=\"Data.mdb\"\n\nOPTIONS=\"-H -D %y-%m-%d\"\nmdb-export $OPTIONS $MDBFILE TableName_1 > output_1.txt\nmdb-export $OPTIONS $MDBFILE TableName_2 > output_2.txt\n\nmdb-export $OPTIONS $MDBFILE TableName_n > output_n.txt\n\nMYSQLOPTIONS=' --fields-optionally-enclosed-by=\" --fields-terminated-by=, -r '\nmysqlimport $MYSQLOPTIONS -L -uuser -ppasword database output_1.txt\nmysqlimport $MYSQLOPTIONS -L -uuser -ppasword database output_2.txt\nmysqlimport $MYSQLOPTIONS -L -uuser -ppasword database output_n.txt\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1246613/" ]
242,992
<p>Does the HTML "select" element have an on select event? what exactly is the name of the event?</p>
[ { "answer_id": 242993, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 7, "selected": true, "text": "onchange" }, { "answer_id": 242999, "author": "Ryan McCue", "author_id": 2575, "author_profile": "https://Stackoverflow.com/users/2575", "pm_score": 2, "selected": false, "text": "onchange" }, { "answer_id": 243038, "author": "Alexander Prokofyev", "author_id": 11256, "author_profile": "https://Stackoverflow.com/users/11256", "pm_score": 4, "selected": false, "text": ".change addEventListner('change', function...) <html>\n<head>\n <script type=\"text/javascript\" src=\"jquery-1.2.6.js\"></script>\n <script type=\"text/javascript\">\n\n// If using jQuery\n$(document).ready( function() {\n $(\"#list\").attr( \"selectedIndex\", -1 );\n $(\"#list\").change( function() {\n $(\"#answer\").text( $(\"#list option:selected\").val() );\n });\n});\n </script>\n\n <script type=\"text/javascript\">\n\n// Plain Javascript:\ndocument.addEventListener('DOMContentLoaded', function(event) {\n var selectList = document.getElementById(\"list\");\n var divAnswer = document.getElementById(\"answer\");\n selectList.addEventListener(\"change\", function(changeEvent) {\n divAnswer.textContent = selectList.value;\n });\n});\n </script>\n\n</head>\n<body>\n <div id=\"answer\">No answer</div>\n <form>\n Answer\n <select id=\"list\">\n <option value=\"Answer A\">A</option>\n <option value=\"Answer B\">B</option>\n <option value=\"Answer C\">C</option>\n </select>\n </form>\n</body>\n</html>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/242992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13370/" ]
243,021
<p>I have a VS2005 windows service where I have the need to use 'useUnsafeHeaderParsing' as per documentation from MSDN.</p> <p>As this is a library used within my windows service, I do not have a web.config to add httpwebrequest element and set useUnsafeHeaderParsing to true.</p> <p>How would I go about achieving this in code. I tried <a href="http://social.msdn.microsoft.com/Forums/en-US/netfxnetcom/thread/ff098248-551c-4da9-8ba5-358a9f8ccc57/" rel="nofollow noreferrer">this</a> and <a href="http://wiki.lessthandot.com/index.php/Setting_unsafeheaderparsing" rel="nofollow noreferrer">this</a> but that was a no go.</p>
[ { "answer_id": 3191915, "author": "Aaronontheweb", "author_id": 377476, "author_profile": "https://Stackoverflow.com/users/377476", "pm_score": 3, "selected": false, "text": "private static bool SetUseUnsafeHeaderParsing(bool b)\n {\n Assembly a = Assembly.GetAssembly(typeof(System.Net.Configuration.SettingsSection));\n if (a == null) return false;\n\n Type t = a.GetType(\"System.Net.Configuration.SettingsSectionInternal\");\n if (t == null) return false;\n\n object o = t.InvokeMember(\"Section\",\n BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.NonPublic, null, null, new object[] { });\n if (o == null) return false;\n\n FieldInfo f = t.GetField(\"useUnsafeHeaderParsing\", BindingFlags.NonPublic | BindingFlags.Instance);\n if (f == null) return false;\n\n f.SetValue(o, b);\n\n return true;\n }\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
243,022
<p>I'm building an application that needs to run through an XML feed but I'm having a little trouble with getting certain elements.</p> <p>I'm using the <a href="http://twitter.com/statuses/public_timeline.rss" rel="nofollow noreferrer">Twitter feed</a> and want to run through all the <code>&lt;item&gt;</code> elements. I can connect fine and get the content from the feed but I can't figure out how to select only the <code>item</code> elements when I'm loopuing through <code>reader.Read();</code>.</p> <p>Thanks for your help!</p>
[ { "answer_id": 3191915, "author": "Aaronontheweb", "author_id": 377476, "author_profile": "https://Stackoverflow.com/users/377476", "pm_score": 3, "selected": false, "text": "private static bool SetUseUnsafeHeaderParsing(bool b)\n {\n Assembly a = Assembly.GetAssembly(typeof(System.Net.Configuration.SettingsSection));\n if (a == null) return false;\n\n Type t = a.GetType(\"System.Net.Configuration.SettingsSectionInternal\");\n if (t == null) return false;\n\n object o = t.InvokeMember(\"Section\",\n BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.NonPublic, null, null, new object[] { });\n if (o == null) return false;\n\n FieldInfo f = t.GetField(\"useUnsafeHeaderParsing\", BindingFlags.NonPublic | BindingFlags.Instance);\n if (f == null) return false;\n\n f.SetValue(o, b);\n\n return true;\n }\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ]
243,027
<p>I've got this ASP.NET drop down control that displays other textbox controls when the value is not UK (this is to help find UK addresses using postcodes). When UK is reselected I will like to hide the other controls. I've enabled view state and AutoPostBack to true. I have an <code>onSelectedIndexChanged</code> event that only gets fired once (when the dropdown value changes to a different country as by default it's UK).</p> <p>I'll like to have the <code>OnSelectedIndexChanged</code> to fire every time the value is different, but this isn't the case.</p> <p>P.S. Here's the code snippet.</p> <pre><code>&lt;asp:DropDownList runat="server" ID="Country2" AutoPostBack="True" OnSelectedIndexChanged="Country2_SelectedIndexChanged" DataSource="&lt;%# RegionList %&gt;" DataTextField="Name" DataValueField="Code" CssClass="dropdown country"&gt;&lt;/asp:DropDownList&gt; protected void Country2_SelectedIndexChanged(object sender, EventArgs e) { DropDownList d = (DropDownList)sender; addressEntry.CountryPrePostBack_SelectedIndexChanged(d.SelectedItem.Value); } </code></pre>
[ { "answer_id": 243047, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 0, "selected": false, "text": "this.dropDownList.SelectedIndexChanged += new EventHandler(dropDownList_SelectedIndexChanged);\n !IsPostback CauseValidation = false" }, { "answer_id": 271024, "author": "Middletone", "author_id": 35331, "author_profile": "https://Stackoverflow.com/users/35331", "pm_score": 0, "selected": false, "text": "Private Sub LinkButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LinkButton.Click\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
243,035
<p>I have two tables, one stores the products and quantity we have bought, the other stores the sells. The current stock is therefore the sum of all the quantity columns in the bought table minus the number of rows in the sells table. How can this be expressed in MySQL. Remember that there are many different products.</p> <p><strong>EDIT:</strong> To make it harder, I have another requirement. I have the bought table, the sold table, but I also have the products table. I want a list of all the products, and I want to know the quantity available of each product. The problem with the current answers is that they only return the products that we have sold or bought already. I want all the products.</p>
[ { "answer_id": 243063, "author": "SquareCog", "author_id": 15962, "author_profile": "https://Stackoverflow.com/users/15962", "pm_score": 4, "selected": true, "text": "\nSELECT inv_t.product_id, inventory_total-nvl(sales_total,0)\nFROM \n (SELECT product_id, sum(quantity) as inventory_total\n FROM inventory\n GROUP BY product_id) inv_t LEFT OUTER JOIN\n (SELECT product_id, count(*) AS sales_total \n FROM sales \n GROUP BY product_id) sale_t\n ON (inv_t.product_id = sale_t.product_id)\n\n" }, { "answer_id": 243066, "author": "Marius", "author_id": 1585, "author_profile": "https://Stackoverflow.com/users/1585", "pm_score": 0, "selected": false, "text": "SELECT product AS prd, \nSUM(quantity) - \n IFNULL((SELECT COUNT(*)\n FROM sells\n WHERE product = prd \n GROUP BY product), 0)\nAS stock \nFROM bought\nGROUP BY product;\n" }, { "answer_id": 243271, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 0, "selected": false, "text": "--First view: list products and the purchased qty\ncreate or replace view product_purchases as\nselect\n product_id\n ,sum(purchased_qty) as purchased_qty\nfrom\n purchases\ngroup by\n product_id;\n\n--Second view: list of products and the amount sold \ncreate or replace view product_sales as\nselect\n product_id\n ,count(*) as sales_qty\nfrom\n sales\ngroup by\n product_id;\n\n--after creating those two views, run this query:\nselect\n pp.product_id\n ,pp.purchased_qty - ps.sales_qty as on_hand_qty\nfrom\n product_purchases pp\n ,product_sales ps\nwhere ps.product_id = pp.product_id;\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1585/" ]
243,037
<p>This problem has several of us stumped in the office. We are all new to deploying ASP.NET apps to a web farm, and I am fresh out of ideas.</p> <p>We have a web farm, and the application is copied on to all of them. However, we are having a problem..</p> <p>An exception is being thrown when trying to get settings from <code>appSettings</code>. Upon further investigation, it turns out the node is actually not using the local <code>Web.Config</code> but it falling back to the <code>Web.Config</code> in the .NET framework folder (we have proved this by adding keys there, which appear on a test page).</p> <p>I must be missing something, because my understanding is that so long as the file is there, IIS should use that! One of the servers seems to work fine!</p> <p>Here's a list of what we have confirmed:</p> <ul> <li>The config file is in the app directory.</li> <li>Said file's content is correct.</li> <li>When viewing the file from IIS > Site > Properties > ASP.NET > Edit Config the correct content is shown.</li> </ul> <p>However, at run-time the file that is used is the global one (<code>windows\ms .net\framework\v2\config\web.config</code>).</p> <p>Anyone have any suggestions as to what may be going wrong? Appreciate all the help I can get!</p> <p>Thanks.</p> <p>Rob</p>
[ { "answer_id": 243048, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 3, "selected": false, "text": "<httpModules>\n <remove name=\"ErrorLog\"/>\n</httpModules>\n <httpModules>\n <add name=\"ErrorLog\" type=\"GotDotNet.Elmah.ErrorLogModule, GotDotNet.Elmah, Version=1.0.5527.0, Culture=neutral, PublicKeyToken=978d5e1bd64b33e5\" />\n</httpModules>print(\"code sample\");\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/832/" ]
243,045
<p>What does Java do with long variables while performing addition?</p> <p>Wrong version 1:</p> <pre><code>Vector speeds = ... //whatever, speeds.size() returns 2 long estimated = 1l; long time = speeds.size() + estimated; // time = 21; string concatenation?? </code></pre> <p>Wrong version 2:</p> <pre><code>Vector speeds = ... //whatever, speeds.size() returns 2 long estimated = 1l; long time = estimated + speeds.size(); // time = 12; string concatenation?? </code></pre> <p>Correct version:</p> <pre><code>Vector speeds = ... //whatever, speeds.size() returns 2 long estimated = 1l; long size = speeds.size(); long time = size + estimated; // time = 3; correct </code></pre> <p>I don't get it, why Java concatenate them.</p> <p>Can anybody help me, why two primitive variables are concatenated?</p> <p>Greetings, guerda</p>
[ { "answer_id": 243054, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "import java.util.*;\n\npublic class Test\n{\n public static void main(String[] args)\n {\n Vector speeds = new Vector();\n speeds.add(\"x\");\n speeds.add(\"y\");\n\n long estimated = 1l;\n long time = speeds.size() + estimated;\n System.out.println(time); // Prints out 3\n }\n}\n" }, { "answer_id": 243087, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 5, "selected": false, "text": "System.out.println(\"\" + size + estimated); \n \"\" + size <--- string concatenation, so if size is 3, will produce \"3\"\n\"3\" + estimated <--- string concatenation, so if estimated is 2, will produce \"32\"\n System.out.println(\"\" + (size + estimated));\n \"\" + (expression) <-- string concatenation - need to evaluate expression first\n(3 + 2) <-- 5\nHence:\n\"\" + 5 <-- string concatenation - will produce \"5\"\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32043/" ]
243,057
<p>I'm using a Response.Redirect to redirect users to another server to download a file, and the other server is checking the header to ensure it came from the correct server... however it seems Response.Redirect strips the headers from the Response.</p> <p>Does anybody know how i can add the headers back? I've tried:</p> <pre><code>Response.AddHeader("Referer", "www.domain.com"); </code></pre> <p>But the receiving page tests false when i check if the Referrer header is set. </p> <p>Any suggestions how i can get this working, other than displaying a button for the user to click on (i'd like to keep the url hidden from the user as much as possible).</p>
[ { "answer_id": 243260, "author": "Martin Brown", "author_id": 20553, "author_profile": "https://Stackoverflow.com/users/20553", "pm_score": 1, "selected": false, "text": "Response.Redirect(\"url?Referer=\" + Server.UrlEncode(Request.UrlReferrer));\n" }, { "answer_id": 247518, "author": "matt.mercieca", "author_id": 30407, "author_profile": "https://Stackoverflow.com/users/30407", "pm_score": 4, "selected": false, "text": "<form action=\"http://url.goes.here\" id=\"test\" method=\"GET\"></form>\n<script type=\"text/javascript\">\n document.getElementById(\"test\").submit();\n</script>\n Response.Write( @\"<form action='http://url.goes.here' id='test' method='GET'></form>\n <script type='text/javascript'>\n document.getElementById('test').submit();\n </script> \");\n" }, { "answer_id": 247539, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": -1, "selected": false, "text": "Response.StatusCode = 302; //temp redirect\nResponse.Headers.Add(\"Location\", \"your/url/here\");\nResponse.Headers.Add(\"Referer\", \"something.com\");\nResponse.End();\n" }, { "answer_id": 4462712, "author": "Makkie", "author_id": 528853, "author_profile": "https://Stackoverflow.com/users/528853", "pm_score": 1, "selected": false, "text": "default.asp\n\nservername = Lcase(Request.ServerVariables(\"SERVER_NAME\"))\nResponse.Status = \"301 Moved Permanently\"\nResponse.AddHeader \"Location\", \"http://yoursite\"\nResponse.AddHeader \"Referer\", servername\nResponse.End()\n" }, { "answer_id": 9584407, "author": "user787262", "author_id": 787262, "author_profile": "https://Stackoverflow.com/users/787262", "pm_score": 0, "selected": false, "text": "javascript document.location = '<%:yourURL%>;';" }, { "answer_id": 10137150, "author": "Mr Moose", "author_id": 685760, "author_profile": "https://Stackoverflow.com/users/685760", "pm_score": 1, "selected": false, "text": "string token = vwrApi.GetAuthenticationToken(userId);\nResponse.Cookies.Add(new HttpCookie(\"VwrAuthorization\", token));\nResponse.Redirect(returnUrl, true);\n" }, { "answer_id": 11232430, "author": "Kristofor", "author_id": 860329, "author_profile": "https://Stackoverflow.com/users/860329", "pm_score": -1, "selected": false, "text": "HttpContext.Current.Response.StatusCode = 307;\nHttpContext.Current.Response.AddHeader(\"Location\", \"http://stackoverflow.com\");\nHttpContext.Current.Response.End(); \n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21969/" ]
243,060
<p>Emacs does not recognize my correct Python path. I think it is a general problem with Emacs not recognizing my environment variables. I have GNU Emacs 22.1.1 (i386-apple-darwin8.9.1, Carbon Version 1.6.0) of 2007-06-17 installed.</p> <p>I have set <code>PYTHONPATH</code> in my <code>~/.bashrc</code>. Maybe I should set it somewhere else?</p>
[ { "answer_id": 243239, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 6, "selected": true, "text": ".bashrc setenv .emacs (setenv \"PYTHONPATH\" \"PATH_STRING_HERE\")\n PYTHONPATH ~/.MacOSX/environment.plist" }, { "answer_id": 42206188, "author": "Christophe Van Neste", "author_id": 3940298, "author_profile": "https://Stackoverflow.com/users/3940298", "pm_score": 2, "selected": false, "text": "(setenv \"PYTHONPATH\" (shell-command-to-string \"$SHELL --login -c 'echo -n $PYTHONPATH'\"))\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2007483/" ]
243,068
<p>How can I create EPS files in C#? Are there any opensource libraries available or do I have to resort to <a href="http://www.adobe.com/devnet/postscript/pdfs/5002.EPSF_Spec.pdf" rel="noreferrer">the spec</a> and do it by hand?</p>
[ { "answer_id": 243239, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 6, "selected": true, "text": ".bashrc setenv .emacs (setenv \"PYTHONPATH\" \"PATH_STRING_HERE\")\n PYTHONPATH ~/.MacOSX/environment.plist" }, { "answer_id": 42206188, "author": "Christophe Van Neste", "author_id": 3940298, "author_profile": "https://Stackoverflow.com/users/3940298", "pm_score": 2, "selected": false, "text": "(setenv \"PYTHONPATH\" (shell-command-to-string \"$SHELL --login -c 'echo -n $PYTHONPATH'\"))\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25571/" ]
243,072
<p>When a user logs in to my site I want a css styled button to appear (this could be anything really, i.e. some special news text item etc), how can you do this via masterpages in asp.net? Or is there some other way you do this?</p>
[ { "answer_id": 243084, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 3, "selected": true, "text": " <asp:LoginView>\n <AnonymousTemplate>\n Nothing Displayed\n </AnonymousTemplate>\n <LoggedInTemplate>\n <asp:Button ID=\"myButton\" runat=\"server\">\n </LoggedInTemplate>\n </asp:LoginView>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5175/" ]
243,074
<p>I'm wondering what are the recommended ways to handle situations where, in memory managed code, object didn't belong to any particular owner, i.e. objects released themselves. One such example could be a subclass of NSWindowController, which configures, displays and manages input and output of a single window. The controller object displays a window and releases itself later at some point (usually when the window or sheet it manages is closed). AppKit provides couple examples as well: NSAnimation retains itself in startAnimation and releases itself when the animation is done. Another example is NSWindow, which can be configured to release itself when closed. </p> <p>When implementing these "self-owned" objects myself, I see at least three different GC-safe patterns, but all of them have some drawbacks. </p> <p>a). Using CFRetain/CFRelease.</p> <p>Self-owned object calls CFRetain on self before it starts its operation (e.g. in the window controller example before the window is displayed). It then calls CFRelease() on self when it's done (e.g. in the window controller example after the window is closed). </p> <p>Pros: User of the object doesn't have to worry about memory management.<br> Cons: A bit ugly, since requires use of memory management functions, although we're using GC in pure ObjC code. If CFRelease() isn't called, leak may be hard to locate.</p> <p>b). Avoiding self-ownership idiom with static data structure.</p> <p>Object adds itself into a data structure (e.g. a static mutable array) before it starts its operation and removes itself from there when it's done. </p> <p>Pros: User of the object doesn't have to worry about memory management. No calls to memory management functions. Objects have explicit owner. Potential leaks are easy to locate.<br> Cons: Locking is needed if objects may be created from different threads. Extra data structure.</p> <p>c). Avoiding self-ownership idiom by requiring the user of object to save a reference to the object (e.g. into an ivar).</p> <p>Pros: No calls to memory management functions. Objects have explicit owner.<br> Cons: User of the object has to keep a reference even if it doesn't need the object anymore. Extra ivars.</p> <p>What pattern would you use to handle these cases?</p>
[ { "answer_id": 244237, "author": "Jens Ayton", "author_id": 6443, "author_profile": "https://Stackoverflow.com/users/6443", "pm_score": 3, "selected": false, "text": "CFRetain(foo) CFRelease(foo) [[NSGarbageCollector defaultCollector] disableCollectorForPointer:foo] [[NSGarbageCollector defaultCollector] enableCollectorForPointer:foo]" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32045/" ]
243,082
<p>Let's say I have a <strong>Base</strong> class and several <strong>Derived</strong> classes. Is there any way to cast an object to one of the derived classes without the need to write something like this :</p> <pre><code> string typename = typeid(*object).name(); if(typename == "Derived1") { Derived1 *d1 = static_cast&lt Derived1*&gt(object); } else if(typename == "Derived2") { Derived2 *d2 = static_cast &lt Derived2*&gt(object); } ... else { ... } </code></pre>
[ { "answer_id": 243111, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 1, "selected": false, "text": "dynamic_cast Dynamic_cast" }, { "answer_id": 243115, "author": "fhe", "author_id": 4445, "author_profile": "https://Stackoverflow.com/users/4445", "pm_score": 3, "selected": false, "text": "dynamic_cast" }, { "answer_id": 243123, "author": "marijne", "author_id": 7038, "author_profile": "https://Stackoverflow.com/users/7038", "pm_score": 3, "selected": false, "text": "Derived1* d1 = dynamic_cast< Derived1* >(object);\nif (d1 == NULL)\n{\n Derived2* d2 = dynamic_cast< Derived2* >(object);\n //etc\n}\n template< class Y > bool is() const throw()\n {return !null() && dynamic_cast< Y* >(ptr) != NULL;}\ntemplate< class Y > Y* as() const throw()\n {return null() ? NULL : dynamic_cast< Y* >(ptr);}\n" }, { "answer_id": 243126, "author": "ChrisN", "author_id": 3853, "author_profile": "https://Stackoverflow.com/users/3853", "pm_score": 2, "selected": false, "text": "dynamic_cast if ( Derived1* d1 = dynamic_cast<Derived1*>(object) ) {\n // object points to a Derived1\n d1->foo();\n}\nelse if ( Derived2* d2 = dynamic_cast<Derived2*>(object) ) {\n // object points to a Derived2\n d2->bar();\n}\nelse {\n // etc.\n}\n" }, { "answer_id": 243150, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 6, "selected": true, "text": "string typename = typeid(*object).name();\nif(typename == \"Derived1\") {\n Derived1 *d1 = static_cast< Derived1*>(object);\n d1->doSomethingUseful();\n}\nelse if(typename == \"Derived2\") {\n Derived2 *d2 = static_cast < Derived2*>(object);\n d2->doSomethingUseful();\n}\n...\nelse {\n ...\n}\n object->doSomethingUseful();\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31610/" ]
243,083
<p>What is a strongly typed dataset? (.net)</p>
[ { "answer_id": 243096, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 4, "selected": false, "text": "EmployeeDataset ds = ...\nEmployeeRow row = ds.Employees.Rows[0];\nrow.Name = \"Joe\";\n DataSet ds = ...\nDataRow row = ds.Tables[\"Employees\"].Rows[0];\nrow[\"Name\"] = \"Joe\";\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
243,097
<p>I have a unit test where I have statically defined a quite large byte array (over 8000 bytes) as the byte data of a file I don't want to read every time I run my unit test.</p> <pre><code>private static final byte[] FILE_DATA = new byte[] { 12,-2,123,................ } </code></pre> <p>This compiles fine within Eclipse, but when compiling via Ant script I get the following error:</p> <pre><code>[javac] C:\workspace\CCUnitTest\src\UnitTest.java:72: code too large [javac] private static final byte[] FILE_DATA = new byte[] { [javac] ^ </code></pre> <p>Any ideas why and how I can avoid this?</p> <hr> <p><strong>Answer</strong>: Shimi's answer did the trick. I moved the byte array out to a separate class and it compiled fine. Thanks!</p>
[ { "answer_id": 244100, "author": "Cem Catikkas", "author_id": 3087, "author_profile": "https://Stackoverflow.com/users/3087", "pm_score": 0, "selected": false, "text": "@BeforeClass" }, { "answer_id": 22637216, "author": "Josh", "author_id": 82505, "author_profile": "https://Stackoverflow.com/users/82505", "pm_score": 0, "selected": false, "text": "private static final byte[] FILE_DATA = new byte[] {12,-2,123,...,<LARGE>};\n private static final class FILE_DATA\n{\n private static final byte[] VALUES = new byte[] {12,-2,123,...,<LARGE>};\n}\n FILE_DATA.VALUES[i] FILE_DATA[i]" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
243,120
<p>Is it possible to get a list of control events that are going to fire before they happen, say inside the <code>Page_Load</code> handler?</p> <p>For example if a button was clicked can I figure this out before the <code>button_click</code> event handler is called?</p>
[ { "answer_id": 243181, "author": "tpower", "author_id": 18107, "author_profile": "https://Stackoverflow.com/users/18107", "pm_score": 0, "selected": false, "text": "Page.Request.Form[\"__EVENTTARGET\"]\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18107/" ]
243,124
<p>Here is the problem: we have lots of Javascripts and lots of CSS files, which we'd rather be serving minified. Minification is easy: set up the YUI Compressor, run an Ant task, and it spits out minified files, which we save beside the originals.</p> <p>So we end up with the following directory structure somewhere inside our DocumentRoot:</p> <pre> / /js /min foo-min.js bar-min.js foo.js bar.js quux.js /css ... </pre> <p>Now what we need is that Apache serve files from the <strong>min</strong> subdirectory, <em>and fallback to serving uncompressed files</em>, if their minified versions are not available. The last issue is the one I cannot solve.</p> <p>For example: suppose we have a request to <strong>example.com/js/foo.js</strong> — in this case Apache should send contents of <strong>/js/min/foo-min.js</strong>. There is no minified <strong>quux.js</strong>, so request to <strong>/js/quux.js</strong> returns <strong>/js/quux.js</strong> itself, not 404. Finally, if there is no <strong>/js/fred.js</strong>, it should end up with 404.</p> <p>Actually, I'm setting build scripts in such a way that unminified files are not deployed on the production server, but this configuration still might be useful on an integration server and on development machines.</p>
[ { "answer_id": 243135, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 0, "selected": false, "text": "ant productionDeploy ant integrationDeploy" }, { "answer_id": 243154, "author": "Ignacio Vazquez-Abrams", "author_id": 20862, "author_profile": "https://Stackoverflow.com/users/20862", "pm_score": 2, "selected": false, "text": "RewriteCond %{REQUESTURI} ^/js/(.*\\.js)\nRewriteCond js/min/%1 -f\nRewriteRule %1 min/%1 [L]\n" }, { "answer_id": 243373, "author": "Stepan Stolyarov", "author_id": 6573, "author_profile": "https://Stackoverflow.com/users/6573", "pm_score": 4, "selected": true, "text": "RewriteEngine On\n\nRewriteBase /js\n\nRewriteCond %{REQUEST_URI} ^/js/((.+)\\.js)$\nRewriteCond %{DOCUMENT_ROOT}/js/min/%2-min.js -f\nRewriteRule ^(.+)$ min/%2-min.js [L]\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6573/" ]
243,132
<p>I have a key that appears to be an empty string, however using <code>unset($array[""]);</code> does not remove the key/value pair. I don't see another function that does what I want, so I'm guessing it's more complicated that just calling a function.</p> <p>The line for the element on a print_r is <code>[] =&gt; 1</code>, which indicates to me that the key is the empty string.</p> <p>Using var_export, the element is listed as <code>'' =&gt; 1</code>.</p> <p>Using var_dump, the element is listed as <code>[""]=&gt;int(1)</code>.</p> <p>So far, I have tried all of the suggested methods of removal, but none have removed the element. I have tried <code>unset($array[""]);</code>, <code>unset($array['']);</code>, and <code>unset($array[null]);</code> with no luck.</p>
[ { "answer_id": 243141, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 1, "selected": false, "text": "foreach ($array as $index => $value) {\n echo $index;\n echo ' is ';\n echo gettype($index);\n echo \"\\n\";\n}\n" }, { "answer_id": 243171, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "$someList = Array('A' => 'Foo', 'B' => 'Bar', '' => 'Bah');\nprint_r($someList);\necho '<br/>';\nunset($someList['A']);\nprint_r($someList);\necho '<br/>';\nunset($someList['']);\nprint_r($someList);\necho '<br/>';\n Array ( [A] => Foo [B] => Bar [] => Bah )\nArray ( [B] => Bar [] => Bah )\nArray ( [B] => Bar )\n" }, { "answer_id": 243194, "author": "Lemming", "author_id": 9454, "author_profile": "https://Stackoverflow.com/users/9454", "pm_score": 6, "selected": true, "text": "unset($array[null]); var_export var_dump print_r var_export var_export($array);" }, { "answer_id": 243199, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 1, "selected": false, "text": "var_dump print_r" }, { "answer_id": 243481, "author": "Lemming", "author_id": 9454, "author_profile": "https://Stackoverflow.com/users/9454", "pm_score": 0, "selected": false, "text": "var_export($array);\necho \"\\n\";\nunset($array[\"\"]);\nvar_export($array);\n var_export array (\n '' => 1,\n)\narray (\n)\n" }, { "answer_id": 243588, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 1, "selected": false, "text": "<?php\n\n$arr = array(\n false => 1\n , true => 2\n , null => 3\n , 'test' => 4\n// , '' => 5\n);\n\nprint_r( $arr );\n\nforeach ( $arr as $key => $value )\n{\n var_dump( $key );\n}\n\nunset( $arr[''] );\n\nprint_r( $arr );\n Array\n(\n [0] => 1\n [1] => 2\n [] => 3\n [test] => 4\n)\nint(0)\nint(1)\nstring(0) \"\"\nstring(4) \"test\"\nArray\n(\n [0] => 1\n [1] => 2\n [test] => 4\n)\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
243,152
<p>The thing is I've been using the <a href="http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx" rel="noreferrer">lock statement</a> to protect a critical part of my code, but now, I realize I could allow concurrent execution of that critical code is some conditions are met.<br> Is there a way to condition the lock?</p>
[ { "answer_id": 243168, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 4, "selected": true, "text": "Action doThatThing = someMethod;\n\nif (condition)\n{\n lock(thatThing)\n {\n doThatThing();\n }\n}\nelse\n{\n doThatThing();\n}\n" }, { "answer_id": 243180, "author": "noocyte", "author_id": 11220, "author_profile": "https://Stackoverflow.com/users/11220", "pm_score": 1, "selected": false, "text": "private Monkey GetScaryMonkey(int numberOfHeads){\n Monkey ape = null; \n lock(this) {\n ape = new Monkey();\n ape.AddHeads(numberOfHeads); \n }\n return ape;\n}\n private Monkey GetScaryMonkey(int numberOfHeads){\n if ( numberOfHeads > 1 ) {\n lock(this) {\n return CreateNewMonkey( numberOfHeads ); \n }\n }\n return CreateNewMonkey( numberOfHeads );\n}\n" }, { "answer_id": 243190, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "ReaderWriterLockSlim if (someCondition) {\n lockObj.EnterReadLock();\n try { Foo(); }\n finally { lockObj.ExitReadLock(); }\n } else {\n lockObj.EnterWriteLock();\n try { Foo(); }\n finally { lockObj.ExitWriteLock(); }\n }\n" }, { "answer_id": 243192, "author": "marijne", "author_id": 7038, "author_profile": "https://Stackoverflow.com/users/7038", "pm_score": 3, "selected": false, "text": "bool locked = false;\nif (condition) {\n Monitor.Enter(lockObject);\n locked = true;\n}\ntry {\n // possibly critical section\n}\nfinally {\n if (locked) Monitor.Exit(lockObject);\n}\n" }, { "answer_id": 243743, "author": "user31934", "author_id": 31934, "author_profile": "https://Stackoverflow.com/users/31934", "pm_score": 3, "selected": false, "text": "private static object lockHolder = new object();\n\nif (ActionIsValid()) {\n lock(lockHolder) {\n if (ActionIsValid()) {\n DoSomething(); \n }\n }\n}\n" }, { "answer_id": 63491084, "author": "l33t", "author_id": 419761, "author_profile": "https://Stackoverflow.com/users/419761", "pm_score": 2, "selected": false, "text": "struct IDisposable public void DoStuff()\n{\n using (ConditionalLock())\n {\n // Thread-safe code\n }\n}\n public class Counter\n{\n private static readonly int MAX_COUNT = 100;\n\n private readonly bool synchronized;\n private int count;\n private readonly object lockObject = new object();\n\n private int lockCount;\n\n public Counter(bool synchronized)\n {\n this.synchronized = synchronized;\n }\n\n public int Count\n {\n get\n {\n using (ConditionalLock())\n {\n return count;\n }\n }\n }\n\n public int LockCount\n {\n get\n {\n using (ConditionalLock())\n {\n return lockCount;\n }\n }\n }\n\n public void Increase()\n {\n using (ConditionalLock())\n {\n if (count < MAX_COUNT)\n {\n Thread.Sleep(10);\n ++count;\n }\n }\n }\n\n private LockHelper ConditionalLock() => new LockHelper(this);\n\n // This is where the magic happens!\n private readonly struct LockHelper : IDisposable\n {\n private readonly Counter counter;\n private readonly bool lockTaken;\n\n public LockHelper(Counter counter)\n {\n this.counter = counter;\n\n lockTaken = false;\n if (counter.synchronized)\n {\n Monitor.Enter(counter.lockObject, ref lockTaken);\n counter.lockCount++;\n }\n }\n\n private void Exit()\n {\n if (lockTaken)\n {\n Monitor.Exit(counter.lockObject);\n }\n }\n\n void IDisposable.Dispose() => Exit();\n }\n}\n class Program\n{\n static void Main(string[] args)\n {\n var onlyOnThisThread = new Counter(synchronized: false);\n IncreaseToMax(c1);\n\n var onManyThreads = new Counter(synchronized: true);\n var t1 = Task.Factory.StartNew(() => IncreaseToMax(c2));\n var t2 = Task.Factory.StartNew(() => IncreaseToMax(c2));\n var t3 = Task.Factory.StartNew(() => IncreaseToMax(c2));\n Task.WaitAll(t1, t2, t3);\n\n Console.WriteLine($\"Counter(false) => Count = {c1.Count}, LockCount = {c1.LockCount}\");\n Console.WriteLine($\"Counter(true) => Count = {c2.Count}, LockCount = {c2.LockCount}\");\n }\n\n private static void IncreaseToMax(Counter counter)\n {\n for (int i = 0; i < 1000; i++)\n {\n counter.Increase();\n }\n }\n}\n Counter(false) => Count = 100, LockCount = 0\nCounter(true) => Count = 100, LockCount = 3002\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23893/" ]
243,170
<p>I'll try to explain my scenario as best i can;</p> <p>At each application <em>tick</em> I query the current state of the keyboard and mouse and wrap them in individual classes and data structures. For the keyboard it's an array of my <em>Keys</em> enum (one item for each of the keys that are currently pressed) and for the mouse it's a class containing coordinate delta's and bools for each buttons pressed.</p> <p>I also have a rudimentary state machine managed via a state manager class which maintains the stack and marshalls the states.</p> <p>All I want to know is, how best to pass the input (snapshots) to the individual states my app can be in at any one time?</p> <p>I would like to process as much of the input as possible away from the individual states, so as to reduce repeating logic within the states.</p> <p>Or would it be better to keep the input snapshots as pure as possible and pass them to the states so they can keep they're input-specific-logic hidden?</p> <p><strong>Note</strong><br/> This structure is similiar to how I imagine a game would work, and although this application is not a game it does need to be processed as quickly as possible.</p>
[ { "answer_id": 243549, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 1, "selected": false, "text": "KeyboardState state = Keyboard.GetState();\n" }, { "answer_id": 244129, "author": "Nicholas Mancuso", "author_id": 8945, "author_profile": "https://Stackoverflow.com/users/8945", "pm_score": 0, "selected": false, "text": "class YourClass\n{ \n //data members ...\n\n public void OnKeyboardPress(object sender, EventArgs args)\n {\n //handle your logic capturing the state here\n }\n}\n\n//elsewhere\nsomeControl.KeyPress += new KeyPressDelegate(yourClassInstance.OnKeyboardPress);\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17540/" ]
243,173
<p>I'm having an issue with a USB project using <code>LIB-USB</code>. The USB device is based on a PIC18F4550 and has a single control endpoint. The PC front-end is written in MSVC and uses Lib-Usb 1.12.</p> <p>On the PC end, the program begins by setting the configuration, claiming the interface, then sending (and receiving) control messages (vendor specific), all successfully. After what seems like a random # of bytes have been transferred (anywhere between 100 and 2000) the transfer halts with an <strong>error rc=-5</strong> returned from the usb_control_msg call.</p> <p>On the PC-end, the calls look like this:</p> <pre><code>ret = usb_set_configuration(udev, 1); ret = usb_claim_interface(udev, 0); ret = usb_control_msg(udev, USB_TYPE_VENDOR|USB_RECIP_DEVICE, CMD_RESET, 0, 0, buffer, 0, 100); ret = usb_control_msg(udev, 0xC0, GET_FIFO_DATA, 0, 0, buffer, 8, 100); </code></pre> <p>The last call, which actually acquires data from the USB device, runs many times in succession but always dies after a random number of bytes (100 to 2000 in total) are transferred in this way. Changing the pipe to EP1 does the same thing with the same error eventually appearing.</p> <p>On the USB device (PIC) end the descriptor is very simple, having only the EP0 pipe, and looks like this:</p> <pre><code>Device db 0x12, DEVICE ; bLength, bDescriptorType db 0x10, 0x01 ; bcdUSB (low byte), bcdUSB (high byte) db 0x00, 0x00 ; bDeviceClass, bDeviceSubClass db 0x00, MAX_PACKET_SIZE ; bDeviceProtocol, bMaxPacketSize db 0xD8, 0x04 ; idVendor (low byte), idVendor (high byte) db 0x01, 0x00 ; idProduct (low byte), idProduct (high byte) db 0x00, 0x00 ; bcdDevice (low byte), bcdDevice (high byte) db 0x01, 0x02 ; iManufacturer, iProduct db 0x00, NUM_CONFIGURATIONS ; iSerialNumber (none), bNumConfigurations Configuration1 db 0x09, CONFIGURATION ; bLength, bDescriptorType db 0x12, 0x00 ; wTotalLength (low byte), wTotalLength (high byte) db NUM_INTERFACES, 0x01 ; bNumInterfaces, bConfigurationValue db 0x00, 0xA0 ; iConfiguration (none), bmAttributes db 0x32, 0x09 ; bMaxPower (100 mA), bLength (Interface1 descriptor starts here) db INTERFACE, 0x00 ; bDescriptorType, bInterfaceNumber db 0x00, 0x00 ; bAlternateSetting, bNumEndpoints (excluding EP0) db 0xFF, 0x00 ; bInterfaceClass (vendor specific class code), bInterfaceSubClass db 0xFF, 0x00 ; bInterfaceProtocol (vendor specific protocol used), iInterface (none) </code></pre> <p>The actual framework is that of Bradley Minch's in assembly language. </p> <p>If anyone has encountered this type of problem before I'd love to hear about it as I've tried just about everything to solve it including using a different pipe (EP1, with the same results), checking the UOWN bit on the PIC before writing to the pipe, handshaking with the PC host (where the PC must send a vendor-specific command first before the datsa is written) but to no avail.</p>
[ { "answer_id": 243748, "author": "Ilya", "author_id": 6807, "author_profile": "https://Stackoverflow.com/users/6807", "pm_score": 1, "selected": false, "text": "vendor_class_request(): request failed: status: 0xc0000001, urb-status: 0xc000000c usb.h:#define USBD_STATUS_BUFFER_OVERRUN ((USBD_STATUS)0xC000000CL)" }, { "answer_id": 252480, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "\"I forgot to read the fine print\"" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
243,193
<p>I have a set of tables that are used to track bills. These tables are loaded from an SSIS process that runs weekly.</p> <p>I am in the process of creating a second set of tables to track adjustments to the bills that are made via the web. Some of our clients hand key their bills and all of those entries need to be backed up on a more regular schedule (the SSIS fed data can always be imported again so it isn't backed up).</p> <p>Is there a best practice for this type of behavior? I'm looking at implementing a DDL trigger that will parse the ALTER TABLE call and change the table being called. This is somewhat painful, and I'm curious if there is a better way.</p>
[ { "answer_id": 252233, "author": "Jeremiah Peschka", "author_id": 11780, "author_profile": "https://Stackoverflow.com/users/11780", "pm_score": 1, "selected": true, "text": "-- Create pvt and pvtWeb as test tables\nCREATE TABLE [dbo].[pvt](\n [VendorID] [int] NULL,\n [Emp1] [int] NULL,\n [Emp2] [int] NULL,\n [Emp3] [int] NULL,\n [Emp4] [int] NULL,\n [Emp5] [int] NULL\n) ON [PRIMARY];\nGO\n\n\nCREATE TABLE [dbo].[pvtWeb](\n [VendorID] [int] NULL,\n [Emp1] [int] NULL,\n [Emp2] [int] NULL,\n [Emp3] [int] NULL,\n [Emp4] [int] NULL,\n [Emp5] [int] NULL\n) ON [PRIMARY];\nGO\n\n\nIF EXISTS(SELECT * FROM sys.triggers WHERE name = ‘ddl_trigger_pvt_alter’)\n DROP TRIGGER ddl_trigger_pvt_alter ON DATABASE;\nGO\n\n-- Create a trigger that will trap ALTER TABLE events\nCREATE TRIGGER ddl_trigger_pvt_alter\nON DATABASE\nFOR ALTER_TABLE\nAS\n DECLARE @data XML;\n DECLARE @tableName NVARCHAR(255);\n DECLARE @newTableName NVARCHAR(255);\n DECLARE @sql NVARCHAR(MAX);\n\n SET @sql = ”;\n -- Store the event in an XML variable\n SET @data = EVENTDATA();\n\n -- Get the name of the table that is being modified\n SELECT @tableName = @data.value(‘(/EVENT_INSTANCE/ObjectName)[1]‘, ‘NVARCHAR(255)’);\n -- Get the actual SQL that was executed\n SELECT @sql = @data.value(‘(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]‘, ‘NVARCHAR(MAX)’);\n\n -- Figure out the name of the new table\n SET @newTableName = @tableName + ‘Web’;\n\n -- Replace the original table name with the new table name\n -- str_replace is from Robyn Page and Phil Factor’s delighful post on \n -- string arrays in SQL. The other posts on string functions are indispensible\n -- to handling string input\n --\n -- http://www.simple-talk.com/sql/t-sql-programming/tsql-string-array-workbench/\n -- http://www.simple-talk.com/sql/t-sql-programming/sql-string-user-function-workbench-part-1/\n --http://www.simple-talk.com/sql/t-sql-programming/sql-string-user-function-workbench-part-2/\n SET @sql = dbo.str_replace(@tableName, @newTableName, @sql);\n\n -- Debug the SQL if needed.\n --PRINT @sql;\n\n IF OBJECT_ID(@newTableName, N’U’) IS NOT NULL\n BEGIN\n BEGIN TRY\n -- Now that the table name has been changed, execute the new SQL\n EXEC sp_executesql @sql;\n END TRY\n BEGIN CATCH\n -- Rollback any existing transactions and report the full nasty \n -- error back to the user.\n IF @@TRANCOUNT > 0\n ROLLBACK TRANSACTION;\n\n DECLARE\n @ERROR_SEVERITY INT,\n @ERROR_STATE INT,\n @ERROR_NUMBER INT,\n @ERROR_LINE INT,\n @ERROR_MESSAGE NVARCHAR(4000);\n\n SELECT\n @ERROR_SEVERITY = ERROR_SEVERITY(),\n @ERROR_STATE = ERROR_STATE(),\n @ERROR_NUMBER = ERROR_NUMBER(),\n @ERROR_LINE = ERROR_LINE(),\n @ERROR_MESSAGE = ERROR_MESSAGE();\n\n RAISERROR(‘Msg %d, Line %d, :%s’,\n @ERROR_SEVERITY,\n @ERROR_STATE,\n @ERROR_NUMBER,\n @ERROR_LINE,\n @ERROR_MESSAGE);\n END CATCH\n END\nGO\n\n\n\n\nALTER TABLE pvt\nADD test INT NULL;\nGO\n\nEXEC sp_help pvt;\nGO\n\nALTER TABLE pvt\nDROP COLUMN test;\nGO\n\nEXEC sp_help pvt;\nGO\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11780/" ]
243,200
<p>I'm looking to improve my PHP coding and am wondering what PHP-specific techniques other programmers use to improve productivity or workaround PHP limitations.</p> <p>Some examples:</p> <ol> <li><p>Class naming convention to handle namespaces: <code>Part1_Part2_ClassName</code> maps to file <code>Part1/Part2/ClassName.php</code></p></li> <li><p><code>if ( count($arrayName) ) // handles $arrayName being unset or empty</code></p></li> <li><p>Variable function names, e.g. <code>$func = 'foo'; $func($bar); // calls foo($bar);</code></p></li> </ol>
[ { "answer_id": 243254, "author": "changelog", "author_id": 5646, "author_profile": "https://Stackoverflow.com/users/5646", "pm_score": 3, "selected": false, "text": "ini_set('display_errors', '1');\nerror_reporting(E_ALL); require_once if(isset($array[$key])) if($array[$key]) for $listIndex $j" }, { "answer_id": 243337, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 3, "selected": false, "text": "=== == if (array_search('needle',$array) == false) {\n // it's not there, i think...\n}\n if (array_search('needle',$array) === false) {\n // it's not there!\n}\n" }, { "answer_id": 245663, "author": "Preston", "author_id": 25213, "author_profile": "https://Stackoverflow.com/users/25213", "pm_score": 4, "selected": false, "text": "spl_autoload_register() __autoload() function f(SomeClass $x, array $y, $z) {\n assert(is_bool($z))\n}\n header('Content-type: text/xml'); // or text/css, application/pdf, or...\n define() Date unset() ob_start();\necho \"whatever\\n\";\ndebug_print_backtrace();\n$s = ob_get_clean();\n __get __set __call extract()" }, { "answer_id": 246571, "author": "Jrgns", "author_id": 6681, "author_profile": "https://Stackoverflow.com/users/6681", "pm_score": 2, "selected": false, "text": "ini_set('display_errors', 1); error_reporting(E_ALL && $_STRICT);" }, { "answer_id": 452941, "author": "too much php", "author_id": 28835, "author_profile": "https://Stackoverflow.com/users/28835", "pm_score": 2, "selected": false, "text": "=== strpos() return false" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4890/" ]
243,215
<p>Did someone ever used a BIRT report in a desktop application. I'm comming from the .NET environment and there you can use Crystal Reports to show reports in desktop apps. Is this possible with BIRT too, without having to set up a server environment?</p> <p>Can you give me some advice how to reach this goal?</p> <p>Thanks in advance.</p>
[ { "answer_id": 243222, "author": "paul", "author_id": 11249, "author_profile": "https://Stackoverflow.com/users/11249", "pm_score": 2, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<classpath>\n <classpathentry kind=\"src\" path=\"src\"/>\n <classpathentry kind=\"con\" path=\"org.eclipse.jdt.launching.JRE_CONTAINER\"/>\n <classpathentry kind=\"var\" path=\"JUNIT_HOME/junit.jar\" sourcepath=\"JUNIT_SRC_HOME/junitsrc.zip\"/>\n <classpathentry kind=\"lib\" path=\"lib/log4j-1.2.14.jar\"/>\n <classpathentry kind=\"lib\" path=\"lib/swt.jar\"/>\n <classpathentry kind=\"con\" path=\"SWT_CONTAINER\"/>\n <classpathentry kind=\"lib\" path=\"org.eclipse.birt.chart_2.1.2.v20070205-1728.jar\"/>\n <classpathentry kind=\"lib\" path=\"org.eclipse.birt.chart.device.extension_2.1.2.v20070205-1728.jar\"/>\n <classpathentry kind=\"lib\" path=\"org.eclipse.birt.chart.device.swt_2.1.1.v20070205-1728.jar\"/>\n <classpathentry kind=\"lib\" path=\"org.eclipse.birt.chart.engine_2.1.2.v20070205-1728.jar\" sourcepath=\"C:/Programme/eclipse/plugins/org.eclipse.birt.chart.source_2.2.0.v20070209/src\"/>\n <classpathentry kind=\"lib\" path=\"org.eclipse.birt.chart.engine.extension_2.1.2.v20070205-1728.jar\"/>\n <classpathentry kind=\"lib\" path=\"org.eclipse.birt.chart.runtime_2.1.2.v20070205-1728.jar\"/>\n <classpathentry kind=\"lib\" path=\"org.eclipse.birt.core_2.1.2.v20070205-1728.jar\"/>\n <classpathentry kind=\"lib\" path=\"org.eclipse.emf.common_2.2.1.v200609210005.jar\"/>\n <classpathentry kind=\"lib\" path=\"org.eclipse.emf.ecore_2.2.1.v200609210005.jar\"/>\n <classpathentry kind=\"lib\" path=\"org.eclipse.emf.ecore.xmi_2.2.1.v200609210005.jar\"/>\n <classpathentry kind=\"lib\" path=\"js.jar\"/>\n <classpathentry kind=\"lib\" path=\"com.ibm.icu_3.4.5.jar\"/>\n <classpathentry kind=\"lib\" path=\"org.eclipse.birt.chart.ui_2.1.1.v20070205-1728.jar\"/>\n <classpathentry kind=\"lib\" path=\"org.eclipse.birt.chart.ui.extension_2.1.2.v20070205-1728.jar\"/>\n <classpathentry kind=\"lib\" path=\"lib/hsqldb.jar\"/>\n <classpathentry kind=\"output\" path=\"bin\"/>\n</classpath>\n" }, { "answer_id": 21038235, "author": "Alexandr Zaichenko", "author_id": 3172544, "author_profile": "https://Stackoverflow.com/users/3172544", "pm_score": 0, "selected": false, "text": "package com.passport;\n\nimport java.io.FileOutputStream;\nimport java.util.Collection;\nimport java.util.Iterator;\n\n\nimport org.eclipse.birt.core.framework.Platform;\nimport org.eclipse.birt.report.engine.api.EngineConfig;\nimport org.eclipse.birt.report.engine.api.IGetParameterDefinitionTask;\nimport org.eclipse.birt.report.engine.api.IParameterDefnBase;\nimport org.eclipse.birt.report.engine.api.IRenderOption;\nimport org.eclipse.birt.report.engine.api.IReportEngine;\nimport org.eclipse.birt.report.engine.api.IReportEngineFactory;\nimport org.eclipse.birt.report.engine.api.IReportRunnable;\nimport org.eclipse.birt.report.engine.api.IRunAndRenderTask;\nimport org.eclipse.birt.report.engine.api.RenderOption;\n\npublic class EngineReport {\n private static final long serialVersionUID = 1L; \n private IReportEngine engine=null; \n private EngineConfig engineconfig = null;\n private IReportEngineFactory factory = null;\n private String sourceReport;\n private String locationReport;\n private String reportRealPath = \"\";\n\npublic static void main(String[] args){\n EngineReport engineReport = new EngineReport();\n engineReport.save(\"src/com/passport/report.rptdesign\",\"c:/tmp/rep.doc\");\n}\n\nprivate void save(String sourceReport, String locationReport) {\n\n this.sourceReport = sourceReport;\n this.locationReport = locationReport;\n IReportRunnable design = null;\n IRenderOption options = null;\n try {\n String reportFormat = locationReport.substring(locationReport.lastIndexOf('.')+1);\n sourceReport = \"src/com/passport/report.rptdesign\";\n if ((sourceReport != null && (sourceReport.length() > 0)) ) {\n\n engineconfig = new EngineConfig();\n reportRealPath = \"\"; \n Platform.startup(engineconfig);\n factory = (IReportEngineFactory) Platform.createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY); \n engine = factory.createReportEngine(engineconfig);\n design = engine.openReportDesign(reportRealPath+sourceReport); \n IRunAndRenderTask task = engine.createRunAndRenderTask(design); \n\n IGetParameterDefinitionTask taskParam = engine.createGetParameterDefinitionTask( design );\n Collection<?> params = taskParam.getParameterDefns( false );\n String paramName = null;\n Iterator<?> iterOuter = params.iterator( );\n while ( iterOuter.hasNext( ) ) {\n IParameterDefnBase param = (IParameterDefnBase) iterOuter.next( );\n paramName = param.getName( ); \n if (paramName.equalsIgnoreCase(\"PR_SOME_PARAM\")) {\n task.setParameterValue(paramName,\"someparam\");\n } \n else if (paramName.equalsIgnoreCase(\"PR_SOME_PARAM_2\")) {\n task.setParameterValue(paramName,\"someparam2\");\n }\n } \n options = new RenderOption(); \n options.setOutputFormat(reportFormat);\n\n FileOutputStream fos = new FileOutputStream(locationReport);\n options.setOutputStream(fos);\n task.setRenderOption(options);\n task.run();\n task.close();\n engine.destroy();\n fos.close();\n\n }\n } catch(Exception e) {\n System.out.println(e.toString());\n }\n}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
243,217
<p>I keep it in single line, if it's short. Lately I've been using this style for longer or nested ternary operator expressions. A contrived example:</p> <pre><code>$value = ( $a == $b ) ? 'true value # 1' : ( $a == $c ) ? 'true value # 2' : 'false value'; </code></pre> <p>Personally which style you use, or find most readable?</p> <p><strong>Edit:</strong> <em>(on when to use ternary-operator)</em></p> <p>I usually avoid using more than 2 levels deep ternary operator. I tend prefer 2 levels deep ternary operator over 2 level if-else, when I'm echoing variables in PHP template scripts.</p>
[ { "answer_id": 243229, "author": "biozinc", "author_id": 30698, "author_profile": "https://Stackoverflow.com/users/30698", "pm_score": 5, "selected": false, "text": "if else if else\n" }, { "answer_id": 243240, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 2, "selected": false, "text": "if else if else" }, { "answer_id": 243241, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 6, "selected": false, "text": "$value = ($a < 0) ? 'minus' : 'plus';\n" }, { "answer_id": 243349, "author": "Simon Howard", "author_id": 24806, "author_profile": "https://Stackoverflow.com/users/24806", "pm_score": 8, "selected": true, "text": " result = (foo == bar) ? result1 :\n (foo == baz) ? result2 :\n (foo == qux) ? result3 :\n (foo == quux) ? result4 : \n fail_result;\n" }, { "answer_id": 246914, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "$foo = (isset($bar)) ? $bar : 'default';\n" }, { "answer_id": 246985, "author": "Vinze", "author_id": 26859, "author_profile": "https://Stackoverflow.com/users/26859", "pm_score": 1, "selected": false, "text": "String var = (obj == null) ? \"not set\" : obj.toString();\n String val; [...]\nint var = (val == null) ? 0 : Integer.parseInt(val);\n" }, { "answer_id": 283256, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 5, "selected": false, "text": "$result = ($x == y)\n ? \"foo\"\n : \"bar\";\n = ? :" }, { "answer_id": 1475108, "author": "Chris Jacob", "author_id": 114140, "author_profile": "https://Stackoverflow.com/users/114140", "pm_score": 4, "selected": false, "text": "$myvar = ($x == $y)\n?(($x == $z)?'both':'foo')\n:(($x == $z)?'bar':'none');\n $x = 1;\n$y = 2;\n$z = 3; \n$myvar = ($x == $y) \n ? \"foo\" \n : ($x == $z) \n ? \"bar\" \n : \"none\"; \n$myvar == 'none'; // Good\n\n$x = 1;\n$y = 2;\n$z = 1; \n$myvar = ($x == $y) ? \"foo\" : ($x == $z) ? \"bar\" : \"none\"; \n$myvar == 'bar'; // Good\n\n$x = 1;\n$y = 1;\n$z = 3; \n$myvar = ($x == $y) ? \"foo\" : ($x == $z) ? \"bar\" : \"none\"; \n$myvar == 'bar'; // Bad!\n\n$x = 1;\n$y = 1;\n$z = 1; \n$myvar = ($x == $y) ? \"foo\" : ($x == $z) ? \"bar\" : \"none\"; \n$myvar == 'bar'; // Bad!\n" }, { "answer_id": 4902530, "author": "Patrick Szalapski", "author_id": 7453, "author_profile": "https://Stackoverflow.com/users/7453", "pm_score": 2, "selected": false, "text": " 'before refactoring \n If x = 0 Then ' If-Then-Else puts emphasis on flow control\n label = \"None\"\n Else\n label = Foo.getLabel(x) ' If-Then-Else forces repeat of assignment line\n End If\n\n 'after refactoring \n label = If(x = 0, \"None\", Foo.getLabel(x)) ' ternary If puts emphasis on assignment\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1897/" ]
243,218
<p>I think in this case there is no need to declare a public constructor since the class is not accessible outside the package anyway. But is there some hidden impact when the class has only package private constructor?</p>
[ { "answer_id": 243276, "author": "Denis R.", "author_id": 32015, "author_profile": "https://Stackoverflow.com/users/32015", "pm_score": 2, "selected": false, "text": "public" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/446104/" ]
243,232
<p>Inside my page, I have the following:</p> <pre><code>&lt;aspe:UpdatePanel runat="server" ID="updatePanel"&gt; &lt;ContentTemplate&gt; &lt;local:KeywordSelector runat="server" ID="ksKeywords" /&gt; &lt;/ContentTemplate&gt; &lt;/aspe:UpdatePanel&gt; </code></pre> <p>The <code>KeywordSelector</code> control is a control I define in the same assembly and <code>local</code> is mapped to its namespace.</p> <p>The control is made up of several other controls and is defined as such:</p> <pre><code>&lt;%@ Control Language="C#" AutoEventWireup="true" CodeBehind="KeywordSelector.ascx.cs" Inherits="Keywords.KeywordSelector" %&gt; </code></pre> <p>and has quite a few server controls of its own, all defined as members in the <code>.designer.cs</code> file.</p> <p>However, <strong>during no part of the control's lifecycle does it have any child control objects nor does it produce HTML</strong>:</p> <ol> <li>All of the members defined in the <code>.designer.cs</code> file are <code>null</code>.</li> <li>Calls to <code>HasControls</code> return <code>false</code>.</li> <li>Calls to <code>EnsureChildControls</code> do nothing.</li> <li>The <code>Controls</code> collection is empty.</li> </ol> <p>Removing the <code>UpdatePanel</code> did no good. I tried to reproduce it in a clean page with a new <code>UserControl</code> and the same thing happens.</p> <p>I am using ASP.NET over .NET Framework 3.5 SP1 with the integrated web server.</p> <p>What am I missing here?</p> <p><strong>Update #1:</strong> Following Rob's comment, I looked into <code>OnInit</code> and found that the <code>UserControl</code> does not detect that it has any child controls. Moreover, <code>CreateControlCollection</code> is never called!</p>
[ { "answer_id": 243493, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 6, "selected": true, "text": "<add tagPrefix=\"local\" tagName=\"KeywordSelector\" src=\"~/KeywordSelector.ascx\" /> <add tagPrefix=\"local\" namespace=\"Keywords\" assembly=\"Keywords\" /> WebControl Control" }, { "answer_id": 26551804, "author": "vladimir", "author_id": 303298, "author_profile": "https://Stackoverflow.com/users/303298", "pm_score": 1, "selected": false, "text": "<%@ Register Src=\"~/Controls/Hello/Hello.ascx\" TagName=\"Hello\" TagPrefix=\"p\" %>\n <%@ Register TagPrefix=\"p\" Namespace=\"MyNamespace.WebApp.Controls\" Assembly=\"MyApp.Web\" %>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4979/" ]
243,237
<p>I am using a ASP/.Net webpage and i want to upload a pdf file into a SQL Database as a binary I am uping the build in upload control, can you please suggest a way of doing this. I also need to no how to read the pdf back and display it in a web browser. I will be using linq to upload and query my sql database.</p>
[ { "answer_id": 243250, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 2, "selected": false, "text": "VARBINARY(MAX) Binary byte[]" }, { "answer_id": 243431, "author": "Leandro López", "author_id": 22695, "author_profile": "https://Stackoverflow.com/users/22695", "pm_score": 2, "selected": false, "text": "HttpHandler <%@ Page Language=\"C#\" AutoEventWireup=\"false\" CodeFile=\"SendPDF.aspx.vb\" Inherits=\"SendPDF\" %>\n SendPDF.aspx.vb partial class EWTD : System.Web.UI.Page\n{\n    \n    protected void Page_Load(object sender, System.EventArgs e)\n    {\n        Response.ContentType = \"application/pdf\";\n        Response.BinaryWrite(GetPDF());\n    }\n    \n    protected byte[] GetPDF()\n    {\n        // Here you will retrieve the PDF as an array of bytes\n    }\n    \n}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
243,242
<p>I had the following piece of code (simplified for this question):</p> <pre><code>struct StyleInfo { int width; int height; }; typedef int (StyleInfo::*StyleInfoMember); void AddStyleInfoMembers(std::vector&lt;StyleInfoMember&gt;&amp; members) { members.push_back(&amp;StyleInfo::width); members.push_back(&amp;StyleInfo::height); } </code></pre> <p>Now, we had to restructure this a bit, and we did something like this:</p> <pre><code>struct Rectangle { int width; int height; }; struct StyleInfo { Rectangle size; }; typedef int (StyleInfo::*StyleInfoMember); void AddStyleInfoMembers(std::vector&lt;StyleInfoMember&gt;&amp; members) { members.push_back(&amp;StyleInfo::size::width); members.push_back(&amp;StyleInfo::size::height); } </code></pre> <p>If this all looks like a stupid thing to do, or if you feel there's a good opportunity to apply BOOST here for some reason, I must warn you that I really simplified it all down to the problem at hand:</p> <blockquote> <p>error C3083: 'size': the symbol to the left of a '::' must be a type</p> </blockquote> <p>The point I'm trying to make is that I don't know what the correct syntax is to use here. It might be that "StyleInfo" is not the correct type of take the address from to begin with, but in my project I can fix that sort of thing (there's a whole framework there). I simply don't know how to point to this member-within-a-member.</p>
[ { "answer_id": 243396, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 1, "selected": false, "text": "typedef Rectangle (StyleInfo::*StyleInfoMember);\ntypedef int (Rectangle::*RectangleMember);\n" }, { "answer_id": 243418, "author": "andreas buykx", "author_id": 19863, "author_profile": "https://Stackoverflow.com/users/19863", "pm_score": 0, "selected": false, "text": "&StyleInfo::size::width" }, { "answer_id": 243829, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 3, "selected": true, "text": " Obj x;\n\n int y = (x.*)ptrMem;\n #include <vector>\n#include <iostream>\n\n\nstruct Rectangle\n{\n int width;\n int height;\n};\n\nstruct StyleInfo\n{\n Rectangle size;\n};\n\ntypedef Rectangle (StyleInfo::*StyleInfoMember);\ntypedef int (Rectangle::*RectangleMember);\n\ntypedef std::pair<StyleInfoMember,RectangleMember> Access;\n\nvoid AddStyleInfoMembers(std::vector<Access>& members)\n{\n members.push_back(std::make_pair(&StyleInfo::size,&Rectangle::width));\n members.push_back(std::make_pair(&StyleInfo::size,&Rectangle::height));\n}\n\n\nint main()\n{\n std::vector<Access> data;\n AddStyleInfoMembers(data);\n\n StyleInfo obj;\n obj.size.width = 10;\n\n std::cout << obj.*(data[0].first).*(data[0].second) << std::endl;\n}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/455874/" ]
243,252
<p>We're doing a lot of large, but straightforward forms for a fairly big project (about 600 users using it throughout the day - that's big for me at least ;-) ).</p> <p>The forms have a lot of question/answer type sections, so it's natural for some people to type a sentence, while others type a novel. <strong>How beneficial would it be to put a character limit on some of these fields <em>really</em>?</strong></p> <p>(Please include references or citations, if necessary/possible - Thanks!)</p>
[ { "answer_id": 243287, "author": "dl__", "author_id": 28565, "author_profile": "https://Stackoverflow.com/users/28565", "pm_score": 1, "selected": false, "text": "Type - Maximum Length -Storage\nTINYBLOB, TINYTEXT 255 Length+1 bytes\nBLOB, TEXT 65535 Length+2 bytes\nMEDIUMBLOB, MEDIUMTEXT 16777215 Length+3 bytes\nLONGBLOB, LONGTEXT 4294967295 Length+4 bytes\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25538/" ]
243,266
<p>Core Animation allows for custom animations by implementing the actionForKey method in your CALayer based class:</p> <pre><code>- (id&lt;CAAction&gt;)actionForKey:(NSString *)key { // Custom animations return [super actionForKey:key]; } </code></pre> <p>I can then create an animation and return it for the <code>onOrderIn</code> action (i.e. when the layer is added to another layer). This works just fine. If I do the same for <code>onOrderOut</code> (i.e. the layer is removed from its superlayer), the returned animation is ignored, and the default animation is applied instead.</p> <p>My goal is to zoom the layer in (<code>onOrderIn</code>) and out (<code>onOrderOut</code>):</p> <pre><code>- (id&lt;CAAction&gt;)actionForKey:(NSString *)key { if ([key isEqualToString:@"onOrderIn"] || [key isEqualToString:@"onOrderOut"]) { CABasicAnimation *a = [CABasicAnimation animationWithKeyPath:@"transform.scale"]; a.duration = 0.25; a.removedOnCompletion = NO; a.fillMode = kCAFillModeBoth; if ([key isEqualToString:@"onOrderIn"]) { a.fromValue = [NSNumber numberWithFloat:0.0]; a.toValue = [NSNumber numberWithFloat:1.0]; } else { a.fromValue = [NSNumber numberWithFloat:1.0]; a.toValue = [NSNumber numberWithFloat:0.0]; } return a; } return [super actionForKey:key]; } </code></pre> <p>Zooming in works, zooming out does not. Instead the default fade out animation is used. </p> <p>The code might contain some typos, as I'm typing this on another machine.</p> <p>Can anyone help?</p>
[ { "answer_id": 245089, "author": "Colin Barrett", "author_id": 23106, "author_profile": "https://Stackoverflow.com/users/23106", "pm_score": 0, "selected": false, "text": "key @\"onOrderOut\"" }, { "answer_id": 1285044, "author": "tjw", "author_id": 11029, "author_profile": "https://Stackoverflow.com/users/11029", "pm_score": 3, "selected": true, "text": "animationDidStop:" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9454/" ]
243,267
<p>I'm looking for an efficient way of searching through a dataset to see if an item exists. I have an arraylist of ~6000 items and I need to determine which of those doesn't exist in the dataset by comparing each item within the arraylist with data in a particular column of the dataset.</p> <p>I attempted to loop through each item in the dataset for each in the arraylist but that took forever. I then attempted to use the RowFilter method below. None of which looks to be efficient. Any help is greatly appreciated, as you can tell I'm not much of a programmer...</p> <p>example:</p> <pre><code>Dim alLDAPUsers As ArrayList alLDAPUsers = clsLDAP.selectAllStudents Dim curStu, maxStu As Integer maxStu = alLDAPUsers.Count For curStu = 0 To maxStu - 1 Dim DomainUsername As String = "" DomainUsername = alLDAPUsers.Item(curStu).ToString Dim filteredView As DataView filteredView = dsAllStudents.Tables(0).DefaultView filteredView.RowFilter = "" filteredView.RowFilter = "szvausr_un = '" &amp; DomainUsername &amp; "'" Dim returnedrows As Integer = filteredView.Count If returnedrows = 0 Then '' Delete the user... End If Next </code></pre>
[ { "answer_id": 243309, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "Dim LDAPUsers As List(Of String) = clsLDAP.selectAllStudents\n\nFor Each DomainUsername As String in LDAPUsers\n Dim filteredView As DataView = dsAllStudents.Tables(0).DefaultView\n filteredView.RowFilter = \"szvausr_un = '\" & DomainUsername & \"'\"\n\n If filteredView.Count = 0 Then\n '' Delete the user...\n End If\nNext\n" }, { "answer_id": 243320, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 0, "selected": false, "text": "Dim alLDAPUsers As ArrayList\nDim DomainUsername As String\nDim curStu, maxStu As Integer\nDim filteredView As DataView\nDim returnedrows As Integer\n\nalLDAPUsers = clsLDAP.selectAllStudents\nmaxStu = alLDAPUsers.Count\n\nFor curStu = 0 To maxStu - 1\n DomainUsername = alLDAPUsers.Item(curStu).ToString\n\n\n filteredView = dsAllStudents.Tables(0).DefaultView\n filteredView.RowFilter = \"szvausr_un = '\" & DomainUsername & \"'\"\n\n returnedrows = filteredView.Count\n If returnedrows = 0 Then\n '' Delete the user...\n End If\nNext\n" }, { "answer_id": 243389, "author": "Carl", "author_id": 951280, "author_profile": "https://Stackoverflow.com/users/951280", "pm_score": 2, "selected": false, "text": "for each s as string in LDAPUsers.Except(AllStudents)\n ''Delete the user (s)\nnext\n LDAPUsers.Except(AllStudents, StringComparer.InvariantCultureIgnoreCase)\n Dim LDAPUsers as new List(Of String)(alLDAPUsers.Cast(Of String))\nDim AllStudents as new List(OfString)()\n\nfor each dr as DataRow in dsAllStudents.Tables(0).Rows\n AllStudents.Add(dr(\"szvausr_un\"))\nnext\n" }, { "answer_id": 319173, "author": "codeConcussion", "author_id": 1321, "author_profile": "https://Stackoverflow.com/users/1321", "pm_score": 1, "selected": false, "text": "dsAllStudents.Tables(0).Select(\"szvausr_un = '\" & DomainUserName & \"'\")\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32059/" ]
243,269
<p>Windows Mobile pops up a "busy wheel" - a rotating colour disk - when things are happening . I can't find in the documentation how this is done - can someone point me in the right direction?</p> <p>We have a situation where we need to prompt the user to say we're doing stuff for a while, but we don't know how long it will take. So we can't do a progress bar, hence the proposal to use this busy wheel.</p>
[ { "answer_id": 243282, "author": "SmacL", "author_id": 22564, "author_profile": "https://Stackoverflow.com/users/22564", "pm_score": 2, "selected": false, "text": "void DoSomethingSlow()\n{\n CWaitCursor cw;\n.\n.\n.\n.\n}\n" }, { "answer_id": 243304, "author": "ctacke", "author_id": 13154, "author_profile": "https://Stackoverflow.com/users/13154", "pm_score": 4, "selected": true, "text": "SetCursor(LoadCursor(NULL, IDC_WAIT));\n\n// my code\n\nShowCursor(FALSE);\n" }, { "answer_id": 243336, "author": "Mat Nadrofsky", "author_id": 26853, "author_profile": "https://Stackoverflow.com/users/26853", "pm_score": 0, "selected": false, "text": "try {\n Cursor.Current = Cursors.WaitCursor;\n //Do something time consuming…\n}\nfinally {\n Cursor.Current = Cursors.Default;\n}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21755/" ]
243,274
<p>I was wondering how to unit test abstract classes, and classes that extend abstract classes.</p> <p>Should I test the abstract class by extending it, stubbing out the abstract methods, and then test all the concrete methods? Then only test the methods I override, and test the abstract methods in the unit tests for objects that extend my abstract class?</p> <p>Should I have an abstract test case that can be used to test the methods of the abstract class, and extend this class in my test case for objects that extend the abstract class?</p> <p>Note that my abstract class has some concrete methods.</p>
[ { "answer_id": 243451, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "public abstract class MyBase{\n /*...*/\n public abstract void VoidMethod(object param1);\n public abstract object MethodWithReturn(object param1);\n /*,,,*/\n}\n public class MyBaseHarness : MyBase{\n /*...*/\n public Action<object> VoidMethodFunction;\n public override void VoidMethod(object param1){\n VoidMethodFunction(param1);\n }\n public Func<object, object> MethodWithReturnFunction;\n public override object MethodWithReturn(object param1){\n return MethodWihtReturnFunction(param1);\n }\n /*,,,*/\n}\n" }, { "answer_id": 30272586, "author": "shreeram banne", "author_id": 4319188, "author_profile": "https://Stackoverflow.com/users/4319188", "pm_score": 2, "selected": false, "text": " public abstract class A \n\n {\n\n public boolean method 1\n {\n // concrete method which we have to test.\n\n }\n\n\n }\n\n\n class B extends class A\n\n {\n\n @override\n public boolean method 1\n {\n // override same method as above.\n\n }\n\n\n } \n\n\n class Test_A \n\n {\n\n private static B b; // reference object of the class B\n\n @Before\n public void init()\n\n {\n\n b = new B (); \n\n }\n\n @Test\n public void Test_method 1\n\n {\n\n b.method 1; // use some assertion statements.\n\n }\n\n }\n" }, { "answer_id": 41810622, "author": "Arpit Aggarwal", "author_id": 3118209, "author_profile": "https://Stackoverflow.com/users/3118209", "pm_score": 1, "selected": false, "text": "@Test import java.util.ArrayList;\nimport java.util.List;\n\npublic abstract class ABC {\n\n abstract String sayHello();\n\n public List<String> getList() {\n final List<String> defaultList = new ArrayList<>();\n defaultList.add(\"abstract class\");\n return defaultList;\n }\n}\n public class DEF extends ABC {\n\n @Override\n public String sayHello() {\n return \"Hello!\";\n }\n}\n import org.junit.Before;\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.Matchers.empty;\nimport static org.hamcrest.Matchers.is;\nimport static org.hamcrest.Matchers.not;\nimport static org.hamcrest.Matchers.contains;\nimport java.util.Collection;\nimport java.util.List;\nimport static org.hamcrest.Matchers.equalTo;\n\nimport org.junit.Test;\n\npublic class DEFTest {\n\n private DEF def;\n\n @Before\n public void setup() {\n def = new DEF();\n }\n\n @Test\n public void add(){\n String result = def.sayHello();\n assertThat(result, is(equalTo(\"Hello!\")));\n }\n\n @Test\n public void getList(){\n List<String> result = def.getList();\n assertThat((Collection<String>) result, is(not(empty())));\n assertThat(result, contains(\"abstract class\"));\n }\n}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3050/" ]
243,277
<p>My SQL is rusty -- I have a simple requirement to calculate the sum of the greater of two column values:</p> <pre><code>CREATE TABLE [dbo].[Test] ( column1 int NOT NULL, column2 int NOT NULL ); insert into Test (column1, column2) values (2,3) insert into Test (column1, column2) values (6,3) insert into Test (column1, column2) values (4,6) insert into Test (column1, column2) values (9,1) insert into Test (column1, column2) values (5,8) </code></pre> <p>In the absence of the GREATEST function in SQL Server, I can get the larger of the two columns with this:</p> <pre><code>select column1, column2, (select max(c) from (select column1 as c union all select column2) as cs) Greatest from test </code></pre> <p>And I was hoping that I could simply sum them thus:</p> <pre><code>select sum((select max(c) from (select column1 as c union all select column2) as cs)) from test </code></pre> <p>But no dice:</p> <pre><code>Msg 130, Level 15, State 1, Line 7 Cannot perform an aggregate function on an expression containing an aggregate or a subquery. </code></pre> <p>Is this possible in T-SQL without resorting to a procedure/temp table?</p> <p>UPDATE: Eran, thanks - I used this approach. My final expression is a little more complicated, however, and I'm wondering about performance in this case:</p> <pre><code>SUM(CASE WHEN ABS(column1 * column2) &gt; ABS(column3 * column4) THEN column5 * ABS(column1 * column2) * column6 ELSE column5 * ABS(column3 * column4) * column6 END) </code></pre>
[ { "answer_id": 243292, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 1, "selected": false, "text": "SELECT\n 'LargerValue' = CASE \n WHEN SUM(c1) >= SUM(c2) THEN SUM(c1)\n ELSE SUM(c2)\n END\nFROM Test\n" }, { "answer_id": 243308, "author": "Eran Galperin", "author_id": 10585, "author_profile": "https://Stackoverflow.com/users/10585", "pm_score": 5, "selected": true, "text": " SELECT SUM(CASE WHEN column1 > column2 \n THEN column1 \n ELSE column2 END) \n FROM test\n" }, { "answer_id": 243326, "author": "changelog", "author_id": 5646, "author_profile": "https://Stackoverflow.com/users/5646", "pm_score": 1, "selected": false, "text": "SELECT\n SUM(MaximumValue)\nFROM (\n SELECT \n CASE WHEN column1 > column2\n THEN\n column1\n ELSE\n column2\n END AS MaximumValue\n FROM\n Test\n) A" }, { "answer_id": 1665942, "author": "Dev Shah", "author_id": 201476, "author_profile": "https://Stackoverflow.com/users/201476", "pm_score": 0, "selected": false, "text": " -- eg (empid , data1,data2,data3 )\n select emplid , max(tmp.a)\n from\n (select emplid,date1 from table\n union \n select emplid,date2 from table \n union \n select emplid,date3 from table\n ) tmp , table\n where tmp.emplid = table.emplid\n" }, { "answer_id": 1678772, "author": "srinivas", "author_id": 203223, "author_profile": "https://Stackoverflow.com/users/203223", "pm_score": 0, "selected": false, "text": "select sum(id) from (\n select (select max(c)\n from (select column1 as c\n union all\n select column2) as cs) id\n from test\n)\n" }, { "answer_id": 15667805, "author": "Dominic Goulet", "author_id": 452792, "author_profile": "https://Stackoverflow.com/users/452792", "pm_score": 0, "selected": false, "text": ";With Greatest_CTE As\n(\n Select ( Select Max(ValueField) From ( Values (column1), (column2) ) ValueTable(ValueField) ) Greatest\n From Test\n)\nSelect Sum(Greatest)\n From Greatest_CTE\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18482/" ]
243,293
<p>A while back I asked about instantiating a HttpContext object. Now that I have learnt what I didn't know, what confuses me is that you cannot say HttpContext ctx = new HttpContext(); because the object does not have a constructor.</p> <p>But doesn't every class need a constructor? In C#, if you don't provide one, the compiler automatically provides a default cstr for you.</p> <p>Also, if I have a string (example: "Hello There!") and I say Convert.ToBoolean("Hello"), or any string, how does this work? What happens behind the scenes? I guess a book like CLR Via C# would be handy in this case.</p> <p>What am I missing?</p>
[ { "answer_id": 243317, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "Class A{\npublic static readonly A Instance = new A();\n\nprivate A()\n{\n}\n\n}\n" }, { "answer_id": 243321, "author": "Elie", "author_id": 23249, "author_profile": "https://Stackoverflow.com/users/23249", "pm_score": 2, "selected": false, "text": "MyClass c = new MyClass();\n MyClass c = MyClass.getInstance();\n" }, { "answer_id": 243433, "author": "JohnIdol", "author_id": 1311500, "author_profile": "https://Stackoverflow.com/users/1311500", "pm_score": 3, "selected": false, "text": "//Initialize this stuff with some crap\nstring appVirtualDir = \"/\"; \nstring appPhysicalDir = @\"C:\\Documents and Settings\\\"; \nstring page = @\"localhost\"; \nstring query = string.Empty; \nTextWriter output = null; \n//Create a SimpleWorkerRequest object passing down the crap\nSimpleWorkerRequest workerRequest = new SimpleWorkerRequest(appVirtualDir, appPhysicalDir, page, query, output);\n//Create your fake HttpContext instance \nHttpContext.Current = new HttpContext(workerRequest);\n" }, { "answer_id": 243466, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "MyType foo = new MyType(\"abc\"); abstract static bool.Parse(\"Hello\")" }, { "answer_id": 45463935, "author": "Namrata Ajmeri", "author_id": 7337493, "author_profile": "https://Stackoverflow.com/users/7337493", "pm_score": -1, "selected": false, "text": "public class Sample\n{\n int x;\n public Sample (int x)\n {\n x = 2;\n }\n}\npublic class Program\n {\n static void Main(string[] args)\n {\n Sample s = new Sample();//error is shown\n }\n }\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30004/" ]
243,298
<p>I'm launching a Weblogic application inside Eclipse via the BEA Weblogic Server v9.2 runtime environment. If this were running straight from the command-line, I'd do a ctrl-BREAK to force a thread dump. Is there a way to do it in Eclipse?</p>
[ { "answer_id": 243698, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 6, "selected": true, "text": "jstack 7088" }, { "answer_id": 9745282, "author": "Alper Akture", "author_id": 1138137, "author_profile": "https://Stackoverflow.com/users/1138137", "pm_score": 0, "selected": false, "text": "ps -ef | grep java kill -3 PID" }, { "answer_id": 25031971, "author": "Peter Butkovic", "author_id": 1581069, "author_profile": "https://Stackoverflow.com/users/1581069", "pm_score": 2, "selected": false, "text": "Threads Thread Dump" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18995/" ]
243,322
<p>State should include at least the following:</p> <ul> <li>All settings set via SetStreamResource()</li> <li>Indices</li> </ul> <p>I have a class whose Draw() function will call SetStreamResource, set Indices and eventually call DrawIndexedPrimitive(). I would like to restore the device state before Draw() returns.</p> <p>I am looking for something along the lines of GDI's SaveDC()/RestoreDC().</p>
[ { "answer_id": 253742, "author": "Agnel Kurian", "author_id": 45603, "author_profile": "https://Stackoverflow.com/users/45603", "pm_score": 1, "selected": false, "text": "Microsoft::DirectX::Direct3D::Device::BeginStateBlock\nMicrosoft::DirectX::Direct3D::Device::EndStateBlock\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45603/" ]
243,344
<p>In my Page_Load event of codebehind file, I am loading data in to a datatable.In my .aspx page I am having some inline coding,I want to display some data from this datatable.But when i am running the program,It is showing an error like "Error 64 Use of unassigned local variable 'dtblChild' " dtblChild is my DataTable Object</p> <p>Is Page_Load in codebehind executes after loading the form elements ?</p>
[ { "answer_id": 243382, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<% %>" }, { "answer_id": 243416, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " }\n" }, { "answer_id": 243448, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<asp:Repeater ID=\"MyRepeater\" runat=\"server\" DataSource=\"dtblChild\">\n <ItemTemplate>\n <tr><td>Thisss</td></tr>\n </ItemTemplate>\n</asp:Repeater>\n" }, { "answer_id": 243470, "author": "Tom", "author_id": 7376, "author_profile": "https://Stackoverflow.com/users/7376", "pm_score": 0, "selected": false, "text": "<table>\n<asp:Repeater ID=\"rptSearchResults\" runat=\"server\">\n <ItemTemplate>\n <tr>\n <td><%#DataBinder.Eval(Container.DataItem, \"ColumnName\") %></td>\n </tr>\n </ItemTemplate>\n</asp:Repeater>\n</table>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
243,347
<p>I launch my program in C#, which then calls some unmanaged C++. </p> <p>When I break on a line in the unmanaged C++, the 'New Data Breakpoint' menu item is grayed out.</p> <p>Is there anyway around this?</p>
[ { "answer_id": 34708528, "author": "Mojtaba Rezaeian", "author_id": 2721611, "author_profile": "https://Stackoverflow.com/users/2721611", "pm_score": 2, "selected": false, "text": "If (Condition)\n System.Diagnostics.Debugger.Break()\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14841/" ]
243,351
<p>Is it ever OK to use <code>Environment.TickCount</code>to calculate time spans?</p> <pre><code>int start = Environment.TickCount; // Do stuff int duration = Environment.TickCount - start; Console.WriteLine("That took " + duration " ms"); </code></pre> <p>Because <code>TickCount</code> is signed and will rollover after 25 days (it takes 50 days to hit all 32 bits, but you have to scrap the signed bit if you want to make any sense of the math), it seems like it's too risky to be useful. </p> <p>I'm using <code>DateTime.Now</code> instead. Is this the best way to do this?</p> <pre><code>DateTime start = DateTime.Now; // Do stuff TimeSpan duration = DateTime.Now - start; Console.WriteLine("That took " + duration.TotalMilliseconds + " ms"); </code></pre>
[ { "answer_id": 243357, "author": "Grzenio", "author_id": 5363, "author_profile": "https://Stackoverflow.com/users/5363", "pm_score": 7, "selected": true, "text": " Stopwatch stopWatch = Stopwatch.StartNew();\n Thread.Sleep(10000);\n stopWatch.Stop();\n // Get the elapsed time as a TimeSpan value.\n TimeSpan ts = stopWatch.Elapsed;\n" }, { "answer_id": 243358, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": false, "text": "System.Diagnostics.StopWatch" }, { "answer_id": 243359, "author": "Martin Kool", "author_id": 216896, "author_profile": "https://Stackoverflow.com/users/216896", "pm_score": 3, "selected": false, "text": "System.Diagnostics.Stopwatch\n EllapsedMilliseconds\n" }, { "answer_id": 652633, "author": "vanmelle", "author_id": 76365, "author_profile": "https://Stackoverflow.com/users/76365", "pm_score": 0, "selected": false, "text": "Stopwatch stopWatch = Stopwatch.StartNew();\n...dostuff...\nDebug.WriteLine(String.Format(\"It took {0} milliseconds\",\n stopWatch.EllapsedMilliseconds)));\n" }, { "answer_id": 1078089, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": " int before_rollover = Int32.MaxValue - 5;\n int after_rollover = Int32.MinValue + 7;\n int duration = after_rollover - before_rollover;\n Console.WriteLine(\"before_rollover: \" + before_rollover.ToString());\n Console.WriteLine(\"after_rollover: \" + after_rollover.ToString());\n Console.WriteLine(\"duration: \" + duration.ToString());\n before_rollover: 2147483642\n after_rollover: -2147483641\n duration: 13\n" }, { "answer_id": 6308701, "author": "Mark", "author_id": 90328, "author_profile": "https://Stackoverflow.com/users/90328", "pm_score": 3, "selected": false, "text": "Environment.TickCount Stopwatch Stopwatch.GetTimestamp() Stopwatch.Frequency GetTimestamp() long Environment.TickCount" }, { "answer_id": 8865560, "author": "mistika", "author_id": 725903, "author_profile": "https://Stackoverflow.com/users/725903", "pm_score": 7, "selected": false, "text": "static void Main(string[] args)\n{\n int xcnt = 0;\n long xdelta, xstart;\n xstart = DateTime.UtcNow.Ticks;\n do {\n xdelta = DateTime.UtcNow.Ticks - xstart;\n xcnt++;\n } while (xdelta == 0);\n\n Console.WriteLine(\"DateTime:\\t{0} ms, in {1} cycles\", xdelta / (10000.0), xcnt);\n\n int ycnt = 0, ystart;\n long ydelta;\n ystart = Environment.TickCount;\n do {\n ydelta = Environment.TickCount - ystart;\n ycnt++;\n } while (ydelta == 0);\n\n Console.WriteLine(\"Environment:\\t{0} ms, in {1} cycles \", ydelta, ycnt);\n\n\n Stopwatch sw = new Stopwatch();\n int zcnt = 0;\n long zstart, zdelta;\n\n sw.Start();\n zstart = sw.ElapsedTicks; // This minimizes the difference (opposed to just using 0)\n do {\n zdelta = sw.ElapsedTicks - zstart;\n zcnt++;\n } while (zdelta == 0);\n sw.Stop();\n\n Console.WriteLine(\"StopWatch:\\t{0} ms, in {1} cycles\", (zdelta * 1000.0) / Stopwatch.Frequency, zcnt);\n Console.ReadKey();\n}\n" }, { "answer_id": 43338538, "author": "cskwg", "author_id": 4386189, "author_profile": "https://Stackoverflow.com/users/4386189", "pm_score": 4, "selected": false, "text": "Environment.TickCount 71\nDateTime.UtcNow.Ticks 213\nsw.ElapsedMilliseconds 1273\n static void Main( string[] args ) {\n const int max = 10000000;\n //\n //\n for ( int j = 0; j < 3; j++ ) {\n var sw = new Stopwatch();\n sw.Start();\n for ( int i = 0; i < max; i++ ) {\n var a = Environment.TickCount;\n }\n sw.Stop();\n Console.WriteLine( $\"Environment.TickCount {sw.ElapsedMilliseconds}\" );\n //\n //\n sw = new Stopwatch();\n sw.Start();\n for ( int i = 0; i < max; i++ ) {\n var a = DateTime.UtcNow.Ticks;\n }\n sw.Stop();\n Console.WriteLine( $\"DateTime.UtcNow.Ticks {sw.ElapsedMilliseconds}\" );\n //\n //\n sw = new Stopwatch();\n sw.Start();\n for ( int i = 0; i < max; i++ ) {\n var a = sw.ElapsedMilliseconds;\n }\n sw.Stop();\n Console.WriteLine( $\"sw.ElapsedMilliseconds {sw.ElapsedMilliseconds}\" );\n }\n Console.WriteLine( \"Done\" );\n Console.ReadKey();\n}\n" }, { "answer_id": 43770774, "author": "Philm", "author_id": 1469896, "author_profile": "https://Stackoverflow.com/users/1469896", "pm_score": 4, "selected": false, "text": "using System.Diagnostics;\nusing System.Runtime.InteropServices;\nusing System.Threading;\nusing static System.Environment;\n [DllImport(\"kernel32.dll\") ]\n public static extern UInt64 GetTickCount64(); // Retrieves a 64bit value containing ticks since system start\n\n static void Main(string[] args)\n {\n const int max = 10_000_000;\n const int n = 3;\n Stopwatch sw;\n\n // Following Process&Thread lines according to tips by Thomas Maierhofer: https://codeproject.com/KB/testing/stopwatch-measure-precise.aspx\n // But this somewhat contradicts to assertions by MS in: https://msdn.microsoft.com/en-us/library/windows/desktop/dn553408%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396#Does_QPC_reliably_work_on_multi-processor_systems__multi-core_system__and_________systems_with_hyper-threading\n Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(1); // Use only the first core\n Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;\n Thread.CurrentThread.Priority = ThreadPriority.Highest;\n Thread.Sleep(2); // warmup\n\n Console.WriteLine($\"Repeating measurement {n} times in loop of {max:N0}:{NewLine}\");\n for (int j = 0; j < n; j++)\n {\n sw = new Stopwatch();\n sw.Start();\n for (int i = 0; i < max; i++)\n {\n var tickCount = GetTickCount64();\n }\n sw.Stop();\n Console.WriteLine($\"Measured: GetTickCount64() [ms]: {sw.ElapsedMilliseconds}\");\n //\n //\n sw = new Stopwatch();\n sw.Start();\n for (int i = 0; i < max; i++)\n {\n var tickCount = Environment.TickCount; // only int capacity, enough for a bit more than 24 days\n }\n sw.Stop();\n Console.WriteLine($\"Measured: Environment.TickCount [ms]: {sw.ElapsedMilliseconds}\");\n //\n //\n sw = new Stopwatch();\n sw.Start();\n for (int i = 0; i < max; i++)\n {\n var a = DateTime.UtcNow.Ticks;\n }\n sw.Stop();\n Console.WriteLine($\"Measured: DateTime.UtcNow.Ticks [ms]: {sw.ElapsedMilliseconds}\");\n //\n //\n sw = new Stopwatch();\n sw.Start();\n for (int i = 0; i < max; i++)\n {\n var a = sw.ElapsedMilliseconds;\n }\n sw.Stop();\n Console.WriteLine($\"Measured: Stopwatch: .ElapsedMilliseconds [ms]: {sw.ElapsedMilliseconds}\");\n //\n //\n sw = new Stopwatch();\n sw.Start();\n for (int i = 0; i < max; i++)\n {\n var a = Stopwatch.GetTimestamp();\n }\n sw.Stop();\n Console.WriteLine($\"Measured: static Stopwatch.GetTimestamp [ms]: {sw.ElapsedMilliseconds}\");\n //\n //\n DateTime dt=DateTime.MinValue; // just init\n sw = new Stopwatch();\n sw.Start();\n for (int i = 0; i < max; i++)\n {\n var a = new DateTime(sw.Elapsed.Ticks); // using variable dt here seems to make nearly no difference\n }\n sw.Stop();\n //Console.WriteLine($\"Measured: Stopwatch+conversion to DateTime [s] with millisecs: {dt:s.fff}\");\n Console.WriteLine($\"Measured: Stopwatch+conversion to DateTime [ms]: {sw.ElapsedMilliseconds}\");\n\n Console.WriteLine();\n }\n //\n //\n sw = new Stopwatch();\n var tickCounterStart = Environment.TickCount;\n sw.Start();\n for (int i = 0; i < max/10; i++)\n {\n var a = DateTime.Now.Ticks;\n }\n sw.Stop();\n var tickCounter = Environment.TickCount - tickCounterStart;\n Console.WriteLine($\"Compare that with DateTime.Now.Ticks [ms]: {sw.ElapsedMilliseconds*10}\");\n\n Console.WriteLine($\"{NewLine}General Stopwatch information:\");\n if (Stopwatch.IsHighResolution)\n Console.WriteLine(\"- Using high-resolution performance counter for Stopwatch class.\");\n else\n Console.WriteLine(\"- Using high-resolution performance counter for Stopwatch class.\");\n\n double freq = (double)Stopwatch.Frequency;\n double ticksPerMicroSec = freq / (1000d*1000d) ; // microsecond resolution: 1 million ticks per sec\n Console.WriteLine($\"- Stopwatch accuracy- ticks per microsecond (1000 ms): {ticksPerMicroSec:N1}\");\n Console.WriteLine(\" (Max. tick resolution normally is 100 nanoseconds, this is 10 ticks/microsecond.)\");\n\n DateTime maxTimeForTickCountInteger= new DateTime(Int32.MaxValue*10_000L); // tickCount means millisec -> there are 10.000 milliseconds in 100 nanoseconds, which is the tick resolution in .NET, e.g. used for TimeSpan\n Console.WriteLine($\"- Approximated capacity (maxtime) of TickCount [dd:hh:mm:ss] {maxTimeForTickCountInteger:dd:HH:mm:ss}\");\n // this conversion from seems not really accurate, it will be between 24-25 days.\n Console.WriteLine($\"{NewLine}Done.\");\n\n while (Console.KeyAvailable)\n Console.ReadKey(false);\n Console.ReadKey();\n }\n" }, { "answer_id": 62860441, "author": "cskwg", "author_id": 4386189, "author_profile": "https://Stackoverflow.com/users/4386189", "pm_score": 0, "selected": false, "text": "using System;\nnamespace ConsoleApp1 {\n class Program {\n //\n static byte Lower = byte.MaxValue / 3;\n static byte Upper = 2 * byte.MaxValue / 3;\n //\n ///<summary>Compute delta between two TickCount values reliably, because TickCount might wrap after 49.8 days.</summary>\n static short Delta( byte next, byte ticks ) {\n if ( next < Lower ) {\n if ( ticks > Upper ) {\n return (short) ( ticks - ( byte.MaxValue + 1 + next ) );\n }\n }\n if ( next > Upper ) {\n if ( ticks < Lower ) {\n return (short) ( ( ticks + byte.MaxValue + 1 ) - next );\n }\n }\n return (short) ( ticks - next );\n }\n //\n static void Main( string[] args ) {\n // Init\n Random rnd = new Random();\n int max = 0;\n byte last = 0;\n byte wait = 3;\n byte next = (byte) ( last + wait );\n byte step = 0;\n // Loop tick\n for ( byte tick = 0; true; ) {\n //\n short delta = Delta( next, tick );\n if ( delta >= 0 ) {\n Console.WriteLine( \"RUN: last: {0} next: {1} tick: {2} delta: {3}\", last, next, tick, delta );\n last = tick;\n next = (byte) ( last + wait );\n }\n // Will overflow to 0 automatically\n step = (byte) rnd.Next( 0, 11 );\n tick += step;\n max++; if ( max > 99999 ) break;\n }\n }\n }\n}\n" }, { "answer_id": 62870428, "author": "cskwg", "author_id": 4386189, "author_profile": "https://Stackoverflow.com/users/4386189", "pm_score": 1, "selected": false, "text": "Environment.TickCount: 2265\nEnvironment.TickCount64: 2531\nDateTime.UtcNow.Ticks: 69016\n static void Main( string[] args ) {\n long start, end, length = 1000 * 1000 * 1000;\n start = Environment.TickCount64;\n for ( int i = 0; i < length; i++ ) {\n var a = Environment.TickCount;\n }\n end = Environment.TickCount64;\n Console.WriteLine( \"Environment.TickCount: {0}\", end - start );\n start = Environment.TickCount64;\n for ( int i = 0; i < length; i++ ) {\n var a = Environment.TickCount64;\n }\n end = Environment.TickCount64;\n Console.WriteLine( \"Environment.TickCount64: {0}\", end - start );\n start = Environment.TickCount64;\n for ( int i = 0; i < length; i++ ) {\n var a = DateTime.UtcNow.Ticks;\n }\n end = Environment.TickCount64;\n Console.WriteLine( \"DateTime.UtcNow.Ticks: {0}\", end - start );\n}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27414/" ]
243,355
<p>Is there a way to quickly list which sites are on which IP address in IIS 7? </p> <p>If I remember correctly you could sort a view of domains by IP in IIS 6 which was a big help to me in seeing which IPs I had available.</p>
[ { "answer_id": 243370, "author": "Kieron", "author_id": 5791, "author_profile": "https://Stackoverflow.com/users/5791", "pm_score": 2, "selected": false, "text": "MachineName = \"localhost\"\nIIsObjectPath = \"IIS://\" & MachineName & \"/w3svc\"\n\nWScript.Echo \"Checking : \" & IISObjectPath\n\nSet IIsObject = GetObject(IIsObjectPath)\nfor each obj in IISObject\n if (Obj.Class = \"IIsWebServer\") then\n BindingPath = IIsObjectPath & \"/\" & Obj.Name\n\n Set IIsObjectIP = GetObject(BindingPath)\n wScript.Echo BindingPath & \" - \" & IISObjectIP.ServerComment\n\n ValueList = IISObjectIP.Get(\"ServerBindings\")\n ValueString = \"\"\n For ValueIndex = 0 To UBound(ValueList)\n value = ValueList(ValueIndex)\n Values = split(value, \":\")\n IP = values(0)\n if (IP = \"\") then\n IP = \"(All Unassigned)\"\n end if \n TCP = values(1)\n if (TCP = \"\") then\n TCP = \"80\"\n end if \n HostHeader = values(2)\n\n if (HostHeader <> \"\") then\n wScript.Echo \" IP = \" & IP & \" TCP/IP Port = \" & TCP & \", HostHeader = \" & HostHeader\n else\n wScript.Echo \" IP = \" & IP & \" TCP/IP Port = \" & TCP \n end if\n Next \n wScript.Echo \"\"\n set IISObjectIP = Nothing\n end if\nnext\nset IISObject = Nothing\n" }, { "answer_id": 245593, "author": "John Lemp", "author_id": 12915, "author_profile": "https://Stackoverflow.com/users/12915", "pm_score": 3, "selected": false, "text": " %systemroot%\\system32\\inetsrv\\APPCMD list sites\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34548/" ]
243,363
<p>Can someone explain the structure of a Pid in Erlang?</p> <p>Pids looks like this: <code>&lt;A.B.C&gt;</code>, e.g. <code>&lt;0.30.0&gt;</code> , but I would like to know what is the meaning of these three &quot;bits&quot;: <code>A</code>, <code>B</code> and <code>C</code>.</p> <p><code>A</code> seems to be always <code>0</code> on a local node, but this value changes when the Pid's owner is located on another node.</p> <p>Is it possible to directly send a message on a remote node using only the Pid? Something like that: <code>&lt;4568.30.0&gt; ! Message</code>, without having to explicitly specify the name of the registered process and the node name (<code> {proc_name, Node} ! Message</code>)?</p>
[ { "answer_id": 243668, "author": "Jon Gretar", "author_id": 5601, "author_profile": "https://Stackoverflow.com/users/5601", "pm_score": 4, "selected": false, "text": "<nodeid,serial,creation> list_to_pid/1 PidString = \"<0.39.0>\",\nlist_to_pid(PidString) ! message.\n list_to_pid( make_pid_from_term({proc_name, Node}) ) ! message\n" }, { "answer_id": 262179, "author": "archaelus", "author_id": 9040, "author_profile": "https://Stackoverflow.com/users/9040", "pm_score": 7, "selected": true, "text": "<0.10.0> inet_db <2265.10.0> % get the PID of the user server on OtherNode\nRemoteUser = rpc:call(OtherNode, erlang,whereis,[user]), \n\ntrue = is_pid(RemoteUser),\n\n% send message to remote PID\nRemoteUser ! ignore_this, \n\n% print \"Hello from <nodename>\\n\" on the remote node's console.\nio:format(RemoteUser, \"Hello from ~p~n\", [node()]). \n" }, { "answer_id": 28542245, "author": "nacmartin", "author_id": 225540, "author_profile": "https://Stackoverflow.com/users/225540", "pm_score": 0, "selected": false, "text": "1> node().\nnonode@nohost\n2> term_to_binary(node()).\n<<131,100,0,13,110,111,110,111,100,101,64,110,111,104,111,\n 115,116>>\n3> self(). \n<0.32.0>\n4> term_to_binary(self()).\n<<131,103,100,0,13,110,111,110,111,100,101,64,110,111,104,\n 111,115,116,0,0,0,32,0,0,0,0,0>>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15539/" ]
243,365
<p>I was just reading this <a href="https://stackoverflow.com/questions/243082/c-casting-programmatically-can-it-be-done">thread</a> and it occurred to me that there is one seemingly-valid use of that pattern the OP is asking about. I know I've used it before to implement dynamic creation of objects. As far as I know, there is no better solution in C++, but I was wondering if any gurus out there know of a better way. Generally, I run into this situation when I need to create one of several subclasses of an object based one something unknown at compile time (such as based on a config file). I use the object polymorphically once it is created.</p> <p>There's another related situation when you're using a message-passing scheme (usually over TCP/IP) where each message is an object. I like to implement that pattern as letting each message serialize itself into some serialization stream interface, which works well and is fairly clean on the sending end, but on the receiver, I always find myself examining a header on the message to determine the type, then constructing an appropriate message object using the pattern from the linked article, then having it deserialize itself from the stream. Sometimes I implement it so that the construction and deserialization happen at the same time as part of the constructor, which seems more RAII, but that's small consolation for the mess of if/else statements figuring out the type.</p> <p>Any better solutions out there? If you're going to suggest a 3rd party library, it should be free (and ideally open source) and I'd appreciate it if you could explain how the library accomplishes this feat.</p>
[ { "answer_id": 243405, "author": "SpoonMeiser", "author_id": 1577190, "author_profile": "https://Stackoverflow.com/users/1577190", "pm_score": 2, "selected": false, "text": "Base* Base::get_object(std::string type)\n{\n if (type == \"derived1\") return new Derived1;\n if (type == \"derived2\") return new Derived2;\n}\n" }, { "answer_id": 243484, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 0, "selected": false, "text": "class Sub1 : public Super { ... };\nclass Sub2 : public Super { ... };\n\nSuper *factory(int param) {\n if (param == 1) return new Sub1();\n if (param == 2) return new Sub2();\n return new Super();\n}\n\nint main(int argc, char **argv) {\n Super *parser = factory(argc);\n parser->parse(argv); // parse declared virtual in Super\n delete parser;\n return 0;\n}\n Super *deserialize(char *data, vector<Deserializer *> &factories>) {\n for (int i = 0; i < factories.size(); ++i) { // or a for_each loop\n Super *result = factories[i]->deserialize(data);\n if (result != NULL) return result;\n }\n throw stop_wasting_my_time_with_garbage_data();\n}\n Super *deserialize(char *data) {\n uint32_t type = *((uint32_t *)data); // or use a stream\n switch(type) {\n case 0: return new Super(data+4);\n case 1: return new Sub1(data+4);\n case 2: return new Sub2(data+4);\n default: throw stop_wasting_my_time_with_garbage_data();\n }\n}\n" }, { "answer_id": 243548, "author": "KeithB", "author_id": 2298, "author_profile": "https://Stackoverflow.com/users/2298", "pm_score": 3, "selected": true, "text": "class Factory\n{\n public:\n typedef Object*(*Func)(istream& is);\n static void register(int key, Func f) {m[key] = f;}\n Object* create(key, istream& is) {return m[key](is);}\n private:\n std::map<key, func> m;\n}\n while(cin)\n{\n int key;\n is >> key;\n Object* obj = Factory::Create(key, is);\n // do something with objects\n}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10861/" ]
243,368
<p>How do I programmatically reset the Excel <code>Find and Replace</code> dialog box parameters to defaults ("Find what", "Replace with", "Within", "Search", "Look in", "Match case", "Match entire cell contents")?</p> <p>I am using <code>Application.FindFormat.Clear</code> and <code>Application.ReplaceFormat.Clear</code> to reset find and replace cell formats.</p> <p>Interestingly, after using <code>expression.Replace(FindWhat, ReplaceWhat, After, MatchCase, WholeWords)</code>, the <code>FindWhat</code> string shows in the <code>Find and Replace</code> dialog box but not the <code>ReplaceWhat</code> parameter.</p>
[ { "answer_id": 2061040, "author": "DaveParillo", "author_id": 167483, "author_profile": "https://Stackoverflow.com/users/167483", "pm_score": 3, "selected": false, "text": "Sub ResetFind()\n Dim r As Range\n\n On Error Resume Next 'just in case there is no active cell\n Set r = ActiveCell\n On Error Goto 0\n\n Cells.Find what:=\"\", _\n After:=ActiveCell, _\n LookIn:=xlFormulas, _\n LookAt:=xlPart, _\n SearchOrder:=xlByRows, _\n SearchDirection:=xlNext, _\n MatchCase:=False, _\n SearchFormat:=False\n Cells.Replace what:=\"\", Replacement:=\"\", ReplaceFormat:=False\n\n If Not r Is Nothing Then r.Select\n Set r = Nothing\nEnd Sub\n" }, { "answer_id": 26062232, "author": "Mike", "author_id": 4083745, "author_profile": "https://Stackoverflow.com/users/4083745", "pm_score": 0, "selected": false, "text": "Sub ResetFindReplace()\n 'Resets the find/replace dialog box options\n Dim r As Range\n\n On Error Resume Next\n\n Set r = Cells.Find(What:=\"\", _\n LookIn:=xlFormulas, _\n SearchOrder:=xlRows, _\n LookAt:=xlPart, _\n MatchCase:=False)\n\n On Error GoTo 0\n\n 'Reset the defaults\n\n On Error Resume Next\n\n Set r = Cells.Find(What:=\"\", _\n LookIn:=xlFormulas, _\n SearchOrder:=xlRows, _\n LookAt:=xlPart, _\n MatchCase:=False)\n\n On Error GoTo 0\nEnd Sub\n" }, { "answer_id": 27459084, "author": "dave", "author_id": 4356987, "author_profile": "https://Stackoverflow.com/users/4356987", "pm_score": 0, "selected": false, "text": "Sub RR0() 'Replace Reset & Open dialog (specs: clear settings, search columns, match case)\n\n'Dim r As RANGE 'not seem to need\n'Set r = ActiveCell 'not seem to need\nOn Error Resume Next 'just in case there is no active cell\nOn Error GoTo 0\n\nApplication.FindFormat.Clear 'yes\nApplication.ReplaceFormat.Clear 'yes\n\nCells.find what:=\"\", After:=ActiveCell, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext\nCells.Replace what:=\"\", Replacement:=\"\", ReplaceFormat:=False, MatchCase:=True 'format not seem to do anything\n'Cells.Replace what:=\"\", Replacement:=\"\", ReplaceFormat:=False 'orig, wo matchcase not work unless put here - in replace\n\n'If Not r Is Nothing Then r.Select 'not seem to need\n'Set r = Nothing\n\n'settings choices:\n'match entire cell: LookAt:=xlWhole, or: LookAt:=xlPart,\n'column or row: SearchOrder:=xlByColumns, or: SearchOrder:=xlByRows,\n\nApplication.CommandBars(\"Edit\").Controls(\"Replace...\").Execute 'YES WORKS\n'Application.CommandBars(\"Edit\").Controls(\"Find...\").Execute 'YES same, easier to manipulate\n'Application.CommandBars.FindControl(ID:=1849).Execute 'YES full find dialog\n\n'PROBLEM: how to expand options?\n'SendKeys (\"%{T}\") 'alt-T works the first time, want options to stay open\n\nApplication.EnableEvents = True 'EVENTS\n\nEnd Sub\n" }, { "answer_id": 69561199, "author": "UncleBob", "author_id": 3107264, "author_profile": "https://Stackoverflow.com/users/3107264", "pm_score": 0, "selected": false, "text": "Sub ResetFindAndReplace()\n Dim oldActive As Range, oldSelection As Range\n On Error Resume Next ' just in case there is no active cell\n Set oldActive = ActiveCell\n Set oldSelection = Selection\n On Error GoTo 0 \n Cells.Find what:=\"\", _\n After:=ActiveCell, _\n LookIn:=xlFormulas, _\n LookAt:=xlPart, _\n SearchOrder:=xlByRows, _\n SearchDirection:=xlNext, _\n MatchCase:=False, _\n SearchFormat:=False\n Cells.Replace what:=\"\", Replacement:=\"\", ReplaceFormat:=False\n Application.FindFormat.Clear\n ' return selection cell\n If Not oldSelection Is Nothing Then oldSelection.Select \n ' return active cell\n If Not oldActive Is Nothing Then oldActive.Activate\n Set oldActive = Nothing\nEnd Sub\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
243,375
<p>I have written a CGI script that creates an image dynamically using GET data. To include this image in my webpage, I am using the following code:</p> <pre><code>&lt;img src="image.py?text=xxxxxxxxxxxxxx"&gt; </code></pre> <p>The problem is that I expect in the future the "text" field will get very long and the URL will become too large. From Googling around there doesn't seem to be a fixed limit on URL length (ie. depends on the browser, server, proxy, etc.) Is there a better way to do this? </p> <p>If it matters, I am working with Django and Python and I cannot use any client-side scripting (ie. JavaScript).</p> <p>Cheers, Ben</p>
[ { "answer_id": 243521, "author": "fuentesjr", "author_id": 10708, "author_profile": "https://Stackoverflow.com/users/10708", "pm_score": 1, "selected": false, "text": "<img src=\"render_img.py?row_id=0122\">" }, { "answer_id": 243860, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<img src=\"{% create_image \"This is the text that will be displayed\" %}\">\n" }, { "answer_id": 1051870, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "newimg.src = 'blah';\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27478/" ]
243,383
<p>I was reading about parsers and parser generators and found this statement in wikipedia's LR parsing -page:</p> <blockquote> <p>Many programming languages can be parsed using some variation of an LR parser. One notable exception is C++.</p> </blockquote> <p>Why is it so? What particular property of C++ causes it to be impossible to parse with LR parsers?</p> <p>Using google, I only found that C can be perfectly parsed with LR(1) but C++ requires LR(∞). </p>
[ { "answer_id": 243447, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 8, "selected": true, "text": "int(x), y, *const z;\n int x;\nint y;\nint *const z;\n int(x), y, new int;\n (int(x)), (y), (new int));\n" }, { "answer_id": 1004737, "author": "Ira Baxter", "author_id": 120163, "author_profile": "https://Stackoverflow.com/users/120163", "pm_score": 8, "selected": false, "text": "x * y ;\n" }, { "answer_id": 14852664, "author": "reuns", "author_id": 1952009, "author_profile": "https://Stackoverflow.com/users/1952009", "pm_score": 4, "selected": false, "text": "Type Type; struct Type Type names tokens types func< func < func < Type a(2); Type a(); Type a(int) int (k); int k; typedef int func_type(); typedef int (func_type)(); typedef int (*func_ptr_type)(); int a,b,c[9],*d,(*f)(), (*g)()[9], h(char); int a,b,c[9],*d; int (*f)(); int (*g)()[9]; int h(char); int (MyClass::*MethodPtr)(char*); int (MyClass::*)(char*) MethodPtr; (int (MyClass::*)(char*)) typedef int type, *type_ptr; typedef int type; typedef int *type_ptr; sizeof int sizeof char sizeof long long int #type int : signed_integer(4) unsigned_integer(4) #type sizeof int source.cpp ambiguous_syntax source.cpp" }, { "answer_id": 51898104, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "/* C Typedef Solution. */\n\n/* Terminal Declarations. */\n\n <identifier> => lookup(); /* Symbol table lookup. */\n\n/* Rules. */\n\n Goal -> [Declaration]... <eof> +> goal_\n\n Declaration -> Type... VarList ';' +> decl_\n -> typedef Type... TypeVarList ';' +> typedecl_\n\n VarList -> Var /','... \n TypeVarList -> TypeVar /','...\n\n Var -> [Ptr]... Identifier \n TypeVar -> [Ptr]... TypeIdentifier \n\n Identifier -> <identifier> +> identifier_(1) \n TypeIdentifier -> <identifier> =+> typedefidentifier_(1,{typedef})\n\n// The above line will assign {typedef} to the <identifier>, \n// because {typedef} is the second argument of the action typeidentifier_(). \n// This handles the context-sensitive feature of the C++ language.\n\n Ptr -> '*' +> ptr_\n\n Type -> char +> type_(1)\n -> int +> type_(1)\n -> short +> type_(1)\n -> unsigned +> type_(1)\n -> {typedef} +> type_(1)\n\n/* End Of Grammar. */\n typedef int x;\n x * y;\n\n typedef unsigned int uint, *uintptr;\n uint a, b, c;\n uintptr p, q, r;\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21711/" ]
243,385
<p>I'm pretty new to the Spring Framework, I've been playing around with it and putting a few samples apps together for the purposes of evaluating Spring MVC for use in an upcoming company project. So far I really like what I see in Spring MVC, seems very easy to use and encourages you to write classes that are very unit test-friendly.</p> <p>Just as an exercise, I'm writing a main method for one of my sample/test projects. One thing I'm unclear about is the exact differences between <code>BeanFactory</code> and <code>ApplicationContext</code> - which is appropriate to use in which conditions?</p> <p>I understand that <code>ApplicationContext</code> extends <code>BeanFactory</code>, but if I'm just writing a simple main method, do I need the extra functionality that <code>ApplicationContext</code> provides? And just exactly what kind of extra functionality does <code>ApplicationContext</code> provide?</p> <p>In addition to answering "which should I use in a main() method", are there any standards or guidelines as far as which implementation I should use in such a scenario? Should my main() method be written to depend on the bean/application configuration to be in XML format - is that a safe assumption, or am I locking the user into something specific?</p> <p>And does this answer change in a web environment - if any of my classes needed to be aware of Spring, are they more likely to need <code>ApplicationContext</code>?</p> <p>Thanks for any help. I know a lot of these questions are probably answered in the reference manual, but I'm having a hard time finding a clear breakdown of these two interfaces and the pros/cons of each without reading thru the manual with a fine-tooth comb.</p>
[ { "answer_id": 2347229, "author": "srinivas reddy", "author_id": 282661, "author_profile": "https://Stackoverflow.com/users/282661", "pm_score": 4, "selected": false, "text": "ApplicationContext BeanFactory BeanFactory ApplicationContext BeanFactory ApplicationContext extends BeanFactory" }, { "answer_id": 2349891, "author": "Lyle", "author_id": 80144, "author_profile": "https://Stackoverflow.com/users/80144", "pm_score": 6, "selected": false, "text": "BeanFactory ApplicationContext ApplicationContext BeanFactory BeanFactory classpath BeanFactory ApplicationContext ClassPathXmlApplicationContext public class LazyLoadingXmlApplicationContext extends ClassPathXmlApplicationContext {\n\n public LazyLoadingXmlApplicationContext(String[] configLocations) {\n super(configLocations);\n }\n\n /**\n * Upon loading bean definitions, force beans to be lazy-initialized.\n * @see org.springframework.context.support.AbstractXmlApplicationContext#loadBeanDefinitions(org.springframework.beans.factory.xml.XmlBeanDefinitionReader)\n */\n\n @Override\n protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws IOException {\n super.loadBeanDefinitions(reader);\n for (String name: reader.getBeanFactory().getBeanDefinitionNames()) {\n AbstractBeanDefinition beanDefinition = (AbstractBeanDefinition) reader.getBeanFactory().getBeanDefinition(name);\n beanDefinition.setLazyInit(true);\n }\n }\n\n}\n" }, { "answer_id": 34804942, "author": "Divyesh Kanzariya", "author_id": 5246706, "author_profile": "https://Stackoverflow.com/users/5246706", "pm_score": 3, "selected": false, "text": "ClassPathResource resource = new ClassPathResource(\"appConfig.xml\");\nXmlBeanFactory factory = new XmlBeanFactory(resource);\n" }, { "answer_id": 34890503, "author": "Premraj", "author_id": 1697099, "author_profile": "https://Stackoverflow.com/users/1697099", "pm_score": 6, "selected": false, "text": "XMLBeanFactory ApplicationContext FileSystemXmlApplicationContext ClassPathXmlApplicationContext XMLWebApplicationContext AnnotationConfigWebApplicationContext AnnotationConfigApplicationContext ApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeansConfiguration.class);\n ApplicationContext ContextLoaderListener ContextLoaderServlet web.xml ContextLoaderPlugin struts-config.xml XmlBeanFactory DefaultListableBeanFactory XmlBeanDefinitionReader" }, { "answer_id": 35641652, "author": "KarthikPon", "author_id": 1874536, "author_profile": "https://Stackoverflow.com/users/1874536", "pm_score": 1, "selected": false, "text": "<bean></bean> <bean></bean> /*\n * Using core Container - Lazy container - Because it creates the bean objects On-Demand\n */\n//creating a resource\nResource r = (Resource) new ClassPathResource(\"com.spring.resources/spring.xml\");\n//creating BeanFactory \nBeanFactory factory=new XmlBeanFactory(r);\n\n//Getting the bean for the POJO class \"HelloWorld.java\"\nHelloWorld worldObj1 = (HelloWorld) factory.getBean(\"test\");\n ApplicationContext context = new ClassPathXmlApplicationContext(\"com/ioc/constructorDI/resources/spring.xml\");\n" }, { "answer_id": 41508415, "author": "rajvineet", "author_id": 3912385, "author_profile": "https://Stackoverflow.com/users/3912385", "pm_score": 2, "selected": false, "text": "ApplicationContext context = new ClassPathXmlApplicationContext(\"spring.xml\");\n ApplicationContext context = new ClassPathXmlApplicationContext{\"spring_dao.xml\",\"spring_service.xml};\n" }, { "answer_id": 46514347, "author": "Raman Gupta", "author_id": 8609030, "author_profile": "https://Stackoverflow.com/users/8609030", "pm_score": 3, "selected": false, "text": "BeanFactory beanfactory = new XMLBeanFactory(new FileSystemResource(\"spring.xml\"));\n Triangle triangle =(Triangle)beanFactory.getBean(\"triangle\");\n ApplicationContext context = new ClassPathXMLApplicationContext(\"spring.xml\")\nTriangle triangle =(Triangle)context.getBean(\"triangle\");\n" }, { "answer_id": 48402405, "author": "Ronan Quillevere", "author_id": 1301197, "author_profile": "https://Stackoverflow.com/users/1301197", "pm_score": 0, "selected": false, "text": "@configuration @scope @Configuration\npublic class MyFactory {\n\n @Bean\n @Scope(\"prototype\")\n public MyClass create() {\n return new MyClass();\n }\n}\n @ComponentScan" }, { "answer_id": 73295978, "author": "Amitabha Roy", "author_id": 1906350, "author_profile": "https://Stackoverflow.com/users/1906350", "pm_score": 1, "selected": false, "text": "BeanFactory ApplicationContext ApplicationContext BeanFactory ApplicationContext BeanFactory ApplicationContext BeanFactory BeanFactory BeanFactory ApplicationContext BeanFactory ApplicationContext ApplicationContext BeanFactory BeanFactory ApplicationContext BeanFactory BeanFactoryPostProcessor BeanPostProcessor ApplicationContext" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4249/" ]
243,388
<p>I <del>understand (I think) the basic idea behind RESTful-ness. Use HTTP methods semantically - GET gets, PUT puts, DELETE deletes, etc... Right?</del> thought I understood the idea behind REST, but I think I'm confusing that with the details of an HTTP implementation. What is the driving idea behind rest, why is this becoming an important thing? Have people actually been using it for a long time, in a corner of the internets that my flashlight never shined upon? <hr/> The Google talk mentions Atom Publishing Protocols having a lot of synergy with RESTful implementations. Any thoughts on that?</p>
[ { "answer_id": 1081615, "author": "pbreitenbach", "author_id": 42048, "author_profile": "https://Stackoverflow.com/users/42048", "pm_score": 7, "selected": true, "text": "POST /user\nfname=John&lname=Doe&age=25\n 201 Created\nLocation: /user/123\n GET /user/123\n 200 OK\n<user><fname>John</fname><lname>Doe</lname><age>25</age></user>\n PUT /user/123\nfname=Johnny\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96/" ]
243,408
<p>This is the error, it's basically a security warning</p> <p><a href="http://img357.imageshack.us/img357/7992/visualstudiowarninggr4.jpg" rel="nofollow noreferrer">Warning message http://img357.imageshack.us/img357/7992/visualstudiowarninggr4.jpg</a></p> <p>(And here's the text grabbed off the dialog box) Security Warning for WindowsApplication4 __________________________I The WindowsApplication4 project file has been customized and could present a security risk by executing custom build steps when opened in Microsoft Visual Studio. If this project came from an untrustwoithy source, it could cause damage to your computer or compromise your private information. More Details Project load options 0 Load project for browsing Opens the project in Microsoft Visual Studio with increased security. This option allows you to browse the contents of the project, but some functionality, such as IntelliSense, is restricted, When a project is loaded for browsing, actions such as building, cleaning, publishing, or opening designers could still remain unsafe. Load project normally Opens the project normally in Microsoft Visual Studio. Use this option if you trust the source and understand the potential risks involved. Microsoft Visual Studio does not restrict any project functionality and will not prompt you again for this project. Ask me for every project in this solution OK L Cancel</p> <p>When click the more details button get this:</p> <p>Microsoft Visual Studio ______ An item referring to the file was found in the project file “C:\Users\mgriffiths\Documents\Visual Studio 2008\ProjectATemp\Win dowsApplication4\WindowsApplicdtion4\W in dowsApplication4.vbproj”. Since this file is located within a system directory, root directory, or network share, it could be harmful to write to this file. OK</p>
[ { "answer_id": 10699178, "author": "Slappy", "author_id": 765955, "author_profile": "https://Stackoverflow.com/users/765955", "pm_score": 2, "selected": false, "text": "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\<VS_VERSION>\\MSBuild\\SafeImports]\n\"<YOUR_NAME>\"=\"<PATH\\TO\\YOUR\\FILE.targets>\"\n\n[HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\VisualStudio\\<VS_VERSION>Exp\\Configuration\\MSBuild\\SafeImports]\n\"<YOUR_NAME>\"=\"<PATH\\TO\\YOUR\\FILE.targets>\"\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
243,409
<p>I need to set the fetch mode on my hibernate mappings to be eager in some cases, and lazy in others. I have my default (set through the hbm file) as lazy="true". How do I override this setting in code? MyClass has a set defined of type MyClass2 for which I want to set the FetchMode to EAGER.</p> <p>Currently, I have something like:</p> <pre><code>Session s = HibernateUtil.getSessionFactory().openSession(); MyClass c = (MyClass)session.get(MyClass.class, myClassID); </code></pre>
[ { "answer_id": 243488, "author": "Mat Mannion", "author_id": 6282, "author_profile": "https://Stackoverflow.com/users/6282", "pm_score": 4, "selected": true, "text": "Criteria crit = session.createCriteria(MyClass.class);\ncrit.add(Restrictions.eq(\"id\", myClassId));\ncrit.setFetchMode(\"myProperty\", FetchMode.EAGER);\nMyClass myThingy = (MyClass)crit.uniqueResult();\n" }, { "answer_id": 243555, "author": "Henning", "author_id": 29549, "author_profile": "https://Stackoverflow.com/users/29549", "pm_score": 1, "selected": false, "text": "initialize(Object) Hibernate MyClass c = (MyClass)session.get(MyClass.class, myClassID);\nHibernate.initialize(c.getMySetOfMyClass2());\n" }, { "answer_id": 243642, "author": "Damo", "author_id": 2955, "author_profile": "https://Stackoverflow.com/users/2955", "pm_score": 2, "selected": false, "text": "JOIN FETCH session.createQuery(\"select p from Parent p join fetch p.children c\")\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23249/" ]
243,417
<p>How do you pass "this" to the constructor for ObjectDataProvider in XAML.</p> <p>Lets say my presenter class is:</p> <pre><code>public class ApplicationPresenter(IView view){} </code></pre> <p>and that my UserControl implements IView.</p> <p>What do I pass to the ConstructorParameters in the code below so that the UserControl can create the ApplicationPresenter using the default constructor? </p> <pre><code>&lt;ObjectDataProvider x:Key="ApplicationPresenterDS" ObjectType="{x:Type Fenix_Presenters:ApplicationPresenter}" ConstructorParameters="{ ?? what goes here ??}" d:IsDataSource="True" /&gt; </code></pre> <p>I only need to do this so that I can use Blend 2. I know that I can do this in the code behind, but if I do I can't instantiate the class from within Blend. I also know that I can create a parameterless constructor for ApplicationPresenter and pass it a dummy class that implements IView, but I would rather do this in markup if at all possible.</p> <p>My code behind at the moment is:</p> <pre><code>public MyUserControl() { InitializeComponent(); DataContext = new ApplicationPresenter(this); } </code></pre>
[ { "answer_id": 243429, "author": "Joachim Kerschbaumer", "author_id": 20227, "author_profile": "https://Stackoverflow.com/users/20227", "pm_score": 0, "selected": false, "text": "x:Name=\"myUserCotrol\"\n ... ConstructorParameters=\"{Binding ElementName=myUserControl}\" ...\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30046/" ]
243,459
<p>How would I expose an <em>Objective-C</em> method within JavaScript when using the <em>iPhone SDK</em> when using the <code>UIWebView</code>?</p> <p>Any help would be appreciated!</p>
[ { "answer_id": 243505, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 6, "selected": true, "text": "-webView:shouldStartLoadWithRequest:navigationType:" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46304/" ]
243,464
<p>I was mapping a relation using something like the following </p> <pre><code>&lt;map name="Foo" cascade="all-delete-orphan" lazy="false"&gt; &lt;key column="FooId"/&gt; &lt;index column="FooType" type="Domain.Enum.FooType, Domain"/&gt; &lt;element column ="FooStatus" type="Domain.Enum.FooStatus, Domain"/&gt; &lt;/map&gt; </code></pre> <p>The class is like this</p> <pre><code>namespace Domain { public class Enum { public enum FooType { Foo1, Foo2, ... Foo50} public enum FooStatus { NotNeeded, NeededFor1, NeededFor2, NeededFor3, NiceToHave} } } </code></pre> <p>Can I do this using Fluent Nhibernate? If not can I map a class mixing Fluent and XML?</p>
[ { "answer_id": 247036, "author": "Nikelman", "author_id": 32388, "author_profile": "https://Stackoverflow.com/users/32388", "pm_score": 0, "selected": false, "text": "namespace Domain \n{\npublic virtual IDictionary<FooType, FooStatus> MyFoo { set; get; }\n}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
243,469
<p>I have a .Net app that will allow the users to attach files to a SQL Server 2005 database. I want to limit the filesize to 10MB, so from what I can tell, I have to declare the datatype varbinary(max), since the max size I can actually specify is 8000 bytes. But the ~2GB filesize varbinary(max) allows seems like overkill. Is there a way for me to limit it at 10MB in the database, or do I just need to check that they're not trying to attach something larger on the frontend.</p>
[ { "answer_id": 243495, "author": "mohammedn", "author_id": 29268, "author_profile": "https://Stackoverflow.com/users/29268", "pm_score": 0, "selected": false, "text": "</configuration>\n </system.web>\n <httpRuntime maxRequestLength=\"60000\"/>\n </system.web>\n</configuration>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30415/" ]
243,489
<p>I am doing an Financial Winforms application and am having some trouble with the controls.</p> <p>My customer needs to insert decimal values all over the place (Prices, Discounts etc) and I'd like to avoid some of the repeating validation.</p> <p>So I immediately tried the MaskedTextBox that would fit my needs (with a Mask like "€ 00000.00"), if it weren't for the focus and the length of the mask.</p> <p>I can't predict how big the numbers are my customer is going to enter into the app. </p> <p>I also can't expect him to start everything with 00 to get to the comma. Everything should be keyboard-friendly.</p> <p>Am I missing something or is there simply no way (beyond writing a custom control) to achieve this with the standard Windows Forms controls?</p>
[ { "answer_id": 243536, "author": "Abel Gaxiola", "author_id": 31191, "author_profile": "https://Stackoverflow.com/users/31191", "pm_score": 4, "selected": true, "text": " protected override void OnKeyPress(KeyPressEventArgs e)\n {\n if (!char.IsNumber(e.KeyChar) & (Keys)e.KeyChar != Keys.Back \n & e.KeyChar != '.')\n {\n e.Handled = true;\n }\n\n base.OnKeyPress(e);\n }\n\n private string currentText;\n\n protected override void OnTextChanged(EventArgs e)\n {\n if (this.Text.Length > 0)\n {\n float result;\n bool isNumeric = float.TryParse(this.Text, out result);\n\n if (isNumeric)\n {\n currentText = this.Text;\n }\n else\n {\n this.Text = currentText;\n this.Select(this.Text.Length, 0);\n }\n }\n base.OnTextChanged(e);\n }\n" }, { "answer_id": 29064309, "author": "madmaniac", "author_id": 2428976, "author_profile": "https://Stackoverflow.com/users/2428976", "pm_score": 0, "selected": false, "text": "public class DecimalBox : TextBox\n{\n protected override void OnKeyPress(KeyPressEventArgs e)\n {\n if (e.KeyChar == ',')\n {\n e.KeyChar = '.';\n }\n\n if (!char.IsNumber(e.KeyChar) && (Keys)e.KeyChar != Keys.Back && e.KeyChar != '.')\n {\n e.Handled = true;\n }\n\n if(e.KeyChar == '.' )\n {\n if (this.Text.Length == 0)\n {\n this.Text = \"0.\";\n this.SelectionStart = 2;\n e.Handled = true;\n }\n else if (this.Text.Contains(\".\"))\n {\n e.Handled = true;\n }\n }\n\n base.OnKeyPress(e);\n }\n}\n" }, { "answer_id": 52339938, "author": "clamchoda", "author_id": 591285, "author_profile": "https://Stackoverflow.com/users/591285", "pm_score": 0, "selected": false, "text": "class DecimalTextBox : TextBox\n{\n // Handle multiple decimals\n protected override void OnKeyPress(KeyPressEventArgs e)\n {\n if (e.KeyChar == '.')\n if (this.Text.Contains('.'))\n e.Handled = true;\n\n base.OnKeyPress(e);\n }\n\n // Block non digits\n // I scrub characters here instead of handling in OnKeyPress so I can support keyboard events (ctrl + c/v/a)\n protected override void OnTextChanged(EventArgs e)\n {\n this.Text = System.Text.RegularExpressions.Regex.Replace(this.Text, \"[^.0-9]\", \"\");\n base.OnTextChanged(e);\n }\n\n // Apply our format when we're done\n protected override void OnLostFocus(EventArgs e)\n {\n if (!String.IsNullOrEmpty(this.Text))\n this.Text = string.Format(\"{0:N}\", Convert.ToDouble(this.Text));\n\n base.OnLostFocus(e);\n }\n\n\n}\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21699/" ]