qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
94,331
<p>I use the recent Ganymede release of Eclipse, specifically the distro for Java EE and web developers. I have installed a few additional plugins (e.g. Subclipse, Spring, FindBugs) and removed all the Mylyn plugins. </p> <p>I don't do anything particularly heavy-duty within Eclipse such as starting an app server or connecting to databases, yet for some reason, after several hours use I see that Eclipse is using close to 500MB of memory.</p> <p>Does anybody know why Eclipse uses so much memory (leaky?), and more importantly, if there's anything I can do to improve this?</p>
[ { "answer_id": 101193, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 2, "selected": false, "text": "C:\\[jdk1.6.0_0x path]\\bin\\jconsole.exe\n" }, { "answer_id": 101995, "author": "GKelly", "author_id": 18744, "author_profile": "https://Stackoverflow.com/users/18744", "pm_score": 5, "selected": false, "text": "-Xms128m\n-Xmx512m\n-XX:MaxPermSize=120m\n-XX:MaxGCPauseMillis=10\n-XX:MaxHeapFreeRatio=70\n-XX:+UseConcMarkSweepGC\n-XX:+CMSIncrementalMode\n-XX:+CMSIncrementalPacing\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
94,342
<p>I have a string which contain tags in the form <code>&lt; tag &gt;</code>. Is there an easy way for me to programmatically replace instances of these tags with special ascii characters? e.g. replace a tag like <code>"&lt; tab &gt;"</code> with the ascii equivelent of <code>'/t'</code>?</p>
[ { "answer_id": 94366, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 5, "selected": true, "text": "string s = \"...<tab>...\";\ns = s.Replace(\"<tab>\", \"\\t\");\n" }, { "answer_id": 94367, "author": "Burkhard", "author_id": 12860, "author_profile": "https://Stackoverflow.com/users/12860", "pm_score": 2, "selected": false, "text": "using System.Text.RegularExpressions;\n\nRegex.Replace(s, \"TAB\", \"\\t\");//s is your string and TAB is a tab.\n" }, { "answer_id": 94387, "author": "ddc0660", "author_id": 16027, "author_profile": "https://Stackoverflow.com/users/16027", "pm_score": 2, "selected": false, "text": "public static Regex regex = new Regex(\"< tab >\", RegexOptions.CultureInvariant | RegexOptions.Compiled);\npublic static string regexReplace = \"\\t\";\nstring result = regex.Replace(InputText,regexReplace);\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1816/" ]
94,361
<p>What are the best practices for using Java's <code>@Override</code> annotation and why? </p> <p>It seems like it would be overkill to mark every single overridden method with the <code>@Override</code> annotation. Are there certain programming situations that call for using the <code>@Override</code> and others that should never use the <code>@Override</code>? </p>
[ { "answer_id": 94386, "author": "jjnguy", "author_id": 2598, "author_profile": "https://Stackoverflow.com/users/2598", "pm_score": 5, "selected": false, "text": "tostring() toString()" }, { "answer_id": 94388, "author": "Greg Mattes", "author_id": 13940, "author_profile": "https://Stackoverflow.com/users/13940", "pm_score": 3, "selected": false, "text": "@Override" }, { "answer_id": 94411, "author": "Dave L.", "author_id": 3093, "author_profile": "https://Stackoverflow.com/users/3093", "pm_score": 10, "selected": true, "text": "@Implements" }, { "answer_id": 94419, "author": "toluju", "author_id": 12457, "author_profile": "https://Stackoverflow.com/users/12457", "pm_score": 4, "selected": false, "text": "@Override @Override" }, { "answer_id": 94447, "author": "jon", "author_id": 12215, "author_profile": "https://Stackoverflow.com/users/12215", "pm_score": 7, "selected": false, "text": "protected boolean displaySensitiveInformation() {\n return false;\n}\n protected boolean displaySensitiveInformation(Context context) {\n return true;\n}\n" }, { "answer_id": 95019, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 3, "selected": false, "text": "hashcode() hashCode() @Override" }, { "answer_id": 1433076, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "someUIComponent.addMouseListener(new MouseAdapter(){\n public void mouseEntered() {\n ...do something...\n }\n});\n mouseEntered(MouseEvent ev) mouseEntered() @Override" }, { "answer_id": 1510685, "author": "jai", "author_id": 157705, "author_profile": "https://Stackoverflow.com/users/157705", "pm_score": 3, "selected": false, "text": "public class Bigram {\n private final char first;\n private final char second;\n public Bigram(char first, char second) {\n this.first = first;\n this.second = second;\n }\n public boolean equals(Bigram b) {\n return b.first == first && b.second == second;\n }\n public int hashCode() {\n return 31 * first + second;\n }\n\n public static void main(String[] args) {\n Set<Bigram> s = new HashSet<Bigram>();\n for (int i = 0; i < 10; i++)\n for (char ch = 'a'; ch <= 'z'; ch++)\n s.add(new Bigram(ch, ch));\n System.out.println(s.size());\n }\n}\n" }, { "answer_id": 1843124, "author": "Sree", "author_id": 224294, "author_profile": "https://Stackoverflow.com/users/224294", "pm_score": 0, "selected": false, "text": "@Override" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6180/" ]
94,372
<p>I am building a quiz and i need to calculate the total time taken to do the quiz. and i need to display the time taken in HH::MM::SS..any pointers?</p>
[ { "answer_id": 94427, "author": "Brian", "author_id": 1750627, "author_profile": "https://Stackoverflow.com/users/1750627", "pm_score": 3, "selected": true, "text": "var nStart:Number = new Date().time;\n\n// Some time passes\n\nvar nMillisElapsed:Number = new Date().time - nStart;\n\nvar strTime:String = Math.floor(nMillisElapsed / (1000 * 60 * 60)) + \"::\" + \n (Math.floor(nMillisElapsed / (1000 * 60)) % 60) + \"::\" + \n (Math.floor(nMillisElapsed / (1000)) % 60);\n" }, { "answer_id": 4458977, "author": "mica", "author_id": 544503, "author_profile": "https://Stackoverflow.com/users/544503", "pm_score": 1, "selected": false, "text": "var now:Date; //\nvar startDate:Date;\nvar startTime:Number; \n// initialize timer and start it\nfunction initTimer():void{\n startDate = new Date();\n startTime = startDate.getTime();\n //\n var timer:Timer = new Timer(1000,0); // set a new break\n timer.addEventListener(TimerEvent.TIMER, onTimer); // add timer listener\n //\n function onTimer():void{\n now=new Date();\n var nowTime:Number = now.getTime();\n var diff:Number = nowTime-startTime;\n var strTime:String = Math.floor(diff / (1000 * 60 * 60)) + \":\" + \n zeroFill(Math.floor(diff / (1000 * 60)) % 60) + \":\" + \n zeroFill(Math.floor(diff / (1000)) % 60);\n // display where you want\n trace('time elapsed : ' + strTime);\n }\n // fill with zero when number is less than 10\n function zeroFill(myNumber:Number):String{\n var zeroFilledNumber:String=myNumber.toString();\n if(myNumber<10){\n zeroFilledNumber = '0'+zeroFilledNumber;\n }\n return zeroFilledNumber;\n }\n\n // start TIMER\n timer.start();\n\n}\ninitTimer();\n" }, { "answer_id": 15896624, "author": "Jonathan Graef", "author_id": 1045086, "author_profile": "https://Stackoverflow.com/users/1045086", "pm_score": 2, "selected": false, "text": "var startTime:Number = getTimer();\n\n// then after some time passes:\n\nvar elapsedMilliseconds:Number = getTimer() - startTime;\n var strTime:String = Math.floor(elapsedMilliseconds / (1000 * 60 * 60)) + \"::\" + \n(Math.floor(elapsedMilliseconds / (1000 * 60)) % 60) + \"::\" + \n(Math.floor(elapsedMilliseconds / (1000)) % 60);\n" }, { "answer_id": 20033764, "author": "Chakroun Yesser", "author_id": 2898474, "author_profile": "https://Stackoverflow.com/users/2898474", "pm_score": 0, "selected": false, "text": "var countdown:Timer = new Timer(1000);\ncountdown.addEventListener(TimerEvent.TIMER, timerHandler);\ncountdown.start();\n\nfunction timerHandler(e:TimerEvent):void\n{ \n var minute = Math.floor(countdown.currentCount / 60);\n if(minute < 10)\n minute = '0'+minute;\n\n var second = countdown.currentCount % 60;\n if(second < 10)\n second = '0'+second;\n\n\n var timeElapsed = minute +':'+second;\n trace(timeElapsed);\n}\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16458/" ]
94,382
<p>I'm using gvim on Windows.</p> <p>In my _vimrc I've added:</p> <pre><code>set shell=powershell.exe set shellcmdflag=-c set shellpipe=&gt; set shellredir=&gt; function! Test() echo system("dir -name") endfunction command! -nargs=0 Test :call Test() </code></pre> <p>If I execute this function (:Test) I see nonsense characters (non number/letter ASCII characters).</p> <p>If I use cmd as the shell, it works (without the -name), so the problem seems to be with getting output from powershell into vim. </p> <p>Interestingly, this works great:</p> <pre><code>:!dir -name </code></pre> <p>As does this:</p> <pre><code>:r !dir -name </code></pre> <p><strong>UPDATE:</strong> confirming behavior mentioned by <a href="https://stackoverflow.com/questions/94382/vim-with-powershell#101743">David</a></p> <p>If you execute the set commands mentioned above in the _vimrc, :Test outputs nonsense. However, if you execute them directly in vim instead of in the _vimrc, :Test works as expected.</p> <p>Also, I've tried using iconv in case it was an encoding problem:</p> <pre><code>:echo iconv( system("dir -name"), "unicode", &amp;enc ) </code></pre> <p>But this didn't make any difference. I could be using the wrong encoding types though.</p> <p>Anyone know how to make this work?</p>
[ { "answer_id": 94697, "author": "Mark Schill", "author_id": 9482, "author_profile": "https://Stackoverflow.com/users/9482", "pm_score": 2, "selected": false, "text": "\"dir \\*vim\\*\"\n \" -command { dir \\*vim\\* }\"\n" }, { "answer_id": 101743, "author": "David Mohundro", "author_id": 4570, "author_profile": "https://Stackoverflow.com/users/4570", "pm_score": 2, "selected": false, "text": ":set shell=powershell.exe\n:set shellcmdflag=-noprofile\n:echo system(\"dir -name\")\n" }, { "answer_id": 2539941, "author": "Dan Fitch", "author_id": 27614, "author_profile": "https://Stackoverflow.com/users/27614", "pm_score": 2, "selected": false, "text": "set encoding=utf8\n" }, { "answer_id": 3419406, "author": "Nathan Hartley", "author_id": 80161, "author_profile": "https://Stackoverflow.com/users/80161", "pm_score": 6, "selected": true, "text": "if has(\"win32\")\n set shell=cmd.exe\n set shellcmdflag=/c\\ powershell.exe\\ -NoLogo\\ -NoProfile\\ -NonInteractive\\ -ExecutionPolicy\\ RemoteSigned\n set shellpipe=|\n set shellredir=>\nendif\n\nfunction! Test()\n echo system(\"dir -name\")\nendfunction\n :!dir -name :call Test()" }, { "answer_id": 7830735, "author": "actf", "author_id": 205836, "author_profile": "https://Stackoverflow.com/users/205836", "pm_score": 4, "selected": false, "text": ":set shell=powershell\n set shell=powershell\n powershell -c \"cmd > tmpfile\"\n powershell -c \"cmd\" > tmpfile\n set shell=powershell\nset shellcmdflag=-c\nset shellquote=\\\"\nset shellxquote=\n" }, { "answer_id": 27499996, "author": "Enno", "author_id": 3528522, "author_profile": "https://Stackoverflow.com/users/3528522", "pm_score": 0, "selected": false, "text": "\nset shellcmdflag=\\ -c\n \nset shell=powershell\nset shellcmdflag=-c\n \nset shellcmdflag=\\ -c\n" }, { "answer_id": 33745531, "author": "Mark Stanfill", "author_id": 5460180, "author_profile": "https://Stackoverflow.com/users/5460180", "pm_score": 1, "selected": false, "text": "if has(\"win32\") || has(\"gui_win32\") \n if executable(\"PowerShell\") \n \" Set PowerShell as the shell for running external ! commands \n \" http://stackoverflow.com/questions/7605917/system-with-powershell-in-vim \n set shell=PowerShell \n set shellcmdflag=-ExecutionPolicy\\ RemoteSigned\\ -Command \n set shellquote=\\\" \n \" shellxquote must be a literal space character. \n set shellxquote= \n endif \nendif \n" }, { "answer_id": 41980093, "author": "Lobo", "author_id": 2968792, "author_profile": "https://Stackoverflow.com/users/2968792", "pm_score": 0, "selected": false, "text": "Remove-Item Alias:diff -force\n" }, { "answer_id": 59870353, "author": "Rafael Kitover", "author_id": 262458, "author_profile": "https://Stackoverflow.com/users/262458", "pm_score": 1, "selected": false, "text": "$profile diffutils Remove-Item Alias:diff -force\n ~/.vimrc if (has('win32') || has('gui_win32')) && executable('pwsh')\n set shell=pwsh\n set shellcmdflag=\\ -ExecutionPolicy\\ RemoteSigned\\ -NoProfile\\ -Nologo\\ -NonInteractive\\ -Command\nendif\n shellcmdflag" }, { "answer_id": 66261005, "author": "CRTejaswi", "author_id": 7794299, "author_profile": "https://Stackoverflow.com/users/7794299", "pm_score": 0, "selected": false, "text": "set shell=C:\\\\Windows\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4407/" ]
94,410
<p>I'm considering using Castle Windsor's Interceptors to cache data for helping scale an asp.net site.</p> <p>Does anyone have any thoughts/experience with doing this?</p> <p>Minor clarification: My intention was to use Windsor to intercept 'expensive' calls and delegate to MemCacheD or Velocity (or another distributed cache) for the caching itself.</p>
[ { "answer_id": 26620863, "author": "Jakob", "author_id": 1809290, "author_profile": "https://Stackoverflow.com/users/1809290", "pm_score": 0, "selected": false, "text": "var container = new WindsorContainer();\ncontainer.Register(Component.For<CacheInterceptor>()\n .Instance(new CacheInterceptor(new Cache(TimeoutStyle.RenewTimoutOnQuery, TimeSpan.FromSeconds(3)))));\ncontainer.Register(Component.For<IServer>().ImplementedBy<Server>().Interceptors<CacheInterceptor>());" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17824/" ]
94,420
<p>So I have a form that uses infopath services via sharepoint, and after multiple attempts at attempting to fix a rendering problem (tables appear WAY too wide to be readable), I think I have found the problem : date controls.</p> <p>It seems date controls within Infopath 2007 screw with rendering somehow. To test, I made 2 variations of a VERY simple form - one with a date control, one with a text control - and placed them inside a table.</p> <p>When emailed, the one with the date control rendered incorrectly.</p> <p>My question is - has anyone experienced this before? If you have time, test it out. I think it is a bug or something, but not exactly sure.</p> <p>I am using Infopath 2007, Sharepoint 2007, and Outlook 2007.</p> <hr> <h2><strong>Updated Sept 19, 2008</strong></h2> <p>Yes, web form capability is checked. Web compatible date controls? I think so - everything looks perfect in the browser... only the email messes up. and yes you are correct. My mistake this is Sharepoint 2007. I fixed it above.</p> <p>If anyone has the time, try it out - it's very frustrating to have to use text boxes for dates. Especially with the 'talent' we have here. lol</p>
[ { "answer_id": 26620863, "author": "Jakob", "author_id": 1809290, "author_profile": "https://Stackoverflow.com/users/1809290", "pm_score": 0, "selected": false, "text": "var container = new WindsorContainer();\ncontainer.Register(Component.For<CacheInterceptor>()\n .Instance(new CacheInterceptor(new Cache(TimeoutStyle.RenewTimoutOnQuery, TimeSpan.FromSeconds(3)))));\ncontainer.Register(Component.For<IServer>().ImplementedBy<Server>().Interceptors<CacheInterceptor>());" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13959/" ]
94,445
<p>I'm generating a self-signed SSL certificate to protect my server's admin section, and I keep getting this message from OpenSSL:</p> <blockquote> <p>unable to write 'random state'</p> </blockquote> <p>What does this mean?</p> <p>This is on an Ubuntu server. I have upgraded libssl to fix <a href="http://www.ubuntu.com/usn/usn-612-1">the recent security vulnerability</a>.</p>
[ { "answer_id": 94458, "author": "Ville Laurikari", "author_id": 7446, "author_profile": "https://Stackoverflow.com/users/7446", "pm_score": 10, "selected": true, "text": "sudo rm ~/.rnd\n" }, { "answer_id": 6484589, "author": "Jusuf", "author_id": 816211, "author_profile": "https://Stackoverflow.com/users/816211", "pm_score": 4, "selected": false, "text": "vars.bat set HOME=C:\\Program Files (x86)\\OpenVPN\\easy-rsa\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17965/" ]
94,456
<p>I have an instance of a <code>System.Drawing.Bitmap</code> and would like to make it available to my WPF app in the form of a <code>System.Windows.Media.Imaging.BitmapImage</code>.</p> <p>What would be the best approach for this?</p>
[ { "answer_id": 96470, "author": "Kevin", "author_id": 2723, "author_profile": "https://Stackoverflow.com/users/2723", "pm_score": 7, "selected": true, "text": "ScreenCapture = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(\n bmp.GetHbitmap(), \n IntPtr.Zero, \n System.Windows.Int32Rect.Empty, \n BitmapSizeOptions.FromWidthAndHeight(width, height));\n" }, { "answer_id": 1069509, "author": "Pawel Lesnikowski", "author_id": 80894, "author_profile": "https://Stackoverflow.com/users/80894", "pm_score": 8, "selected": false, "text": "using(MemoryStream memory = new MemoryStream())\n{\n bitmap.Save(memory, ImageFormat.Png);\n memory.Position = 0;\n BitmapImage bitmapImage = new BitmapImage();\n bitmapImage.BeginInit();\n bitmapImage.StreamSource = memory;\n bitmapImage.CacheOption = BitmapCacheOption.OnLoad;\n bitmapImage.EndInit();\n}\n" }, { "answer_id": 1470182, "author": "Alastair Pitts", "author_id": 120243, "author_profile": "https://Stackoverflow.com/users/120243", "pm_score": 6, "selected": false, "text": " /// <summary>\n /// Converts a <see cref=\"System.Drawing.Image\"/> into a WPF <see cref=\"BitmapSource\"/>.\n /// </summary>\n /// <param name=\"source\">The source image.</param>\n /// <returns>A BitmapSource</returns>\n public static BitmapSource ToBitmapSource(this System.Drawing.Image source)\n {\n System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(source);\n\n var bitSrc = bitmap.ToBitmapSource();\n\n bitmap.Dispose();\n bitmap = null;\n\n return bitSrc;\n }\n\n /// <summary>\n /// Converts a <see cref=\"System.Drawing.Bitmap\"/> into a WPF <see cref=\"BitmapSource\"/>.\n /// </summary>\n /// <remarks>Uses GDI to do the conversion. Hence the call to the marshalled DeleteObject.\n /// </remarks>\n /// <param name=\"source\">The source bitmap.</param>\n /// <returns>A BitmapSource</returns>\n public static BitmapSource ToBitmapSource(this System.Drawing.Bitmap source)\n {\n BitmapSource bitSrc = null;\n\n var hBitmap = source.GetHbitmap();\n\n try\n {\n bitSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(\n hBitmap,\n IntPtr.Zero,\n Int32Rect.Empty,\n BitmapSizeOptions.FromEmptyOptions());\n }\n catch (Win32Exception)\n {\n bitSrc = null;\n }\n finally\n {\n NativeMethods.DeleteObject(hBitmap);\n }\n\n return bitSrc;\n }\n /// <summary>\n/// FxCop requires all Marshalled functions to be in a class called NativeMethods.\n/// </summary>\ninternal static class NativeMethods\n{\n [DllImport(\"gdi32.dll\")]\n [return: MarshalAs(UnmanagedType.Bool)]\n internal static extern bool DeleteObject(IntPtr hObject);\n}\n" }, { "answer_id": 6775114, "author": "Daniel Wolf", "author_id": 52041, "author_profile": "https://Stackoverflow.com/users/52041", "pm_score": 5, "selected": false, "text": "using System.Drawing;\nusing System.Drawing.Imaging;\nusing System.IO;\nusing System.Windows.Media.Imaging;\n\npublic static class BitmapConversion {\n\n public static Bitmap ToWinFormsBitmap(this BitmapSource bitmapsource) {\n using (MemoryStream stream = new MemoryStream()) {\n BitmapEncoder enc = new BmpBitmapEncoder();\n enc.Frames.Add(BitmapFrame.Create(bitmapsource));\n enc.Save(stream);\n\n using (var tempBitmap = new Bitmap(stream)) {\n // According to MSDN, one \"must keep the stream open for the lifetime of the Bitmap.\"\n // So we return a copy of the new bitmap, allowing us to dispose both the bitmap and the stream.\n return new Bitmap(tempBitmap);\n }\n }\n }\n\n public static BitmapSource ToWpfBitmap(this Bitmap bitmap) {\n using (MemoryStream stream = new MemoryStream()) {\n bitmap.Save(stream, ImageFormat.Bmp);\n\n stream.Position = 0;\n BitmapImage result = new BitmapImage();\n result.BeginInit();\n // According to MSDN, \"The default OnDemand cache option retains access to the stream until the image is needed.\"\n // Force the bitmap to load right now so we can dispose the stream.\n result.CacheOption = BitmapCacheOption.OnLoad;\n result.StreamSource = stream;\n result.EndInit();\n result.Freeze();\n return result;\n }\n }\n}\n" }, { "answer_id": 7375570, "author": "Roland", "author_id": 480894, "author_profile": "https://Stackoverflow.com/users/480894", "pm_score": 2, "selected": false, "text": "// Create the image element.\nImage simpleImage = new Image(); \nsimpleImage.Width = 200;\nsimpleImage.Margin = new Thickness(5);\n\n// Create source.\nBitmapImage bi = new BitmapImage();\n// BitmapImage.UriSource must be in a BeginInit/EndInit block.\nbi.BeginInit();\nbi.UriSource = new Uri(@\"/sampleImages/cherries_larger.jpg\",UriKind.RelativeOrAbsolute);\nbi.EndInit();\n// Set the image source.\nsimpleImage.Source = bi;\n" }, { "answer_id": 7390373, "author": "Tony", "author_id": 194717, "author_profile": "https://Stackoverflow.com/users/194717", "pm_score": 3, "selected": false, "text": "// at class level;\n[System.Runtime.InteropServices.DllImport(\"gdi32.dll\")]\npublic static extern bool DeleteObject(IntPtr hObject); // https://stackoverflow.com/a/1546121/194717\n\n\n/// <summary> \n/// Converts a <see cref=\"System.Drawing.Bitmap\"/> into a WPF <see cref=\"BitmapSource\"/>. \n/// </summary> \n/// <remarks>Uses GDI to do the conversion. Hence the call to the marshalled DeleteObject. \n/// </remarks> \n/// <param name=\"source\">The source bitmap.</param> \n/// <returns>A BitmapSource</returns> \npublic static System.Windows.Media.Imaging.BitmapSource ToBitmapSource(this System.Drawing.Bitmap source)\n{\n var hBitmap = source.GetHbitmap();\n var result = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, System.Windows.Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());\n\n DeleteObject(hBitmap);\n\n return result;\n}\n" }, { "answer_id": 29917964, "author": "weston", "author_id": 360211, "author_profile": "https://Stackoverflow.com/users/360211", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Drawing;\nusing System.Runtime.ConstrainedExecution;\nusing System.Runtime.InteropServices;\nusing System.Security;\nusing System.Windows;\nusing System.Windows.Interop;\nusing System.Windows.Media.Imaging;\nusing Microsoft.Win32.SafeHandles;\n\nnamespace WpfHelpers\n{\n public static class BitmapToBitmapSource\n {\n public static BitmapSource ToBitmapSource(this Bitmap source)\n {\n using (var handle = new SafeHBitmapHandle(source))\n {\n return Imaging.CreateBitmapSourceFromHBitmap(handle.DangerousGetHandle(),\n IntPtr.Zero, Int32Rect.Empty,\n BitmapSizeOptions.FromEmptyOptions());\n }\n }\n\n [DllImport(\"gdi32\")]\n private static extern int DeleteObject(IntPtr o);\n\n private sealed class SafeHBitmapHandle : SafeHandleZeroOrMinusOneIsInvalid\n {\n [SecurityCritical]\n public SafeHBitmapHandle(Bitmap bitmap)\n : base(true)\n {\n SetHandle(bitmap.GetHbitmap());\n }\n\n [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]\n protected override bool ReleaseHandle()\n {\n return DeleteObject(handle) > 0;\n }\n }\n }\n}\n" }, { "answer_id": 32841840, "author": "Andreas", "author_id": 690656, "author_profile": "https://Stackoverflow.com/users/690656", "pm_score": 3, "selected": false, "text": "class SharedBitmapSource : BitmapSource, IDisposable\n{\n #region Public Properties\n\n /// <summary>\n /// I made it public so u can reuse it and get the best our of both namespaces\n /// </summary>\n public Bitmap Bitmap { get; private set; }\n\n public override double DpiX { get { return Bitmap.HorizontalResolution; } }\n\n public override double DpiY { get { return Bitmap.VerticalResolution; } }\n\n public override int PixelHeight { get { return Bitmap.Height; } }\n\n public override int PixelWidth { get { return Bitmap.Width; } }\n\n public override System.Windows.Media.PixelFormat Format { get { return ConvertPixelFormat(Bitmap.PixelFormat); } }\n\n public override BitmapPalette Palette { get { return null; } }\n\n #endregion\n\n #region Constructor/Destructor\n\n public SharedBitmapSource(int width, int height,System.Drawing.Imaging.PixelFormat sourceFormat)\n :this(new Bitmap(width,height, sourceFormat) ) { }\n\n public SharedBitmapSource(Bitmap bitmap)\n {\n Bitmap = bitmap;\n }\n\n // Use C# destructor syntax for finalization code.\n ~SharedBitmapSource()\n {\n // Simply call Dispose(false).\n Dispose(false);\n }\n\n #endregion\n\n #region Overrides\n\n public override void CopyPixels(Int32Rect sourceRect, Array pixels, int stride, int offset)\n {\n BitmapData sourceData = Bitmap.LockBits(\n new Rectangle(sourceRect.X, sourceRect.Y, sourceRect.Width, sourceRect.Height),\n ImageLockMode.ReadOnly,\n Bitmap.PixelFormat);\n\n var length = sourceData.Stride * sourceData.Height;\n\n if (pixels is byte[])\n {\n var bytes = pixels as byte[];\n Marshal.Copy(sourceData.Scan0, bytes, 0, length);\n }\n\n Bitmap.UnlockBits(sourceData);\n }\n\n protected override Freezable CreateInstanceCore()\n {\n return (Freezable)Activator.CreateInstance(GetType());\n }\n\n #endregion\n\n #region Public Methods\n\n public BitmapSource Resize(int newWidth, int newHeight)\n {\n Image newImage = new Bitmap(newWidth, newHeight);\n using (Graphics graphicsHandle = Graphics.FromImage(newImage))\n {\n graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;\n graphicsHandle.DrawImage(Bitmap, 0, 0, newWidth, newHeight);\n }\n return new SharedBitmapSource(newImage as Bitmap);\n }\n\n public new BitmapSource Clone()\n {\n return new SharedBitmapSource(new Bitmap(Bitmap));\n }\n\n //Implement IDisposable.\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n #endregion\n\n #region Protected/Private Methods\n\n private static System.Windows.Media.PixelFormat ConvertPixelFormat(System.Drawing.Imaging.PixelFormat sourceFormat)\n {\n switch (sourceFormat)\n {\n case System.Drawing.Imaging.PixelFormat.Format24bppRgb:\n return PixelFormats.Bgr24;\n\n case System.Drawing.Imaging.PixelFormat.Format32bppArgb:\n return PixelFormats.Pbgra32;\n\n case System.Drawing.Imaging.PixelFormat.Format32bppRgb:\n return PixelFormats.Bgr32;\n\n }\n return new System.Windows.Media.PixelFormat();\n }\n\n private bool _disposed = false;\n\n protected virtual void Dispose(bool disposing)\n {\n if (!_disposed)\n {\n if (disposing)\n {\n // Free other state (managed objects).\n }\n // Free your own state (unmanaged objects).\n // Set large fields to null.\n _disposed = true;\n }\n }\n\n #endregion\n}\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2723/" ]
94,488
<p>More specifically, when the exception contains custom objects which may or may not themselves be serializable.</p> <p>Take this example:</p> <pre><code>public class MyException : Exception { private readonly string resourceName; private readonly IList&lt;string&gt; validationErrors; public MyException(string resourceName, IList&lt;string&gt; validationErrors) { this.resourceName = resourceName; this.validationErrors = validationErrors; } public string ResourceName { get { return this.resourceName; } } public IList&lt;string&gt; ValidationErrors { get { return this.validationErrors; } } } </code></pre> <p>If this Exception is serialized and de-serialized, the two custom properties (<code>ResourceName</code> and <code>ValidationErrors</code>) will not be preserved. The properties will return <code>null</code>.</p> <p><strong>Is there a common code pattern for implementing serialization for custom exception?</strong></p>
[ { "answer_id": 94625, "author": "Adrian Clark", "author_id": 148, "author_profile": "https://Stackoverflow.com/users/148", "pm_score": 5, "selected": false, "text": "GetObjectData [Serializable]\npublic class MyException : Exception\n{\n private readonly string resourceName;\n private readonly IList<string> validationErrors;\n\n public MyException(string resourceName, IList<string> validationErrors)\n {\n this.resourceName = resourceName;\n this.validationErrors = validationErrors;\n }\n\n public string ResourceName\n {\n get { return this.resourceName; }\n }\n\n public IList<string> ValidationErrors\n {\n get { return this.validationErrors; }\n }\n\n [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter=true)]\n protected MyException(SerializationInfo info, StreamingContext context) : base (info, context)\n {\n this.resourceName = info.GetString(\"MyException.ResourceName\");\n this.validationErrors = info.GetValue(\"MyException.ValidationErrors\", typeof(IList<string>));\n }\n\n [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter=true)]\n public override void GetObjectData(SerializationInfo info, StreamingContext context)\n {\n base.GetObjectData(info, context);\n\n info.AddValue(\"MyException.ResourceName\", this.ResourceName);\n\n // Note: if \"List<T>\" isn't serializable you may need to work out another\n // method of adding your list, this is just for show...\n info.AddValue(\"MyException.ValidationErrors\", this.ValidationErrors, typeof(IList<string>));\n }\n\n}\n" }, { "answer_id": 100369, "author": "Daniel Fortunov", "author_id": 5975, "author_profile": "https://Stackoverflow.com/users/5975", "pm_score": 10, "selected": true, "text": "namespace SerializableExceptions\n{\n using System;\n using System.Runtime.Serialization;\n\n [Serializable]\n // Important: This attribute is NOT inherited from Exception, and MUST be specified \n // otherwise serialization will fail with a SerializationException stating that\n // \"Type X in Assembly Y is not marked as serializable.\"\n public class SerializableExceptionWithoutCustomProperties : Exception\n {\n public SerializableExceptionWithoutCustomProperties()\n {\n }\n\n public SerializableExceptionWithoutCustomProperties(string message) \n : base(message)\n {\n }\n\n public SerializableExceptionWithoutCustomProperties(string message, Exception innerException) \n : base(message, innerException)\n {\n }\n\n // Without this constructor, deserialization will fail\n protected SerializableExceptionWithoutCustomProperties(SerializationInfo info, StreamingContext context) \n : base(info, context)\n {\n }\n }\n}\n MySerializableException sealed MyDerivedSerializableException [Serializable] SerializationException [Serializable] Exception ISerializable private sealed protected base.GetObjectData(info, context) namespace SerializableExceptions\n{\n using System;\n using System.Collections.Generic;\n using System.Runtime.Serialization;\n using System.Security.Permissions;\n\n [Serializable]\n // Important: This attribute is NOT inherited from Exception, and MUST be specified \n // otherwise serialization will fail with a SerializationException stating that\n // \"Type X in Assembly Y is not marked as serializable.\"\n public class SerializableExceptionWithCustomProperties : Exception\n {\n private readonly string resourceName;\n private readonly IList<string> validationErrors;\n\n public SerializableExceptionWithCustomProperties()\n {\n }\n\n public SerializableExceptionWithCustomProperties(string message) \n : base(message)\n {\n }\n\n public SerializableExceptionWithCustomProperties(string message, Exception innerException)\n : base(message, innerException)\n {\n }\n\n public SerializableExceptionWithCustomProperties(string message, string resourceName, IList<string> validationErrors)\n : base(message)\n {\n this.resourceName = resourceName;\n this.validationErrors = validationErrors;\n }\n\n public SerializableExceptionWithCustomProperties(string message, string resourceName, IList<string> validationErrors, Exception innerException)\n : base(message, innerException)\n {\n this.resourceName = resourceName;\n this.validationErrors = validationErrors;\n }\n\n [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]\n // Constructor should be protected for unsealed classes, private for sealed classes.\n // (The Serializer invokes this constructor through reflection, so it can be private)\n protected SerializableExceptionWithCustomProperties(SerializationInfo info, StreamingContext context)\n : base(info, context)\n {\n this.resourceName = info.GetString(\"ResourceName\");\n this.validationErrors = (IList<string>)info.GetValue(\"ValidationErrors\", typeof(IList<string>));\n }\n\n public string ResourceName\n {\n get { return this.resourceName; }\n }\n\n public IList<string> ValidationErrors\n {\n get { return this.validationErrors; }\n }\n\n [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]\n public override void GetObjectData(SerializationInfo info, StreamingContext context)\n {\n if (info == null)\n {\n throw new ArgumentNullException(\"info\");\n }\n\n info.AddValue(\"ResourceName\", this.ResourceName);\n\n // Note: if \"List<T>\" isn't serializable you may need to work out another\n // method of adding your list, this is just for show...\n info.AddValue(\"ValidationErrors\", this.ValidationErrors, typeof(IList<string>));\n\n // MUST call through to the base class to let it save its own state\n base.GetObjectData(info, context);\n }\n }\n}\n namespace SerializableExceptions\n{\n using System;\n using System.Collections.Generic;\n using System.Runtime.Serialization;\n using System.Security.Permissions;\n\n [Serializable]\n public sealed class DerivedSerializableExceptionWithAdditionalCustomProperty : SerializableExceptionWithCustomProperties\n {\n private readonly string username;\n\n public DerivedSerializableExceptionWithAdditionalCustomProperty()\n {\n }\n\n public DerivedSerializableExceptionWithAdditionalCustomProperty(string message)\n : base(message)\n {\n }\n\n public DerivedSerializableExceptionWithAdditionalCustomProperty(string message, Exception innerException) \n : base(message, innerException)\n {\n }\n\n public DerivedSerializableExceptionWithAdditionalCustomProperty(string message, string username, string resourceName, IList<string> validationErrors) \n : base(message, resourceName, validationErrors)\n {\n this.username = username;\n }\n\n public DerivedSerializableExceptionWithAdditionalCustomProperty(string message, string username, string resourceName, IList<string> validationErrors, Exception innerException) \n : base(message, resourceName, validationErrors, innerException)\n {\n this.username = username;\n }\n\n [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]\n // Serialization constructor is private, as this class is sealed\n private DerivedSerializableExceptionWithAdditionalCustomProperty(SerializationInfo info, StreamingContext context)\n : base(info, context)\n {\n this.username = info.GetString(\"Username\");\n }\n\n public string Username\n {\n get { return this.username; }\n }\n\n public override void GetObjectData(SerializationInfo info, StreamingContext context)\n {\n if (info == null)\n {\n throw new ArgumentNullException(\"info\");\n }\n info.AddValue(\"Username\", this.username);\n base.GetObjectData(info, context);\n }\n }\n}\n namespace SerializableExceptions\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using System.Runtime.Serialization.Formatters.Binary;\n using Microsoft.VisualStudio.TestTools.UnitTesting;\n\n [TestClass]\n public class UnitTests\n {\n private const string Message = \"The widget has unavoidably blooped out.\";\n private const string ResourceName = \"Resource-A\";\n private const string ValidationError1 = \"You forgot to set the whizz bang flag.\";\n private const string ValidationError2 = \"Wally cannot operate in zero gravity.\";\n private readonly List<string> validationErrors = new List<string>();\n private const string Username = \"Barry\";\n\n public UnitTests()\n {\n validationErrors.Add(ValidationError1);\n validationErrors.Add(ValidationError2);\n }\n\n [TestMethod]\n public void TestSerializableExceptionWithoutCustomProperties()\n {\n Exception ex =\n new SerializableExceptionWithoutCustomProperties(\n \"Message\", new Exception(\"Inner exception.\"));\n\n // Save the full ToString() value, including the exception message and stack trace.\n string exceptionToString = ex.ToString();\n\n // Round-trip the exception: Serialize and de-serialize with a BinaryFormatter\n BinaryFormatter bf = new BinaryFormatter();\n using (MemoryStream ms = new MemoryStream())\n {\n // \"Save\" object state\n bf.Serialize(ms, ex);\n\n // Re-use the same stream for de-serialization\n ms.Seek(0, 0);\n\n // Replace the original exception with de-serialized one\n ex = (SerializableExceptionWithoutCustomProperties)bf.Deserialize(ms);\n }\n\n // Double-check that the exception message and stack trace (owned by the base Exception) are preserved\n Assert.AreEqual(exceptionToString, ex.ToString(), \"ex.ToString()\");\n }\n\n [TestMethod]\n public void TestSerializableExceptionWithCustomProperties()\n {\n SerializableExceptionWithCustomProperties ex = \n new SerializableExceptionWithCustomProperties(Message, ResourceName, validationErrors);\n\n // Sanity check: Make sure custom properties are set before serialization\n Assert.AreEqual(Message, ex.Message, \"Message\");\n Assert.AreEqual(ResourceName, ex.ResourceName, \"ex.ResourceName\");\n Assert.AreEqual(2, ex.ValidationErrors.Count, \"ex.ValidationErrors.Count\");\n Assert.AreEqual(ValidationError1, ex.ValidationErrors[0], \"ex.ValidationErrors[0]\");\n Assert.AreEqual(ValidationError2, ex.ValidationErrors[1], \"ex.ValidationErrors[1]\");\n\n // Save the full ToString() value, including the exception message and stack trace.\n string exceptionToString = ex.ToString();\n\n // Round-trip the exception: Serialize and de-serialize with a BinaryFormatter\n BinaryFormatter bf = new BinaryFormatter();\n using (MemoryStream ms = new MemoryStream())\n {\n // \"Save\" object state\n bf.Serialize(ms, ex);\n\n // Re-use the same stream for de-serialization\n ms.Seek(0, 0);\n\n // Replace the original exception with de-serialized one\n ex = (SerializableExceptionWithCustomProperties)bf.Deserialize(ms);\n }\n\n // Make sure custom properties are preserved after serialization\n Assert.AreEqual(Message, ex.Message, \"Message\");\n Assert.AreEqual(ResourceName, ex.ResourceName, \"ex.ResourceName\");\n Assert.AreEqual(2, ex.ValidationErrors.Count, \"ex.ValidationErrors.Count\");\n Assert.AreEqual(ValidationError1, ex.ValidationErrors[0], \"ex.ValidationErrors[0]\");\n Assert.AreEqual(ValidationError2, ex.ValidationErrors[1], \"ex.ValidationErrors[1]\");\n\n // Double-check that the exception message and stack trace (owned by the base Exception) are preserved\n Assert.AreEqual(exceptionToString, ex.ToString(), \"ex.ToString()\");\n }\n\n [TestMethod]\n public void TestDerivedSerializableExceptionWithAdditionalCustomProperty()\n {\n DerivedSerializableExceptionWithAdditionalCustomProperty ex = \n new DerivedSerializableExceptionWithAdditionalCustomProperty(Message, Username, ResourceName, validationErrors);\n\n // Sanity check: Make sure custom properties are set before serialization\n Assert.AreEqual(Message, ex.Message, \"Message\");\n Assert.AreEqual(ResourceName, ex.ResourceName, \"ex.ResourceName\");\n Assert.AreEqual(2, ex.ValidationErrors.Count, \"ex.ValidationErrors.Count\");\n Assert.AreEqual(ValidationError1, ex.ValidationErrors[0], \"ex.ValidationErrors[0]\");\n Assert.AreEqual(ValidationError2, ex.ValidationErrors[1], \"ex.ValidationErrors[1]\");\n Assert.AreEqual(Username, ex.Username);\n\n // Save the full ToString() value, including the exception message and stack trace.\n string exceptionToString = ex.ToString();\n\n // Round-trip the exception: Serialize and de-serialize with a BinaryFormatter\n BinaryFormatter bf = new BinaryFormatter();\n using (MemoryStream ms = new MemoryStream())\n {\n // \"Save\" object state\n bf.Serialize(ms, ex);\n\n // Re-use the same stream for de-serialization\n ms.Seek(0, 0);\n\n // Replace the original exception with de-serialized one\n ex = (DerivedSerializableExceptionWithAdditionalCustomProperty)bf.Deserialize(ms);\n }\n\n // Make sure custom properties are preserved after serialization\n Assert.AreEqual(Message, ex.Message, \"Message\");\n Assert.AreEqual(ResourceName, ex.ResourceName, \"ex.ResourceName\");\n Assert.AreEqual(2, ex.ValidationErrors.Count, \"ex.ValidationErrors.Count\");\n Assert.AreEqual(ValidationError1, ex.ValidationErrors[0], \"ex.ValidationErrors[0]\");\n Assert.AreEqual(ValidationError2, ex.ValidationErrors[1], \"ex.ValidationErrors[1]\");\n Assert.AreEqual(Username, ex.Username);\n\n // Double-check that the exception message and stack trace (owned by the base Exception) are preserved\n Assert.AreEqual(exceptionToString, ex.ToString(), \"ex.ToString()\");\n }\n }\n}\n" }, { "answer_id": 26895291, "author": "Uwe Keim", "author_id": 107625, "author_profile": "https://Stackoverflow.com/users/107625", "pm_score": 4, "selected": false, "text": "Data Exception [Serializable]\npublic class JsonReadException : Exception\n{\n // ...\n\n public string JsonFilePath\n {\n get { return Data[@\"_jsonFilePath\"] as string; }\n private set { Data[@\"_jsonFilePath\"] = value; }\n }\n\n public string Json\n {\n get { return Data[@\"_json\"] as string; }\n private set { Data[@\"_json\"] = value; }\n }\n\n // ...\n}\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5975/" ]
94,490
<p>I need to read selected files, matching on the file name, from a remote zip archive using Python. I don't want to save the full zip to a temporary file (it's not that large, so I can handle everything in memory).</p> <p>I've already written the code and it works, and I'm answering this myself so I can search for it later. But since evidence suggests that I'm one of the dumber participants on Stackoverflow, I'm sure there's room for improvement.</p>
[ { "answer_id": 94491, "author": "Marcel Levy", "author_id": 676, "author_profile": "https://Stackoverflow.com/users/676", "pm_score": 4, "selected": true, "text": "import urllib2, cStringIO, zipfile\n\ntry:\n remotezip = urllib2.urlopen(url)\n zipinmemory = cStringIO.StringIO(remotezip.read())\n zip = zipfile.ZipFile(zipinmemory)\n for fn in zip.namelist():\n if fn.endswith(\".ranks\"):\n ranks_data = zip.read(fn)\n for line in ranks_data.split(\"\\n\"):\n # do something with each line\nexcept urllib2.HTTPError:\n # handle exception\n" }, { "answer_id": 952834, "author": "Tim Pietzcker", "author_id": 20670, "author_profile": "https://Stackoverflow.com/users/20670", "pm_score": 2, "selected": false, "text": "import urllib.request, io, zipfile\n\ntry:\n remotezip = urllib.request.urlopen(url)\n zipinmemory = io.BytesIO(remotezip.read())\n zip = zipfile.ZipFile(zipinmemory)\n for fn in zip.namelist():\n if fn.endswith(\".ranks\"):\n ranks_data = zip.read(fn)\n for line in ranks_data.split(\"\\n\"):\n # do something with each line\nexcept urllib.request.HTTPError:\n # handle exception\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/676/" ]
94,502
<p>I have a simple database table called "Entries":</p> <pre><code>class CreateEntries &lt; ActiveRecord::Migration def self.up create_table :entries do |t| t.string :firstName t.string :lastName #etc. t.timestamps end end def self.down drop_table :entries end end </code></pre> <p>How do I write a handler that will return the contents of the Entries table as a CSV file (ideally in a way that it will automatically open in Excel)?</p> <pre><code>class EntriesController &lt; ApplicationController def getcsv @entries = Entry.find( :all ) # ??? NOW WHAT ???? end end </code></pre>
[ { "answer_id": 94520, "author": "kch", "author_id": 13989, "author_profile": "https://Stackoverflow.com/users/13989", "pm_score": 3, "selected": false, "text": "gem install fastercsv\ngem install spreadsheet-excel\n FasterCSV.generate(:col_sep => \";\", :row_sep => \"\\r\\n\") { |csv| ... }\n CSV_FIELDS = %w[ title created_at etc ]\nFasterCSV.generate do |csv|\n Entry.all.map { |r| CSV_FIELDS.map { |m| r.send m } }.each { |row| csv << row }\nend\n" }, { "answer_id": 94577, "author": "JasonTrue", "author_id": 13433, "author_profile": "https://Stackoverflow.com/users/13433", "pm_score": 2, "selected": false, "text": "csv_string = FasterCSV.generate do |csv|\n csv << [\"row\", \"of\", \"CSV\", \"data\"]\n csv << [\"another\", \"row\"]\n# ...\nend\n" }, { "answer_id": 94626, "author": "Clinton Dreisbach", "author_id": 6262, "author_profile": "https://Stackoverflow.com/users/6262", "pm_score": 6, "selected": false, "text": "def render_csv(filename = nil)\n filename ||= params[:action]\n filename += '.csv'\n\n if request.env['HTTP_USER_AGENT'] =~ /msie/i\n headers['Pragma'] = 'public'\n headers[\"Content-type\"] = \"text/plain\" \n headers['Cache-Control'] = 'no-cache, must-revalidate, post-check=0, pre-check=0'\n headers['Content-Disposition'] = \"attachment; filename=\\\"#{filename}\\\"\" \n headers['Expires'] = \"0\" \n else\n headers[\"Content-Type\"] ||= 'text/csv'\n headers[\"Content-Disposition\"] = \"attachment; filename=\\\"#{filename}\\\"\" \n end\n\n render :layout => false\nend\n respond_to do |wants|\n wants.csv do\n render_csv(\"users-#{Time.now.strftime(\"%Y%m%d\")}\")\n end\nend\n generate_csv UserID,Email,Password,ActivationURL,Messages\n<%= generate_csv do |csv|\n @users.each do |user|\n csv << [ user[:id], user[:email], user[:password], user[:url], user[:message] ]\n end\nend %>\n" }, { "answer_id": 94654, "author": "Eric", "author_id": 4540, "author_profile": "https://Stackoverflow.com/users/4540", "pm_score": 5, "selected": false, "text": "require 'fastercsv'\n\nclass EntriesController < ApplicationController\n\n def getcsv\n entries = Entry.find(:all)\n csv_string = FasterCSV.generate do |csv| \n csv << [\"first\",\"last\"]\n entries.each do |e|\n csv << [e.firstName,e.lastName]\n end\n end\n send_data csv_string, :type => \"text/plain\", \n :filename=>\"entries.csv\",\n :disposition => 'attachment'\n\n end\n\n\nend\n" }, { "answer_id": 222698, "author": "rwc9u", "author_id": 7778, "author_profile": "https://Stackoverflow.com/users/7778", "pm_score": 5, "selected": false, "text": "require \"csv\"\n def show\n @advertiser_search = AdvertiserSearch.find(params[:id])\n @advertisers = @advertiser_search.search(params[:page])\n respond_to do |format|\n format.html # show.html.erb\n format.csv # show.csv.erb\n end\n end\n <%- headers = [\"Id\", \"Name\", \"Account Number\", \"Publisher\", \"Product Name\", \"Status\"] -%>\n<%= CSV.generate_line headers %>\n<%- @advertiser_search.advertisers.each do |advertiser| -%>\n<%- advertiser.subscriptions.each do |subscription| -%>\n<%- row = [ advertiser.id,\n advertiser.name,\n advertiser.external_id,\n advertiser.publisher.name,\n publisher_product_name(subscription),\n subscription.state ] -%>\n<%= CSV.generate_line row %>\n<%- end -%>\n<%- end -%>\n <%= link_to \"Export Report\", formatted_advertiser_search_path(@advertiser_search, :csv) %>\n" }, { "answer_id": 11148546, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "def index\n respond_to do |format|\n format.csv { return index_csv }\n end\nend\n\ndef index_csv\n send_data(\n method_that_returns_csv_data(...),\n :type => 'text/csv',\n :filename => 'export.csv',\n :disposition => 'attachment'\n )\nend\n" }, { "answer_id": 17736685, "author": "boulder_ruby", "author_id": 1276506, "author_profile": "https://Stackoverflow.com/users/1276506", "pm_score": 0, "selected": false, "text": "tags = [Model.column_names]\nrows = tags + Model.all.map(&:attributes).map(&:to_a).map { |m| m.inject([]) { |data, pair| data << pair.last } }\nFile.open(\"ss.csv\", \"w\") {|f| f.write(rows.inject([]) { |csv, row| csv << CSV.generate_line(row) }.join(\"\"))}\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4540/" ]
94,528
<p>In other words may one use <code>/&lt;tag[^&gt;]*&gt;.*?&lt;\/tag&gt;/</code> regex to match the <code>tag</code> html element which does not contain nested <code>tag</code> elements?</p> <p>For example (lt.html):</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;greater than sign in attribute value&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt;1&lt;/div&gt; &lt;div title="&gt;"&gt;2&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Regex:</p> <pre><code>$ perl -nE"say $1 if m~&lt;div[^&gt;]*&gt;(.*?)&lt;/div&gt;~" lt.html </code></pre> <p>And screen-scraper:</p> <pre><code>#!/usr/bin/env python import sys import BeautifulSoup soup = BeautifulSoup.BeautifulSoup(sys.stdin) for div in soup.findAll('div'): print div.string $ python lt.py &lt;lt.html </code></pre> <p>Both give the same output:</p> <pre><code>1 "&gt;2 </code></pre> <p>Expected output:</p> <pre><code>1 2 </code></pre> <p><a href="http://www.w3.org/TR/html5/syntax.html#attributes2" rel="noreferrer" title="html attribute syntax">w3c</a> says:</p> <blockquote> <p>Attribute values are a mixture of text and character references, except with the additional restriction that the text cannot contain an ambiguous ampersand.</p> </blockquote>
[ { "answer_id": 94544, "author": "Per Hornshøj-Schierbeck", "author_id": 11619, "author_profile": "https://Stackoverflow.com/users/11619", "pm_score": 0, "selected": false, "text": "yeah except /<tag[^>]*>.*?<\\/tag>/\n" }, { "answer_id": 94559, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 2, "selected": false, "text": "]]>" }, { "answer_id": 94721, "author": "kch", "author_id": 13989, "author_profile": "https://Stackoverflow.com/users/13989", "pm_score": 2, "selected": false, "text": ">" }, { "answer_id": 131131, "author": "Troels Thomsen", "author_id": 20138, "author_profile": "https://Stackoverflow.com/users/20138", "pm_score": 2, "selected": false, "text": "<tag((\\s+\\w+(\\s*=\\s*(?:\".*?\"|'.*?'|[^'\">\\s]+))?)+\\s*|\\s*)>.*?<\\/tag>" }, { "answer_id": 217136, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 5, "selected": true, "text": "< >" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4279/" ]
94,542
<p>I have a handful of projects that all use one project for the data model. Each of these projects has its own applicationContext.xml file with a bunch of repetitive data stuff within it.</p> <p>I'd like to have a modelContext.xml file and another for my ui.xml, etc.</p> <p>Can I do this?</p>
[ { "answer_id": 94586, "author": "enricopulatzo", "author_id": 9883, "author_profile": "https://Stackoverflow.com/users/9883", "pm_score": 2, "selected": false, "text": "<import resource=\"services.xml\"/>\n" }, { "answer_id": 94588, "author": "Nicholas Trandem", "author_id": 765, "author_profile": "https://Stackoverflow.com/users/765", "pm_score": 5, "selected": true, "text": "<import resource=\"services.xml\"/>\n<import resource=\"resources/messageSource.xml\"/>\n<import resource=\"/resources/themeSource.xml\"/>\n\n<bean id=\"bean1\" class=\"...\"/>\n<bean id=\"bean2\" class=\"...\"/>\n" }, { "answer_id": 94788, "author": "Asgeir S. Nilsen", "author_id": 16023, "author_profile": "https://Stackoverflow.com/users/16023", "pm_score": 2, "selected": false, "text": "classpath*:springconfig/spring-appname-*.xml\n" }, { "answer_id": 95020, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 2, "selected": false, "text": "GenericApplicationContext ctx = new GenericApplicationContext();\nXmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);\nxmlReader.loadBeanDefinitions(new ClassPathResource(\"modelContext.xml\"));\nxmlReader.loadBeanDefinitions(new ClassPathResource(\"uiContext.xml\"));\nctx.refresh();\n" }, { "answer_id": 96039, "author": "Michael", "author_id": 13379, "author_profile": "https://Stackoverflow.com/users/13379", "pm_score": 1, "selected": false, "text": "web.xml <context-param>\n <param-name>contextConfigLocation</param-name>\n <param-value>\n /WEB-INF/applicationContext.xml\n /WEB-INF/modelContext.xml\n /WEB-INF/ui.xml\n </param-value>\n </context-param>\n web.xml /WEB-INF/applicationContext.xml" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
94,556
<p>We've got a multiproject we're trying to run Cobertura test coverage reports on as part of our mvn site build. I can get Cobertura to run on the child projects, but it erroneously reports 0% coverage, even though the reports still highlight the lines of code that were hit by the unit tests. </p> <p>We are using mvn 2.0.8. I have tried running <code>mvn clean site</code>, <code>mvn clean site:stage</code> and <code>mvn clean package site</code>. I know the tests are running, they show up in the surefire reports (both the txt/xml and site reports). Am I missing something in the configuration? Does Cobertura not work right with multiprojects?</p> <p>This is in the parent .pom:</p> <pre><code>&lt;build&gt; &lt;pluginManagement&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt; &lt;artifactId&gt;cobertura-maven-plugin&lt;/artifactId&gt; &lt;inherited&gt;true&lt;/inherited&gt; &lt;executions&gt; &lt;execution&gt; &lt;id&gt;clean&lt;/id&gt; &lt;goals&gt; &lt;goal&gt;clean&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/pluginManagement&gt; &lt;/build&gt; &lt;reporting&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt; &lt;artifactId&gt;cobertura-maven-plugin&lt;/artifactId&gt; &lt;inherited&gt;true&lt;/inherited&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/reporting&gt; </code></pre> <p>I've tried running it with and without the following in the child .poms:</p> <pre><code> &lt;reporting&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt; &lt;artifactId&gt;cobertura-maven-plugin&lt;/artifactId&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/reporting&gt; </code></pre> <p>I get this in the output of the build:</p> <pre><code>... [INFO] [cobertura:instrument] [INFO] Cobertura 1.9 - GNU GPL License (NO WARRANTY) - See COPYRIGHT file Instrumenting 3 files to C:\workspaces\sandbox\CommonJsf\target\generated-classes\cobertura Cobertura: Saved information on 3 classes. Instrument time: 186ms [INFO] Instrumentation was successful. ... [INFO] Generating "Cobertura Test Coverage" report. [INFO] Cobertura 1.9 - GNU GPL License (NO WARRANTY) - See COPYRIGHT file Cobertura: Loaded information on 3 classes. Report time: 481ms [INFO] Cobertura Report generation was successful. </code></pre> <p>And the report looks like this: <img src="https://i.stack.imgur.com/D7yiM.png" alt="cobertura report"></p>
[ { "answer_id": 94586, "author": "enricopulatzo", "author_id": 9883, "author_profile": "https://Stackoverflow.com/users/9883", "pm_score": 2, "selected": false, "text": "<import resource=\"services.xml\"/>\n" }, { "answer_id": 94588, "author": "Nicholas Trandem", "author_id": 765, "author_profile": "https://Stackoverflow.com/users/765", "pm_score": 5, "selected": true, "text": "<import resource=\"services.xml\"/>\n<import resource=\"resources/messageSource.xml\"/>\n<import resource=\"/resources/themeSource.xml\"/>\n\n<bean id=\"bean1\" class=\"...\"/>\n<bean id=\"bean2\" class=\"...\"/>\n" }, { "answer_id": 94788, "author": "Asgeir S. Nilsen", "author_id": 16023, "author_profile": "https://Stackoverflow.com/users/16023", "pm_score": 2, "selected": false, "text": "classpath*:springconfig/spring-appname-*.xml\n" }, { "answer_id": 95020, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 2, "selected": false, "text": "GenericApplicationContext ctx = new GenericApplicationContext();\nXmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);\nxmlReader.loadBeanDefinitions(new ClassPathResource(\"modelContext.xml\"));\nxmlReader.loadBeanDefinitions(new ClassPathResource(\"uiContext.xml\"));\nctx.refresh();\n" }, { "answer_id": 96039, "author": "Michael", "author_id": 13379, "author_profile": "https://Stackoverflow.com/users/13379", "pm_score": 1, "selected": false, "text": "web.xml <context-param>\n <param-name>contextConfigLocation</param-name>\n <param-value>\n /WEB-INF/applicationContext.xml\n /WEB-INF/modelContext.xml\n /WEB-INF/ui.xml\n </param-value>\n </context-param>\n web.xml /WEB-INF/applicationContext.xml" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/765/" ]
94,582
<p>Say I have some javascript that if run in a browser would be typed like this...</p> <pre><code>&lt;script type="text/javascript" src="http://someplace.net/stuff.ashx"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; var stuff = null; stuff = new TheStuff('myStuff'); &lt;/script&gt; </code></pre> <p>... and I want to use the javax.script package in java 1.6 to run this code within a jvm (not within an applet) and get the stuff. How do I let the engine know the source of the classes to be constructed is found within the remote .ashx file?</p> <p>For instance, I know to write the java code as...</p> <pre><code>ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName("JavaScript"); engine.eval( "stuff = new TheStuff('myStuff');" ); Object obj = engine.get("stuff"); </code></pre> <p>...but the "JavaScript" engine doesn't know anything by default about the TheStuff class because that information is in the remote .ashx file. Can I make it look to the above src string for this?</p>
[ { "answer_id": 96911, "author": "Stephen Deken", "author_id": 7154, "author_profile": "https://Stackoverflow.com/users/7154", "pm_score": 2, "selected": false, "text": "ScriptEngine ScriptEngine ScriptEngine Reader URL url = new URL( \"http://someplace.net/stuff.ashx\" );\nInputStreamReader reader = new InputStreamReader( url.openStream() );\nengine.eval( reader );\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17978/" ]
94,591
<p>I can never remember the number. I need a memory rule.</p>
[ { "answer_id": 94645, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 4, "selected": false, "text": "Console.WriteLine(Int32.MaxValue);\n" }, { "answer_id": 94646, "author": "Adrian Clark", "author_id": 148, "author_profile": "https://Stackoverflow.com/users/148", "pm_score": 9, "selected": false, "text": "Int32.MaxValue" }, { "answer_id": 94889, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 6, "selected": false, "text": "2^(x+y) = 2^x * 2^y\n\n2^10 ~ 1,000\n2^20 ~ 1,000,000\n2^30 ~ 1,000,000,000\n2^40 ~ 1,000,000,000,000\n(etc.)\n\n2^1 = 2\n2^2 = 4\n2^3 = 8\n2^4 = 16\n2^5 = 32\n2^6 = 64\n2^7 = 128\n2^8 = 256\n2^9 = 512\n" }, { "answer_id": 95001, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 3, "selected": false, "text": "2^10 = 1024 ~= one thousand\n2^20 = 1024^2 = 1048576 ~= one million\n2^30 = 1024^3 = 1073741824 ~= one billion\n" }, { "answer_id": 95114, "author": "Michael Easter", "author_id": 12704, "author_profile": "https://Stackoverflow.com/users/12704", "pm_score": 2, "selected": false, "text": "groovy -e \" println Integer.MAX_VALUE \"\n" }, { "answer_id": 606061, "author": "Seq", "author_id": 67248, "author_profile": "https://Stackoverflow.com/users/67248", "pm_score": 4, "selected": false, "text": "std::numeric_limits< int >::max() // numeric_limits_max.cpp\n\n#include <iostream>\n#include <limits>\n\nusing namespace std;\n\nint main() {\n cout << \"The maximum value for type float is: \"\n << numeric_limits<float>::max( )\n << endl;\n cout << \"The maximum value for type double is: \"\n << numeric_limits<double>::max( )\n << endl;\n cout << \"The maximum value for type int is: \"\n << numeric_limits<int>::max( )\n << endl;\n cout << \"The maximum value for type short int is: \"\n << numeric_limits<short int>::max( )\n << endl;\n}\n" }, { "answer_id": 2951618, "author": "Chizh", "author_id": 225389, "author_profile": "https://Stackoverflow.com/users/225389", "pm_score": 6, "selected": false, "text": "[0-9]{1,9}|[0-1][0-9]{1,8}|20[0-9]{1,8}|21[0-3][0-9]{1,7}|214[0-6][0-9]{1,7}|2147[0-3][0-9]{1,6}|21474[0-7][0-9]{1,5}|214748[0-2][0-9]{1,4}|2147483[0-5][0-9]{1,3}|21474836[0-3][0-9]{1,2}|214748364[0-7]" }, { "answer_id": 2951657, "author": "NotMe", "author_id": 2424, "author_profile": "https://Stackoverflow.com/users/2424", "pm_score": 4, "selected": false, "text": "Int3<period>M<enter>" }, { "answer_id": 6612973, "author": "panzi", "author_id": 277767, "author_profile": "https://Stackoverflow.com/users/277767", "pm_score": 1, "selected": false, "text": "0x f 0xffffffff 0x7fffffff 0x100000000 - 1 0x80000000 - 1" }, { "answer_id": 8331281, "author": "Sean Vikoren", "author_id": 959448, "author_profile": "https://Stackoverflow.com/users/959448", "pm_score": 2, "selected": false, "text": "0xFFFFFFFF >> 1 # => 2147483647\n" }, { "answer_id": 11057486, "author": "Aaren Cordova", "author_id": 1459680, "author_profile": "https://Stackoverflow.com/users/1459680", "pm_score": 7, "selected": false, "text": "drunk ========= Drinking age is 21\nAK ============ AK 47\nA ============= 4 (A and 4 look the same)\nhorny ========= internet rule 34 (if it exists, there's 18+ material of it) \n\n21 47 4(years) 3(years) 4(years)\n21 47 48 36 48\n" }, { "answer_id": 12427919, "author": "Joe Plante", "author_id": 1524209, "author_profile": "https://Stackoverflow.com/users/1524209", "pm_score": 4, "selected": false, "text": "8-bit 0xFF\n16-bit 0xFFFF\n32-bit 0xFFFFFFFF\n64-bit 0xFFFFFFFFFFFFFFFF\n128-bit 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\n 8-bit 0x7F\n16-bit 0x7FFF\n32-bit 0x7FFFFFFF\n64-bit 0x7FFFFFFFFFFFFFFF\n 8-bit 0x80\n16-bit 0x8000\n32-bit 0x80000000\n64-bit 0x8000000000000000\n F hex to binary: 1111\n8 hex to binary: 1000\n7 hex to binary: 0111\n0 hex to binary: 0000\n" }, { "answer_id": 13591146, "author": "Martin Thoma", "author_id": 562769, "author_profile": "https://Stackoverflow.com/users/562769", "pm_score": 5, "selected": false, "text": "2.1 * 10^9 2^{31} - 1 = 2,147,483,647 #include <stdio.h>\n#include <limits.h>\n\nmain() {\n printf(\"max int:\\t\\t%i\\n\", INT_MAX);\n printf(\"max unsigned int:\\t%u\\n\", UINT_MAX);\n}\n , max int: 2,147,483,647\nmax unsigned int: 4,294,967,295\n std::cout << std::numeric_limits<int>::max() << \"\\n\";\nstd::cout << std::numeric_limits<unsigned int>::max() << \"\\n\";\n System.out.println(Integer.MAX_VALUE);\n import sys\nsys.maxint\n>>> 2147483647\nsys.maxint + 1\n>>> 2147483648L\n long 2^31 -1" }, { "answer_id": 16448744, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 5, "selected": false, "text": "Boys And Dogs Go Duck Hunting, Come Friday Ducks Hide\n2 1 4 7 4 8 3 6 4 8\n" }, { "answer_id": 17487532, "author": "Mikołaj Rozwadowski", "author_id": 1692777, "author_profile": "https://Stackoverflow.com/users/1692777", "pm_score": 6, "selected": false, "text": "2147483647 214_48_64_\nand insert:\n ^ ^ ^\n 7 3 7 - which is Boeing's airliner jet (thanks, sgorozco)\n" }, { "answer_id": 20374349, "author": "Aerospace", "author_id": 1770831, "author_profile": "https://Stackoverflow.com/users/1770831", "pm_score": 5, "selected": false, "text": "2^31 - 1 = 2147483647\n Rank 1 2 3 4 5 6 ... 2147483648\nNumber 0 1 2 3 4 5 ... 2147483647\n 2^2 - 1 = 3\n 1: 100 ==> -4\n2: 101 ==> -3\n3: 110 ==> -2\n4: 111 ==> -1\n5: 000 ==> 0\n6: 001 ==> 1\n7: 010 ==> 2\n8: 011 ==> 3\n" }, { "answer_id": 20374628, "author": "juniperi", "author_id": 2497102, "author_profile": "https://Stackoverflow.com/users/2497102", "pm_score": 3, "selected": false, "text": "#define INT8_MAX 127\n#define INT16_MAX 32767\n#define INT32_MAX 2147483647\n#define INT64_MAX 9223372036854775807LL\n\n#define UINT8_MAX 255\n#define UINT16_MAX 65535\n#define UINT32_MAX 4294967295U\n#define UINT64_MAX 18446744073709551615ULL\n" }, { "answer_id": 25678134, "author": "Mark Hurd", "author_id": 256431, "author_profile": "https://Stackoverflow.com/users/256431", "pm_score": 4, "selected": false, "text": "MaxInt !GH6G = 21 47 48 36 47" }, { "answer_id": 29240910, "author": "Sнаđошƒаӽ", "author_id": 3375713, "author_profile": "https://Stackoverflow.com/users/3375713", "pm_score": 4, "selected": false, "text": "--47----47\n 12 4 47 12 * 4 = 48\n--4748--47 <-- after placing 48 to the right of first 47\n 12 3 7 7 - 4 = 3 12 * 3 = 36\n--47483647 <-- after placing 36 to the right of first two pairs\n 2-47483647 <-- after placing 2\n2147483647 <-- after placing 1\n" }, { "answer_id": 31823937, "author": "Samuel", "author_id": 398715, "author_profile": "https://Stackoverflow.com/users/398715", "pm_score": 3, "selected": false, "text": "2 - To\n1 - A\n4 - Far\n7 - Savannah\n4 - Quarter\n8 - Optimus\n3 - Trio\n6 - Hexed\n4 - Forty\n7 - Septenary\n" }, { "answer_id": 38043722, "author": "lllllllllll", "author_id": 6411310, "author_profile": "https://Stackoverflow.com/users/6411310", "pm_score": -1, "selected": false, "text": "max_signed_32_bit_num = 1 << 31 - 1; // alternatively ~(1 << 31)\n 1 << 31 - 1 0x7fffffff f unsigned( pow( 2, 31 ) ) - 1 <math.h>" }, { "answer_id": 40265552, "author": "saolof", "author_id": 6425831, "author_profile": "https://Stackoverflow.com/users/6425831", "pm_score": -1, "selected": false, "text": "2*2 = 4\n4*4 = 16\n16*16 = 256\n256*256 = 25*25*100 + 2*250*6 + 36 = 62500 + 3000 + 36 = 65536\n65536*65536 =65000*65000 + 2*65000*536 + 536*536 = \n4225000000 + 130000*536 + (250000 + 3600 + 36*36) =\n4225000000 + 69680000 + 250000 + 3600 + 1296 =\n4294967296\n" }, { "answer_id": 42078338, "author": "Reed Hedges", "author_id": 39686, "author_profile": "https://Stackoverflow.com/users/39686", "pm_score": 0, "selected": false, "text": "INT32_MAX #include <stdint.h> INT32_MAX #include <cstdint> INT_MAX UINT32_MAX UINT_MAX unsigned int sizeof(int)" }, { "answer_id": 43330055, "author": "Michael Easter", "author_id": 12704, "author_profile": "https://Stackoverflow.com/users/12704", "pm_score": 1, "selected": false, "text": "$ jshell\n| Welcome to JShell -- Version 9-Debian\n\njshell> System.out.println(Integer.MAX_VALUE)\n2147483647\n" }, { "answer_id": 45380528, "author": "wiesion", "author_id": 3820185, "author_profile": "https://Stackoverflow.com/users/3820185", "pm_score": 0, "selected": false, "text": "max = 0\nbits = [1] * 31 # Generate a \"bit array\" filled with 1's\nfor bit in bits:\n max = (max << 1) | bit\n# max is now 2147483647\n a = 4\nb = 8\nab = int('%d%d' % (a, b))\nba = int('%d%d' % (b, a))\n'%d%d%d%d%d' % (ba/a, ab-1, ab, ab-a-b, ab-1)\n# gives '2147483647'\n x = 48\n'%d%d%d%d%d' % (x/2-3, x-1, x, x*3/4, x-1) \n# gives '2147483647'\n" }, { "answer_id": 51182653, "author": "g10guang", "author_id": 7159205, "author_profile": "https://Stackoverflow.com/users/7159205", "pm_score": 1, "selected": false, "text": ">>> int('1' * 31, base=2)\n2147483647\n" }, { "answer_id": 53328806, "author": "yazanpro", "author_id": 465495, "author_profile": "https://Stackoverflow.com/users/465495", "pm_score": 2, "selected": false, "text": "public static int GetIntMaxValueGenius1()\n{\n int n = 0;\n while (++n > 0) { }\n return --n;\n}\n\npublic static int GetIntMaxValueGenius2()\n{\n int n = 0;\n try\n {\n while (true)\n n = checked(n + 1);\n }\n catch { }\n return n;\n}\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15054/" ]
94,592
<p>Sometimes it might be useful, but mostly just looking cool or impressive to visualize log files (anything from http requests and to bandwith usage to cups of coffee drunk per day). I know about <a href="http://www.visitorville.com/" rel="noreferrer">Visitorville</a> which I think look a bit silly, and then there's <a href="http://www.fudgie.org/" rel="noreferrer">gltail</a>. </p> <p>How do you "visualize" your log files in realtime?</p>
[ { "answer_id": 16763271, "author": "sdaau", "author_id": 277826, "author_profile": "https://Stackoverflow.com/users/277826", "pm_score": 2, "selected": false, "text": "matplotlib stdin" }, { "answer_id": 17211281, "author": "Lloyd", "author_id": 1029644, "author_profile": "https://Stackoverflow.com/users/1029644", "pm_score": 1, "selected": false, "text": "$ ws --log-format default | logstalgia -\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17542/" ]
94,594
<p>I'm implementing a simple service using datagrams over unix local sockets (AF_UNIX address family, i.e. <strong>not UDP</strong>). The server is bound to a public address, and it receives requests just fine. Unfortunately, when it comes to answering back, <code>sendto</code> fails unless the client is bound too. (the common error is <code>Transport endpoint is not connected</code>).</p> <p>Binding to some random name (filesystem-based or abstract) works. But I'd like to avoid that: who am I to guarantee the names I picked won't collide?</p> <p>The unix sockets' stream mode documentation tell us that an abstract name will be assigned to them at <code>connect</code> time if they don't have one already. Is such a feature available for datagram oriented sockets?</p>
[ { "answer_id": 95090, "author": "Nick Stinemates", "author_id": 4960, "author_profile": "https://Stackoverflow.com/users/4960", "pm_score": -1, "selected": false, "text": "from socket import *\nimport time\nclass Listener:\n def __init__(self, port):\n self.port = port\n self.buffer = 102400\n\n def listen(self):\n\n sock = socket(AF_INET, SOCK_DGRAM)\n sock.bind(('', self.port))\n\n while 1:\n data, addr = sock.recvfrom(self.buffer)\n print \"Received: \" + data\n print \"sending to %s\" % addr[0]\n print \"sending data %s\" % data\n time.sleep(0.25)\n #print addr # will tell you what IP address the request came from and port\n sock.sendto(data, (addr[0], addr[1]))\n print \"sent\"\n sock.close()\n\nif __name__ == \"__main__\":\n l = Listener(1975)\n l.listen()\n from socket import *\nfrom time import sleep\nclass Sender:\n def __init__(self, server):\n self.port = 1975\n self.server = server\n self.buffer = 102400\n\n def sendPacket(self, packet):\n sock = socket(AF_INET, SOCK_DGRAM)\n sock.settimeout(10.75)\n\n\n sock.sendto(packet, (self.server, int(self.port)))\n\n while 1:\n print \"waiting for response\"\n data, addr = sock.recvfrom(self.buffer)\n sock.close()\n return data\n\n\n\nif __name__ == \"__main__\":\n s = Sender(\"127.0.0.1\")\n response = s.sendPacket(\"Hello, world!\")\n print response\n" }, { "answer_id": 107358, "author": "Robᵩ", "author_id": 8747, "author_profile": "https://Stackoverflow.com/users/8747", "pm_score": 3, "selected": true, "text": "struct sockaddr_un me;\nme.sun_family = AF_UNIX;\nint result = bind(fd, (void*)&me, sizeof(short));\n" }, { "answer_id": 1284208, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "SO_SOCKET man 7 unix SO_PASSCRED SO_PASSCRED" }, { "answer_id": 8523777, "author": "CapnBry", "author_id": 1100177, "author_profile": "https://Stackoverflow.com/users/1100177", "pm_score": 3, "selected": false, "text": "struct sockaddr_un me;\nconst char name[] = \"\\0myabstractsocket\";\nme.sun_family = AF_UNIX;\n// size-1 because abstract socket names are not null terminated\nmemcpy(me.sun_path, name, sizeof(name) - 1);\nint result = bind(fd, (void*)&me, sizeof(me.sun_family) + sizeof(name) - 1);\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12274/" ]
94,610
<p>I have a Silverlight 2 application that is consuming a WCF service. As such, it uses asynchronous callbacks for all the calls to the methods of the service. If the service is not running, or it crashes, or the network goes down, etc before or during one of these calls, an exception is generated as you would expect. The problem is, I don't know how to catch this exception.</p> <ul> <li><p>Because it is an asynchronous call, I can't wrap my begin call with a try/catch block and have it pick up an exception that happens after the program has moved on from that point.</p></li> <li><p>Because the service proxy is automatically generated, I can't put a try/catch block on each and every generated function that calls EndInvoke (where the exception actually shows up). These generated functions are also surrounded by External Code in the call stack, so there's nowhere else in the stack to put a try/catch either.</p></li> <li><p>I can't put the try/catch in my callback functions, because the exception occurs before they would get called.</p></li> <li><p>There is an Application_UnhandledException function in my App.xaml.cs, which captures all unhandled exceptions. I could use this, but it seems like a messy way to do it. I'd rather reserve this function for the truly unexpected errors (aka bugs) and not end up with code in this function for every circumstance I'd like to deal with in a specific way.</p></li> </ul> <p>Am I missing an obvious solution? Or am I stuck using Application_UnhandledException?</p> <p>[Edit]<br> As mentioned below, the Error property is exactly what I was looking for. What is throwing me for a loop is that the fact that the exception is thrown and appears to be uncaught, yet execution is able to continue. It triggers the Application_UnhandledException event and causes VS2008 to break execution, but continuing in the debugger allows execution to continue. It's not really a problem, it just seems odd.</p>
[ { "answer_id": 636512, "author": "Braulio", "author_id": 76922, "author_profile": "https://Stackoverflow.com/users/76922", "pm_score": 0, "selected": false, "text": "Braulio\n" }, { "answer_id": 637612, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "- In development even detaching from the debugger, this method is never reached. \n- On the production environment yes.\n" }, { "answer_id": 960273, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "public class myWCFService : MyWCFServiceClient\n{\n\n protected override MyController.MyService.IMyWCFService CreateChannel()\n {\n return new MyWCFServiceClientChannel(this);\n }\n\n}\n\nprivate class MyWCFServiceClientChannel : ChannelBase<MyController.MyService.IMyWCFService>, MyController.MyService.IMyWCFService\n{\n /// <summary>\n /// Channel Constructor\n /// </summary>\n /// <param name=\"client\"></param>\n public MyWCFServiceClientChannel(System.ServiceModel.ClientBase<MyController.MyService.IMyWCFService> client) :\n base(client)\n {\n }\n /// <summary>\n /// Begin Call To RegisterUser\n /// </summary>\n /// <param name=\"memberInformation\"></param>\n /// <param name=\"callback\"></param>\n /// <param name=\"asyncState\"></param>\n /// <returns></returns>\n public System.IAsyncResult BeginRegisterUser(MyDataEntities.MembershipInformation memberInformation, System.AsyncCallback callback, object asyncState)\n { \n object[] _args = new object[1];\n _args[0] = memberInformation;\n System.IAsyncResult _result = base.BeginInvoke(\"RegisterUser\", _args, callback, asyncState);\n return _result; \n }\n /// <summary>\n /// Result from RegisterUser\n /// </summary>\n /// <param name=\"result\"></param>\n /// <returns></returns>\n public MyDataEntities.MembershipInformation EndRegisterUser(System.IAsyncResult result)\n {\n try\n {\n object[] _args = new object[0];\n MyDataEntities.MembershipInformation _result = ((MyDataEntities.MembershipInformation)(base.EndInvoke(\"RegisterUser\", _args, result)));\n return _result;\n }\n catch (Exception ex)\n {\n MyDataEntities.MembershipInformation _result = new MyDataEntities.MembershipInformation();\n _result.ValidationInformation.HasErrors = true;\n _result.ValidationInformation.Message = ex.Message;\n return _result;\n }\n }\n}\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17986/" ]
94,612
<p>To elaborate .. a) A table (BIGTABLE) has a capacity to hold a million rows with a primary Key as the ID. (random and unique) b) What algorithm can be used to arrive at an ID that has not been used so far. This number will be used to insert another row into table BIGTABLE.</p> <p>Updated the question with more details.. C) This table already has about 100 K rows and the primary key is not an set as identity. d) Currently, a random number is generated as the primary key and a row inserted into this table, if the insert fails another random number is generated. the problem is sometimes it goes into a loop and the random numbers generated are pretty random, but unfortunately, They already exist in the table. so if we re try the random number generation number after some time it works. e) The sybase rand() function is used to generate the random number.</p> <p>Hope this addition to the question helps clarify some points.</p>
[ { "answer_id": 94666, "author": "John Meagher", "author_id": 3535, "author_profile": "https://Stackoverflow.com/users/3535", "pm_score": 2, "selected": false, "text": "int id;\ndo {\n id = generateRandomId();\n} while (doesIdAlreadyExist(id));\ndoSomethingWithNewId(id); \n" }, { "answer_id": 95065, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 3, "selected": false, "text": "CREATE FUNCTION lift(integer, integer) returns bigint AS $$\nSELECT ($1::bigint << 31) + $2\n$$ LANGUAGE SQL;\n\nCREATE FUNCTION random_pos_int() RETURNS integer AS $$\nselect floor((lift(1,0) - 1)*random())::integer\n$$ LANGUAGE sql;\n\nALTER TABLE client ALTER COLUMN id SET DEFAULT\nlift((nextval('client_id_seq'::regclass))::integer, random_pos_int());\n select lift(1, random_pos_int()); => 3108167398\nselect lift(2, random_pos_int()); => 4673906795\nselect lift(3, random_pos_int()); => 7414644984\n...\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17987/" ]
94,667
<p>How can I bind an array parameter in the HQL editor of the HibernateTools plugin? The query parameter type list does not include arrays or collections.</p> <p>For example:<br> <code>Select * from Foo f where f.a in (:listOfValues)</code>.<br> How can I bind an array to that listOfValues?</p>
[ { "answer_id": 119294, "author": "boutta", "author_id": 15108, "author_profile": "https://Stackoverflow.com/users/15108", "pm_score": 1, "selected": false, "text": "select * from Foo f where f.a in f.list\n" }, { "answer_id": 6833770, "author": "Shaun Stone", "author_id": 290095, "author_profile": "https://Stackoverflow.com/users/290095", "pm_score": 0, "selected": false, "text": "Select * from Foo f where f.a in (123,1234)\n" }, { "answer_id": 7279391, "author": "Ravi Shankar", "author_id": 575055, "author_profile": "https://Stackoverflow.com/users/575055", "pm_score": 0, "selected": false, "text": "select * from Foo f where f.a in (:foolist)\n\nquery.SetParameterList(\"foolist\", list)\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12905/" ]
94,674
<p>How come this doesn't work (operating on an empty select list <code>&lt;select id="requestTypes"&gt;&lt;/select&gt;</code></p> <pre><code>$(function() { $.getJSON("/RequestX/GetRequestTypes/", showRequestTypes); } ); function showRequestTypes(data, textStatus) { $.each(data, function() { var option = new Option(this.RequestTypeName, this.RequestTypeID); // Use Jquery to get select list element var dropdownList = $("#requestTypes"); if ($.browser.msie) { dropdownList.add(option); } else { dropdownList.add(option, null); } } ); } </code></pre> <p>But this does:</p> <ul> <li><p>Replace:</p> <p><code>var dropdownList = $("#requestTypes");</code></p></li> <li><p>With plain old javascript:</p> <p><code>var dropdownList = document.getElementById("requestTypes");</code></p></li> </ul>
[ { "answer_id": 94686, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 3, "selected": false, "text": " var dropdownList = $(\"#requestTypes\")[0];\n" }, { "answer_id": 94716, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 5, "selected": true, "text": "$(\"#requestTypes\") add() add() $(\"#requestTypes\")[0]" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17729/" ]
94,684
<p>We are trying to integrate tests in our daily builds using TestComplete, so far we have a machine dedicated for testing and our build script copies to this machine everything TestComplete needs for its tests (Application, Database, Test script project and source files, etc).</p> <p>Basically we can open the TestComplete project manually and run the tests.</p> <p>Now we want to automate that process, so how do you do it? Or how do you think would be the simplest and best way to make this automation?</p> <p>Keeping it short, we want to automate the process of opening TestComplete after each build, run all the tests and send an email with the test results.</p> <p>Anyone can share some experience about this?</p> <p>Thanks.</p>
[ { "answer_id": 258000, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "Set wshShell = CreateObject(\"WScript.Shell\")\nwshShell.Run(\"\"\"C:\\Program Files\\Automated QA\\TestComplete 6\\Bin\\TestComplete.exe\"\" \"\"C:\\Documents and Settings\\My Documents\\TestComplete 6 Projects\\abc\\abc.pjs(your script path)\"\" /r /p:(Project Name) /u:(Unit Name) /rt:(Method to be executed) /e /SilentMode\")\n C:\\WINDOWS\\system32\\cmd.exe\nWScript.Echo \"\"\nSet wshShell = CreateObject(\"WScript.Shell\")\nwshShell.Run(\"\"\"C:\\Program Files\\Automated QA\\TestComplete 6\\Bin\\TestComplete.exe\"\" \"\"C:\\Documents and Settings\\My Documents\\TestComplete 6 Projects\\abc\\abc.pjs\"\" /r /p:prj1 /u:Unit1 /rt:Test1 /e\") \n" }, { "answer_id": 853351, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "C:\\PROGRA~1\\AUTOMA~1\\TESTEX~1\\Bin\\TestExecute.exe \"path\\Project.pjs\" /r /e\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/727/" ]
94,689
<p>I am new to asp and have a deadline in the next few days. i receive the following xml from within a webservice response.</p> <pre><code>print("&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;user_data&gt; &lt;execution_status&gt;0&lt;/execution_status&gt; &lt;row_count&gt;1&lt;/row_count&gt; &lt;txn_id&gt;stuetd678&lt;/txn_id&gt; &lt;person_info&gt; &lt;attribute name="firstname"&gt;john&lt;/attribute&gt; &lt;attribute name="lastname"&gt;doe&lt;/attribute&gt; &lt;attribute name="emailaddress"&gt;john.doe@johnmail.com&lt;/attribute&gt; &lt;/person_info&gt; &lt;/user_data&gt;"); </code></pre> <p>How can i parse this xml into asp attributes?</p> <p>Any help is greatly appreciated</p> <p>Thanks Damien</p> <p>On more analysis, some soap stuff is also returned as the aboce response is from a web service call. can i still use lukes code below?</p>
[ { "answer_id": 94712, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 4, "selected": true, "text": "Dim oXML, oNode, sKey, sValue\n\nSet oXML = Server.CreateObject(\"MSXML2.DomDocument.6.0\") 'creating the parser object\noXML.LoadXML(sXML) 'loading the XML from the string\n\nFor Each oNode In oXML.SelectNodes(\"/user_data/person_info/attribute\")\n sKey = oNode.GetAttribute(\"name\")\n sValue = oNode.Text\n Select Case sKey\n Case \"execution_status\"\n ... 'do something with the tag value\n Case else\n ... 'unknown tag\n End Select\nNext\n\nSet oXML = Nothing\n" }, { "answer_id": 94751, "author": "Luke Bennett", "author_id": 17602, "author_profile": "https://Stackoverflow.com/users/17602", "pm_score": 3, "selected": false, "text": "Dim oXML, oNode, sKey, sValue\n\nSet oXML = Server.CreateObject(\"MSXML2.DomDocument.4.0\")\noXML.LoadXML(sXML)\n\nFor Each oNode In oXML.SelectNodes(\"/user_data/person_info/attribute\")\n sKey = oNode.GetAttribute(\"name\")\n sValue = oNode.Text\n ' Do something with these values here\nNext\n\nSet oXML = Nothing\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11612/" ]
94,696
<p>I know it happens sometime before Load, but during what event exactly?</p>
[ { "answer_id": 21776865, "author": "Liam", "author_id": 542251, "author_profile": "https://Stackoverflow.com/users/542251", "pm_score": 3, "selected": false, "text": "LoadViewState" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9991/" ]
94,747
<p>What would be a good offline alternative of the online <a href="http://www.lipsum.com/feed/html" rel="noreferrer">Lipsum generator</a>? It's frustrating when I'm not online and need some placeholder text for testing purpose. A CLI utility would be ideal, so that I can tailor the output to fit my needs.</p>
[ { "answer_id": 94785, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 1, "selected": false, "text": "{% lorem %}" }, { "answer_id": 94798, "author": "shadit", "author_id": 9925, "author_profile": "https://Stackoverflow.com/users/9925", "pm_score": 4, "selected": false, "text": "=lorem(n)\n n" }, { "answer_id": 94842, "author": "hacama", "author_id": 17457, "author_profile": "https://Stackoverflow.com/users/17457", "pm_score": 2, "selected": false, "text": "#!/usr/bin/env python\n\nimport sys\nimport random\n\ntry:\n n = int(sys.argv[1])\nexcept:\n print 'Usage: %s num-words' % sys.argv[0]\n\nwords = open('/usr/share/dict/words').readlines()\nfor i in range(n):\n print words[random.randrange(0, len(words))][:-1],\n" }, { "answer_id": 94868, "author": "artificialidiot", "author_id": 7988, "author_profile": "https://Stackoverflow.com/users/7988", "pm_score": 1, "selected": false, "text": "pdf2ps | ps2txt < yourarticlecollection/someresearchpaper.pdf\n" }, { "answer_id": 21615254, "author": "hurufu", "author_id": 3817947, "author_profile": "https://Stackoverflow.com/users/3817947", "pm_score": 1, "selected": false, "text": "Text::Lorem $> sudo apt-get install libtext-lorem-perl $> lorem" }, { "answer_id": 44748451, "author": "K. Shores", "author_id": 5217293, "author_profile": "https://Stackoverflow.com/users/5217293", "pm_score": 1, "selected": false, "text": "brew install lorem" }, { "answer_id": 70286372, "author": "Penny Liu", "author_id": 6904888, "author_profile": "https://Stackoverflow.com/users/6904888", "pm_score": 0, "selected": false, "text": "lorem10 p*3>lorem5" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1897/" ]
94,755
<p>What is the best way (in C++) to set up a container allowing for double-indexing? Specifically, I have a list of objects, each indexed by a key (possibly multiple per key). This implies a multimap. The problem with this, however, is that it means a possibly worse-than-linear lookup to find the location of an object. I'd rather avoid duplication of data, so having each object maintain it's own coordinate and have to move itself in the map would be bad (not to mention that moving your own object may indirectly call your destructor whilst in a member function!). I would rather some container that maintains an index both by object pointer and coordinate, and that the objects themselves guarantee stable references/pointers. Then each object could store an iterator to the index (including the coordinate), sufficiently abstracted, and know where it is. Boost.MultiIndex seems like the best idea, but it's very scary and I don't wany my actual objects to need to be const.</p> <p>What would you recommend?</p> <p>EDIT: Boost Bimap seems nice, but does it provide stable indexing? That is, if I change the coordinate, references to other elements must remain valid. The reason I want to use pointers for indexing is because objects have otherwise no intrinsic ordering, and a pointer can remain constant while the object changes (allowing its use in a Boost MultiIndex, which, IIRC, does provide stable indexing).</p>
[ { "answer_id": 94979, "author": "Commodore Jaeger", "author_id": 4659, "author_profile": "https://Stackoverflow.com/users/4659", "pm_score": 4, "selected": true, "text": "std::multimap<Key, Object *> std::map<Object *, Key> std::multimap Object Key" }, { "answer_id": 95251, "author": "Matt Price", "author_id": 852, "author_profile": "https://Stackoverflow.com/users/852", "pm_score": 2, "selected": false, "text": "template<typename T, typename K1, typename K2>\nclass MyBiMap\n{\npublic:\n typedef boost::shared_ptr<T> ptr_type;\n\n void insert(const ptr_type& value, const K1& key1, const K2& key2)\n {\n _map1.insert(std::make_pair(key1, value));\n _map2.insert(std::make_pair(key2, value));\n }\n\n ptr_type find1(const K1& key)\n {\n std::map<K1, ptr_type >::const_iterator itr = _map1.find(key);\n if (itr == _map1.end())\n throw std::exception(\"Unable to find key\");\n return itr->second;\n }\n\n ptr_type find2(const K2& key)\n {\n std::map<K2, ptr_type >::const_iterator itr = _map2.find(key);\n if (itr == _map2.end())\n throw std::exception(\"Unable to find key\");\n return itr->second;\n }\n\nprivate:\n std::map<K1, ptr_type > _map1;\n std::map<K2, ptr_type > _map2;\n};\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16855/" ]
94,757
<p>I have a web application where there are number of Ajax components which refresh themselves every so often inside a page (it's a dashboard of sorts).</p> <p>Now, I want to add functionality to the page so that when there is no Internet connectivity, the current content of the page doesn't change and a message appears on the page saying that the page is offline (currently, as these various gadgets on the page try to refresh themselves and find that there is no connectivity, their old data vanishes).</p> <p>So, what is the best way to go about this?</p>
[ { "answer_id": 94808, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 4, "selected": false, "text": "navigator.onLine\n if (navigator.onLine) {\n updatePage();\n} else {\n displayOfflineWarning();\n}\n" }, { "answer_id": 94901, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 2, "selected": false, "text": "navigator.onLine" }, { "answer_id": 98813, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 3, "selected": true, "text": "/**\n * Monitor AJAX requests for timeouts\n * Based on the script here: http://codejanitor.com/wp/2006/03/23/ajax-timeouts-with-prototype/\n *\n * Usage: If an AJAX call takes more than the designated amount of time to return, we call the onFailure\n * method (if it exists), passing an error code to the function.\n *\n */\n\nvar xhr = {\n errorCode: 'timeout',\n callInProgress: function (xmlhttp) {\n switch (xmlhttp.readyState) {\n case 1: case 2: case 3:\n return true;\n // Case 4 and 0\n default:\n return false;\n }\n }\n};\n\n// Register global responders that will occur on all AJAX requests\nAjax.Responders.register({\n onCreate: function (request) {\n request.timeoutId = window.setTimeout(function () {\n // If we have hit the timeout and the AJAX request is active, abort it and let the user know\n if (xhr.callInProgress(request.transport)) {\n var parameters = request.options.parameters;\n request.transport.abort();\n // Run the onFailure method if we set one up when creating the AJAX object\n if (request.options.onFailure) {\n request.options.onFailure(request.transport, xhr.errorCode, parameters);\n }\n }\n },\n // 10 seconds\n 10000);\n },\n onComplete: function (request) {\n // Clear the timeout, the request completed ok\n window.clearTimeout(request.timeoutId);\n }\n});\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380/" ]
94,767
<p>I'm attempting to debug my web application with FireFox3. However, when a JSON feed comes from my application, Firefox wants to open up the "application/json" in a new program. Is there a way to configure FireFox3 to handle JSON like regular text files and open up the JSON in the current tab?</p> <p>Thanks.</p>
[ { "answer_id": 815578, "author": "Tarnay Kálmán", "author_id": 55267, "author_profile": "https://Stackoverflow.com/users/55267", "pm_score": 4, "selected": false, "text": "\"application/json\" \"application/json\"" }, { "answer_id": 8889271, "author": "Robert I. Jr.", "author_id": 1153091, "author_profile": "https://Stackoverflow.com/users/1153091", "pm_score": 0, "selected": false, "text": "def show\n @object = Object.find(params[:id])\n respond_to do |format|\n format.html\n format.json { render json: @object }\n end\nend\n /object/1 # => renders as html\n/object/1?format=json # => renders as json\n/object/1.json # => also renders as json\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10333/" ]
94,779
<p>I am working on a client proposal and they will need to upgrade their network infrastructure to support hosting an ASP.NET application. Essentially, I need to estimate peak usage for a system with a known quantity of users (currently 250). A simple answer like "you'll need a dedicated T1 line" would probably suffice, but I'd like to have data to back it up.</p> <p><a href="https://stackoverflow.com/questions/54184/best-tool-to-monitor-network-connection-bandwidth#54245">Another question</a> referenced NetLimiter, which looks pretty slick for getting a sense of what's being used.</p> <p>My general thought is that I'll fire the web app up and use the system like I would anticipate it be used at the customer, really at a leisurely pace, over a certain time span, and then multiply the bandwidth usage by the number of users and divide by the time. </p> <p>This doesn't seem very scientific. It may be good enough for a proposal, but I'd like to see if there's a better way.</p> <p>I know there are load tools available for testing web application performance, but it seems like these would not accurately simulate peak user load for bandwidth testing purposes (too much at once).</p> <p>The platform is Windows/ASP.NET and the application is hosted within SharePoint (MOSS 2007).</p>
[ { "answer_id": 815578, "author": "Tarnay Kálmán", "author_id": 55267, "author_profile": "https://Stackoverflow.com/users/55267", "pm_score": 4, "selected": false, "text": "\"application/json\" \"application/json\"" }, { "answer_id": 8889271, "author": "Robert I. Jr.", "author_id": 1153091, "author_profile": "https://Stackoverflow.com/users/1153091", "pm_score": 0, "selected": false, "text": "def show\n @object = Object.find(params[:id])\n respond_to do |format|\n format.html\n format.json { render json: @object }\n end\nend\n /object/1 # => renders as html\n/object/1?format=json # => renders as json\n/object/1.json # => also renders as json\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7301/" ]
94,794
<p>Compared to </p> <ul> <li>Simple memory access</li> <li>Disk access</li> <li>Memory access on another computer(on the same network)</li> <li>Disk access on another computer(on the same network)</li> </ul> <p>in C++ on windows.</p>
[ { "answer_id": 2382542, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": " for (int i = 0; i < iMax; i++)\n {\n //gives about 5.94 seconds to do a billion loops, \n // or 0.594 for 100M, about 6 times faster than\n //the method call.\n }\n\n sw.Stop(); \n\n long iE = sw.ElapsedMilliseconds;\n\n Debug.WriteLine(\"elapsed time of main function (ms) is: \" + iE.ToString());\n\n Debug.WriteLine(\"stop2\");\n\n Class1 myClass1 = new Class1();\n Stopwatch sw2 = Stopwatch.StartNew();\n int dummyI;\n for (int ie = 0; ie < iMax; ie++)\n {\n dummyI = myClass1.Method1();\n }\n sw2.Stop(); \n\n long iE2 = sw2.ElapsedMilliseconds;\n\n Debug.WriteLine(\"elapsed time of helper class function (ms) is: \" + iE2.ToString());\n\n Debug.WriteLine(\"Hi3\");\n\n\n }\n}\n public Class1()\n {\n }\n\n public int Method1 ()\n {\n return 0;\n }\n}\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15054/" ]
94,809
<p>I want to log on to a server inside my program using Windows authentication of the current user logged in. I thought that perhaps I could use </p> <p>System.Security.Principal.WindowsIdentity.GetCurrent().Name</p> <p>but while that does give a name, I do not see how I can find out the password of the user to enter it.</p>
[ { "answer_id": 94839, "author": "Doug Moore", "author_id": 13179, "author_profile": "https://Stackoverflow.com/users/13179", "pm_score": 1, "selected": false, "text": " <system.web>\n <authentication mode=\"Windows\" />\n <identity impersonate=\"true\"/>\n </system>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
94,860
<p>I have searched the forum, and google for this topic. Most of the articles are talking about using JSON to call the controller/action on the server and do ajax effect on the result.</p> <p>I am trying to use some very basic JQuery features, like the JQuery UI/Tabs, and JQuery UI/Block for a dialog window. I cannot get these simple samples to work in my MVC project. Any ideas how I should modify these samples? I only need these basic feature now and I can go from here.</p> <p>Thanks!</p>
[ { "answer_id": 423576, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": " public static string Script(this HtmlHelper html, string path)\n {\n var filePath = VirtualPathUtility.ToAbsolute(path);\n return \"<script type=\\\"text/javascript\\\" src=\\\"\" + filePath + \"\\\"></script>\";\n }\n <head>...</head> <%=Html.Script(\"~/Scripts/jquery-1.2.6.js\")%>\n <script ... src=\"<%=Url.Foo(...)%>\"></script>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
94,884
<p>The system I work on here was written before .net 2.0 and didn't have the benefit of generics. It was eventually updated to 2.0, but none of the code was refactored due to time constraints. There are a number of places where the code uses ArraysLists etc. that store things as objects. </p> <p>From performance perspective, how important change the code to using generics? I know from a perfomance perspective, boxing and unboxing etc., it is inefficient, but how much of a performance gain will there really be from changing it? Are generics something to use on a go forward basis, or it there enough of a performance change that a conscience effort should be made to update old code?</p>
[ { "answer_id": 95753, "author": "torial", "author_id": 13990, "author_profile": "https://Stackoverflow.com/users/13990", "pm_score": 3, "selected": false, "text": "Public Sub Run(ByVal strToProcess As String) Implements IPerfStub.Run\n Dim genList As New ArrayList\n\n For Each ch As Char In strToProcess.ToCharArray\n genList.Add(ch)\n Next\n\n Dim dummy As New System.Text.StringBuilder()\n For i As Integer = 0 To genList.Count - 1\n dummy.Append(genList(i))\n Next\n\nEnd Sub\n\n Public Sub Run(ByVal strToProcess As String) Implements IPerfStub.Run\n Dim genList As New List(Of Char)\n\n For Each ch As Char In strToProcess.ToCharArray\n genList.Add(ch)\n Next\n\n Dim dummy As New System.Text.StringBuilder()\n For i As Integer = 0 To genList.Count - 1\n dummy.Append(genList(i))\n Next\n End Sub\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1942/" ]
94,906
<p>I'm running a SQL query on SQL Server 2005, and in addition to 2 columns being queried from the database, I'd also like to return 1 column of random numbers along with them. I tried this:</p> <pre><code>select column1, column2, floor(rand() * 10000) as column3 from table1 </code></pre> <p>Which kinda works, but the problem is that this query returns the same random number on every row. It's a different number each time you run the query, but it doesn't vary from row to row. How can I do this and get a new random number for each row?</p>
[ { "answer_id": 94951, "author": "Adam", "author_id": 13320, "author_profile": "https://Stackoverflow.com/users/13320", "pm_score": 1, "selected": false, "text": "CREATE VIEW vRandNumber\nAS\nSELECT RAND() as RandNumber\n CREATE FUNCTION RandNumber()\nRETURNS float\nAS\n BEGIN\n RETURN (SELECT RandNumber FROM vRandNumber)\n END\n SELECT dbo.RandNumber(), *\nFROM <table>\n" }, { "answer_id": 94995, "author": "Jonas Lincoln", "author_id": 17436, "author_profile": "https://Stackoverflow.com/users/17436", "pm_score": 1, "selected": false, "text": "select column1, column2, cast(new_id() as varchar(10)) as column3 \nfrom table1\n" }, { "answer_id": 491502, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 6, "selected": true, "text": "select column1, column2, \n ABS(CAST(CAST(NEWID() AS VARBINARY) AS int)) % 10000 as column3 \nfrom table1\n" }, { "answer_id": 493703, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 2, "selected": false, "text": "CREATE VIEW vRandNumber\nAS\nSELECT RAND() as RandNumber\n\ngo \n\nCREATE FUNCTION RandNumber()\nRETURNS float\nAS\n BEGIN\n RETURN (SELECT RandNumber FROM vRandNumber)\n END\n\ngo \n\ncreate table bigtable(i int)\n\ngo \n\ninsert into bigtable \nselect top 100000 1 from sysobjects a\njoin sysobjects b on 1=1\n\ngo \n\nselect cast(dbo.RandNumber() * 10000 as integer) as r into #t from bigtable \n-- CPU (1607) READS (204639) DURATION (1551)\n\ngo\n\nselect ABS(CAST(CAST(NEWID() AS VARBINARY) AS int)) % 10000 as r into #t1 \nfrom bigtable\n-- Runs 15 times faster - CPU (78) READS (809) DURATION (99)\n -- proof that stuff is random enough \nselect avg(r) from #t\n-- 5004\nselect STDEV(r) from #t\n-- 2895.1999 \n\nselect avg(r) from #t1\n-- 4992\nselect STDEV(r) from #t1\n-- 2881.44 \n\n\nselect r,count(r) from #t\ngroup by r \n-- 10000 rows returned \n\nselect r,count(r) from #t1\ngroup by r \n-- 10000 row returned \n" }, { "answer_id": 1731558, "author": "Ken", "author_id": 72966, "author_profile": "https://Stackoverflow.com/users/72966", "pm_score": 1, "selected": false, "text": "rand() newid() VARBINARY INT SELECT CAST(SubString(CONVERT(binary(16), newid()), 14, 3) AS INT) / 16777216.0 AS R\n" }, { "answer_id": 4373009, "author": "denis_n", "author_id": 217372, "author_profile": "https://Stackoverflow.com/users/217372", "pm_score": 2, "selected": false, "text": "select RAND(CHECKSUM(NEWID()))\n" }, { "answer_id": 16225215, "author": "Cindy Conway", "author_id": 2200446, "author_profile": "https://Stackoverflow.com/users/2200446", "pm_score": 1, "selected": false, "text": "SELECT \n rowNumber, \n name, \n randomNumber\nFROM dbo.tvfRandomNumberList(1,10,100) \nINNER JOIN (select ROW_NUMBER() over (order by int_id) as 'rowNumber', name from client \n )as clients\nON clients.rowNumber = uniqueKey\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8409/" ]
94,912
<p>We currently have code like this:</p> <pre><code>Dim xDoc = XDocument.Load(myXMLFilePath) </code></pre> <p>The only way we know how to do it currently is by using a file path and impersonation (since this file is on a secured network path).</p> <p>I've looked at <a href="http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.load.aspx" rel="nofollow noreferrer">XDocument.Load on MSDN</a>, but I don't see anything.</p>
[ { "answer_id": 94993, "author": "Domenic", "author_id": 3191, "author_profile": "https://Stackoverflow.com/users/3191", "pm_score": 2, "selected": false, "text": "XDocument.Load" }, { "answer_id": 9182657, "author": "Shawinder Sekhon", "author_id": 823800, "author_profile": "https://Stackoverflow.com/users/823800", "pm_score": 0, "selected": false, "text": "//Sample XML\n<Product>\n <Name>Product1</Name>\n <Price>0.00</Price>\n</Product>\n\n //Reading XML\n XmlTextReader rdr = new XmlTextReader(\"http://your-url\");\n XDocument loaded = XDocument.Load(rdr);\n\n //View the loaded contents\n //Response.ClearHeaders();\n //Response.ContentType = \"text/xml;charset=UTF-8\";\n //Response.Write(loaded);\n //Response.End();\n\n var data = from c in loaded.Descendants(\"Product\")\n select new\n {\n name = c.Element(\"Name\").Value,\n price = c.Element(\"Price\").Value,\n };\n\n foreach (var element in data)\n {\n //Do something here\n }\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7072/" ]
94,930
<p>I have a table with game scores, allowing multiple rows per account id: <code>scores (id, score, accountid)</code>. I want a list of the top 10 scorer ids and their scores.</p> <p>Can you provide an sql statement to select the top 10 scores, but only one score per account id? </p> <p>Thanks!</p>
[ { "answer_id": 94958, "author": "Danimal", "author_id": 2757, "author_profile": "https://Stackoverflow.com/users/2757", "pm_score": 2, "selected": false, "text": "select top 10 username, \n max(score) \nfrom usertable \ngroup by username \norder by max(score) desc\n" }, { "answer_id": 94982, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 1, "selected": false, "text": "SELECT DISTINCT ON (accountid) id, score, accountid\nFROM scoretable\nORDER BY score DESC\nLIMIT 10;\n" }, { "answer_id": 94985, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 2, "selected": false, "text": "select username, max(score) from usertable group by username order by max(score) desc limit 10;\n" }, { "answer_id": 95016, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 3, "selected": true, "text": "SELECT TOP 10 AccountId, Score\nFROM Scores s1\nWHERE AccountId NOT IN \n (SELECT AccountId s2 FROM Scores \n WHERE s1.AccountId = s2.AccountId and s1.Score > s2.Score)\nORDER BY Score DESC\n" }, { "answer_id": 109662, "author": "John Fiala", "author_id": 9143, "author_profile": "https://Stackoverflow.com/users/9143", "pm_score": 1, "selected": false, "text": "SELECT accountid, MAX(score) as top_score\nFROM Scores\nGROUP BY accountid,\nORDER BY top_score DESC\nLIMIT 0, 10" }, { "answer_id": 1169549, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "DISTINCT ON ORDER BY DISTINCT ON (accountid) ORDER BY score DESC ORDER BY SELECT DISTINCT ON (accountid) *\nFROM scoretable\nORDER BY accountid, score DESC\nLIMIT 10;\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13636/" ]
94,932
<p>Our CF server occasionally stops processing mail. This is problematic, as many of our clients depend on it. </p> <p>We found suggestions online that mention zero-byte files in the undeliverable folder, so I created a task that removes them every three minutes. However, the stoppage has occurred again.</p> <p>I am looking for suggestions for diagnosing and fixing this issue.</p> <ul> <li>CF 8 standard </li> <li>Win2k3</li> </ul> <p>Added:</p> <ul> <li>There are no errors in the mail log at the time the queue fails</li> <li>We have not tried to run this without using the queue, due to the large amount of mail we send</li> </ul> <p>Added 2:</p> <ul> <li>It does not seem to be a problem with any of the files in the spool folder. When we restart the mail queue, they all seem to process correctly.</li> </ul> <p>Added 3:</p> <ul> <li>We are not using attachments.</li> </ul>
[ { "answer_id": 528530, "author": "Ben Doom", "author_id": 12267, "author_profile": "https://Stackoverflow.com/users/12267", "pm_score": 5, "selected": true, "text": "<cfdirectory action=\"list\" directory=\"c:\\coldfusion8\\mail\\spool\\\" name=\"spool\" sort=\"datelastmodified\">\n<cfset restart = 0>\n<cfif datediff('n', spool.datelastmodified, now()) gt 30>\n <cfset restart = 1>\n</cfif>\n<cfif restart>\n <cfset sFactory = CreateObject(\"java\",\"coldfusion.server.ServiceFactory\")>\n <cfset MailSpoolService = sFactory.mailSpoolService>\n <cfset MailSpoolService.stop()>\n <cfset MailSpoolService.start()>\n</cfif>\n" }, { "answer_id": 23314430, "author": "user3576573", "author_id": 3576573, "author_profile": "https://Stackoverflow.com/users/3576573", "pm_score": 1, "selected": false, "text": "<!--- check if request for this page is local to prevent \"webusers\" to request this page over and over, only localhost (server) can get it e.g. by cf scheduled tasks--->\n<cfsetting requesttimeout=\"30000\">\n<cfset who = CGI.SERVER_NAME>\n<cfif find(\"localhost\",who) LT 1>\n security restriction, access denied.\n <cfabort>\n</cfif> \n\n<!--- get spool directory info --->\n<cfdirectory action=\"list\" directory=\"C:\\JRun4\\servers\\cfusion\\cfusion-ear\\cfusion-war\\WEB-INF\\cfusion\\Mail\\Spool\\\" name=\"spool\" sort=\"datelastmodified\">\n<cfset restart = 0>\n<cfif spool.recordcount GT 0><!--- content there? --->\n <cfif datediff('n', spool.datelastmodified, now()) gt 120>\n <cfset restart = 1>\n </cfif>\n</cfif>\n<cfif restart><!--- restart --->\n <cfsavecontent variable=\"liste\">\n <cfdump var=\"#list#\">\n </cfsavecontent> \n <!--- info --->\n <cfmail to=\"x@y.com\" subject=\"cfmailqueue restarted by daemon\" server=\"xxx\" port=\"25\" from=\"xxxx\" username=\"xxxx\" password=\"xxx\" replyto=\"xxxx\">\n 1/2 action: ...try to restart. Send another mail if succeeded!\n #now()#\n\n Mails:\n #liste#\n </cfmail>\n\n <cfset sFactory = CreateObject(\"java\",\"coldfusion.server.ServiceFactory\")>\n <cfset MailSpoolService = sFactory.mailSpoolService>\n <cfset MailSpoolService.stop()>\n <cfset MailSpoolService.start()>\n\n <!--- info --->\n <cfmail to=\"x@y.com\" subject=\"cfmailqueue restarted by daemon\" server=\"xxx\" port=\"25\" from=\"xxxx\" username=\"xxxx\" password=\"xxx\" replyto=\"xxxx\">\n 2/2 action: ...succeeded!\n #now()#\n </cfmail>\n\n</cfif>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12267/" ]
94,934
<p>I'd like to create a &quot;universal&quot; debug logging function that inspects the JS namespace for well-known logging libraries.</p> <p>For example, currently, it supports Firebug's console.log:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> var console = window['console']; if (console &amp;&amp; console.log) { console.log(message); }</code></pre> </div> </div> </p> <p>Obviously, this only works in Firefox if Firebug is installed/enabled (it'll also work on other browsers with <a href="http://getfirebug.com/lite.html" rel="nofollow noreferrer">Firebug Lite</a>). Basically, I will be providing a JS library which I don't know what environment it will be pulled into, and I'd like to be able to figure out if there is a way to report debug output to the user.</p> <p>So, perhaps jQuery provides something - I'd check that jQuery is present and use it. Or maybe there are well-known IE plugins that work that I can sniff for. But it has to be fairly well-established and used machinery. I can't check for every obscure log function that people create.</p> <p>Please, only one library/technology per answer, so they can get voted ranked. Also, using alert() is a good short-term solution but breaks down if you want robust debug logging or if blocking the execution is a problem.</p>
[ { "answer_id": 94944, "author": "Teifion", "author_id": 1384652, "author_profile": "https://Stackoverflow.com/users/1384652", "pm_score": -1, "selected": false, "text": "alert('Some message/variables');\n" }, { "answer_id": 94996, "author": "dgvid", "author_id": 9897, "author_profile": "https://Stackoverflow.com/users/9897", "pm_score": 1, "selected": false, "text": "$.log('My value is: ' + val);\n" }, { "answer_id": 95574, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 2, "selected": false, "text": "MochiKit.Logging.logDebug() // prefaces value with \"DEBUG: \"\nMochiKit.Logging.log() // prefaces value with \"INFO: \"\nMochiKit.Logging.logError() // prefaces value with \"ERROR: \"\nMochiKit.Logging.logFatal() // prefaces value with \"FATAL: \"\nMochiKit.Logging.logWarning() // prefaces value with \"WARNING: \"\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4465/" ]
94,935
<p>Apparently xrange is faster but I have no idea why it's faster (and no proof besides the anecdotal so far that it is faster) or what besides that is different about</p> <pre><code>for i in range(0, 20): for i in xrange(0, 20): </code></pre>
[ { "answer_id": 94953, "author": "Oko", "author_id": 9402, "author_profile": "https://Stackoverflow.com/users/9402", "pm_score": -1, "selected": false, "text": "range xrange" }, { "answer_id": 94962, "author": "Charles", "author_id": 18031, "author_profile": "https://Stackoverflow.com/users/18031", "pm_score": 11, "selected": true, "text": "range range(1, 10000000) 9999999 xrange range xrange list(range(...)) xrange" }, { "answer_id": 94971, "author": "Antti Rasinen", "author_id": 8570, "author_profile": "https://Stackoverflow.com/users/8570", "pm_score": 5, "selected": false, "text": "print xrange.__doc__ # def doc(x): print x.__doc__ is super useful\nhelp(xrange)\n" }, { "answer_id": 95100, "author": "Corey", "author_id": 1595, "author_profile": "https://Stackoverflow.com/users/1595", "pm_score": 8, "selected": false, "text": "range(1, 10000000) 9999999 xrange range() xrange() list(range(1,100))\n" }, { "answer_id": 95168, "author": "efotinis", "author_id": 12320, "author_profile": "https://Stackoverflow.com/users/12320", "pm_score": 6, "selected": false, "text": "xrange xrange(2**32-1, 2**32+1) # When long is 32 bits, OverflowError: Python int too large to convert to C long\nrange(2**32-1, 2**32+1) # OK --> [4294967295L, 4294967296L]\n range xrange" }, { "answer_id": 95549, "author": "Lucas S.", "author_id": 7363, "author_profile": "https://Stackoverflow.com/users/7363", "pm_score": 4, "selected": false, "text": "MemoryError" }, { "answer_id": 97530, "author": "John Fouhy", "author_id": 15154, "author_profile": "https://Stackoverflow.com/users/15154", "pm_score": 7, "selected": false, "text": "timeit $ python -m timeit 'for i in range(1000000):' ' pass'\n10 loops, best of 3: 90.5 msec per loop\n$ python -m timeit 'for i in xrange(1000000):' ' pass'\n10 loops, best of 3: 51.1 msec per loop\n range() xrange() range()" }, { "answer_id": 5351725, "author": "Dave Everitt", "author_id": 123033, "author_profile": "https://Stackoverflow.com/users/123033", "pm_score": 3, "selected": false, "text": "import time\n\nfor x in range(1, 10):\n\n t = time.time()\n [v*10 for v in range(1, 10000)]\n print \"range: %.4f\" % ((time.time()-t)*100)\n\n t = time.time()\n [v*10 for v in xrange(1, 10000)]\n print \"xrange: %.4f\" % ((time.time()-t)*100)\n $python range_tests.py\nrange: 0.4273\nxrange: 0.3733\nrange: 0.3881\nxrange: 0.3507\nrange: 0.3712\nxrange: 0.3565\nrange: 0.4031\nxrange: 0.3558\nrange: 0.3714\nxrange: 0.3520\nrange: 0.3834\nxrange: 0.3546\nrange: 0.3717\nxrange: 0.3511\nrange: 0.3745\nxrange: 0.3523\nrange: 0.3858\nxrange: 0.3997 <- garbage collection?\n range: 0.4172\nxrange: 0.3701\nrange: 0.3840\nxrange: 0.3547\nrange: 0.3830\nxrange: 0.3862 <- garbage collection?\nrange: 0.4019\nxrange: 0.3532\nrange: 0.3738\nxrange: 0.3726\nrange: 0.3762\nxrange: 0.3533\nrange: 0.3710\nxrange: 0.3509\nrange: 0.3738\nxrange: 0.3512\nrange: 0.3703\nxrange: 0.3509\n" }, { "answer_id": 22905006, "author": "Kishor Pawar", "author_id": 1936024, "author_profile": "https://Stackoverflow.com/users/1936024", "pm_score": 4, "selected": false, "text": "range() xrange xrange() range() xrange() break" }, { "answer_id": 27144195, "author": "kmario23", "author_id": 2956066, "author_profile": "https://Stackoverflow.com/users/2956066", "pm_score": 2, "selected": false, "text": "range xrange object xrange range range xrange" }, { "answer_id": 30088340, "author": "abarnert", "author_id": 908494, "author_profile": "https://Stackoverflow.com/users/908494", "pm_score": 3, "selected": false, "text": "range xrange range len range collections.abc.Sequence list index count in 123456 in r issubclass(xrange, collections.Sequence) True" }, { "answer_id": 30545536, "author": "Evgeni Sergeev", "author_id": 1143274, "author_profile": "https://Stackoverflow.com/users/1143274", "pm_score": 1, "selected": false, "text": "range(..) xrange(..) $ python -m timeit \"for i in xrange(10111):\" \" for k in range(100):\" \" pass\"\n10 loops, best of 3: 59.4 msec per loop\n\n$ python -m timeit \"for i in xrange(10111):\" \" for k in xrange(100):\" \" pass\"\n10 loops, best of 3: 46.9 msec per loop\n xrange(100)" }, { "answer_id": 30997385, "author": "Tushar Patil", "author_id": 2013238, "author_profile": "https://Stackoverflow.com/users/2013238", "pm_score": 3, "selected": false, "text": "In [1]: range(1,10)\n\nOut[1]: [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\nIn [2]: xrange(10)\n\nOut[2]: xrange(10)\n\nIn [3]: print xrange.__doc__\n\nxrange([start,] stop[, step]) -> xrange object\n" }, { "answer_id": 35680931, "author": "Siyaram Malav", "author_id": 5326634, "author_profile": "https://Stackoverflow.com/users/5326634", "pm_score": 3, "selected": false, "text": ">>> a = range(5)\n>>> a\n[0, 1, 2, 3, 4]\n >>> b = xrange(5)\n>>> b\nxrange(5)\n" }, { "answer_id": 38318039, "author": "Supercolbat", "author_id": 6491545, "author_profile": "https://Stackoverflow.com/users/6491545", "pm_score": 3, "selected": false, "text": "range(x,y) for range range range(x.y) xrange(x,y) xrange(x,y) for xrange xrange xrange xrange(x,y) [In] range(1,10)\n[Out] [1, 2, 3, 4, 5, 6, 7, 8, 9]\n[In] xrange(1,10)\n[Out] xrange(1,10)\n for [In] for i in range(1,10):\n print i\n[Out] 1\n 2\n 3\n 4\n 5\n 6\n 7\n 8\n 9\n[In] for i in xrange(1,10):\n print i\n[Out] 1\n 2\n 3\n 4\n 5\n 6\n 7\n 8\n 9\n" }, { "answer_id": 40191633, "author": "User_Targaryen", "author_id": 6354622, "author_profile": "https://Stackoverflow.com/users/6354622", "pm_score": 4, "selected": false, "text": "xrange range import timeit\n\nt1 = timeit.default_timer()\na = 0\nfor i in xrange(1, 100000000):\n pass\nt2 = timeit.default_timer()\n\nprint \"time taken: \", (t2-t1) # 4.49153590202 seconds\n\nt1 = timeit.default_timer()\na = 0\nfor i in range(1, 100000000):\n pass\nt2 = timeit.default_timer()\n\nprint \"time taken: \", (t2-t1) # 7.04547905922 seconds\n xrange range xrange import timeit\n\nt1 = timeit.default_timer()\na = 0\nfor i in xrange(1, 100000000):\n if i == 10000:\n break\nt2 = timeit.default_timer()\n\nprint \"time taken: \", (t2-t1) # 0.000764846801758 seconds\n\nt1 = timeit.default_timer()\na = 0\nfor i in range(1, 100000000):\n if i == 10000:\n break\nt2 = timeit.default_timer() \n\nprint \"time taken: \", (t2-t1) # 2.78506207466 seconds\n range xrange range xrange xrange" }, { "answer_id": 45278377, "author": "ANKUR SATYA", "author_id": 8154961, "author_profile": "https://Stackoverflow.com/users/8154961", "pm_score": 2, "selected": false, "text": "a=0\nfor i in range(1,100000):\n a=a+i\n for i in list(range(1,100000)):\n a=a+i\n" }, { "answer_id": 45768014, "author": "Rajendra Uppal", "author_id": 277734, "author_profile": "https://Stackoverflow.com/users/277734", "pm_score": 2, "selected": false, "text": ">>> print range.__doc__\nrange(stop) -> list of integers\nrange(start, stop[, step]) -> list of integers\n\nReturn a list containing an arithmetic progression of integers.\nrange(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\nWhen step is given, it specifies the increment (or decrement).\nFor example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\nThese are exactly the valid indices for a list of 4 elements.\n\n>>> print xrange.__doc__\nxrange(stop) -> xrange object\nxrange(start, stop[, step]) -> xrange object\n\nLike range(), but instead of returning a list, returns an object that\ngenerates the numbers in the range on demand. For looping, this is \nslightly faster than range() and more memory efficient.\n >>> print(range.__doc__)\nrange(stop) -> range object\nrange(start, stop[, step]) -> range object\n\nReturn an object that produces a sequence of integers from start (inclusive)\nto stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1.\nstart defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3.\nThese are exactly the valid indices for a list of 4 elements.\nWhen step is given, it specifies the increment (or decrement).\n\n>>> print(xrange.__doc__)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nNameError: name 'xrange' is not defined\n range xrange range xrange xrange" }, { "answer_id": 52696055, "author": "U12-Forward", "author_id": 8708364, "author_profile": "https://Stackoverflow.com/users/8708364", "pm_score": 1, "selected": false, "text": "list(xrange(...)) range(...) list xrange xrange" }, { "answer_id": 60917801, "author": "Giorgos Myrianthous", "author_id": 7131757, "author_profile": "https://Stackoverflow.com/users/7131757", "pm_score": 2, "selected": false, "text": "range() 2.x range() 2.x list for i in range(1000000) range() 3.x xrange() 2.x 3.x range() 2.x xrange() range() range # Python 2.x\n>>> a = range(10)\n>>> type(a)\n<type 'list'>\n>>> b = xrange(10)\n>>> type(b)\n<type 'xrange'>\n # Python 3.x\n>>> a = range(10)\n>>> type(a)\n<class 'range'>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
94,975
<p>I've read in one of my AI books that popular algorithms (A-Star, Dijkstra) for path-finding in simulation or games is also used to solve the well-known "15-puzzle".</p> <p>Can anyone give me some pointers on how I would reduce the 15-puzzle to a graph of nodes and edges so that I could apply one of these algorithms?</p> <p>If I were to treat each node in the graph as a game state then wouldn't that tree become quite large? Or is that just the way to do it?</p>
[ { "answer_id": 9990636, "author": "satnhak", "author_id": 323316, "author_profile": "https://Stackoverflow.com/users/323316", "pm_score": 2, "selected": false, "text": "n x n n > 3 n (n^2)! (n^2 − 1) n^3" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
94,977
<p>In C# and in Java (and possibly other languages as well), variables declared in a "try" block are not in scope in the corresponding "catch" or "finally" blocks. For example, the following code does not compile:</p> <pre><code>try { String s = "test"; // (more code...) } catch { Console.Out.WriteLine(s); //Java fans: think "System.out.println" here instead } </code></pre> <p>In this code, a compile-time error occurs on the reference to s in the catch block, because s is only in scope in the try block. (In Java, the compile error is "s cannot be resolved"; in C#, it's "The name 's' does not exist in the current context".)</p> <p>The general solution to this issue seems to be to instead declare variables just before the try block, instead of within the try block:</p> <pre><code>String s; try { s = "test"; // (more code...) } catch { Console.Out.WriteLine(s); //Java fans: think "System.out.println" here instead } </code></pre> <p>However, at least to me, (1) this feels like a clunky solution, and (2) it results in the variables having a larger scope than the programmer intended (the entire remainder of the method, instead of only in the context of the try-catch-finally).</p> <p>My question is, what were/are the rationale(s) behind this language design decision (in Java, in C#, and/or in any other applicable languages)? </p>
[ { "answer_id": 95015, "author": "EndangeredMassa", "author_id": 106, "author_profile": "https://Stackoverflow.com/users/106", "pm_score": 2, "selected": false, "text": "try\n dim i as integer = 10 / 0 ''// Throw an exception\n dim s as string = \"hi\"\ncatch (e)\n console.writeln(s) ''// Would throw another exception, if this was allowed to compile\nend try\n" }, { "answer_id": 95030, "author": "John Christensen", "author_id": 1194, "author_profile": "https://Stackoverflow.com/users/1194", "pm_score": 9, "selected": true, "text": "\ntry\n{\n throw new ArgumentException(\"some operation that throws an exception\");\n string s = \"blah\";\n}\ncatch (e as ArgumentException)\n{ \n Console.Out.WriteLine(s);\n}\n" }, { "answer_id": 95034, "author": "jW.", "author_id": 8880, "author_profile": "https://Stackoverflow.com/users/8880", "pm_score": 2, "selected": false, "text": "try { \n fileOpen(\"no real file Name\"); \n String s = \"GO TROJANS\"; \n} catch (Exception) { \n print(s); \n}\n" }, { "answer_id": 95047, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 5, "selected": false, "text": "... code ...\n{\n string s = \"test\";\n try\n {\n // more code\n }\n catch(...)\n {\n Console.Out.WriteLine(s);\n }\n}\n int f() { return 0; }\n\nvoid main() \n{\n int y = 0;\n\n if (int x = f())\n {\n cout << x;\n }\n else\n {\n cout << x;\n }\n}\n" }, { "answer_id": 95054, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 3, "selected": false, "text": "try catch try catch // here is some code\n{\n string s;\n try\n {\n\n throw new Exception(\":(\")\n }\n catch (Exception e)\n {\n Debug.WriteLine(s);\n }\n}\n" }, { "answer_id": 95068, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 2, "selected": false, "text": "{ // block A\n string s = \"dude\";\n}\n\n{ // block B\n Console.Out.WriteLine(s); // or printf or whatever\n}\n" }, { "answer_id": 95133, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 2, "selected": false, "text": " try\n {\n //Code 1\n String s = \"1|2\";\n //Code 2\n }\n catch\n {\n Console.WriteLine(s.Split('|')[1]);\n }\n String s; s = \"1|2\"; {} {\n String s;\n try\n {\n s = \"test\";\n //More code\n }\n catch\n {\n Console.WriteLine(s);\n }\n}\n" }, { "answer_id": 95136, "author": "Timothy Carter", "author_id": 4660, "author_profile": "https://Stackoverflow.com/users/4660", "pm_score": 2, "selected": false, "text": "string s = String.Empty;\ntry\n{\n //do work\n}\ncatch\n{\n //safely access s\n Console.WriteLine(s);\n}\n string s;\ntry\n{\n //do work\n}\ncatch\n{\n if (!String.IsNullOrEmpty(s))\n {\n //safely access s\n Console.WriteLine(s);\n }\n}\n" }, { "answer_id": 95451, "author": "ykaganovich", "author_id": 10026, "author_profile": "https://Stackoverflow.com/users/10026", "pm_score": 2, "selected": false, "text": " try (FileReader in = makeReader(), FileWriter out = makeWriter()) {\n // code using in and out\n } catch(IOException e) {\n // ...\n }\n with(FileReader in : makeReader()) with(FileWriter out : makeWriter()) {\n // code using in and out\n}\n" }, { "answer_id": 97346, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 4, "selected": false, "text": "static void TryCatchFinally()\n{\n StreamReader sr = null;\n try\n {\n sr = new StreamReader(path);\n Console.WriteLine(sr.ReadToEnd());\n }\n catch (Exception ex)\n {\n Console.WriteLine(ex.ToString());\n }\n finally\n {\n if (sr != null)\n {\n sr.Close();\n }\n }\n}\n .method private hidebysig static void TryCatchFinallyDispose() cil managed\n{\n // Code size 53 (0x35) \n .maxstack 2 \n .locals init ([0] class [mscorlib]System.IO.StreamReader sr, \n [1] class [mscorlib]System.Exception ex) \n IL_0000: ldnull \n IL_0001: stloc.0 \n .try \n { \n .try \n { \n IL_0002: ldsfld string UsingTest.Class1::path \n IL_0007: newobj instance void [mscorlib]System.IO.StreamReader::.ctor(string) \n IL_000c: stloc.0 \n IL_000d: ldloc.0 \n IL_000e: callvirt instance string [mscorlib]System.IO.TextReader::ReadToEnd()\n IL_0013: call void [mscorlib]System.Console::WriteLine(string) \n IL_0018: leave.s IL_0028\n } // end .try\n catch [mscorlib]System.Exception \n {\n IL_001a: stloc.1\n IL_001b: ldloc.1 \n IL_001c: callvirt instance string [mscorlib]System.Exception::ToString() \n IL_0021: call void [mscorlib]System.Console::WriteLine(string) \n IL_0026: leave.s IL_0028 \n } // end handler \n IL_0028: leave.s IL_0034 \n } // end .try \n finally \n { \n IL_002a: ldloc.0 \n IL_002b: brfalse.s IL_0033 \n IL_002d: ldloc.0 \n IL_002e: callvirt instance void [mscorlib]System.IDisposable::Dispose() \n IL_0033: endfinally \n } // end handler \n IL_0034: ret \n} // end of method Class1::TryCatchFinallyDispose\n" }, { "answer_id": 98148, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 0, "selected": false, "text": "// won't compile!\ntry\n{\n VeryLargeArray v = new VeryLargeArray(TOO_BIG_CONSTANT); // throws OutOfMemoryException\n string s = \"Help\";\n}\ncatch\n{\n Console.WriteLine(s); // whoops!\n}\n using(Writer writer = new Writer())\n{\n writer.Write(\"Hello\");\n}\n Writer writer = new Writer();\ntry\n{ \n writer.Write(\"Hello\");\n}\nfinally\n{\n if( writer != null)\n {\n ((IDisposable)writer).Dispose();\n }\n}\n" }, { "answer_id": 98160, "author": "core", "author_id": 11574, "author_profile": "https://Stackoverflow.com/users/11574", "pm_score": -1, "selected": false, "text": "string html = new Func<string>(() =>\n{\n string webpage;\n\n try\n {\n using(WebClient downloader = new WebClient())\n {\n webpage = downloader.DownloadString(url);\n }\n }\n catch(WebException)\n {\n Console.WriteLine(\"Download failed.\"); \n }\n\n return webpage;\n})();\n" }, { "answer_id": 4553265, "author": "Ravi", "author_id": 556970, "author_profile": "https://Stackoverflow.com/users/556970", "pm_score": 1, "selected": false, "text": "try {\n\n //doSomeWork // Exception is thrown in this line. \n String s;\n //doRestOfTheWork\n\n} catch (Exception) {\n //Use s;//Problem here\n} finally {\n //Use s;//Problem here\n}\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12484/" ]
94,997
<p>Suppose you have a program which reads from a socket. How do you keep the download rate below a certain given threshold?</p>
[ { "answer_id": 95058, "author": "Branan", "author_id": 13894, "author_profile": "https://Stackoverflow.com/users/13894", "pm_score": 1, "selected": false, "text": "ReadFixedRate() {\n while(Data_Exists()) {\n t = GetTime();\n ReadBlock();\n while(t + delay > GetTime()) {\n Delay()'\n }\n }\n}\n" }, { "answer_id": 95219, "author": "INS", "author_id": 13136, "author_profile": "https://Stackoverflow.com/users/13136", "pm_score": 1, "selected": false, "text": "extern int FPS;\n.... \ntimePerFrameinMS = 1000/FPS;\n\nwhile(1) {\ntime = getMilliseconds();\nDrawScene();\ntime = getMilliseconds()-time;\nif (time < timePerFrameinMS) {\n sleep(timePerFrameinMS - time);\n}\n}\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9107/" ]
95,007
<p>I've been mystified by the R quantile function all day. </p> <p>I have an intuitive notion of how quantiles work, and an M.S. in stats, but boy oh boy, the documentation for it is confusing to me. </p> <p>From the docs:</p> <blockquote> <p>Q[i](p) = (1 - gamma) x[j] + gamma x[j+1],</p> </blockquote> <p>I'm with it so far. For a type <em>i</em> quantile, it's an interpolation between x[j] and x [j+1], based on some mysterious constant <em>gamma</em></p> <blockquote> <p>where 1 &lt;= i &lt;= 9, (j-m)/n &lt;= p &lt; (j-m+1)/ n, x[j] is the jth order statistic, n is the sample size, and m is a constant determined by the sample quantile type. Here gamma depends on the fractional part of g = np+m-j. </p> </blockquote> <p>So, how calculate j? m?</p> <blockquote> <p>For the continuous sample quantile types (4 through 9), the sample quantiles can be obtained by linear interpolation between the kth order statistic and p(k): </p> <p>p(k) = (k - alpha) / (n - alpha - beta + 1), where α and β are constants determined by the type. Further, m = alpha + p(1 - alpha - beta), and gamma = g.</p> </blockquote> <p>Now I'm really lost. p, which was a constant before, is now apparently a function. </p> <p>So for Type 7 quantiles, the default...</p> <blockquote> <p>Type 7</p> <p>p(k) = (k - 1) / (n - 1). In this case, p(k) = mode[F(x[k])]. This is used by S. </p> </blockquote> <p>Anyone want to help me out? In particular I'm confused by the notation of p being a function and a constant, what the heck <em>m</em> is, and now to calculate j for some particular <em>p</em>. </p> <p>I hope that based on the answers here, we can submit some revised documentation that better explains what is going on here. </p> <p><a href="https://svn.r-project.org/R/trunk/src/library/stats/R/quantile.R" rel="noreferrer">quantile.R source code</a> or type: quantile.default</p>
[ { "answer_id": 1463249, "author": "AFoglia", "author_id": 79513, "author_profile": "https://Stackoverflow.com/users/79513", "pm_score": 7, "selected": true, "text": "j = int(pn+m) Q[i](p) p m m Q[i] m m[i] m m p(k) p p(k) p k m p p m = alpha + p * (1 - alpha - beta) p k x[k] p Q[i](p) p k" }, { "answer_id": 58754784, "author": "Michael Roswell", "author_id": 8400969, "author_profile": "https://Stackoverflow.com/users/8400969", "pm_score": 2, "selected": false, "text": "quantile(x, probs=probs) quantile.default <-function(x, probs = seq(0, 1, 0.25), na.rm = FALSE, names = TRUE\n , type = 7, ...){\n if(is.factor(x)) { #worry about non-numeric data\n if(!is.ordered(x) || ! type %in% c(1L, 3L))\n stop(\"factors are not allowed\")\n lx <- levels(x)\n } else lx <- NULL\n if (na.rm){\n x <- x[!is.na(x)]\n } else if (anyNA(x)){\n stop(\"missing values and NaN's not allowed if 'na.rm' is FALSE\")\n }\n eps <- 100*.Machine$double.eps #this is to deal with rounding things sensibly\n if (any((p.ok <- !is.na(probs)) & (probs < -eps | probs > 1+eps)))\n stop(\"'probs' outside [0,1]\")\n\n #####################################\n # here is where terms really used in default type==7 situation get defined\n\n n <- length(x) #how many observations are in sample?\n\n if(na.p <- any(!p.ok)) { # set aside NA & NaN\n o.pr <- probs\n probs <- probs[p.ok]\n probs <- pmax(0, pmin(1, probs)) # allow for slight overshoot\n }\n\n np <- length(probs) #how many quantiles are you computing?\n\n if (n > 0 && np > 0) { #have positive observations and # quantiles to compute\n if(type == 7) { # be completely back-compatible\n\n index <- 1 + (n - 1) * probs #this gives the order statistic of the quantiles\n lo <- floor(index) #this is the observed order statistic just below each quantile\n hi <- ceiling(index) #above\n x <- sort(x, partial = unique(c(lo, hi))) #the partial thing is to reduce time to sort, \n #and it only guarantees that sorting is \"right\" at these order statistics, important for large vectors \n #ties are not broken and tied elements just stay in their original order\n qs <- x[lo] #the values associated with the \"floor\" order statistics\n i <- which(index > lo) #which of the order statistics for the quantiles do not land on an order statistic for an observed value\n\n #this is the difference between the order statistic and the available ranks, i think\n h <- (index - lo)[i] # > 0 by construction \n ## qs[i] <- qs[i] + .minus(x[hi[i]], x[lo[i]]) * (index[i] - lo[i])\n ## qs[i] <- ifelse(h == 0, qs[i], (1 - h) * qs[i] + h * x[hi[i]])\n qs[i] <- (1 - h) * qs[i] + h * x[hi[i]] # This is the interpolation step: assemble the estimated quantile by removing h*low and adding back in h*high. \n # h is the arithmetic difference between the desired order statistic amd the available ranks\n #interpolation only occurs if the desired order statistic is not observed, e.g. .5 quantile is the actual observed median if n is odd. \n # This means having a more extreme 99th observation doesn't matter when computing the .75 quantile\n\n\n ###################################\n # print all of these things\n\n cat(\"floor pos=\", c(lo))\n cat(\"\\nceiling pos=\", c(hi))\n cat(\"\\nfloor values= \", c(x[lo]))\n cat( \"\\nwhich floors not targets? \", c(i))\n cat(\"\\ninterpolate between \", c(x[lo[i]]), \";\", c(x[hi[i]]))\n cat( \"\\nadjustment values= \", c(h))\n cat(\"\\nquantile estimates:\")\n\n }else if (type <= 3){## Types 1, 2 and 3 are discontinuous sample qs.\n nppm <- if (type == 3){ n * probs - .5 # n * probs + m; m = -0.5\n } else {n * probs} # m = 0\n\n j <- floor(nppm)\n h <- switch(type,\n (nppm > j), # type 1\n ((nppm > j) + 1)/2, # type 2\n (nppm != j) | ((j %% 2L) == 1L)) # type 3\n\n } else{\n ## Types 4 through 9 are continuous sample qs.\n switch(type - 3,\n {a <- 0; b <- 1}, # type 4\n a <- b <- 0.5, # type 5\n a <- b <- 0, # type 6\n a <- b <- 1, # type 7 (unused here)\n a <- b <- 1 / 3, # type 8\n a <- b <- 3 / 8) # type 9\n ## need to watch for rounding errors here\n fuzz <- 4 * .Machine$double.eps\n nppm <- a + probs * (n + 1 - a - b) # n*probs + m\n j <- floor(nppm + fuzz) # m = a + probs*(1 - a - b)\n h <- nppm - j\n\n if(any(sml <- abs(h) < fuzz)) h[sml] <- 0\n\n x <- sort(x, partial =\n unique(c(1, j[j>0L & j<=n], (j+1)[j>0L & j<n], n))\n )\n x <- c(x[1L], x[1L], x, x[n], x[n])\n ## h can be zero or one (types 1 to 3), and infinities matter\n #### qs <- (1 - h) * x[j + 2] + h * x[j + 3]\n ## also h*x might be invalid ... e.g. Dates and ordered factors\n qs <- x[j+2L]\n qs[h == 1] <- x[j+3L][h == 1]\n other <- (0 < h) & (h < 1)\n if(any(other)) qs[other] <- ((1-h)*x[j+2L] + h*x[j+3L])[other]\n\n } \n } else {\n qs <- rep(NA_real_, np)}\n\n if(is.character(lx)){\n qs <- factor(qs, levels = seq_along(lx), labels = lx, ordered = TRUE)}\n if(names && np > 0L) {\n names(qs) <- format_perc(probs)\n }\n if(na.p) { # do this more elegantly (?!)\n o.pr[p.ok] <- qs\n names(o.pr) <- rep(\"\", length(o.pr)) # suppress <NA> names\n names(o.pr)[p.ok] <- names(qs)\n o.pr\n } else qs\n}\n\n####################\n\n# fake data\nx<-c(1,2,2,2,3,3,3,4,4,4,4,4,5,5,5,5,5,5,5,5,5,6,6,7,99)\ny<-c(1,2,2,2,3,3,3,4,4,4,4,4,5,5,5,5,5,5,5,5,5,6,6,7,9)\nz<-c(1,2,2,2,3,3,3,4,4,4,4,4,5,5,5,5,5,5,5,5,5,6,6,7)\n\n#quantiles \"of interest\"\nprobs<-c(0.5, 0.75, 0.95, 0.975)\n\n# a tiny bit of illustrative behavior\nquantile.default(x,probs=probs, names=F)\nquantile.default(y,probs=probs, names=F) #only difference is .975 quantile since that is driven by highest 2 observations\nquantile.default(z,probs=probs, names=F) # This shifts everything b/c now none of the quantiles fall on an observation (and of course the distribution changed...)... but \n#.75 quantile is stil 5.0 b/c the observations just above and below the order statistic for that quantile are still 5. However, it got there for a different reason.\n\n#how does rescaling affect quantile estimates?\nsqrt(quantile.default(x^2, probs=probs, names=F))\nexp(quantile.default(log(x), probs=probs, names=F))\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15842/" ]
95,061
<p>How can I tell Activerecord to not load blob columns unless explicitly asked for? There are some pretty large blobs in my legacy DB that must be excluded for 'normal' Objects.</p>
[ { "answer_id": 95413, "author": "Mike Tunnicliffe", "author_id": 13956, "author_profile": "https://Stackoverflow.com/users/13956", "pm_score": 2, "selected": false, "text": "MyModel.find(id, :select => 'every, attribute, except, the, blobs')\n MyModel.find(id, :select => (MyModel.column_names - ['column_to_exclude']).join(', '))\n" }, { "answer_id": 1354650, "author": "Zeke", "author_id": 95670, "author_profile": "https://Stackoverflow.com/users/95670", "pm_score": 2, "selected": false, "text": "desired_columns = (MyModel.column_names - ['column_to_exclude']).join(', ')\nMyModel.find(id, :select => desired_columns)\n" }, { "answer_id": 1604529, "author": "choonkeat", "author_id": 136558, "author_profile": "https://Stackoverflow.com/users/136558", "pm_score": 1, "selected": false, "text": ":select Member.create(:name => \"Michael\", :photo => IO.read(\"avatar.png\"))\n#=> creates a record in \"members\" table, saving \"Michael\" into the \"name\" column\n#=> creates a record in \"binary_columns\" table, saving \"avatar.png\" binary into \"content\" column\n\nm = Member.last #=> only columns in \"members\" table is fetched (no blobs)\nm.name #=> \"Michael\"\nm.photo #=> binary content of the \"avatar.png\" file\n" }, { "answer_id": 3274347, "author": "Chris Hoffman", "author_id": 394985, "author_profile": "https://Stackoverflow.com/users/394985", "pm_score": 4, "selected": false, "text": "default_scope default_scope select((column_names - ['data']).map { |column_name| \"`#{table_name}`.`#{column_name}`\"})\n .select(:data)" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
95,074
<p>I have noticed that setting row height in DataGridView control is slow. Is there a way to make it faster?</p>
[ { "answer_id": 95362, "author": "ImJustPondering", "author_id": 17940, "author_profile": "https://Stackoverflow.com/users/17940", "pm_score": 0, "selected": false, "text": " // my test to specify a size for a datagridview row\n dataGridView1.Columns.Add(new DataGridViewTextBoxColumn { Name = \"ColumnNameGoesHere\" });\n dataGridView1.RowTemplate.Height = 50;\n for (var x = 0; x <= 10000; x++)\n {\n dataGridView1.Rows.Add(x.ToString());\n }\n" }, { "answer_id": 95437, "author": "hometoast", "author_id": 2009, "author_profile": "https://Stackoverflow.com/users/2009", "pm_score": 2, "selected": false, "text": "DataGridView1.AutoSizeRowsMode = None\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18046/" ]
95,077
<p>What is the best way to store string data across postback. I need to store an ID and name for multiple entities. I was thinking of using a datatable in viewstate, but would that make viewstate grow too large? I can't use a database yet because I'll be inserting a record that those other records need to be related to. So I'll just be storing them temporarily until the user submits the form.</p>
[ { "answer_id": 101205, "author": "rohancragg", "author_id": 5351, "author_profile": "https://Stackoverflow.com/users/5351", "pm_score": 0, "selected": false, "text": "Dictionary<int, string> myValues = new Dictionary<int, string>();\nmyValues.Add(1, \"Apple\");\nmaValues.Add(2, \"Pear\");\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16891/" ]
95,089
<p>Trying the easy approach:</p> <blockquote> <p>sqlite2 mydb.db .dump | sqlite3 mydb-new.db</p> </blockquote> <p>I got this error:</p> <blockquote> <p>SQL error near line 84802: no such column: Ð</p> </blockquote> <p>In that line the script is this:</p> <blockquote> <p>INSERT INTO vehiculo VALUES(127548,'21K0065217',<strong>Ñ</strong>,'PA007808',65217,279,1989,3,468,'1998-07-30 00:00:00.000000','14/697/98-07',2,'',1);</p> </blockquote> <p>My guess is that <strong>the 'Ñ' without quotes is the problem</strong>.</p> <p>any idea?</p> <p>PD: I'm under Windows right now and I would like to use the command-line so it can be automatized (this process will be done on daily basis by a server).</p>
[ { "answer_id": 548310, "author": "Kyle Brantley", "author_id": 66329, "author_profile": "https://Stackoverflow.com/users/66329", "pm_score": 2, "selected": false, "text": "$ sqlite3 v2database.db\nsqlite> .quit\n$\n" }, { "answer_id": 1193101, "author": "ygrek", "author_id": 118799, "author_profile": "https://Stackoverflow.com/users/118799", "pm_score": 2, "selected": true, "text": "$sqlite3 db2\nSQLite version 3.6.16\nEnter \".help\" for instructions\nEnter SQL statements terminated with a \";\"\nsqlite> .tables\nError: file is encrypted or is not a database\nsqlite> .q\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7946/" ]
95,098
<p>Using the method <code>Application.Restart()</code> in C# should restart the current application: but it seems that this is not always working.</p> <p>Is there a reason for this Issue, can somebody tell me, why it doesn't work all the time?</p>
[ { "answer_id": 95239, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 2, "selected": false, "text": "Context.Application.Lock();\nContext.Session.Abandon();\nContext.Application.RemoveAll();\nContext.Application.Restart();\nContext.Application.UnLock();\n" }, { "answer_id": 95274, "author": "Timothy Carter", "author_id": 4660, "author_profile": "https://Stackoverflow.com/users/4660", "pm_score": 3, "selected": false, "text": "FormClosing Application.Restart()" }, { "answer_id": 4005990, "author": "cprcrack", "author_id": 423171, "author_profile": "https://Stackoverflow.com/users/423171", "pm_score": 4, "selected": false, "text": "Application.Restart();\n System.Diagnostics.Process.Start(Application.ExecutablePath);\nApplication.Exit();\n" }, { "answer_id": 6843504, "author": "ferhatayhan", "author_id": 865250, "author_profile": "https://Stackoverflow.com/users/865250", "pm_score": 0, "selected": false, "text": "bool appNotRestarted = true;\n if (appNotRestarted == true)\n{\n appNotRestarted = false;\n Application.Restart();\n Application.ExitThread();\n}\n" }, { "answer_id": 9056664, "author": "cmptrs4now", "author_id": 1176935, "author_profile": "https://Stackoverflow.com/users/1176935", "pm_score": 3, "selected": false, "text": "Properties.Settings Application.Restart() Properties.Settings Program.Main() property.settings Thread.Sleep(3000); if (ShouldRestartApp)\n{\n Properties.Settings.Default.IsRestarting = true;\n Properties.Settings.Default.Save();\n Application.Restart();\n}\n Program.Main() [STAThread]\nstatic void Main()\n{\n Mutex runOnce = null;\n\n if (Properties.Settings.Default.IsRestarting)\n {\n Properties.Settings.Default.IsRestarting = false;\n Properties.Settings.Default.Save();\n Thread.Sleep(3000);\n }\n\n try\n {\n runOnce = new Mutex(true, \"SOME_MUTEX_NAME\");\n\n if (runOnce.WaitOne(TimeSpan.Zero))\n {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Application.Run(new Form1());\n }\n }\n finally\n {\n if (null != runOnce)\n runOnce.Close();\n }\n}\n" }, { "answer_id": 23775554, "author": "shima lagzian", "author_id": 3659486, "author_profile": "https://Stackoverflow.com/users/3659486", "pm_score": 0, "selected": false, "text": "Application.Restart();\nApplication.ExitThread(); \n" }, { "answer_id": 35187243, "author": "Nathan", "author_id": 5875316, "author_profile": "https://Stackoverflow.com/users/5875316", "pm_score": -1, "selected": false, "text": "Applicatoin.Restart 'VB Code Sample\n Dim strStart As String = System.Environment.GetFolderPath(Environment.SpecialFolder.StartMenu) & \"\\Programs\\Folder\\YourApplication.appref-ms\"\n Application.Exit()\n Try\n Process.Start(strStart)\n Catch ex As Exception\n 'Do something with the exception\n End Try\n" }, { "answer_id": 42436204, "author": "Martin.Martinsson", "author_id": 434209, "author_profile": "https://Stackoverflow.com/users/434209", "pm_score": 1, "selected": false, "text": "public delegate void MethodDelegate<in TControl>(TControl value);\n\npublic static void InvokeIfRequired<TControl>(this TControl control, MethodDelegate<TControl> action)\n where TControl : Control\n{\n if (control.InvokeRequired)\n {\n control.Invoke(action, control);\n }\n else\n {\n action(control);\n }\n} \n private static bool _exiting;\nprivate static readonly object SynchObj = new object();\n public static void ApplicationRestart(params string[] commandLine)\n{\n lock (SynchObj)\n {\n if (Assembly.GetEntryAssembly() == null)\n {\n throw new NotSupportedException(\"RestartNotSupported\");\n }\n\n if (_exiting)\n return;\n\n _exiting = true;\n\n if (Environment.OSVersion.Version.Major < 6) return;\n\n bool cancelExit = true;\n\n try\n {\n foreach (Form f in Application.OpenForms.OfType<Form>().ToList())\n {\n f.InvokeIfRequired(frm =>\n {\n frm.FormClosing += (sender, args) => cancelExit = args.Cancel;\n frm.Close();\n });\n\n if (cancelExit) break;\n }\n\n if (cancelExit) return;\n\n Process.Start(new ProcessStartInfo\n {\n UseShellExecute = true,\n WorkingDirectory = Environment.CurrentDirectory,\n FileName = Application.ExecutablePath,\n Arguments = commandLine.Length > 0 ? string.Join(\" \", commandLine) : string.Empty\n });\n\n Application.Exit();\n }\n finally\n {\n _exiting = false;\n }\n }\n}\n" }, { "answer_id": 50515645, "author": "Nandostyle", "author_id": 3142999, "author_profile": "https://Stackoverflow.com/users/3142999", "pm_score": 0, "selected": false, "text": "If JustCloseIT = False Then\n 'all closing code, like logging the session log-out to a database and all those goodies we all do.\n End If\n" }, { "answer_id": 66685600, "author": "Ashutosh Ranjan", "author_id": 4855954, "author_profile": "https://Stackoverflow.com/users/4855954", "pm_score": 1, "selected": false, "text": "static class Program\n{\n static Mutex _mutex = new Mutex(false, \"MYAPP\");\n\n /// <summary>\n /// The main entry point for the application.\n /// </summary>\n [STAThread]\n static void Main()\n {\n if (!_mutex.WaitOne(1000, false))\n {\n MessageBox.Show(\"Another instance is already running!!!\", \"Already Running\", MessageBoxButtons.OK,\n MessageBoxIcon.Error);\n return;\n }\n\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Application.Run(new PrimaryForm());\n\n _mutex.ReleaseMutex();\n }\n}\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17558/" ]
95,105
<p>Convert.ToString() only allows base values of 2, 8, 10, and 16 for some odd reason; is there some obscure way of providing any base between 2 and 16?</p>
[ { "answer_id": 95116, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": -1, "selected": false, "text": "string foo = Convert.ToString(myint,base);\n" }, { "answer_id": 95331, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 3, "selected": false, "text": "string ConvertToBase(int value, int toBase)\n{\n if (toBase < 2 || toBase > 36) throw new ArgumentException(\"toBase\");\n if (value < 0) throw new ArgumentException(\"value\");\n\n if (value == 0) return \"0\"; //0 would skip while loop\n\n string AlphaCodes = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n string retVal = \"\";\n\n while (value > 0)\n {\n retVal = AlphaCodes[value % toBase] + retVal;\n value /= toBase;\n }\n\n return retVal;\n}\n" }, { "answer_id": 95411, "author": "Brian", "author_id": 8959, "author_profile": "https://Stackoverflow.com/users/8959", "pm_score": 0, "selected": false, "text": "//untested -- public domain\n// if you do a lot of conversions, using StringBuilder will be \n// much, much more efficient with memory and time than using string\n// alone.\n\nstring toStringWithBase(int number, int base)\n { \n if(0==number) //handle corner case\n return \"0\";\n if(base < 2)\n return \"ERROR: Base less than 2\";\n\n StringBuilder buffer = new StringBuilder(); \n\n bool negative = (number < 0) ? true : false;\n if(negative)\n {\n number=-number;\n buffer.Append('-');\n }\n\n int digits=0;\n int factor=1;\n\n int runningTotal=number;\n while(number > 0)\n {\n number = number/base;\n digits++;\n factor*=base;\n }\n factor = factor/base;\n\n while(factor >= 1)\n {\n int remainder = (number/factor) % base;\n\n Char out = '0'+remainder;\n if(remainder > 9)\n out = 'A' + remainder - 10;\n buffer.Append(out);\n factor = factor/base;\n }\n\n return buffer.ToString\n }\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9913/" ]
95,106
<p>Is there a Vim shortcut for jumping to the argument list of the current function? I often find myself needing to mess with the argument list of a function, and it's kind of annoying to have to do ?def or ?function or 10k or what-have-you until I finally get to it, then /( or t( or 5e to get to the right position in the argument list, and so on. It would be great if I could just hit ,a for example and instantly get put into insert mode at the end/beginning of the argument list.</p> <p>Possible approaches:</p> <ul> <li>Folding</li> <li>Tag support (ctags)</li> </ul> <p>Also, I'm using Python, so solutions based on curly braces unfortunately won't work.</p> <p>If no such shortcut exists, I'll just write one and post it here as an answer. :-)</p>
[ { "answer_id": 95745, "author": "Luc Hermitte", "author_id": 15934, "author_profile": "https://Stackoverflow.com/users/15934", "pm_score": 2, "selected": false, "text": " :nnoremap <buffer> [m :call search('def\\|function', 'b')<cr>f(\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16034/" ]
95,112
<p>I have a long running process in VB6 that I want to finish before executing the next line of code. How can I do that? Built-in function? Can I control how long to wait?</p> <p>Trivial example:</p> <pre><code>Call ExternalLongRunningProcess Call DoOtherStuff </code></pre> <p>How do I delay 'DoOtherStuff'?</p>
[ { "answer_id": 95142, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 5, "selected": true, "text": "Do\n If isSomeCheckCondition() Then Exit Do\n DoEvents\nLoop\n Private Declare Sub Sleep Lib \"kernel32\" (ByVal dwMilliseconds As Long)\n\nSleep 10000\n" }, { "answer_id": 102685, "author": "Kris Erickson", "author_id": 3798, "author_profile": "https://Stackoverflow.com/users/3798", "pm_score": 4, "selected": false, "text": "Private Declare Sub Sleep Lib \"kernel32\" (ByVal dwMilliseconds As Long)\n\nWhile IsStillWaitingForSomething()\n DoEvents\n DoEvents\n Sleep(55)\nWend\n" }, { "answer_id": 19862277, "author": "twynham", "author_id": 2969458, "author_profile": "https://Stackoverflow.com/users/2969458", "pm_score": -1, "selected": false, "text": "System.Threading.Thread.Sleep(500)" }, { "answer_id": 44914645, "author": "RetroDev", "author_id": 8256081, "author_profile": "https://Stackoverflow.com/users/8256081", "pm_score": 0, "selected": false, "text": "Dim ALongTime As Integer = 2000\nSystem.Threading.Thread.Sleep(ALongTime)\n" }, { "answer_id": 67009079, "author": "RkdL", "author_id": 6277654, "author_profile": "https://Stackoverflow.com/users/6277654", "pm_score": 1, "selected": false, "text": "sleep wait sleep Dim TimeStart as currency\nDim TimeStop as currency\nDim TimePassed as currency\nDim TimeWait as currency\n\n'use this block where you need a pause\nTimeWait = 0.5 'seconds\nTimeStart = Timer()\nTimePassed = 0\nDo while TimePassed < TimeWait 'seconds\n TimeStop = timer()\n TimePassed = TimeStop - TimeStart \n doevents\nloop\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
95,134
<p>I'm using the following code to query a database from my jsp, but I'd like to know more about what's happening behind the scenes.</p> <p>These are my two primary questions.</p> <p>Does the tag access the ResultSet directly, or is the query result being stored in a datastructure in memory?</p> <p>When is the connection closed?</p> <pre><code>&lt;%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %&gt; &lt;sql:query var="query" dataSource="${ds}" sql="${listQuery}"&gt;&lt;/sql:query&gt; &lt;c:forEach var="row" items="${query.rows}" begin="0"&gt; ${row.data } ${row.more_data } &lt;/c:forEach&gt; </code></pre> <p>Note: I've always been against running queries in the jsp, but my result set is too large to store in memory between my action and my jsp. Using this tag library looks like the easiest solution.</p>
[ { "answer_id": 95813, "author": "Will Hartung", "author_id": 13663, "author_profile": "https://Stackoverflow.com/users/13663", "pm_score": 1, "selected": false, "text": "\npublic class ResultSetIterator implements Iterator { \n\nConnection con;\nStatement s;\nResultSet rs;\nObject curObject;\nboolean closed;\n\npublic ResultSetIterator(Connection con, Statement s, ResultSet rs) {\n this.con = con;\n this.s = s;\n this.rs = rs;\n closed = false;\n}\n\npublic boolean hasNext() {\n advance();\n return curObject != null;\n}\n\npublic Object next() {\n advance();\n if (curObject == null) {\n throw new NoSuchElementException();\n } else {\n Object result = curObject;\n curObject = null;\n return result;\n }\n}\n\npublic void remove() {\n throw new UnsupportedOperationException(\"Not supported yet.\");\n}\n\nprivate void advance() {\n if (closed) {\n curObject = null;\n return;\n }\n if (curObject == null) {\n try {\n if (rs.next()) {\n curObject = bindObject(rs);\n }\n } catch (SQLException ex) {\n shutDown();\n throw new RuntimeException(ex);\n }\n }\n if (curObject == null) {\n // Still no object, must be at the end of the result set\n shutDown();\n }\n}\n\nprotected Object bindObject(ResultSet rs) throws SQLException {\n // Bind result set row to an object, replace or override this method\n String name = rs.getString(1);\n return name;\n}\n\npublic void shutDown() {\n closed = true;\n try {\n rs.close();\n } catch (SQLException ex) {\n // Ignored\n }\n try {\n s.close();\n } catch (SQLException ex) {\n // Ignored\n }\n try {\n con.close();\n } catch (SQLException ex) {\n // Ignored\n }\n}\n\n\n Connection con;\nStatement s;\nResultSet rs;\nObject curObject;\nboolean closed;\n\npublic ResultSetIterator(Connection con, Statement s, ResultSet rs) {\n this.con = con;\n this.s = s;\n this.rs = rs;\n closed = false;\n}\n\npublic boolean hasNext() {\n advance();\n return curObject != null;\n}\n\npublic Object next() {\n advance();\n if (curObject == null) {\n throw new NoSuchElementException();\n } else {\n Object result = curObject;\n curObject = null;\n return result;\n }\n}\n\npublic void remove() {\n throw new UnsupportedOperationException(\"Not supported yet.\");\n}\n\nprivate void advance() {\n if (closed) {\n curObject = null;\n return;\n }\n if (curObject == null) {\n try {\n if (rs.next()) {\n curObject = bindObject(rs);\n }\n } catch (SQLException ex) {\n shutDown();\n throw new RuntimeException(ex);\n }\n }\n if (curObject == null) {\n // Still no object, must be at the end of the result set\n shutDown();\n }\n}\n\nprotected Object bindObject(ResultSet rs) throws SQLException {\n // Bind result set row to an object, replace or override this method\n String name = rs.getString(1);\n return name;\n}\n\npublic void shutDown() {\n closed = true;\n try {\n rs.close();\n } catch (SQLException ex) {\n // Ignored\n }\n try {\n s.close();\n } catch (SQLException ex) {\n // Ignored\n }\n try {\n con.close();\n } catch (SQLException ex) {\n // Ignored\n }\n}\n }\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310/" ]
95,163
<p>I'm new to .Net and I'm trying to understand the basics first. What is the difference between MSIL and Java bytecode?</p>
[ { "answer_id": 96028, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 6, "selected": false, "text": "struct enums enums out ref static" }, { "answer_id": 9155197, "author": "Justin", "author_id": 332026, "author_profile": "https://Stackoverflow.com/users/332026", "pm_score": 5, "selected": false, "text": "class Factorial{\n public static void main(String[] a){\n System.out.println(new Fac().ComputeFac(10));\n }\n}\n\nclass Fac {\n public int ComputeFac(int num){\n int num_aux ;\n if (num < 1)\n num_aux = 1 ;\n else \n num_aux = num * (this.ComputeFac(num-1)) ;\n return num_aux ;\n }\n}\n .assembly extern mscorlib { }\n.assembly 'Factorial' { .ver 0:0:0:0 }\n.class private auto ansi beforefieldinit Factorial extends [mscorlib]System.Object\n{\n .method public static default void main (string[] a) cil managed\n {\n .entrypoint\n .maxstack 16\n newobj instance void class Fac::'.ctor'()\n ldc.i4 3\n callvirt instance int32 class Fac::ComputeFac (int32)\n call void class [mscorlib]System.Console::WriteLine(int32)\n ret\n }\n}\n\n.class private Fac extends [mscorlib]System.Object\n{\n .method public instance default void '.ctor' () cil managed\n {\n ldarg.0\n call instance void object::'.ctor'()\n ret\n }\n\n .method public int32 ComputeFac(int32 num) cil managed\n {\n .locals init ( int32 num_aux )\n ldarg num\n ldc.i4 1\n clt\n brfalse L1\n ldc.i4 1\n stloc num_aux\n br L2\n L1:\n ldarg num\n ldarg.0\n ldarg num\n ldc.i4 1\n sub\n callvirt instance int32 class Fac::ComputeFac (int32)\n mul\n stloc num_aux\n L2:\n ldloc num_aux\n ret\n }\n}\n ilasm.exe javac javap class Factorial extends java.lang.Object{\nFactorial();\n Code:\n 0: aload_0\n 1: invokespecial #1; //Method java/lang/Object.\"<init>\":()V\n 4: return\n\npublic static void main(java.lang.String[]);\n Code:\n 0: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;\n 3: new #3; //class Fac\n 6: dup\n 7: invokespecial #4; //Method Fac.\"<init>\":()V\n 10: bipush 10\n 12: invokevirtual #5; //Method Fac.ComputeFac:(I)I\n 15: invokevirtual #6; //Method java/io/PrintStream.println:(I)V\n 18: return\n\n}\n\nclass Fac extends java.lang.Object{\nFac();\n Code:\n 0: aload_0\n 1: invokespecial #1; //Method java/lang/Object.\"<init>\":()V\n 4: return\n\npublic int ComputeFac(int);\n Code:\n 0: iload_1\n 1: iconst_1\n 2: if_icmpge 10\n 5: iconst_1\n 6: istore_2\n 7: goto 20\n 10: iload_1\n 11: aload_0\n 12: iload_1\n 13: iconst_1\n 14: isub\n 15: invokevirtual #2; //Method ComputeFac:(I)I\n 18: imul\n 19: istore_2\n 20: iload_2\n 21: ireturn\n}\n javap" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18055/" ]
95,181
<p>I have:</p> <pre><code>class MyClass extends MyClass2 implements Serializable { //... } </code></pre> <p>In MyClass2 is a property that is not serializable. How can I serialize (and de-serialize) this object?</p> <p>Correction: MyClass2 is, of course, not an interface but a class.</p>
[ { "answer_id": 95208, "author": "Mike Deck", "author_id": 1247, "author_profile": "https://Stackoverflow.com/users/1247", "pm_score": 5, "selected": false, "text": "private transient Foo foo;\n" }, { "answer_id": 95224, "author": "sk.", "author_id": 16399, "author_profile": "https://Stackoverflow.com/users/16399", "pm_score": 3, "selected": false, "text": "writeObject() readObject() java.io.Serializable" }, { "answer_id": 97630, "author": "Scott Bale", "author_id": 2495576, "author_profile": "https://Stackoverflow.com/users/2495576", "pm_score": 7, "selected": true, "text": "\nclass MyClass extends MyClass2 implements Serializable{\n\n public MyClass(int quantity) {\n setNonSerializableProperty(new NonSerializableClass(quantity));\n }\n\n private void writeObject(java.io.ObjectOutputStream out)\n throws IOException{\n // note, here we don't need out.defaultWriteObject(); because\n // MyClass has no other state to serialize\n out.writeInt(super.getNonSerializableProperty().getQuantity());\n }\n\n private void readObject(java.io.ObjectInputStream in)\n throws IOException {\n // note, here we don't need in.defaultReadObject();\n // because MyClass has no other state to deserialize\n super.setNonSerializableProperty(new NonSerializableClass(in.readInt()));\n }\n}\n\n/* this class must have no-arg constructor accessible to MyClass */\nclass MyClass2 {\n\n /* this property must be gettable/settable by MyClass. It cannot be final, therefore. */\n private NonSerializableClass nonSerializableProperty;\n\n public void setNonSerializableProperty(NonSerializableClass nonSerializableProperty) {\n this.nonSerializableProperty = nonSerializableProperty;\n }\n\n public NonSerializableClass getNonSerializableProperty() {\n return nonSerializableProperty;\n }\n}\n\nclass NonSerializableClass{\n\n private final int quantity;\n\n public NonSerializableClass(int quantity){\n this.quantity = quantity;\n }\n\n public int getQuantity() {\n return quantity;\n }\n}\n" }, { "answer_id": 13347836, "author": "Radim Burget", "author_id": 1168635, "author_profile": "https://Stackoverflow.com/users/1168635", "pm_score": 4, "selected": false, "text": "private transient SomeClass myClz;\n object->bytes->object Kryo kryo = new Kryo();\n// #### Store to disk...\nOutput output = new Output(new FileOutputStream(\"file.bin\"));\nSomeClass someObject = ...\nkryo.writeObject(output, someObject);\noutput.close();\n// ### Restore from disk...\nInput input = new Input(new FileInputStream(\"file.bin\"));\nSomeClass someObject = kryo.readObject(input, SomeClass.class);\ninput.close();\n kryo.register(SomeObject.class, new DeflateCompressor(new FieldSerializer(kryo, SomeObject.class)));\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12860/" ]
95,183
<p>How do I create an index on the date part of DATETIME field?</p> <pre><code>mysql&gt; SHOW COLUMNS FROM transactionlist; +-------------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------------+------------------+------+-----+---------+----------------+ | TransactionNumber | int(10) unsigned | NO | PRI | NULL | auto_increment | | WagerId | int(11) | YES | MUL | 0 | | | TranNum | int(11) | YES | MUL | 0 | | | TranDateTime | datetime | NO | | NULL | | | Amount | double | YES | | 0 | | | Action | smallint(6) | YES | | 0 | | | Uid | int(11) | YES | | 1 | | | AuthId | int(11) | YES | | 1 | | +-------------------+------------------+------+-----+---------+----------------+ 8 rows in set (0.00 sec) </code></pre> <p>TranDateTime is used to save the date and time of a transaction as it happens</p> <p>My Table has over 1,000,000 records in it and the statement </p> <pre><code>SELECT * FROM transactionlist where date(TranDateTime) = '2008-08-17' </code></pre> <p>takes a long time.</p> <p>EDIT: </p> <p>Have a look at this blog post on "<a href="http://billauer.co.il/blog/2009/03/mysql-datetime-epoch-unix-time/" rel="noreferrer">Why MySQL’s DATETIME can and should be avoided</a>"</p>
[ { "answer_id": 95252, "author": "Clinton Pierce", "author_id": 8173, "author_profile": "https://Stackoverflow.com/users/8173", "pm_score": 3, "selected": false, "text": " select * from translist \n where TranDateTime > '2008-08-16 23:59:59'\n and TranDateTime < '2008-08-18 00:00:00'\n" }, { "answer_id": 95256, "author": "Michael Johnson", "author_id": 17688, "author_profile": "https://Stackoverflow.com/users/17688", "pm_score": 7, "selected": true, "text": "SELECT * FROM transactionlist \nWHERE TranDateTime BETWEEN '2008-08-17' AND '2008-08-17 23:59:59.999999';\n" }, { "answer_id": 95759, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": 3, "selected": false, "text": "SELECT * FROM transactionlist WHERE TranDateTime BETWEEN '2008-08-17' AND '2008-08-18'\n" }, { "answer_id": 2424539, "author": "antonia007", "author_id": 291421, "author_profile": "https://Stackoverflow.com/users/291421", "pm_score": 1, "selected": false, "text": "SELECT * FROM translist \nWHERE TranDateTime >= '2008-08-17 00:00:00.0000'\n AND TranDateTime < '2008-08-18 00:00:00.0000'\n 00:00:00.0000 00:00" }, { "answer_id": 6979909, "author": "Mari", "author_id": 883727, "author_profile": "https://Stackoverflow.com/users/883727", "pm_score": -1, "selected": false, "text": "convert(datetime, left(date_field,10))" }, { "answer_id": 44548610, "author": "Liran Brimer", "author_id": 1924716, "author_profile": "https://Stackoverflow.com/users/1924716", "pm_score": 4, "selected": false, "text": "CREATE TABLE `table` (\n`my_datetime` datetime NOT NULL,\n`my_date` varchar(12) GENERATED ALWAYS AS (DATE(`my_datetime`)) STORED,\nKEY `my_idx` (`my_date`)\n) ENGINE=InnoDB;\n" }, { "answer_id": 53773972, "author": "Walf", "author_id": 315024, "author_profile": "https://Stackoverflow.com/users/315024", "pm_score": 0, "selected": false, "text": "+-------------------+------------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+-------------------+------------------+------+-----+---------+----------------+\n| TransactionNumber | int(10) unsigned | NO | PRI | NULL | auto_increment |\n| WagerId | int(11) | YES | MUL | 0 | |\n| TranNum | int(11) | YES | MUL | 0 | |\n| TranDate | date | NO | | NULL | |\n| TranTime | time | NO | | NULL | |\n| Amount | double | YES | | 0 | |\n| Action | smallint(6) | YES | | 0 | |\n| Uid | int(11) | YES | | 1 | |\n| AuthId | int(11) | YES | | 1 | |\n+-------------------+------------------+------+-----+---------+----------------+\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17560/" ]
95,192
<p>Our CruiseControl system checks out from starteam. I've noticed that it is sometimes not checking out new versions of files, only added files.</p> <p>Does anyone know why this is?</p>
[ { "answer_id": 95353, "author": "dgvid", "author_id": 9897, "author_profile": "https://Stackoverflow.com/users/9897", "pm_score": 1, "selected": false, "text": "delete-local -q -p &quot;${starteam_project_root}&quot; -is -filter &quot;N&quot; -cfgd &quot;${exec_time}&quot;\n delete-local -q -p \"user:passwd@SERVER:49201/ProjectName/\" -is -filter \"N\"-cfgd \"09/18/2008 14:33:22\"\n" }, { "answer_id": 10252893, "author": "Eddddddddddd1", "author_id": 1325181, "author_profile": "https://Stackoverflow.com/users/1325181", "pm_score": 1, "selected": false, "text": " <prebuild>\n <exec>\n <executable>C:\\Program Files\\Borland\\StarTeam Cross-Platform Client 2006 R2\\stcmd.exe</executable >\n <buildArgs>update-status -nologo -is -q -p \"username:password@192.168.0.1:49201/Code Project/Code Path\" -fp \"C:\\projects\\My Code Directory\"</buildArgs>\n <buildTimeoutSeconds>0</buildTimeoutSeconds>\n </exec>\n </prebuild>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
95,211
<p>I want to generate a Makefile from an existing Xcode project on the Mac. Specifically, an existing iPhone, Objective-C program on the Mac.</p> <p>I found <a href="http://members.bellatlantic.net/%7Evze35xda/software.html" rel="noreferrer">PBToMake</a>, but it looks like it is for Xcode 2.1 and when I tried using it, it did not work for an Xcode 3.1 project.</p>
[ { "answer_id": 95653, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 1, "selected": false, "text": "xcodebuild" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5284/" ]
95,213
<p>Simple example: I want to have some items on a page (like divs or table rows), and I want to let the user click on them to select them. That seems easy enough in jQuery. To save which items a user clicks on with no server-side post backs, I was thinking a cookie would be a simple way to get this done.</p> <ol> <li>Is this assumption that a cookie is OK in this case, correct?</li> <li>If it is correct, does the jQuery API have some way to read/write cookie information that is nicer than the default JavaScript APIs?</li> </ol>
[ { "answer_id": 95351, "author": "Steve Moyer", "author_id": 17008, "author_profile": "https://Stackoverflow.com/users/17008", "pm_score": 4, "selected": false, "text": "$.cookie('cookie_name', 'cookie_value') $.cookie('cookie_name', 'cookie_value', 'cookie_expiration\") document.cookie = \"name=value; expires=date; domain=domain; path=path; secure\"\n" }, { "answer_id": 2210411, "author": "adam", "author_id": 116718, "author_profile": "https://Stackoverflow.com/users/116718", "pm_score": 6, "selected": false, "text": "document.cookie = 'mycookie=valueOfCookie;expires=DateHere;path=/'\n $.cookie('mycookie', 'valueOfCookie')\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5619/" ]
95,218
<p>Here's something I haven't been able to fix, and I've looked <strong>everywhere</strong>. Perhaps someone here will know!</p> <p>I have a table called dandb_raw, with three columns in particular: dunsId (PK), name, and searchName. I also have a trigger that acts on this table:</p> <pre><code>SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER TRIGGER [dandb_raw_searchNames] ON [dandb_raw] FOR INSERT, UPDATE AS SET NOCOUNT ON select dunsId, name into #magic from inserted UPDATE dandb SET dandb.searchName = company_generateSearchName(dandb.name) FROM (select dunsId, name from #magic) i INNER JOIN dandb_raw dandb on i.dunsId = dandb.dunsId --Add new search matches SELECT c.companyId, dandb.dunsId INTO #newMatches FROM dandb_raw dandb INNER JOIN (select dunsId, name from #magic) a on a.dunsId = dandb.dunsId INNER JOIN companies c ON dandb.searchName = c.searchBrand --avoid url matches that are potentially wrong AND (lower(dandb.url) = lower(c.url) OR dandb.url = '' OR c.url = '' OR c.url is null) INSERT INTO #newMatches (companyId, dunsId) SELECT c.companyId, max(dandb.dunsId) dunsId FROM dandb_raw dandb INNER JOIN ( select case when charindex('/',url) &lt;&gt; 0 then left(url, charindex('/',url)-1) else url end urlMatch, * from companies ) c ON dandb.url = c.urlMatch where subsidiaryOf = 1 and isReported = 1 and dandb.url &lt;&gt; '' and c.companyId not in (select companyId from #newMatches) group by companyId having count(dandb.dunsId) = 1 UPDATE cd SET cd.dunsId = nm.dunsId FROM companies_dandb cd INNER JOIN #newMatches nm ON cd.companyId = nm.companyId GO </code></pre> <p>The trigger causes inserts to fail:</p> <pre><code>insert into [dandb_raw](dunsId, name) select 3442355, 'harper' union all select 34425355, 'har 466per' update [dandb_raw] set name ='grap6767e' </code></pre> <p>With this error:</p> <pre><code>Msg 213, Level 16, State 1, Procedure companies_contactInfo_updateTerritories, Line 20 Insert Error: Column name or number of supplied values does not match table definition. </code></pre> <p>The most curious thing about this is that each of the individual statements in the trigger works on its own. It's almost as though inserted is a one-off table that infects temporary tables if you try to move inserted into one of them.</p> <p>So what causes the trigger to fail? How can it be stopped?</p>
[ { "answer_id": 95768, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": false, "text": "CREATE TABLE #newMatches\n(\n CompanyID int PRIMARY KEY,\n DunsID int\n)\n DROP TABLE #newMatches\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40352/" ]
95,222
<p>I found this link <a href="http://artis.imag.fr/~Xavier.Decoret/resources/glsl-mode/" rel="noreferrer">http://artis.imag.fr/~Xavier.Decoret/resources/glsl-mode/</a>, but there isn't a lot of description around it, aside that it's "simple".</p> <p>Ideally, I'd like an extension to CcMode that can do it, or at least a mode that can handle auto-styling and has similar shortcuts to CcMode.</p> <p>If there isn't one, any good elisp references to help me get started writing it myself would be greatly appreciated.</p> <p>EDIT: David's response prompted me to take a closer look at glsl-mode.el, and it is in fact based on cc-mode, so it's exactly what I was looking for in the first place.</p>
[ { "answer_id": 95494, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 5, "selected": true, "text": "(autoload 'glsl-mode \"glsl-mode\" nil t)\n(add-to-list 'auto-mode-alist '(\"\\\\.vert\\\\'\" . glsl-mode))\n(add-to-list 'auto-mode-alist '(\"\\\\.frag\\\\'\" . glsl-mode))\n (setq load-path (cons \"~/.emacs.d\" load-path))\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13894/" ]
95,257
<p>I just want a quick way (and preferably not using a while loop)of createing a table of every date between date @x and date @y so I can left outer join to some stats tables, some of which will have no records for certain days in between, allowing me to mark missing days with a 0</p>
[ { "answer_id": 95517, "author": "digiguru", "author_id": 5055, "author_profile": "https://Stackoverflow.com/users/5055", "pm_score": 0, "selected": false, "text": "Declare @FromDate datetime, \n @ToDate datetime \nDeclare @tmpDates table \n (StatsDate datetime)\nSet @FromDate = DateAdd(day,-30,GetDate())\nSet @ToDate = GetDate()\n\nInsert Into @tmpDates (StatsDate)\nSelect \n distinct CAST(FLOOR(CAST(visitDate AS DECIMAL(12, 5))) AS DATETIME)\nFROM tbl_visitorstats \nWhere visitDate between @FromDate And @ToDate \nOrder By CAST(FLOOR(CAST(visitDate AS DECIMAL(12, 5))) AS DATETIME) \n\n\nSelect * FROM @tmpDates\n" }, { "answer_id": 95728, "author": "BigJump", "author_id": 8542, "author_profile": "https://Stackoverflow.com/users/8542", "pm_score": 5, "selected": true, "text": "WITH numbers ( n ) AS (\n SELECT 1 UNION ALL\n SELECT 1 + n FROM numbers WHERE n < 500 )\n SELECT DATEADD(day,n-1,'2008/11/01') FROM numbers\n OPTION ( MAXRECURSION 500 )\n" }, { "answer_id": 95963, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": -1, "selected": false, "text": "DECLARE @Dates TABLE\n(\n TheDate datetime PRIMARY KEY\n)\nDECLARE @StartDate datetime, @EndDate datetime\nSELECT @StartDate = '2000-01-01', @EndDate = '2010-01-01'\n\n\nDECLARE @LoopVar int, @LoopEnd int \nSELECT @LoopEnd = DateDiff(dd, @StartDate, @EndDate), @LoopVar = 0\n\n\nWHILE @LoopVar <= @LoopEnd\nBEGIN\n INSERT INTO @Dates (TheDate)\n SELECT DateAdd(dd,@LoopVar,@StartDate)\n\n SET @LoopVar = @LoopVar + 1\nEND\n\n\nSELECT *\nFROM @Dates\n" }, { "answer_id": 96053, "author": "Garry Shutler", "author_id": 6369, "author_profile": "https://Stackoverflow.com/users/6369", "pm_score": 1, "selected": false, "text": "select ...\nfrom Calendar\n left outer join\n ...\nwhere Calendar.Date >= @x\nand Calendar.Date <= @y\n" }, { "answer_id": 36001142, "author": "Adrian Russell", "author_id": 395440, "author_profile": "https://Stackoverflow.com/users/395440", "pm_score": 0, "selected": false, "text": "DECLARE @startDate datetime\nSET @startDate = '2015/5/29';\n\nWITH number ( n ) AS (\n SELECT 1 UNION ALL\n SELECT 1 + n FROM dates WHERE n < DATEDIFF(Day, @startDate, GETDATE()) )\n SELECT DATEADD(day,n-1,@startDate) FROM number where\n datename(dw, DATEADD(day,n-1,@startDate)) in ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday')\n OPTION ( MAXRECURSION 500 )\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5055/" ]
95,277
<p>I'd like to be able to create a parameterized query in MS Access 2003 and feed the values of certain form elements to that query and then get the corresponding resultset back and do some basic calculations with them. I'm coming up short in figuring out how to get the parameters of the query to be populated by the form elements. If I have to use VBA, that's fine.</p>
[ { "answer_id": 96047, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 1, "selected": false, "text": "Set db = CurrentDb\n\nSet qdf = db.QueryDefs(\"AddHospital\")\nqdf.Parameters!txtHospital = Trim(Me.HospName)\nqdf.ReturnsRecords = False\n\nqdf.Execute dbFailOnError\n\nintResult = qdf.RecordsAffected\n PARAMETERS txtHospital Text(255); \n\nINSERT INTO tblHospitals ( \n[Hospital] )\n\nVALUES ( \n[txtHospital] )\n" }, { "answer_id": 96128, "author": "Philippe Grondier", "author_id": 11436, "author_profile": "https://Stackoverflow.com/users/11436", "pm_score": 0, "selected": false, "text": "Select Tbl_Country.* From Tbl_Country WHERE id_Country = _\n [?enter ISO code of the country]\n fid_Country id_Country qr = \"Select Tbl_Country.* From Tbl_Country WHERE id_Country = [fid_country]\"\n Dim ctl as Control\nFor each ctl in Me.controls\n If instr(qr,\"[\" & ctl.name & \"]\") > 0 Then\n qr = replace(qr,\"[\" & ctl.name & \"]\",ctl.value)\n End if\nNext i\n qr = \"Select Tbl_Country.* From Tbl_Country WHERE id_Country = \"\"GB\"\"\"\n Set rsQuery = currentDb.openRecordset(qr)\n" }, { "answer_id": 96134, "author": "BIBD", "author_id": 685, "author_profile": "https://Stackoverflow.com/users/685", "pm_score": 1, "selected": false, "text": "[?enter ISO code of the country] [Forms]![MyForm]![LastName] 'Ed. Start - for completion of the example\ndim qryStartDate as date\ndim qryEndDate as date\nqryStartDate = #2001-01-01# \nqryEndDate = #2010-01-01# \n'Ed. End\n\n'QUOTEING \"stallyon\": To pass parameters to a query in VBA \n' is really quite simple:\n\n'First we'll set some variables:\nDim qdf As Querydef\nDim rst As Recordset\n\n'then we'll open up the query:\nSet qdf = CurrentDB.QueryDefs(qryname)\n\n'Now we'll assign values to the query using the parameters option:\nqdf.Parameters(0) = qryStartDate\nqdf.Parameters(1) = qryEndDate\n\n'Now we'll convert the querydef to a recordset and run it\nSet rst = qdf.OpenRecordset\n\n'Run some code on the recordset\n'Close all objects\nrst.Close\nqdf.Close\nSet rst = Nothing\nSet qdf = Nothing\n '...\nDim qdf As DAO.QueryDef\nDim prmOne As DAO.Parameter\nDim prmTwo As DAO.Parameter\nDim rst as recordset\n '...\n 'open up the query:\n Set qdf = db.QueryDefs(\"my_two_param_query\") 'params called param_one and \n 'param_two\n\n 'link your DAP.Parameters to the query\n Set prmOne = qdf.Parameters!param_one\n Set prmTwo = qdf.Parameters!param_two\n\n 'set the values of the parameters\n prmOne = 1 \n prmTwo = 2\n\n Set rst = qdf.OpenRecordset(dbOpenDynaset, _\n dbSeeChanges)\n '... treat the recordset as normal\n\n 'make sure you clean up after your self\n Set rst = Nothing\n Set prmOne = Nothing\n Set prmTwo = Nothing\n Set qdf = Nothing\n" }, { "answer_id": 97350, "author": "David-W-Fenton", "author_id": 9787, "author_profile": "https://Stackoverflow.com/users/9787", "pm_score": 2, "selected": false, "text": "LastName = Forms!MyForm!LastName\n PARAMETERS [[Forms]!MyForm![LastName]] Text ( 255 );\nSELECT tblCustomers.*\nFROM tblCustomers\nWHERE tblCustomers.LastName=[Forms]![MyForm]![LastName];\n" }, { "answer_id": 48668448, "author": "Mart", "author_id": 5179566, "author_profile": "https://Stackoverflow.com/users/5179566", "pm_score": 0, "selected": false, "text": "DoCmd.SetParameter \"frontMthOffset\", -3\nDoCmd.SetParameter \"endMthOffset\", -2\nDoCmd.OpenQuery \"QryShowDifference_ValuesChangedBetweenSELECTEDMonths\"\n \"select blah from mytable where dateoffset=[frontMthOffset]\"\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16562/" ]
95,286
<p>I have the following configuration, but I have not able to find any documentation on how to set a maximum backup files on date rolling style. I know that you can do this with size rolling style by using the maxSizeRollBackups.</p> <pre><code>&lt;appender name="AppLogFileAppender" type="log4net.Appender.RollingFileAppender"&gt; &lt;file value="mylog.log" /&gt; &lt;appendToFile value="true" /&gt; &lt;lockingModel type="log4net.Appender.FileAppender+MinimalLock" /&gt; &lt;rollingStyle value="Date" /&gt; &lt;datePattern value=".yyMMdd.'log'" /&gt; &lt;layout type="log4net.Layout.PatternLayout"&gt; &lt;conversionPattern value="%d %-5p %c - %m%n" /&gt; &lt;/layout&gt; &lt;/appender&gt; </code></pre>
[ { "answer_id": 95390, "author": "wcm", "author_id": 2173, "author_profile": "https://Stackoverflow.com/users/2173", "pm_score": 2, "selected": false, "text": " <appender name=\"RollingFile\" type=\"log4net.Appender.RollingFileAppender\">\n <param name=\"File\" value=\"App_Data\\log\"/>\n <param name=\"DatePattern\" value=\".yyyy-MM-dd-tt&quot;.log&quot;\"/>\n <param name=\"AppendToFile\" value=\"true\"/>\n <param name=\"RollingStyle\" value=\"Date\"/>\n <param name=\"StaticLogFileName\" value=\"false\"/>\n <param name=\"maxSizeRollBackups\" value=\"60\" />\n <layout type=\"log4net.Layout.PatternLayout\">\n <param name=\"ConversionPattern\" value=\"%r %d [%t] %-5p %c - %m%n\"/>\n </layout>\n </appender>\n" }, { "answer_id": 2916628, "author": "Jeff", "author_id": 303284, "author_profile": "https://Stackoverflow.com/users/303284", "pm_score": 5, "selected": false, "text": " <appender name=\"RollingLogFileAppender\" type=\"log4net.Appender.RollingFileAppender\">\n <file value=\"C:\\logs\\LoggingTest\\logfile.txt\" />\n <appendToFile value=\"true\" />\n <rollingStyle value=\"Composite\" />\n <datePattern value=\"yyyyMMdd\" />\n <maxSizeRollBackups value=\"10\" />\n <maximumFileSize value=\"1MB\" />\n <layout type=\"log4net.Layout.PatternLayout\">\n <conversionPattern value=\"%date - %message%newline\" />\n </layout>\n </appender>\n XmlConfigurator.Configure();\n var date = DateTime.Now.AddDays(-10);\n var task = new LogFileCleanupTask();\n task.CleanUp(date);\n using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\n\nusing log4net;\nusing log4net.Appender;\nusing log4net.Config;\n\n public class LogFileCleanupTask\n {\n #region - Constructor -\n public LogFileCleanupTask()\n {\n }\n #endregion\n\n #region - Methods -\n /// <summary>\n /// Cleans up. Auto configures the cleanup based on the log4net configuration\n /// </summary>\n /// <param name=\"date\">Anything prior will not be kept.</param>\n public void CleanUp(DateTime date)\n {\n string directory = string.Empty;\n string filePrefix = string.Empty;\n\n var repo = LogManager.GetAllRepositories().FirstOrDefault(); ;\n if (repo == null)\n throw new NotSupportedException(\"Log4Net has not been configured yet.\");\n\n var app = repo.GetAppenders().Where(x => x.GetType() == typeof(RollingFileAppender)).FirstOrDefault();\n if (app != null)\n {\n var appender = app as RollingFileAppender;\n\n directory = Path.GetDirectoryName(appender.File);\n filePrefix = Path.GetFileName(appender.File);\n\n CleanUp(directory, filePrefix, date);\n }\n }\n\n /// <summary>\n /// Cleans up.\n /// </summary>\n /// <param name=\"logDirectory\">The log directory.</param>\n /// <param name=\"logPrefix\">The log prefix. Example: logfile dont include the file extension.</param>\n /// <param name=\"date\">Anything prior will not be kept.</param>\n public void CleanUp(string logDirectory, string logPrefix, DateTime date)\n {\n if (string.IsNullOrEmpty(logDirectory))\n throw new ArgumentException(\"logDirectory is missing\");\n\n if (string.IsNullOrEmpty(logPrefix))\n throw new ArgumentException(\"logPrefix is missing\");\n\n var dirInfo = new DirectoryInfo(logDirectory);\n if (!dirInfo.Exists)\n return;\n\n var fileInfos = dirInfo.GetFiles(\"{0}*.*\".Sub(logPrefix));\n if (fileInfos.Length == 0)\n return;\n\n foreach (var info in fileInfos)\n {\n if (info.CreationTime < date)\n {\n info.Delete();\n }\n }\n\n }\n #endregion\n }\n /// <summary>\n/// Extension helper methods for strings\n/// </summary>\n[DebuggerStepThrough, DebuggerNonUserCode]\npublic static class StringExtensions\n{\n /// <summary>\n /// Formats a string using the <paramref name=\"format\"/> and <paramref name=\"args\"/>.\n /// </summary>\n /// <param name=\"format\">The format.</param>\n /// <param name=\"args\">The args.</param>\n /// <returns>A string with the format placeholders replaced by the args.</returns>\n public static string Sub(this string format, params object[] args)\n {\n return string.Format(format, args);\n }\n}\n" }, { "answer_id": 15364915, "author": "mattezell", "author_id": 159720, "author_profile": "https://Stackoverflow.com/users/159720", "pm_score": 2, "selected": false, "text": " //.........................\n //Log Config Stuff Above...\n\n log4net.Config.BasicConfigurator.Configure(fileAppender);\n if(logConfig.DaysToKeep > 0)\n CleanupLogs(logConfig.LogFilePath, logConfig.DaysToKeep);\n}\n\nstatic void CleanupLogs(string logPath, int maxAgeInDays)\n{\n if (File.Exists(logPath))\n {\n var datePattern = \"yyyy.MM.dd\";\n List<string> logPatternsToKeep = new List<string>();\n for (var i = 0; i <= maxAgeInDays; i++)\n {\n logPatternsToKeep.Add(DateTime.Now.AddDays(-i).ToString(datePattern));\n }\n\n FileInfo fi = new FileInfo(logPath);\n\n var logFiles = fi.Directory.GetFiles(fi.Name + \"*\")\n .Where(x => logPatternsToKeep.All(y => !x.Name.Contains(y) && x.Name != fi.Name));\n\n foreach (var log in logFiles)\n {\n if (File.Exists(log.FullName)) File.Delete(log.FullName);\n }\n }\n}\n" }, { "answer_id": 70396398, "author": "HouseCat", "author_id": 3072640, "author_profile": "https://Stackoverflow.com/users/3072640", "pm_score": 0, "selected": false, "text": "public string LogPath { get; set; }\npublic int MaxFileCount { get; set; } = 10;\n\nprivate FileSystemWatcher _fileSystemWatcher;\n\n[PermissionSet(SecurityAction.Demand, Name = \"FullTrust\")]\npublic async Task StartAsync()\n{\n await Task.Yield();\n\n if (!Directory.Exists(LogPath))\n { Directory.CreateDirectory(LogPath); }\n\n _fileSystemWatcher = new FileSystemWatcher\n {\n Filter = \"*.*\",\n Path = LogPath,\n EnableRaisingEvents = true,\n NotifyFilter = NotifyFilters.FileName\n | NotifyFilters.LastAccess\n | NotifyFilters.LastWrite\n | NotifyFilters.Security\n | NotifyFilters.Size\n };\n\n _fileSystemWatcher.Created += OnCreated;\n}\n\npublic async Task StopAsync()\n{\n await Task.Yield();\n\n _fileSystemWatcher.Created -= OnCreated; // prevents a resource / memory leak.\n _fileSystemWatcher = null; // not using dispose allows us to re-start if necessary.\n}\n\nprivate void OnCreated(object sender, FileSystemEventArgs e)\n{\n var fileInfos = Directory\n .GetFiles(LogPath)\n .Select(filePath => new FileInfo(filePath))\n .OrderBy(fileInfo => fileInfo.LastWriteTime)\n .ToArray();\n\n if (fileInfos.Length <= MaxFileCount)\n { return; }\n\n // For every file (over MaxFileCount) delete, starting with the oldest file.\n for (var i = 0; i < fileInfos.Length - MaxFileCount; i++)\n {\n try\n {\n fileInfos[i].Delete();\n }\n catch (Exception ex)\n {\n /* Handle */\n }\n }\n}\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4191/" ]
95,305
<p>Most of my users have email addresses associated with their profile in <code>/etc/passwd</code>. They are always in the 5th field, which I can grab, but they appear at different places within a comma-separated list in the 5th field.</p> <p>Can somebody give me a <strong>regex to grab just the email address</strong> (delimeted by commas) from a line in this file? (I will be using grep and sed from a bash script)</p> <p>Sample lines from file:</p> <pre><code>user1:x:1147:5005:User One,Department,,,email@domain.org:/home/directory:/bin/bash user2:x:1148:5002:User Two,Department2,email2@gmail.com,:/home/directory:/bin/bash </code></pre>
[ { "answer_id": 95344, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": -1, "selected": false, "text": "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\n" }, { "answer_id": 95474, "author": "reefnet_alex", "author_id": 2745, "author_profile": "https://Stackoverflow.com/users/2745", "pm_score": 3, "selected": false, "text": "awk -F : '{print $5}' /etc/passwd\n awk -F , '{print $1}'\n awk -F : '{print $5}' /etc/passwd | awk -F , '{print $1}'\n" }, { "answer_id": 95860, "author": "Brent ", "author_id": 3764, "author_profile": "https://Stackoverflow.com/users/3764", "pm_score": 2, "selected": false, "text": "sed -r -e \"s/^.*[,:]([^,:]+@[^,:]+).*$/\\1/g\" /etc/passwd\n" }, { "answer_id": 97803, "author": "Marcio Aguiar", "author_id": 4213, "author_profile": "https://Stackoverflow.com/users/4213", "pm_score": -1, "selected": false, "text": "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])\n" }, { "answer_id": 2474985, "author": "ghostdog74", "author_id": 131527, "author_profile": "https://Stackoverflow.com/users/131527", "pm_score": 0, "selected": false, "text": "sed 's/,*:\\/.*//;s/^.*://;s/.*,//' /etc/passwd\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3764/" ]
95,361
<p>I'm programming in C++ on Visual Studio 2005. My question deals with .rc files. You can manually place include directives like (#include "blah.h"), at the top of an .rc file. But that's bad news since the first time someone opens the .rc file in the resource editor, it gets overwritten. I know there is a place to make these defines so that they don't get trashed but I can't find it and googling hasn't helped. Anyone know?</p>
[ { "answer_id": 95718, "author": "dgvid", "author_id": 9897, "author_profile": "https://Stackoverflow.com/users/9897", "pm_score": 4, "selected": true, "text": "2 TEXTINCLUDE\nBEGIN\n \"#include \"\"windows.h\"\"\\r\\n\"\n \"#include \"\"blah.h\\r\\n\"\n \"\\0\"\n END\n" }, { "answer_id": 96257, "author": "Andrei Belogortseff", "author_id": 17037, "author_profile": "https://Stackoverflow.com/users/17037", "pm_score": 2, "selected": false, "text": "#ifdef WIN64\n#include \"Icons64.rc\"\n#else\n#include \"Icons32.rc\"\n#endif\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
95,364
<p>I have a LINQ to SQL generated class with a readonly property:</p> <pre><code>&lt;Column(Name:="totalLogins", Storage:="_TotalLogins", DbType:="Int", UpdateCheck:=UpdateCheck.Never)&gt; _ Public ReadOnly Property TotalLogins() As System.Nullable(Of Integer) Get Return Me._TotalLogins End Get End Property </code></pre> <p>This prevents it from being changed externally, but I would like to update the property from within my class like below:</p> <pre><code>Partial Public Class User ... Public Shared Sub Login(Username, Password) ValidateCredentials(UserName, Password) Dim dc As New MyDataContext() Dim user As User = (from u in dc.Users select u where u.UserName = Username)).FirstOrDefault() user._TotalLogins += 1 dc.SubmitChanges() End Sub ... End Class </code></pre> <p>But the call to user._TotalLogins += 1 is not being written to the database? Any thoughts on how to get LINQ to see my changes?</p>
[ { "answer_id": 96076, "author": "chrissie1", "author_id": 2936, "author_profile": "https://Stackoverflow.com/users/2936", "pm_score": 0, "selected": false, "text": "Make a second property that is protected or internal(?) \n\n<Column(Name:=\"totalLogins\", Storage:=\"_TotalLogins\", DbType:=\"Int\", UpdateCheck:=UpdateCheck.Never)> _\nprotected Property TotalLogins2() As System.Nullable(Of Integer)\n Get\n Return Me._TotalLogins\n End Get\n Set(byval value as System.Nullable(Of Integer))\n Return Me._TotalLogins\n End Get\nEnd Property\n" }, { "answer_id": 96157, "author": "DamienG", "author_id": 5720, "author_profile": "https://Stackoverflow.com/users/5720", "pm_score": 3, "selected": true, "text": "Public ReadOnly Property TotalLogins() As System.Nullable(Of Integer)\n Get\n Return Me.InternalTotalLogins\n End Get\nEnd Property\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11991/" ]
95,378
<p>What is a tool or technique that can be used to perform spell checks upon a whole source code base and its associated resource files?</p> <p>The spell check should be <em>source code aware</em> meaning that it would stick to checking string literals in the code and not the code itself. Bonus points if the spell checker understands common resource file formats, for example text files containing name-value pairs (only check the values). Super-bonus points if you can tell it which parts of an XML DTD or Schema should be checked and which should be ignored.</p> <p>Many IDEs can do this for the file you are currently working with. The difference in what I am looking for is something that can operate upon a whole source code base at once.</p> <p>Something like a Findbugs or PMD type tool for mis-spellings would be ideal.</p>
[ { "answer_id": 96076, "author": "chrissie1", "author_id": 2936, "author_profile": "https://Stackoverflow.com/users/2936", "pm_score": 0, "selected": false, "text": "Make a second property that is protected or internal(?) \n\n<Column(Name:=\"totalLogins\", Storage:=\"_TotalLogins\", DbType:=\"Int\", UpdateCheck:=UpdateCheck.Never)> _\nprotected Property TotalLogins2() As System.Nullable(Of Integer)\n Get\n Return Me._TotalLogins\n End Get\n Set(byval value as System.Nullable(Of Integer))\n Return Me._TotalLogins\n End Get\nEnd Property\n" }, { "answer_id": 96157, "author": "DamienG", "author_id": 5720, "author_profile": "https://Stackoverflow.com/users/5720", "pm_score": 3, "selected": true, "text": "Public ReadOnly Property TotalLogins() As System.Nullable(Of Integer)\n Get\n Return Me.InternalTotalLogins\n End Get\nEnd Property\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9925/" ]
95,419
<p>Had a conversation with a coworker the other day about this.</p> <p>There's the obvious using a constructor, but what are the other ways there?</p>
[ { "answer_id": 95448, "author": "John Meagher", "author_id": 3535, "author_profile": "https://Stackoverflow.com/users/3535", "pm_score": 2, "selected": false, "text": "someClass.newInstance();\n" }, { "answer_id": 2103107, "author": "Thomas Lötzer", "author_id": 3587, "author_profile": "https://Stackoverflow.com/users/3587", "pm_score": 4, "selected": false, "text": "String.class.newInstance()" }, { "answer_id": 2103118, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 3, "selected": false, "text": " Object myObj = Class.forName(\"your.cClass\").newInstance();\n" }, { "answer_id": 2103142, "author": "ryanprayogo", "author_id": 93979, "author_profile": "https://Stackoverflow.com/users/93979", "pm_score": 2, "selected": false, "text": "SomeClass anObj = SomeClass.class.newInstance();\n" }, { "answer_id": 2103314, "author": "Roman", "author_id": 100516, "author_profile": "https://Stackoverflow.com/users/100516", "pm_score": 2, "selected": false, "text": "Foo fooClone = fooOriginal.clone (); \n" }, { "answer_id": 2103578, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 6, "selected": false, "text": "Class.newInstance Constructor.newInstance Object.clone new String ... throw null; \"\".toCharArray()[0] new" }, { "answer_id": 5104598, "author": "Bozho", "author_id": 203907, "author_profile": "https://Stackoverflow.com/users/203907", "pm_score": 2, "selected": false, "text": "new clazz.newInstance() clazz.getConstructor(..).newInstance(..)" }, { "answer_id": 5104630, "author": "kamaci", "author_id": 453596, "author_profile": "https://Stackoverflow.com/users/453596", "pm_score": 9, "selected": true, "text": "new MyObject object = new MyObject();\n Class.forName() MyObject object = (MyObject) Class.forName(\"subin.rnd.MyObject\").newInstance();\n clone() MyObject anotherObject = new MyObject();\nMyObject object = (MyObject) anotherObject.clone();\n object deserialization ObjectInputStream inStream = new ObjectInputStream(anInputStream );\nMyObject object = (MyObject) inStream.readObject();\n" }, { "answer_id": 5104913, "author": "Paŭlo Ebermann", "author_id": 600500, "author_profile": "https://Stackoverflow.com/users/600500", "pm_score": 3, "selected": false, "text": " A[] array = new A[len];\n A[] array = new A[] { value0, value1, value2 };\n A[] array = (A[]) Array.newInstance(A.class, len);\n" }, { "answer_id": 5105730, "author": "Peter Lawrey", "author_id": 57695, "author_profile": "https://Stackoverflow.com/users/57695", "pm_score": 3, "selected": false, "text": "anewarray multianewarray newarray new" }, { "answer_id": 6000453, "author": "K.V.Subrahmanya Reddy", "author_id": 753398, "author_profile": "https://Stackoverflow.com/users/753398", "pm_score": 2, "selected": false, "text": "MyObject object = new MyObject();//normal way\n ClassName ObgRef=ClassName.FactoryMethod();\n RunTime rt=Runtime.getRunTime();//Static Factory Method\n clone() clone() MyObjectName anotherObject = new MyObjectName();\nMyObjectName object = anotherObjectName.clone();//cloning Object\n MyObjectName object = (MyObjectNmae) Class.forName(\"PackageName.ClassName\").newInstance();\n String st=(String)Class.forName(\"java.lang.String\").newInstance();\n ObjectInputStreamName inStream = new ObjectInputStreamName(anInputStream );\nMyObjectName object = (MyObjectNmae) inStream.readObject();\n" }, { "answer_id": 24379913, "author": "Deepak Sharma", "author_id": 1047565, "author_profile": "https://Stackoverflow.com/users/1047565", "pm_score": -1, "selected": false, "text": "String s =\"Hello\";\n" }, { "answer_id": 31313449, "author": "Andriya", "author_id": 4939075, "author_profile": "https://Stackoverflow.com/users/4939075", "pm_score": 2, "selected": false, "text": "Employee object = new Employee();\n Employee object2 = (Employee) Class.forName(NewEmployee).newInstance();\n Employee secondObject = new Employee();\nEmployee object3 = (Employee) secondObject.clone();\n Object object4 = Employee.class.getClassLoader().loadClass(NewEmployee).newInstance();\n // Create Object5\n// create a new file with an ObjectOutputStream\nFileOutputStream out = new FileOutputStream(\"\");\nObjectOutputStream oout = new ObjectOutputStream(out);\n\n// write something in the file\noout.writeObject(object3);\noout.flush();\n\n// create an ObjectInputStream for the file we created before\nObjectInputStream ois = new ObjectInputStream(new FileInputStream(\"crunchify.txt\"));\nEmployee object5 = (Employee) ois.readObject();\n" }, { "answer_id": 40689708, "author": "Naresh Joshi", "author_id": 2078093, "author_profile": "https://Stackoverflow.com/users/2078093", "pm_score": 4, "selected": false, "text": "new Employee emp1 = new Employee();\n newInstance() Class Employee emp2 = (Employee) Class.forName(\"org.programming.mitra.exercises.Employee\")\n .newInstance();\n Employee emp2 = Employee.class.newInstance();\n newInstance() Constructor Constructor<Employee> constructor = Employee.class.getConstructor();\nEmployee emp3 = constructor.newInstance();\n clone() Employee emp4 = (Employee) emp3.clone();\n ObjectInputStream in = new ObjectInputStream(new FileInputStream(\"data.obj\"));\nEmployee emp5 = (Employee) in.readObject();\n new newInstance()" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1247/" ]
95,432
<p>I'd like to create a hotkey to search for files <strong>under a specific folder</strong> in Windows XP; I'm using AutoHotkey to create this shortcut.</p> <p>Problem is that I need to know a command-line statement to run in order to open the standard Windows "Find Files/Folders" dialog. I've googled for a while and haven't found any page indicating how to do this.</p> <p>I'm assuming that if I know the command-line statement for bringing up this prompt, it will allow me to pass in a parameter for what folder I want to be searching under. I know you can do this by right-clicking on a folder in XP, so I assume there's some way I could do it on the command line...?</p>
[ { "answer_id": 95502, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 0, "selected": false, "text": "Win+f" }, { "answer_id": 95580, "author": "Charles Roper", "author_id": 1944, "author_profile": "https://Stackoverflow.com/users/1944", "pm_score": 3, "selected": false, "text": "index.php D:\\home locate32.exe -r -p D:\\home index.php\n -r -p D:\\home locate.exe" }, { "answer_id": 95638, "author": "Pascal Paradis", "author_id": 1291, "author_profile": "https://Stackoverflow.com/users/1291", "pm_score": 2, "selected": false, "text": "'ExplorerFind.vbs\nDim objShell\nSet objShell = WScript.CreateObject(\"Shell.Application\")\nobjShell.FindFiles\n" }, { "answer_id": 95640, "author": "Brian", "author_id": 2831, "author_profile": "https://Stackoverflow.com/users/2831", "pm_score": 3, "selected": true, "text": "@echo off\necho CreateObject(\"Shell.Application\").FindFiles >%temp%\\myff.vbs\ncscript.exe //Nologo %temp%\\myff.vbs\ndel %temp%\\myff.vbs\n" }, { "answer_id": 7509943, "author": "Vitim.us", "author_id": 938822, "author_profile": "https://Stackoverflow.com/users/938822", "pm_score": 2, "selected": false, "text": "search-ms:query=New%20Folder&\n search-ms:query=*.lnk&crumb=folder:%userprofile%\\Desktop&\n search-ms:query=exe&crumb=location:C:\\Program Files&\n search-ms:query=microsoft&\nsearch-ms:query=vacation&subquery=mydepartment.search-ms&\nsearch-ms:query=seattle&crumb=kind:pics& \nsearch-ms:query=seattle&crumb=folder:C:\\MyFolder&\n" }, { "answer_id": 45701457, "author": "Trevor", "author_id": 2697942, "author_profile": "https://Stackoverflow.com/users/2697942", "pm_score": 0, "selected": false, "text": "explorer.exe \"search-ms:query=*.exe&crumb=location:C:\\Program Files&\"" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1766670/" ]
95,492
<p>Given a date/time as an array of (year, month, day, hour, minute, second), how would you convert it to epoch time, i.e., the number of seconds since 1970-01-01 00:00:00 GMT?</p> <p>Bonus question: If given the date/time as a string, how would you first parse it into the (y,m,d,h,m,s) array?</p>
[ { "answer_id": 95539, "author": "dreeves", "author_id": 4234, "author_profile": "https://Stackoverflow.com/users/4234", "pm_score": 6, "selected": true, "text": "use Time::Local;\ntimelocal($second,$minute,$hour,$day,$month-1,$year);\n use Time::Local;\n\nsub parsedate { \n my($s) = @_;\n my($year, $month, $day, $hour, $minute, $second);\n\n if($s =~ m{^\\s*(\\d{1,4})\\W*0*(\\d{1,2})\\W*0*(\\d{1,2})\\W*0*\n (\\d{0,2})\\W*0*(\\d{0,2})\\W*0*(\\d{0,2})}x) {\n $year = $1; $month = $2; $day = $3;\n $hour = $4; $minute = $5; $second = $6;\n $hour |= 0; $minute |= 0; $second |= 0; # defaults.\n $year = ($year<100 ? ($year<70 ? 2000+$year : 1900+$year) : $year);\n return timelocal($second,$minute,$hour,$day,$month-1,$year); \n }\n return -1;\n}\n" }, { "answer_id": 95629, "author": "raldi", "author_id": 7598, "author_profile": "https://Stackoverflow.com/users/7598", "pm_score": -1, "selected": false, "text": "#! /usr/bin/perl -w\n\nuse strict;\n\n$_ = (join ' ', @ARGV);\n$_ ||= <STDIN>;\n\nchomp;\n\nif (/^[\\d.]+$/) {\n print scalar localtime $_;\n print \"\\n\";\n}\nelse {\n exec \"date -d '$_' +%s\";\n}\n $ Time now\n1221763842\n\n$ Time yesterday\n1221677444\n\n$ Time 1221677444\nWed Sep 17 11:50:44 2008\n\n$ Time '12:30pm jan 4 1987'\n536790600\n\n$ Time '9am 8 weeks ago'\n1216915200\n" }, { "answer_id": 95741, "author": "Martin Dorey", "author_id": 18096, "author_profile": "https://Stackoverflow.com/users/18096", "pm_score": -1, "selected": false, "text": "martind@whitewater:~$ cat `which isoToEpoch`\n#!/usr/bin/perl -w\nuse strict;\nuse Time::Piece;\n# sudo apt-get install libtime-piece-perl\nwhile (<>) {\n # date --iso=s:\n # 2007-02-15T18:25:42-0800\n # Other matched formats:\n # 2007-02-15 13:50:29 (UTC-0800)\n # 2007-02-15 13:50:29 (UTC-08:00)\n s/(\\d{4}-\\d{2}-\\d{2}([T ])\\d{2}:\\d{2}:\\d{2})(?:\\.\\d+)? ?(?:\\(UTC)?([+\\-]\\d{2})?:?00\\)?/Time::Piece->strptime ($1, \"%Y-%m-%d$2%H:%M:%S\")->epoch - (defined ($3) ? $3 * 3600 : 0)/eg;\n print;\n}\nmartind@whitewater:~$ \n" }, { "answer_id": 95838, "author": "scottc", "author_id": 7408, "author_profile": "https://Stackoverflow.com/users/7408", "pm_score": 3, "selected": false, "text": "use Date::Manip;\n$string = '18-Sep-2008 20:09'; # or a wide range of other date formats\n$unix_time = UnixDate( ParseDate($string), \"%s\" );\n" }, { "answer_id": 125869, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 3, "selected": false, "text": "$ENV{TZ}=\"GMT\";\nPOSIX::tzset();\n$time = POSIX::mktime($s,$m,$h,$d,$mo-1,$y-1900);\n" }, { "answer_id": 2499485, "author": "Anders", "author_id": 127751, "author_profile": "https://Stackoverflow.com/users/127751", "pm_score": 2, "selected": false, "text": "!#/bin/sh EPOCH=\"`perl -e 'use Time::Local; print timelocal('${SEC}','${MIN}','${HOUR}','${DAY}','${MONTH}','${YEAR}'),\\\"\\n\\\";'`\"\n" }, { "answer_id": 28484217, "author": "Sobrique", "author_id": 2566198, "author_profile": "https://Stackoverflow.com/users/2566198", "pm_score": 3, "selected": false, "text": "Time::Piece strptime my $t = Time::Piece->strptime(\"Sunday 3rd Nov, 1943\",\n \"%A %drd %b, %Y\");\n if ( $t < time() ) { #do something }\n print $t,\"\\n\"; \n Wed Nov 3 00:00:00 1943\n" }, { "answer_id": 60908148, "author": "NotThat JohnSmith", "author_id": 13144150, "author_profile": "https://Stackoverflow.com/users/13144150", "pm_score": 0, "selected": false, "text": "%MonthMatrix=(\"Jan\",0,\"Feb\",31,\"Mar\",59,\"Apr\",90,\"May\",120,\"Jun\",151,\"Jul\",181,\"Aug\",212,\"Sep\",243,\"Oct\",273,\"Nov\",304,\"Dec\",334);\n$LeapYearCount=int($YearFourDigits/4);\n$EpochDayNumber=$MonthMatrix{$MonthThreeLetters};\nif ($LeapYearCount==($YearFourDigits/4)) { if ($EpochDayNumber<32) { $EpochDayNumber--; }}\n$EpochDayNumber=($YearFourDigits-1970)*365+$LeapYearCount+$EpochDayNumber+$DayAsNumber-493;\n$TimeOfDaySeconds=($HourAsNumber*3600)+($MinutesAsNumber*60)+$SecondsAsNumber;\n$ActualEpochTime=($EpochDayNumber*86400)+$TimeOfDaySeconds;\n $MonthThreeLetters\n$DayAsNumber\n$YearFourDigits\n$HourAsNumber\n$MinutesAsNumber\n$SecondsAsNumber\n" }, { "answer_id": 74570979, "author": "gpwr", "author_id": 2870624, "author_profile": "https://Stackoverflow.com/users/2870624", "pm_score": 0, "selected": false, "text": "use Time::Local;\n$number_of_seconds = timelocal(0,24,2, 26,3,2022); \n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4234/" ]
95,500
<p>While refactoring code and ridding myself of all those #defines that we're now taught to hate, I came across this beauty used to calculate the number of elements in a structure:</p> <pre><code>#define STRUCTSIZE(s) (sizeof(s) / sizeof(*s)) </code></pre> <p>Very useful as it is but can it be converted into an inline function or template?</p> <p>OK, ARRAYSIZE would be a better name but this is legacy code (no idea where it came from, it's at least 15 years old) so I pasted it 'as is'.</p>
[ { "answer_id": 95518, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 1, "selected": false, "text": "template <typename T>\nuint32_t StructSize() // This might get inlined to a constant at compile time\n{\n return sizeof(T)/sizeof(*T);\n}\n\n// or to get it at compile time for shure\n\nclass StructSize<typename T>\n{\n enum { result = sizeof(T)/sizeof(*T) };\n}\n" }, { "answer_id": 95521, "author": "Doug T.", "author_id": 8123, "author_profile": "https://Stackoverflow.com/users/8123", "pm_score": 0, "selected": false, "text": "template <typename T>\nsize_t getTypeSize()\n{\n return sizeof(T)/sizeof(*T);\n}\n struct JibbaJabba\n{\n int int1;\n float f;\n};\n\nint main()\n{\n cout << \"sizeof JibbaJabba is \" << getTypeSize<JibbaJabba>() << std::endl;\n return 0;\n}\n" }, { "answer_id": 95664, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 1, "selected": false, "text": "template< typename T > size_t structsize( const T& t ) { \n return sizeof( t ) / sizeof( *t ); \n}\n\n\nint ints[] = { 1,2,3 };\nassert( structsize( ints ) == 3 );\n" }, { "answer_id": 95714, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "//\n// Return the number of elements in a statically sized array.\n// DWORD Buffer[100];\n// RTL_NUMBER_OF(Buffer) == 100\n// This is also popularly known as: NUMBER_OF, ARRSIZE, _countof, NELEM, etc.\n//\n#define RTL_NUMBER_OF_V1(A) (sizeof(A)/sizeof((A)[0]))\n\n#if defined(__cplusplus) && \\\n !defined(MIDL_PASS) && \\\n !defined(RC_INVOKED) && \\\n !defined(_PREFAST_) && \\\n (_MSC_FULL_VER >= 13009466) && \\\n !defined(SORTPP_PASS)\n//\n// RtlpNumberOf is a function that takes a reference to an array of N Ts.\n//\n// typedef T array_of_T[N];\n// typedef array_of_T &reference_to_array_of_T;\n//\n// RtlpNumberOf returns a pointer to an array of N chars.\n// We could return a reference instead of a pointer but older compilers do not accept that.\n//\n// typedef char array_of_char[N];\n// typedef array_of_char *pointer_to_array_of_char;\n//\n// sizeof(array_of_char) == N\n// sizeof(*pointer_to_array_of_char) == N\n//\n// pointer_to_array_of_char RtlpNumberOf(reference_to_array_of_T);\n//\n// We never even call RtlpNumberOf, we just take the size of dereferencing its return type.\n// We do not even implement RtlpNumberOf, we just decare it.\n//\n// Attempts to pass pointers instead of arrays to this macro result in compile time errors.\n// That is the point.\n//\nextern \"C++\" // templates cannot be declared to have 'C' linkage\ntemplate <typename T, size_t N>\nchar (*RtlpNumberOf( UNALIGNED T (&)[N] ))[N];\n\n#define RTL_NUMBER_OF_V2(A) (sizeof(*RtlpNumberOf(A)))\n\n//\n// This does not work with:\n//\n// void Foo()\n// {\n// struct { int x; } y[2];\n// RTL_NUMBER_OF_V2(y); // illegal use of anonymous local type in template instantiation\n// }\n//\n// You must instead do:\n//\n// struct Foo1 { int x; };\n//\n// void Foo()\n// {\n// Foo1 y[2];\n// RTL_NUMBER_OF_V2(y); // ok\n// }\n//\n// OR\n//\n// void Foo()\n// {\n// struct { int x; } y[2];\n// RTL_NUMBER_OF_V1(y); // ok\n// }\n//\n// OR\n//\n// void Foo()\n// {\n// struct { int x; } y[2];\n// _ARRAYSIZE(y); // ok\n// }\n//\n\n#else\n#define RTL_NUMBER_OF_V2(A) RTL_NUMBER_OF_V1(A)\n#endif\n\n#ifdef ENABLE_RTL_NUMBER_OF_V2\n#define RTL_NUMBER_OF(A) RTL_NUMBER_OF_V2(A)\n#else\n#define RTL_NUMBER_OF(A) RTL_NUMBER_OF_V1(A)\n#endif\n\n//\n// ARRAYSIZE is more readable version of RTL_NUMBER_OF_V2, and uses\n// it regardless of ENABLE_RTL_NUMBER_OF_V2\n//\n// _ARRAYSIZE is a version useful for anonymous types\n//\n#define ARRAYSIZE(A) RTL_NUMBER_OF_V2(A)\n#define _ARRAYSIZE(A) RTL_NUMBER_OF_V1(A)\n" }, { "answer_id": 95896, "author": "KTC", "author_id": 12868, "author_profile": "https://Stackoverflow.com/users/12868", "pm_score": 5, "selected": true, "text": "template<typename T,int SIZE>\ninline size_t array_size(const T (&array)[SIZE])\n{\n return SIZE;\n}\n constexpr size_t array_size(const T (&array)[SIZE])\n #include <boost/typeof/typeof.hpp>\n\ntemplate<typename T>\nstruct ArraySize\n{\n private: static T x;\n public: enum { size = sizeof(T)/sizeof(*x)};\n};\ntemplate<typename T>\nstruct ArraySize<T*> {};\n ArraySize<BOOST_TYPEOF(foo)>::size\n" }, { "answer_id": 96085, "author": "JohnMcG", "author_id": 1674, "author_profile": "https://Stackoverflow.com/users/1674", "pm_score": 1, "selected": false, "text": "template<typename T, int SIZE>\nint arraySize(const T(&arr)[SIZE])\n{\n return SIZE;\n}\n" }, { "answer_id": 97523, "author": "jwfearn", "author_id": 10559, "author_profile": "https://Stackoverflow.com/users/10559", "pm_score": 3, "selected": false, "text": "// asize.hpp\ntemplate < typename T >\nstruct asize; // no implementation for all types...\n\ntemplate < typename T, size_t N >\nstruct asize< T[N] > { // ...except arrays\n static const size_t val = N;\n};\n\ntemplate< size_t N >\nstruct count_type { char val[N]; };\n\ntemplate< typename T, size_t N >\ncount_type< N > count( const T (&)[N] ) {}\n\n#define ASIZE( a ) ( sizeof( count( a ).val ) ) \n#define ASIZET( A ) ( asize< A >::val ) \n // asize_test.cpp\n#include <boost/static_assert.hpp>\n#include \"asize.hpp\"\n\n#define OLD_ASIZE( a ) ( sizeof( a ) / sizeof( *a ) )\n\ntypedef char C;\ntypedef struct { int i; double d; } S;\ntypedef C A[42];\ntypedef S B[42];\ntypedef C * PA;\ntypedef S * PB;\n\nint main() {\n A a; B b; PA pa; PB pb;\n BOOST_STATIC_ASSERT( ASIZET( A ) == 42 );\n BOOST_STATIC_ASSERT( ASIZET( B ) == 42 );\n BOOST_STATIC_ASSERT( ASIZET( A ) == OLD_ASIZE( a ) );\n BOOST_STATIC_ASSERT( ASIZET( B ) == OLD_ASIZE( b ) );\n BOOST_STATIC_ASSERT( ASIZE( a ) == OLD_ASIZE( a ) );\n BOOST_STATIC_ASSERT( ASIZE( b ) == OLD_ASIZE( b ) );\n BOOST_STATIC_ASSERT( OLD_ASIZE( pa ) != 42 ); // logic error: pointer accepted\n BOOST_STATIC_ASSERT( OLD_ASIZE( pb ) != 42 ); // logic error: pointer accepted\n // BOOST_STATIC_ASSERT( ASIZE( pa ) != 42 ); // compile error: pointer rejected\n // BOOST_STATIC_ASSERT( ASIZE( pb ) != 42 ); // compile error: pointer rejected\n return 0;\n}\n" }, { "answer_id": 98059, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 1, "selected": false, "text": "#include <iterator>\n#include <algorithm>\n#include <iostream>\n\n\ntemplate<typename T>\nstruct StructSize\n{\n private: static T x;\n public: enum { size = sizeof(T)/sizeof(*x)};\n};\n\ntemplate<typename T>\nstruct StructSize<T*>\n{\n /* Can only guarantee 1 item (maybe we should even disallow this situation) */\n //public: enum { size = 1};\n};\n\nstruct X\n{\n int operator *();\n};\n\n\nint main(int argc,char* argv[])\n{\n int data[] = {1,2,3,4,5,6,7,8};\n int copy[ StructSize<typeof(data)>::size];\n\n std::copy(&data[0],&data[StructSize<typeof(data)>::size],&copy[0]);\n std::copy(&copy[0],&copy[StructSize<typeof(copy)>::size],std::ostream_iterator<int>(std::cout,\",\"));\n\n /*\n * For extra points we should make the following cause the compiler to generate an error message */\n X bad1;\n X bad2[StructSize<typeof(bad1)>::size];\n}\n" }, { "answer_id": 100495, "author": "shoosh", "author_id": 9611, "author_profile": "https://Stackoverflow.com/users/9611", "pm_score": 0, "selected": false, "text": "_countof()" }, { "answer_id": 100872, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "template<int n>\nstruct char_array_wrapper{\n char result[n];\n};\n\ntemplate<typename T, int s>\nchar_array_wrapper<s> the_type_of_the_variable_is_not_an_array(const T (&array)[s]){\n}\n\n\n#define ARRAYSIZE_OF_VAR(v) sizeof(the_type_of_the_variable_is_not_an_array(v).result)\n\n#include <iostream>\nusing namespace std;\n\nint main(){\n int foo[42];\n int*bar;\n cout<<ARRAYSIZE_OF_VAR(foo)<<endl;\n // cout<<ARRAYSIZE_OF_VAR(bar)<<endl; fails\n}\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
95,510
<p>I need my application to behave differently depending on whether Vista UAC is enabled or not. How can my application detect the state of UAC on the user's computer?</p>
[ { "answer_id": 95605, "author": "Philip Rieck", "author_id": 12643, "author_profile": "https://Stackoverflow.com/users/12643", "pm_score": 5, "selected": true, "text": "HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System\n EnableLUA (DWORD) 1 0" }, { "answer_id": 95646, "author": "Andrei Belogortseff", "author_id": 17037, "author_profile": "https://Stackoverflow.com/users/17037", "pm_score": 2, "selected": false, "text": "BOOL IsUacEnabled( )\n{\n LPCTSTR pszSubKey = _T(\"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\System\");\n LPCTSTR pszValue = _T(\"EnableLUA\");\n DWORD dwType = 0;\n DWORD dwValue = 0;\n DWORD dwValueSize = sizeof( DWORD );\n\n if ( ERROR_SUCCESS != SHGetValue( HKEY_LOCAL_MACHINE, pszSubKey, pszValueOn, \n &dwType, &dwValue, &dwValueSize) )\n {\n return FALSE;\n }\n\n return dwValue != 0;\n} \n" }, { "answer_id": 6114816, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 2, "selected": false, "text": "CheckTokenMembership ///This function tells us if we're running with administrative permissions.\nfunction IsUserAdmin: Boolean;\nvar\n b: BOOL;\n AdministratorsGroup: PSID;\nbegin\n {\n This function returns true if you are currently running with \n admin privileges.\n In Vista and later, if you are non-elevated, this function will \n return false (you are not running with administrative privileges).\n If you *are* running elevated, then IsUserAdmin will return \n true, as you are running with admin privileges.\n\n Windows provides this similar function in Shell32.IsUserAnAdmin.\n But the function is depricated, and this code is lifted from the \n docs for CheckTokenMembership: \n http://msdn.microsoft.com/en-us/library/aa376389.aspx\n }\n\n {\n Routine Description: This routine returns TRUE if the caller's\n process is a member of the Administrators local group. Caller is NOT\n expected to be impersonating anyone and is expected to be able to\n open its own process and process token.\n Arguments: None.\n Return Value:\n TRUE - Caller has Administrators local group.\n FALSE - Caller does not have Administrators local group.\n }\n b := AllocateAndInitializeSid(\n SECURITY_NT_AUTHORITY,\n 2, //2 sub-authorities\n SECURITY_BUILTIN_DOMAIN_RID, //sub-authority 0\n DOMAIN_ALIAS_RID_ADMINS, //sub-authority 1\n 0, 0, 0, 0, 0, 0, //sub-authorities 2-7 not passed\n AdministratorsGroup);\n if (b) then\n begin\n if not CheckTokenMembership(0, AdministratorsGroup, b) then\n b := False;\n FreeSid(AdministratorsGroup);\n end;\n\n Result := b;\nend;\n" }, { "answer_id": 14899279, "author": "Mark D. MacLachlan", "author_id": 2076290, "author_profile": "https://Stackoverflow.com/users/2076290", "pm_score": 1, "selected": false, "text": "On Error Resume Next\nUACPath = \"HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System\\EnableLUA\"\nDim WshShell\nSet WshShell = CreateObject(\"wscript.Shell\")\nUACValue = WshShell.RegRead(UACPath)\nIf UACValue = 1 Then\n'Run Elevated\n If WScript.Arguments.length =0 Then\n Set objShell = CreateObject(\"Shell.Application\")\n 'Pass a bogus argument with leading blank space, say [ uac]\n objShell.ShellExecute \"wscript.exe\", Chr(34) & _\n WScript.ScriptFullName & Chr(34) & \" uac\", \"\", \"runas\", 1\n WScript.Quit\n Else \n Body()\n End If\nElse\nBody()\nEnd If\n\nFunction Body()\nMsgBox \"This is the body of the script\"\nEnd Function\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17037/" ]
95,525
<p>I've just built a VS C++ 6.0 program using VS 2008. When I attempt to run or debug the application, Vista asks for permission. What is it about how the program is built that causes this? The program is being built and run from a subfolder of C:\Dev</p> <p><a href="http://www.vistax64.com/vista-installation-setup/138053-vista-asks-permission-run-installed-programs.html" rel="nofollow noreferrer">This response</a> made no sense to me as a solution to the problem.</p>
[ { "answer_id": 96033, "author": "AlanKley", "author_id": 8761, "author_profile": "https://Stackoverflow.com/users/8761", "pm_score": 1, "selected": false, "text": "<trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v3\">\n <security>\n <requestedPrivileges>\n <requestedExecutionLevel level=\"asInvoker\" uiAccess=\"false\"></requestedExecutionLevel>\n </requestedPrivileges>\n </security> \n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8761/" ]
95,547
<p>Should I catch exceptions for logging purposes?</p> <pre> public foo(..) { try { ... } catch (Exception ex) { Logger.Error(ex); throw; } } </pre> <p>If I have this in place in each of my layers (DataAccess, Business and WebService) it means the exception is logged several times.</p> <p>Does it make sense to do so if my layers are in separate projects and only the public interfaces have try/catch in them? Why? Why not? Is there a different approach I could use?</p>
[ { "answer_id": 95667, "author": "MADMap", "author_id": 17558, "author_profile": "https://Stackoverflow.com/users/17558", "pm_score": 0, "selected": false, "text": "public foo(..)\n{\n try\n {\n ...\n }\n catch (NullReferenceException ex) {\n DoSmth(e);\n }\n catch (ArgumentExcetion ex) {\n DoSmth(e);\n }\n catch (Exception ex) {\n DoSmth(e);\n }\n}\n" }, { "answer_id": 95690, "author": "Marcio Aguiar", "author_id": 4213, "author_profile": "https://Stackoverflow.com/users/4213", "pm_score": 2, "selected": false, "text": "public void connect() throws ConnectionException {\n try {\n File conf = new File(\"blabla\");\n ...\n } catch (FileNotFoundException ex) {\n LOGGER.error(\"log message\", ex);\n throw new ConnectionException(\"The configuration file was not found\", ex);\n }\n}\n" }, { "answer_id": 95773, "author": "Pat", "author_id": 14206, "author_profile": "https://Stackoverflow.com/users/14206", "pm_score": 3, "selected": false, "text": "try\n{\n this.Persist(trans);\n}\ncatch(Exception ex)\n{\n trans.Rollback();\n throw ex;\n}\n Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);\n static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)\n{\n LogException(e.Exception);\n}\n\nstatic void LogException(Exception ex)\n{\n YYYExceptionHandling.HandleException(ex,\n YYYExceptionHandling.ExceptionPolicyType.YYY_Policy,\n YYYExceptionHandling.ExceptionPriority.Medium,\n \"An error has occurred, please contact Administrator\");\n} \n" }, { "answer_id": 231732, "author": "David Leppik", "author_id": 18078, "author_profile": "https://Stackoverflow.com/users/18078", "pm_score": 1, "selected": false, "text": "public void methodWithDynamicallyGeneratedSQL() throws SQLException {\n String sql = ...; // Generate some SQL\n try {\n ... // Try running the query\n }\n catch (SQLException ex) {\n // Don't bother to log the stack trace, that will\n // be printed when the exception is handled for real\n logger.error(ex.toString()+\"For SQL: '\"+sql+\"'\");\n throw ex; // Handle the exception long after the SQL is gone\n }\n}\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15771/" ]
95,554
<p>I want to override the JSON MIME type ("application/json") in Rails to ("text/x-json"). I tried to register the MIME type again in mime_types.rb but that didn't work. Any suggestions?</p> <p>Thanks.</p>
[ { "answer_id": 95863, "author": "Mike Tunnicliffe", "author_id": 13956, "author_profile": "https://Stackoverflow.com/users/13956", "pm_score": 2, "selected": false, "text": "render :json => var_containing_my_json, :content_type => 'text/x-json'\n" }, { "answer_id": 95968, "author": "Ben Scofield", "author_id": 6478, "author_profile": "https://Stackoverflow.com/users/6478", "pm_score": 5, "selected": true, "text": "Mime.send(:remove_const, :JSON)\nMime::Type.register \"text/x-json\", :json\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10333/" ]
95,578
<ul> <li>I have an Oracle database backup file (.dmp) that was created with <code>expdp</code>.</li> <li>The .dmp file was an export of an entire database.</li> <li>I need to restore 1 of the schemas from within this dump file.</li> <li>I don't know the names of the schemas inside this dump file.</li> <li>To use <code>impdp</code> to import the data I need the name of the schema to load.</li> </ul> <p>So, I need to inspect the .dmp file and list all of the schemas in it, how do I do that?</p> <hr /> <p><em>Update (2008-09-18 13:02) - More detailed information:</em></p> <p>The impdp command i'm current using is:</p> <pre><code>impdp user/password@database directory=DPUMP_DIR dumpfile=EXPORT.DMP logfile=IMPORT.LOG </code></pre> <p>And the DPUMP_DIR is correctly configured.</p> <pre><code>SQL&gt; SELECT directory_path 2 FROM dba_directories 3 WHERE directory_name = 'DPUMP_DIR'; DIRECTORY_PATH ------------------------- D:\directory_path\dpump_dir\ </code></pre> <p>And yes, the EXPORT.DMP file is in fact in that folder.</p> <p>The error message I get when I run the <code>impdp</code> command is:</p> <pre><code>Connected to: Oracle Database 10g Enterprise Edition ... ORA-31655: no data or metadata objects selected for the job ORA-39154: Objects from foreign schemas have been removed from import </code></pre> <p>This error message is mostly expected. I need the <code>impdp</code> command be:</p> <pre><code>impdp user/password@database directory=DPUMP_DIR dumpfile=EXPORT.DMP SCHEMAS=SOURCE_SCHEMA REMAP_SCHEMA=SOURCE_SCHEMA:MY_SCHEMA </code></pre> <p>But to do that, I need the source schema.</p>
[ { "answer_id": 103454, "author": "KyleLanser", "author_id": 12923, "author_profile": "https://Stackoverflow.com/users/12923", "pm_score": 4, "selected": false, "text": "<OWNER_NAME>SOURCE_SCHEMA</OWNER_NAME> SCHEMA_LIST 'SOURCE_SCHEMA' SCHEMA_LIST 'SOURCE_SCHEMA'" }, { "answer_id": 6708618, "author": "Factor Mystic", "author_id": 1569, "author_profile": "https://Stackoverflow.com/users/1569", "pm_score": 7, "selected": false, "text": "impdp dmp SQLFILE impdp '/ as sysdba' dumpfile=<your .dmp file> logfile=import_log.txt sqlfile=ddl_dump.txt\n ddl_dump.txt" }, { "answer_id": 14450325, "author": "Peter Wiseman", "author_id": 1998792, "author_profile": "https://Stackoverflow.com/users/1998792", "pm_score": 2, "selected": false, "text": "select value_t \nfrom SYS_IMPORT_TABLE_01 \nwhere name = 'CLIENT_COMMAND' \nand process_order = -59;\n\ncol object_name for a30\ncol processing_status head STATUS for a6\ncol processing_state head STATE for a5\nselect distinct\n object_schema,\n object_name,\n object_type,\n object_tablespace,\n process_order,\n duplicate,\n processing_status,\n processing_state\nfrom sys_import_table_01\nwhere process_order > 0\nand object_name is not null\norder by object_schema, object_name\n/\n" }, { "answer_id": 16192910, "author": "slafs", "author_id": 407001, "author_profile": "https://Stackoverflow.com/users/407001", "pm_score": 2, "selected": false, "text": "strings dumpfile.dmp | grep SCHEMA_LIST\n" }, { "answer_id": 16230116, "author": "DBA", "author_id": 2295045, "author_profile": "https://Stackoverflow.com/users/2295045", "pm_score": 2, "selected": false, "text": "SQLFILE CREATE USER $ impdp directory=exp_dir dumpfile=exp_user1_all_tab.dmp logfile=imp_exp_user1_tab sqlfile=tables.sql\n $ grep \"CREATE USER\" tables.sql\n" }, { "answer_id": 42374293, "author": "Aldur", "author_id": 12942, "author_profile": "https://Stackoverflow.com/users/12942", "pm_score": 2, "selected": false, "text": "cat -v dumpfile.dmp | grep -o '<OWNER_NAME>.*</OWNER_NAME>' | uniq -u\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12923/" ]
95,600
<p>The documentation indicates that the error: option function will make available: XHR instance, a status message string (in this case always error) and an optional exception object returned from the XHR instance (Book: JQuery in Action)</p> <p>Using the following (in the $.ajax call) I was able to determine I had a "parsererror" and a "timeout" (since I added the timeout: option) error</p> <pre><code>error: function(request, error){} </code></pre> <p>What are other things you evaluate in the error option? do you include the optional exception object?</p> <p><strong>EDIT:</strong> one of the answers indicates all the return errors...learning more about what is of value (for debugging) in the XHR instance and exception object would be helpful</p> <p>This is a complete $.ajax call:</p> <pre><code>$.ajax({ type: "post", url: "http://myServer/cgi-bin/broker" , dataType: "text", data: { '_service' : 'myService', '_program' : 'myProgram', 'start' : start, 'end' : end }, beforeSend: function() { $("#loading").removeClass("hide"); }, timeout: 5000, error: function(request,error) { $("#loading").addClass("hide"); if (error == "timeout") { $("#error").append("The request timed out, please resubmit"); } else { $("#error").append("ERROR: " + error); } }, success: function(request) { $("#loading").addClass("hide"); var t = eval( "(" + request + ")" ) ; } // End success }); // End ajax method </code></pre> <p>Thanks for the input</p>
[ { "answer_id": 95947, "author": "Tomasz Tybulewicz", "author_id": 17405, "author_profile": "https://Stackoverflow.com/users/17405", "pm_score": 0, "selected": false, "text": "var t = eval( \"(\" + request + \")\" ) ;" }, { "answer_id": 1682211, "author": "davegurnell", "author_id": 203842, "author_profile": "https://Stackoverflow.com/users/203842", "pm_score": 2, "selected": false, "text": " if (error = \"timeout\") {\n if (error == \"timeout\") {\n" }, { "answer_id": 1956505, "author": "Matt", "author_id": 179310, "author_profile": "https://Stackoverflow.com/users/179310", "pm_score": 5, "selected": false, "text": "error:function(xhr,err){\n alert(\"readyState: \"+xhr.readyState+\"\\nstatus: \"+xhr.status);\n alert(\"responseText: \"+xhr.responseText);\n}" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755/" ]
95,606
<p>In XNA, how do I load in a texture or mesh from a file without using the content pipeline?</p>
[ { "answer_id": 6951962, "author": "Aranda", "author_id": 858350, "author_profile": "https://Stackoverflow.com/users/858350", "pm_score": 0, "selected": false, "text": "Xna.Framework.Graphics.Model" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632/" ]
95,625
<p>Basically, we have a rule setup to run a script when a code word is detected in the body of an incoming message. The script will append the current subject header with a word in front. For example, Before: "Test Message", After: "Dept - Test Message". Any ideas?</p>
[ { "answer_id": 95695, "author": "Matt", "author_id": 17849, "author_profile": "https://Stackoverflow.com/users/17849", "pm_score": 0, "selected": false, "text": "mailItem.Subject = \"Dept - \" & mailItem.Subject\nmailItem.Save \n" }, { "answer_id": 95746, "author": "Matt", "author_id": 17849, "author_profile": "https://Stackoverflow.com/users/17849", "pm_score": 2, "selected": false, "text": "Sub RewriteSubject(MyMail As MailItem)\n\n Dim mailId As String\n Dim outlookNS As Outlook.NameSpace\n Dim myMailItem As Outlook.MailItem\n\n mailId = MyMail.EntryID\n Set outlookNS = Application.GetNamespace(\"MAPI\")\n Set myMailItem = outlookNS.GetItemFromID(mailId)\n\n ' Do any detection here\n\n With myMailItem \n .Subject = \"Dept - \" & mailItem.Subject\n .Save\n End With\n\n Set myMailItem = Nothing\n Set outlookNS = Nothing\n\nEnd Sub\n" }, { "answer_id": 95837, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "Sub AppendSubject(MyMail As MailItem)\n Dim strID As String\n Dim mailNS As Outlook.NameSpace\n Dim mailItem As Outlook.MailItem\n\n strID = MyMail.EntryID\n Set mailNS = Application.GetNamespace(\"MAPI\")\n Set mailItem = mailNS.GetItemFromID(strID)\n mailItem.Subject = \"Dept - \" & mailItem.Subject\n mailItem.Save\n\n Set mailItem = Nothing\n Set mailNS = Nothing\nEnd Sub\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
95,631
<p>Suppose I want to open a file in an existing Emacs session using <code>su</code> or <code>sudo</code>, without dropping down to a shell and doing <code>sudoedit</code> or <code>sudo emacs</code>. One way to do this is</p> <pre><code>C-x C-f /sudo::/path/to/file </code></pre> <p>but this requires an expensive <a href="http://www.gnu.org/software/tramp/" rel="noreferrer">round-trip through SSH</a>. Is there a more direct way?</p> <p>[EDIT] @JBB is right. I want to be able to invoke <code>su</code>/<code>sudo</code> to save as well as open. It would be OK (but not ideal) to re-authorize when saving. What I'm looking for is variations of <code>find-file</code> and <code>save-buffer</code> that can be "piped" through <code>su</code>/<code>sudo</code>.</p>
[ { "answer_id": 29255604, "author": "anquegi", "author_id": 1900722, "author_profile": "https://Stackoverflow.com/users/1900722", "pm_score": 2, "selected": false, "text": "(defadvice ido-find-file (after find-file-sudo activate)\n \"Find file as root if necessary.\"\n (unless (and buffer-file-name\n (file-writable-p buffer-file-name))\n (find-alternate-file (concat \"/sudo:root@localhost:\" buffer-file-name))))\n" }, { "answer_id": 31092680, "author": "Qudit", "author_id": 3101625, "author_profile": "https://Stackoverflow.com/users/3101625", "pm_score": 4, "selected": false, "text": "helm helm-find-files C-c r" }, { "answer_id": 36569381, "author": "alex_1948511", "author_id": 1948511, "author_profile": "https://Stackoverflow.com/users/1948511", "pm_score": 1, "selected": false, "text": "(defun sudo-find-file (file-name)\n\"Like find file, but opens the file as root.\"\n(interactive \"FSudo Find File: \")\n(let ((tramp-file-name (concat \"/sudo::\" (expand-file-name file-name))))\n(find-file tramp-file-name)))\n\n\n(add-hook 'dired-mode-hook\n (lambda ()\n ;; open current file as sudo \n (local-set-key (kbd \"C-x <M-S-return>\") (lambda()\n (interactive)\n (message \"!!! SUDO opening %s\" (dired-file-name-at-point))\n (sudo-find-file (dired-file-name-at-point))\n ))\n )\n)\n" }, { "answer_id": 68870716, "author": "Daoist Paul", "author_id": 12980261, "author_profile": "https://Stackoverflow.com/users/12980261", "pm_score": 0, "selected": false, "text": "sudo edit s-e" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1412/" ]
95,635
<p>What does a JIT compiler specifically do as opposed to a non-JIT compiler? Can someone give a succinct and easy to understand description?</p>
[ { "answer_id": 35664946, "author": "Anands23", "author_id": 4643764, "author_profile": "https://Stackoverflow.com/users/4643764", "pm_score": 3, "selected": false, "text": "while(i<10){\n // ...\n a=a+i;\n // ...\n }\n" }, { "answer_id": 52523015, "author": "Willem van der Veen", "author_id": 8059459, "author_profile": "https://Stackoverflow.com/users/8059459", "pm_score": 3, "selected": false, "text": "Intermediate representation JIT Native machine code for the current CPU architecture\n\n Java bytecode ---> machine code\n Javascript (run with V8) ---> machine code\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6264/" ]
95,642
<p>Long story short, I have a substantial Python application that, among other things, does outcalls to "losetup", "mount", etc. on Linux. Essentially consuming system resources that must be released when complete.</p> <p>If my application crashes, I want to ensure these system resources are properly released.</p> <p>Does it make sense to do something like the following?</p> <pre><code>def main(): # TODO: main application entry point pass def cleanup(): # TODO: release system resources here pass if __name__ == "__main__": try: main() except: cleanup() raise </code></pre> <p>Is this something that is typically done? Is there a better way? Perhaps the destructor in a singleton class?</p>
[ { "answer_id": 98085, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 2, "selected": false, "text": "try:\n main()\nfinally:\n cleanup()\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9188/" ]
95,683
<p>I have a .NET 3.5 (target framework) web application. I have some code that looks like this:</p> <pre><code>public string LogPath { get; private set; } public string ErrorMsg { get; private set; } </code></pre> <p>It's giving me this compilation error for these lines:</p> <pre><code>"must declare a body because it is not marked abstract or extern." </code></pre> <p>Any ideas? My understanding was that this style of property was valid as of .NET 3.0.</p> <p>Thanks!</p> <hr> <p>The problem turned out to be in my .sln file itself. Although I was changing the target version in my build options, in the .sln file, I found this:</p> <pre><code>TargetFramework = "3.0" </code></pre> <p>Changing that to "3.5" solved it. Thanks, guys!</p>
[ { "answer_id": 95716, "author": "Nikki9696", "author_id": 456669, "author_profile": "https://Stackoverflow.com/users/456669", "pm_score": -1, "selected": false, "text": "public abstract string LogPath { get; private set; }\npublic abstract string ErrorMsg { get; private set; }\n" }, { "answer_id": 1140423, "author": "R.L.", "author_id": 104991, "author_profile": "https://Stackoverflow.com/users/104991", "pm_score": 5, "selected": true, "text": "<system.codedom>\n <compilers>\n <compiler language=\"c#;cs;csharp\" extension=\".cs\" type=\"Microsoft.CSharp.CSharpCodeProvider,System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" warningLevel=\"4\">\n <providerOption name=\"CompilerVersion\" value=\"v3.5\" />\n <providerOption name=\"WarnAsError\" value=\"false\" />\n </compiler>\n </compilers>\n</system.codedom>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13348/" ]
95,700
<p>I am looking to build a multi-threaded text import facility (generally CSV into SQL Server 2005) and would like to do this in VB.NET but I am not against C#. I have VS 2008 trial and just dont know where to begin. Can anyone point me in the direction of where I can look at and play with the source of a <em>VERY</em> simple multi-threaded application for VS 2008?</p> <p>Thanks!</p>
[ { "answer_id": 95721, "author": "nathaniel", "author_id": 11947, "author_profile": "https://Stackoverflow.com/users/11947", "pm_score": 2, "selected": false, "text": "Dim t As Thread\nt = New Thread(AddressOf Me.BackgroundProcess)\nt.Start()\n\nPrivate Sub BackgroundProcess()\n Dim i As Integer = 1\n Do While True\n ListBox1.Items.Add(\"Iterations: \" + i)\n i += 1\n Thread.CurrentThread.Sleep(2000)\n Loop\nEnd Sub\n" }, { "answer_id": 509999, "author": "Tom A", "author_id": 10226, "author_profile": "https://Stackoverflow.com/users/10226", "pm_score": 3, "selected": true, "text": "Imports System.ComponentModel\n\nPartial Public Class Page\n Inherits UserControl\n Private bw As BackgroundWorker = New BackgroundWorker\n\n Public Sub New()\n InitializeComponent()\n\n bw.WorkerReportsProgress = True\n bw.WorkerSupportsCancellation = True\n AddHandler bw.DoWork, AddressOf bw_DoWork\n AddHandler bw.ProgressChanged, AddressOf bw_ProgressChanged\n AddHandler bw.RunWorkerCompleted, AddressOf bw_RunWorkerCompleted\n\n End Sub\n Private Sub buttonStart_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)\n If Not bw.IsBusy = True Then\n bw.RunWorkerAsync()\n End If\n End Sub\n Private Sub buttonCancel_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)\n If bw.WorkerSupportsCancellation = True Then\n bw.CancelAsync()\n End If\n End Sub\n Private Sub bw_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)\n Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)\n\n For i = 1 To 10\n If bw.CancellationPending = True Then\n e.Cancel = True\n Exit For\n Else\n ' Perform a time consuming operation and report progress.\n System.Threading.Thread.Sleep(500)\n bw.ReportProgress(i * 10)\n End If\n Next\n End Sub\n Private Sub bw_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)\n If e.Cancelled = True Then\n Me.tbProgress.Text = \"Canceled!\"\n ElseIf e.Error IsNot Nothing Then\n Me.tbProgress.Text = \"Error: \" & e.Error.Message\n Else\n Me.tbProgress.Text = \"Done!\"\n End If\n End Sub\n Private Sub bw_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs)\n Me.tbProgress.Text = e.ProgressPercentage.ToString() & \"%\"\n End Sub\nEnd Class\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14728/" ]
95,715
<p>What causes Firefox to follow a POST request with a GET request when submitting a form via the POST method? The GET method is sent to the same url as the POST method but without the request parameters.</p> <p>If you change the form method to GET, it will result in two identical GET requests.</p>
[ { "answer_id": 95762, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<img src=\"\"/>" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
95,727
<p>Let's say we have <code>0.33</code>, we need to output <code>1/3</code>. <br /> If we have <code>0.4</code>, we need to output <code>2/5</code>.</p> <p>The idea is to make it human-readable to make the user understand "<strong>x parts out of y</strong>" as a better way of understanding data.</p> <p>I know that percentages is a good substitute but I was wondering if there was a simple way to do this?</p>
[ { "answer_id": 95778, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 4, "selected": false, "text": "3.141592 * 1000000 = 3141592\n 3 + (141592 / 1000000)\n 3 + (17699 / 125000)\n" }, { "answer_id": 95785, "author": "devinmoore", "author_id": 15950, "author_profile": "https://Stackoverflow.com/users/15950", "pm_score": 4, "selected": false, "text": "Public Function Dec2Frac(ByVal f As Double) As String\n\n Dim df As Double\n Dim lUpperPart As Long\n Dim lLowerPart As Long\n \n lUpperPart = 1\n lLowerPart = 1\n \n df = lUpperPart / lLowerPart\n While (df <> f)\n If (df < f) Then\n lUpperPart = lUpperPart + 1\n Else\n lLowerPart = lLowerPart + 1\n lUpperPart = f * lLowerPart\n End If\n df = lUpperPart / lLowerPart\n Wend\nDec2Frac = CStr(lUpperPart) & \"/\" & CStr(lLowerPart)\nEnd Function\n" }, { "answer_id": 95790, "author": "Orion Adrian", "author_id": 7756, "author_profile": "https://Stackoverflow.com/users/7756", "pm_score": 3, "selected": false, "text": "floor(5/2) = 2\n5/2 = 2.5\n" }, { "answer_id": 96035, "author": "Epsilon", "author_id": 18143, "author_profile": "https://Stackoverflow.com/users/18143", "pm_score": 7, "selected": true, "text": "/*\n** find rational approximation to given real number\n** David Eppstein / UC Irvine / 8 Aug 1993\n**\n** With corrections from Arno Formella, May 2008\n**\n** usage: a.out r d\n** r is real number to approx\n** d is the maximum denominator allowed\n**\n** based on the theory of continued fractions\n** if x = a1 + 1/(a2 + 1/(a3 + 1/(a4 + ...)))\n** then best approximation is found by truncating this series\n** (with some adjustments in the last term).\n**\n** Note the fraction can be recovered as the first column of the matrix\n** ( a1 1 ) ( a2 1 ) ( a3 1 ) ...\n** ( 1 0 ) ( 1 0 ) ( 1 0 )\n** Instead of keeping the sequence of continued fraction terms,\n** we just keep the last partial product of these matrices.\n*/\n\n#include <stdio.h>\n\nmain(ac, av)\nint ac;\nchar ** av;\n{\n double atof();\n int atoi();\n void exit();\n\n long m[2][2];\n double x, startx;\n long maxden;\n long ai;\n\n /* read command line arguments */\n if (ac != 3) {\n fprintf(stderr, \"usage: %s r d\\n\",av[0]); // AF: argument missing\n exit(1);\n }\n startx = x = atof(av[1]);\n maxden = atoi(av[2]);\n\n /* initialize matrix */\n m[0][0] = m[1][1] = 1;\n m[0][1] = m[1][0] = 0;\n\n /* loop finding terms until denom gets too big */\n while (m[1][0] * ( ai = (long)x ) + m[1][1] <= maxden) {\n long t;\n t = m[0][0] * ai + m[0][1];\n m[0][1] = m[0][0];\n m[0][0] = t;\n t = m[1][0] * ai + m[1][1];\n m[1][1] = m[1][0];\n m[1][0] = t;\n if(x==(double)ai) break; // AF: division by zero\n x = 1/(x - (double) ai);\n if(x>(double)0x7FFFFFFF) break; // AF: representation failure\n } \n\n /* now remaining x is between 0 and 1/ai */\n /* approx as either 0 or 1/m where m is max that will fit in maxden */\n /* first try zero */\n printf(\"%ld/%ld, error = %e\\n\", m[0][0], m[1][0],\n startx - ((double) m[0][0] / (double) m[1][0]));\n\n /* now try other possibility */\n ai = (maxden - m[1][1]) / m[1][0];\n m[0][0] = m[0][0] * ai + m[0][1];\n m[1][0] = m[1][0] * ai + m[1][1];\n printf(\"%ld/%ld, error = %e\\n\", m[0][0], m[1][0],\n startx - ((double) m[0][0] / (double) m[1][0]));\n}\n" }, { "answer_id": 97337, "author": "jpsecher", "author_id": 13372, "author_profile": "https://Stackoverflow.com/users/13372", "pm_score": 5, "selected": false, "text": "char *userTextForDouble(double d, char *rval)\n{\n if (d == 0.0)\n return \"0\";\n \n // TODO: negative numbers:if (d < 0.0)...\n if (d >= 1.0)\n sprintf(rval, \"%.0f \", floor(d));\n d = d-floor(d); // now only the fractional part is left\n \n if (d == 0.0)\n return rval;\n \n if( d < 0.47 )\n {\n if( d < 0.25 )\n {\n if( d < 0.16 )\n {\n if( d < 0.12 ) // Note: fixed from .13\n {\n if( d < 0.11 )\n strcat(rval, \"1/10\"); // .1\n else\n strcat(rval, \"1/9\"); // .1111....\n }\n else // d >= .12\n {\n if( d < 0.14 )\n strcat(rval, \"1/8\"); // .125\n else\n strcat(rval, \"1/7\"); // .1428...\n }\n }\n else // d >= .16\n {\n if( d < 0.19 )\n {\n strcat(rval, \"1/6\"); // .1666...\n }\n else // d > .19\n {\n if( d < 0.22 )\n strcat(rval, \"1/5\"); // .2\n else\n strcat(rval, \"2/9\"); // .2222...\n }\n }\n }\n else // d >= .25\n {\n if( d < 0.37 ) // Note: fixed from .38\n {\n if( d < 0.28 ) // Note: fixed from .29\n {\n strcat(rval, \"1/4\"); // .25\n }\n else // d >=.28\n {\n if( d < 0.31 )\n strcat(rval, \"2/7\"); // .2857...\n else\n strcat(rval, \"1/3\"); // .3333...\n }\n }\n else // d >= .37\n {\n if( d < 0.42 ) // Note: fixed from .43\n {\n if( d < 0.40 )\n strcat(rval, \"3/8\"); // .375\n else\n strcat(rval, \"2/5\"); // .4\n }\n else // d >= .42\n {\n if( d < 0.44 )\n strcat(rval, \"3/7\"); // .4285...\n else\n strcat(rval, \"4/9\"); // .4444...\n }\n }\n }\n }\n else\n {\n if( d < 0.71 )\n {\n if( d < 0.60 )\n {\n if( d < 0.55 ) // Note: fixed from .56\n {\n strcat(rval, \"1/2\"); // .5\n }\n else // d >= .55\n {\n if( d < 0.57 )\n strcat(rval, \"5/9\"); // .5555...\n else\n strcat(rval, \"4/7\"); // .5714\n }\n }\n else // d >= .6\n {\n if( d < 0.62 ) // Note: Fixed from .63\n {\n strcat(rval, \"3/5\"); // .6\n }\n else // d >= .62\n {\n if( d < 0.66 )\n strcat(rval, \"5/8\"); // .625\n else\n strcat(rval, \"2/3\"); // .6666...\n }\n }\n }\n else\n {\n if( d < 0.80 )\n {\n if( d < 0.74 )\n {\n strcat(rval, \"5/7\"); // .7142...\n }\n else // d >= .74\n {\n if(d < 0.77 ) // Note: fixed from .78\n strcat(rval, \"3/4\"); // .75\n else\n strcat(rval, \"7/9\"); // .7777...\n }\n }\n else // d >= .8\n {\n if( d < 0.85 ) // Note: fixed from .86\n {\n if( d < 0.83 )\n strcat(rval, \"4/5\"); // .8\n else\n strcat(rval, \"5/6\"); // .8333...\n }\n else // d >= .85\n {\n if( d < 0.87 ) // Note: fixed from .88\n {\n strcat(rval, \"6/7\"); // .8571\n }\n else // d >= .87\n {\n if( d < 0.88 ) // Note: fixed from .89\n {\n strcat(rval, \"7/8\"); // .875\n }\n else // d >= .88\n {\n if( d < 0.90 )\n strcat(rval, \"8/9\"); // .8888...\n else\n strcat(rval, \"9/10\"); // .9\n }\n }\n }\n }\n }\n }\n \n return rval;\n}\n" }, { "answer_id": 97574, "author": "robottobor", "author_id": 10184, "author_profile": "https://Stackoverflow.com/users/10184", "pm_score": 2, "selected": false, "text": "a = rational(1);\nb = rational(3);\nc = a / b;\n\nprint (c.asFraction) ---> \"1/3\"\nprint (c.asFloat) ----> \"0.333333\"\n" }, { "answer_id": 681534, "author": "mivk", "author_id": 111036, "author_profile": "https://Stackoverflow.com/users/111036", "pm_score": 3, "selected": false, "text": "sub dec2frac {\n my $d = shift;\n\n my $df = 1;\n my $top = 1;\n my $bot = 1;\n\n while ($df != $d) {\n if ($df < $d) {\n $top += 1;\n }\n else {\n $bot += 1;\n $top = int($d * $bot);\n }\n $df = $top / $bot;\n }\n return \"$top/$bot\";\n}\n function dec2frac(d) {\n\n var df = 1;\n var top = 1;\n var bot = 1;\n\n while (df != d) {\n if (df < d) {\n top += 1;\n }\n else {\n bot += 1;\n top = parseInt(d * bot);\n }\n df = top / bot;\n }\n return top + '/' + bot;\n}\n\n//Put in your test number here:\nvar floatNumber = 2.56;\nalert(floatNumber + \" = \" + dec2frac(floatNumber));" }, { "answer_id": 1331433, "author": "eldad", "author_id": 163131, "author_profile": "https://Stackoverflow.com/users/163131", "pm_score": 3, "selected": false, "text": ">>> from fractions import Fraction\n>>> Fraction('3.1415926535897932').limit_denominator(1000)\nFraction(355, 113)\n" }, { "answer_id": 1992465, "author": "João Lopes", "author_id": 242395, "author_profile": "https://Stackoverflow.com/users/242395", "pm_score": 1, "selected": false, "text": "public static function toFrac(f:Number) : String\n {\n if (f>1)\n {\n var parte1:int;\n var parte2:Number;\n var resultado:String;\n var loc:int = String(f).indexOf(\".\");\n parte2 = Number(String(f).slice(loc, String(f).length));\n parte1 = int(String(f).slice(0,loc));\n resultado = toFrac(parte2);\n parte1 *= int(resultado.slice(resultado.indexOf(\"/\") + 1, resultado.length)) + int(resultado.slice(0, resultado.indexOf(\"/\")));\n resultado = String(parte1) + resultado.slice(resultado.indexOf(\"/\"), resultado.length)\n return resultado;\n }\n if( f < 0.47 )\n if( f < 0.25 )\n if( f < 0.16 )\n if( f < 0.13 )\n if( f < 0.11 )\n return \"1/10\";\n else\n return \"1/9\";\n else\n if( f < 0.14 )\n return \"1/8\";\n else\n return \"1/7\";\n else\n if( f < 0.19 )\n return \"1/6\";\n else\n if( f < 0.22 )\n return \"1/5\";\n else\n return \"2/9\";\n else\n if( f < 0.38 )\n if( f < 0.29 )\n return \"1/4\";\n else\n if( f < 0.31 )\n return \"2/7\";\n else\n return \"1/3\";\n else\n if( f < 0.43 )\n if( f < 0.40 )\n return \"3/8\";\n else\n return \"2/5\";\n else\n if( f < 0.44 )\n return \"3/7\";\n else\n return \"4/9\";\n else\n if( f < 0.71 )\n if( f < 0.60 )\n if( f < 0.56 )\n return \"1/2\";\n else\n if( f < 0.57 )\n return \"5/9\";\n else\n return \"4/7\";\n else\n if( f < 0.63 )\n return \"3/5\";\n else\n if( f < 0.66 )\n return \"5/8\";\n else\n return \"2/3\";\n else\n if( f < 0.80 )\n if( f < 0.74 )\n return \"5/7\";\n else\n if(f < 0.78 )\n return \"3/4\";\n else\n return \"7/9\";\n else\n if( f < 0.86 )\n if( f < 0.83 )\n return \"4/5\";\n else\n return \"5/6\";\n else\n if( f < 0.88 )\n return \"6/7\";\n else\n if( f < 0.89 )\n return \"7/8\";\n else\n if( f < 0.90 )\n return \"8/9\";\n else\n return \"9/10\";\n }\n" }, { "answer_id": 1992522, "author": "Debilski", "author_id": 200266, "author_profile": "https://Stackoverflow.com/users/200266", "pm_score": 5, "selected": false, "text": "fractions >>> from fractions import Fraction\n>>> Fraction('3.1415926535897932').limit_denominator(1000)\nFraction(355, 113)\n\n>>> from math import pi, cos\n>>> Fraction.from_float(cos(pi/3))\nFraction(4503599627370497, 9007199254740992)\n>>> Fraction.from_float(cos(pi/3)).limit_denominator()\nFraction(1, 2)\n" }, { "answer_id": 2912737, "author": "valodzka", "author_id": 159550, "author_profile": "https://Stackoverflow.com/users/159550", "pm_score": 0, "selected": false, "text": "Math.frac(0.2, 100) # => (1/5)\nMath.frac(0.33, 10) # => (1/3)\nMath.frac(0.33, 100) # => (33/100)\n" }, { "answer_id": 7457287, "author": "bpm", "author_id": 950575, "author_profile": "https://Stackoverflow.com/users/950575", "pm_score": 2, "selected": false, "text": "ostringstream sprintf ostringstream oss;\nfloat num;\ncin >> num;\noss << num;\nstring numStr = oss.str();\nint i = numStr.length(), pow_ten = 0;\nwhile (i > 0) {\n if (numStr[i] == '.')\n break;\n pow_ten++;\n i--;\n}\nfor (int j = 1; j < pow_ten; j++) {\n num *= 10.0;\n}\ncout << static_cast<int>(num) << \"/\" << pow(10, pow_ten - 1) << endl;\n" }, { "answer_id": 8584303, "author": "Tom", "author_id": 882436, "author_profile": "https://Stackoverflow.com/users/882436", "pm_score": 3, "selected": false, "text": "/// <summary>\n/// Represents a rational number\n/// </summary>\npublic struct Fraction\n{\n public int Numerator;\n public int Denominator;\n\n /// <summary>\n /// Constructor\n /// </summary>\n public Fraction(int numerator, int denominator)\n {\n this.Numerator = numerator;\n this.Denominator = denominator;\n }\n\n /// <summary>\n /// Approximates a fraction from the provided double\n /// </summary>\n public static Fraction Parse(double d)\n {\n return ApproximateFraction(d);\n }\n\n /// <summary>\n /// Returns this fraction expressed as a double, rounded to the specified number of decimal places.\n /// Returns double.NaN if denominator is zero\n /// </summary>\n public double ToDouble(int decimalPlaces)\n {\n if (this.Denominator == 0)\n return double.NaN;\n\n return System.Math.Round(\n Numerator / (double)Denominator,\n decimalPlaces\n );\n }\n\n\n /// <summary>\n /// Approximates the provided value to a fraction.\n /// http://stackoverflow.com/questions/95727/how-to-convert-floats-to-human-readable-fractions\n /// </summary>\n private static Fraction ApproximateFraction(double value)\n {\n const double EPSILON = .000001d;\n\n int n = 1; // numerator\n int d = 1; // denominator\n double fraction = n / d;\n\n while (System.Math.Abs(fraction - value) > EPSILON)\n {\n if (fraction < value)\n {\n n++;\n }\n else\n {\n d++;\n n = (int)System.Math.Round(value * d);\n }\n\n fraction = n / (double)d;\n }\n\n return new Fraction(n, d);\n }\n}\n" }, { "answer_id": 12564894, "author": "Ivan Kochurkin", "author_id": 1046374, "author_profile": "https://Stackoverflow.com/users/1046374", "pm_score": 2, "selected": false, "text": "/// <summary>\n/// Convert decimal to fraction\n/// </summary>\n/// <param name=\"value\">decimal value to convert</param>\n/// <param name=\"result\">result fraction if conversation is succsess</param>\n/// <param name=\"decimalPlaces\">precision of considereation frac part of value</param>\n/// <param name=\"trimZeroes\">trim zeroes on the right part of the value or not</param>\n/// <param name=\"minPeriodRepeat\">minimum period repeating</param>\n/// <param name=\"digitsForReal\">precision for determination value to real if period has not been founded</param>\n/// <returns></returns>\npublic static bool FromDecimal(decimal value, out Rational<T> result, \n int decimalPlaces = 28, bool trimZeroes = false, decimal minPeriodRepeat = 2, int digitsForReal = 9)\n{\n var valueStr = value.ToString(\"0.0000000000000000000000000000\", CultureInfo.InvariantCulture);\n var strs = valueStr.Split('.');\n\n long intPart = long.Parse(strs[0]);\n string fracPartTrimEnd = strs[1].TrimEnd(new char[] { '0' });\n string fracPart;\n\n if (trimZeroes)\n {\n fracPart = fracPartTrimEnd;\n decimalPlaces = Math.Min(decimalPlaces, fracPart.Length);\n }\n else\n fracPart = strs[1];\n\n result = new Rational<T>();\n try\n {\n string periodPart;\n bool periodFound = false;\n\n int i;\n for (i = 0; i < fracPart.Length; i++)\n {\n if (fracPart[i] == '0' && i != 0)\n continue;\n\n for (int j = i + 1; j < fracPart.Length; j++)\n {\n periodPart = fracPart.Substring(i, j - i);\n periodFound = true;\n decimal periodRepeat = 1;\n decimal periodStep = 1.0m / periodPart.Length;\n var upperBound = Math.Min(fracPart.Length, decimalPlaces);\n int k;\n for (k = i + periodPart.Length; k < upperBound; k += 1)\n {\n if (periodPart[(k - i) % periodPart.Length] != fracPart[k])\n {\n periodFound = false;\n break;\n }\n periodRepeat += periodStep;\n }\n\n if (!periodFound && upperBound - k <= periodPart.Length && periodPart[(upperBound - i) % periodPart.Length] > '5')\n {\n var ind = (k - i) % periodPart.Length;\n var regroupedPeriod = (periodPart.Substring(ind) + periodPart.Remove(ind)).Substring(0, upperBound - k);\n ulong periodTailPlusOne = ulong.Parse(regroupedPeriod) + 1;\n ulong fracTail = ulong.Parse(fracPart.Substring(k, regroupedPeriod.Length));\n if (periodTailPlusOne == fracTail)\n periodFound = true;\n }\n\n if (periodFound && periodRepeat >= minPeriodRepeat)\n {\n result = FromDecimal(strs[0], fracPart.Substring(0, i), periodPart);\n break;\n }\n else\n periodFound = false;\n }\n\n if (periodFound)\n break;\n }\n\n if (!periodFound)\n {\n if (fracPartTrimEnd.Length >= digitsForReal)\n return false;\n else\n {\n result = new Rational<T>(long.Parse(strs[0]), 1, false);\n if (fracPartTrimEnd.Length != 0)\n result = new Rational<T>(ulong.Parse(fracPartTrimEnd), TenInPower(fracPartTrimEnd.Length));\n return true;\n }\n }\n\n return true;\n }\n catch\n {\n return false;\n }\n}\n\npublic static Rational<T> FromDecimal(string intPart, string fracPart, string periodPart)\n{\n Rational<T> firstFracPart;\n if (fracPart != null && fracPart.Length != 0)\n {\n ulong denominator = TenInPower(fracPart.Length);\n firstFracPart = new Rational<T>(ulong.Parse(fracPart), denominator);\n }\n else\n firstFracPart = new Rational<T>(0, 1, false);\n\n Rational<T> secondFracPart;\n if (periodPart != null && periodPart.Length != 0)\n secondFracPart =\n new Rational<T>(ulong.Parse(periodPart), TenInPower(fracPart.Length)) *\n new Rational<T>(1, Nines((ulong)periodPart.Length), false);\n else\n secondFracPart = new Rational<T>(0, 1, false);\n\n var result = firstFracPart + secondFracPart;\n if (intPart != null && intPart.Length != 0)\n {\n long intPartLong = long.Parse(intPart);\n result = new Rational<T>(intPartLong, 1, false) + (intPartLong == 0 ? 1 : Math.Sign(intPartLong)) * result;\n }\n\n return result;\n}\n\nprivate static ulong TenInPower(int power)\n{\n ulong result = 1;\n for (int l = 0; l < power; l++)\n result *= 10;\n return result;\n}\n\nprivate static decimal TenInNegPower(int power)\n{\n decimal result = 1;\n for (int l = 0; l > power; l--)\n result /= 10.0m;\n return result;\n}\n\nprivate static ulong Nines(ulong power)\n{\n ulong result = 9;\n if (power >= 0)\n for (ulong l = 0; l < power - 1; l++)\n result = result * 10 + 9;\n return result;\n}\n Rational<long>.FromDecimal(0.33333333m, out r, 8, false);\n// then r == 1 / 3;\n\nRational<long>.FromDecimal(0.33333333m, out r, 9, false);\n// then r == 33333333 / 100000000;\n Rational<long>.FromDecimal(0.33m, out r, 28, true);\n// then r == 1 / 3;\n\nRational<long>.FromDecimal(0.33m, out r, 28, true);\n// then r == 33 / 100;\n Rational<long>.FromDecimal(0.123412m, out r, 28, true, 1.5m));\n// then r == 1234 / 9999;\nRational<long>.FromDecimal(0.123412m, out r, 28, true, 1.6m));\n// then r == 123412 / 1000000; because of minimu repeating of period is 0.1234123 in this case.\n Rational<long>.FromDecimal(0.8888888888888888888888888889m, out r));\n// then r == 8 == 9;\n Rational<long>.FromDecimal(0.12345678m, out r, 28, true, 2, 9);\n// then r == 12345678 / 100000000;\n\nRational<long>.FromDecimal(0.12345678m, out r, 28, true, 2, 8);\n// Conversation failed, because of period has not been founded and there are too many digits in fraction part of input value.\n\nRational<long>.FromDecimal(0.12121212121212121m, out r, 28, true, 2, 9));\n// then r == 4 / 33; Despite of too many digits in input value, period has been founded. Thus it's possible to convert value to fraction.\n" }, { "answer_id": 13774496, "author": "Josh W Lewis", "author_id": 1406964, "author_profile": "https://Stackoverflow.com/users/1406964", "pm_score": 2, "selected": false, "text": "0.33.rationalize.to_s # => \"33/100\"\n0.4.rationalize.to_s # => \"2/5\"\n product.size = 0.33\nproduct.size.to_r.to_s # => \"33/100\"\n" }, { "answer_id": 14085473, "author": "Ben Bolker", "author_id": 190277, "author_profile": "https://Stackoverflow.com/users/190277", "pm_score": 2, "selected": false, "text": "library(MASS)\nfractions(0.666666666)\n## [1] 2/3\n cycles max.denominator" }, { "answer_id": 20468509, "author": "Deepak Joy Cheenath", "author_id": 446215, "author_profile": "https://Stackoverflow.com/users/446215", "pm_score": 1, "selected": false, "text": "/* This should convert any decimals to a simplified fraction within the range specified by the two for loops. Haven't done any thorough testing, but it seems to work fine.\n\nI have set the bounds for numerator and denominator to 20, 20... but you can increase this if you want in the two for loops.\n\nDisclaimer: Its not at all optimized. (Feel free to create an improved version.)\n*/\n\ndecimalToSimplifiedFraction = function(n) {\n \nfor(num = 1; num < 20; num++) { // \"num\" is the potential numerator\n for(den = 1; den < 20; den++) { // \"den\" is the potential denominator\n var multiplyByInverse = (n * den ) / num;\n \n var roundingError = Math.round(multiplyByInverse) - multiplyByInverse;\n \n // Checking if we have found the inverse of the number, \n if((Math.round(multiplyByInverse) == 1) && (Math.abs(roundingError) < 0.01)) {\n return num + \"/\" + den;\n }\n }\n}\n};\n\n//Put in your test number here.\nvar floatNumber = 2.56;\n\nalert(floatNumber + \" = \" + decimalToSimplifiedFraction(floatNumber));" }, { "answer_id": 20834613, "author": "barak manos", "author_id": 1382251, "author_profile": "https://Stackoverflow.com/users/1382251", "pm_score": 2, "selected": false, "text": "BigInt unsigned long long void GetRational(double val)\n{\n if (val == val+1) // Inf\n throw \"Infinite Value\";\n if (val != val) // NaN\n throw \"Undefined Value\";\n\n bool sign = false;\n BigInt enumerator = 0;\n BigInt denominator = 1;\n\n if (val < 0)\n {\n val = -val;\n sign = true;\n }\n\n while (val > 0)\n {\n unsigned int intVal = (unsigned int)val;\n val -= intVal;\n enumerator += intVal;\n val *= 2;\n enumerator *= 2;\n denominator *= 2;\n }\n\n BigInt gcd = GCD(enumerator,denominator);\n enumerator /= gcd;\n denominator /= gcd;\n\n Print(sign? \"-\":\"+\");\n Print(enumerator);\n Print(\"/\");\n Print(denominator);\n\n // Or simply return {sign,enumerator,denominator} as you wish\n}\n" }, { "answer_id": 42197629, "author": "Kay Zed", "author_id": 344541, "author_profile": "https://Stackoverflow.com/users/344541", "pm_score": 2, "selected": false, "text": "double new Fraction(numerator, denominator) public Fraction RealToFraction(double value, double accuracy)\n{\n if (accuracy <= 0.0 || accuracy >= 1.0)\n {\n throw new ArgumentOutOfRangeException(\"accuracy\", \"Must be > 0 and < 1.\");\n }\n\n int sign = Math.Sign(value);\n\n if (sign == -1)\n {\n value = Math.Abs(value);\n }\n\n // Accuracy is the maximum relative error; convert to absolute maxError\n double maxError = sign == 0 ? accuracy : value * accuracy;\n\n int n = (int) Math.Floor(value);\n value -= n;\n\n if (value < maxError)\n {\n return new Fraction(sign * n, 1);\n }\n\n if (1 - maxError < value)\n {\n return new Fraction(sign * (n + 1), 1);\n }\n\n double z = value;\n int previousDenominator = 0;\n int denominator = 1;\n int numerator;\n\n do\n {\n z = 1.0 / (z - (int) z);\n int temp = denominator;\n denominator = denominator * (int) z + previousDenominator;\n previousDenominator = temp;\n numerator = Convert.ToInt32(value * denominator);\n }\n while (Math.Abs(value - (double) numerator / denominator) > maxError && z != (int) z);\n\n return new Fraction((n * denominator + numerator) * sign, denominator);\n}\n Accuracy: 1.0E-3 | Richards \nInput | Result Error \n======================| =============================\n 3 | 3/1 0 \n 0.999999 | 1/1 1.0E-6 \n 1.000001 | 1/1 -1.0E-6 \n 0.50 (1/2) | 1/2 0 \n 0.33... (1/3) | 1/3 0 \n 0.67... (2/3) | 2/3 0 \n 0.25 (1/4) | 1/4 0 \n 0.11... (1/9) | 1/9 0 \n 0.09... (1/11) | 1/11 0 \n 0.62... (307/499) | 8/13 2.5E-4 \n 0.14... (33/229) | 16/111 2.7E-4 \n 0.05... (33/683) | 10/207 -1.5E-4 \n 0.18... (100/541) | 17/92 -3.3E-4 \n 0.06... (33/541) | 5/82 -3.7E-4 \n 0.1 | 1/10 0 \n 0.2 | 1/5 0 \n 0.3 | 3/10 0 \n 0.4 | 2/5 0 \n 0.5 | 1/2 0 \n 0.6 | 3/5 0 \n 0.7 | 7/10 0 \n 0.8 | 4/5 0 \n 0.9 | 9/10 0 \n 0.01 | 1/100 0 \n 0.001 | 1/1000 0 \n 0.0001 | 1/10000 0 \n 0.33333333333 | 1/3 1.0E-11 \n 0.333 | 333/1000 0 \n 0.7777 | 7/9 1.0E-4 \n 0.11 | 10/91 -1.0E-3 \n 0.1111 | 1/9 1.0E-4 \n 3.14 | 22/7 9.1E-4 \n 3.14... (pi) | 22/7 4.0E-4 \n 2.72... (e) | 87/32 1.7E-4 \n 0.7454545454545 | 38/51 -4.8E-4 \n 0.01024801004 | 2/195 8.2E-4 \n 0.99011 | 100/101 -1.1E-5 \n 0.26... (5/19) | 5/19 0 \n 0.61... (37/61) | 17/28 9.7E-4 \n | \nAccuracy: 1.0E-4 | Richards \nInput | Result Error \n======================| =============================\n 0.62... (307/499) | 299/486 -6.7E-6 \n 0.05... (33/683) | 23/476 6.4E-5 \n 0.06... (33/541) | 33/541 0 \n 1E-05 | 1/99999 1.0E-5 \n 0.7777 | 1109/1426 -1.8E-7 \n 3.14... (pi) | 333/106 -2.6E-5 \n 2.72... (e) | 193/71 1.0E-5 \n 0.61... (37/61) | 37/61 0 \n" }, { "answer_id": 46127671, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "{-# LANGUAGE AllowAmbiguousTypes #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Monad (ap)\nimport Data.Functor.Foldable\nimport Data.Ratio (Ratio, (%))\n\nisInteger :: (RealFrac a) => a -> Bool\nisInteger = ((==) <*>) (realToFrac . floor)\n\ncontinuedFraction :: (RealFrac a) => a -> [Int]\ncontinuedFraction = liftA2 (:) floor (ana coalgebra)\n where coalgebra x\n | isInteger x = Nil\n | otherwise = Cons (floor alpha) alpha\n where alpha = 1 / (x - realToFrac (floor x))\n\ncollapseFraction :: (Integral a) => [Int] -> Ratio a\ncollapseFraction [x] = fromIntegral x % 1\ncollapseFraction (x:xs) = (fromIntegral x % 1) + 1 / collapseFraction xs\n\n-- | Use the nth convergent to approximate x\napproximate :: (RealFrac a, Integral b) => a -> Int -> Ratio b\napproximate x n = collapseFraction $ take n (continuedFraction x)\n λ:> approximate pi 2\n22 % 7\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4869/" ]
95,731
<p>Ran into this problem today, posting in case someone else has the same issue.</p> <pre><code>var execBtn = document.createElement('input'); execBtn.setAttribute("type", "button"); execBtn.setAttribute("id", "execBtn"); execBtn.setAttribute("value", "Execute"); execBtn.setAttribute("onclick", "runCommand();"); </code></pre> <p>Turns out to get IE to run an onclick on a dynamically generated element, we can't use setAttribute. Instead, we need to set the onclick property on the object with an anonymous function wrapping the code we want to run.</p> <pre><code>execBtn.onclick = function() { runCommand() }; </code></pre> <p><strong>BAD IDEAS:</strong></p> <p>You can do </p> <pre><code>execBtn.setAttribute("onclick", function() { runCommand() }); </code></pre> <p>but it will break in IE in non-standards mode according to @scunliffe.</p> <p>You can't do this at all </p> <pre><code>execBtn.setAttribute("onclick", runCommand() ); </code></pre> <p>because it executes immediately, and sets the result of runCommand() to be the onClick attribute value, nor can you do</p> <pre><code>execBtn.setAttribute("onclick", runCommand); </code></pre>
[ { "answer_id": 96018, "author": "kch", "author_id": 13989, "author_profile": "https://Stackoverflow.com/users/13989", "pm_score": 1, "selected": false, "text": "<div class=''> div.className <label for='...'> label.htmlFor setAttribute div.setAttribute('class', 'foo') div.setAttribute('className', 'foo')" }, { "answer_id": 561099, "author": "Shaike Katz", "author_id": 36899, "author_profile": "https://Stackoverflow.com/users/36899", "pm_score": 7, "selected": true, "text": "\n button_element.setAttribute('onclick','doSomething();'); // for FF\n button_element.onclick = function() {doSomething();}; // for IE\n // get old onclick attribute\nvar onclick = button_element.getAttribute(\"onclick\"); \n\n// if onclick is not a function, it's not IE7, so use setAttribute\nif(typeof(onclick) != \"function\") { \n button_element.setAttribute('onclick','doSomething();' + onclick); // for FF,IE8,Chrome\n\n// if onclick is a function, use the IE7 method and call onclick() in the anonymous function\n} else {\n button_element.onclick = function() { \n doSomething();\n onclick();\n }; // for IE7\n}\n" }, { "answer_id": 642929, "author": "David Berger", "author_id": 50272, "author_profile": "https://Stackoverflow.com/users/50272", "pm_score": 1, "selected": false, "text": "function makeEvent(element, callback, param, event) {\n function local() {\n return callback(param);\n }\n\n if (element.addEventListener) {\n //Mozilla\n element.addEventListener(event,local,false);\n } else if (element.attachEvent) {\n //IE\n element.attachEvent(\"on\"+event,local);\n }\n}\n\nmakeEvent(execBtn, alert, \"hey buddy, what's up?\", \"click\");\n" }, { "answer_id": 1070273, "author": "Marko", "author_id": 45516, "author_profile": "https://Stackoverflow.com/users/45516", "pm_score": 1, "selected": false, "text": "var rowIndex = 1;\nvar linkDeleter = document.createElement('a');\nlinkDeleter.setAttribute('href', \"javascript:function(\" + rowIndex + \");\");\n\nvar imgDeleter = document.createElement('img');\nimgDeleter.setAttribute('alt', \"Delete\");\nimgDeleter.setAttribute('src', \"Imagenes/DeleteHS.png\");\nimgDeleter.setAttribute('border', \"0\");\n\nlinkDeleter.appendChild(imgDeleter);\n" }, { "answer_id": 1070313, "author": "cdmckay", "author_id": 62571, "author_profile": "https://Stackoverflow.com/users/62571", "pm_score": 3, "selected": false, "text": "var execBtn = $(\"<input>\", {\n type: \"button\",\n id: \"execBtn\",\n value: \"Execute\"\n })\n .click(runCommand); \n" }, { "answer_id": 1276399, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "HtmlElement.onclick = myMethod;\n HtmlElement.onclick = new Function('myMethod(' + someParameter + ')');\n" }, { "answer_id": 3009590, "author": "Acorn", "author_id": 311220, "author_profile": "https://Stackoverflow.com/users/311220", "pm_score": 3, "selected": false, "text": "Events.addEvent(element, event, function); function hello() {\n alert('Hello');\n}\n\nvar button = document.createElement('input');\nbutton.value = \"Hello\";\nbutton.type = \"button\";\n\nEvents.addEvent(input_0, \"click\", hello);\n\ndocument.body.appendChild(button);\n // We create a function which is called immediately,\n// returning the actual function object. This allows us to\n// work in a separate scope and only return the functions\n// we require.\nvar Events = (function() {\n\n // For DOM2-compliant browsers.\n function addEventW3C(el, ev, f) {\n // Since IE only supports bubbling, for\n // compatibility we can't use capturing here.\n return el.addEventListener(ev, f, false);\n }\n\n function removeEventW3C(el, ev, f) {\n el.removeEventListener(ev, f, false);\n }\n\n // The function as required by IE.\n function addEventIE(el, ev, f) {\n // This is to work around a bug in IE whereby the\n // current element doesn't get passed as context.\n // We pass it via closure instead and set it as the\n // context using call().\n // This needs to be stored for removeEvent().\n // We also store the original wrapped function as a\n // property, _w.\n ((el._evts = el._evts || [])[el._evts.length]\n = function(e) { return f.call(el, e); })._w = f;\n\n // We prepend \"on\" to the event name.\n return el.attachEvent(\"on\" + ev,\n el._evts[el._evts.length - 1]);\n }\n\n function removeEventIE(el, ev, f) {\n for (var evts = el._evts || [], i = evts.length; i--; )\n if (evts[i]._w === f)\n el.detachEvent(\"on\" + ev, evts.splice(i, 1)[0]);\n }\n\n // A handler to call all events we've registered\n // on an element for legacy browsers.\n function addEventLegacyHandler(e) {\n var evts = this._evts[e.type];\n for (var i = 0; i < evts.length; ++i)\n if (!evts[i].call(this, e || event))\n return false;\n }\n\n // For older browsers. We basically reimplement\n // attachEvent().\n function addEventLegacy(el, ev, f) {\n if (!el._evts)\n el._evts = {};\n\n if (!el._evts[ev])\n el._evts[ev] = [];\n\n el._evts[ev].push(f);\n\n return true;\n }\n\n function removeEventLegacy(el, ev, f) {\n // Loop through the handlers for this event type\n // and remove them if they match f.\n for (var evts = el._evts[ev] || [], i = evts.length; i--; )\n if (evts[i] === f)\n evts.splice(i, 1);\n }\n\n // Select the appropriate functions based on what's\n // available on the window object and return them.\n return window.addEventListener\n ? {addEvent: addEventW3C, removeEvent: removeEventW3C}\n : window.attachEvent\n ? {addEvent: addEventIE, removeEvent: removeEventIE}\n : {addEvent: addEventLegacy, removeEvent: removeEventLegacy};\n})();\n if (el.addEventListener) { \n el.addEventListener('click', function, false); \n} else if (el.attachEvent) { \n el.attachEvent('onclick', function); \n} \n function changeInputType(oldObject, oType) {\n var newObject = document.createElement('input');\n newObject.type = oType;\n if(oldObject.size) newObject.size = oldObject.size;\n if(oldObject.value) newObject.value = oldObject.value;\n if(oldObject.name) newObject.name = oldObject.name;\n if(oldObject.id) newObject.id = oldObject.id;\n if(oldObject.className) newObject.className = oldObject.className;\n oldObject.parentNode.replaceChild(newObject,oldObject);\n return newObject;\n}\n" }, { "answer_id": 9684524, "author": "Titus", "author_id": 1266526, "author_profile": "https://Stackoverflow.com/users/1266526", "pm_score": 4, "selected": false, "text": "execBtn.onclick = function() { runCommand() };\n" }, { "answer_id": 14922726, "author": "Medyancev", "author_id": 2080704, "author_profile": "https://Stackoverflow.com/users/2080704", "pm_score": 2, "selected": false, "text": "function CheckBrowser(){\n if(navigator.userAgent.match(/Android/i)!=null||\n navigator.userAgent.match(/BlackBerry/i)!=null||\n navigator.userAgent.match(/iPhone|iPad|iPod/i)!=null||\n navigator.userAgent.match(/Nokia/i)!=null||\n navigator.userAgent.match(/Opera M/i)!=null||\n navigator.userAgent.match(/Chrome/i)!=null)\n {\n return 'OTHER';\n }else{\n return 'IE';\n }\n}\n\n\nfunction AddButt(i){\n var new_butt = document.createElement('input');\n new_butt.setAttribute('type','button');\n new_butt.setAttribute('value','Delete Item');\n new_butt.setAttribute('id', 'answer_del_'+i);\n if(CheckBrowser()=='IE'){\n new_butt.setAttribute(\"onclick\", function() { DelElemAnswer(i) });\n }else{\n new_butt.setAttribute('onclick','javascript:DelElemAnswer('+i+');');\n }\n}\n" }, { "answer_id": 18990475, "author": "Karl", "author_id": 2812568, "author_profile": "https://Stackoverflow.com/users/2812568", "pm_score": 2, "selected": false, "text": "x.setAttribute() x.appendChild()" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13289/" ]
95,760
<p>In order to distribute a function I've written that depends on other functions I've written that have their own dependencies and so on without distributing every m-file I have ever written, I need to figure out what the full list of dependencies is for a given m-file. Is there a built-in/freely downloadable way to do this?</p> <p>Specifically I am interested in solutions for MATLAB 7.4.0 (R2007a), but if there is a different way to do it in older versions, by all means please add them here. </p>
[ { "answer_id": 97072, "author": "Azim J", "author_id": 4612, "author_profile": "https://Stackoverflow.com/users/4612", "pm_score": 6, "selected": true, "text": ">> profile on % turn profiling on\n>> foo; % entry point to your matlab function or script\n>> profile off % turn profiling off\n>> profview % view the report\n >> deps = depfun('foo');\n matlab.codetools.requiredFilesAndProducts" }, { "answer_id": 29049918, "author": "Jonas Stein", "author_id": 1749675, "author_profile": "https://Stackoverflow.com/users/1749675", "pm_score": 3, "selected": false, "text": "MATLAB 2015a doc matlab.codetools.requiredFilesAndProducts depfun" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17231/" ]
95,767
<p>We'd like a trace in our application logs of these exceptions - by default Java just outputs them to the console.</p>
[ { "answer_id": 97176, "author": "shemnon", "author_id": 8020, "author_profile": "https://Stackoverflow.com/users/8020", "pm_score": 4, "selected": true, "text": "class AWTExceptionHandler {\n\n public void handle(Throwable t) {\n try {\n // insert your exception handling code here\n // or do nothing to make it go away\n } catch (Throwable t) {\n // don't let the exception get thrown out, will cause infinite looping!\n }\n }\n\n public static void registerExceptionHandler() {\n System.setProperty('sun.awt.exception.handler', AWTExceptionHandler.class.getName())\n }\n}\n" }, { "answer_id": 107439, "author": "Roland Schneider", "author_id": 16515, "author_profile": "https://Stackoverflow.com/users/16515", "pm_score": 2, "selected": false, "text": "public class AwtExceptionHandler {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(AwtExceptionHandler.class);\n\n private static List exceptionHandlerList = new LinkedList();\n\n /**\n * WARNING: Don't change the signature of this method!\n */\n public void handle(Throwable throwable) {\n if (exceptionHandlerList.isEmpty()) {\n LOGGER.error(\"Uncatched Throwable detected\", throwable);\n } else {\n delegate(new ExceptionEvent(throwable));\n }\n }\n\n private void delegate(ExceptionEvent event) {\n for (Iterator handlerIterator = exceptionHandlerList.iterator(); handlerIterator.hasNext();) {\n IExceptionHandler handler = (IExceptionHandler) handlerIterator.next();\n\n try {\n handler.handleException(event);\n if (event.isConsumed()) {\n break;\n }\n } catch (Throwable e) {\n LOGGER.error(\"Error while running exception handler: \" + handler, e);\n }\n }\n }\n\n public static void addErrorHandler(IExceptionHandler exceptionHandler) {\n exceptionHandlerList.add(exceptionHandler);\n }\n\n public static void removeErrorHandler(IExceptionHandler exceptionHandler) {\n exceptionHandlerList.remove(exceptionHandler);\n }\n\n}\n" }, { "answer_id": 27859016, "author": "ToYonos", "author_id": 2003986, "author_profile": "https://Stackoverflow.com/users/2003986", "pm_score": 4, "selected": false, "text": "sun.awt.exception.handler // Regular Exception\nThread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());\n\n// EDT Exception\nSwingUtilities.invokeAndWait(new Runnable()\n{\n public void run()\n {\n // We are in the event dispatching thread\n Thread.currentThread().setUncaughtExceptionHandler(new ExceptionHandler());\n }\n});\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18117/" ]
95,820
<p>Let's say I have an array, and I know I'm going to be doing a lot of "Does the array contain X?" checks. The efficient way to do this is to turn that array into a hash, where the keys are the array's elements, and then you can just say <pre>if($hash{X}) { ... }</pre></p> <p>Is there an easy way to do this array-to-hash conversion? Ideally, it should be versatile enough to take an anonymous array and return an anonymous hash.</p>
[ { "answer_id": 95826, "author": "raldi", "author_id": 7598, "author_profile": "https://Stackoverflow.com/users/7598", "pm_score": 8, "selected": true, "text": "%hash = map { $_ => 1 } @array;\n" }, { "answer_id": 95888, "author": "skiphoppy", "author_id": 18103, "author_profile": "https://Stackoverflow.com/users/18103", "pm_score": 5, "selected": false, "text": "@hash{@keys} = undef;\n @ $hash{$keys[0]} $hash{$keys[1]} $hash{$keys[2]} $hash{$keys[0]} undef @ if ($hash{$key} == 1) # then key is in the hash\n if (exists $hash{$key}) # then key is in the set\n exists undef undef" }, { "answer_id": 95998, "author": "Frosty", "author_id": 7476, "author_profile": "https://Stackoverflow.com/users/7476", "pm_score": 2, "selected": false, "text": "my %hash = map { $_,1 } @array;\n my %hash = map { $_,1 } split(\",\",$line)\n my %hash = map { split(\"=\",$_) } split(\",\",$line);\n my %hash;\n#The values in %hash can only be accessed by doing exists($hash{$key})\n#The assignment only works with '= undef;' and will not work properly with '= 1;'\n#if you do '= 1;' only the hash key of $array[0] will be set to 1;\n@hash{@array} = undef;\n" }, { "answer_id": 96088, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 5, "selected": false, "text": " @hash{@array} = (1) x @array;\n" }, { "answer_id": 96543, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 1, "selected": false, "text": "use Perl6::Junction qw'any';\n\nmy @arr = ( 1, 2, 3 );\n\nif( any(@arr) == 1 ){ ... }\n" }, { "answer_id": 98128, "author": "RET", "author_id": 14750, "author_profile": "https://Stackoverflow.com/users/14750", "pm_score": 3, "selected": false, "text": "sub invite_in {\n my $vampires = [ qw(Angel Darla Spike Drusilla) ];\n return ($_[0] ~~ $vampires) ? 0 : 1 ;\n}\n" }, { "answer_id": 98382, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 4, "selected": false, "text": "if ( exists $hash{ key } ) @hash{@key} = ();\n" }, { "answer_id": 99579, "author": "arclight", "author_id": 13366, "author_profile": "https://Stackoverflow.com/users/13366", "pm_score": 3, "selected": false, "text": "any() none() true() false() map() grep() print \"At least one value undefined\" if any { !defined($_) } @list; any() any() any() any()" }, { "answer_id": 111645, "author": "zby", "author_id": 20028, "author_profile": "https://Stackoverflow.com/users/20028", "pm_score": 1, "selected": false, "text": "$s = Set::Scalar->new( @array ) $s->contains($m)" }, { "answer_id": 111793, "author": "Keith", "author_id": 9444, "author_profile": "https://Stackoverflow.com/users/9444", "pm_score": 3, "selected": false, "text": "foreach my $item (@array) { $hash{$item} = 1 }\n" }, { "answer_id": 264160, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 1, "selected": false, "text": "my $hash_ref =\n sub{\n my %hash;\n @hash{ @{[ qw'one two three' ]} } = undef;\n return \\%hash;\n }->();\n sub keylist(@){\n my %hash;\n @hash{@_} = undef;\n return \\%hash;\n}\n\nmy $hash_ref = keylist qw'one two three';\n\n# or\n\nmy @key_list = qw'one two three';\nmy $hash_ref = keylist @key_list;\n sub keylist(\\@){\n my %hash;\n @hash{ @{$_[0]} } = undef if @_;\n return \\%hash;\n}\n\nmy @key_list = qw'one two three';\nmy $hash_ref = keylist @key_list;\n" }, { "answer_id": 7415443, "author": "Mark Dibley", "author_id": 944469, "author_profile": "https://Stackoverflow.com/users/944469", "pm_score": 1, "selected": false, "text": "#!/usr/bin/perl -w\n\nuse strict;\nuse Data::Dumper;\n\nmy @a = qw(5 8 2 5 4 8 9);\nmy @b = qw(7 6 5 4 3 2 1);\nmy $h = {};\n\n@{$h}{@a} = @b;\n\nprint Dumper($h);\n $VAR1 = {\n '8' => '2',\n '4' => '3',\n '9' => '1',\n '2' => '5',\n '5' => '4'\n };\n" }, { "answer_id": 7615613, "author": "Tamzin Blake", "author_id": 650551, "author_profile": "https://Stackoverflow.com/users/650551", "pm_score": 3, "selected": false, "text": "@keys @vals my %hash = map { $keys[$_] => $vals[$_] } (0..@keys-1);" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
95,821
<p>I have been playing with Haml recently and really like the way the resulting code looks to me...the developer. I'm also not too worried about a designer being able to consume or change it...we're a small team. </p> <p>That said, beginning work on a project we believe will generate quite a bit of traffic (who doesn't?). I'm concerned that there are things I just don't know about haml. Is there anything erb can do that haml can't? Does haml have a negative effect as a project grows? Are there other things that should be considered?</p> <p>And finally...how does Haml compare speedwise to erubis? I see that it supposedly beats erb and eruby now...</p> <p>Thanks!</p>
[ { "answer_id": 98591, "author": "outcassed", "author_id": 18424, "author_profile": "https://Stackoverflow.com/users/18424", "pm_score": 6, "selected": false, "text": "Haml::Template::options[:ugly] = true" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
95,824
<p>I'm looking for a way to do a substring replace on a string in LaTeX. What I'd like to do is build a command that I can call like this:</p> <pre><code>\replace{File,New} </code></pre> <p>and that would generate something like</p> <pre><code>\textbf{File}$\rightarrow$\textbf{New} </code></pre> <p>This is a simple example, but I'd like to be able to put formatting/structure in a single command rather than everywhere in the document. I know that I could build several commands that take increasing numbers of parameters, but I'm hoping that there is an easier way. </p> <p><strong>Edit for clarification</strong></p> <p>I'm looking for an equivalent of </p> <pre><code>string.replace(",", "$\rightarrow$) </code></pre> <p>something that can take an arbitrary string, and replace a substring with another substring.</p> <p>So I could call the command with \replace{File}, \replace{File,New}, \replace{File,Options,User}, etc., wrap the words with bold formatting, and replace any commas with the right arrow command. Even if the "wrapping with bold" bit is too difficult (as I think it might be), just the replace part would be helpful.</p>
[ { "answer_id": 95959, "author": "Brent.Longborough", "author_id": 9634, "author_profile": "https://Stackoverflow.com/users/9634", "pm_score": -1, "selected": false, "text": "\\newcommand{\\replace}[2]{\\textbf{#1}$\\rightarrow$\\textbf{#2}} \n\\replace{File}{New} \n" }, { "answer_id": 101032, "author": "Brent.Longborough", "author_id": 9634, "author_profile": "https://Stackoverflow.com/users/9634", "pm_score": 2, "selected": false, "text": "\\usepackage{forloop} \n\\usepackage[trim]{tokenizer} \n... \n\\newcounter{rrCount} \n\\newcommand{\\replace}[1]{% \n \\GetTokens{rrFirst}{rrRest}{#1,}% \n \\textbf{\\rrFirst}% \n \\forloop{rrCount}{0}{\\value{rrCount} < 100}{% \n \\ifthenelse{\\equal{\\rrRest}{}}{% \n \\setcounter{rrCount}{101}% \n }{% \n \\GetTokens{rrFirst}{rrRest}{\\rrRest}% \n $\\rightarrow$\\textbf{\\rrFirst}% \n }% \n }% \n}% \n% ----------------------------------------------------------------- \n\\replace{a1}\\\\ \n\\replace{a2,b2}\\\\ \n\\replace{a3,b3,c3}\\\\ \n" }, { "answer_id": 101403, "author": "Will Robertson", "author_id": 4161, "author_profile": "https://Stackoverflow.com/users/4161", "pm_score": 4, "selected": true, "text": "\\documentclass[12pt]{article}\n\\makeatletter\n\\newcommand\\formatnice[1]{%\n \\let\\@formatsep\\@formatsepinit\n \\@for\\@ii:=#1\\do{%\n \\@formatsep\n \\formatentry{\\@ii}%\n }%\n}\n\\def\\@formatsepinit{\\let\\@formatsep\\formatsep}\n\\makeatother\n\\newcommand\\formatsep{,}\n\\newcommand\\formatentry[1]{#1}\n\\begin{document}\n\\formatnice{abc,def}\n\n\\renewcommand\\formatsep{\\,$\\rightarrow$\\,}\n\\renewcommand\\formatentry[1]{\\textbf{#1}}\n\\formatnice{abc,def}\n\\end{document}\n" }, { "answer_id": 971839, "author": "Paul Biggar", "author_id": 104021, "author_profile": "https://Stackoverflow.com/users/104021", "pm_score": 2, "selected": false, "text": "xstring \\usepackage{xstring}\n\n[…]\n\n\\StrSubstitute{File,New}{,}{\\(\\rightarrow\\)}\n" }, { "answer_id": 5121142, "author": "Becheru Petru-Ioan", "author_id": 634651, "author_profile": "https://Stackoverflow.com/users/634651", "pm_score": 2, "selected": false, "text": "\\usepackage[trim]{tokenizer} \n\n\\def\\SH@GetTokens#1,#2\\@empty{%\n \\def\\SH@token{#1}%\n \\ifx\\SH@trimtokens\\SH@true% strip spaces if requested\n \\TrimSpaces\\SH@token%\n \\fi%\n \\SH@DefineCommand{\\SH@FirstArgName}{\\SH@token}%\n \\SH@DefineCommand{\\SH@SecondArgName}{#2}%\n }\n\\def\\SH@CheckTokenSep#1,#2\\@empty{%\n \\def\\SH@CTSArgTwo{#2}%\n \\ifx\\SH@CTSArgTwo\\@empty%\n \\edef\\SH@TokenValid{\\SH@false}%\n \\else%\n \\edef\\SH@TokenValid{\\SH@true}%\n \\fi%\n }\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1322/" ]
95,834
<p>I have a Windows Workflow application that uses classes I've written for COM automation. I'm opening Word and Excel from my classes using COM.</p> <p>I'm currently implementing IDisposable in my COM helper and using Marshal.ReleaseComObject(). However, if my Workflow fails, the Dispose() method isn't being called and the Word or Excel handles stay open and my application hangs.</p> <p>The solution to this problem is pretty straightforward, but rather than just solve it, I'd like to learn something and gain insight into the right way to work with COM. I'm looking for the "best" or most efficient and safest way to handle the lifecycle of the classes that own the COM handles. Patterns, best practices, or sample code would be helpful.</p>
[ { "answer_id": 96672, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 2, "selected": true, "text": " class Program\n {\n static void Main(string[] args)\n {\n using(WorkflowRuntime workflowRuntime = new WorkflowRuntime())\n {\n AutoResetEvent waitHandle = new AutoResetEvent(false);\n workflowRuntime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e) \n {\n waitHandle.Set();\n };\n workflowRuntime.WorkflowTerminated += delegate(object sender, WorkflowTerminatedEventArgs e)\n {\n Console.WriteLine(e.Exception.Message);\n waitHandle.Set();\n };\n\n WorkflowInstance instance = workflowRuntime.CreateWorkflow(typeof(WorkflowConsoleApplication1.Workflow1));\n instance.Start();\n\n waitHandle.WaitOne();\n }\n Console.ReadKey();\n }\n }\n public sealed partial class Workflow1: SequentialWorkflowActivity\n {\n public Workflow1()\n {\n InitializeComponent();\n this.codeActivity1.ExecuteCode += new System.EventHandler(this.codeActivity1_ExecuteCode);\n }\n\n [DebuggerStepThrough()]\n private void codeActivity1_ExecuteCode(object sender, EventArgs e)\n {\n Console.WriteLine(\"Throw ApplicationException.\");\n throw new ApplicationException();\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing)\n {\n // Here you must free your resources \n // by calling your COM helper Dispose() method\n Console.WriteLine(\"Object disposed.\");\n }\n }\n }\n" }, { "answer_id": 97059, "author": "Euro Micelli", "author_id": 2230, "author_profile": "https://Stackoverflow.com/users/2230", "pm_score": 0, "selected": false, "text": "MyComHelper helper = new MyComHelper();\nhelper.DoStuffWithExcel();\nhelper.Dispose();\n...\n MyComHelper helper = new MyComHelper();\ntry\n{\n helper.DoStuffWithExcel();\n}\nfinally()\n{\n helper.Dispose();\n}\n using(MyComHelper helper = new MyComHelper())\n{\n helper.DoStuffWithExcel();\n}\n using" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7565/" ]
95,842
<p>The name of a temporary table such as #t1 can be determined using </p> <pre><code>select @TableName = [Name] from tempdb.sys.tables where [Object_ID] = object_id('tempDB.dbo.#t1') </code></pre> <p>How can I find the name of a table valued variable, i.e. one declared by</p> <pre><code>declare @t2 as table (a int) </code></pre> <p>the purpose is to be able to get meta-information about the table, using something like</p> <pre><code>select @Headers = dbo.Concatenate('[' + c.[Name] + ']') from sys.all_columns c inner join sys.tables t on c.object_id = t.object_id where t.name = @TableName </code></pre> <p>although for temp tables you have to look in <code>tempdb.sys.tables</code> instead of <code>sys.tables</code>. where do you look for table valued variables?</p> <hr> <p>I realize now that I can't do what I wanted to do, which is write a generic function for formatting table valued variables into html tables. For starters, in sql server 2005 you can't pass table valued parameters:</p> <p><a href="http://www.sqlteam.com/article/sql-server-2008-table-valued-parameters" rel="nofollow noreferrer">http://www.sqlteam.com/article/sql-server-2008-table-valued-parameters</a></p> <p>moreover, in sql server 2008, the parameters have to be strongly typed, so you will always know the number and type of columns.</p>
[ { "answer_id": 215844, "author": "6eorge Jetson", "author_id": 23422, "author_profile": "https://Stackoverflow.com/users/23422", "pm_score": -1, "selected": false, "text": "CREATE FUNCTION [dbo].[udtShredXmlInputBondIdList] \n( \n-- Add the parameters for the function here\n@xmlInputBondIdList xml\n)\nRETURNS \n@tblResults TABLE \n(\n-- Add the column definitions for the TABLE variable here\n BondId int \n)\nAS\nBEGIN\n-- Should add a schema validation for @xmlInputIssuerIdList here\n--Place validation here\n-- Fill the table variable with the rows for your result set\nINSERT @tblResults\nSELECT \nnref.value('.', 'int') as BondId\nFROM\n@xmlInputBondIdList.nodes('//BondID') as R(nref)\nRETURN \nEND\n DECLARE @xmlInputBondIdList xml\nSET @xmlInputBondIdList =\n'<XmlInputBondIdList>\n\n<BondID>8681</BondID>\n\n<BondID>8680</BondID>\n\n<BondID>8684</BondID>\n\n</XmlInputBondIdList>\n'\n\nSELECT * \nFROM [CorporateBond].[dbo].[udtShredXmlInputBondIdList] \n (@xmlInputBondIdList)\n" }, { "answer_id": 8561729, "author": "Martin Smith", "author_id": 73226, "author_profile": "https://Stackoverflow.com/users/73226", "pm_score": 3, "selected": false, "text": "tempdb.sys.tables declare @t2 as table ( [38F055D8-25D9-4AA6-9571-F436FE] int)\n\nSELECT t.name, t.object_id\nFROM tempdb.sys.tables t\nJOIN tempdb.sys.columns c\nON t.object_id = c.object_id \nWHERE c.name = '38F055D8-25D9-4AA6-9571-F436FE'\n name object_id\n------------------------------ -----------\n#4DB4832C 1303675692\n %%physloc%% DBCC PAGE DECLARE @t2 AS TABLE ( a INT)\n\nINSERT INTO @t2\nVALUES (1)\n\nDECLARE @DynSQL NVARCHAR(100)\n\nSELECT TOP (1) @DynSQL = 'DBCC PAGE(2,' + CAST(file_id AS VARCHAR) + ',' + \n CAST( page_id AS VARCHAR) +\n ',1) WITH TABLERESULTS'\nFROM @t2\n CROSS APPLY sys.fn_PhysLocCracker( %% physloc %% )\n\nDECLARE @DBCCPage TABLE (\n [ParentObject] [VARCHAR](100) NULL,\n [Object] [VARCHAR](100) NULL,\n [Field] [VARCHAR](100) NULL,\n [VALUE] [VARCHAR](100) NULL )\n\nINSERT INTO @DBCCPage\nEXEC (@DynSQL)\n\nSELECT VALUE AS object_id,\n OBJECT_NAME(VALUE, 2) AS object_name\nFROM @DBCCPage\nWHERE Field = 'Metadata: ObjectId' \n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18116/" ]
95,850
<p>I'm looking for the total <a href="http://en.wikipedia.org/wiki/Commit_charge" rel="nofollow noreferrer">commit charge</a>.</p>
[ { "answer_id": 96094, "author": "JustinD", "author_id": 12063, "author_profile": "https://Stackoverflow.com/users/12063", "pm_score": 1, "selected": false, "text": "strComputer = \".\"\n\nSet objSWbemServices = GetObject(\"winmgmts:\\\\\" & strComputer)\nSet colSWbemObjectSet = _\n objSWbemServices.InstancesOf(\"Win32_LogicalMemoryConfiguration\")\n\nFor Each objSWbemObject In colSWbemObjectSet\n Wscript.Echo \"Total Physical Memory (kb): \" & _\n objSWbemObject.TotalPhysicalMemory\n WScript.Echo \"Total Virtual Memory (kb): \" & _\n objSWbemObject.TotalVirtualMemory\n WScript.Echo \"Total Page File Space (kb): \" & _\n objSWbemObject.TotalPageFileSpace\nNext\n" }, { "answer_id": 96240, "author": "Steve Cooper", "author_id": 6722, "author_profile": "https://Stackoverflow.com/users/6722", "pm_score": 3, "selected": true, "text": " public static long GetCommitCharge()\n {\n var p = new System.Diagnostics.PerformanceCounter(\"Memory\", \"Committed Bytes\");\n return p.RawValue;\n }\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337/" ]
95,858
<p>I have a web application that is dynamically loading PDF files for viewing in the browser. Currently, it uses "innerHTML" to replace a div with the PDF Object. This works.</p> <p>But, is there a better way to get the ID of the element and set the "src" or "data" parameter for the Object / Embed and have it instantly load up a new document? I'm hoping the instance of Adobe Acrobat Reader will stay on the screen, but the new document will load into it.</p> <p>Here is a JavaScript example of the object:</p> <pre><code>document.getElementById(`divPDF`).innerHTML = `&lt;OBJECT id='objPDF' DATA="'+strFilename+'" TYPE="application/pdf" TITLE="IMAGING" WIDTH="100%" HEIGHT="100%"&gt;&lt;/object&gt;`; </code></pre> <p>Any insight is appreciated.</p>
[ { "answer_id": 96296, "author": "Lark", "author_id": 8804, "author_profile": "https://Stackoverflow.com/users/8804", "pm_score": 1, "selected": false, "text": "$(\"objPDF\").attr({\n data: \"dir/to/newPDF\"\n});\n function pdfLoad(dirToPDF) {\n $(\"objPDF\").attr({\n data: dirToPDF\n });\n}\n" }, { "answer_id": 97306, "author": "Shinhan", "author_id": 18219, "author_profile": "https://Stackoverflow.com/users/18219", "pm_score": 0, "selected": false, "text": "$('#objPDF').attr('data','dirToPDF');\n" }, { "answer_id": 11385351, "author": "Daniel KUPPER", "author_id": 1510377, "author_profile": "https://Stackoverflow.com/users/1510377", "pm_score": 0, "selected": false, "text": "PDF-Reader.EXE <FORM action=\"\"> \n <INPUT type=\"button\" value=\"PDF file\" \n onclick=\"window.open('http://www.Dku-betrieb.eu/Pdfn.html', \n 'PDFN', 'width=620, height=630')\">\n</FORM>\n Pdfn.html <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Frameset//EN\" \"http://www.w3.org/TR/html4/frameset.dtd\">\n<html lang=\"de\">\n <meta http-equiv=\"refresh\" content=\"12;url=http://www.dku-betrieb.eu/Pdfn1.html\">\n <head>\n <title>Reader</title>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">\n </head>\n <frameset>\n <frame src=\"http://www.dku-betrieb.eu/File.pdf\" frameborder=0 name=\"p1\">\n </frameset>\n</HTML>\n <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Frameset//EN\" \"http://www.w3.org/TR/html4/frameset.dtd\">\n<html lang=\"de\">\n <head>\n <title>Reader</title>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">\n </head>\n <frameset >\n <frame src=\"http://www.dku-betrieb.eu/PDFReader.exe\" frameborder=0 name=\"p2\">\n </frameset>\n</HTML>\n" }, { "answer_id": 43938694, "author": "onur", "author_id": 2037521, "author_profile": "https://Stackoverflow.com/users/2037521", "pm_score": 0, "selected": false, "text": "function pdfLoad(datasrc) {\n\n var x = document.getElementById('objPDF');\n x.data = datasrc;\n\n }\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
95,866
<p>I have a simple table comments <code>(id INT, revision INT, comment VARCHAR(140))</code> with some content like this:</p> <pre><code>1|1|hallo1| 1|2|hallo2| 1|3|hallo3| 2|1|hallo1| 2|2|hallo2| </code></pre> <p>I'm searching for an SQL statement which will return each comment with the highest revision:</p> <pre><code>1|3|hallo3| 2|2|hallo2| </code></pre> <p>I've come up with this solution:</p> <pre><code>select id, revision, comment from comments where revision = ( select max(revision) from comments as f where f.id = comments.id ); </code></pre> <p>but it is very slow on large data sets. Are there any better queries to accomplish this?</p>
[ { "answer_id": 95914, "author": "nathaniel", "author_id": 11947, "author_profile": "https://Stackoverflow.com/users/11947", "pm_score": 3, "selected": false, "text": "SELECT c.* \n FROM comments c\n INNER JOIN (\n SELECT id,max(revision) AS maxrev \n FROM comments \n GROUP BY id\n ) b\n ON c.id=b.id AND c.revision=b.maxrev\n Subquery:\n25157 records\n2 seconds\nExecution plan includes an Index Seek (82%) base and a Segment (17%)\n\nLeft Outer Join:\n25160 records\n3 seconds\nExecution plan includes two Index Scans @ 22% each with a Right Outer Merge at 45% and a Filter at 11%\n" }, { "answer_id": 95979, "author": "devinmoore", "author_id": 15950, "author_profile": "https://Stackoverflow.com/users/15950", "pm_score": 4, "selected": false, "text": "SELECT comments.ID, comments.revision, comments.comment FROM comments \nLEFT OUTER JOIN comments AS maxcomments \nON maxcomments.ID= comments.ID\nAND maxcomments.revision > comments.revision\nWHERE maxcomments.revision IS NULL\n" }, { "answer_id": 96011, "author": "Nikki9696", "author_id": 456669, "author_profile": "https://Stackoverflow.com/users/456669", "pm_score": 2, "selected": false, "text": "select\nFIELD1, FIELD2, FIELD3\nfrom\nOURTABLE (nolock) T1\nWHERE FIELD3 = \n(\nSELECT MAX(FIELD3) FROM \nOURTABLE T2 (nolock)\nWHERE T1.FIELD2=T2.FIELD2\n)\nORDER BY FIELD2 DESC\n" }, { "answer_id": 96516, "author": "Garry Shutler", "author_id": 6369, "author_profile": "https://Stackoverflow.com/users/6369", "pm_score": 0, "selected": false, "text": "CurrentRevision bit not null\n select Id,\n Comment\nfrom Comments\nwhere CurrentRevision = 1\n" }, { "answer_id": 101025, "author": "Rowan", "author_id": 2087, "author_profile": "https://Stackoverflow.com/users/2087", "pm_score": 0, "selected": false, "text": "SELECT id, revision, comment \nFROM comments\nWHERE (id, revision) IN (\n SELECT id, MAX(revision)\n FROM comments\n -- WHERE clause comes here if needed\n GROUP BY id\n)\n" }, { "answer_id": 111393, "author": "borjab", "author_id": 16206, "author_profile": "https://Stackoverflow.com/users/16206", "pm_score": 0, "selected": false, "text": " SELECT c1.id, \n c1.revision, \n c1.comment \n FROM comments c1 \nINNER JOIN ( SELECT id, \n max(revision) AS max_revision\n FROM comments \n GROUP BY id ) c2\n ON c1.id = c2.id\n AND c1.revision = c2.max_revision\n" }, { "answer_id": 116070, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "select id, max_revision, comment\nfrom (select c.id, c.comment, c.revision, max(c.revision)over(partition by c.id) as max_revision\n from comments c)\nwhere revision = max_revision;\n" }, { "answer_id": 11609805, "author": "Patrick Savalle", "author_id": 1199612, "author_profile": "https://Stackoverflow.com/users/1199612", "pm_score": 0, "selected": false, "text": "SELECT c1.ID, c1.revision, c1.comment \nFROM comments AS c1\nLEFT JOIN comments AS c2 \n ON c1.ID = c2.ID\n AND c1.revision < c2.revision\nWHERE c2.revision IS NULL\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
95,875
<p>How do I see if a certain object has been loaded, and if not, how can it be loaded, like the following?</p> <pre><code>if (!isObjectLoaded(someVar)) { someVar= loadObject(); } </code></pre>
[ { "answer_id": 95898, "author": "Loren Segal", "author_id": 6436, "author_profile": "https://Stackoverflow.com/users/6436", "pm_score": 1, "selected": false, "text": "typeof(obj)" }, { "answer_id": 95901, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 5, "selected": false, "text": "if(typeof(o) != 'object') o = loadObject();\n" }, { "answer_id": 95935, "author": "rjzii", "author_id": 1185, "author_profile": "https://Stackoverflow.com/users/1185", "pm_score": 6, "selected": true, "text": "if (myObject === null || myObject === undefined) {\n myObject = loadObject();\n}\n" }, { "answer_id": 95958, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 2, "selected": false, "text": "object function isObjectType(obj, type) {\n return !!(obj && type && type.prototype && obj.constructor == type.prototype.constructor);\n}\n if (isObjectType(object, MyType)) { object = loadObject(); } object typeof object === 'undefined' if ('undefined' === typeof object) { object = loadObject(); }\n" }, { "answer_id": 95969, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 2, "selected": false, "text": " var generate = function()\n { \n window.foo = {}; \n }; \n var i = 0;\n var detect = function()\n {\n if( typeof window.foo == \"undefined\" ) \n {\n alert( \"Created!\"); \n clearInterval( i );\n }\n };\n setTimeout( generate, 15000 ); \n i = setInterval( detect, 100 ); \n" }, { "answer_id": 95970, "author": "Zach", "author_id": 9128, "author_profile": "https://Stackoverflow.com/users/9128", "pm_score": 2, "selected": false, "text": "// craete a custom object\nfunction MyObject(){\n\n}\n\n// check if it's the right kind of object\nif(!(object instanceof MyObject)){\n object = new MyObject();\n}\n" }, { "answer_id": 95971, "author": "ScottKoon", "author_id": 1538, "author_profile": "https://Stackoverflow.com/users/1538", "pm_score": 2, "selected": false, "text": "if(obj)" }, { "answer_id": 97034, "author": "Alan Storm", "author_id": 4668, "author_profile": "https://Stackoverflow.com/users/4668", "pm_score": 2, "selected": false, "text": "alert(typeof(null));\n if(null !== x && 'object' == typeof(x)){\n alert(\"Hey, It's an object or an array; good enough!\");\n}\n" }, { "answer_id": 4061756, "author": "Bruce", "author_id": 492556, "author_profile": "https://Stackoverflow.com/users/492556", "pm_score": 3, "selected": false, "text": "myObject = myObject || loadObject();\n" }, { "answer_id": 12548663, "author": "Mike Samuel", "author_id": 20394, "author_profile": "https://Stackoverflow.com/users/20394", "pm_score": 1, "selected": false, "text": "if (!(\"someVar\" in window)) {\n someVar = loadObject();\n}\n someVar var someVar undefined" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5261/" ]