qid
int64 1
82.4k
| question
stringlengths 27
22.5k
| answers
stringlengths 509
252k
| date
stringlengths 10
10
| metadata
stringlengths 108
162
|
---|---|---|---|---|
77,522 | <p>GDB has severe issues when debugging with multiple threads (pthreads).
Are there any other good multi-threaded debuggers for C/C++ on *nix?</p>
| [{'answer_id': 77575, 'author': 'X-Istence', 'author_id': 13986, 'author_profile': 'https://Stackoverflow.com/users/13986', 'pm_score': 1, 'selected': False, 'text': '<p>From my search, I have not found any good multi-thread debuggers for *nix. GDB seems to be getting better, and the last time I had to debug a multi-threaded application on FreeBSD (7.0-RELEASE) it behaved fairly well, letting me find where the error was.</p>\n'}, {'answer_id': 77576, 'author': 'magpulse', 'author_id': 13581, 'author_profile': 'https://Stackoverflow.com/users/13581', 'pm_score': 0, 'selected': False, 'text': "<p>I once looked for a gdb alternative, but unfortunately every one I found was based on gdb. I think this is because gdb is intricately tied to gcc, and it's hard for third-party debuggers to keep up with every gcc change.</p>\n"}, {'answer_id': 77636, 'author': 'Todd Gamblin', 'author_id': 9122, 'author_profile': 'https://Stackoverflow.com/users/9122', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://www.roguewave.com/products/totalview.aspx" rel="nofollow noreferrer">TotalView</a> is what the national labs use for huge clusters. I believe it has some good support for thread parallelism, too. It\'s probably out of your price range, but you can try it for free.</p>\n'}, {'answer_id': 77680, 'author': 'Zach Burlingame', 'author_id': 2233, 'author_profile': 'https://Stackoverflow.com/users/2233', 'pm_score': 3, 'selected': False, 'text': '<p>I\'ve personally not had any GDB specific issues when debugging a multi-threaded application, so it may helpful for you to elaborate on exactly what "issues" you are having. It will help us answer you better.</p>\n\n<p>There are several aids that I have used in the past when debugging multi-threaded applications in linux, most of which build upon GDB rather than replace it. These include:</p>\n\n<ul>\n<li>DDD <a href="http://www.gnu.org/software/ddd/" rel="nofollow noreferrer">http://www.gnu.org/software/ddd/</a></li>\n<li>Eclipse <a href="http://www.eclipse.org/" rel="nofollow noreferrer">http://www.eclipse.org/</a></li>\n<li>Native POSIX Thread Library (NTPL) Trace Tool <a href="http://nptltracetool.sourceforge.net/" rel="nofollow noreferrer">http://nptltracetool.sourceforge.net/</a></li>\n</ul>\n\n<p>Additionally, if you are new to debugging in Linux (and even if you aren\'t!) I highly recommend the paper titled "Debugging Linux Applications" which you can find here:</p>\n\n<p><a href="http://www.scribd.com/doc/3009706/Debugging-Linux-Applications" rel="nofollow noreferrer">http://www.scribd.com/doc/3009706/Debugging-Linux-Applications</a></p>\n'}, {'answer_id': 77781, 'author': 'Ronny Brendel', 'author_id': 14114, 'author_profile': 'https://Stackoverflow.com/users/14114', 'pm_score': 3, 'selected': False, 'text': '<p><a href="http://www.allinea.com/products/ddt" rel="nofollow noreferrer">Allinea DDT</a> ... graphical debugger for scalar, multi-threaded and large-scale parallel applications that are written in C, C++ and Fortran.</p>\n'}, {'answer_id': 79212, 'author': 'EvilTeach', 'author_id': 7734, 'author_profile': 'https://Stackoverflow.com/users/7734', 'pm_score': 0, 'selected': False, 'text': "<p>The AIX debugger for windows, let's you debug multithread applications.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77522', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
77,528 | <p>I'm currently running Vista and I would like to manually complete the same operations as my Windows Service. Since the Windows Service is running under the Local System Account, I would like to emulate this same behavior. Basically, I would like to run CMD.EXE under the Local System Account.</p>
<p>I found information online which suggests lauching the CMD.exe using the DOS Task Scheduler AT command, but I received a Vista warning that "due to security enhancements, this task will run at the time excepted but not interactively." Here's a sample command:</p>
<pre><code>AT 12:00 /interactive cmd.exe
</code></pre>
<p>Another solution suggested creating a secondary Windows Service via the Service Control (sc.exe) which merely launches CMD.exe. </p>
<pre><code>C:\sc create RunCMDAsLSA binpath= "cmd" type=own type=interact
C:\sc start RunCMDAsLSA
</code></pre>
<p>In this case the service fails to start and results it the following error message:</p>
<pre><code>FAILED 1053: The service did not respond to the start or control request in a timely fashion.
</code></pre>
<p>The third suggestion was to launch CMD.exe via a Scheduled Task. Though you may run scheduled tasks under various accounts, I don't believe the Local System Account is one of them.</p>
<p>I've tried using the Runas as well, but think I'm running into the same restriction as found when running a scheduled task.</p>
<p>Thus far, each of my attempts have ended in failure. Any suggestions?</p>
| [{'answer_id': 77615, 'author': 'Bryant', 'author_id': 10893, 'author_profile': 'https://Stackoverflow.com/users/10893', 'pm_score': 3, 'selected': False, 'text': '<p>Found an answer <a href="http://blogs.msdn.com/adioltean/articles/271063.aspx" rel="noreferrer">here</a> which seems to solve the problem by adding /k start to the binPath parameter. So that would give you:</p>\n\n<p><code>sc create testsvc binpath= "cmd /K start" type= own type= interact</code></p>\n\n<p>However, Ben said that didn\'t work for him and when I tried it on Windows Server 2008 it did create the cmd.exe process under local system, but it wasn\'t interactive (I couldn\'t see the window). </p>\n\n<p>I don\'t think there is an easy way to do what you ask, but I\'m wondering why you\'re doing it at all? Are you just trying to see what is happening when you run your service? Seems like you could just use logging to determine what is happening instead of having to run the exe as local system...</p>\n'}, {'answer_id': 77623, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>if you can write a batch file that does not need to be interactive, try running that batch file as a service, to do what needs to be done.</p>\n'}, {'answer_id': 78691, 'author': 'Ben Griswold', 'author_id': 4115, 'author_profile': 'https://Stackoverflow.com/users/4115', 'pm_score': 9, 'selected': True, 'text': '<p>Though I haven\'t personally tested, I have good reason to believe that the above stated AT COMMAND solution will work for XP, 2000 and Server 2003. Per my and Bryant\'s testing, we\'ve identified that the same approach does not work with Vista or Windows Server 2008 -- most probably due to added security and the /interactive switch being deprecated. </p>\n\n<p>However, I came across this <a href="http://verbalprocessor.com/2007/12/05/running-a-cmd-prompt-as-local-system" rel="noreferrer">article</a> which demonstrates the use of <a href="http://download.sysinternals.com/files/PSTools.zip" rel="noreferrer">PSTools</a> from <a href="http://sysinternals.com/" rel="noreferrer">SysInternals</a> (which was acquired by Microsoft in July, 2006.) I launched the command line via the following and suddenly I was running under the Local Admin Account like magic:</p>\n\n<pre><code>psexec -i -s cmd.exe\n</code></pre>\n\n<p>PSTools works well. It\'s a lightweight, well-documented set of tools which provides an appropriate solution to my problem.</p>\n\n<p>Many thanks to those who offered help.</p>\n'}, {'answer_id': 5063705, 'author': 'James5001', 'author_id': 626221, 'author_profile': 'https://Stackoverflow.com/users/626221', 'pm_score': 2, 'selected': False, 'text': '<p>an alternative to this is Process hacker if you go into run as... (Interactive doesnt work for people with the security enhancments but that wont matter) and when box opens put Service into\nthe box type and put SYSTEM into user box and put C:\\Users\\Windows\\system32\\cmd.exe leave the rest click ok and boch you have got a window with cmd on it and run as system now do the other steps for yourself because im suggesting you know them</p>\n'}, {'answer_id': 16974787, 'author': 'raven', 'author_id': 2461825, 'author_profile': 'https://Stackoverflow.com/users/2461825', 'pm_score': 6, 'selected': False, 'text': '<ol>\n<li><a href="https://technet.microsoft.com/en-us/sysinternals/bb896649" rel="noreferrer">Download psexec.exe from Sysinternals</a>.</li>\n<li>Place it in your C:\\ drive.</li>\n<li>Logon as a standard or admin user and use the following command: <code>cd \\</code>. This places you in the root directory of your drive, where psexec is located.</li>\n<li>Use the following command: <code>psexec -i -s cmd.exe</code> where -i is for interactive and -s is for system account.</li>\n<li>When the command completes, a cmd shell will be launched. Type <code>whoami</code>; it will say \'system"</li>\n<li>Open taskmanager. Kill explorer.exe.</li>\n<li>From an elevated command shell type <code>start explorer.exe</code>.</li>\n<li>When explorer is launched notice the name "system" in start menu bar. Now you can delete some files in system32 directory which as admin you can\'t delete or as admin you would have to try hard to change permissions to delete those files.</li>\n</ol>\n\n<p>Users who try to rename or deleate System files in any protected directory of windows should know that all windows files are protected by DACLS while renaming a file you have to change the owner and replace TrustedInstaller which owns the file and make any user like a user who belongs to administrator group as owner of file then try to rename it after changing the permission, it will work and while you are running windows explorer with kernel privilages you are somewhat limited in terms of Network access for security reasons and it is still a research topic for me to get access back</p>\n'}, {'answer_id': 30543362, 'author': 'raven', 'author_id': 2461825, 'author_profile': 'https://Stackoverflow.com/users/2461825', 'pm_score': 3, 'selected': False, 'text': '<h2>Using Secure Desktop to run <code>cmd.exe</code> as <code>system</code></h2>\n\n<p>We can get kernel access through <code>CMD</code> in Windows XP/Vista/7/8.1 easily by attaching a debugger: </p>\n\n<pre><code>REG ADD "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\osk.exe" /v Debugger /t REG_SZ /d "C:\\windows\\system32\\cmd.exe"\n</code></pre>\n\n<ol>\n<li><p>Run <code>CMD</code> as Administrator</p></li>\n<li><p>Then use this command in Elevated:</p>\n\n<pre><code> CMD REG ADD "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\osk.exe" /v Debugger /t REG_SZ /d "C:\\windows\\system32\\cmd.exe"\n</code></pre></li>\n<li><p>Then run <code>osk</code> (onscreenkeyboard). It still does not run with system Integrity level if you check through process explorer, but if you can use OSK in service session, it will run as <code>NT Authority\\SYSTEM</code></p></li>\n</ol>\n\n<p>so I had the idea you have to run it on Secure Desktop.</p>\n\n<p>Start any file as Administrator. When UAC prompts appear, just press <kbd>Win</kbd>+<kbd>U</kbd> and start <code>OSK</code> and it will start <code>CMD</code> instead. Then in the elevated prompt, type <code>whoami</code> and you will get <code>NT Authority\\System</code>. After that, you can start Explorer from the system command shell and use the System profile, but you are somewhat limited what you can do on the network through SYSTEM privileges for security reasons. I will add more explanation later as I discovered it a year ago.</p>\n\n<h2>A Brief Explanation of how this happens</h2>\n\n<p>Running <code>Cmd.exe</code> Under Local System Account Without Using <code>PsExec</code>. This method runs Debugger Trap technique that was discovered earlier, well this technique has its own benefits it can be used to trap some crafty/malicious worm or malware in the debugger and run some other exe instead to stop the spread or damage temporary. here this registry key traps onscreen keyboard in windows native debugger and runs cmd.exe instead but cmd will still run with Logged on users privileges, however if we run cmd in session0 we can get system shell. so we add here another idea we span the cmd on secure desktop remember secure desktop runs in session 0 under system account and we get system shell. So whenever you run anything as elevated, you have to answer the UAC prompt and UAC prompts on dark, non interactive desktop and once you see it you have to press <kbd>Win</kbd>+<kbd>U</kbd> and then select <code>OSK</code> you will get <code>CMD.exe</code> running under Local system privileges. There are even more ways to get local system access with <code>CMD</code></p>\n'}, {'answer_id': 50329723, 'author': 'Alexander Haakan', 'author_id': 9214134, 'author_profile': 'https://Stackoverflow.com/users/9214134', 'pm_score': 2, 'selected': False, 'text': '<p>There is another way. There is a program called PowerRun which allows for elevated cmd to be run. Even with TrustedInstaller rights. It allows for both console and GUI commands. </p>\n'}, {'answer_id': 50881442, 'author': 'anton_rh', 'author_id': 5447906, 'author_profile': 'https://Stackoverflow.com/users/5447906', 'pm_score': 1, 'selected': False, 'text': '<p>I use the <a href="https://github.com/jschicht/RunAsTI" rel="nofollow noreferrer"><em>RunAsTi</em></a> utility to run as <em>TrustedInstaller</em> (high privilege). The utility can be used even in recovery mode of Windows (the mode you enter by doing <code>Shift</code>+<code>Restart</code>), the <em>psexec</em> utility doesn\'t work there. But you need to add your <code>C:\\Windows</code> and <code>C:\\Windows\\System32</code> (not <code>X:\\Windows</code> and <code>X:\\Windows\\System32</code>) paths to the <code>PATH</code> environment variable, otherwise <em>RunAsTi</em> won\'t work in recovery mode, it will just print: <em>AdjustTokenPrivileges for SeImpersonateName: Not all privileges or groups referenced are assigned to the caller</em>.</p>\n'}, {'answer_id': 56399430, 'author': 'Paul Harris', 'author_id': 11584338, 'author_profile': 'https://Stackoverflow.com/users/11584338', 'pm_score': 1, 'selected': False, 'text': '<p>Using task scheduler, schedule a run of CMDKEY running under SYSTEM with the appropriate arguments of /add: /user: and /pass:</p>\n\n<p>No need to install anything.</p>\n'}, {'answer_id': 66005881, 'author': 'Alex Roberts', 'author_id': 5016790, 'author_profile': 'https://Stackoverflow.com/users/5016790', 'pm_score': 2, 'selected': False, 'text': "<p>(Comment)</p>\n<p>I can't comment yet, so posting here... I just tried the above OSK.EXE debug trick but regedit instantly closes when I save the filled "C:\\windows\\system32\\cmd.exe" into the already created Debugger key so Microsoft is actively working to block native ways to do this. It is really weird because other things do not trigger this.</p>\n<p>Using task scheduler does create a SYSTEM CMD but it is in the system environment and not displayed within a human user profile so this is also now defunct (though it is logical).</p>\n<p>Currently on Microsoft Windows [Version 10.0.20201.1000]</p>\n<p>So, at this point it has to be third party software that mediates this and further tricks are being more actively sealed by Microsoft these days.</p>\n"}, {'answer_id': 73283420, 'author': 'HandyManny', 'author_id': 7356180, 'author_profile': 'https://Stackoverflow.com/users/7356180', 'pm_score': 0, 'selected': False, 'text': '<p>i used Paul Harris recommendation and created a batch file .cmd or .bat with what ever command i needed to run under system and used the schedule task run one time.\nthan trigger it as needed. and updated the batch as needed. so any command i need to run under system i just update the batch.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77528', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4115/'] |
77,531 | <p>When I installed Windows Server 2008 I didn't have the (activation) key. Now that I have it I can't find where to enter it. Anybody know?</p>
| [{'answer_id': 77549, 'author': 'Bryant', 'author_id': 10893, 'author_profile': 'https://Stackoverflow.com/users/10893', 'pm_score': 5, 'selected': True, 'text': '<p>Go to Control Panel\\System and then under Windows Activation click "Change Product Key".</p>\n'}, {'answer_id': 77550, 'author': 'Joshua Hudson', 'author_id': 6232, 'author_profile': 'https://Stackoverflow.com/users/6232', 'pm_score': 0, 'selected': False, 'text': '<p>I know in Vista this is done from the system control panel. I would check there in Server 2008.</p>\n'}, {'answer_id': 77579, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>There might be an icon down in the tray, or it will prompt you during logon. I don't recall how long it will take to prompt you, or if it takes any time at all.</p>\n\n<p>Try rebooting and logging on.</p>\n"}, {'answer_id': 37013518, 'author': 'user6287731', 'author_id': 6287731, 'author_profile': 'https://Stackoverflow.com/users/6287731', 'pm_score': 0, 'selected': False, 'text': '<p>open command window. </p>\n\n<p>type slui 4 </p>\n\n<p>follow wizard</p>\n'}, {'answer_id': 37838169, 'author': 'Michael T. Will', 'author_id': 6470080, 'author_profile': 'https://Stackoverflow.com/users/6470080', 'pm_score': 0, 'selected': False, 'text': '<p>Right click on <strong>Computer</strong> and select <strong>Properties</strong>. Then select <strong>Change product key</strong> under the <em>Windows activation</em> section.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77531', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1463/'] |
77,534 | <p>When running wsdl.exe on a WSDL I created, I get this error:</p>
<blockquote>
<p>Error: Unable to import binding 'SomeBinding' from namespace 'SomeNS'.</p>
<ul>
<li>Unable to import operation 'someOperation'.</li>
<li>These members may not be derived.</li>
</ul>
</blockquote>
<p>I'm using the document-literal style, and to the best of my knowledge I'm following all the rules.</p>
<p>To sum it up, I have a valid WSDL, but the tool doesn't like it.</p>
<p>What I'm looking for is if someone has lots of experience with the wsdl.exe tool and knows about some secret gotcha that I don't.</p>
| [{'answer_id': 472991, 'author': 'thehhv', 'author_id': 53512, 'author_profile': 'https://Stackoverflow.com/users/53512', 'pm_score': 7, 'selected': True, 'text': '<p>I have came across to the same error message. After digging for a while, found out that one can supply xsd files in addition to wsdl file. So included/imported .xsd files in addition to .wsdl at the end of the wsdl command as follows:</p>\n\n<blockquote>\n <p>wsdl.exe myWebService.wsdl myXsd1.xsd myType1.xsd myXsd2.xsd ...</p>\n</blockquote>\n\n<p>Wsdl gave some warnings but it did create an ok service interface.</p>\n'}, {'answer_id': 4269920, 'author': 'mo.', 'author_id': 178454, 'author_profile': 'https://Stackoverflow.com/users/178454', 'pm_score': 3, 'selected': False, 'text': '<p>sometimes u have to change ur code.\nthe message part-names should not the same ;)</p>\n\n<pre><code><wsdl:message name="AnfrageRisikoAnfrageL">\n <wsdl:part name="parameters" element="his1_0:typeIn"/>\n</wsdl:message>\n<wsdl:message name="AnfrageRisikoAntwortL">\n <wsdl:part name="parameters" element="his1_0:typeOut"/>\n</wsdl:message>\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code><wsdl:message name="AnfrageRisikoAnfrageL">\n <wsdl:part name="in" element="his1_0:typeIn"/>\n</wsdl:message>\n<wsdl:message name="AnfrageRisikoAntwortL">\n <wsdl:part name="out" element="his1_0:typeOut"/>\n</wsdl:message>\n</code></pre>\n'}, {'answer_id': 27252843, 'author': 'Matas Vaitkevicius', 'author_id': 1509764, 'author_profile': 'https://Stackoverflow.com/users/1509764', 'pm_score': 2, 'selected': False, 'text': '<p>@thehhv solution is correct. There\'s workaround that does not require you to add <code>xsd</code>s by hand.</p>\n\n<p>Go to your service then instead of going <code>?wsdl</code> go to <code>?singleWsdl</code> (screenshot below)</p>\n\n<p><img src="https://i.stack.imgur.com/PpDs0.png" alt="enter image description here"> </p>\n\n<p>then save page as <code>.wsdl</code> file (it will offer <code>.svc</code> so change it)</p>\n\n<p>then open <code>Visual studio command prompt</code> you can find it in (Win 7) Start -> All Programs -> Visual studio 2013 -> Visual Studio tools -> VS2013 x64 Native Tools Command Prompt (could be something simmilar)<br>\nThen run the following command in <code>Visual studio command prompt</code> (where instead of C:\\WebPricingService.wsdl is where you have saved your wsdl, unless it so happens that we think very much alike and choose same file name and location which is worrying)</p>\n\n<pre><code>wsdl.exe C:\\WebPricingService.wsdl\n</code></pre>\n\n<p>It should give you some warnings as @thehhv said but still generate the client in <code>C:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\VC\\bin\\amd64\\WebPricingService.cs</code> (or wherever it puts it on your machine - check console output where it reads \'Writing file\')</p>\n\n<p><img src="https://i.stack.imgur.com/h782L.png" alt="enter image description here"></p>\n\n<p>Hope this saves you some time.</p>\n'}, {'answer_id': 33826526, 'author': 'BartoszKP', 'author_id': 2642204, 'author_profile': 'https://Stackoverflow.com/users/2642204', 'pm_score': 3, 'selected': False, 'text': '<p>In my case the problem was different, and is well described <a href="http://webservices20.blogspot.com/2010/01/interoperability-gotcha-these-members.html" rel="noreferrer">here</a>:</p>\n\n<blockquote>\n <p>Whenever the name of a part is "parameters" .Net assumed doc/lit/wrapped is used and generates the proxy accordingly. If even though the word "parameters" is used the wsdl is not doc/lit/wrapped (as in the last example) .Net may give us some error. Which error? You guessed correctly: "These members may not be derived". Now we can understand what the error means: .Net tries to omit the root element as it thinks doc/lit/wrapped is used. However this element cannot be removed since it is not dummy - it should be actively chosen by the user out of a few derived types.</p>\n</blockquote>\n\n<p>The fix is as follows, and worked perfectly for me:</p>\n\n<blockquote>\n <p>The way to fix it is open the wsdl in a text editor and change the part name from <strong>"parameters"</strong> to <strong>"parameters1"</strong>. Now .Net will know to generate a doc/lit/bare proxy. This means a new wrapper class will appear as the root parameter in the proxy. While this may be a little more tedious api, this will not have any affect on the wire format and the proxy is fully interoperable. </p>\n</blockquote>\n\n<p><sup>(emphasis by me)</sup></p>\n'}, {'answer_id': 44764622, 'author': 'Alex Sk', 'author_id': 5284180, 'author_profile': 'https://Stackoverflow.com/users/5284180', 'pm_score': 0, 'selected': False, 'text': '<p>In case someone hits this wall, here is what caused the error in my case:</p>\n\n<p>I have an operation:</p>\n\n<pre><code><wsdl:operation name="FormatReport">\n <wsdl:documentation>Runs a report, which is returned as the response</wsdl:documentation>\n <wsdl:input message="FormatReportRequest" />\n <wsdl:output message="FormatReportResponse" />\n</wsdl:operation>\n</code></pre>\n\n<p>which takes an input:</p>\n\n<pre><code><wsdl:message name="FormatReportRequest">\n <wsdl:part name="parameters" element="reporting:FormatReportInput" />\n</wsdl:message>\n</code></pre>\n\n<p>and another operation:</p>\n\n<pre><code><wsdl:operation name="FormatReportAsync">\n <wsdl:documentation>Creates and submits an Async Report Job to be executed asynchronously by the Async Report Windows Service.</wsdl:documentation>\n <wsdl:input message="FormatReportAsyncRequest" />\n <wsdl:output message="FormatReportAsyncResponse" />\n</wsdl:operation>\n</code></pre>\n\n<p>taking an input:</p>\n\n<pre><code> <wsdl:message name="FormatReportAsyncRequest">\n <wsdl:part name="parameters" element="reporting:FormatReportInputAsync" />\n </wsdl:message>\n</code></pre>\n\n<p>And the input elements are instances of two types:</p>\n\n<pre><code><xsd:element name="FormatReportInput" type="reporting:FormatReportInputType"/>\n<xsd:element name="FormatReportInputAsync" type="reporting:FormatReportAsyncInputType"/>\n</code></pre>\n\n<p>Here is the catch - the <code>reporting:FormatReportAsyncInputType</code> type extends (derives from) the <code>reporting:FormatReportInputType</code> type. That\'s what seems to confuse the tool and cause the "These members may not be derived." error. You can go around that following teh suggestion in the accepted answer.</p>\n'}, {'answer_id': 52749635, 'author': 'user2242618', 'author_id': 2242618, 'author_profile': 'https://Stackoverflow.com/users/2242618', 'pm_score': 0, 'selected': False, 'text': '<p>In case you are doing this with UPS Shipping wsdl and you want to swap dev to prod urls when you are building for different regions (debug,dev,prod) etc. You would use the command below to generate a vb or C# file from the Ship.wsdl and then override values in this case Ship.vb file. </p>\n\n<pre><code>WSDL /Language:VB /out:"C:\\wsdl\\Ship.vb" "C:\\wsdl\\Ship.wsdl" C:\\wsdl\\UPSSecurity.xsd C:\\wsdl\\ShipWebServiceSchema.xsd C:\\wsdl\\IFWS.xsd C:\\wsdl\\common.xsd\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5726/'] |
77,535 | <p>Has anyone found a way to get gcc to build/install on SCO6? With 2.95 and 4.3 I get to the point where it needs to use (2.95) or find (4.3) the assembler and that's where it fails.</p>
<p>If anyone has figured this out I would appreciate the info!</p>
<p>Thanks</p>
| [{'answer_id': 472991, 'author': 'thehhv', 'author_id': 53512, 'author_profile': 'https://Stackoverflow.com/users/53512', 'pm_score': 7, 'selected': True, 'text': '<p>I have came across to the same error message. After digging for a while, found out that one can supply xsd files in addition to wsdl file. So included/imported .xsd files in addition to .wsdl at the end of the wsdl command as follows:</p>\n\n<blockquote>\n <p>wsdl.exe myWebService.wsdl myXsd1.xsd myType1.xsd myXsd2.xsd ...</p>\n</blockquote>\n\n<p>Wsdl gave some warnings but it did create an ok service interface.</p>\n'}, {'answer_id': 4269920, 'author': 'mo.', 'author_id': 178454, 'author_profile': 'https://Stackoverflow.com/users/178454', 'pm_score': 3, 'selected': False, 'text': '<p>sometimes u have to change ur code.\nthe message part-names should not the same ;)</p>\n\n<pre><code><wsdl:message name="AnfrageRisikoAnfrageL">\n <wsdl:part name="parameters" element="his1_0:typeIn"/>\n</wsdl:message>\n<wsdl:message name="AnfrageRisikoAntwortL">\n <wsdl:part name="parameters" element="his1_0:typeOut"/>\n</wsdl:message>\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code><wsdl:message name="AnfrageRisikoAnfrageL">\n <wsdl:part name="in" element="his1_0:typeIn"/>\n</wsdl:message>\n<wsdl:message name="AnfrageRisikoAntwortL">\n <wsdl:part name="out" element="his1_0:typeOut"/>\n</wsdl:message>\n</code></pre>\n'}, {'answer_id': 27252843, 'author': 'Matas Vaitkevicius', 'author_id': 1509764, 'author_profile': 'https://Stackoverflow.com/users/1509764', 'pm_score': 2, 'selected': False, 'text': '<p>@thehhv solution is correct. There\'s workaround that does not require you to add <code>xsd</code>s by hand.</p>\n\n<p>Go to your service then instead of going <code>?wsdl</code> go to <code>?singleWsdl</code> (screenshot below)</p>\n\n<p><img src="https://i.stack.imgur.com/PpDs0.png" alt="enter image description here"> </p>\n\n<p>then save page as <code>.wsdl</code> file (it will offer <code>.svc</code> so change it)</p>\n\n<p>then open <code>Visual studio command prompt</code> you can find it in (Win 7) Start -> All Programs -> Visual studio 2013 -> Visual Studio tools -> VS2013 x64 Native Tools Command Prompt (could be something simmilar)<br>\nThen run the following command in <code>Visual studio command prompt</code> (where instead of C:\\WebPricingService.wsdl is where you have saved your wsdl, unless it so happens that we think very much alike and choose same file name and location which is worrying)</p>\n\n<pre><code>wsdl.exe C:\\WebPricingService.wsdl\n</code></pre>\n\n<p>It should give you some warnings as @thehhv said but still generate the client in <code>C:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\VC\\bin\\amd64\\WebPricingService.cs</code> (or wherever it puts it on your machine - check console output where it reads \'Writing file\')</p>\n\n<p><img src="https://i.stack.imgur.com/h782L.png" alt="enter image description here"></p>\n\n<p>Hope this saves you some time.</p>\n'}, {'answer_id': 33826526, 'author': 'BartoszKP', 'author_id': 2642204, 'author_profile': 'https://Stackoverflow.com/users/2642204', 'pm_score': 3, 'selected': False, 'text': '<p>In my case the problem was different, and is well described <a href="http://webservices20.blogspot.com/2010/01/interoperability-gotcha-these-members.html" rel="noreferrer">here</a>:</p>\n\n<blockquote>\n <p>Whenever the name of a part is "parameters" .Net assumed doc/lit/wrapped is used and generates the proxy accordingly. If even though the word "parameters" is used the wsdl is not doc/lit/wrapped (as in the last example) .Net may give us some error. Which error? You guessed correctly: "These members may not be derived". Now we can understand what the error means: .Net tries to omit the root element as it thinks doc/lit/wrapped is used. However this element cannot be removed since it is not dummy - it should be actively chosen by the user out of a few derived types.</p>\n</blockquote>\n\n<p>The fix is as follows, and worked perfectly for me:</p>\n\n<blockquote>\n <p>The way to fix it is open the wsdl in a text editor and change the part name from <strong>"parameters"</strong> to <strong>"parameters1"</strong>. Now .Net will know to generate a doc/lit/bare proxy. This means a new wrapper class will appear as the root parameter in the proxy. While this may be a little more tedious api, this will not have any affect on the wire format and the proxy is fully interoperable. </p>\n</blockquote>\n\n<p><sup>(emphasis by me)</sup></p>\n'}, {'answer_id': 44764622, 'author': 'Alex Sk', 'author_id': 5284180, 'author_profile': 'https://Stackoverflow.com/users/5284180', 'pm_score': 0, 'selected': False, 'text': '<p>In case someone hits this wall, here is what caused the error in my case:</p>\n\n<p>I have an operation:</p>\n\n<pre><code><wsdl:operation name="FormatReport">\n <wsdl:documentation>Runs a report, which is returned as the response</wsdl:documentation>\n <wsdl:input message="FormatReportRequest" />\n <wsdl:output message="FormatReportResponse" />\n</wsdl:operation>\n</code></pre>\n\n<p>which takes an input:</p>\n\n<pre><code><wsdl:message name="FormatReportRequest">\n <wsdl:part name="parameters" element="reporting:FormatReportInput" />\n</wsdl:message>\n</code></pre>\n\n<p>and another operation:</p>\n\n<pre><code><wsdl:operation name="FormatReportAsync">\n <wsdl:documentation>Creates and submits an Async Report Job to be executed asynchronously by the Async Report Windows Service.</wsdl:documentation>\n <wsdl:input message="FormatReportAsyncRequest" />\n <wsdl:output message="FormatReportAsyncResponse" />\n</wsdl:operation>\n</code></pre>\n\n<p>taking an input:</p>\n\n<pre><code> <wsdl:message name="FormatReportAsyncRequest">\n <wsdl:part name="parameters" element="reporting:FormatReportInputAsync" />\n </wsdl:message>\n</code></pre>\n\n<p>And the input elements are instances of two types:</p>\n\n<pre><code><xsd:element name="FormatReportInput" type="reporting:FormatReportInputType"/>\n<xsd:element name="FormatReportInputAsync" type="reporting:FormatReportAsyncInputType"/>\n</code></pre>\n\n<p>Here is the catch - the <code>reporting:FormatReportAsyncInputType</code> type extends (derives from) the <code>reporting:FormatReportInputType</code> type. That\'s what seems to confuse the tool and cause the "These members may not be derived." error. You can go around that following teh suggestion in the accepted answer.</p>\n'}, {'answer_id': 52749635, 'author': 'user2242618', 'author_id': 2242618, 'author_profile': 'https://Stackoverflow.com/users/2242618', 'pm_score': 0, 'selected': False, 'text': '<p>In case you are doing this with UPS Shipping wsdl and you want to swap dev to prod urls when you are building for different regions (debug,dev,prod) etc. You would use the command below to generate a vb or C# file from the Ship.wsdl and then override values in this case Ship.vb file. </p>\n\n<pre><code>WSDL /Language:VB /out:"C:\\wsdl\\Ship.vb" "C:\\wsdl\\Ship.wsdl" C:\\wsdl\\UPSSecurity.xsd C:\\wsdl\\ShipWebServiceSchema.xsd C:\\wsdl\\IFWS.xsd C:\\wsdl\\common.xsd\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77535', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14046/'] |
77,552 | <p>Why is it bad to name a variable <code>id</code> in Python?</p>
| [{'answer_id': 77563, 'author': 'ahockley', 'author_id': 8209, 'author_profile': 'https://Stackoverflow.com/users/8209', 'pm_score': -1, 'selected': False, 'text': "<p>Because it's the name of a builtin function.</p>\n"}, {'answer_id': 77600, 'author': 'Toni Ruža', 'author_id': 6267, 'author_profile': 'https://Stackoverflow.com/users/6267', 'pm_score': 3, 'selected': False, 'text': "<p>It's bad to name any variable after a built in function. One of the reasons is because it can be confusing to a reader that doesn't know the name is overridden.</p>\n"}, {'answer_id': 77606, 'author': 'brian buck', 'author_id': 5926, 'author_profile': 'https://Stackoverflow.com/users/5926', 'pm_score': 2, 'selected': False, 'text': '<p><code>id</code> is a built-in function in Python. Assigning a value to <code>id</code> will override the function. It is best to either add a prefix as in <code>some_id</code> or use it in a different capitalization as in <code>ID</code>.</p>\n<p>The built in function takes a single argument and returns an integer for the memory address of the object that you passed (in CPython).</p>\n<pre><code>>>> id(1)\n9787760\n>>> x = 1\n>>> id(x)\n9787760\n</code></pre>\n'}, {'answer_id': 77612, 'author': 'Kevin Little', 'author_id': 14028, 'author_profile': 'https://Stackoverflow.com/users/14028', 'pm_score': 9, 'selected': True, 'text': '<p><code>id()</code> is a fundamental built-in:</p>\n\n<blockquote>\n <p>Help on built-in function <code>id</code> in module\n <code>__builtin__</code>:</p>\n \n <pre class="lang-none prettyprint-override"><code>id(...)\n\n id(object) -> integer\n\n Return the identity of an object. This is guaranteed to be unique among\n simultaneously existing objects. (Hint: it\'s the object\'s memory\n address.)\n</code></pre>\n</blockquote>\n\n<p>In general, using variable names that eclipse a keyword or built-in function in any language is a bad idea, even if it is allowed.</p>\n'}, {'answer_id': 77925, 'author': 'Sebastian Rittau', 'author_id': 7779, 'author_profile': 'https://Stackoverflow.com/users/7779', 'pm_score': 6, 'selected': False, 'text': "<p>I might say something unpopular here: <code>id()</code> is a rather specialized built-in function that is rarely used in business logic. Therefore I don't see a problem in using it as a variable name in a tight and well-written function, where it's clear that id doesn't mean the built-in function.</p>\n"}, {'answer_id': 78433, 'author': 'Kitty', 'author_id': 14345, 'author_profile': 'https://Stackoverflow.com/users/14345', 'pm_score': -1, 'selected': False, 'text': "<p>Because python is a dynamic language, it's not usually a good idea to give a variable and a function the same name. id() is a function in python, so it's recommend not to use a variable named id. Bearing that in mind, that applies to all functions that you might use... a variable shouldn't have the same name as a function.</p>\n"}, {'answer_id': 79198, 'author': 'Nathan Shively-Sanders', 'author_id': 7851, 'author_profile': 'https://Stackoverflow.com/users/7851', 'pm_score': 6, 'selected': False, 'text': '<p><a href="https://docs.python.org/library/functions.html#id" rel="noreferrer"><code>id</code></a> is a built-in function that gives the identity of an object (which is also its memory address in CPython). If you name one of your functions <code>id</code>, you will have to say <a href="https://docs.python.org/library/builtins.html" rel="noreferrer"><code>builtins.id</code></a> to get the original (or <code>__builtins__.id</code> in CPython). Renaming <code>id</code> globally is confusing in anything but a small script.</p>\n<p>However, reusing built-in names as variables isn\'t all that bad as long as the use is local. Python has a <em>lot</em> of built-in functions that (1) have common names and (2) you will not use much anyway. Using these as local variables or as members of an object is OK because it\'s obvious from context what you\'re doing:</p>\n<p>Example:</p>\n<pre><code>def numbered(filename):\n with open(filename) as file:\n for i, input in enumerate(file):\n print("%s:\\t%s" % (i, input), end=\'\')\n</code></pre>\n<p>Some built-ins with tempting names:</p>\n<ul>\n<li><code>id</code></li>\n<li><code>file</code></li>\n<li><code>list</code>, <code>dict</code></li>\n<li><code>map</code></li>\n<li><code>all</code>, <code>any</code></li>\n<li><code>complex</code>, <code>int</code></li>\n<li><code>dir</code></li>\n<li><code>input</code></li>\n<li><code>slice</code></li>\n<li><code>buffer</code></li>\n<li><code>sum</code></li>\n<li><code>min</code>, <code>max</code></li>\n<li><code>object</code></li>\n</ul>\n'}, {'answer_id': 28091085, 'author': 'DavidRR', 'author_id': 1497596, 'author_profile': 'https://Stackoverflow.com/users/1497596', 'pm_score': 7, 'selected': False, 'text': '<p>In <strong>PEP 8 - Style Guide for Python Code</strong>, the following guidance appears in the section <a href="https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles" rel="noreferrer">Descriptive: Naming Styles </a>:</p>\n\n<blockquote>\n <ul>\n <li><p><code>single_trailing_underscore_</code> : used by convention to avoid conflicts\n with Python keyword, e.g.</p>\n \n <p><code>Tkinter.Toplevel(master, class_=\'ClassName\')</code></p></li>\n </ul>\n</blockquote>\n\n<p>So, to answer the question, an example that applies this guideline is:</p>\n\n<pre><code>id_ = 42\n</code></pre>\n\n<p>Including the trailing underscore in the variable name makes the intent clear (to those familiar with the guidance in PEP 8).</p>\n'}, {'answer_id': 62973285, 'author': 'wjandrea', 'author_id': 4518341, 'author_profile': 'https://Stackoverflow.com/users/4518341', 'pm_score': 3, 'selected': False, 'text': '<p>Others have mentioned that it\'s confusing, but I want to expand on <strong>why</strong>. Here\'s an example, based on a true story. Basically, I wrote a class that takes an <code>id</code> parameter but then tried to use the builtin <code>id</code> later.</p>\n<pre><code>class Employee:\n def __init__(self, name, id):\n """Create employee, with their name and badge id."""\n self.name = name\n self.id = id\n # ... lots more code, making you forget about the parameter names\n print(\'Created\', type(self).__name__, repr(name), \'at\', hex(id(self)))\n\ntay = Employee(\'Taylor Swift\', 1985)\n</code></pre>\n<p>Expected output:</p>\n<pre class="lang-none prettyprint-override"><code>Created Employee \'Taylor Swift\' at 0x7efde30ae910\n</code></pre>\n<p>Actual output:</p>\n<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):\n File "company.py", line 9, in <module>\n tay = Employee(\'Taylor Swift\', 1985)\n File "company.py", line 7, in __init__\n print(\'Created\', type(self).__name__, repr(name), \'at\', hex(id(self)))\nTypeError: \'int\' object is not callable\n</code></pre>\n<blockquote>\n<p><em>Huh? Where am I trying to call an int? Those are all builtins...</em></p>\n</blockquote>\n<p>If I had named it <code>badge_id</code> or <code>id_</code>, I wouldn\'t have had this problem.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77552', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5926/'] |
77,558 | <p>I want to write a raw byte/byte stream to a position in a file.
This is what I have currently:</p>
<pre><code>$fpr = fopen($out, 'r+');
fseek($fpr, 1); //seek to second byte
fwrite($fpr, 0x63);
fclose($fpr);
</code></pre>
<p>This currently writes the actually string value of "99" starting at byte offset 1. IE, it writes bytes "9" and "9". I just want to write the actual one byte value 0x63 which happens to represent number 99.</p>
<p>Thanks for your time.</p>
| [{'answer_id': 77585, 'author': 'nsayer', 'author_id': 13757, 'author_profile': 'https://Stackoverflow.com/users/13757', 'pm_score': 4, 'selected': True, 'text': '<p><code>fwrite()</code> takes strings. Try <code>chr(0x63)</code> if you want to write a <code>0x63</code> byte to the file.</p>\n'}, {'answer_id': 77597, 'author': 'Don Neufeld', 'author_id': 13097, 'author_profile': 'https://Stackoverflow.com/users/13097', 'pm_score': 1, 'selected': False, 'text': '<p>You are trying to pass an int to a function that accepts a string, so it\'s being converted to a string for you.</p>\n\n<p>This will write what you want:</p>\n\n<pre><code>fwrite($fpr, "\\x63");\n</code></pre>\n'}, {'answer_id': 77626, 'author': 'Paige Ruten', 'author_id': 813, 'author_profile': 'https://Stackoverflow.com/users/813', 'pm_score': 2, 'selected': False, 'text': "<p>That's because fwrite() expects a string as its second argument. Try doing this instead:</p>\n\n<pre><code>fwrite($fpr, chr(0x63));\n</code></pre>\n\n<p>chr(0x63) returns a string with one character with ASCII value 0x63. (So it'll write the number 0x63 to the file.)</p>\n"}, {'answer_id': 8965004, 'author': 'Christian', 'author_id': 314056, 'author_profile': 'https://Stackoverflow.com/users/314056', 'pm_score': 0, 'selected': False, 'text': '<p>If you really want to write binary to files, I would advise to use the <code>pack()</code> approach together with the file API.</p>\n\n<p><a href="https://stackoverflow.com/questions/5719803/what-is-the-realtime-use-of-php-pack-and-unpack-function">See this question</a> for an example.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77558', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10333/'] |
77,582 | <p>I am looking for a tool for regression testing a suite of equipment we are building.</p>
<p>The current concept is that you create an input file (text/csv) to the tool specifying inputs to the system under test. The tool then captures the outputs from the system and records the inputs and outputs to an output file. </p>
<p>The output is in the same format as the original input file and can be used as an input for following runs of the tool, with the measured outputs matched with the values from the previous run. </p>
<p>The results of two runs will not be exact matches, there are some timing differences that depend on the state of the battery, or which depend on other internal state of the equipment.</p>
<p>We would have to write our own interfaces to pass the commands from the tool to the equipment and to capture the output of the equipment.</p>
<p>This is a relatively simple task, but I am looking for an existing tool / package / library to avoid re-inventing the wheel / steal lessons from.</p>
| [{'answer_id': 77684, 'author': 'apenwarr', 'author_id': 42219, 'author_profile': 'https://Stackoverflow.com/users/42219', 'pm_score': 0, 'selected': False, 'text': '<p>You can just use any test framework. The hard part is writing the tools to send/retrieve the data from your test system, not the actual string comparisons.</p>\n\n<p>Your tests would just all look like this:</p>\n\n<pre><code>x = read_input_file(ifilename);\ny1 = read_expected_data(ofilename);\nsend_input_file_to_server();\ny2 = read_output_from_server();\ncheckequal(y1, y2)\n</code></pre>\n'}, {'answer_id': 77729, 'author': 'apenwarr', 'author_id': 42219, 'author_profile': 'https://Stackoverflow.com/users/42219', 'pm_score': 2, 'selected': False, 'text': '<p>I recently built a system like this on top of git (<a href="http://git.or.cz/" rel="nofollow noreferrer">http://git.or.cz/</a>). Basically, write a program that takes all your input files, sends them to the server, reads the output back, and writes it to a set of output files. After the first run, commit the output files to git.</p>\n\n<p>For future runs, your success is determined by whether the git repository is clean after the run finishes:</p>\n\n<pre><code>test 0 == $(git diff data/output/ | wc -l)\n</code></pre>\n\n<p>As a bonus, you can use all the git tools to compare differences, and commit them if it turns out the differences were an improvement, so that future runs will pass. It also works great when merging between branches.</p>\n'}, {'answer_id': 84903, 'author': 'Eli Bendersky', 'author_id': 8206, 'author_profile': 'https://Stackoverflow.com/users/8206', 'pm_score': 1, 'selected': False, 'text': "<p>I'm not sure there will be a single package that exactly suits your needs. You have a few considerations to make:</p>\n\n<ol>\n<li>How to pass data to the equipment and how to collect it back. This is very application specific, but a usually good option is the old'n'good serial port (RS232) for which an easy interfact exists for any programming language.</li>\n<li>How to run the tests. A unit-testing framework can definitely help you here. The existing frameworks have a lot of the basic features implemented - selecting tests to run, selecting the detail-level of the report (very important for detailed debugging at first and production-stage PASS/FAIL analysis later on). I've had good experience using the test frameworks of both Perl and Python from testing embedded devices.</li>\n<li>You also have to decide how to make the comparisons. As you correctly noted, the results won't be equal. This is where your domain knowledge comes in. Usually, it is simply implemented using error margins that are applicable in your domain. Of course, you won't be able to use a basic <code>diff</code> tool and will have to write an intelligent script.</li>\n</ol>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13923/'] |
77,598 | <p>I have an application written in java, and I want to add a flash front end to it. The flash front end will run on the same computer as the java app in the stand alone flash player. I need two way communication between the two parts, and have no idea how to even start going about this. I suppose I could open a socket between the two programs, but I feel that there must be an easier way. Is there a nice part of the api in actionscript 3.0 that will allow me to access java methods directly, or will I have to resort to sockets? I am relatively new to flash, by the way, so any good guides would be much appreciated!</p>
<p>Thanks</p>
| [{'answer_id': 77630, 'author': 'Aeon', 'author_id': 13289, 'author_profile': 'https://Stackoverflow.com/users/13289', 'pm_score': 4, 'selected': True, 'text': '<p><a href="http://en.wikipedia.org/wiki/Action_Message_Format" rel="nofollow noreferrer">AMF</a> is a messaging protocol commonly used to talk between flash and a backend system. There\'re several Java implementations, but I haven\'t used any of them so can\'t tell you which is best.</p>\n\n<ul>\n<li><a href="http://labs.adobe.com/technologies/blazeds/" rel="nofollow noreferrer">Blaze DS</a></li>\n<li><a href="http://www.osflash.org/red5" rel="nofollow noreferrer">Red5</a></li>\n<li><a href="http://www.graniteds.org/" rel="nofollow noreferrer">Granite DS</a></li>\n</ul>\n\n<p>Flash can also talk plain old XML, SOAP or REST to the backend, so depending on your codebase that might be easier.</p>\n'}, {'answer_id': 78113, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>MERAPI is a bridge framework for communication between Java and Flash.</p>\n'}, {'answer_id': 81916, 'author': 'Stu Thompson', 'author_id': 2961, 'author_profile': 'https://Stackoverflow.com/users/2961', 'pm_score': 2, 'selected': False, 'text': '<p>There is also <strong><a href="http://sourceforge.net/projects/openamf/" rel="nofollow noreferrer">OpenAMF</a></strong>. It is <em>very</em> mature, stable, simple and lightweight relative to Blaze, Red5 and Granite. </p>\n\n<p><strong>BUT</strong>, it is also dated (AMF0 protocol only) and the project is no longer active. Lots of people are still using it out in the wild. And the documentation is borderline non-existent. </p>\n'}, {'answer_id': 204371, 'author': 'baronDodd', 'author_id': 28198, 'author_profile': 'https://Stackoverflow.com/users/28198', 'pm_score': 1, 'selected': False, 'text': "<p>Granite DS is a good solution, it will allow you to set up services to communicate not only to POJO's but to EJB3 session beans also. It comes with a GAS code generator for converting your java beans into as3 equivalents and also data push to the client using the gravity side project.</p>\n"}, {'answer_id': 229340, 'author': 'user30684', 'author_id': 30684, 'author_profile': 'https://Stackoverflow.com/users/30684', 'pm_score': 0, 'selected': False, 'text': '<p>I agree on Granite DS. It was easy to setup and get going. </p>\n\n<p>I have used it to talk directly with a EJB3 bean communicating with thrift generated objects.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77598', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
77,603 | <p>We are developing automated regression tests using VMWare and NUnit. We have divided tests into steps and now I would like to see each step be examined for performance regression. Simply timing the tests, as NUnit does, does not seem reliable. I have figured in a acceptance factor of about 15% but our steps can differ sometimes to over 35%. In such a resource dependent test environment is there any consistent way of testing performance? Is a "smart" timing system my only option?</p>
| [{'answer_id': 77634, 'author': 'Mitchel Sellers', 'author_id': 13279, 'author_profile': 'https://Stackoverflow.com/users/13279', 'pm_score': 0, 'selected': False, 'text': "<p>You might look into the features available with a tool such as Ants Profiler as it does give method executing/run times, but I'm not sure what it offers in terms of repeated testing.</p>\n"}, {'answer_id': 77643, 'author': 'crackity_jones', 'author_id': 1474, 'author_profile': 'https://Stackoverflow.com/users/1474', 'pm_score': 0, 'selected': False, 'text': "<p>With respect to performance testing I've been very skeptical of using vmware or other virtualization processes. The way we have handled this in the past is to have part of the build install the latest version on a static machine and run the tests. You should see more consistent results outside of the virtualization. </p>\n"}, {'answer_id': 77788, 'author': 'apenwarr', 'author_id': 42219, 'author_profile': 'https://Stackoverflow.com/users/42219', 'pm_score': 4, 'selected': True, 'text': '<p>For this sort of performance testing, there\'s no such thing as a system that will give you a simple pass/fail result. In real life, changing your system is likely to make some things faster and some other things slower, so it\'s usually not a choice between "better" and "not better", it\'s a choice between different kinds of better. (Of course, you want to avoid cases where it\'s strictly worse.)</p>\n\n<p>What I\'ve done for this in the past is to just keep statistics over time. Every time you run your tests, drop the results in a SQL database with the revision number and the test timings. Then you can graph them whenever and however you want (ideally in a little web applet so everyone on the team can review them) and see if your performance is trending up or down, or if performance has been sucking ever since a particular revision.</p>\n\n<p>The key thing here, though, is that it needs to be a <em>graph</em>. That way human eyes can look at it and find the trends. You could spend all week trying to come up with an AI algorithm to analyse the data numerically, but it would never beat a human\'s pattern-recognition ability.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77603', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13688/'] |
77,632 | <p>I thought I'd offer this softball to whomever would like to hit it out of the park. What are generics, what are the advantages of generics, why, where, how should I use them? Please keep it fairly basic. Thanks.</p>
| [{'answer_id': 77652, 'author': 'Mitchel Sellers', 'author_id': 13279, 'author_profile': 'https://Stackoverflow.com/users/13279', 'pm_score': 2, 'selected': False, 'text': "<p>Generics allow you to create objects that are strongly typed, yet you don't have to define the specific type. I think the best useful example is the List and similar classes. </p>\n\n<p>Using the generic list you can have a List List List whatever you want and you can always reference the strong typing, you don't have to convert or anything like you would with a Array or standard List.</p>\n"}, {'answer_id': 77662, 'author': 'Darren Kopp', 'author_id': 77, 'author_profile': 'https://Stackoverflow.com/users/77', 'pm_score': 3, 'selected': False, 'text': "<p>Generics avoid the performance hit of boxing and unboxing. Basically, look at ArrayList vs List<T>. Both do the same core things, but List<T> will be a lot faster because you don't have to box to/from object.</p>\n"}, {'answer_id': 77663, 'author': 'Steve Landey', 'author_id': 8061, 'author_profile': 'https://Stackoverflow.com/users/8061', 'pm_score': 1, 'selected': False, 'text': '<p>Generics let you use strong typing for objects and data structures that should be able to hold any object. It also eliminates tedious and expensive typecasts when retrieving objects from generic structures (boxing/unboxing).</p>\n\n<p>One example that uses both is a linked list. What good would a linked list class be if it could only use object Foo? To implement a linked list that can handle any kind of object, the linked list and the nodes in a hypothetical node inner class must be generic if you want the list to contain only one type of object.</p>\n'}, {'answer_id': 77682, 'author': 'gt124', 'author_id': 14093, 'author_profile': 'https://Stackoverflow.com/users/14093', 'pm_score': 1, 'selected': False, 'text': "<p>If your collection contains value types, they don't need to box/unbox to objects when inserted into the collection so your performance increases dramatically. Cool add-ons like resharper can generate more code for you, like foreach loops.</p>\n"}, {'answer_id': 77691, 'author': 'Tom Kidd', 'author_id': 2577, 'author_profile': 'https://Stackoverflow.com/users/2577', 'pm_score': 3, 'selected': False, 'text': '<p>I just like them because they give you a quick way to define a custom type (as I use them anyway).</p>\n\n<p>So for example instead of defining a structure consisting of a string and an integer, and then having to implement a whole set of objects and methods on how to access an array of those structures and so forth, you can just make a Dictionary</p>\n\n<pre><code>Dictionary<int, string> dictionary = new Dictionary<int, string>();\n</code></pre>\n\n<p>And the compiler/IDE does the rest of the heavy lifting. A Dictionary in particular lets you use the first type as a key (no repeated values).</p>\n'}, {'answer_id': 77709, 'author': 'ljs', 'author_id': 3394, 'author_profile': 'https://Stackoverflow.com/users/3394', 'pm_score': 8, 'selected': True, 'text': '<ul>\n<li>Allows you to write code/use library methods which are type-safe, i.e. a List<string> is guaranteed to be a list of strings.</li>\n<li>As a result of generics being used the compiler can perform compile-time checks on code for type safety, i.e. are you trying to put an int into that list of strings? Using an ArrayList would cause that to be a less transparent runtime error.</li>\n<li>Faster than using objects as it either avoids boxing/unboxing (where .net has to convert <a href="https://stackoverflow.com/questions/5057267/what-is-the-difference-between-a-reference-type-and-value-type-in-c">value types to reference types or vice-versa</a>) or casting from objects to the required reference type.</li>\n<li>Allows you to write code which is applicable to many types with the same underlying behaviour, i.e. a Dictionary<string, int> uses the same underlying code as a Dictionary<DateTime, double>; using generics, the framework team only had to write one piece of code to achieve both results with the aforementioned advantages too.</li>\n</ul>\n'}, {'answer_id': 77716, 'author': 'Kevin Pang', 'author_id': 1574, 'author_profile': 'https://Stackoverflow.com/users/1574', 'pm_score': 2, 'selected': False, 'text': '<p>The primary advantage, as Mitchel points out, is strong-typing without needing to define multiple classes.</p>\n\n<p>This way you can do stuff like:</p>\n\n<pre><code>List<SomeCustomClass> blah = new List<SomeCustomClass>();\nblah[0].SomeCustomFunction();\n</code></pre>\n\n<p>Without generics, you would have to cast blah[0] to the correct type to access its functions.</p>\n'}, {'answer_id': 77915, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>the jvm casts anyway... it implicitly creates code which treats the generic type as "Object" and creates casts to the desired instantiation. Java generics are just syntactic sugar.</p>\n'}, {'answer_id': 77937, 'author': 'Chris Pietschmann', 'author_id': 7831, 'author_profile': 'https://Stackoverflow.com/users/7831', 'pm_score': 1, 'selected': False, 'text': '<p>Another advantage of using Generics (especially with Collections/Lists) is you get Compile Time Type Checking. This is really useful when using a Generic List instead of a List of Objects.</p>\n'}, {'answer_id': 77956, 'author': 'Vin', 'author_id': 1747, 'author_profile': 'https://Stackoverflow.com/users/1747', 'pm_score': 1, 'selected': False, 'text': '<p>Single most reason is they provide <strong>Type safety</strong></p>\n\n<pre><code>List<Customer> custCollection = new List<Customer>;\n</code></pre>\n\n<p>as opposed to,</p>\n\n<pre><code>object[] custCollection = new object[] { cust1, cust2 };\n</code></pre>\n\n<p>as a simple example.</p>\n'}, {'answer_id': 77970, 'author': 'Thomas Danecker', 'author_id': 9632, 'author_profile': 'https://Stackoverflow.com/users/9632', 'pm_score': 1, 'selected': False, 'text': "<p>In summary, generics allow you to specify more precisily what you intend to do (stronger typing).</p>\n\n<p>This has several benefits for you: </p>\n\n<ul>\n<li><p>Because the compiler knows more about what you want to do, it allows you to omit a lot of type-casting because it already knows that the type will be compatible.</p></li>\n<li><p>This also gets you earlier feedback about the correctnes of your program. Things that previously would have failed at runtime (e.g. because an object couldn't be casted in the desired type), now fail at compile-time and you can fix the mistake before your testing-department files a cryptical bug report.</p></li>\n<li><p>The compiler can do more optimizations, like avoiding boxing, etc.</p></li>\n</ul>\n"}, {'answer_id': 79081, 'author': 'SpongeJim', 'author_id': 13361, 'author_profile': 'https://Stackoverflow.com/users/13361', 'pm_score': 1, 'selected': False, 'text': '<p>A couple of things to add/expand on (speaking from the .NET point of view):</p>\n\n<p>Generic types allow you to create role-based classes and interfaces. This has been said already in more basic terms, but I find you start to design your code with classes which are implemented in a type-agnostic way - which results in highly reusable code.</p>\n\n<p>Generic arguments on methods can do the same thing, but they also help apply the "Tell Don\'t Ask" principle to casting, i.e. "give me what I want, and if you can\'t, you tell me why".</p>\n'}, {'answer_id': 79281, 'author': 'etchasketch', 'author_id': 14640, 'author_profile': 'https://Stackoverflow.com/users/14640', 'pm_score': 2, 'selected': False, 'text': '<p>I know this is a C# question, but <a href="http://en.wikipedia.org/wiki/Generic_programming" rel="nofollow noreferrer">generics</a> are used in other languages too, and their use/goals are quite similar.</p>\n\n<p>Java collections use <a href="http://en.wikipedia.org/wiki/Generics_in_Java" rel="nofollow noreferrer">generics</a> since Java 1.5. So, a good place to use them is when you are creating your own collection-like object.</p>\n\n<p>An example I see almost everywhere is a Pair class, which holds two objects, but needs to deal with those objects in a generic way.</p>\n\n<pre><code>class Pair<F, S> {\n public final F first;\n public final S second;\n\n public Pair(F f, S s)\n { \n first = f;\n second = s; \n }\n} \n</code></pre>\n\n<p>Whenever you use this Pair class you can specify which kind of objects you want it to deal with and any type cast problems will show up at compile time, rather than runtime.</p>\n\n<p>Generics can also have their bounds defined with the keywords \'super\' and \'extends\'. For example, if you want to deal with a generic type but you want to make sure it extends a class called Foo (which has a setTitle method):</p>\n\n<pre><code>public class FooManager <F extends Foo>{\n public void setTitle(F foo, String title) {\n foo.setTitle(title);\n }\n}\n</code></pre>\n\n<p>While not very interesting on its own, it\'s useful to know that whenever you deal with a FooManager, you know that it will handle MyClass types, and that MyClass extends Foo.</p>\n'}, {'answer_id': 79339, 'author': 'Michael L Perry', 'author_id': 7668, 'author_profile': 'https://Stackoverflow.com/users/7668', 'pm_score': 0, 'selected': False, 'text': '<p>I once gave a talk on this topic. You can find my slides, code, and audio recording at <a href="http://www.adventuresinsoftware.com/generics/" rel="nofollow noreferrer">http://www.adventuresinsoftware.com/generics/</a>.</p>\n'}, {'answer_id': 79857, 'author': 'Dean Poulin', 'author_id': 5462, 'author_profile': 'https://Stackoverflow.com/users/5462', 'pm_score': 3, 'selected': False, 'text': '<p>The best benefit to Generics is code reuse. Lets say that you have a lot of business objects, and you are going to write VERY similar code for each entity to perform the same actions. (I.E Linq to SQL operations).</p>\n\n<p>With generics, you can create a class that will be able to operate given any of the types that inherit from a given base class or implement a given interface like so:</p>\n\n<pre><code>public interface IEntity\n{\n\n}\n\npublic class Employee : IEntity\n{\n public string FirstName { get; set; }\n public string LastName { get; set; }\n public int EmployeeID { get; set; }\n}\n\npublic class Company : IEntity\n{\n public string Name { get; set; }\n public string TaxID { get; set }\n}\n\npublic class DataService<ENTITY, DATACONTEXT>\n where ENTITY : class, IEntity, new()\n where DATACONTEXT : DataContext, new()\n{\n\n public void Create(List<ENTITY> entities)\n {\n using (DATACONTEXT db = new DATACONTEXT())\n {\n Table<ENTITY> table = db.GetTable<ENTITY>();\n\n foreach (ENTITY entity in entities)\n table.InsertOnSubmit (entity);\n\n db.SubmitChanges();\n }\n }\n}\n\npublic class MyTest\n{\n public void DoSomething()\n {\n var dataService = new DataService<Employee, MyDataContext>();\n dataService.Create(new Employee { FirstName = "Bob", LastName = "Smith", EmployeeID = 5 });\n var otherDataService = new DataService<Company, MyDataContext>();\n otherDataService.Create(new Company { Name = "ACME", TaxID = "123-111-2233" });\n\n }\n}\n</code></pre>\n\n<p>Notice the reuse of the same service given the different Types in the DoSomething method above. Truly elegant!</p>\n\n<p>There\'s many other great reasons to use generics for your work, this is my favorite.</p>\n'}, {'answer_id': 953640, 'author': 'Steve B.', 'author_id': 19479, 'author_profile': 'https://Stackoverflow.com/users/19479', 'pm_score': 3, 'selected': False, 'text': '<ul>\n<li><p>Typed collections - even if you don\'t want to use them you\'re likely to have to deal with them from other libraries , other sources. </p></li>\n<li><p>Generic typing in class creation: </p>\n\n<p>public class Foo < T> { \npublic T get()...</p></li>\n<li><p>Avoidance of casting - I\'ve always disliked things like </p>\n\n<p>new Comparator {\n public int compareTo(Object o){\n if (o instanceof classIcareAbout)...</p></li>\n</ul>\n\n<p>Where you\'re essentially checking for a condition that should only exist because the interface is expressed in terms of objects.</p>\n\n<p>My initial reaction to generics was similar to yours - "too messy, too complicated". My experience is that after using them for a bit you get used to them, and code without them feels less clearly specified, and just less comfortable. Aside from that, the rest of the java world uses them so you\'re going to have to get with the program eventually, right?</p>\n'}, {'answer_id': 953645, 'author': 'victor hugo', 'author_id': 70616, 'author_profile': 'https://Stackoverflow.com/users/70616', 'pm_score': 1, 'selected': False, 'text': '<p>I use them for example in a GenericDao implemented with SpringORM and Hibernate which look like this</p>\n\n<pre><code>public abstract class GenericDaoHibernateImpl<T> \n extends HibernateDaoSupport {\n\n private Class<T> type;\n\n public GenericDaoHibernateImpl(Class<T> clazz) {\n type = clazz;\n }\n\n public void update(T object) {\n getHibernateTemplate().update(object);\n }\n\n @SuppressWarnings("unchecked")\n public Integer count() {\n return ((Integer) getHibernateTemplate().execute(\n new HibernateCallback() {\n public Object doInHibernate(Session session) {\n // Code in Hibernate for getting the count\n }\n }));\n }\n .\n .\n .\n}\n</code></pre>\n\n<p>By using generics my implementations of this DAOs force the developer to pass them just the entities they are designed for by just subclassing the GenericDao</p>\n\n<pre><code>public class UserDaoHibernateImpl extends GenericDaoHibernateImpl<User> {\n public UserDaoHibernateImpl() {\n super(User.class); // This is for giving Hibernate a .class\n // work with, as generics disappear at runtime\n }\n\n // Entity specific methods here\n}\n</code></pre>\n\n<p><em>My little framework is more robust (have things like filtering, lazy-loading, searching). I just simplified here to give you an example</em></p>\n\n<p>I, like Steve and you, said at the beginning <em>"Too messy and complicated"</em> but now I see its advantages</p>\n'}, {'answer_id': 953646, 'author': 'Will Hartung', 'author_id': 13663, 'author_profile': 'https://Stackoverflow.com/users/13663', 'pm_score': 0, 'selected': False, 'text': '<p>Using generics for collections is just simple and clean. Even if you punt on it everywhere else, the gain from the collections is a win to me.</p>\n\n<pre><code>List<Stuff> stuffList = getStuff();\nfor(Stuff stuff : stuffList) {\n stuff.do();\n}\n</code></pre>\n\n<p>vs </p>\n\n<pre><code>List stuffList = getStuff();\nIterator i = stuffList.iterator();\nwhile(i.hasNext()) {\n Stuff stuff = (Stuff)i.next();\n stuff.do();\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>List stuffList = getStuff();\nfor(int i = 0; i < stuffList.size(); i++) {\n Stuff stuff = (Stuff)stuffList.get(i);\n stuff.do();\n}\n</code></pre>\n\n<p>That alone is worth the marginal "cost" of generics, and you don\'t have to be a generic Guru to use this and get value.</p>\n'}, {'answer_id': 953647, 'author': 'Tom Hawtin - tackline', 'author_id': 4725, 'author_profile': 'https://Stackoverflow.com/users/4725', 'pm_score': 4, 'selected': False, 'text': '<p>If you were to search the Java bug database just before 1.5 was released, you\'d find seven times more bugs with <code>NullPointerException</code> than <code>ClassCastException</code>. So it doesn\'t seem that it is a great feature to find bugs, or at least bugs that persist after a little smoke testing.</p>\n\n<p>For me the huge advantage of generics is that they document <strong>in code</strong> important type information. If I didn\'t want that type information documented in code, then I\'d use a dynamically typed language, or at least a language with more implicit type inference.</p>\n\n<p>Keeping an object\'s collections to itself isn\'t a bad style (but then the common style is to effectively ignore encapsulation). It rather depends upon what you are doing. Passing collections to "algorithms" is slightly easier to check (at or before compile-time) with generics.</p>\n'}, {'answer_id': 953655, 'author': 'Peter Lange', 'author_id': 80164, 'author_profile': 'https://Stackoverflow.com/users/80164', 'pm_score': 3, 'selected': False, 'text': '<p>To give a good example. Imagine you have a class called Foo</p>\n\n<pre><code>public class Foo\n{\n public string Bar() { return "Bar"; }\n}\n</code></pre>\n\n<p><strong>Example 1</strong>\nNow you want to have a collection of Foo objects. You have two options, LIst or ArrayList, both of which work in a similar manner.</p>\n\n<pre><code>Arraylist al = new ArrayList();\nList<Foo> fl = new List<Foo>();\n\n//code to add Foos\nal.Add(new Foo());\nf1.Add(new Foo());\n</code></pre>\n\n<p>In the above code, if I try to add a class of FireTruck instead of Foo, the ArrayList will add it, but the Generic List of Foo will cause an exception to be thrown.</p>\n\n<p><strong>Example two.</strong></p>\n\n<p>Now you have your two array lists and you want to call the Bar() function on each. Since hte ArrayList is filled with Objects, you have to cast them before you can call bar. But since the Generic List of Foo can only contain Foos, you can call Bar() directly on those.</p>\n\n<pre><code>foreach(object o in al)\n{\n Foo f = (Foo)o;\n f.Bar();\n}\n\nforeach(Foo f in fl)\n{\n f.Bar();\n}\n</code></pre>\n'}, {'answer_id': 953665, 'author': 'Demi', 'author_id': 67985, 'author_profile': 'https://Stackoverflow.com/users/67985', 'pm_score': 2, 'selected': False, 'text': '<p>From the Sun Java documentation, in response to "why should i use generics?":</p>\n\n<p>"Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type of the collection, the compiler can check that you have used the collection consistently and can insert the correct casts on values being taken out of the collection... The code using generics is clearer and safer.... <strong>the compiler can verify at compile time that the type constraints are not violated at run time</strong> [emphasis mine]. Because the program compiles without warnings, we can state with certainty that it will not throw a ClassCastException at run time. The net effect of using generics, especially in large programs, is <strong>improved readability and robustness</strong>. [emphasis mine]"</p>\n'}, {'answer_id': 953683, 'author': 'James Schek', 'author_id': 17871, 'author_profile': 'https://Stackoverflow.com/users/17871', 'pm_score': 6, 'selected': False, 'text': "<p>I really hate to repeat myself. I hate typing the same thing more often than I have to. I don't like restating things multiple times with slight differences.</p>\n\n<p>Instead of creating:</p>\n\n<pre><code>class MyObjectList {\n MyObject get(int index) {...}\n}\nclass MyOtherObjectList {\n MyOtherObject get(int index) {...}\n}\nclass AnotherObjectList {\n AnotherObject get(int index) {...}\n}\n</code></pre>\n\n<p>I can build one reusable class... (in the case where you don't want to use the raw collection for some reason)</p>\n\n<pre><code>class MyList<T> {\n T get(int index) { ... }\n}\n</code></pre>\n\n<p>I'm now 3x more efficient and I only have to maintain one copy. Why WOULDN'T you want to maintain less code?</p>\n\n<p>This is also true for non-collection classes such as a <code>Callable<T></code> or a <code>Reference<T></code> that has to interact with other classes. Do you really want to extend <code>Callable<T></code> and <code>Future<T></code> and every other associated class to create type-safe versions?</p>\n\n<p>I don't.</p>\n"}, {'answer_id': 953699, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>Generics also give you the ability to create more reusable objects/methods while still providing type specific support. You also gain a lot of performance in some cases. I don't know the full spec on the Java Generics, but in .NET I can specify constraints on the Type parameter, like Implements a Interface, Constructor , and Derivation.</p>\n"}, {'answer_id': 953755, 'author': 'jigawot', 'author_id': 117724, 'author_profile': 'https://Stackoverflow.com/users/117724', 'pm_score': 2, 'selected': False, 'text': "<p>Don't forget that generics aren't just used by classes, they can also be used by methods. For example, take the following snippet:</p>\n\n<pre><code>private <T extends Throwable> T logAndReturn(T t) {\n logThrowable(t); // some logging method that takes a Throwable\n return t;\n}\n</code></pre>\n\n<p>It is simple, but can be used very elegantly. The nice thing is that the method returns whatever it was that it was given. This helps out when you are handling exceptions that need to be re-thrown back to the caller:</p>\n\n<pre><code> ...\n} catch (MyException e) {\n throw logAndReturn(e);\n}\n</code></pre>\n\n<p>The point is that you don't lose the type by passing it through a method. You can throw the correct type of exception instead of just a <code>Throwable</code>, which would be all you could do without generics.</p>\n\n<p>This is just a simple example of one use for generic methods. There are quite a few other neat things you can do with generic methods. The coolest, in my opinion, is type inferring with generics. Take the following example (taken from Josh Bloch's Effective Java 2nd Edition):</p>\n\n<pre><code>...\nMap<String, Integer> myMap = createHashMap();\n...\npublic <K, V> Map<K, V> createHashMap() {\n return new HashMap<K, V>();\n}\n</code></pre>\n\n<p>This doesn't do a lot, but it does cut down on some clutter when the generic types are long (or nested; i.e. <code>Map<String, List<String>></code>).</p>\n"}, {'answer_id': 953756, 'author': 'coobird', 'author_id': 17172, 'author_profile': 'https://Stackoverflow.com/users/17172', 'pm_score': 5, 'selected': False, 'text': '<p><strong>Not needing to typecast is one of the biggest advantages of Java generics</strong>, as it will perform type checking at compile-time. This will reduce the possibility of <code>ClassCastException</code>s which can be thrown at runtime, and can lead to more robust code.</p>\n\n<p>But I suspect that you\'re fully aware of that.</p>\n\n<blockquote>\n <p>Every time I look at Generics it gives\n me a headache. I find the best part of\n Java to be it\'s simplicity and minimal\n syntax and generics are not simple and\n add a significant amount of new\n syntax. </p>\n</blockquote>\n\n<p>At first, I didn\'t see the benefit of generics either. I started learning Java from the 1.4 syntax (even though Java 5 was out at the time) and when I encountered generics, I felt that it was more code to write, and I really didn\'t understand the benefits.</p>\n\n<p><strong>Modern IDEs make writing code with generics easier.</strong></p>\n\n<p>Most modern, decent IDEs are smart enough to assist with writing code with generics, especially with code completion.</p>\n\n<p>Here\'s an example of making an <code>Map<String, Integer></code> with a <code>HashMap</code>. The code I would have to type in is:</p>\n\n<pre><code>Map<String, Integer> m = new HashMap<String, Integer>();\n</code></pre>\n\n<p>And indeed, that\'s a lot to type just to make a new <code>HashMap</code>. However, in reality, I only had to type this much before Eclipse knew what I needed:</p>\n\n<p><code>Map<String, Integer> m = new Ha</code> <kbd>Ctrl</kbd>+<kbd>Space</kbd></p>\n\n<p>True, I did need to select <code>HashMap</code> from a list of candidates, but basically the IDE knew what to add, including the generic types. With the right tools, using generics isn\'t too bad.</p>\n\n<p>In addition, since the types are known, when retrieving elements from the generic collection, the IDE will act as if that object is already an object of its declared type -- there is no need to casting for the IDE to know what the object\'s type is.</p>\n\n<p><strong>A key advantage of generics comes from the way it plays well with new Java 5 features.</strong> Here\'s an example of tossing integers in to a <code>Set</code> and calculating its total:</p>\n\n<pre><code>Set<Integer> set = new HashSet<Integer>();\nset.add(10);\nset.add(42);\n\nint total = 0;\nfor (int i : set) {\n total += i;\n}\n</code></pre>\n\n<p>In that piece of code, there are three new Java 5 features present:</p>\n\n<ul>\n<li><a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html" rel="noreferrer">Generics</a></li>\n<li><a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html" rel="noreferrer">Autoboxing and unboxing</a></li>\n<li><a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html" rel="noreferrer">For-each loop</a></li>\n</ul>\n\n<p>First, generics and autoboxing of primitives allow the following lines:</p>\n\n<pre><code>set.add(10);\nset.add(42);\n</code></pre>\n\n<p>The integer <code>10</code> is autoboxed into an <code>Integer</code> with the value of <code>10</code>. (And same for <code>42</code>). Then that <code>Integer</code> is tossed into the <code>Set</code> which is known to hold <code>Integer</code>s. Trying to throw in a <code>String</code> would cause a compile error.</p>\n\n<p>Next, for for-each loop takes all three of those:</p>\n\n<pre><code>for (int i : set) {\n total += i;\n}\n</code></pre>\n\n<p>First, the <code>Set</code> containing <code>Integer</code>s are used in a for-each loop. Each element is declared to be an <code>int</code> and that is allowed as the <code>Integer</code> is unboxed back to the primitive <code>int</code>. And the fact that this unboxing occurs is known because generics was used to specify that there were <code>Integer</code>s held in the <code>Set</code>.</p>\n\n<p>Generics can be the glue that brings together the new features introduced in Java 5, and it just makes coding simpler and safer. And most of the time IDEs are smart enough to help you with good suggestions, so generally, it won\'t a whole lot more typing.</p>\n\n<p>And frankly, as can be seen from the <code>Set</code> example, I feel that utilizing Java 5 features can make the code more concise and robust.</p>\n\n<p><strong>Edit - An example without generics</strong></p>\n\n<p>The following is an illustration of the above <code>Set</code> example without the use of generics. It is possible, but isn\'t exactly pleasant:</p>\n\n<pre><code>Set set = new HashSet();\nset.add(10);\nset.add(42);\n\nint total = 0;\nfor (Object o : set) {\n total += (Integer)o;\n}\n</code></pre>\n\n<p><em>(Note: The above code will generate unchecked conversion warning at compile-time.)</em></p>\n\n<p>When using non-generics collections, the types that are entered into the collection is objects of type <code>Object</code>. Therefore, in this example, a <code>Object</code> is what is being <code>add</code>ed into the set.</p>\n\n<pre><code>set.add(10);\nset.add(42);\n</code></pre>\n\n<p>In the above lines, autoboxing is in play -- the primitive <code>int</code> value <code>10</code> and <code>42</code> are being autoboxed into <code>Integer</code> objects, which are being added to the <code>Set</code>. However, keep in mind, the <code>Integer</code> objects are being handled as <code>Object</code>s, as there are no type information to help the compiler know what type the <code>Set</code> should expect.</p>\n\n<pre><code>for (Object o : set) {\n</code></pre>\n\n<p>This is the part that is crucial. The reason the for-each loop works is because the <code>Set</code> implements the <a href="http://java.sun.com/javase/6/docs/api/java/lang/Iterable.html" rel="noreferrer"><code>Iterable</code></a> interface, which returns an <code>Iterator</code> with type information, if present. (<code>Iterator<T></code>, that is.)</p>\n\n<p>However, since there is no type information, the <code>Set</code> will return an <code>Iterator</code> which will return the values in the <code>Set</code> as <code>Object</code>s, and that is why the element being retrieved in the for-each loop <em>must</em> be of type <code>Object</code>.</p>\n\n<p>Now that the <code>Object</code> is retrieved from the <code>Set</code>, it needs to be cast to an <code>Integer</code> manually to perform the addition:</p>\n\n<pre><code> total += (Integer)o;\n</code></pre>\n\n<p>Here, a typecast is performed from an <code>Object</code> to an <code>Integer</code>. In this case, we know this will always work, but manual typecasting always makes me feel it is fragile code that could be damaged if a minor change is made else where. (I feel that every typecast is a <code>ClassCastException</code> waiting to happen, but I digress...)</p>\n\n<p>The <code>Integer</code> is now unboxed into an <code>int</code> and allowed to perform the addition into the <code>int</code> variable <code>total</code>.</p>\n\n<p>I hope I could illustrate that the new features of Java 5 is possible to use with non-generic code, but it just isn\'t as clean and straight-forward as writing code with generics. And, in my opinion, to take full advantage of the new features in Java 5, one should be looking into generics, if at the very least, allows for compile-time checks to prevent invalid typecasts to throw exceptions at runtime.</p>\n'}, {'answer_id': 953769, 'author': 'Bert F', 'author_id': 11296, 'author_profile': 'https://Stackoverflow.com/users/11296', 'pm_score': 2, 'selected': False, 'text': "<p>Haven't you ever written a method (or a class) where the key concept of the method/class wasn't tightly bound to a specific data type of the parameters/instance variables (think linked list, max/min functions, binary search, etc.).</p>\n\n<p>Haven't you ever wish you could reuse the algorthm/code without resorting to cut-n-paste reuse or compromising strong-typing (e.g. I want a <code>List</code> of Strings, not a <code>List</code> of things I <em>hope</em> are strings!)?</p>\n\n<p>That's why you should <strong><em>want</em></strong> to use generics (or something better).</p>\n"}, {'answer_id': 953781, 'author': 'Apocalisp', 'author_id': 3434, 'author_profile': 'https://Stackoverflow.com/users/3434', 'pm_score': 4, 'selected': False, 'text': '<p>Generics in Java facilitate <a href="http://en.wikipedia.org/wiki/Polymorphism_(computer_science)" rel="nofollow noreferrer">parametric polymorphism</a>. By means of type parameters, you can pass arguments to types. Just as a method like <code>String foo(String s)</code> models some behaviour, not just for a particular string, but for any string <code>s</code>, so a type like <code>List<T></code> models some behaviour, not just for a specific type, but <em>for any type</em>. <code>List<T></code> says that <em>for any type <code>T</code>, there\'s a type of <code>List</code> whose elements are <code>T</code>s</em>. So <code>List</code> is a actually a <em>type constructor</em>. It takes a type as an argument and constructs another type as a result.</p>\n\n<p>Here are a couple of examples of generic types I use every day. First, a very useful generic interface:</p>\n\n<pre><code>public interface F<A, B> {\n public B f(A a);\n}\n</code></pre>\n\n<p>This interface says that <em>for some two types, <code>A</code> and <code>B</code>, there\'s a function (called <code>f</code>) that takes an <code>A</code> and returns a <code>B</code>.</em> When you implement this interface, <code>A</code> and <code>B</code> can be any types you want, as long as you provide a function <code>f</code> that takes the former and returns the latter. Here\'s an example implementation of the interface:</p>\n\n<pre><code>F<Integer, String> intToString = new F<Integer, String>() {\n public String f(int i) {\n return String.valueOf(i);\n }\n}\n</code></pre>\n\n<p>Before generics, polymorphism was achieved by <em>subclassing</em> using the <code>extends</code> keyword. With generics, we can actually do away with subclassing and use parametric polymorphism instead. For example, consider a parameterised (generic) class used to calculate hash codes for any type. Instead of overriding Object.hashCode(), we would use a generic class like this:</p>\n\n<pre><code>public final class Hash<A> {\n private final F<A, Integer> hashFunction;\n\n public Hash(final F<A, Integer> f) {\n this.hashFunction = f;\n }\n\n public int hash(A a) {\n return hashFunction.f(a);\n }\n}\n</code></pre>\n\n<p>This is much more flexible than using inheritance, because we can stay with the theme of using composition and parametric polymorphism without locking down brittle hierarchies.</p>\n\n<p>Java\'s generics are not perfect though. You can abstract over types, but you can\'t abstract over type constructors, for example. That is, you can say "for any type T", but you can\'t say "for any type T that takes a type parameter A".</p>\n\n<p><a href="http://apocalisp.wordpress.com/2008/10/23/heterogeneous-lists-and-the-limits-of-the-java-type-system/" rel="nofollow noreferrer">I wrote an article about these limits of Java generics, here.</a></p>\n\n<p>One huge win with generics is that they let you avoid subclassing. Subclassing tends to result in brittle class hierarchies that are awkward to extend, and classes that are difficult to understand individually without looking at the entire hierarchy.</p>\n\n<p>Wereas before generics you might have classes like <code>Widget</code> extended by <code>FooWidget</code>, <code>BarWidget</code>, and <code>BazWidget</code>, with generics you can have a single generic class <code>Widget<A></code> that takes a <code>Foo</code>, <code>Bar</code> or <code>Baz</code> in its constructor to give you <code>Widget<Foo></code>, <code>Widget<Bar></code>, and <code>Widget<Baz></code>.</p>\n'}, {'answer_id': 51103844, 'author': 'stdout', 'author_id': 1388943, 'author_profile': 'https://Stackoverflow.com/users/1388943', 'pm_score': 1, 'selected': False, 'text': '<p>Obvious benefits like "type safety" and "no casting" are already mentioned so maybe I can talk about some other "benefits" which I hope it helps.</p>\n\n<p>First of all, generics is a language-independent concept and , IMO, it might make more sense if you think about regular (runtime) polymorphism at the same time. </p>\n\n<p>For example, the polymorphism as we know from object oriented design has a runtime notion in where the caller object is figured out at runtime as program execution goes and the relevant method gets called accordingly depending on the runtime type. In generics, the idea is somewhat similar but everything happens at compile time. What does that mean and how you make use of it?</p>\n\n<p>(Let\'s stick with generic methods to keep it compact) It means that you can still have the same method on separate classes (like you did previously in polymorphic classes) but this time they\'re auto-generated by the compiler depend on the types set at compile time. You parametrise your methods on the type you give at compile time. So, instead of writing the methods from scratch <strong>for every single type</strong> you have as you do in runtime polymorphism (method overriding), you let compilers do the work during compilation. This has an obvious advantage since you don\'t need to infer all possible types that might be used in your system which makes it far more scalable without a code change.</p>\n\n<p>Classes work the pretty much same way. You parametrise the type and the code is generated by the compiler.</p>\n\n<p>Once you get the idea of "compile time", you can make use "bounded" types and restrict what can be passed as a parametrised type through classes/methods. So, you can control what to be passed through which is a powerful thing especially you\'ve a framework being consumed by other people.</p>\n\n<pre><code>public interface Foo<T extends MyObject> extends Hoo<T>{\n ...\n}\n</code></pre>\n\n<p>No one can set sth other than MyObject now.</p>\n\n<p>Also, you can "enforce" type constraints on your method arguments which means you can make sure both your method arguments would depend on the same type.</p>\n\n<pre><code>public <T extends MyObject> foo(T t1, T t2){\n ...\n} \n</code></pre>\n\n<p>Hope all of this makes sense.</p>\n'}, {'answer_id': 64616245, 'author': 'Ash', 'author_id': 6497200, 'author_profile': 'https://Stackoverflow.com/users/6497200', 'pm_score': 0, 'selected': False, 'text': '<ol>\n<li><p>Enabling programmers to implement generic algorithms - By using generics, programmers can implement generic algorithms that work on collections of different types, can be customized, and are type-safe and easier to read.</p>\n</li>\n<li><p>Stronger type checks at compile time - A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.</p>\n</li>\n<li><p>Elimination of casts.</p>\n</li>\n</ol>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77632', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13578/'] |
77,639 | <p>When is it right for a constructor to throw an exception? (Or in the case of Objective C: when is it right for an init'er to return nil?)</p>
<p>It seems to me that a constructor should fail -- and thus refuse to create an object -- if the object isn't complete. I.e., the constructor should have a contract with its caller to provide a functional and working object on which methods can be called meaningfully? Is that reasonable?</p>
| [{'answer_id': 77681, 'author': 'Michael L Perry', 'author_id': 7668, 'author_profile': 'https://Stackoverflow.com/users/7668', 'pm_score': 3, 'selected': False, 'text': "<p>Because of all the trouble that a partially created class can cause, I'd say never.</p>\n\n<p>If you need to validate something during construction, make the constructor private and define a public static factory method. The method can throw if something is invalid. But if everything checks out, it calls the constructor, which is guaranteed not to throw.</p>\n"}, {'answer_id': 77698, 'author': 'blowdart', 'author_id': 2525, 'author_profile': 'https://Stackoverflow.com/users/2525', 'pm_score': 3, 'selected': False, 'text': "<p>It's always pretty dodgy, especially if you're allocating resources inside a constructor; depending on your language the destructor won't get called, so you need to manually cleanup. It depends on how when an object's lifetime begins in your language.</p>\n\n<p>The only time I've really done it is when there's been a security problem somewhere that means the object should not, rather than cannot, be created.</p>\n"}, {'answer_id': 77705, 'author': 'Sebastian Redl', 'author_id': 8922, 'author_profile': 'https://Stackoverflow.com/users/8922', 'pm_score': 9, 'selected': True, 'text': "<p>The constructor's job is to bring the object into a usable state. There are basically two schools of thought on this.</p>\n\n<p>One group favors two-stage construction. The constructor merely brings the object into a sleeper state in which it refuses to do any work. There's an additional function that does the actual initialization.</p>\n\n<p>I've never understood the reasoning behind this approach. I'm firmly in the group that supports one-stage construction, where the object is fully initialized and usable after construction.</p>\n\n<p>One-stage constructors should throw if they fail to fully initialize the object. If the object cannot be initialized, it must not be allowed to exist, so the constructor must throw.</p>\n"}, {'answer_id': 77721, 'author': 'moonshadow', 'author_id': 11834, 'author_profile': 'https://Stackoverflow.com/users/11834', 'pm_score': 2, 'selected': False, 'text': '<p>See C++ FAQ sections <a href="http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.2" rel="nofollow noreferrer">17.2</a> and <a href="http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.4" rel="nofollow noreferrer">17.4</a>.</p>\n\n<p>In general, I have found that code that is easier to port and maintain results if constructors are written so they do not fail, and code that can fail is placed in a separate method that returns an error code and leaves the object in an inert state.</p>\n'}, {'answer_id': 77733, 'author': 'Matt Dillard', 'author_id': 863, 'author_profile': 'https://Stackoverflow.com/users/863', 'pm_score': 3, 'selected': False, 'text': '<p>It\'s reasonable for a constructor to throw an exception so long as it cleans itself up properly. If you follow the <a href="http://en.wikipedia.org/wiki/Resource_acquisition_is_initialization" rel="noreferrer">RAII</a> paradigm (Resource Acquisition Is Initialization) then it <strong>is</strong> quite common for a constructor to do meaningful work; a well-written constructor will in turn clean up after itself if it can\'t fully be initialized.</p>\n'}, {'answer_id': 77740, 'author': 'VonC', 'author_id': 6309, 'author_profile': 'https://Stackoverflow.com/users/6309', 'pm_score': 1, 'selected': False, 'text': '<p>Yes, if the constructor fails to build one of its internal part, it can be - by choice - its responsibility to throw (and in certain language to declare) an <a href="https://stackoverflow.com/questions/27578/when-to-choose-checked-and-unchecked-exceptions">explicit exception</a> , duly noted in the constructor documentation.</p>\n\n<p>This is not the only option: It could finish the constructor and build an object, but with a method \'isCoherent()\' returning false, in order to be able to signal an incoherent state (that may be preferable in certain case, in order to avoid a brutal interruption of the execution workflow due to an exception)<br>\nWarning: as said by EricSchaefer in his comment, that can bring some complexity to the unit testing (a throw can increase the <a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity" rel="nofollow noreferrer">cyclomatic complexity</a> of the function due to the condition that triggers it)</p>\n\n<p>If it fails because of the caller (like a null argument provided by the caller, where the called constructor expects a non-null argument), the constructor will throw an unchecked runtime exception anyway.</p>\n'}, {'answer_id': 77765, 'author': 'Don Neufeld', 'author_id': 13097, 'author_profile': 'https://Stackoverflow.com/users/13097', 'pm_score': 1, 'selected': False, 'text': '<p>Throwing an exception during construction is a great way to make your code way more complex. Things that would seem simple suddenly become hard. For example, let\'s say you have a stack. How do you pop the stack and return the top value? Well, if the objects in the stack can throw in their constructors (constructing the temporary to return to the caller), you can\'t guarantee that you won\'t lose data (decrement stack pointer, construct return value using copy constructor of value in stack, which throws, and now have a stack that just lost an item)! This is why std::stack::pop does not return a value, and you have to call std::stack::top.</p>\n\n<p>This problem is well described <a href="http://books.google.com/books?id=mT7E5gDuW_4C&pg=PA39&lpg=PA39&dq=exception+safe+stack+pop&source=web&ots=AXUQyXfWkW&sig=0c3POTY82SsQ5-zNUWTzSNIoRu0&hl=en&sa=X&oi=book_result&resnum=3&ct=result#PPA32,M1" rel="nofollow noreferrer">here</a>, check Item 10, writing exception-safe code.</p>\n'}, {'answer_id': 77766, 'author': 'Luke Halliwell', 'author_id': 3974, 'author_profile': 'https://Stackoverflow.com/users/3974', 'pm_score': 2, 'selected': False, 'text': '<p>You absolutely should throw an exception from a constructor if you\'re unable to create a valid object. This allows you to provide proper invariants in your class.</p>\n\n<p>In practice, you may have to be very careful. Remember that in C++, the destructor will not be called, so if you throw after allocating your resources, you need to take great care to handle that properly!</p>\n\n<p><a href="http://www.gotw.ca/gotw/066.htm" rel="nofollow noreferrer">This page</a> has a thorough discussion of the situation in C++.</p>\n'}, {'answer_id': 77784, 'author': 'scubabbl', 'author_id': 9450, 'author_profile': 'https://Stackoverflow.com/users/9450', 'pm_score': 0, 'selected': False, 'text': '<p>Speaking strictly from a Java standpoint, any time you initialize a constructor with illegal values, it should throw an exception. That way it does not get constructed in a bad state.</p>\n'}, {'answer_id': 77786, 'author': 'nsanders', 'author_id': 1244, 'author_profile': 'https://Stackoverflow.com/users/1244', 'pm_score': 0, 'selected': False, 'text': '<p>To me it\'s a somewhat philosophical design decision.</p>\n\n<p>It\'s very nice to have instances which are valid as long as they exist, from ctor time onwards. For many nontrivial cases this may require throwing exceptions from the ctor if a memory/resource allocation can\'t be made. </p>\n\n<p>Some other approaches are the init() method which comes with some issues of its own. One of which is ensuring init() actually gets called. </p>\n\n<p>A variant is using a lazy approach to automatically call init() the first time an accessor/mutator gets called, but that requires any potential caller to have to worry about the object being valid. (As opposed to the "it exists, hence it\'s valid philosophy").</p>\n\n<p>I\'ve seen various proposed design patterns to deal with this issue too. Such as being able to create an initial object via ctor, but having to call init() to get your hands on a contained, initialized object with accesors/mutators.</p>\n\n<p>Each approach has its ups and downs; I have used all of these successfully. If you don\'t make ready-to-use objects from the instant they\'re created, then I recommend a heavy dose of asserts or exceptions to make sure users don\'t interact before init(). </p>\n\n<p><strong>Addendum</strong></p>\n\n<p>I wrote from a C++ programmers perspective. I also assume you are properly using the RAII idiom to handle resources being released when exceptions are thrown.</p>\n'}, {'answer_id': 77789, 'author': 'Tim Williscroft', 'author_id': 2789, 'author_profile': 'https://Stackoverflow.com/users/2789', 'pm_score': 1, 'selected': False, 'text': '<p>The usual contract in OO is that object methods do actually function.</p>\n\n<p>So as a corrolary, to never return a zombie object form a constructor/init.</p>\n\n<p>A zombie is not functional and may be missing internal components. Just a null-pointer exception waiting to happen.</p>\n\n<p>I first made zombies in Objective C, many years ago. </p>\n\n<p>Like all rules of thumb , there is an "exception".</p>\n\n<p>It is entirely possible that a <em>specific interface</em> may have a contract that says that \nthere exists a method "initialize" that is allowed to thron an exception.\nThat an object inplementing this interface may not respond correctly to any calls except property setters until initialize has been called. I used this for device drivers in an OO operating system during the boot process, and it was workable.</p>\n\n<p>In general, you don\'t want zombie objects. In languages like Smalltalk with <strong>become</strong> things get a little fizzy-buzzy, but overuse of <em>become</em> is bad style too. <em>Become lets an object change into another object in-situ, so there is no need for envelope-wrapper(Advanced C++) or the strategy pattern(GOF).</em></p>\n'}, {'answer_id': 77797, 'author': 'Jacob Krall', 'author_id': 3140, 'author_profile': 'https://Stackoverflow.com/users/3140', 'pm_score': 6, 'selected': False, 'text': '<p><a href="https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/" rel="noreferrer">Eric Lippert says</a> there are 4 kinds of exceptions.</p>\n\n<ul>\n<li>Fatal exceptions are not your fault, you cannot prevent them, and you cannot sensibly clean up from them.</li>\n<li>Boneheaded exceptions are your own darn fault, you could have prevented them and therefore they are bugs in your code.</li>\n<li>Vexing exceptions are the result of unfortunate design decisions. Vexing exceptions are thrown in a completely non-exceptional circumstance, and therefore must be caught and handled all the time.</li>\n<li>And finally, exogenous exceptions appear to be somewhat like vexing exceptions except that they are not the result of unfortunate design choices. Rather, they are the result of untidy external realities impinging upon your beautiful, crisp program logic.</li>\n</ul>\n\n<p>Your constructor should never throw a fatal exception on its own, but code it executes may cause a fatal exception. Something like "out of memory" isn\'t something you can control, but if it occurs in a constructor, hey, it happens.</p>\n\n<p>Boneheaded exceptions should never occur in any of your code, so they\'re right out.</p>\n\n<p>Vexing exceptions (the example is <code>Int32.Parse()</code>) shouldn\'t be thrown by constructors, because they don\'t have non-exceptional circumstances.</p>\n\n<p>Finally, exogenous exceptions should be avoided, but if you\'re doing something in your constructor that depends on external circumstances (like the network or filesystem), it would be appropriate to throw an exception.</p>\n\n<p>Reference link: <a href="https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/" rel="noreferrer">https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/</a></p>\n'}, {'answer_id': 77863, 'author': 'mlbrock', 'author_id': 9966, 'author_profile': 'https://Stackoverflow.com/users/9966', 'pm_score': 1, 'selected': False, 'text': "<p>I can't address best practice in Objective-C, but in C++ it's fine for a constructor to throw an exception. Especially as there's no other way to ensure that an exceptional condition encountered at construction is reported without resorting to invoking an isOK() method.</p>\n\n<p>The function try block feature was designed specifically to support failures in constructor memberwise initialization (though it may be used for regular functions also). It's the only way to modify or enrich the exception information which will be thrown. But because of its original design purpose (use in constructors) it doesn't permit the exception to be swallowed by an empty catch() clause.</p>\n"}, {'answer_id': 77951, 'author': 'Denice', 'author_id': 14178, 'author_profile': 'https://Stackoverflow.com/users/14178', 'pm_score': 3, 'selected': False, 'text': "<p>A constructor should throw an exception when it is unable to complete the construction of said object.</p>\n\n<p>For example, if the constructor is supposed to allocate 1024 KB of ram, and it fails to do so, it should throw an exception, this way the caller of the constructor knows that the object is not ready to be used and there is an error somewhere that needs to be fixed.</p>\n\n<p>Objects that are half-initialised and half-dead just cause problems and issues, as there really is no way for the caller to know. I'd rather have my constructor throw an error when things go wrong, than having to rely on the programming to run a call to the isOK() function which returns true or false.</p>\n"}, {'answer_id': 78020, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>Throw an exception if you're unable to initialize the object in the constructor, one example are illegal arguments.</p>\n\n<p>As a general rule of thumb an exception should always be thrown as soon as possible, as it makes debugging easier when the source of the problem is closer to the method signaling something is wrong.</p>\n"}, {'answer_id': 82373, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': False, 'text': "<p>There is <strong>generally</strong> nothing to be gained by divorcing object initialization from construction. RAII is correct, a successful call to the constructor should either result in a fully initialized live object or it should fail, and <strong>ALL</strong> failures at any point in any code path should always throw an exception. You gain nothing by use of a separate init() method except additional complexity at some level. The ctor contract should be either it returns a functional valid object or it cleans up after itself and throws.</p>\n\n<p>Consider, if you implement a separate init method, you <strong>still</strong> have to call it. It will still have the potential to throw exceptions, they still have to be handled and they virtually always have to be called immediately after the constructor anyway, except now you have 4 possible object states instead of 2 (IE, constructed, initialized, uninitialized, and failed vs just valid and non-existent). </p>\n\n<p>In any case I've run across in 25 years of OO development cases where it seems like a separate init method would 'solve some problem' are design flaws. If you don't need an object NOW then you shouldn't be constructing it now, and if you do need it now then you need it initialized. KISS should always be the principle followed, along with the simple concept that the behavior, state, and API of any interface should reflect WHAT the object does, not HOW it does it, client code should not even be aware that the object has any kind of internal state that requires initialization, thus the init after pattern violates this principle.</p>\n"}, {'answer_id': 85467, 'author': 'Tegan Mulholland', 'author_id': 16431, 'author_profile': 'https://Stackoverflow.com/users/16431', 'pm_score': 0, 'selected': False, 'text': "<p>Using factories or factory methods for all object creation, you can avoid invalid objects without throwing exceptions from constructors. The creation method should return the requested object if it's able to create one, or null if it's not. You lose a little bit of flexibility in handling construction errors in the user of a class, because returning null doesn't tell you what went wrong in the object creation. But it also avoids adding the complexity of multiple exception handlers every time you request an object, and the risk of catching exceptions you shouldn't handle.</p>\n"}, {'answer_id': 389525, 'author': 'Nick', 'author_id': 44741, 'author_profile': 'https://Stackoverflow.com/users/44741', 'pm_score': 2, 'selected': False, 'text': "<p>If you are writing UI-Controls (ASPX, WinForms, WPF, ...) you should avoid throwing exceptions in the constructor because the designer (Visual Studio) can't handle them when it creates your controls. Know your control-lifecycle (control events) and use lazy initialization wherever possible.</p>\n"}, {'answer_id': 5006212, 'author': 'stevex', 'author_id': 8831, 'author_profile': 'https://Stackoverflow.com/users/8831', 'pm_score': 2, 'selected': False, 'text': '<p>Note that if you throw an exception in an initializer, you\'ll end up leaking if any code is using the <code>[[[MyObj alloc] init] autorelease]</code> pattern, since the exception will skip the autorelease.</p>\n\n<p>See this question:</p>\n\n<p><a href="https://stackoverflow.com/questions/5005852/how-do-you-prevent-leaks-when-raising-an-exception-in-init">How do you prevent leaks when raising an exception in init?</a></p>\n'}, {'answer_id': 42913195, 'author': 'cwharris', 'author_id': 696056, 'author_profile': 'https://Stackoverflow.com/users/696056', 'pm_score': 4, 'selected': False, 'text': '<p>As far as I can tell, no-one is presenting a fairly obvious solution which embodies the best of both one-stage and two-stage construction.</p>\n\n<p><strong>note:</strong> This answer assumes C#, but the principles can be applied in most languages.</p>\n\n<p>First, the benefits of both:</p>\n\n<h2>One-Stage</h2>\n\n<p>One-stage construction benefits us by preventing objects from existing in an invalid state, thus preventing all sorts of erroneous state management and all the bugs which come with it. However, it leaves some of us feeling weird because we don\'t want our constructors to throw exceptions, and sometimes that\'s what we need to do when initialization arguments are invalid.</p>\n\n<pre><code>public class Person\n{\n public string Name { get; }\n public DateTime DateOfBirth { get; }\n\n public Person(string name, DateTime dateOfBirth)\n {\n if (string.IsNullOrWhitespace(name))\n {\n throw new ArgumentException(nameof(name));\n }\n\n if (dateOfBirth > DateTime.UtcNow) // side note: bad use of DateTime.UtcNow\n {\n throw new ArgumentOutOfRangeException(nameof(dateOfBirth));\n }\n\n this.Name = name;\n this.DateOfBirth = dateOfBirth;\n }\n}\n</code></pre>\n\n<h2>Two-Stage via validation method</h2>\n\n<p>Two-stage construction benefits us by allowing our validation to be executed outside of the constructor, and therefore prevents the need for throwing exceptions within the constructor. However, it leaves us with "invalid" instances, which means there\'s state we have to track and manage for the instance, or we throw it away immediately after heap-allocation. It begs the question: Why are we performing a heap allocation, and thus memory collection, on an object we don\'t even end up using?</p>\n\n<pre><code>public class Person\n{\n public string Name { get; }\n public DateTime DateOfBirth { get; }\n\n public Person(string name, DateTime dateOfBirth)\n {\n this.Name = name;\n this.DateOfBirth = dateOfBirth;\n }\n\n public void Validate()\n {\n if (string.IsNullOrWhitespace(Name))\n {\n throw new ArgumentException(nameof(Name));\n }\n\n if (DateOfBirth > DateTime.UtcNow) // side note: bad use of DateTime.UtcNow\n {\n throw new ArgumentOutOfRangeException(nameof(DateOfBirth));\n }\n }\n}\n</code></pre>\n\n<h2>Single-Stage via private constructor</h2>\n\n<p>So how can we keep exceptions out of our constructors, and prevent ourselves from performing heap allocation on objects which will be immediately discarded? It\'s pretty basic: we make the constructor private and create instances via a static method designated to perform an instantiation, and therefore heap-allocation, only <strong><em>after</em></strong> validation.</p>\n\n<pre><code>public class Person\n{\n public string Name { get; }\n public DateTime DateOfBirth { get; }\n\n private Person(string name, DateTime dateOfBirth)\n {\n this.Name = name;\n this.DateOfBirth = dateOfBirth;\n }\n\n public static Person Create(\n string name,\n DateTime dateOfBirth)\n {\n if (string.IsNullOrWhitespace(Name))\n {\n throw new ArgumentException(nameof(name));\n }\n\n if (dateOfBirth > DateTime.UtcNow) // side note: bad use of DateTime.UtcNow\n {\n throw new ArgumentOutOfRangeException(nameof(DateOfBirth));\n }\n\n return new Person(name, dateOfBirth);\n }\n}\n</code></pre>\n\n<h2>Async Single-Stage via private constructor</h2>\n\n<p>Aside from the aforementioned validation and heap-allocation prevention benefits, the previous methodology provides us with another nifty advantage: async support. This comes in handy when dealing with multi-stage authentication, such as when you need to retrieve a bearer token before using your API. This way, you don\'t end up with an invalid "signed out" API client, and instead you can simply re-create the API client if you receive an authorization error while attempting to perform a request.</p>\n\n<pre><code>public class RestApiClient\n{\n public RestApiClient(HttpClient httpClient)\n {\n this.httpClient = new httpClient;\n }\n\n public async Task<RestApiClient> Create(string username, string password)\n {\n if (username == null)\n {\n throw new ArgumentNullException(nameof(username));\n }\n\n if (password == null)\n {\n throw new ArgumentNullException(nameof(password));\n }\n\n var basicAuthBytes = Encoding.ASCII.GetBytes($"{username}:{password}");\n var basicAuthValue = Convert.ToBase64String(basicAuthBytes);\n\n var authenticationHttpClient = new HttpClient\n {\n BaseUri = new Uri("https://auth.example.io"),\n DefaultRequestHeaders = {\n Authentication = new AuthenticationHeaderValue("Basic", basicAuthValue)\n }\n };\n\n using (authenticationHttpClient)\n {\n var response = await httpClient.GetAsync("login");\n var content = response.Content.ReadAsStringAsync();\n var authToken = content;\n var restApiHttpClient = new HttpClient\n {\n BaseUri = new Uri("https://api.example.io"), // notice this differs from the auth uri\n DefaultRequestHeaders = {\n Authentication = new AuthenticationHeaderValue("Bearer", authToken)\n }\n };\n\n return new RestApiClient(restApiHttpClient);\n }\n }\n}\n</code></pre>\n\n<p>The downsides of this method are few, in my experience.</p>\n\n<p>Generally, using this methodology means that you can no longer use the class as a DTO because deserializing to an object without a public default constructor is hard, at best. However, if you were using the object as a DTO, you shouldn\'t really be validating the object itself, but rather invaliding the values on the object as you attempt to use them, since technically the values aren\'t "invalid" with regards to the DTO.</p>\n\n<p>It also means that you\'ll end up creating factory methods or classes when you need to allow an IOC container to create the object, since otherwise the container won\'t know how to instantiate the object. However, in a lot of cases the factory methods end up being one of <code>Create</code> methods themselves.</p>\n'}, {'answer_id': 46705088, 'author': 'Raedwald', 'author_id': 545127, 'author_profile': 'https://Stackoverflow.com/users/545127', 'pm_score': 0, 'selected': False, 'text': "<p>The best advice I've seen about exceptions is to throw an exception if, and only if, the alternative is failure to meet a post condition or to maintain an invariant.</p>\n\n<p>That advice replaces an unclear subjective decision (is it a <em>good idea</em>) with a technical, precise question based on design decisions (invariant and post conditions) you should already have made.</p>\n\n<p>Constructors are just a particular, but not special, case for that advice. So the question becomes, what invariants should a class have? Advocates of a separate initialization method, to be called after construction, are suggesting that the class has two or more <em>operating mode</em>, with an <em>unready</em> mode after construction and at least one <em>ready</em> mode, entered after initialization. That is an additional complication, but acceptable if the class has multiple operating modes anyway. It is hard to see how that complication is worthwhile if the class would otherwise not have operating modes.</p>\n\n<p>Note that pushing set up into a separate initialization method does not enable you to avoid exceptions being thrown. Exceptions that your constructor might have thrown will now be thrown by the initialization method. All the useful methods of your class will have to throw exceptions if they are called for an uninitialized object.</p>\n\n<p>Note also that avoiding the possibility of exceptions being thrown by your constructor is troublesome, and in many cases <em>impossible</em> in many standard libraries. This is because the designers of those libraries believe that throwing exceptions from constructors is a good idea. In particular, any operation that attempts to acquire a non shareable or finite resource (such as allocating memory) can fail, and that failure is typically indicated in OO languages and libraries by throwing an exception.</p>\n"}, {'answer_id': 49033272, 'author': 'Denise Skidmore', 'author_id': 2091951, 'author_profile': 'https://Stackoverflow.com/users/2091951', 'pm_score': 1, 'selected': False, 'text': "<p>I'm not sure that any answer can be entirely language-agnostic. Some languages handle exceptions and memory management differently. </p>\n\n<p>I've worked before under coding standards requiring exceptions never be used and only error codes on initializers, because developers had been burned by the language poorly handling exceptions. Languages without garbage collection will handle heap and stack very differently, which may matter for non RAII objects. It is important though that a team decide to be consistent so they know by default if they need to call initializers after constructors. All methods (including constructors) should also be well documented as to what exceptions they can throw, so callers know how to handle them.</p>\n\n<p>I'm generally in favor of a single-stage construction, as it's easy to forget to initialize an object, but there are plenty of exceptions to that.</p>\n\n<ul>\n<li>Your language support for exceptions isn't very good.</li>\n<li>You have a pressing design reason to still use <code>new</code> and <code>delete</code></li>\n<li>Your initialization is processor intensive and should run async to the thread that created the object.</li>\n<li>You are creating a DLL that may be throwing exceptions outside it's interface to an application using a different language. In this case it may not be so much an issue of not throwing exceptions, but making sure they are caught before the public interface. (You can catch C++ exceptions in C#, but there are hoops to jump through.)</li>\n<li>Static constructors (C#)</li>\n</ul>\n"}, {'answer_id': 51277298, 'author': 'Ashley', 'author_id': 5370163, 'author_profile': 'https://Stackoverflow.com/users/5370163', 'pm_score': 1, 'selected': False, 'text': '<p>The OP\'s question has a "language-agnostic" tag... this question cannot be safely answered the same way for all languages/situations.</p>\n\n<p>The following C# example\'s class hierarchy throws in class B\'s constructor, skipping an immediate call to class A\'s <code>IDisposeable.Dispose</code> upon exit of the main\'s <code>using</code>, skipping explicit disposal of class A\'s resources.</p>\n\n<p>If, for example, class A had created a <code>Socket</code> at construction, connected to a network resource, such would likely still be the case after the <code>using</code> block (a relatively hidden anomaly). </p>\n\n<pre><code>class A : IDisposable\n{\n public A()\n {\n Console.WriteLine("Initialize A\'s resources.");\n }\n\n public void Dispose()\n {\n Console.WriteLine("Dispose A\'s resources.");\n }\n}\n\nclass B : A, IDisposable\n{\n public B()\n {\n Console.WriteLine("Initialize B\'s resources.");\n throw new Exception("B construction failure: B can cleanup anything before throwing so this is not a worry.");\n }\n\n public new void Dispose()\n {\n Console.WriteLine("Dispose B\'s resources.");\n base.Dispose();\n }\n}\nclass C : B, IDisposable\n{\n public C()\n {\n Console.WriteLine("Initialize C\'s resources. Not called because B throws during construction. C\'s resources not a worry.");\n }\n\n public new void Dispose()\n {\n Console.WriteLine("Dispose C\'s resources.");\n base.Dispose();\n }\n}\n\n\nclass Program\n{\n static void Main(string[] args)\n {\n try\n {\n using (C c = new C())\n {\n }\n }\n catch\n { \n }\n\n // Resource\'s allocated by c\'s "A" not explicitly disposed.\n }\n}\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77639', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14050/'] |
77,659 | <p>I have a .NET <strong>2.0</strong> WebBrowser control used to navigate some pages with no user interaction (don't ask...long story). Because of the user-less nature of this application, I have set the WebBrowser control's ScriptErrorsSuppressed property to true, which the documentation included with VS 2005 states will [...]"hide all its dialog boxes that originate from the underlying ActiveX control, not just script errors." The <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.scripterrorssuppressed(VS.80).aspx" rel="noreferrer">MSDN article</a> doesn't mention this, however.
I have managed to cancel the NewWindow event, which prevents popups, so that's taken care of.</p>
<p>Anyone have any experience using one of these and successfully blocking <strong>all</strong> dialogs, script errors, etc?</p>
<p><strong>EDIT</strong></p>
<p>This isn't a standalone instance of IE, but an instance of a WebBrowser control living on a Windows Form application. Anyone have any experience with this control, or the underlying one, <strong>AxSHDocVW</strong>?</p>
<p><strong>EDIT again</strong></p>
<p>Sorry I forgot to mention this... I'm trying to block a <strong>JavaScript alert()</strong>, with just an OK button. Maybe I can cast into an IHTMLDocument2 object and access the scripts that way, I've used MSHTML a little bit, anyone know?</p>
| [{'answer_id': 98543, 'author': 'William', 'author_id': 14829, 'author_profile': 'https://Stackoverflow.com/users/14829', 'pm_score': 0, 'selected': False, 'text': "<p>Are you trying to implement a web robot? I have little experience in using the hosted IE control but I did completed a few Win32 projects tried to use the IE control. Disabling the popups should be done via the event handlers of the control as you already did, but I found that you also need to change the 'Disable script debugging xxxx' in the IE options (or you could modify the registry in your codes) as cjheath already pointed out. However I also found that extra steps needed to be done on checking the navigating url for any downloadable contents to prevent those open/save dialogs. But I do not know how to deal with streaming files since I cannot skip them by looking at the urls alone and in the end I turned to the Indy library saving me all the troubles in dealing with IE. Finally, I remember Microsoft did mention something online that IE is not designed to be used as an OLE control. According to my own experience, every time the control navigates to a new page did introduce memory leaks for the programs!</p>\n"}, {'answer_id': 101632, 'author': 'David Mohundro', 'author_id': 4570, 'author_profile': 'https://Stackoverflow.com/users/4570', 'pm_score': 4, 'selected': True, 'text': '<p>This is most definitely hacky, but if you do any work with the WebBrowser control, you\'ll find yourself doing a lot of hacky stuff.</p>\n\n<p>This is the easiest way that I know of to do this. You need to inject JavaScript to override the alert function... something along the lines of injecting this JavaScript function:</p>\n\n<pre><code>window.alert = function () { }\n</code></pre>\n\n<p>There are <em>many ways to do this</em>, but it is very possible to do. One possibility is to hook an implementation of the <a href="http://msdn.microsoft.com/en-us/library/aa768283.aspx" rel="noreferrer">DWebBrowserEvents2</a> interface. Once this is done, you can then plug into the NavigateComplete, the DownloadComplete, or the DocumentComplete (or, as we do, some variation thereof) and then call an InjectJavaScript method that you\'ve implemented that performs this overriding of the window.alert method.</p>\n\n<p>Like I said, hacky, but it works :)</p>\n\n<p>I can go into more details if I need to.</p>\n'}, {'answer_id': 110048, 'author': 'Jim Crafton', 'author_id': 9864, 'author_profile': 'https://Stackoverflow.com/users/9864', 'pm_score': 3, 'selected': False, 'text': '<p>You may have to customize some things, take a look at <code>IDocHostUIHandler</code>, and then check out some of the other related interfaces. You can have a fair amount of control, even to the point of customizing dialog display/ui (I can\'t recall which interface does this). I\'m pretty sure you can do what you want, but it does require mucking around in the internals of <code>MSHTML</code> and being able to implement the various <code>COM</code> interfaces.</p>\n\n<p>Some other ideas:\n<a href="http://msdn.microsoft.com/en-us/library/aa770041.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa770041.aspx</a></p>\n\n<pre><code>IHostDialogHelper\nIDocHostShowUI\n</code></pre>\n\n<p>These may be the things you\'re looking at implementing.</p>\n'}, {'answer_id': 251524, 'author': 'Sire', 'author_id': 2440, 'author_profile': 'https://Stackoverflow.com/users/2440', 'pm_score': 4, 'selected': False, 'text': '<p>And for an easy way to inject that magic line of javascript, read <a href="https://stackoverflow.com/questions/153748/webbrowser-control-from-net-how-to-inject-javascript">how to inject javascript into webbrowser control</a>.</p>\n\n<p>Or just use this complete code: </p>\n\n<pre><code>private void InjectAlertBlocker() {\n HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];\n HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");\n string alertBlocker = "window.alert = function () { }";\n scriptEl.SetAttribute("text", alertBlocker);\n head.AppendChild(scriptEl);\n}\n</code></pre>\n'}, {'answer_id': 330495, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>I managed to inject the code above by creating an extended <code>WebBroswer</code> class and overriding the <code>OnNavigated</code> method.\n<br /><br />\nThis seemed to work quite well:\n<br /></p>\n\n<pre><code>class WebBrowserEx : WebBrowser\n{\n public WebBrowserEx ()\n {\n }\n\n protected override void OnNavigated( WebBrowserNavigatedEventArgs e )\n {\n HtmlElement he = this.Document.GetElementsByTagName( "head" )[0];\n HtmlElement se = this.Document.CreateElement( "script" );\n mshtml.IHTMLScriptElement element = (mshtml.IHTMLScriptElement)se.DomElement;\n string alertBlocker = "window.alert = function () { }";\n element.text = alertBlocker;\n he.AppendChild( se );\n base.OnNavigated( e );\n }\n}\n</code></pre>\n'}, {'answer_id': 5780448, 'author': 'abobjects.com', 'author_id': 618173, 'author_profile': 'https://Stackoverflow.com/users/618173', 'pm_score': 2, 'selected': False, 'text': '<p>The <code>InjectAlertBlocker</code> is absolutely correct\ncode is </p>\n\n<pre><code>private void InjectAlertBlocker() {\n HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];\n HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");\n IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;\n string alertBlocker = "window.alert = function () { }";\n element.text = alertBlocker;\n head.AppendChild(scriptEl);\n}\n</code></pre>\n\n<p>References needed to be added is </p>\n\n<ol>\n<li><p>Add a reference to <code>MSHTML</code>, which will probalby be called "<strong>Microsoft HTML Object Library</strong>" under <code>COM</code> references.</p></li>\n<li><p>Add <code>using mshtml;</code> to your namespaces.</p></li>\n<li><p>Get a reference to your script element\'s <code>IHTMLElement</code>:</p></li>\n</ol>\n\n<p>Then you can use the <code>Navigated</code> event of webbrowser as:</p>\n\n<pre><code>private void InjectAlertBlocker()\n{\n HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];\n HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");\n IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;\n string alertBlocker = "window.alert = function () { }";\n element.text = alertBlocker;\n head.AppendChild(scriptEl);\n}\n\nprivate void webDest_Navigated(object sender, WebBrowserNavigatedEventArgs e)\n{\n InjectAlertBlocker();\n}\n</code></pre>\n'}, {'answer_id': 7903067, 'author': 'Prashant Bassi', 'author_id': 1014615, 'author_profile': 'https://Stackoverflow.com/users/1014615', 'pm_score': 2, 'selected': False, 'text': '<pre><code>webBrowser1.ScriptErrorsSuppressed = true;\n</code></pre>\n\n<p>Just add that to your entry level function. After alot of research is when I came across this method, and touch wood till now its worked. Cheers!!</p>\n'}, {'answer_id': 9412021, 'author': 'Legoless', 'author_id': 573186, 'author_profile': 'https://Stackoverflow.com/users/573186', 'pm_score': 0, 'selected': False, 'text': '<p>I had bigger problems with this: loading a webpage that is meant for printing and it displays annoying Print dialog. The InjectBlocker was the only way that worked, but fairly unreliable. Under certain conditions (I am considering it\'s due that WebBrowser control uses IE engine and this depends on installed IE version) the print dialog still appears. This is a major problem, the solution works on Win7 with IE9 installed, but WinXP with IE8 displays the dialog, no matter what.</p>\n\n<p>I believe the solution is in modifying source code and removing the print javascript, before control renders the page. However I tried that with: DocumentText property of the webbrowser control and it is not working. The property is not read only, but it has no effect, when I modify the source.</p>\n\n<p>The solution I found for my problem is the Exec script:</p>\n\n<pre><code>string alertBlocker = "window.print = function emptyMethod() { }; window.alert = function emptyMethod() { }; window.open = function emptyMethod() { };"; \nthis.Document.InvokeScript("execScript", new Object[] { alertBlocker, "JavaScript" });\n</code></pre>\n'}, {'answer_id': 9812051, 'author': 'Harry', 'author_id': 126537, 'author_profile': 'https://Stackoverflow.com/users/126537', 'pm_score': 3, 'selected': False, 'text': '<p>Bulletproof alert blocker:</p>\n\n<pre><code>Browser.Navigated +=\n new WebBrowserNavigatedEventHandler(\n (object sender, WebBrowserNavigatedEventArgs args) => {\n Action<HtmlDocument> blockAlerts = (HtmlDocument d) => {\n HtmlElement h = d.GetElementsByTagName("head")[0];\n HtmlElement s = d.CreateElement("script");\n IHTMLScriptElement e = (IHTMLScriptElement)s.DomElement;\n e.text = "window.alert=function(){};";\n h.AppendChild(s);\n };\n WebBrowser b = sender as WebBrowser;\n blockAlerts(b.Document);\n for (int i = 0; i < b.Document.Window.Frames.Count; i++)\n try { blockAlerts(b.Document.Window.Frames[i].Document); }\n catch (Exception) { };\n }\n );\n</code></pre>\n\n<p>This sample assumes you have <em>Microsoft.mshtml</em> reference added, "<em>using mshtml;</em>" in your namespaces and <em>Browser</em> is your <em>WebBrowser</em> instance.</p>\n\n<p>Why is it bulletproof? First, it <strong>handles scripts inside frames</strong>. Then, it <strong>doesn\'t crash</strong> when a special <em>"killer frame"</em> exists in document. A <em>"killer frame"</em> is a frame which raises an exception on attempt to use it as HtmlWindow object. Any "foreach" used on Document.Window.Frames would cause an exception, so safer "for" loop must be used with try / catch block.</p>\n\n<p>Maybe it\'s not the most readable piece of code, but it works with real life, ill-formed pages.</p>\n'}, {'answer_id': 14669921, 'author': 'volody', 'author_id': 241811, 'author_profile': 'https://Stackoverflow.com/users/241811', 'pm_score': 2, 'selected': False, 'text': '<p>window.showModelessDialog and window.showModalDialog can be blocked by implementing INewWindowManager interface, additionally code below show how to block alert dialogs by implementing IDocHostShowUI</p>\n\n<pre><code>public class MyBrowser : WebBrowser\n{\n\n [PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]\n public MyBrowser()\n {\n }\n\n protected override WebBrowserSiteBase CreateWebBrowserSiteBase()\n {\n var manager = new NewWindowManagerWebBrowserSite(this);\n return manager;\n }\n\n protected class NewWindowManagerWebBrowserSite : WebBrowserSite, IServiceProvider, IDocHostShowUI\n {\n private readonly NewWindowManager _manager;\n\n public NewWindowManagerWebBrowserSite(WebBrowser host)\n : base(host)\n {\n _manager = new NewWindowManager();\n }\n\n public int ShowMessage(IntPtr hwnd, string lpstrText, string lpstrCaption, int dwType, string lpstrHelpFile, int dwHelpContext, out int lpResult)\n {\n lpResult = 0;\n return Constants.S_OK; // S_OK Host displayed its UI. MSHTML does not display its message box.\n }\n\n // Only files of types .chm and .htm are supported as help files.\n public int ShowHelp(IntPtr hwnd, string pszHelpFile, uint uCommand, uint dwData, POINT ptMouse, object pDispatchObjectHit)\n {\n return Constants.S_OK; // S_OK Host displayed its UI. MSHTML does not display its message box.\n }\n\n #region Implementation of IServiceProvider\n\n public int QueryService(ref Guid guidService, ref Guid riid, out IntPtr ppvObject)\n {\n if ((guidService == Constants.IID_INewWindowManager && riid == Constants.IID_INewWindowManager))\n {\n ppvObject = Marshal.GetComInterfaceForObject(_manager, typeof(INewWindowManager));\n if (ppvObject != IntPtr.Zero)\n {\n return Constants.S_OK;\n }\n }\n ppvObject = IntPtr.Zero;\n return Constants.E_NOINTERFACE;\n }\n\n #endregion\n }\n }\n\n[ComVisible(true)]\n[Guid("01AFBFE2-CA97-4F72-A0BF-E157038E4118")]\npublic class NewWindowManager : INewWindowManager\n{\n public int EvaluateNewWindow(string pszUrl, string pszName,\n string pszUrlContext, string pszFeatures, bool fReplace, uint dwFlags, uint dwUserActionTime)\n {\n\n // use E_FAIL to be the same as CoInternetSetFeatureEnabled with FEATURE_WEBOC_POPUPMANAGEMENT\n //int hr = MyBrowser.Constants.E_FAIL; \n int hr = MyBrowser.Constants.S_FALSE; //Block\n //int hr = MyBrowser.Constants.S_OK; //Allow all\n return hr;\n }\n}\n</code></pre>\n'}, {'answer_id': 35044129, 'author': 'Marym Nor Marym Nor', 'author_id': 5848168, 'author_profile': 'https://Stackoverflow.com/users/5848168', 'pm_score': 0, 'selected': False, 'text': '<p>Simply from the browser control properties: scriptErrorSupressed=true</p>\n'}, {'answer_id': 36258414, 'author': 'IsLeadByte', 'author_id': 6123304, 'author_profile': 'https://Stackoverflow.com/users/6123304', 'pm_score': 0, 'selected': False, 'text': '<p>The easiest way to do this is : \nIn the : Webbrowser Control you have the procedure ( standard ) <code>BeforeScriptExecute</code> </p>\n\n<p>( The parameter for <code>BeforeScriptExecute</code> is <code>pdispwindow</code> )</p>\n\n<p>Add this :</p>\n\n<pre><code>pdispwindow.execscript("window.alert = function () { }")\n</code></pre>\n\n<p>In this way before any script execution on the page window alert will be suppressed by injected code.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77659', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13791/'] |
77,664 | <p>We're currently running a server on Compatibility mode 8 and I want to update it. </p>
<ul>
<li>What are the implications of just going in and changing it? </li>
<li>What is likely to break? </li>
<li>Is there anything that checks the data will survive before I perform it? </li>
<li>Can I rollback to mode 8 without performing a restore and without loss of data?</li>
</ul>
| [{'answer_id': 77713, 'author': 'Mitchel Sellers', 'author_id': 13279, 'author_profile': 'https://Stackoverflow.com/users/13279', 'pm_score': 0, 'selected': False, 'text': "<p>Compatibility mode disables the features of the newer version, personally I haven't really worked with many databases that have issues, the key thing that was a problem in our environment is after moving to 9, you can no longer use Enterprise Manager to view the database.</p>\n\n<p>A backup/restore is a good option, and I also believe you can flip it back without any issues.</p>\n"}, {'answer_id': 77767, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': True, 'text': '<p>If you\'re going from 80 to 90, the differences are minimal. Going from 65 to 70+ can cause severe impact (NULLs are stored differently).</p>\n\n<p>Implications - your SPs can return different results than you\'d expect\nLikely to break: functions, SPs\nData should survive; nothing in there should affect things.<br>\nMoving from 80 to 90 and back only takes a few seconds. Yes, you can move back and forth.</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/bb510680.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/bb510680.aspx</a></p>\n\n<p>some gotchas: <a href="http://mapamdug.blogspot.com/2006/03/sql-server-2005-gotcha-1.html" rel="noreferrer">http://mapamdug.blogspot.com/2006/03/sql-server-2005-gotcha-1.html</a></p>\n'}, {'answer_id': 77808, 'author': 'GSerg', 'author_id': 11683, 'author_profile': 'https://Stackoverflow.com/users/11683', 'pm_score': 2, 'selected': False, 'text': '<ol>\n<li>Compatibility mode does not affect storage. It\'s just a flag. Nothing will change in the data or queries. Only query execution will get affected.</li>\n<li>Nothing - or lots of things. Did you use syntax marked as obsolete and subject to deletion in 2000? Did you use parethesis when providing hints in queries? Did you use query execution hints? If yes, it\'s better to revise your database first, remove obsolete syntax, put the parenthesis back and dig the BOL to find which hints are going to slow down your fine-tuned query on new engine.</li>\n<li>No. But the data will survive. In fact, if you are able to run your database on server2005, even in mode 8, you\'re using new data format already.</li>\n<li>Yes, you can roll back. It\'s not transforming, it\'s just setting a flag which says "My queries are that compatible."</li>\n</ol>\n'}, {'answer_id': 83146, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>(I did say it was only if you were moving from 6.5, which stored nothing in <code>char()</code> fields when NULL - 70 and greater use the whole of the field, which can cause massive size changes.)</p>\n\n<p>VBStreets is right on his points - and definitely on point 3 - when you first ran the database on 2005 it converted the data structure. If you take a backup, it cannot be restored on prior versions, regardless of the compatibility level.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77664', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5055/'] |
77,683 | <p>For example, <a href="http://reductiotest.org/" rel="nofollow noreferrer">Reductio</a> (for Java/Scala) and <a href="http://www.cs.chalmers.se/~rjmh/QuickCheck/" rel="nofollow noreferrer">QuickCheck</a> (for Haskell). The kind of framework I'm thinking of would provide "generators" for built-in data types and allow the programmer to define new generators. Then, the programmer would define a test method that asserts some property, taking variables of the appropriate types as parameters. The framework then generates a bunch of random data for the parameters, and runs hundreds of tests of that method.</p>
<p>For example, if I implemented a Vector class, and it had an add() method, I might want to check that my addition commutes. So I would write something like (in pseudocode):</p>
<pre><code>boolean testAddCommutes(Vector v1, Vector v2) {
return v1.add(v2).equals(v2.add(v1));
}
</code></pre>
<p>I could run testAddCommutes() on two particular vectors to see if that addition commutes. But instead of writing a few invocations of testAddCommutes, I write a procedure than generates arbitrary Vectors. Given this, the framework can run testAddCommutes on hundreds of different inputs.</p>
<p>Does this ring a bell for anyone?</p>
| [{'answer_id': 77720, 'author': 'Adam Driscoll', 'author_id': 13688, 'author_profile': 'https://Stackoverflow.com/users/13688', 'pm_score': -1, 'selected': False, 'text': '<p>I might not understand you correctly but check this out...</p>\n\n<p><a href="http://www.ayende.com/projects/rhino-mocks.aspx" rel="nofollow noreferrer">http://www.ayende.com/projects/rhino-mocks.aspx</a></p>\n'}, {'answer_id': 79139, 'author': 'Alan', 'author_id': 9916, 'author_profile': 'https://Stackoverflow.com/users/9916', 'pm_score': 1, 'selected': False, 'text': '<p>I may not understand correctly either, but <a href="http://www.codeplex.com/Pex" rel="nofollow noreferrer">PEX</a> may be of use to you.</p>\n'}, {'answer_id': 1542844, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>There\'s FsCheck, a port from QuickCheck to F# and thus C#, although most of the doc seems to be for f#.\nI\'ve been exploring the ideas myself aswell. see : <a href="http://kilfour.wordpress.com/2009/08/02/testing-tool-tour-quicknet-preview/" rel="nofollow noreferrer">http://kilfour.wordpress.com/2009/08/02/testing-tool-tour-quicknet-preview/</a></p>\n'}, {'answer_id': 1580698, 'author': 'kilfour', 'author_id': 191485, 'author_profile': 'https://Stackoverflow.com/users/191485', 'pm_score': 1, 'selected': False, 'text': '<p>to elaborate on my previous remark, the QN code to test the pseudo-code example would look something like this :</p>\n\n<pre>\nnew TestRun(1, 1000)\n .AddTransition(new MetaTransition<Input<Vector, Vector>, Vector>\n {\n Name = "Vector Add ",\n Generator = DoubleVectorGenerator,\n Execute = input => input.paramOne.Add(input.paramTwo)\n }\n .RegisterProperty(\n (input, output) =>\n new QnProperty(\n "Is Communative",\n () => QnAssert.IsTrue(output == input.paramTwo.Add(input.paramOne) )\n )\n )\n )\n .Verify()\n .RethrowLastFailureifAny()\n .ReportPropertiesTested(new ConsoleReporter());\n</pre>\n\n<p>where DoubleVectorGenerator is a userdefined class supplying values of the type Input<Vector, Vector>.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77683', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14113/'] |
77,686 | <p>Is it possible to sign only part of an applet? Ie, have an applet that pops up no security warnings about being signed, but if some particular function is used (that requires privileges) then use the signed jar?</p>
<p>From what I can tell, some (perhaps most) browsers will pop up the warning for a signed applet even if you don't request privileges at all at execution time. I'd rather avoid that if possible.</p>
| [{'answer_id': 78036, 'author': 'Jason Dagit', 'author_id': 5113, 'author_profile': 'https://Stackoverflow.com/users/5113', 'pm_score': -1, 'selected': False, 'text': '<p>I\'ve been given the impression that Sun wants to discourage the creation of Applets and encourage the usage of Java Web Start. I think this issue of signing applets is part of the problem. See this documentation from Sun: <a href="http://java.sun.com/j2se/1.5.0/docs/guide/javaws/developersguide/faq.html" rel="nofollow noreferrer">Java Web start FAQ</a>.</p>\n\n<p>I haven\'t tried this, but could you segment the features that need signing into separate jars that only require permission checks when the user needs the functionality in those jars?</p>\n'}, {'answer_id': 78224, 'author': 'James A. N. Stauffer', 'author_id': 6770, 'author_profile': 'https://Stackoverflow.com/users/6770', 'pm_score': 2, 'selected': True, 'text': '<p>Try splitting your code into an unsigned jar and a signed jar.</p>\n'}, {'answer_id': 93350, 'author': 'Javaxpert', 'author_id': 15241, 'author_profile': 'https://Stackoverflow.com/users/15241', 'pm_score': 1, 'selected': False, 'text': "<p>In theory you can (signed + unsigned jar), but in practice it will result that your code will be handled as unsigned. The access decision should be made from the thread, not the immediate caller. If the thread contains in the stack a call made from an object from unsigned code, the whole call should be treated as unsigned. If you work around this you've found a bug.</p>\n\n<p>In other words... <strong>No</strong>.</p>\n\n<p>If I'm not being to curious, may I inquire why do you want to partially sign your code?</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77686', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1432/'] |
77,694 | <p>I've defined a view with the CCK and View 2 modules. I would like to quickly define a template specific to this view. Is there any tutorial or information on this? What are the files I need to modify?</p>
<hr>
<p><strong>Here are my findings: (Edited)</strong></p>
<p>In fact, there are two ways to theme a view: the "<strong>field</strong>" way and the "<strong>node</strong>" way. In "edit View", you can choose "<code>Row style: Node</code>", or "<code>Row style: Fields</code>".</p>
<ul>
<li>with the "<strong>Node</strong>" way, you can create a <strong>node-contentname.tpl.php</strong> which will be called for each node in the view. You'll have access to your cck field values with $field_name[0]['value']. (edit2) You can use <strong>node-view-viewname.tpl.php</strong> which will be only called for each node displayed from this view.</li>
<li>with the "<strong>Field</strong>" way, you add a views-view-field--viewname--field-name-value.tpl.php for each field you want to theme individually.</li>
</ul>
<p>Thanks to previous responses, I've used the following tools :</p>
<ul>
<li>In the 'Basic Settings' block, the 'Theme: Information' to see all the different templates you can modify.</li>
<li>The <a href="http://drupal.org/project/devel" rel="nofollow noreferrer">Devel module</a>'s "Theme developer" to quickly find the field variable names.</li>
<li><a href="http://views-help.doc.logrus.com/" rel="nofollow noreferrer">View 2 documentation</a>, especially the <a href="http://views-help.doc.logrus.com/help/views/using-theme" rel="nofollow noreferrer">"Using Theme"</a> page.</li>
</ul>
| [{'answer_id': 78158, 'author': 'Pierre-Jean Coudert', 'author_id': 8450, 'author_profile': 'https://Stackoverflow.com/users/8450', 'pm_score': 7, 'selected': True, 'text': '<p>In fact there are two ways to theme a view : the "<strong>field</strong>" way and the "<strong>node</strong>" way. In "edit View", you can choose "<code>Row style: Node</code>", or "<code>Row style: Fields</code>".</p>\n\n<ul>\n<li>with the "<strong>Node</strong>" way, you can create a node-contentname.tpl.php wich will be called for each node in the view. You\'ll have access to your cck field values with $field_name[0][\'value\']</li>\n<li>with the "<strong>Field</strong>" way, you add a views-view-field--viewname--field-name-value.tpl.php for each field you want to theme individually.</li>\n</ul>\n\n<p>Thanks to previous responses, I\'ve used the following tools :</p>\n\n<ul>\n<li>In the \'Basic Settings\' block, the \'Theme: Information\' to see all the different templates you can modify.</li>\n<li>The <a href="http://drupal.org/project/devel" rel="noreferrer">Devel module</a>\'s "Theme developer" to quickly find the field variable names.</li>\n<li><a href="http://views-help.doc.logrus.com/" rel="noreferrer">View 2 documentation</a>, especially the <a href="http://views-help.doc.logrus.com/help/views/using-theme" rel="noreferrer">"Using Theme"</a> page.</li>\n</ul>\n'}, {'answer_id': 78330, 'author': 'calebbrown', 'author_id': 7007, 'author_profile': 'https://Stackoverflow.com/users/7007', 'pm_score': 5, 'selected': False, 'text': "<p>A quick way to find the template files you can create and modify for a view in Views 2.0 is to:</p>\n\n<ol>\n<li>Edit the view</li>\n<li>Select the style (e.g. page, block, default)</li>\n<li>In the 'Basic Settings' block click on 'Theme: Information' to see all the different templates you can modify.</li>\n</ol>\n"}, {'answer_id': 78620, 'author': 'Garrett Albright', 'author_id': 11023, 'author_profile': 'https://Stackoverflow.com/users/11023', 'pm_score': 4, 'selected': False, 'text': '<p>The <a href="http://drupal.org/project/devel" rel="noreferrer">Devel module</a>\'s "Theme developer" feature is handy for seeing what template files Drupal is looking for when it goes to theme something. See the screenshot on that page for an example.</p>\n'}, {'answer_id': 1248513, 'author': 'userp2m3h', 'author_id': 152933, 'author_profile': 'https://Stackoverflow.com/users/152933', 'pm_score': 2, 'selected': False, 'text': '<p>My shortcut option.</p>\n\n<ol>\n<li><p>Go to <strong>theme.inc</strong> file in <strong><code>YOUR_MODULE_DIR</code>/views/theme/</strong> folder.</p></li>\n<li><p>In the <strong><code>_views_theme_functions</code></strong> function print the <strong>$themes</strong> variable or put a breakpoint on the last line of the function to see the content of the variable.</p></li>\n</ol>\n\n<p>Just convert <strong><code>views_view</code></strong> to <strong>views-view</strong> and __ to -- and add your template extension to get desired file name.</p>\n\n<p>For example if an element of the <strong>$themes</strong> array is <strong><code>views_view__test_view__block</code></strong> (where <code>test_view</code> is the name of your view) then the name of the template file would be <strong>views-view--test_view--block.tpl.php</strong>.</p>\n'}, {'answer_id': 1598171, 'author': 'svassr', 'author_id': 193489, 'author_profile': 'https://Stackoverflow.com/users/193489', 'pm_score': 3, 'selected': False, 'text': '<p>for me <b>block-views-myViewName-myBlockId.tpl.php</b> works</p>\n'}, {'answer_id': 2306571, 'author': 'Sbhambry', 'author_id': 130927, 'author_profile': 'https://Stackoverflow.com/users/130927', 'pm_score': 2, 'selected': False, 'text': '<p>In my opinion the simplest way to decide which template file to use for theming the views is :\n1) Click on admin/build/views/edit/ViewName -> Basic Settings -> Theme</p>\n\n<p>Clicking this would list all the possible template files. Highlighted (File names in Bold) files indicate which template file is being used to do theme what part of the view. After incorporating the required changes in the relevant view template file RESCAN .. now you should be able to see the changed template file highlighted . </p>\n'}, {'answer_id': 3349883, 'author': 'David Eads', 'author_id': 371064, 'author_profile': 'https://Stackoverflow.com/users/371064', 'pm_score': 3, 'selected': False, 'text': '<p>You should also check out <a href="http://drupal.org/project/semanticviews" rel="noreferrer">Semantic Views</a>. For simple Views theming, it is <em>really</em> handy.</p>\n'}, {'answer_id': 5420512, 'author': 'James', 'author_id': 673434, 'author_profile': 'https://Stackoverflow.com/users/673434', 'pm_score': 3, 'selected': False, 'text': '<p>One tip:</p>\n\n<p>You\'ll likely have a number of views which require similar formatting. Creating templates for each of these views and copying them creates a nightmare of code branching - if you\'re asked to change the whole look and feel of the site (implying changing the display of each of these views formatted in this particular way), you have to go back and edit each of these separately.</p>\n\n<p>Instead of using the views interface to select new templates for views, I sometimes simply insert some code branching into a single views file. E.g. for one site in <code>views-view-fields.tpl.php</code> I have:</p>\n\n<pre><code>if($view->name == \'articleList\' || $view->name == \'frontList\' \n|| $view->name == \'archiveList\') {\n/* field formatting code */\n} else {\n/* the default code running here */\n}\n</code></pre>\n\n<p>This then modifies the fields in the way I want only for this family of Views = articleList, frontList and archiveList - and for other views using this template runs the code one normally finds in this template. If the client asks, "Hey, could you make those pages showing the archives & that list on the front page to look more like ( ... )", it\'s simply a matter of my opening & editing this one file, instead of three different files. Maintenance becomes much more quick & friendly.</p>\n'}, {'answer_id': 7268875, 'author': 'Karel', 'author_id': 722173, 'author_profile': 'https://Stackoverflow.com/users/722173', 'pm_score': 1, 'selected': False, 'text': '<p>If you want to do quick Drupal development with a lot of drag-and-drop, the Display Suite module def. is a something you should use: <a href="http://drupal.org/project/ds" rel="nofollow">http://drupal.org/project/ds</a></p>\n'}, {'answer_id': 41819937, 'author': 'carteblanche', 'author_id': 7460714, 'author_profile': 'https://Stackoverflow.com/users/7460714', 'pm_score': 0, 'selected': False, 'text': '<p>According to me there are two ways to do it:</p>\n\n<p>Programatic Way: </p>\n\n<ol>\n<li>Go to edit view. </li>\n<li>Select page/block style. </li>\n<li>Go to \'Basic Settings\' and click on \'Theme: Information\' to see all the different templates you can modify. </li>\n<li>Add the html you want to theme and print the variables of the view wherever needed</li>\n</ol>\n\n<p>Configuration Update: <img src="https://i.stack.imgur.com/CvhW1.png" alt="Using the Display suite">The Display suite provides us an option to place your labels inline or above and add even to hide them. Custom classes to each of the view\'s elements can be added too.\nAdvanced options include:</p>\n\n<ul>\n<li>Exportables</li>\n<li>Add your own custom fields in the backend or in your code</li>\n<li>Add custom layouts in your theme (D7 only)</li>\n<li>Change labels, add styles or override field settings (semantic fields).</li>\n<li>Full integration with Views and Panels</li>\n<li>Extend the power of your layouts by installing Field Group</li>\n<li>Optimal performance with Object cache (D6) or Entity cache (D7) integration</li>\n</ul>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77694', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8450/'] |
77,695 | <p>What do I need to set up and maintain a local CPAN mirror? What scripts and best practices should I be aware of?</p>
| [{'answer_id': 77722, 'author': 'mopoke', 'author_id': 14054, 'author_profile': 'https://Stackoverflow.com/users/14054', 'pm_score': 2, 'selected': False, 'text': '<p>Try <a href="http://search.cpan.org/perldoc/CPAN::Mini" rel="nofollow noreferrer">CPAN::Mini</a>.</p>\n'}, {'answer_id': 77840, 'author': 'xdg', 'author_id': 11800, 'author_profile': 'https://Stackoverflow.com/users/11800', 'pm_score': 5, 'selected': False, 'text': '<p><a href="http://search.cpan.org/perldoc?CPAN::Mini" rel="noreferrer">CPAN::Mini</a> is the way to go. Once you\'ve mirrored CPAN locally, you\'ll want to set your mirror URL in CPAN.pm or CPANPLUS to the local directory using a "file:" URL like this:</p>\n\n<pre><code>file:///path/to/my/cpan/mirror\n</code></pre>\n\n<p>If you\'d like your mirror to have copies of development versions of CPAN distribution, you can use <a href="http://search.cpan.org/perldoc?CPAN::Mini::Devel" rel="noreferrer">CPAN::Mini::Devel</a>.</p>\n\n<p>Update: </p>\n\n<p>The <a href="http://www.cpan.org/misc/cpan-faq.html#How_mirror_CPAN" rel="noreferrer">"What do I need to mirror CPAN?"</a> FAQ given in another answer is for mirroring <em>all</em> of CPAN, usually to provide another public mirror. That includes old, outdated versions of distributions. CPAN::Mini just mirrors the latest versions. This is much smaller and for most users is generally what people would use for local or disconnected (laptop) access to CPAN.</p>\n'}, {'answer_id': 78078, 'author': 'moritz', 'author_id': 14132, 'author_profile': 'https://Stackoverflow.com/users/14132', 'pm_score': 3, 'selected': False, 'text': '<p>CPAN::Mini is fine. By default it keeps only the latest version of a distribution, not every version as CPAN does.</p>\n\n<p>You can also install CPAN::Mini::Webserver, which provides you with a web interface to your local cpan mirror - very handy if you are offline and still want to work with perl.</p>\n'}, {'answer_id': 82989, 'author': 'Jon Topper', 'author_id': 6945, 'author_profile': 'https://Stackoverflow.com/users/6945', 'pm_score': 2, 'selected': False, 'text': "<p>The most likely scenario for running a CPAN mirror is so that your network of 50 machines can all be updated from it locally, instead of hitting the network 50 times.</p>\n\n<p>I'd argue that using CPAN in the traditional manner is a poor way to keep a network of servers up to date.</p>\n\n<p>I run a network of RedHat machines. I package all CPAN modules intended for use in production into RPMs (mostly using the cpanflute2 tool from RPM::Specfile) and deploy them that way, thereby ensuring proper dependency tracking which you don't really get from CPAN itself in any sane way.</p>\n"}, {'answer_id': 109447, 'author': 'brian d foy', 'author_id': 2766176, 'author_profile': 'https://Stackoverflow.com/users/2766176', 'pm_score': 3, 'selected': False, 'text': '<p>Besides the other answers, check out Leon\'s <a href="http://search.cpan.org/dist/CPAN-Mini-Webserver" rel="nofollow noreferrer">CPAN::Mini::Webserver</a>, which gives you a <a href="http://search.cpan.org" rel="nofollow noreferrer">CPAN Search</a> interface to your local CPAN copy.</p>\n\n<p>If you want to do more fancy things, see my <A href="http://www.slideshare.net/brian_d_foy/mycpan-lapm-september-2007" rel="nofollow noreferrer">"MyCPAN"</a> talk. You can inject your own private modules into your private CPAN with <a href="http://search.cpan.org/dist/CPAN-Mini-Inject" rel="nofollow noreferrer">CPAN::Mini::Inject</a>, for instance.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77695', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9532/'] |
77,718 | <p>Coming from C++ to Java, the obvious unanswered question is why didn't Java include operator overloading?</p>
<p>Isn't <code>Complex a, b, c; a = b + c;</code> much simpler than <code>Complex a, b, c; a = b.add(c);</code>?</p>
<p>Is there a known reason for this, valid arguments for <em>not</em> allowing operator overloading? Is the reason arbitrary, or lost to time?</p>
| [{'answer_id': 77738, 'author': 'Sarien', 'author_id': 1994377, 'author_profile': 'https://Stackoverflow.com/users/1994377', 'pm_score': 3, 'selected': False, 'text': "<p>Well you can really shoot yourself in the foot with operator overloading. It's like with pointers people make stupid mistakes with them and so it was decided to take the scissors away.</p>\n\n<p>At least I think that's the reason.\nI'm on your side anyway. :)</p>\n"}, {'answer_id': 77790, 'author': 'user14128', 'author_id': 14128, 'author_profile': 'https://Stackoverflow.com/users/14128', 'pm_score': 3, 'selected': False, 'text': '<p>I think this may have been a conscious design choice to force developers to create functions whose names clearly communicate their intentions. In C++ developers would overload operators with functionality that would often have no relation to the commonly accepted nature of the given operator, making it nearly impossible to determine what a piece of code does without looking at the definition of the operator.</p>\n'}, {'answer_id': 77798, 'author': 'Sebastian Redl', 'author_id': 8922, 'author_profile': 'https://Stackoverflow.com/users/8922', 'pm_score': 4, 'selected': False, 'text': "<p>The Java designers decided that operator overloading was more trouble than it was worth. Simple as that.</p>\n\n<p>In a language where every object variable is actually a reference, operator overloading gets the additional hazard of being quite illogical - to a C++ programmer at least. Compare the situation with C#'s == operator overloading and <code>Object.Equals</code> and <code>Object.ReferenceEquals</code> (or whatever it's called).</p>\n"}, {'answer_id': 77811, 'author': 'David Schlosnagle', 'author_id': 1750, 'author_profile': 'https://Stackoverflow.com/users/1750', 'pm_score': 2, 'selected': False, 'text': '<p>Assuming Java as the implementation language then a, b, and c would all be references to type Complex with initial values of null. Also assuming that Complex is immutable as the mentioned <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigInteger.html" rel="nofollow noreferrer">BigInteger</a> and similar immutable <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html" rel="nofollow noreferrer">BigDecimal</a>, I\'d I think you mean the following, as you\'re assigning the reference to the Complex returned from adding b and c, and not comparing this reference to a.</p>\n\n<blockquote>\n <p>Isn\'t :</p>\n\n<pre><code>Complex a, b, c; a = b + c;\n</code></pre>\n \n <p><em>much</em> simpler than:</p>\n\n<pre><code>Complex a, b, c; a = b.add(c);\n</code></pre>\n</blockquote>\n'}, {'answer_id': 77908, 'author': 'noah', 'author_id': 12034, 'author_profile': 'https://Stackoverflow.com/users/12034', 'pm_score': 3, 'selected': False, 'text': '<p><a href="http://groovy.codehaus.org/" rel="noreferrer">Groovy</a> has operator overloading, and runs in the JVM. If you don\'t mind the performance hit (which gets smaller everyday). It\'s automatic based on method names. e.g., \'+\' calls the \'plus(argument)\' method.</p>\n'}, {'answer_id': 77963, 'author': 'Aaron', 'author_id': 14153, 'author_profile': 'https://Stackoverflow.com/users/14153', 'pm_score': 5, 'selected': True, 'text': "<p>Assuming you wanted to overwrite the previous value of the object referred to by <code>a</code>, then a member function would have to be invoked.</p>\n\n<pre><code>Complex a, b, c;\n// ...\na = b.add(c);\n</code></pre>\n\n<p>In C++, this expression tells the compiler to create three (3) objects on the stack, perform addition, and <em>copy</em> the resultant value from the temporary object into the existing object <code>a</code>.</p>\n\n<p>However, in Java, <code>operator=</code> doesn't perform value copy for reference types, and users can only create new reference types, not value types. So for a user-defined type named <code>Complex</code>, assignment means to copy a reference to an existing value.</p>\n\n<p>Consider instead:</p>\n\n<pre><code>b.set(1, 0); // initialize to real number '1'\na = b; \nb.set(2, 0);\nassert( !a.equals(b) ); // this assertion will fail\n</code></pre>\n\n<p>In C++, this copies the value, so the comparison will result not-equal. In Java, <code>operator=</code> performs reference copy, so <code>a</code> and <code>b</code> are now referring to the same value. As a result, the comparison will produce 'equal', since the object will compare equal to itself.</p>\n\n<p>The difference between copies and references only adds to the confusion of operator overloading. As @Sebastian mentioned, Java and C# both have to deal with value and reference equality separately -- <code>operator+</code> would likely deal with values and objects, but <code>operator=</code> is already implemented to deal with references.</p>\n\n<p>In C++, you should only be dealing with one kind of comparison at a time, so it can be less confusing. For example, on <code>Complex</code>, <code>operator=</code> and <code>operator==</code> are both working on values -- copying values and comparing values respectively.</p>\n"}, {'answer_id': 78086, 'author': 'Garth Gilmour', 'author_id': 2635682, 'author_profile': 'https://Stackoverflow.com/users/2635682', 'pm_score': 5, 'selected': False, 'text': '<p>James Gosling likened designing Java to the following:</p>\n\n<blockquote>\n <p>"There\'s this principle about moving, when you move from one apartment to another apartment. An interesting experiment is to pack up your apartment and put everything in boxes, then move into the next apartment and not unpack anything until you need it. So you\'re making your first meal, and you\'re pulling something out of a box. Then after a month or so you\'ve used that to pretty much figure out what things in your life you actually need, and then you take the rest of the stuff -- forget how much you like it or how cool it is -- and you just throw it away. It\'s amazing how that simplifies your life, and you can use that principle in all kinds of design issues: not do things just because they\'re cool or just because they\'re interesting."</p>\n</blockquote>\n\n<p>You can read the <a href="http://www.gotw.ca/publications/c_family_interview.htm" rel="noreferrer">context of the quote here</a></p>\n\n<p>Basically operator overloading is great for a class that models some kind of point, currency or complex number. But after that you start running out of examples fast.</p>\n\n<p>Another factor was the abuse of the feature in C++ by developers overloading operators like \'&&\', \'||\', the cast operators and of course \'new\'. The complexity resulting from combining this with pass by value and exceptions is well covered in the <a href="https://rads.stackoverflow.com/amzn/click/com/0201615622" rel="noreferrer" rel="nofollow noreferrer">Exceptional C++</a> book.</p>\n'}, {'answer_id': 78167, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>Sometimes it would be nice to have operator overloading, friend classes and multiple inheritance.</p>\n\n<p>However I still think it was a good decision. If Java would have had operator overloading then we could never be sure of operator meanings without looking through source code. At present that's not necessary. And I think your example of using methods instead of operator overloading is also quite readable. If you want to make things more clear you could always add a comment above hairy statements.</p>\n\n<pre><code>// a = b + c\nComplex a, b, c; a = b.add(c);\n</code></pre>\n"}, {'answer_id': 82890, 'author': 'user15793', 'author_id': 15793, 'author_profile': 'https://Stackoverflow.com/users/15793', 'pm_score': 5, 'selected': False, 'text': '<p>Check out Boost.Units: <a href="http://www.boost.org/doc/libs/1_36_0/doc/html/boost_units.html" rel="noreferrer">link text</a></p>\n\n<p>It provides zero-overhead Dimensional analysis through operator overloading. How much clearer can this get?</p>\n\n<pre><code>quantity<force> F = 2.0*newton;\nquantity<length> dx = 2.0*meter;\nquantity<energy> E = F * dx;\nstd::cout << "Energy = " << E << endl;\n</code></pre>\n\n<p>would actually output "Energy = 4 J" which is correct.</p>\n'}, {'answer_id': 194889, 'author': 'paercebal', 'author_id': 14089, 'author_profile': 'https://Stackoverflow.com/users/14089', 'pm_score': 10, 'selected': False, 'text': '<p>There are a lot of posts complaining about operator overloading.</p>\n<p>I felt I had to clarify the "operator overloading" concepts, offering an alternative viewpoint on this concept.</p>\n<h1>Code obfuscating?</h1>\n<p>This argument is a fallacy.</p>\n<h2>Obfuscating is possible in all languages...</h2>\n<p>It is as easy to obfuscate code in C or Java through functions/methods as it is in C++ through operator overloads:</p>\n<pre><code>// C++\nT operator + (const T & a, const T & b) // add ?\n{\n T c ;\n c.value = a.value - b.value ; // subtract !!!\n return c ;\n}\n\n// Java\nstatic T add (T a, T b) // add ?\n{\n T c = new T() ;\n c.value = a.value - b.value ; // subtract !!!\n return c ;\n}\n\n/* C */\nT add (T a, T b) /* add ? */\n{\n T c ;\n c.value = a.value - b.value ; /* subtract !!! */\n return c ;\n}\n</code></pre>\n<h2>...Even in Java\'s standard interfaces</h2>\n<p>For another example, let\'s see the <a href="http://download.oracle.com/javase/7/docs/api/java/lang/Cloneable.html" rel="noreferrer"><code>Cloneable</code> interface</a> in Java:</p>\n<p>You are supposed to clone the object implementing this interface. But you could lie. And create a different object. In fact, this interface is so weak you could return another type of object altogether, just for the fun of it:</p>\n<pre><code>class MySincereHandShake implements Cloneable\n{\n public Object clone()\n {\n return new MyVengefulKickInYourHead() ;\n }\n}\n</code></pre>\n<p>As the <code>Cloneable</code> interface can be abused/obfuscated, should it be banned on the same grounds C++ operator overloading is supposed to be?</p>\n<p>We could overload the <code>toString()</code> method of a <code>MyComplexNumber</code> class to have it return the stringified hour of the day. Should the <code>toString()</code> overloading be banned, too? We could sabotage <code>MyComplexNumber.equals</code> to have it return a random value, modify the operands... etc. etc. etc..</p>\n<p><b>In Java, as in C++, or whatever language, the programmer must respect a minimum of semantics when writing code. This means implementing an <code>add</code> function that adds, and <code>Cloneable</code> implementation method that clones, and a <code>++</code> operator that increments.</b></p>\n<h1>What\'s obfuscating anyway?</h1>\n<p>Now that we know that code can be sabotaged even through the pristine Java methods, we can ask ourselves about the real use of operator overloading in C++?</p>\n<h2>Clear and natural notation: methods vs. operator overloading?</h2>\n<p>We\'ll compare below, for different cases, the "same" code in Java and C++, to have an idea of which kind of coding style is clearer.</p>\n<h3>Natural comparisons:</h3>\n<pre><code>// C++ comparison for built-ins and user-defined types\nbool isEqual = A == B ;\nbool isNotEqual = A != B ;\nbool isLesser = A < B ;\nbool isLesserOrEqual = A <= B ;\n\n// Java comparison for user-defined types\nboolean isEqual = A.equals(B) ;\nboolean isNotEqual = ! A.equals(B) ;\nboolean isLesser = A.comparesTo(B) < 0 ;\nboolean isLesserOrEqual = A.comparesTo(B) <= 0 ;\n</code></pre>\n<p>Please note that A and B could be of any type in C++, as long as the operator overloads are provided. In Java, when A and B are not primitives, the code can become very confusing, even for primitive-like objects (BigInteger, etc.)...</p>\n<h3>Natural array/container accessors and subscripting:</h3>\n<pre><code>// C++ container accessors, more natural\nvalue = myArray[25] ; // subscript operator\nvalue = myVector[25] ; // subscript operator\nvalue = myString[25] ; // subscript operator\nvalue = myMap["25"] ; // subscript operator\nmyArray[25] = value ; // subscript operator\nmyVector[25] = value ; // subscript operator\nmyString[25] = value ; // subscript operator\nmyMap["25"] = value ; // subscript operator\n\n// Java container accessors, each one has its special notation\nvalue = myArray[25] ; // subscript operator\nvalue = myVector.get(25) ; // method get\nvalue = myString.charAt(25) ; // method charAt\nvalue = myMap.get("25") ; // method get\nmyArray[25] = value ; // subscript operator\nmyVector.set(25, value) ; // method set\nmyMap.put("25", value) ; // method put\n</code></pre>\n<p>In Java, we see that for each container to do the same thing (access its content through an index or identifier), we have a different way to do it, which is confusing.</p>\n<p>In C++, each container uses the same way to access its content, thanks to operator overloading.</p>\n<h3>Natural advanced types manipulation</h3>\n<p>The examples below use a <code>Matrix</code> object, found using the first links found on Google for "<a href="https://encrypted.google.com/search?q=Java+Matrix+object" rel="noreferrer">Java Matrix object</a>" and "<a href="https://encrypted.google.com/search?q=c%2B%2B+Matrix+object" rel="noreferrer">C++ Matrix object</a>":</p>\n<pre><code>// C++ YMatrix matrix implementation on CodeProject\n// http://www.codeproject.com/KB/architecture/ymatrix.aspx\n// A, B, C, D, E, F are Matrix objects;\nE = A * (B / 2) ;\nE += (A - B) * (C + D) ;\nF = E ; // deep copy of the matrix\n\n// Java JAMA matrix implementation (seriously...)\n// http://math.nist.gov/javanumerics/jama/doc/\n// A, B, C, D, E, F are Matrix objects;\nE = A.times(B.times(0.5)) ;\nE.plusEquals(A.minus(B).times(C.plus(D))) ;\nF = E.copy() ; // deep copy of the matrix\n</code></pre>\n<p>And this is not limited to matrices. The <code>BigInteger</code> and <code>BigDecimal</code> classes of Java suffer from the same confusing verbosity, whereas their equivalents in C++ are as clear as built-in types.</p>\n<h3>Natural iterators:</h3>\n<pre><code>// C++ Random Access iterators\n++it ; // move to the next item\n--it ; // move to the previous item\nit += 5 ; // move to the next 5th item (random access)\nvalue = *it ; // gets the value of the current item\n*it = 3.1415 ; // sets the value 3.1415 to the current item\n(*it).foo() ; // call method foo() of the current item\n\n// Java ListIterator<E> "bi-directional" iterators\nvalue = it.next() ; // move to the next item & return the value\nvalue = it.previous() ; // move to the previous item & return the value\nit.set(3.1415) ; // sets the value 3.1415 to the current item\n</code></pre>\n<h3>Natural functors:</h3>\n<pre><code>// C++ Functors\nmyFunctorObject("Hello World", 42) ;\n\n// Java Functors ???\nmyFunctorObject.execute("Hello World", 42) ;\n</code></pre>\n<h3>Text concatenation:</h3>\n<pre><code>// C++ stream handling (with the << operator)\n stringStream << "Hello " << 25 << " World" ;\n fileStream << "Hello " << 25 << " World" ;\n outputStream << "Hello " << 25 << " World" ;\n networkStream << "Hello " << 25 << " World" ;\nanythingThatOverloadsShiftOperator << "Hello " << 25 << " World" ;\n\n// Java concatenation\nmyStringBuffer.append("Hello ").append(25).append(" World") ;\n</code></pre>\n<p>Ok, in Java you can use <code>MyString = "Hello " + 25 + " World" ;</code> too... But, wait a second: This is operator overloading, isn\'t it? Isn\'t it cheating???</p>\n<p>:-D</p>\n<h2>Generic code?</h2>\n<p>The same generic code modifying operands should be usable both for built-ins/primitives (which have no interfaces in Java), standard objects (which could not have the right interface), and user-defined objects.</p>\n<p>For example, calculating the average value of two values of arbitrary types:</p>\n<pre><code>// C++ primitive/advanced types\ntemplate<typename T>\nT getAverage(const T & p_lhs, const T & p_rhs)\n{\n return (p_lhs + p_rhs) / 2 ;\n}\n\nint intValue = getAverage(25, 42) ;\ndouble doubleValue = getAverage(25.25, 42.42) ;\ncomplex complexValue = getAverage(cA, cB) ; // cA, cB are complex\nMatrix matrixValue = getAverage(mA, mB) ; // mA, mB are Matrix\n\n// Java primitive/advanced types\n// It won\'t really work in Java, even with generics. Sorry.\n</code></pre>\n<h1>Discussing operator overloading</h1>\n<p>Now that we have seen fair comparisons between C++ code using operator overloading, and the same code in Java, we can now discuss "operator overloading" as a concept.</p>\n<h2>Operator overloading existed since before computers</h2>\n<p><b>Even outside of computer science, there is operator overloading: For example, in mathematics, operators like <code>+</code>, <code>-</code>, <code>*</code>, etc. are overloaded.</b></p>\n<p>Indeed, the signification of <code>+</code>, <code>-</code>, <code>*</code>, etc. changes depending on the types of the operands (numerics, vectors, quantum wave functions, matrices, etc.).</p>\n<p>Most of us, as part of our science courses, learned multiple significations for operators, depending on the types of the operands. Did we find them confusing, then?</p>\n<h2>Operator overloading depends on its operands</h2>\n<p>This is the most important part of operator overloading: Like in mathematics, or in physics, the operation depends on its operands\' types.</p>\n<p>So, know the type of the operand, and you will know the effect of the operation.</p>\n<h2>Even C and Java have (hard-coded) operator overloading</h2>\n<p>In C, the real behavior of an operator will change according to its operands. For example, adding two integers is different than adding two doubles, or even one integer and one double. There is even the whole pointer arithmetic domain (without casting, you can add to a pointer an integer, but you cannot add two pointers...).</p>\n<p>In Java, there is no pointer arithmetic, but someone still found string concatenation without the <code>+</code> operator would be ridiculous enough to justify an exception in the "operator overloading is evil" creed.</p>\n<p>It\'s just that you, as a C (for historical reasons) or Java (for <i>personal reasons</i>, see below) coder, you can\'t provide your own.</p>\n<h2>In C++, operator overloading is not optional...</h2>\n<p>In C++, operator overloading for built-in types is not possible (and this is a good thing), but <i>user-defined</i> types can have <i>user-defined</i> operator overloads.</p>\n<p>As already said earlier, in C++, and to the contrary to Java, user-types are not considered second-class citizens of the language, when compared to built-in types. So, if built-in types have operators, user types should be able to have them, too.</p>\n<p>The truth is that, like the <code>toString()</code>, <code>clone()</code>, <code>equals()</code> methods are for Java (<i>i.e. quasi-standard-like</i>), C++ operator overloading is so much part of C++ that it becomes as natural as the original C operators, or the before mentioned Java methods.</p>\n<p>Combined with template programming, operator overloading becomes a well known design pattern. In fact, you cannot go very far in STL without using overloaded operators, and overloading operators for your own class.</p>\n<h2>...but it should not be abused</h2>\n<p>Operator overloading should strive to respect the semantics of the operator. Do not subtract in a <code>+</code> operator (as in "do not subtract in a <code>add</code> function", or "return crap in a <code>clone</code> method").</p>\n<p>Cast overloading can be very dangerous because they can lead to ambiguities. So they should really be reserved for well defined cases. As for <code>&&</code> and <code>||</code>, do not ever overload them unless you really know what you\'re doing, as you\'ll lose the the short circuit evaluation that the native operators <code>&&</code> and <code>||</code> enjoy.</p>\n<h1>So... Ok... Then why it is not possible in Java?</h1>\n<p>Because James Gosling said so:</p>\n<blockquote>\n<p>I left out operator overloading as a <b>fairly personal choice</b> because I had seen too many people abuse it in C++.</p>\n<p><i>James Gosling. Source: <a href="http://www.gotw.ca/publications/c_family_interview.htm" rel="noreferrer">http://www.gotw.ca/publications/c_family_interview.htm</a></i></p>\n</blockquote>\n<p>Please compare Gosling\'s text above with Stroustrup\'s below:</p>\n<blockquote>\n<p>Many C++ design decisions have their roots in my dislike for forcing people to do things in some particular way [...] Often, I was tempted to outlaw a feature I personally disliked, I refrained from doing so because <b>I did not think I had the right to force my views on others</b>.</p>\n<p><i>Bjarne Stroustrup. Source: The Design and Evolution of C++ (1.3 General Background)</i></p>\n</blockquote>\n<h2>Would operator overloading benefit Java?</h2>\n<p>Some objects would greatly benefit from operator overloading (concrete or numerical types, like BigDecimal, complex numbers, matrices, containers, iterators, comparators, parsers etc.).</p>\n<p>In C++, you can profit from this benefit because of Stroustrup\'s humility. In Java, you\'re simply screwed because of Gosling\'s <i>personal choice</i>.</p>\n<h2>Could it be added to Java?</h2>\n<p>The reasons for not adding operator overloading now in Java could be a mix of internal politics, allergy to the feature, distrust of developers (you know, the saboteur ones that seem to haunt Java teams...), compatibility with the previous JVMs, time to write a correct specification, etc..</p>\n<p>So don\'t hold your breath waiting for this feature...</p>\n<h2>But they do it in C#!!!</h2>\n<p>Yeah...</p>\n<p>While this is far from being the only difference between the two languages, this one never fails to amuse me.</p>\n<p>Apparently, the C# folks, with their <i>"every primitive is a <code>struct</code>, and a <code>struct</code> derives from Object"</i>, got it right at first try.</p>\n<h2>And they do it in <a href="https://en.wikipedia.org/wiki/Operator_overloading" rel="noreferrer">other languages</a>!!!</h2>\n<p>Despite all the FUD against used defined operator overloading, the following languages support it: <a href="https://kotlinlang.org/docs/reference/operator-overloading.html" rel="noreferrer">Kotlin</a>, <a href="https://stackoverflow.com/q/1991240">Scala</a>, <a href="https://www.dartlang.org/articles/idiomatic-dart/#operators" rel="noreferrer">Dart</a>, <a href="https://docs.python.org/3/reference/datamodel.html#special-method-names" rel="noreferrer">Python</a>, <a href="https://msdn.microsoft.com/en-us/library/dd233204.aspx" rel="noreferrer">F#</a>, <a href="https://msdn.microsoft.com/en-us/library/aa288467.aspx" rel="noreferrer">C#</a>, <a href="http://dlang.org/operatoroverloading.html" rel="noreferrer">D</a>, <a href="http://www.cap-lore.com/Languages/A68Ops.html" rel="noreferrer">Algol 68</a>, <a href="http://logos.cs.uic.edu/476/resources/SmallTalk/cs476_Smalltalk/Smalltalk.htm" rel="noreferrer">Smalltalk</a>, <a href="http://www.groovy-lang.org/operators.html#Operator-Overloading" rel="noreferrer">Groovy</a>, <a href="https://design.raku.org/S06.html#Operator_overloading" rel="noreferrer">Raku (formerly Perl 6)</a>, C++, <a href="https://stackoverflow.com/a/3331974">Ruby</a>, <a href="https://stackoverflow.com/questions/16241556">Haskell</a>, <a href="https://fr.mathworks.com/help/matlab/matlab_oop/implementing-operators-for-your-class.html" rel="noreferrer">MATLAB</a>, <a href="http://se.ethz.ch/~meyer/publications/online/eiffel/basic.html" rel="noreferrer">Eiffel</a>, <a href="http://lua-users.org/wiki/MetamethodsTutorial" rel="noreferrer">Lua</a>, <a href="https://stackoverflow.com/a/1535235">Clojure</a>, <a href="http://research.physics.illinois.edu/ElectronicStructure/498-s97/comp_info/overload.html" rel="noreferrer">Fortran 90</a>, <a href="https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AdvancedOperators.html#//apple_ref/doc/uid/TP40014097-CH27-ID42" rel="noreferrer">Swift</a>, <a href="http://archive.adaic.com/standards/83lrm/html/lrm-06-07.html" rel="noreferrer">Ada</a>, <a href="http://edn.embarcadero.com/article/34324" rel="noreferrer">Delphi 2005</a>...</p>\n<p>So many languages, with so many different (and sometimes opposing) philosophies, and yet they all agree on that point.</p>\n<p>Food for thought...</p>\n'}, {'answer_id': 1413443, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>Saying that operator overloading leads to logical errors of type that operator does not match the operation logic, it\'s like saying nothing. The same type of error will occur if function name is inappropriate for operation logic - so what\'s the solution: drop the ability of function usage!? \n This is a comical answer - "Inappropriate for operation logic", every parameter name, every class, function or whatever can be logicly inappropriate.\nI think that this option should be available in respectable programing language, and those that think that it\'s unsafe - hey no bothy says you have to use it. \nLets take the C#. They drooped the pointers but hey - there is \'unsafe code\' statement - program as you like on your own risk.</p>\n'}, {'answer_id': 2504988, 'author': 'Volksman', 'author_id': 257364, 'author_profile': 'https://Stackoverflow.com/users/257364', 'pm_score': 3, 'selected': False, 'text': '<p>Some people say that operator overloading in Java would lead to obsfuscation. Have those people ever stopped to look at some Java code doing some basic maths like increasing a financial value by a percentage using BigDecimal ? .... the verbosity of such an exercise becomes its own demonstration of obsfuscation. Ironically, adding operator overloading to Java would allow us to create our own Currency class which would make such mathematical code elegant and simple (less obsfuscated).</p>\n'}, {'answer_id': 8251451, 'author': 'Olai', 'author_id': 1063075, 'author_profile': 'https://Stackoverflow.com/users/1063075', 'pm_score': 3, 'selected': False, 'text': "<p>Technically, there is operator overloading in every programming language that can deal with different types of numbers, e.g. integer and real numbers. Explanation: The term overloading means that there are simply several implementations for one function. In most programming languages different implementations are provided for the operator +, one for integers, one for reals, this is called operator overloading.</p>\n\n<p>Now, many people find it strange that Java has operator overloading for the operator + for adding strings together, and from a mathematical standpoint this would be strange indeed, but seen from a programming language's developer's standpoint, there is nothing wrong with adding builtin operator overloading for the operator + for other classes e.g. String. However, most people agree that once you add builtin overloading for + for String, then it is generally a good idea to provide this functionality for the developer as well.</p>\n\n<p>A completely disagree with the fallacy that operator overloading obfuscates code, as this is left for the developer to decide. This is naïve to think, and to be quite honest, it is getting old.</p>\n\n<p>+1 for adding operator overloading in Java 8.</p>\n"}, {'answer_id': 48502000, 'author': 'Sarien', 'author_id': 1994377, 'author_profile': 'https://Stackoverflow.com/users/1994377', 'pm_score': 1, 'selected': False, 'text': '<p>This is not a good reason to disallow it but a practical one:</p>\n\n<p>People do not always use it responsibly. Look at this example from the Python library scapy:</p>\n\n<pre><code>>>> IP()\n<IP |>\n>>> IP()/TCP()\n<IP frag=0 proto=TCP |<TCP |>>\n>>> Ether()/IP()/TCP()\n<Ether type=0x800 |<IP frag=0 proto=TCP |<TCP |>>>\n>>> IP()/TCP()/"GET / HTTP/1.0\\r\\n\\r\\n"\n<IP frag=0 proto=TCP |<TCP |<Raw load=\'GET / HTTP/1.0\\r\\n\\r\\n\' |>>>\n>>> Ether()/IP()/IP()/UDP()\n<Ether type=0x800 |<IP frag=0 proto=IP |<IP frag=0 proto=UDP |<UDP |>>>>\n>>> IP(proto=55)/TCP()\n<IP frag=0 proto=55 |<TCP |>>\n</code></pre>\n\n<p>Here is the explanation:</p>\n\n<blockquote>\n <p>The / operator has been used as a composition operator between two\n layers. When doing so, the lower layer can have one or more of its\n defaults fields overloaded according to the upper layer. (You still\n can give the value you want). A string can be used as a raw layer.</p>\n</blockquote>\n'}, {'answer_id': 51715550, 'author': 'gagarwa', 'author_id': 3862024, 'author_profile': 'https://Stackoverflow.com/users/3862024', 'pm_score': 2, 'selected': False, 'text': '<p><strong>Alternatives to Native Support of Java Operator Overloading</strong></p>\n<p>Since Java doesn\'t have operator overloading, here are some alternatives you can look into:</p>\n<ol>\n<li>Use another language. <a href="https://en.wikipedia.org/wiki/Apache_Groovy" rel="nofollow noreferrer">Groovy</a>, <a href="https://en.wikipedia.org/wiki/Scala_(programming_language)" rel="nofollow noreferrer">Scala</a>, and Kotlin have operator overloading, and are based on Java.</li>\n<li>Use <a href="https://github.com/amelentev/java-oo" rel="nofollow noreferrer">java-oo</a>, a plugin that enables operator overloading in Java. Note that it is NOT platform independent. Also, it has many issues, and is not compatible with the latest releases of Java (i.e. Java 10). (<a href="https://stackoverflow.com/questions/1686699/operator-overloading-in-java/1686714">Original StackOverflow Source</a>)</li>\n<li>Use <a href="https://en.wikipedia.org/wiki/Java_Native_Interface" rel="nofollow noreferrer">JNI</a>, Java Native Interface, or alternatives. This allows you to write C or C++ methods for use in Java. Of course this is also NOT platform independent.</li>\n</ol>\n<p>If anyone is aware of others, please comment, and I will add it to this list.</p>\n'}, {'answer_id': 64889038, 'author': 'Audrius Meškauskas', 'author_id': 1439305, 'author_profile': 'https://Stackoverflow.com/users/1439305', 'pm_score': 1, 'selected': False, 'text': '<p>I think that people making decisions simply forgot about complex values, matrix algebra, set theory and other cases when overloading would allow to use the standard notation without building everything into the language. Anyway, only mathematically oriented software really benefits from such features. A generic customer application almost never needs them.</p>\n<p>They arguments about the unnecessary obfuscation are obviously valid when a programmer defines some program-specific operator where it could be the function instead. A name of the function, when clearly visible, provides the hint that it does. Operator is a function without the readable name.</p>\n<p>Java is generally designed about philosophy that some extra verbosity is not bad as it makes the code more readable. Constructs that do the same just have less code to type in used to be called a "syntax sugar" in the past. This is very different from the Python philosophy, for instance, where shorter is near always seen as better, even if providing less context for the second reader.</p>\n'}, {'answer_id': 72372699, 'author': 'saditya', 'author_id': 14769639, 'author_profile': 'https://Stackoverflow.com/users/14769639', 'pm_score': 0, 'selected': False, 'text': "<p>Java doesn't permit operator overloading because its creator didn't add the functionality to associate different meanings with the same operator. <strong>They just wanted to keep things simple</strong> by just retaining the meaning of an operator uniform throughout the programming language.</p>\n<p>Overloading the operators makes things messy and creates a steep learning curve for new programmers. So, they just kept <strong>operator overloading</strong> out of the syllabus.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77718', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
77,726 | <p>I really like Xml for saving data, but when does sqlite/database become the better option? eg, when the xml has more than <em>x</em> items or is greater than <em>y</em> MB?</p>
<p>I am coding an rss reader and I believe I made the wrong choice in using xml over a sqlite database to store a cache of <em>all</em> the feeds items. There are some feeds which have an xml file of ~1mb after a month, another has over 700 items, while most only have ~30 items and are ~50kb in size after a <em>several</em> months. </p>
<p>I currently have no plans to implement a cap because I like to be able to search through everything.</p>
<p>So, my questions are:</p>
<ol>
<li>When is the overhead of sqlite/databases justified over using xml?</li>
<li>Are the <strong>few large xml files</strong> justification enough for the database when there are <strong>a lot of small</strong> ones, though even the small ones will grow over time? (a long <em>long</em> time)</li>
</ol>
<p><strong>updated</strong> (more info)</p>
<p>Every time a feed is selected in the GUI I reload all the items from that feeds xml file.</p>
<p>I also need to modify the read/unread status which seems really hacky when I loop through all nodes in the xml to find the item and then set it to read/unread.</p>
| [{'answer_id': 77750, 'author': 'Mitchel Sellers', 'author_id': 13279, 'author_profile': 'https://Stackoverflow.com/users/13279', 'pm_score': 2, 'selected': False, 'text': '<p>To me it really depends on what you are doing with them, how many users/processes need access to them at the same time etc.</p>\n\n<p>I work with large XML files all the time, but they are single process, import style items, that multi-user, or performance are not really needs.</p>\n\n<p>SO really it is a balance.</p>\n'}, {'answer_id': 77773, 'author': 'Sebastian Redl', 'author_id': 8922, 'author_profile': 'https://Stackoverflow.com/users/8922', 'pm_score': 0, 'selected': False, 'text': "<p>I say it's not a matter of data size, but of data type. If your data is <em>structured</em>, use a relational database. If your data is <em>semi-structured</em>, use XML or - if the data amounts really grow too large - an XML database.</p>\n"}, {'answer_id': 77777, 'author': 'typicalrunt', 'author_id': 13996, 'author_profile': 'https://Stackoverflow.com/users/13996', 'pm_score': 3, 'selected': False, 'text': "<p>I wouldn't use XML for storing RSS items. A feed reader makes constant updates as it receives data.</p>\n\n<p>With XML, you need to load the data from file first, parse it, then store it for easy search/retrieval/update. Sounds like a database...</p>\n\n<p>Also, what happens if your application crashes? if you use XML, what state is the data in the XML file versus the data in memory. At least with SQLite you get atomicity, so you are assured that your application will start with the same state as when the last database write was made.</p>\n"}, {'answer_id': 77778, 'author': 'Bradley Harris', 'author_id': 10503, 'author_profile': 'https://Stackoverflow.com/users/10503', 'pm_score': 3, 'selected': False, 'text': '<p>XML is best used as an interchange format when you need to move data from your application to somewhere else or share information between applications. A database should be the preferred method of storage for almost any size application. </p>\n'}, {'answer_id': 77812, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>If your searching go with a db. You could split the xml files up into directories to ease seeking, but the managerial overhead easily gets quite heavy. You also get a lot more than just performance with a sql db... </p>\n'}, {'answer_id': 77837, 'author': 'apenwarr', 'author_id': 42219, 'author_profile': 'https://Stackoverflow.com/users/42219', 'pm_score': 1, 'selected': False, 'text': '<p>I agree with @Bradley.</p>\n\n<p>XML is very slow and not particularly useful as a storage format. Why bother? Will you be editing the data by hand using a text editor? If so, XML <em>still</em> isn\'t a very convenient format compared to something like YAML. With something like SQlite, queries are easier to write, and there\'s a well defined API for getting your data in and out.</p>\n\n<p>XML is fine if you need to send data around between programs. But in the name of efficiency, you should probably produce the XML at sending time, and parse it into "real data" at receive time.</p>\n\n<p>All the above means that your question about "when the overhead of a database is justified" is kind of moot. XML has a way higher overhead, all the time, than SQlite does. (Full-on databases like MSSQL are heavier, especially in administrative overhead, but that\'s a totally different question.)</p>\n'}, {'answer_id': 77897, 'author': 'Vin', 'author_id': 1747, 'author_profile': 'https://Stackoverflow.com/users/1747', 'pm_score': 3, 'selected': False, 'text': '<ol>\n<li>Use XML for data that the\napplication should know -\nconfiguration, logging and what not.</li>\n<li>Use databases(oracle, SQL server etc) for data that the user\ninteracts with directly or\nindirectly - real data</li>\n<li>Use SQLite if the user data is more\nof a serialized collection - like\nhuge list of files and their content\nor collection of email items etc.\nSQLite is good at that.</li>\n</ol>\n\n<p>Depends on the kind and the size of the data.</p>\n'}, {'answer_id': 77903, 'author': 'Mostlyharmless', 'author_id': 12881, 'author_profile': 'https://Stackoverflow.com/users/12881', 'pm_score': 2, 'selected': False, 'text': '<p>If any time you will need to scale, use databases.</p>\n'}, {'answer_id': 77912, 'author': 'Oli', 'author_id': 12870, 'author_profile': 'https://Stackoverflow.com/users/12870', 'pm_score': 4, 'selected': False, 'text': "<p>Don't forget that you have a great database at your fingertips: the filesystem!</p>\n\n<p>Lots of programmers forget that a decent directory-file structure is/has:</p>\n\n<ol>\n<li>It's fast as hell</li>\n<li>It's portable</li>\n<li>It has a tiny runtime footprint</li>\n</ol>\n\n<p>People are talking about splitting up XML files into multiple XML files... I would consider splitting your XML into multiple directories and multiple plaintext files. </p>\n\n<p>Give it a go. It's refreshingly fast.</p>\n"}, {'answer_id': 78026, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>XML is good for storing data which is not completely structured and you typically want to exchange it with another application. I prefer to use a SQL database for data. XML is error prone as you can cause subtle errors due to typos or ommissions in the data itself. Some open source application frameworks use too many xml files for configuration, data, etc. I prefer to have it in SQL.</p>\n\n<p>Since you ask for a rule of thumb, I would say that use XML based application data, configuration, etc if you are going to set it up once and not access/search it much. For active searches and updations, its best to go with SQL.</p>\n\n<p>For example, a web server stores application data in a XML file and you dont really need to perform complex search, update the file. The web server starts, reads the xml file and thats that. So XML is perfect here. Suppose you use a framework like Struts. You need to use XML and the action configurations dont change much once the application is developed and deployed. So again, the XML file is a good way. Now if your Struts developed application allows extensive searches and updations, deletions, then SQL is the optimal way.</p>\n\n<p>Offcourse, you will surely meet one or two developers in your organisation who will chant XML or SQL only and proclaim XML or SQL as the only way to go. Beware of such folks and do what 'feels' right for your application. Dont just follow a 'technology religion'.</p>\n\n<p>Think of things like how often you need to update the data, how often you need to search the data. Then you will have your answer on what to use - XML or SQL. </p>\n"}, {'answer_id': 78040, 'author': 'Stan', 'author_id': 14091, 'author_profile': 'https://Stackoverflow.com/users/14091', 'pm_score': 6, 'selected': True, 'text': '<p>I basically agree with <a href="https://stackoverflow.com/questions/77726/xml-or-sqlite-when-to-drop-xml-for-a-database#77750">Mitchel</a>, that this can be highly specific depending on what are you going to do with XML and SQLite. For your case (cache), it seems to me that using SQLite (or other embedded databases) makes more sense.</p>\n<p>First I don\'t really think that SQLite will need more overhead than XML. And I mean both development time overhead and runtime overhead. Only problem is that you have a dependence on SQLite library. But since you would need some library for XML anyway it doesn\'t matter (I assume project is in C/C++).</p>\n<p><strong>Advantages of SQLite over XML:</strong></p>\n<ul>\n<li>everything in one file,</li>\n<li>performance loss is lower than XML as cache gets bigger,</li>\n<li>you can keep feed metadata separate from cache itself (other table), but accessible in the same way,</li>\n<li>SQL is probably easier to work with than XPath for most people.</li>\n</ul>\n<p><strong>Disadvantages of SQLite:</strong></p>\n<ul>\n<li>can be problematic with multiple processes accessing same database (probably not your case),</li>\n<li>you should know at least basic SQL. Unless there will be hundreds of thousands of items in cache, I don\'t think you will need to optimize it much,</li>\n<li>maybe in some way it can be more dangerous from security standpoint (SQL injection). On the other hand, you are not coding web app, so this should not happen.</li>\n</ul>\n<p>Other things are on par for both solutions probably.</p>\n<p>To sum it up, answers to your questions respectively:</p>\n<ol>\n<li><p>You will not know, unless you test your specific application with both back ends. Otherwise it\'s always just a guess. Basic support for both caches should not be a problem to code. Then benchmark and compare.</p>\n</li>\n<li><p>Because of the way XML files are organized, SQLite searches should always be faster (barring some corner cases where it doesn\'t matter anyway because it\'s blazingly fast). Speeding up searches in XML would require index database anyway, in your case that would mean having cache for cache, not a particularly good idea. But with SQLite you can have indexing as part of database.</p>\n</li>\n</ol>\n'}, {'answer_id': 78146, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>XML can be stored as text and as a binary file format. </p>\n\n<p>If your primary goal is to let a computer read / write a file format effeciently you should work with a binary file format. </p>\n\n<p>Databases are an easy to use way of storing and maintaining data. \nThey are not the fastest way to store data that is a binary file format. </p>\n\n<p>What can speed things up is using an in memory database / database type. Sqlite has this option. </p>\n\n<p>And this sounds like the best way to do it for you. </p>\n'}, {'answer_id': 78149, 'author': 'Jay Stramel', 'author_id': 3547, 'author_profile': 'https://Stackoverflow.com/users/3547', 'pm_score': 1, 'selected': False, 'text': "<p>My opinion is that you should use SQLite (or another appropriate embedded database) anytime you don't need a pure-text file format. Note, this is a pretty big exception. There are a lot of scenarios that require, or are benefited by, pure-text file formats.</p>\n\n<p>As far as overhead goes, SQLite compiles to something like 250 k with normal flags. Many XML parsing libraries are larger than SQLite. You get no concurrency gains using XML. The SQLite binary file format is going to support much more efficient writes (largely because you can't append to the end of a well-formatted XML file). And even reading data, most of which I assume is fairly random access, is going to be faster using SQLite.</p>\n\n<p>And to top it all off, you get access to the benefits of SQL like transactions and indexes.</p>\n\n<p>Edit: Forgot to mention. One benefit of SQLite (as opposed to many databases) is that it allows any type in any row in any column. Basically, with SQLite you get the same freedom you have with XML in terms of datatypes. This also means that you don't have to worry about putting limits on text columns.</p>\n"}, {'answer_id': 78871, 'author': 'David Medinets', 'author_id': 219658, 'author_profile': 'https://Stackoverflow.com/users/219658', 'pm_score': 3, 'selected': False, 'text': "<p>When should XML be used for data persistence instead of a database? Almost never. XML is a data transport language. It is slow to parse and awkward to query. Parse the XML (don't shred it!) and convert the resulting data into domain objects. Then persist the domain objects. A major advantage of a database for persistence is SQL which means unstructured queries and access to common tools and optimization techniques.</p>\n"}, {'answer_id': 78918, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': False, 'text': "<p>Man do I have experience with this. I work on a project where we originally stored all of our data using XML, then moved to SQLite. There are many pros and cons to each technology, but it was performance that caused the switchover. Here is what we observed.</p>\n<p>For small databases (a few meg or smaller), XML was much faster, and easier to deal with. Our data was naturally in a tree format, which made XML much more attractive, and XPath allowed us to do many queries in one simple line rather than having to walk down an ancestry tree.</p>\n<p>We were programming in a Win32 environment, and used the standard Microsoft DOM library. We would load all the data into memory, parse it into a DOM tree and search, add, modify on the in memory copy. We would periodically save the data, and needed to rotate copies in case the machine crashed in the middle of a write.</p>\n<p>We also needed to build up some "indexes" by hand using C++ tree maps. This, of course would be trivial to do with SQL.</p>\n<p>Note that the size of the data on the filesystem was a factor of 2-4 smaller than the "in memory" DOM tree.</p>\n<p>By the time the data got to 10M-100M size, we started to have real problems. Interestingly enough, at all data sizes, XML processing was much faster than SQLite turned out to be (because it was in memory, not on the hard drive)! The problem was actually twofold- first, loadup time really started to get long. We would need to wait a minute or so before the data was in memory and the maps were built. Of course once loaded the program was very fast. The second problem was that all of this memory was tied up all the time. Systems with only a few hundred meg would be unresponsive in other apps even though we ran very fast.</p>\n<p>We actually looking into using a filesystem based XML database. There are a couple open sourced versions XML databases, we tried them. I have never tried to use a commercial XML database, so I can't comment on them. Unfortunately, we could never get the XML databases to work well at all. Even the act of populating the database with hundreds of meg of XML took hours.... Perhaps we were using it incorrectly. Another problem was that these databases were pretty heavyweight. They required Java and had full client server architecture. We gave up on this idea.</p>\n<p>We found SQLite then. It solved our problems, but at a price. When we initially plugged SQLite in, the memory and load time problems were gone. Unfortunately, since all processing was now done on the harddrive, the background processing load went way up. While earlier we never even noticed the CPU load, now the processor usage was way up. We needed to optimize the code, and still needed to keep some data in memory. We also needed to rewrite many simple XPath queries as complicated multiquery algorithms.</p>\n<p>So here is a summary of what we learned.</p>\n<ol>\n<li><p>For tree data, XML is much easier to query and modify using XPath.</p>\n</li>\n<li><p>For small datasets (less than 10M), XML blew away SQLite in performance.</p>\n</li>\n<li><p>For large datasets (greater than 10M-100M), XML load time and memory usage became a big problem, to the point that some computers become unusable.</p>\n</li>\n<li><p>We couldn't get any opensource XML database to fix the problems associated with large datasets.</p>\n</li>\n<li><p>SQLite doesn't have the memory problems of XML DOM, but it is generally slower in processing the data (it is on the hard drive, not in memory). (note- SQLite tables can be stored in memory, perhaps this would make it as fast.... We didn't try this because we wanted to get the data out of memory.)</p>\n</li>\n<li><p>Storing and querying tree data in a table is not enjoyable. However, managing transactions and indexing partially makes up for it.</p>\n</li>\n</ol>\n"}, {'answer_id': 86688, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>You should note that many large Relational DBs (Oracle and SQLServer) have XML datatypes to store data within a database and use XPath within the SQL statement to gain access to that data.</p>\n\n<p>Also, there are native XML databases which work very much like SQLite in the sense they are one binary file holding a collection of documents (which could roughly be a table) then you can either XPath/XQuery on a single document or the whole collection. So with an XML database you can do things like store the days data as a separate XML document in the collection... so you just need to use that one document when your dealing with the data for today. But write an XQuery to figure out historical data on the collection of documents for that person. Slick.</p>\n\n<p>I\'ve used Berkeley XMLDB (now backed by Oracle). There are others if you search google for "Native XML Database". I\'ve not seen a performance problem with storing/retrieving data in this manner. </p>\n\n<p>XQuery is a different beast (but well worth learning), however you may be able to just use the XPaths you currently use with slight modifications.</p>\n'}, {'answer_id': 86896, 'author': 'Martin Beckett', 'author_id': 10897, 'author_profile': 'https://Stackoverflow.com/users/10897', 'pm_score': 1, 'selected': False, 'text': "<p>A database is great as part of your program. If quering the data is part of your business logic.\nXML is best as a file format, especially if you data format is:</p>\n\n<p>1, Hierarchal <br>\n2, Likely to change in the future in ways you can't guess <br>\n3, The data is going to live longer than the program</p>\n"}, {'answer_id': 88358, 'author': 'sieben', 'author_id': 1147, 'author_profile': 'https://Stackoverflow.com/users/1147', 'pm_score': 3, 'selected': False, 'text': "<p>I have made the switch to SQLite and I feel <em>much</em> better knowing it's in a database. </p>\n\n<p>There are a lot of other benefits from this: </p>\n\n<ul>\n<li>Adding new items is really simple</li>\n<li>Sorting by multiple columns</li>\n<li>Removing duplicates with a unique index</li>\n</ul>\n\n<p>I've created 2 views, one for unread items and one for all items, not sure if this is the best use of views, but I really wanted to try using them.</p>\n\n<p>I also benchmarked the xml vs sqlite using the <strong>StopWatch</strong> class, and the sqlite is faster, <strong>although it could just be that my way of parsing xml files wasn't the fastest method</strong>.</p>\n\n<ol>\n<li><strong>Small # items and size (25 items, 30kb)</strong>\n\n<ul>\n<li>~1.5 ms sqlite</li>\n<li>~8.0 ms xml</li>\n</ul></li>\n<li><strong>Large # of items (700 items, 350kb)</strong>\n\n<ul>\n<li>~20 ms sqlite</li>\n<li>~25 ms xml</li>\n</ul></li>\n<li><strong>Large file size (850 items, 1024kb)</strong>\n\n<ul>\n<li>~45 ms sqlite</li>\n<li>~60 ms xml</li>\n</ul></li>\n</ol>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77726', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1147/'] |
77,731 | <p>At my current gig, we use iBATIS through Java to CRUD our databases. I like the abstract qualities of the tool, especially when working with legacy databases, as it doesn't impose its own syntax on you.</p>
<p><strong>I'm looking for a Python analogue to this library</strong>, since the website only has Java/.NET/Ruby versions available. I don't want to have to switch to Jython if I don't need to.</p>
<p>Are there any other projects similar to iBATIS functionality out there for Python?</p>
| [{'answer_id': 77859, 'author': 'Yann Ramin', 'author_id': 9167, 'author_profile': 'https://Stackoverflow.com/users/9167', 'pm_score': 1, 'selected': False, 'text': '<p>Perhaps SQLAlchemy SQL Expression support is suitable. See the <a href="http://docs.sqlalchemy.org/en/latest/core/expression_api.html" rel="nofollow noreferrer">documentation</a>. </p>\n'}, {'answer_id': 78147, 'author': 'S.Lott', 'author_id': 10661, 'author_profile': 'https://Stackoverflow.com/users/10661', 'pm_score': 4, 'selected': True, 'text': '<p>iBatis sequesters the SQL DML (or the definitions of the SQL) in an XML file. It specifically focuses on the mapping between the SQL and some object model defined elsewhere.</p>\n\n<p>SQL Alchemy can do this -- but it isn\'t really a very complete solution. Like iBatis, you can merely have SQL table definitions and a mapping between the tables and Python class definitions. </p>\n\n<p>What\'s more complete is to have a class definition that is <em>also</em> the SQL database definition. If the class definition generates the SQL Table DDL as well as the query and processing DML, that\'s much more complete. </p>\n\n<p>I flip-flop between SQLAlchemy and the Django ORM. SQLAlchemy can be used in an iBatis like manner. But I prefer to make the object design central and leave the SQL implementation be derived from the objects by the toolset.</p>\n\n<p>I use SQLAlchemy for large, batch, stand-alone projects. DB Loads, schema conversions, DW reporting and the like work out well. In these projects, the focus is on the relational view of the data, not the object model. The SQL that\'s generated may be moved into PL/SQL stored procedures, for example.</p>\n\n<p>I use Django for web applications, exploiting its built-in ORM capabilities. You can, with a little work, segregate the Django ORM from the rest of the Django environment. You can <a href="http://docs.djangoproject.com/en/dev/topics/settings/#using-settings-without-setting-django-settings-module" rel="noreferrer">provide global settings</a> to bind your app to a specific database without using a separate settings module.</p>\n\n<p>Django includes a number of common relationships (Foreign Key, Many-to-Many, One-to-One) for which it can manage the SQL implementation. It generates key and index definitions for the attached database.</p>\n\n<p>If your problem is largely object-oriented, with the database being used for persistence, then the nearly transparent ORM layer of Django has advantages.</p>\n\n<p>If your problem is largely relational, with the SQL processing central, then the capability of seeing the generated SQL in SQLAlchemy has advantages.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77731', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13996/'] |
77,744 | <p>I have a command line program, which outputs logging to the screen.</p>
<p>I want error lines to show up in red. Is there some special character codes I can output to switch the text color to red, then switch it back to white?</p>
<p>I'm using ruby but I imagine this would be the same in any other language.</p>
<p>Something like:</p>
<pre><code>red = "\0123" # character code
white = "\0223"
print "#{red} ERROR: IT BROKE #{white}"
print "other stuff"
</code></pre>
| [{'answer_id': 77795, 'author': 'Mitchel Sellers', 'author_id': 13279, 'author_profile': 'https://Stackoverflow.com/users/13279', 'pm_score': 0, 'selected': False, 'text': '<p>As far as I know it is not possible with a command line, it is just one color...</p>\n'}, {'answer_id': 77803, 'author': 'betelgeuce', 'author_id': 366182, 'author_profile': 'https://Stackoverflow.com/users/366182', 'pm_score': 0, 'selected': False, 'text': '<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace Console_Test\n{\n class Program\n {\n static void Main(string[] args)\n {\n Console.ForegroundColor = ConsoleColor.DarkRed;\n Console.WriteLine("Hello World");\n Console.ReadKey();\n }\n }\n}\n</code></pre>\n\n<p>You can change the color using a simple C# program, <a href="http://powerof2games.com/node/31" rel="nofollow noreferrer">http://powerof2games.com/node/31</a> describes how you can wrap console output to achieve the effect.</p>\n'}, {'answer_id': 77805, 'author': 'Adam Rosenfield', 'author_id': 9530, 'author_profile': 'https://Stackoverflow.com/users/9530', 'pm_score': 0, 'selected': False, 'text': '<p>You want <a href="http://en.wikipedia.org/wiki/ANSI_escape_code" rel="nofollow noreferrer">ANSI escape codes</a>.</p>\n'}, {'answer_id': 77831, 'author': 'davenpcj', 'author_id': 4777, 'author_profile': 'https://Stackoverflow.com/users/4777', 'pm_score': 0, 'selected': False, 'text': '<p>A lot of the old ANSI <a href="http://pueblo.sourceforge.net/doc/manual/ansi_color_codes.html" rel="nofollow noreferrer">Color Codes</a> work. The code for a red foreground is something like Escape-[31m. Escape is character 27, so that\'s "\\033[31m" or "\\x1B[31m", depending on your escaping scheme.</p>\n\n<p>[39m is the code to return to default color.</p>\n\n<p>It\'s also possible to specify multiple codes at once to set foreground and background color simultaneously.</p>\n\n<p>You may have to load ANSI.sys, see <a href="http://academic.evergreen.edu/projects/biophysics/technotes/program/ansi_esc.htm#notes" rel="nofollow noreferrer">this page</a>.</p>\n'}, {'answer_id': 77861, 'author': 'artur02', 'author_id': 13937, 'author_profile': 'https://Stackoverflow.com/users/13937', 'pm_score': 2, 'selected': False, 'text': '<p>You can read here a good and illustrated article:\n<a href="http://kpumuk.info/ruby-on-rails/colorizing-console-ruby-script-output/" rel="nofollow noreferrer">http://kpumuk.info/ruby-on-rails/colorizing-console-ruby-script-output/</a></p>\n\n<p>I think setting console text color is pretty language-specific. Here is an example in C# from MSDN:</p>\n\n<pre><code>for (int x = 0; x < colorNames.Length; x++)\n{\n Console.Write("{0,2}: ", x);\n Console.BackgroundColor = ConsoleColor.Black;\n Console.ForegroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), colorNames[x]);\n Console.Write("This is foreground color {0}.", colorNames[x]);\n Console.ResetColor();\n Console.WriteLine();\n}\n</code></pre>\n\n<p><strong>Console.ForegroundColor</strong> is the property for setting text color.</p>\n'}, {'answer_id': 77867, 'author': 'Orion Adrian', 'author_id': 7756, 'author_profile': 'https://Stackoverflow.com/users/7756', 'pm_score': 0, 'selected': False, 'text': '<p>The standard C/C++ specification for outputting to the command line doesn\'t specify any capabilities for changing the color of the console window. That said, there are many functions in Win32 for doing such a thing.</p>\n<p>The easiest way to change the color of the Win32 console is through the system command in iostream.h. This function invokes a DOS command. To change colors, we will use it to invoke the color command. For example, <code>system("Color F1");</code> will make the console darkblue on white.</p>\n<p>DOS Colors</p>\n<p>The colors available for use with the command are the sixteen DOS colors each represented with a hex digit. The first being the background and the second being the foreground.</p>\n<pre><code>0 = Black 8 = Gray\n1 = Blue 9 = Light Blue\n2 = Green A = Light Green\n3 = Aqua B = Light Aqua\n4 = Red C = Light Red\n5 = Purple D = Light Purple\n6 = Yellow E = Light Yellow\n7 = White F = Bright White\n</code></pre>\n<p>Just this little touch of color makes console programs more visually pleasing. However, the Color command will change the color of the entire console. To control individual cells, we need to use functions from windows.h.</p>\n<p>Do do that you need to use the <code>SetConsoleAttribute</code> function</p>\n<p><a href="https://learn.microsoft.com/en-us/windows/console/setconsoletextattribute" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms686047.aspx</a></p>\n'}, {'answer_id': 77884, 'author': 'cjm', 'author_id': 8355, 'author_profile': 'https://Stackoverflow.com/users/8355', 'pm_score': 4, 'selected': True, 'text': '<p>You need to access the <a href="https://learn.microsoft.com/en-us/windows/console/console-functions" rel="nofollow noreferrer">Win32 Console API</a>. Unfortunately, I don\'t know how you\'d do that from Ruby. In Perl, I\'d use the <a href="http://search.cpan.org/perldoc?Win32::Console" rel="nofollow noreferrer">Win32::Console</a> module. The Windows console does not respond to ANSI escape codes.</p>\n<p>According to the <a href="http://kpumuk.info/ruby-on-rails/colorizing-console-ruby-script-output/" rel="nofollow noreferrer">article on colorizing Ruby output</a> that artur02 mentioned, you need to install & load the win32console gem.</p>\n'}, {'answer_id': 77904, 'author': 'Mike Dimmick', 'author_id': 6970, 'author_profile': 'https://Stackoverflow.com/users/6970', 'pm_score': 0, 'selected': False, 'text': '<p>Ultimately you need to call <a href="http://msdn.microsoft.com/en-us/library/ms686047.aspx" rel="nofollow noreferrer">SetConsoleTextAttribute</a>. You can get a console screen buffer handle from <a href="http://msdn.microsoft.com/en-us/library/ms683231(VS.85).aspx" rel="nofollow noreferrer">GetStdHandle</a>.</p>\n'}, {'answer_id': 77940, 'author': 'zaphod', 'author_id': 13871, 'author_profile': 'https://Stackoverflow.com/users/13871', 'pm_score': 2, 'selected': False, 'text': '<p>You could use an ANSI escape sequence, but that won\'t do what you want under modern versions of Windows. Wikipedia has a very informative article:</p>\n\n<p><a href="http://en.wikipedia.org/wiki/ANSI_escape_code" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/ANSI_escape_code</a></p>\n\n<p>So the answer to your original question is almost certainly "no." However, you can change the foreground color without writing an escape sequence, for example by invoking a Win32 API function. I don\'t know how to do this sort of thing in Ruby off the top of my head, but somebody else seems to have managed:</p>\n\n<p><a href="http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/241925" rel="nofollow noreferrer">http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/241925</a></p>\n\n<p>I imagine you\'d want to use 4 for dark red or 12 for bright red, and 7 to restore the default color.</p>\n\n<p>Hope this helps!</p>\n'}, {'answer_id': 77981, 'author': 'Orion Edwards', 'author_id': 234, 'author_profile': 'https://Stackoverflow.com/users/234', 'pm_score': 2, 'selected': False, 'text': "<p>on ANSI escape codes:</p>\n<blockquote>\n<p>32-bit character-mode (subsystem:console) Windows applications don't write ANSI escape sequences to the console</p>\n<p>They must interpret the escape code actions and call the native Console API instead</p>\n</blockquote>\n<p>Thanks microsoft :-(</p>\n"}, {'answer_id': 78002, 'author': 'Michael', 'author_id': 13379, 'author_profile': 'https://Stackoverflow.com/users/13379', 'pm_score': 2, 'selected': False, 'text': '<p><code>color [background][foreground]</code></p>\n\n<p>Where colors are defined as follows: </p>\n\n<pre><code>0 = Black 8 = Gray\n1 = Blue 9 = Light Blue\n2 = Green A = Light Green\n3 = Aqua B = Light Aqua\n4 = Red C = Light Red\n5 = Purple D = Light Purple\n6 = Yellow E = Light Yellow\n7 = White F = Bright White\n</code></pre>\n\n<p>For example, to change the background to blue and the foreground to gray, you would type:</p>\n\n<p><code>color 18</code></p>\n'}, {'answer_id': 78622, 'author': 'Mike Duncan', 'author_id': 14483, 'author_profile': 'https://Stackoverflow.com/users/14483', 'pm_score': 0, 'selected': False, 'text': "<p>I've been using a freeware windows tail program called baretail (google it) for ages that lets you do a windows-appified version of unix tail command. It lets you colorize lines dependent on whatever keywords you define. What's nice about it as a solution is its not tied to a specific language or setup, etc, you just define your color scheme and its on like donkey kong. In my personal top 10 freeware helpers!</p>\n"}, {'answer_id': 78741, 'author': 'manveru', 'author_id': 8367, 'author_profile': 'https://Stackoverflow.com/users/8367', 'pm_score': 5, 'selected': False, 'text': '<p>On windows, you can do it easily in three ways:</p>\n\n<pre><code>require \'win32console\'\nputs "\\e[31mHello, World!\\e[0m"\n</code></pre>\n\n<p>Now you could extend String with a small method called <code>red</code></p>\n\n<pre><code> require \'win32console\'\n class String\n def red\n "\\e[31m#{self}\\e[0m"\n end\n end\n\n puts "Hello, World!".red\n</code></pre>\n\n<p>Also you can extend String like this to get more colors:</p>\n\n<pre><code>require \'win32console\'\n\nclass String\n { :reset => 0,\n :bold => 1,\n :dark => 2,\n :underline => 4,\n :blink => 5,\n :negative => 7,\n :black => 30,\n :red => 31,\n :green => 32,\n :yellow => 33,\n :blue => 34,\n :magenta => 35,\n :cyan => 36,\n :white => 37,\n }.each do |key, value|\n define_method key do\n "\\e[#{value}m" + self + "\\e[0m"\n end\n end\nend\n\nputs "Hello, World!".red\n</code></pre>\n\n<p>Or, if you can install gems:</p>\n\n<pre><code>gem install term-ansicolor\n</code></pre>\n\n<p>And in your program:</p>\n\n<pre><code>require \'win32console\'\nrequire \'term/ansicolor\'\n\nclass String\n include Term::ANSIColor\nend\n\nputs "Hello, World!".red\nputs "Hello, World!".blue\nputs "Annoy me!".blink.yellow.bold\n</code></pre>\n\n<p>Please see the docs for term/ansicolor for more information and possible usage.</p>\n'}, {'answer_id': 31743032, 'author': 'Adam', 'author_id': 3254245, 'author_profile': 'https://Stackoverflow.com/users/3254245', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve authored a small cross-platform gem that handles this seamlessly running on Windows or POSIX-systems, under both MRI and JRuby.</p>\n\n<p>It has no dependencies, and uses ANSI codes on POSIX systems, and either FFI (JRuby) or Fiddler (MRI) for Windows.</p>\n\n<p>To use it, simply:</p>\n\n<pre><code>gem install color-console\n</code></pre>\n\n<p>ColorConsole provides methods for outputting lines of text in different colors, using the Console.write and Console.puts functions.</p>\n\n<pre><code>require \'color-console\'\n\nConsole.puts "Some text" # Outputs text using the current console colours\nConsole.puts "Some other text", :red # Outputs red text with the current background\nConsole.puts "Yet more text", nil, :blue # Outputs text using the current foreground and a blue background\n\n# The following lines output BlueRedGreen on a single line, each word in the appropriate color\nConsole.write "Blue ", :blue\nConsole.write "Red ", :red\nConsole.write "Green", :green\n</code></pre>\n\n<p>Visit the project home page at <a href="https://github.com/agardiner/color-console" rel="nofollow">https://github.com/agardiner/color-console</a> for more details.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77744', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/234/'] |
77,748 | <p>We have a server with 10 running mongrel_cluster instances with apache
in front of them, and every now and then one or some of them hang.
No activity is seen in the database (we're using activerecord sessions).
Mysql with innodb tables. show innodb status shows no locks. show
processlist shows nothing.</p>
<p>The server is linux debian 4.0</p>
<p>Ruby is: ruby 1.8.6 (2008-03-03 patchlevel 114) [i486-linux]</p>
<p>Rails is: Rails 1.1.2 (yes, quite old)</p>
<p>We're using the native mysql connector (gem install mysql)</p>
<p>"strace -p PID" gives the following in a loop for the hung mongrel
process:</p>
<pre><code>gettimeofday({1219834026, 235289}, NULL) = 0
select(4, [3], [0], [], {0, 905241}) = -1 EBADF (Bad file descriptor)
gettimeofday({1219834026, 235477}, NULL) = 0
select(4, [3], [0], [], {0, 905053}) = -1 EBADF (Bad file descriptor)
gettimeofday({1219834026, 235654}, NULL) = 0
select(4, [3], [0], [], {0, 904875}) = -1 EBADF (Bad file descriptor)
gettimeofday({1219834026, 235829}, NULL) = 0
select(4, [3], [0], [], {0, 904700}) = -1 EBADF (Bad file descriptor)
gettimeofday({1219834026, 236017}, NULL) = 0
select(4, [3], [0], [], {0, 904513}) = -1 EBADF (Bad file descriptor)
gettimeofday({1219834026, 236192}, NULL) = 0
select(4, [3], [0], [], {0, 904338}) = -1 EBADF (Bad file descriptor)
gettimeofday({1219834026, 236367}, NULL) = 0
...
</code></pre>
<p>I used lsof and found that the process used 67 file descriptors (lsof -p
PID |wc -l)</p>
<p>Is there any other way I can debug this, so that I could for example
determine which file descriptor is "bad"?
Any other info or suggestions? Anybody else seen this?</p>
<p>The site is fairly used, but not overly so, load averages usually around
0.3.</p>
<hr>
<p>Some additional info. I installed mongrelproctitle to show what the
hung processes were doing, and it seems they are hanging on a method
that displays images using file_column / images from the database /
rmagick to resize and make the images greyscale. </p>
<p>Not conclusive the
problem is here, but it is a suspicion.
Is there something obviously wrong with the following? The method
displays a static image if the order doesn't contain an image, else the
image resized from the order. The cache stuff is so that the image gets
updated in the browser every time. The image is inserted in the page
with a normal image tag.</p>
<p>code:</p>
<pre><code> def preview_image
@order = session[:order]
if @order.image.nil?
@headers['Pragma'] = 'no-cache'
@headers['Cache-Control'] = 'no-cache, must-revalidate'
send_data(EMPTY_PIC.to_blob, :filename => "img.jpg", :type =>
"image/jpeg", :disposition => "inline")
else
@pic = Image.read(@order.image)[0]
if (@order.crop)
@pic.crop!(@order.crop[:x1].to_i, @order.crop[:y1].to_i,
@order.crop[:width].to_i, @order.crop[:height].to_i, true)
end
@pic.resize!(103,130)
@pic = @pic.quantize(256, Magick::GRAYColorspace)
@headers['Pragma'] = 'no-cache'
@headers['Cache-Control'] = 'no-cache, must-revalidate'
send_data(@pic.to_blob, :filename => "img.jpg", :type =>
"image/jpeg", :disposition => "inline")
end
end
</code></pre>
<p>Here is the lsof output if anybody can find any problems in it. Don't
know how it will format in this message...</p>
<pre><code>lsof: WARNING: can't stat() ext3 file system /dev/.static/dev
Output information may be incomplete.
COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
mongrel_r 11628 username cwd DIR 9,2 4096 1870688
/home/domains/example.com/usernameOrder/releases/20080831121802
mongrel_r 11628 username rtd DIR 9,1 4096 2 /
mongrel_r 11628 username txt REG 9,1 3564 167172
/usr/bin/ruby1.8
mongrel_r 11628 username mem REG 0,0 0
[heap] (stat: No such file or directory)
mongrel_r 11628 username DEL REG 0,8 15560245
/dev/zero
mongrel_r 11628 username DEL REG 0,8 15560242
/dev/zero
mongrel_r 11628 username DEL REG 0,8 15560602
/dev/zero
mongrel_r 11628 username DEL REG 0,8 15560601
/dev/zero
mongrel_r 11628 username DEL REG 0,8 15560684
/dev/zero
mongrel_r 11628 username DEL REG 0,8 15560683
/dev/zero
mongrel_r 11628 username DEL REG 0,8 15560685
/dev/zero
mongrel_r 11628 username DEL REG 0,8 15560568
/dev/zero
mongrel_r 11628 username DEL REG 0,8 15560607
/dev/zero
mongrel_r 11628 username DEL REG 0,8 15560569
/dev/zero
mongrel_r 11628 username mem REG 9,1 1933648 456972
/usr/lib/libmysqlclient.so.15.0.0
mongrel_r 11628 username DEL REG 0,8 15442414
/dev/zero
mongrel_r 11628 username DEL REG 0,8 15560546
/dev/zero
mongrel_r 11628 username mem REG 9,1 67408 457393
/lib/i686/cmov/libresolv-2.7.so
mongrel_r 11628 username mem REG 9,1 17884 457386
/lib/i686/cmov/libnss_dns-2.7.so
mongrel_r 11628 username DEL REG 0,8 15560541
/dev/zero
mongrel_r 11628 username DEL REG 0,8 15560246
/dev/zero
mongrel_r 11628 username DEL REG 0,8 15560693
/dev/zero
mongrel_r 11628 username DEL REG 0,8 15560608
/dev/zero
mongrel_r 11628 username mem REG 9,1 25700 164963
/usr/lib/gconv/gconv-modules.cache
mongrel_r 11628 username mem REG 9,1 83708 457384
/lib/i686/cmov/libnsl-2.7.so
mongrel_r 11628 username mem REG 9,1 140602 506903
/var/lib/gems/1.8/gems/mysql-2.7/lib/mysql.so
mongrel_r 11628 username mem REG 9,1 1282816 180935
...
mongrel_r 11628 username 1w REG 9,2 462923 1575329
/home/domains/example.com/usernameOrder/shared/log/mongrel.8001.log
mongrel_r 11628 username 2w REG 9,2 462923 1575329
/home/domains/example.com/usernameOrder/shared/log/mongrel.8001.log
mongrel_r 11628 username 3u IPv4 15442350 TCP
localhost:8001 (LISTEN)
mongrel_r 11628 username 4w REG 9,2 118943548 1575355
/home/domains/example.com/usernameOrder/shared/log/production.log
mongrel_r 11628 username 5u REG 9,1 145306 234226
/tmp/mongrel.11628.0 (deleted)
mongrel_r 11628 username 7u unix 0xc3c12480 15442417
socket
mongrel_r 11628 username 11u REG 9,1 50 234180
/tmp/CGI.11628.2
mongrel_r 11628 username 12u REG 9,1 26228 234227
/tmp/CGI.11628.3
</code></pre>
<p>I have installed monit to monitor the server. No automatic restarts yet because of the PID file issue, but maybe I will get the newest version which supports deleting stale PID-files.<br>
It would be nice though to actually fix the problem, because somebody will get disconnects etc if the server need to be restarted all the time (~10 times a day)</p>
<p>The mongrel-processes don't take any large amount of memory when this is happening, and the machine isn't even swapping, so it's probably not a memory leak. </p>
<pre><code> total used free shared buffers cached
Mem: 4152796 4083000 69796 0 616624 2613364
-/+ buffers/cache: 853012 3299784
Swap: 1999992 52 1999940
</code></pre>
| [{'answer_id': 78044, 'author': 'sean lynch', 'author_id': 14232, 'author_profile': 'https://Stackoverflow.com/users/14232', 'pm_score': 1, 'selected': False, 'text': "<p>Chapter 6.3 in the book Deploying Rails Applications (A Step by Step Guide) has a good section on installing and configuring the Monitoring utility Monit on Linux and using it to monitor your mongrels. It can restart your mongrels when they fail.</p>\n\n<p>Older versions of Mongrel had trouble re-starting because of a duplicate PID file existing on disk. Newer versions support the --clean option that will get rid of the leftover PID files, if they exist. So you have to upgrade Mongrel to a version that supports --clean to get around the stale PID file issue, Monit alone can't do this.</p>\n"}, {'answer_id': 78953, 'author': 'manveru', 'author_id': 8367, 'author_profile': 'https://Stackoverflow.com/users/8367', 'pm_score': 2, 'selected': False, 'text': '<p>Consider using <a href="http://seattlerb.rubyforge.org/ImageScience.html" rel="nofollow noreferrer">ImageScience</a>, RMagick is known to leak massive amounts of memory and lock.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77748', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13709/'] |
77,813 | <p>Does anyone have any pointers on how to read the Windows EventLog without using JNI? Or if you <em>have to</em> use JNI, are there any good open-source libraries for doing so?</p>
| [{'answer_id': 78015, 'author': 'Sanjaya R', 'author_id': 9353, 'author_profile': 'https://Stackoverflow.com/users/9353', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://bloggingabout.net/blogs/wellink/archive/2005/04/08/3289.aspx" rel="nofollow noreferrer">http://bloggingabout.net/blogs/wellink/archive/2005/04/08/3289.aspx</a>\nand\n<a href="http://www.j-interop.org/" rel="nofollow noreferrer">http://www.j-interop.org/</a></p>\n'}, {'answer_id': 78035, 'author': 'Flint', 'author_id': 11877, 'author_profile': 'https://Stackoverflow.com/users/11877', 'pm_score': 0, 'selected': False, 'text': '<p>You\'ll need to use <a href="http://en.wikipedia.org/wiki/Java_Native_Interface" rel="nofollow noreferrer">JNI</a>.</p>\n'}, {'answer_id': 78066, 'author': 'Cheekysoft', 'author_id': 1820, 'author_profile': 'https://Stackoverflow.com/users/1820', 'pm_score': 1, 'selected': False, 'text': '<p>You may want to consider looking at <a href="http://www.jinvoke.com/" rel="nofollow noreferrer">J/Invoke</a> or <a href="https://github.com/twall/jna/" rel="nofollow noreferrer">JNA (Java Native Access)</a> as an alternative to the much berated JNI.</p>\n'}, {'answer_id': 3832161, 'author': 'dB.', 'author_id': 123094, 'author_profile': 'https://Stackoverflow.com/users/123094', 'pm_score': 2, 'selected': False, 'text': '<p>JNA 3.2.8 has both an implementation for all event logging functions and a Java iterator. Read <a href="http://code.dblock.org/ShowPost.aspx?id=125" rel="nofollow">this</a>.</p>\n\n<pre><code>EventLogIterator iter = new EventLogIterator("Application"); \nwhile(iter.hasNext()) { \n EventLogRecord record = iter.next(); \n System.out.println(record.getRecordId() \n + ": Event ID: " + record.getEventId() \n + ", Event Type: " + record.getType() \n + ", Event Source: " + record.getSource()); \n} \n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77813', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1693/'] |
77,817 | <p>I have multiple classes that all derive from a base class, now some of the derived classes will not be compiled depending on the platform. I have a class that allows me to return an object of the base class, however now all the names of the derived classes have been hard coded.</p>
<p>Is there a way to determine what classes have been compiled, at run-time preferably, so that I can remove the linking and instead provide dynamically loadable libraries instead.</p>
| [{'answer_id': 77832, 'author': 'Sebastian Redl', 'author_id': 8922, 'author_profile': 'https://Stackoverflow.com/users/8922', 'pm_score': 0, 'selected': False, 'text': '<p>If every class has its own dynamic library, just check if the library exists.</p>\n'}, {'answer_id': 77841, 'author': 'Jason Dagit', 'author_id': 5113, 'author_profile': 'https://Stackoverflow.com/users/5113', 'pm_score': 0, 'selected': False, 'text': '<p>This sounds like a place to use "compile time polymorphism" or template policy parameters.</p>\n\n<p>See Modern C++ Design by Andrei Alexandrescu and his <a href="http://sourceforge.net/projects/loki-lib/" rel="nofollow noreferrer">Loki</a> implementation based on the book. See also the <a href="http://en.wikipedia.org/wiki/Loki_(C%2B%2B)" rel="nofollow noreferrer">Loki</a> page at wikipedia.</p>\n'}, {'answer_id': 77843, 'author': 'Daniel Spiewak', 'author_id': 9815, 'author_profile': 'https://Stackoverflow.com/users/9815', 'pm_score': 0, 'selected': False, 'text': "<p>There are nasty, compiler-specific tricks for getting at class information at runtime. Trust me, you don't want to open that can of worms.</p>\n\n<p>It seems to me that the only serious way of doing this would be to use conditional compilation on each of the derived classes. Within the #ifdef block, define a <em>new</em> constant which contains the class name which is being compiled. Then, the names are still hard coded, but all in a central location.</p>\n"}, {'answer_id': 77851, 'author': 'user10392', 'author_id': 10392, 'author_profile': 'https://Stackoverflow.com/users/10392', 'pm_score': 2, 'selected': False, 'text': "<p>I don't know what you're really trying to accomplish, but you could put a singleton constructor in each derived class's implementation file that adds the name to a list, along with a pointer to a factory. Then the list is always up to date and can create all the compiled in classes.</p>\n"}, {'answer_id': 77856, 'author': 'Dima', 'author_id': 13313, 'author_profile': 'https://Stackoverflow.com/users/13313', 'pm_score': 1, 'selected': False, 'text': '<p>Generally, relying on the run-time type information is a bad idea in C++. What you have described seems like the factory pattern. You may want to consider creating a special factory subclass for each platform, which would only know about classes that exist on that platform. </p>\n'}, {'answer_id': 77911, 'author': 'Denice', 'author_id': 14178, 'author_profile': 'https://Stackoverflow.com/users/14178', 'pm_score': 3, 'selected': True, 'text': '<p>Are you looking for C++ runtime class registration? I found this <a href="http://meat.net/2006/03/cpp-runtime-class-registration/" rel="nofollow noreferrer">link</a> (<a href="http://web.archive.org/web/20100618122920/http://meat.net/2006/03/cpp-runtime-class-registration/" rel="nofollow noreferrer">backup</a>).</p>\n\n<p>That would probably accomplish what you want, I am not sure about the dynamically loaded modules and whether or not you can register them using the same method.</p>\n'}, {'answer_id': 77935, 'author': 'David Thornley', 'author_id': 14148, 'author_profile': 'https://Stackoverflow.com/users/14148', 'pm_score': 0, 'selected': False, 'text': '<p>The names of the derived classes have to be hard-coded in C++. There\'s no other way to use them. Therefore, not only is there no way to automatically detect what classes have been compiled, there would be no way to use that information if it existed.</p>\n\n<p>If you could specify classes at run-time based on their name, something like:</p>\n\n<p>std::string foo = "Derived1";\nBase * object = new "foo"; // or whatever notation you like - doesn\'t work in C++</p>\n\n<p>then the ability to tell if "Derived1" was compiled or not would be useful. Since you have to specify the class directly, like:</p>\n\n<p>Base * object = new Derived1; // does work in C++</p>\n\n<p>all checking is done at compile time.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77817', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13986/'] |
77,826 | <p>One thing I've started doing more often recently is <strong>retrieving some data</strong> at the beginning of a task <strong>and storing it in a $_SESSION['myDataForTheTask']</strong>. </p>
<p>Now it seems very convenient to do so but I don't know anything about performance, security risks or similar, using this approach. Is it something which is regularly done by programmers with more expertise or is it more of an amateur thing to do?</p>
<p><strong>For example:</strong></p>
<pre><code>if (!isset($_SESSION['dataentry']))
{
$query_taskinfo = "SELECT participationcode, modulearray, wavenum FROM mng_wave WHERE wave_id=" . mysql_real_escape_string($_GET['wave_id']);
$result_taskinfo = $db->query($query_taskinfo);
$row_taskinfo = $result_taskinfo->fetch_row();
$dataentry = array("pcode" => $row_taskinfo[0], "modules" => $row_taskinfo[1], "data_id" => 0, "wavenum" => $row_taskinfo[2], "prequest" => FALSE, "highlight" => array());
$_SESSION['dataentry'] = $dataentry;
}
</code></pre>
| [{'answer_id': 77846, 'author': 'nsayer', 'author_id': 13757, 'author_profile': 'https://Stackoverflow.com/users/13757', 'pm_score': 1, 'selected': False, 'text': "<p>$_SESSION items are stored in the session, which is, by default, kept on disk. There is no need to make your own array and stuff it in a 'dataentry' array entry like you did. You can just use $_SESSION['pcode'], $_SESSION['modules'] and so on.</p>\n\n<p>Like I said, the session is stored on disk and a pointer to the session is stored in a cookie. The user thus can't easily get ahold of the session data.</p>\n"}, {'answer_id': 77852, 'author': 'Steve M', 'author_id': 1693, 'author_profile': 'https://Stackoverflow.com/users/1693', 'pm_score': 0, 'selected': False, 'text': "<p>I use this approach a fair bit, I don't see any problem with it. Unlike cookies, the data isn't stored at the client-side, which is often a big mistake.</p>\n\n<p>Like anything though, just be careful that you're always sanitising user input, especially if you're putting user input into the $_SESSION variable, then later using that variable in an SQL query.</p>\n"}, {'answer_id': 77877, 'author': 'pix0r', 'author_id': 72, 'author_profile': 'https://Stackoverflow.com/users/72', 'pm_score': 2, 'selected': False, 'text': '<p>There are a few factors you\'ll want to consider when deciding where to store temporary data. Session storage is great for data that is specific to a single user. If you find the default file-based session storage handler is inefficient you can implement something else, possibly using a database or memcache type of backend. See <a href="http://us.php.net/manual/en/function.session-set-save-handler.php" rel="nofollow noreferrer">session_set_save_handler</a> for more info.</p>\n\n<p>I find it is a bad practice to store common data in a user\'s session. There are better places to store data that will be frequently accessed by several users and by storing this data in the session you will be duplicating the data for each user who needs this data. In your example, you might set up a different type of storage engine for this wave data (based on wave_id) that is NOT tied specifically to a user\'s session. That way you\'ll pull the data down once and them store it somewhere that several users can access the data without requiring another pull.</p>\n'}, {'answer_id': 77882, 'author': 'Lucas Oman', 'author_id': 6726, 'author_profile': 'https://Stackoverflow.com/users/6726', 'pm_score': 1, 'selected': False, 'text': '<p>IMO, it\'s perfectly acceptable to store things in the session. It\'s a great way to make data persistent. It\'s also, in many cases, more secure than storing everything in cookies. Here are a few concerns:</p>\n\n<ul>\n<li>It\'s possible for someone to hijack a session, so if you\'re going to use it to keep track of user authorization, be careful. Read <a href="http://en.wikipedia.org/wiki/Session_hijacking" rel="nofollow noreferrer">this</a> for more information.</li>\n<li>It can be a very lazy way to keep data. Don\'t just throw everything in the session so that you don\'t have to query for it later.</li>\n<li>If you\'re going to store objects in the session, either their class files will need to be included before the session is started on the next request or you\'ll need to have configured an auto loader.</li>\n</ul>\n'}, {'answer_id': 77885, 'author': 'jfs', 'author_id': 6223, 'author_profile': 'https://Stackoverflow.com/users/6223', 'pm_score': 2, 'selected': False, 'text': '<p>If you\'re running on your own server, or in an environment where nobody can snoop on your files/memory on the server, session data are secure. They\'re stored on the server and just an identification cookie sent to the client. The problem is if other people can snatch the cookie and impersonate someone else, of course. Using HTTPS and making sure to not put the session ID in URLs should keep your users safe from most of those problems. (XSS might still be used to snatch cookies if you aren\'t careful, see <a href="http://www.codinghorror.com/blog/archives/001167.html" rel="nofollow noreferrer">Jeef Atwoods post on this</a> too.)</p>\n\n<p>As for what to store in a session variable, put your data there if you want to refer to it again on another page, like a shopping basket, but don\'t put it there if it\'s just temporary data used for producing the result of this page, like a list of tags for the currently viewed post. Sessions are for per-user persistent data.</p>\n'}, {'answer_id': 77899, 'author': 'foxxtrot', 'author_id': 10369, 'author_profile': 'https://Stackoverflow.com/users/10369', 'pm_score': 0, 'selected': False, 'text': "<p>This is a fairly common thing to do, and the session is generally going to be faster than continuous database hits. They're also reasonably secure, as the PHP devs have worked hard to prevent Session Hijacking.</p>\n\n<p>The only issue is that you need to remember to rebuild the session entry when something changes. And, if anything is changed by a user other than the one who owns the session that would result in a need to refresh this key, there is no easy way to notify the system to refresh this session key. Possibly not a big deal, but something you should be aware of.</p>\n"}, {'answer_id': 77906, 'author': 'Ryan Smith', 'author_id': 10420, 'author_profile': 'https://Stackoverflow.com/users/10420', 'pm_score': 3, 'selected': False, 'text': '<p>I use the session variable all the time to store information for users. I haven\'t seen any issues with performance. The session data is pulled based on the cookie (or <em>PHPSESSID</em> if you have cookies turned off). I don\'t see it being any more of a security risk than any other cookie based authentication, and probably more secure than storing the actual data in the users cookie.</p>\n\n<p>Just to let you know though, you do have a security issue with your SQL statement:</p>\n\n<pre><code>SELECT participationcode, modulearray, wavenum FROM mng_wave WHERE wave_id=".$_GET[\'wave_id\'];\n</code></pre>\n\n<p>You should <strong>NEVER, I REPEAT NEVER</strong>, take user provided data and use it to run a SQL statement without first sanitizing it. I would wrap it in quotes and add the function <code>mysql_real_escape_string()</code>. That will protect you from most attacks. So your line would look like:</p>\n\n<pre><code>$query_taskinfo = "SELECT participationcode, modulearray, wavenum FROM mng_wave WHERE wave_id=\'".mysql_real_escape_string($_GET[\'wave_id\'])."\'";\n</code></pre>\n'}, {'answer_id': 77910, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>Zend Framework has a useful library for session data management which helps with expiry and security (for stuff like captchas). They also have a useful explanation of sessions. See <a href="http://framework.zend.com/manual/en/zend.session.html" rel="nofollow noreferrer">http://framework.zend.com/manual/en/zend.session.html</a></p>\n'}, {'answer_id': 77916, 'author': 'HappySmileMan', 'author_id': 14073, 'author_profile': 'https://Stackoverflow.com/users/14073', 'pm_score': 5, 'selected': True, 'text': "<p>Well Session variables are really one of the only ways (and probably the most efficient) of having these variables available for the entire time that visitor is on the website, there's no real way for a user to edit them (other than an exploit in your code, or in the PHP interpreter) so they are fairly secure.</p>\n\n<p>It's a good way of storing settings that can be changed by the user, as you can read the settings from database once at the beginning of a session and it is available for that entire session, you only need to make further database calls if the settings are changed and of course, as you show in your code, it's trivial to find out whether the settings already exist or whether they need to be extracted from database.</p>\n\n<p>I can't think of any other way of storing temporary variables securely (since cookies can easily be modified and this will be undesirable in most cases) so $_SESSION would be the way to\xa0go</p>\n"}, {'answer_id': 78089, 'author': 'William Macdonald', 'author_id': 2725, 'author_profile': 'https://Stackoverflow.com/users/2725', 'pm_score': 2, 'selected': False, 'text': '<p>Another way to improve the input validation is to cast the _GET[\'wave_id\'] variable:</p>\n\n<pre><code>$query_taskinfo = "SELECT participationcode, modulearray, wavenum FROM mng_wave WHERE wave_id=".(int)$_GET[\'wave_id\']." LIMIT 1";\n</code></pre>\n\n<p>I\'m presuming wave_id is an integer, and that there is only one answer.</p>\n\n<p>Will</p>\n'}, {'answer_id': 78514, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>I have found sessions to be very useful, but a few things to note:</p>\n\n<p>1) That PHP may store your sessions in a tmp folder or other directory that may be accessible to other users on your server. You can change the directory were sessions are stored by going to the php.ini file.</p>\n\n<p>2) If you are setting up a high value system that needs very tight security you might want to encrypt the data before you send it to the session, and decrypt it to use it. Note: this might create too much overhead depending on your traffic / server capacity.</p>\n\n<p>3) I have found that session_destroy(); doesn’t delete the session right away, you still have to wait for the PHP garbage collector to clean the sessions up. You can change the frequency that the garbage collector is run in the php.ini file. But is still doesn’t seem very reliable, more info <a href="http://www.captain.at/howto-php-sessions.php" rel="nofollow noreferrer">http://www.captain.at/howto-php-sessions.php</a></p>\n'}, {'answer_id': 196809, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>$_SESSION mechanism is using cookies. </p>\n\n<p>In case of Firefox (and maybe new IE, I didn\'t check myself) that means that <strong>session is shared between opened tabs</strong>. That is not something you expect by default. And it means that session is no longer "something specific to a single window/user".</p>\n\n<p>For example, if you have opened two tabs to access your site, than logged as a root using the first tab, you will gain root privileges in the other one.</p>\n\n<p>That is really inconvenient, especially if you code e-mail client or something else (like e-shop). In this case you will have to manage sessions manually or introduce constantly regenerated key in URL or do something else.</p>\n'}, {'answer_id': 634423, 'author': 'Matt', 'author_id': 17759, 'author_profile': 'https://Stackoverflow.com/users/17759', 'pm_score': 1, 'selected': False, 'text': '<p>You might want to consider how REST-ful this is?</p>\n\n<p>i.e. see "Communicate statelessly" paragraph in "<a href="http://www.infoq.com/articles/rest-introduction" rel="nofollow noreferrer">A Brief Introduction to REST</a>"...</p>\n\n<blockquote>\n <p>"REST mandates that state be either\n turned into resource state, or kept on\n the client. In other words, a server\n should not have to retain some sort of\n communication state for any of the\n clients it communicates with beyond a\n single request."</p>\n</blockquote>\n\n<p>(or any of the other links on wikipedia for <a href="http://en.wikipedia.org/wiki/REST" rel="nofollow noreferrer">REST</a>)</p>\n\n<p>So in your case, the \'wave_id\' is a sensible Resource to GET, but do you really want to store it in the SESSION? Surely <a href="http://www.danga.com/memcached/" rel="nofollow noreferrer">memcached</a> is your solution to cacheing the object Resource?</p>\n'}, {'answer_id': 767861, 'author': 'Tom', 'author_id': 42754, 'author_profile': 'https://Stackoverflow.com/users/42754', 'pm_score': 2, 'selected': False, 'text': '<p>A few other disadvantages of using sessions:</p>\n\n<ol>\n<li><code>$_SESSION</code> data will expire after <em>session.gc_maxlifetime</em> seconds of inactivity.</li>\n<li>You\'ll have to remember to call <code>session_start()</code> for every script that will use the session data.</li>\n<li>Scaling the website by load balancing over multiple servers could be a problem because the user will need to be directed to the same server each time. Solve this with "Sticky Sessions".</li>\n</ol>\n'}, {'answer_id': 803140, 'author': 'Bryan Grezeszak', 'author_id': 89633, 'author_profile': 'https://Stackoverflow.com/users/89633', 'pm_score': 0, 'selected': False, 'text': '<p>$_SESSION is very useful in security, since it is a server side way to store information while a user is actively on your pages, therefore hard to hack unless your actual php file or server has weaknesses that are exploited. One very good implementation is storing a variable to confirm that the user is logged in, and only allowing actions to be taken if they are confirmed logged in.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77826', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11995/'] |
77,833 | <p>I wonder if anyone can think of a good technique to enable any arbitrary section of an aspx page (say, the contents within a specified DIV tag) to be able to be called and displayed in an ajax modal popup? (So, only a certain section of the page would be displayed)</p>
<p>For example:<br>
1) You have a large application with many entities (Customers, Products, Stores, etc, etc etc)<br>
2) Each entity has an EntityDetails aspx page</p>
<p>Now, say from an Invoice screen that shows many entities of different types, I would like to be able to mouseover (or click a small icon) an entity, and have a little tooltip style modal ajax window popup, and what is shown will be the PORTION of the corresponding EntityDetails aspx page that was designated as available for rendering as a popup.
Obviously, the corresponding aspx arguments identifying the specific entity would have to be passed from the page as well.</p>
<p>So to do this, ** I think the requested page would have to be rendered in memory on the server **, and then the innerhtml would have to be pulled out of the designated div, and returned to the calling page, which would then display this html in a popup ajax window.
So, unless there is an easier way to do this that I am missing, how would this rendering be done on the server?</p>
<p>Has anyone seen this done before, is there any sort of a pre-existing framework or anything to do this?</p>
<p>And to complicate things further, would it be possible to have the popup form be editable and saved back to the server utilizing the existing asp.net form mechanism already embedded within the existing page (if the calling form already had an asp.net form....I think only one form is allowed per page, correct?)</p>
<p>And of course, opening the EntityDetails form via a simple javascript popup or new window is not what I am looking for. And I do not want to have to embed the details form on each page where I may want it to display...every form in the application could conceivably call any other as a popup.</p>
<p>Thanks!</p>
| [{'answer_id': 77858, 'author': 'Mitchel Sellers', 'author_id': 13279, 'author_profile': 'https://Stackoverflow.com/users/13279', 'pm_score': 1, 'selected': False, 'text': '<p>You could most likely do this with a collection of user controls and the ModalPopupExtender that is available in the AJAX Control Toolkit.</p>\n'}, {'answer_id': 77865, 'author': 'Danimal', 'author_id': 2757, 'author_profile': 'https://Stackoverflow.com/users/2757', 'pm_score': 1, 'selected': False, 'text': '<p>If you\'re using user controls for the edits, I think you could do it with <a href="http://www.orangoo.com/labs/GreyBox/" rel="nofollow noreferrer">Greybox</a>. Pass the user control name (and other parameters) to the page you show in greybox, then dynamically load the user control that does the edit. </p>\n'}, {'answer_id': 78152, 'author': 'Luke', 'author_id': 14275, 'author_profile': 'https://Stackoverflow.com/users/14275', 'pm_score': 0, 'selected': False, 'text': "<p>I can't vote but user controls would be the way to.</p>\n"}, {'answer_id': 2434747, 'author': 'tbone', 'author_id': 8678, 'author_profile': 'https://Stackoverflow.com/users/8678', 'pm_score': 1, 'selected': True, 'text': '<p><a href="http://api.jquery.com/load/" rel="nofollow noreferrer">http://api.jquery.com/load/</a>\n<a href="http://css.dzone.com/articles/jquery-load-data-from-other-pa" rel="nofollow noreferrer">http://css.dzone.com/articles/jquery-load-data-from-other-pa</a></p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77833', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8678/'] |
77,835 | <p>I am trying to run a SeleniumTestCase with phpunit but I cannot get it to run with the phpunit.bat script. </p>
<p>My goal is to use phpunit with Selenium RC in CruiseControl & phpUnderControl. This is what the test looks like:</p>
<pre><code>require_once 'PHPUnit/Extensions/SeleniumTestCase.php';
class WebTest extends PHPUnit_Extensions_SeleniumTestCase
{
protected function setUp()
{
$this->setBrowser('*firefox');
$this->setBrowserUrl('http://www.example.com/');
}
public function testTitle()
{
$this->open('http://www.example.com/');
$this->assertTitleEquals('Example Web Page');
}
}
</code></pre>
<p>I also got PEAR in the include_path and PHPUnit installed with the Selenium extension. I installed these with the pear installer so I guess that's not the problem. </p>
<p>Any help would be very much appreciated. </p>
<p>Thanks, Remy</p>
| [{'answer_id': 77955, 'author': 'Ciaran', 'author_id': 5048, 'author_profile': 'https://Stackoverflow.com/users/5048', 'pm_score': 1, 'selected': False, 'text': '<p>Have a look at one of the comments in the require_once entry in the php manual..</p>\n\n<p><a href="http://ie.php.net/manual/en/function.require-once.php#62838" rel="nofollow noreferrer">http://ie.php.net/manual/en/function.require-once.php#62838</a></p>\n\n<p>"require_once (and include_once for that matters) is slow</p>\n\n<p>Furthermore, if you plan on using unit tests and mock objects (i.e. including mock classes before the real ones are included in the class you want to test), it will not work as require() loads a file and not a class."</p>\n'}, {'answer_id': 78065, 'author': 'Remy', 'author_id': 12645, 'author_profile': 'https://Stackoverflow.com/users/12645', 'pm_score': 1, 'selected': False, 'text': '<p>I just renamed the file my test was in to "WebTest.php" (the name of the class it contains) and the test runs fine now.</p>\n'}, {'answer_id': 425050, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>Well when I use inline command : if lauching test from PhPunit dir i have the error while whent launching it from test dir I havne't the error ...</p>\n\n<p>but I still haven't any acces to selenium server ... shall I have to launch it before or not.</p>\n\n<p>If Yes it's strange that we havne't to specify any handle to PhPUnit ...</p>\n"}, {'answer_id': 472548, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>Here is the deal:</p>\n\n<p>If you have a "Class PHPUnit_Extensions_SeleniumTestCase could not be found in (testcase file name)" problem, you have to do the following two things:</p>\n\n<p><strong><em>1. Rename the file of test case to the name of the class it contains</em></strong>\n<strong><em>2. You should launch phpunit from the folder with your tests.</em></strong></p>\n\n<p>This should fix your problem.</p>\n\n<p>Andrew</p>\n'}, {'answer_id': 590774, 'author': 'scc', 'author_id': 46183, 'author_profile': 'https://Stackoverflow.com/users/46183', 'pm_score': 1, 'selected': False, 'text': "<p>Do not presume that the pear install occurred without problems.</p>\n\n<p>I had installed phpunit through pear but despite it saying the install went fine when I looked inside the folder, I had all these files starting with .tmp, eg PHPUnit/Util/.tmpErrorHandler.php so naturally when i ran a test for the 1st time it gave me the same error as above. After checking that indeed the file wasn't there I did a manual install of PHPUnit to the same folder as pear and alas, all was fine. I'm in Mac/leopard.</p>\n\n<p>About Selenim RC don't forget to start it by running in terminal\njava -jar /path/to/file/selenium-server.jar</p>\n"}, {'answer_id': 2146178, 'author': 'CruiZen', 'author_id': 232647, 'author_profile': 'https://Stackoverflow.com/users/232647', 'pm_score': 1, 'selected': False, 'text': "<p>I found that the following sample from PHPUnit tutorial was working while the same error appeared in the test that I had written.\nThe solution was a surprise. Ensure that your class is inside a <code><?php .. ?></code> block and not a <code><? .. ?></code> block in the script.</p>\n\n<pre><code><?php\nrequire_once 'PHPUnit/Framework.php';\n\nclass StackTest extends PHPUnit_Framework_TestCase\n{\n public function testPushAndPop()\n {\n $stack = array();\n $this->assertEquals(0, count($stack));\n\n array_push($stack, 'foo');\n $this->assertEquals('foo', $stack[count($stack)-1]);\n $this->assertEquals(1, count($stack));\n\n $this->assertEquals('foo', array_pop($stack));\n $this->assertEquals(0, count($stack));\n }\n}\n?>\n</code></pre>\n"}, {'answer_id': 4456097, 'author': 'farinspace', 'author_id': 97433, 'author_profile': 'https://Stackoverflow.com/users/97433', 'pm_score': 4, 'selected': False, 'text': '<p>hopefully this is a more definitive answer then the ones given here (which did not solve me problem). If you are getting this error, check your PEAR folder and see if the "SeleniumTestCase.php" file is actually there:</p>\n\n<pre><code>/PEAR/PHPUnit/Extensions/SeleniumTestCase.php\n</code></pre>\n\n<p>If it is NOT, the easiest thing to do is to uninstall and reinstall PHPUnit using PEAR ...</p>\n\n<pre><code>pear uninstall phpunit/PHPUnit\n\npear uninstall phpunit/PHPUnit_Selenium\n\npear install phpunit/PHPUnit\n</code></pre>\n\n<p>After doing the above and doing just the single install, PHPUnit_Selenium was also auto installed, I\'m not sure if this is typical, so some might have to do...</p>\n\n<pre><code>pear install phpunit/PHPUnit_Selenium\n</code></pre>\n\n<p>Also see <a href="http://www.phpunit.de/manual/3.5/en/installation.html" rel="noreferrer">http://www.phpunit.de/manual/3.5/en/installation.html</a> for PEAR channel info if needed...</p>\n'}, {'answer_id': 9059767, 'author': 'mosid', 'author_id': 1023151, 'author_profile': 'https://Stackoverflow.com/users/1023151', 'pm_score': 1, 'selected': False, 'text': '<p>Here is how i solved this problem:</p>\n\n<ol>\n<li>Make sure that curl extension for php is installed,\n e.g for ubuntu <code>sudo apt-get install php5-curl</code></li>\n<li>Enter <code>sudo pear install phpunit/PHPUnit_Selenium</code></li>\n</ol>\n\n<p>After that you should have the missing file installed</p>\n\n<p>Happy coding...</p>\n'}, {'answer_id': 21568125, 'author': 'JTHouseCat', 'author_id': 3113435, 'author_profile': 'https://Stackoverflow.com/users/3113435', 'pm_score': 0, 'selected': False, 'text': '<p>When it fails it doesn\'t always print out the most verbose error messages. </p>\n\n<p>Always remember to start Selenium too prior to running test.</p>\n\n<p>java -jar selenium-server-standalone-2.39.0.jar</p>\n\n<p>Here is an example of code that was working for myself. <a href="http://www.siteconsortium.com/h/p1.php?id=php002" rel="nofollow">http://www.siteconsortium.com/h/p1.php?id=php002</a>. Obviously there are a lot of different way to write the test suite, and launch the test case but I used the set_class_path to get rid of class issues at first.</p>\n'}, {'answer_id': 26145421, 'author': 'Slava Nikoolin', 'author_id': 4099507, 'author_profile': 'https://Stackoverflow.com/users/4099507', 'pm_score': 1, 'selected': False, 'text': '<p>Try:</p>\n\n<pre><code>class WebTest extends \\PHPUnit_Extensions_Selenium2TestCase\n</code></pre>\n\n<p>It can be namespace issue, as it was for me.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77835', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12645/'] |
77,836 | <p>Given two vectors <strong>A</strong> and <strong>B</strong> which form the line segment <strong>L</strong> = A-B.
Furthermore given a view frustum <strong>F</strong> which is defined by its left, right, bottom, top, near and far planes.</p>
<p>How do I clip <strong>L</strong> against <strong>F</strong>? </p>
<p>That is, test for an intersection <em>and</em> where on L that intersection occurs?
(Keep in mind that a line segment can have <strong>more</strong> than one intersection with the frustum if it intersects two sides at a corner.)</p>
<p>If possible, provide a code example please (C++ or Python preferred).</p>
| [{'answer_id': 77888, 'author': 'Sarien', 'author_id': 1994377, 'author_profile': 'https://Stackoverflow.com/users/1994377', 'pm_score': 2, 'selected': False, 'text': '<p>I don\'t want to get into writing code for this now but if I understand "frustum" correctly the following should work.</p>\n\n<ol>\n<li>Intersect the Line with all given planes</li>\n<li>If you have two intersections you\'re done.</li>\n<li>If you have only one intersection calculate the front plane and intersect.</li>\n<li>If you still have only one intersection calculate the back plane and intersect.</li>\n</ol>\n\n<p>But I may have completely misunderstood. In that case please elaborate :)</p>\n'}, {'answer_id': 90676, 'author': 'jasonmray', 'author_id': 17230, 'author_profile': 'https://Stackoverflow.com/users/17230', 'pm_score': 1, 'selected': False, 'text': '<p>Adding to what Corporal Touchy said above, you\'ll need to <a href="http://local.wasp.uwa.edu.au/~pbourke/geometry/planeline/" rel="nofollow noreferrer">know how to intersect a line segment with a plane</a>. In the description on that page, u represents the parameter in the parametric definition of your line. First, calculate u using one of the 2 methods described. If the value of u falls in the range of 0.0 to 1.0, then the plane clips the line somewhere on your segment. Plugging u back into your line equation gives you the point where that intersection occurs.</p>\n\n<p>Another approach is to find the <a href="http://mathworld.wolfram.com/Point-PlaneDistance.html" rel="nofollow noreferrer">directed distance</a> of each point to a plane. If the distance of one point is positive and the other is negative, then they lie on opposite sides of the plane. You then know which point is outside your frustum (based on which way your plane normal points). Using this approach, finding the intersection point can be done faster by doing a linear interpolation based on the ratio of the directed distances. E.g. if the distance of one point is +12 and the other is -12, you know the plane cuts the segment in half, and your u parameter is 0.5.</p>\n\n<p>Hope this helps.</p>\n'}, {'answer_id': 34960552, 'author': 'ideasman42', 'author_id': 432509, 'author_profile': 'https://Stackoverflow.com/users/432509', 'pm_score': 1, 'selected': False, 'text': '<p>First <a href="https://stackoverflow.com/a/34960913/432509">extract the planes from your view matrix</a>.</p>\n\n<p>Then use your points to define a vector and min/max as (0, 1), then iterate over the planes and intersect them with the segment, updating the min/max, bailing out early if the <code>min > max</code>.</p>\n\n<p>Here\'s an example of a pure Python function, no external deps.</p>\n\n<pre class="lang-py prettyprint-override"><code>def clip_segment_v3_plane_n(p1, p2, planes):\n """\n - p1, p2: pair of 3d vectors defining a line segment.\n - planes: a sequence of (4 floats): `(x, y, z, d)`.\n\n Returns 2 vector triplets (the clipped segment)\n or (None, None) then segment is entirely outside.\n """\n dp = sub_v3v3(p2, p1)\n\n p1_fac = 0.0\n p2_fac = 1.0\n\n for p in planes:\n div = dot_v3v3(p, dp)\n if div != 0.0:\n t = -plane_point_side_v3(p, p1)\n if div > 0.0: # clip p1 lower bounds\n if t >= div:\n return None, None\n if t > 0.0:\n fac = (t / div)\n if fac > p1_fac:\n p1_fac = fac\n if p1_fac > p2_fac:\n return None, None\n elif div < 0.0: # clip p2 upper bounds\n if t > 0.0:\n return None, None\n if t > div:\n fac = (t / div)\n if fac < p2_fac:\n p2_fac = fac\n if p1_fac > p2_fac:\n return None, None\n\n p1_clip = add_v3v3(p1, mul_v3_fl(dp, p1_fac))\n p2_clip = add_v3v3(p1, mul_v3_fl(dp, p2_fac))\n\n return p1_clip, p2_clip\n\n\n# inline math library\ndef add_v3v3(v0, v1):\n return (\n v0[0] + v1[0],\n v0[1] + v1[1],\n v0[2] + v1[2],\n )\n\ndef sub_v3v3(v0, v1):\n return (\n v0[0] - v1[0],\n v0[1] - v1[1],\n v0[2] - v1[2],\n )\n\ndef dot_v3v3(v0, v1):\n return (\n (v0[0] * v1[0]) +\n (v0[1] * v1[1]) +\n (v0[2] * v1[2])\n )\n\ndef mul_v3_fl(v0, f):\n return (\n v0[0] * f,\n v0[1] * f,\n v0[2] * f,\n )\n\ndef plane_point_side_v3(p, v):\n return dot_v3v3(p, v) + p[3]\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77836', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14157/'] |
77,873 | <p>Are there PHP libraries which can be used to fill PDF forms and then save (flatten) them to PDF files?</p>
| [{'answer_id': 77930, 'author': 'pix0r', 'author_id': 72, 'author_profile': 'https://Stackoverflow.com/users/72', 'pm_score': 1, 'selected': False, 'text': '<p>Looks like this has been <a href="https://stackoverflow.com/questions/7364/pdf-editing-in-php">covered before</a>. Click through for relevant code using Zend Framework PDF library.</p>\n'}, {'answer_id': 77950, 'author': 'foxxtrot', 'author_id': 10369, 'author_profile': 'https://Stackoverflow.com/users/10369', 'pm_score': 1, 'selected': False, 'text': '<p>We use <a href="http://www.pdflib.com/" rel="nofollow noreferrer">PDFLib</a> at work. The paid version isn\'t very expensive, and there is a more limited open source edition, if you are unable to shell out for the paid version.</p>\n'}, {'answer_id': 78300, 'author': 'bmb', 'author_id': 5298, 'author_profile': 'https://Stackoverflow.com/users/5298', 'pm_score': 7, 'selected': True, 'text': '<p>The libraries and frameworks mentioned here are good, but if all you want to do is fill in a form and flatten it, I recommend the command line tool called pdftk (PDF Toolkit).</p>\n\n<p>See <a href="https://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/" rel="noreferrer">https://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/</a></p>\n\n<p>You can call the command line from php, and the command is</p>\n\n<p><code>pdftk</code> <em>formfile.pdf</em> <code>fill_form</code> <em>fieldinfo.fdf</em> <code>output</code> <em>outputfile.pdf</em> <code>flatten</code></p>\n\n<p>You will need to find the format of an FDF file in order to generate the info to fill in the fields. Here\'s a good link for that:</p>\n\n<p><a href="http://www.tgreer.com/fdfServe.html" rel="noreferrer">http://www.tgreer.com/fdfServe.html</a></p>\n\n<p>[Edit: The above link seems to be out of commission. Here is some more info...]</p>\n\n<p>The pdftk command can generate an FDF file from a PDF form file. You can then use the generated FDF file as a sample. The form fields are the portion of the FDF file that looks like</p>\n\n<pre><code>...\n<< /T(f1-1) /V(text of field) >>\n<< /T(f1-2) /V(text of another field) >>\n...\n</code></pre>\n\n<p>You might also check out <a href="https://github.com/mikehaertl/php-pdftk" rel="noreferrer">php-pdftk</a>, which is a library specific to PHP. I have not used it, but commenter Álvaro (below) recommends it.</p>\n'}, {'answer_id': 89023, 'author': 'josh.chavanne', 'author_id': 14708, 'author_profile': 'https://Stackoverflow.com/users/14708', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve had plenty of success with using a form that submits to a php script that uses fpdf and passes in the form fields as get variables (maybe not a great best-practice, but it works). </p>\n\n<pre><code> <?php\nrequire(\'fpdf.php\');\n$pdf=new PDF();\n$pdf->AddPage();\n$pdf->SetY(30);\n$pdf->SetX(100);\n$pdf->MultiCell(10,4,$_POST[\'content\'],0,\'J\');\n$pdf->Output();\n?>\n</code></pre>\n\n<p>and the you could have something like this.</p>\n\n<pre><code> <form action="fooPDF.php" method="post">\n <p>PDF CONTENT: <textarea name="content" ></textarea></p>\n <p><input type="submit" /></p>\n </form>\n</code></pre>\n\n<p>This skeletal example ought to help ya get started. </p>\n'}, {'answer_id': 112712, 'author': 'Chris Dolan', 'author_id': 14783, 'author_profile': 'https://Stackoverflow.com/users/14783', 'pm_score': 1, 'selected': False, 'text': '<p>I wrote a Perl library, <a href="http://search.cpan.org/dist/CAM-PDF/" rel="nofollow noreferrer">CAM::PDF</a>, with a <a href="http://search.cpan.org/dist/CAM-PDF/bin/fillpdffields.pl" rel="nofollow noreferrer">command-line interface</a> that can solve this. I tried using an FDF solution years ago, but found it way too complicated which is why I wrote CAM::PDF in the first place. My library uses a few heuristics to replace the form with the desired text, so it\'s not perfect. But it works most of the time, and it\'s fast, free and quite straightforward to use.</p>\n'}, {'answer_id': 1078577, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>generating fdf File with php:\nsee <a href="http://www.php.net/manual/en/book.fdf.php" rel="nofollow noreferrer">http://www.php.net/manual/en/book.fdf.php</a></p>\n\n<p>then fill it into a pdf with pdftk (see above)</p>\n'}, {'answer_id': 10674039, 'author': 'Nikolay', 'author_id': 1406316, 'author_profile': 'https://Stackoverflow.com/users/1406316', 'pm_score': 2, 'selected': False, 'text': '<p>For:</p>\n\n<ul>\n<li>Easier input format then XFDF</li>\n<li>True UTF-8 (Russian) support</li>\n<li>Complete php usage example</li>\n</ul>\n\n<p>Feel free to check my <a href="https://sourceforge.net/projects/pdfformfiller2/" rel="nofollow">PdfFormFillerUTF-8</a>.</p>\n'}, {'answer_id': 12772058, 'author': 'Val Redchenko', 'author_id': 572660, 'author_profile': 'https://Stackoverflow.com/users/572660', 'pm_score': 3, 'selected': False, 'text': "<p>A big +1 to the accepted answer, and a little tip if you run into encoding issues with the fdf file. If you generate the fields.fdf and upon running</p>\n\n<pre><code>file -bi fields.fdf\n</code></pre>\n\n<p>you get </p>\n\n<pre><code>application/octet-stream; charset=binary\n</code></pre>\n\n<p>then you've most likely run into a UTF-16 character set issue.\nTry converting the ftf by means of</p>\n\n<pre><code>cat fields.fdf | sed -e's/\\x00//g' | sed -e's/\\xFE\\xFF//g' > better.fdf\n</code></pre>\n\n<p>I was then able to edit and import the better.fdf file into my PDF form.</p>\n\n<p>Hopefully this saves someone some Google-ing</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77873', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14166/'] |
77,887 | <p>As someone who is just starting to learn the intricacies of computer debugging, for the life of me, I can't understand how to read the Stack Text of a dump in Windbg. I've no idea of where to start on how to interpret them or how to go about it. Can anyone offer direction to this poor soul?</p>
<p>ie (the only dump I have on hand with me actually)</p>
<pre>>b69dd8f0 bfa1e255 016d2fc0 89efc000 00000040 nv4_disp+0x48b94
b69dd8f4 016d2fc0 89efc000 00000040 00000006 nv4_disp+0x49255
b69dd8f8 89efc000 00000040 00000006 bfa1dcc0 0x16d2fc0
b69dd8fc 00000000 00000006 bfa1dcc0 e1e71018 0x89efc000</pre>
<p>I know the problem is to do with the Nvidia display driver, but what I want to know is how to actually read the stack (eg, what is b69dd8f4?) :-[</p>
| [{'answer_id': 77921, 'author': '1800 INFORMATION', 'author_id': 3146, 'author_profile': 'https://Stackoverflow.com/users/3146', 'pm_score': 0, 'selected': False, 'text': '<p>It might help to include an example of the stack you are trying to read. A good tip is to ensure you have correct debug symbols for all modules shown in the stack. This includes symbols for modules in the OS, Microsoft has made their symbol server publicly available.</p>\n'}, {'answer_id': 78083, 'author': 'Michael Burr', 'author_id': 12711, 'author_profile': 'https://Stackoverflow.com/users/12711', 'pm_score': 2, 'selected': False, 'text': '<p>A really good tutorial on interpreting a stack trace is available here:</p>\n\n<p><a href="http://www.codeproject.com/KB/debug/cdbntsd2.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/debug/cdbntsd2.aspx</a></p>\n\n<p>However, even with a tutorial like that it can be very difficult (or near impossible) to interpret a stack dump without the proper symbols available/loaded.</p>\n'}, {'answer_id': 78111, 'author': 'sachaa', 'author_id': 1152057, 'author_profile': 'https://Stackoverflow.com/users/1152057', 'pm_score': 5, 'selected': True, 'text': '<p>First, you need to have the proper symbols configured. The symbols will allow you to match memory addresses to function names. In order to do this you have to create a local folder in your machine in which you will store a local cache of symbols (for example: C:\\symbols). Then you need to specify the symbols server path. To do this just go to: File > Symbol File Path and type:</p>\n\n<pre><code>SRV*c:\\symbols*http://msdl.microsoft.com/download/symbols\n</code></pre>\n\n<p>You can find more information on how to correctly configure the symbols <a href="http://www.microsoft.com/whdc/devtools/debugging/debugstart.mspx#a" rel="noreferrer">here</a>.</p>\n\n<p>Once you have properly configured the Symbols server you can open the minidump from: File > Open Crash Dump. </p>\n\n<p>Once the minidump is opened it will show you on the left side of the command line the thread that was executing when the dump was generated. If you want to see what this thread was executing type:</p>\n\n<pre><code>kpn 200\n</code></pre>\n\n<p>This might take some time the first you execute it since it has to download the necessary public Microsoft related symbols the first time. Once all the symbols are downloaded you\'ll get something like:</p>\n\n<pre><code>01 MODULE!CLASS.FUNCTIONNAME1(...)\n02 MODULE!CLASS.FUNCTIONNAME2(...)\n03 MODULE!CLASS.FUNCTIONNAME3(...)\n04 MODULE!CLASS.FUNCTIONNAME4(...)\n</code></pre>\n\n<p>Where:</p>\n\n<ul>\n<li><strong>THE FIRST NUMBER</strong>: Indicates the frame number</li>\n<li><strong>MODULE</strong>: The DLL that contains the code</li>\n<li><strong>CLASS</strong>: (Only on C++ code) will show you the class that contains the code</li>\n<li><strong>FUNCTIONAME</strong>: The method that was called. If you have the correct symbols you will also see the parameters.</li>\n</ul>\n\n<p>You might also see something like</p>\n\n<pre><code>01 MODULE!+989823\n</code></pre>\n\n<p>This indicates that you don\'t have the proper Symbol for this DLL and therefore you are only able to see the method offset.</p>\n\n<p>So, what is a callstack? </p>\n\n<p>Imagine you have this code:</p>\n\n<pre><code>void main()\n{\n method1();\n}\n\nvoid method1()\n{\n method2();\n}\n\nint method2()\n{\n return 20/0;\n}\n</code></pre>\n\n<p>In this code method2 basically will throw an Exception since we are trying to divide by 0 and this will cause the process to crash. If we got a minidump when this occurred we would see the following callstack:</p>\n\n<pre><code>01 MYDLL!method2()\n02 MYDLL!method1()\n03 MYDLL!main()\n</code></pre>\n\n<p>You can follow from this callstack that "main" called "method1" that then called "method2" and it failed.</p>\n\n<p>In your case you\'ve got this callstack (which I guess is the result of running "kb" command)</p>\n\n<pre><code>b69dd8f0 bfa1e255 016d2fc0 89efc000 00000040 nv4_disp+0x48b94\nb69dd8f4 016d2fc0 89efc000 00000040 00000006 nv4_disp+0x49255\nb69dd8f8 89efc000 00000040 00000006 bfa1dcc0 0x16d2fc0\nb69dd8fc 00000000 00000006 bfa1dcc0 e1e71018 0x89efc000\n</code></pre>\n\n<p>The first column indicates the Child Frame Pointer, the second column indicates the Return address of the method that is executing, the next three columns show the first 3 parameters that were passed to the method, and the last part is the DLL name (nv4_disp) and the offset of the method that is being executed (+0x48b94). Since you don\'t have the symbols you are not able to see the method name. I doubt tha NVIDIA offers public access to their symbols so I gues you can\'t get much information from here.</p>\n\n<p>I recommend you run "kpn 200". This will show you the full callstack and you might be able to see the origin of the method that caused this crash (if it was a Microsoft DLL you should have the proper symbols in the steps that I provided you).</p>\n\n<p>At least you know it\'s related to a NVIDIA bug ;-) Try upgrading the DLLs of this driver to the latest version.</p>\n\n<p>In case you want to learn more about WinDBG debugging I recommend the following links:</p>\n\n<ul>\n<li><a href="http://blogs.msdn.com/tess/default.aspx" rel="noreferrer">If broken it is, fix it you should</a></li>\n<li><a href="http://www.microsoft.com/events/EventDetails.aspx?CMTYSvcSource=MSCOMMedia&Params=~CMTYDataSvcParams%5E~arg+Name%3D%22ID%22+Value%3D%221032298076%22%2F%5E~arg+Name%3D%22ProviderID%22+Value%3D%22A6B43178-497C-4225-BA42-DF595171F04C%22%2F%5E~arg+Name%3D%22lang%22+Value%3D%22en%22%2F%5E~arg+Name%3D%22cr%22+Value%3D%22US%22%2F%5E~sParams%5E~%2FsParams%5E~%2FCMTYDataSvcParams%5E" rel="noreferrer">TechNet Webcast: Windows Hang and Crash Dump Analysis</a> </li>\n<li><a href="http://delicious.com/popular/windbg" rel="noreferrer">Delicious.com popular links on WinDBG</a></li>\n</ul>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77887', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14173/'] |
77,890 | <p>I am writing some code to see if there is a hole in the firewall exception list for <strong>WinXP</strong> and <strong>Vista</strong> for a specific port used by our client software. </p>
<p>I can see that I can use the <code>NetFwMgr.LocalPolicy.CurrentProfile.GloballyOpenPorts</code> to get a list of the current Open port exceptions. But i can not figure out how to get that enumerated list in to something that I can use in my Delphi program. </p>
<p>My latest try is listed below. It's giving me an access violation when I use <code>port_list.Item</code>. I know that's wrong, it was mostly wishful thinking on my part. Any help would be appreciated.</p>
<pre><code>function TFirewallUtility.IsPortInExceptionList(iPortNumber: integer): boolean;
var
i, h: integer;
port_list, port: OleVariant;
begin
Result := False;
port_list := mxFirewallManager.LocalPolicy.CurrentProfile.GloballyOpenPorts;
for i := 0 to port_list.Count - 1 do
begin
port := port_list.Item[i];
if (port.PortNumber = iPortNumber) then
begin
Result := True;
break;
end;
end;
end;
</code></pre>
| [{'answer_id': 78144, 'author': 'Jim McKeeth', 'author_id': 255, 'author_profile': 'https://Stackoverflow.com/users/255', 'pm_score': 0, 'selected': False, 'text': '<p>Without setting up an application to test with, I\'ll suggest the following. Let me know if it works.</p>\n\n<p>I looked at the <a href="http://blogs.msdn.com/joncole/archive/2005/12/06/managed-classes-to-view-manipulate-the-windows-firewall.aspx" rel="nofollow noreferrer">C# example here</a>, and it looks like you need to do something like the following:</p>\n\n<pre><code>Result := False;\nport_enum := mxFirewallManager.LocalPolicy.CurrentProfile.GloballyOpenPorts._NewEnum;\nwhile port_enum.MoveNext <> Null do // try assigned if that doesn\'t work\nbegin\n port = e.Current as INetFwOpenPort;\n if (port.PortNumber = iPortNumber) then\n begin\n Result := True;\n break;\n end;\nend;\n</code></pre>\n\n<p>Not sure if that will compile, but the <strong>_NewEnum</strong>, <strong>MoveNext</strong> and <strong>Current</strong> are the members you want to use.</p>\n'}, {'answer_id': 105813, 'author': 'Ray Jenkins', 'author_id': 12425, 'author_profile': 'https://Stackoverflow.com/users/12425', 'pm_score': 1, 'selected': False, 'text': "<p>OK, I think that I have it figured out. </p>\n\n<p>I had to create a type library file of the hnetcfg.dll. I did that when I first started but have learned a lot about the firewall objects since then. It didn't work then, but its working now. You can create your own file from Component|Import Component. And then follow the wizard. </p>\n\n<p>The wrapping code uses exceptions which I normally don't like to do, but I don't know how to tell whether an Interface that is returning an Interface is actually returning data that I can work off of... So that would be an improvement if somebody can point me in the right direction.</p>\n\n<p>And now to the code, with a thanks to Jim for his response.</p>\n\n<pre><code>constructor TFirewallUtility.Create;\nbegin\n inherited Create;\n CoInitialize(nil);\n mxCurrentFirewallProfile := INetFwMgr(CreateOLEObject('HNetCfg.FwMgr')).LocalPolicy.CurrentProfile;\nend;\n\nfunction TFirewallUtility.IsPortInExceptionList(iPortNumber: integer): boolean;\nbegin\n try\n Result := mxCurrentFirewallProfile.GloballyOpenPorts.Item(iPortNumber, NET_FW_IP_PROTOCOL_TCP).Port = iPortNumber;\n except\n Result := False;\n end;\nend;\n\nfunction TFirewallUtility.IsPortEnabled(iPortNumber: integer): boolean;\nbegin\n try\n Result := mxCurrentFirewallProfile.GloballyOpenPorts.Item(iPortNumber, NET_FW_IP_PROTOCOL_TCP).Enabled;\n except\n Result := False;\n end;\nend;\n\nprocedure TFirewallUtility.SetPortEnabled(iPortNumber: integer; sPortName: string; xProtocol: TFirewallPortProtocol);\nbegin\n try\n mxCurrentFirewallProfile.GloballyOpenPorts.Item(iPortNumber, CFirewallPortProtocalConsts[xProtocol]).Enabled := True;\n except\n HaltIf(True, 'xFirewallManager.TFirewallUtility.IsPortEnabled: Port not in exception list.');\n end;\nend;\n\nprocedure TFirewallUtility.AddPortToFirewall(sPortName: string; iPortNumber: Cardinal; xProtocol: TFirewallPortProtocol);\nvar\n port: INetFwOpenPort;\nbegin\n port := INetFwOpenPort(CreateOLEObject('HNetCfg.FWOpenPort'));\n port.Name := sPortName;\n port.Protocol := CFirewallPortProtocalConsts[xProtocol];\n port.Port := iPortNumber;\n port.Scope := NET_FW_SCOPE_ALL;\n port.Enabled := true;\n mxCurrentFirewallProfile.GloballyOpenPorts.Add(port);\nend;\n</code></pre>\n"}, {'answer_id': 1613254, 'author': 'jpfollenius', 'author_id': 62391, 'author_profile': 'https://Stackoverflow.com/users/62391', 'pm_score': 1, 'selected': False, 'text': "<p>You can loop through the enum like this:</p>\n\n<pre><code>type\n IEnumVariant = interface(IUnknown)\n ['{00020404-0000-0000-C000-000000000046}']\n function Next(celt: LongWord; var rgvar : OleVariant;\n pceltFetched: PLongWord): HResult; stdcall;\n function Skip(celt: LongWord): HResult; stdcall;\n function Reset: HResult; stdcall;\n function Clone(out Enum : IEnumVariant) : HResult; stdcall;\n end;\n\nvar\n Enum : IEnumVariant;\n Port : OleVariant;\n Count : Integer;\n...\nCount := 1;\nIUnknown (Profile.GloballyOpenPorts._NewEnum).QueryInterface (IEnumVariant, Enum);\nEnum.Reset;\nwhile (Enum.Next (1, FirewallPort, @Count) = S_OK) do\n begin\n if (FirewallPort.Port = Port) then\n Exit (True)\n end;\n</code></pre>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77890', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12425/'] |
77,891 | <p>This is not "exactly" a programming question, but it's highly related. We are writing an app that sends out email invitations for a client (no, it's not spam). Their designer gave us an HTML and CSS template to use which is fine. The problem is that it looks like crap in Outlook 2007 because Microsoft decided to use Word (of all things!) as the <a href="http://msdn.microsoft.com/en-us/library/aa338201.aspx" rel="nofollow noreferrer">rendering engine for HTML in Outlook 2007</a>. I want the client to understand that they should design a "compatible" look and would love to be able to show some kind of statistics about what email clients are being used out there, namely that Outlook 2007 is growing in use. </p>
<p>Has anyone run across any white papers, web sites, studies that even come close to providing a view on this? I don't expect census level accuracy, but something fairly credible would be good. Thanks for any help.</p>
| [{'answer_id': 77909, 'author': 'Rob Fuller', 'author_id': 14183, 'author_profile': 'https://Stackoverflow.com/users/14183', 'pm_score': 1, 'selected': False, 'text': '<p>you should look at <a href="https://returnpath.com/" rel="nofollow noreferrer">ReturnPath</a> - they somewhat specialize in that. </p>\n\n<p>Clients you likely need to consider (aside from Outlook):</p>\n\n<ul>\n<li><a href="https://aol.com" rel="nofollow noreferrer">AOL</a></li>\n<li><a href="https://gmail.com" rel="nofollow noreferrer">Gmail</a> (Google)</li>\n<li><a href="https://ymail.com" rel="nofollow noreferrer">Yahoo Mail</a> (Yahoo)</li>\n<li><a href="https://hotmail.com" rel="nofollow noreferrer">Hotmail</a>/<a href="https://live.com" rel="nofollow noreferrer">Live</a>/<a href="https://msn.com" rel="nofollow noreferrer">MSN</a>/<a href="https://outlook.com" rel="nofollow noreferrer">Outlook</a> (Microsoft)</li>\n<li>Lotus Notes (IBM)</li>\n<li><a href="https://thunderbird.net" rel="nofollow noreferrer">Thunderbird</a> (Mozilla)</li>\n</ul>\n'}, {'answer_id': 77918, 'author': 'jfs', 'author_id': 6223, 'author_profile': 'https://Stackoverflow.com/users/6223', 'pm_score': 0, 'selected': False, 'text': "<p>If you expect to hit many business customers, remember that a very large potion of them will be using MS Office and Exchange Server and therefore also Outlook. If you're more aiming for home users most of them will either be using some webmail or a mail client that uses a regular HTML engine, like Windows Mail, Thunderbird, Opera Mail, Mac OS X Mail.app.</p>\n"}, {'answer_id': 77922, 'author': 'Avner', 'author_id': 1476, 'author_profile': 'https://Stackoverflow.com/users/1476', 'pm_score': -1, 'selected': False, 'text': "<p>I'm using gmail</p>\n"}, {'answer_id': 77949, 'author': 'Cheekysoft', 'author_id': 1820, 'author_profile': 'https://Stackoverflow.com/users/1820', 'pm_score': 4, 'selected': True, 'text': '<p>My understanding of the generally perceived best-practise on this, is is to code for the lowest-common denominator. There are plenty of email clients with enough use in-the-wild that aren\'t great at rendering "modern" HTML.</p>\n\n<p>Firstly, aim to send your mails as a 2-part multipart mime message. An HTML part AND a plain-text part.</p>\n\n<p>Secondly, try to avoid using CSS or positioned divs where possible. Use table-based layouts and inlined-styles. Preferably specifying as much of the style in HTML where possible.</p>\n\n<p>Try to keep images as inline IMG tags, or as table/row/cell background attributes only.</p>\n\n<p>The email world just isn\'t anywhere near as up-to-date, and more importantly, far more diverse than the browser world. If you follow these simple rules, your life is going to be much easier than taking a more advanced approach and repeatedly tweaking it in order to get your content to render satisfactorally on enough of the common clients.</p>\n'}, {'answer_id': 77975, 'author': 'HappySmileMan', 'author_id': 14073, 'author_profile': 'https://Stackoverflow.com/users/14073', 'pm_score': 0, 'selected': False, 'text': '<p>I use KMail, you should also look at Thunderbird, Outlook, Evolution, Lotus and Opera Mail.</p>\n\n<p>Also keep in mind many people use webmail such as GMail, Hotmail, Yahoo Mail etc. And some web mail (and mail-clients) work only in plain-text for security reasons.</p>\n\n<p>Personally I think that plain text emails are best, many people prefer not to allow HTML mails due to security reason and thus would just be viewing a badly formatted plain text mail anyway, regardless of what you send, so in my opinion it would be better to just use plain text.</p>\n'}, {'answer_id': 78052, 'author': 'X-Cubed', 'author_id': 10808, 'author_profile': 'https://Stackoverflow.com/users/10808', 'pm_score': 0, 'selected': False, 'text': "<p>Gmail - personal mail</p>\n\n<p>Lotus Notes - forced to use it for corporate mail :(</p>\n\n<p>Lotus Notes sucks at rendering any HTML message correctly (we're running 6.5), and has only partial support for CSS. The best HTML messages for it are simple table-based layouts.</p>\n"}, {'answer_id': 78098, 'author': 'chryss', 'author_id': 5169, 'author_profile': 'https://Stackoverflow.com/users/5169', 'pm_score': 2, 'selected': False, 'text': '<p>Raw market share figures will not help you much. When designing HTML email, the only thing that matters is what client your particular target population uses. This depends on geographical area, industry, B2B/B2C -- variations are huge in practice. In some industries (journalism...) you\'ll even have to reckon with a sizeable population using clients like Lotus Notes, which is notorious for supporting HTML barely more than nominally (shudder).</p>\n\n<p>Outlook 2007 can certainly not be neglected any more, in particular if you send to business addresses, but with Vista on new PCs it\'s also got a noticeable presence for private accounts.</p>\n\n<p>Return Path indeed have data according to industry.</p>\n\n<p>However, in practice, a good approach is to follow "save" guidelines, in a lowest common denominator style. Outlook 2007 is not the only problematic client -- Gmail is also quite notorious for lacking support for a number of design elements others display just fine. You\'ll find that a surprising number of web designers do run a sideline with HTML email design (there is demand and it helps pay the rent). If you just start out, Campaign Monitor (an email marketing provider) has a wealth of good resources. You could start with their <a href="http://www.campaignmonitor.com/blog/archives/2008/05/2008_email_design_guidelines.html" rel="nofollow noreferrer">2008 Email Design Guidelines</a>. They\'re also one of those behind the <a href="http://www.email-standards.org/" rel="nofollow noreferrer">Email Standards Project</a>. </p>\n\n<p>Oh, personally I use Thunderbird with IMAP, Gmail, and RoundCube. </p>\n\n<p>(Disclaimer/full disclosure: I actually work for a competitor, in the loose sense, of Campaing Monitor.)</p>\n'}, {'answer_id': 78151, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>At work we have 3 x KMail and 4 x mac OSX' mail.<br>\nFurther webmail as fail-over (squirrelmail on mail server) in Firefox, Camino, Safari.\nWe put the words in the mail, the rest in attachments.</p>\n\n<p>Words (pure text messages) can simply be copy/pasted, forwarded etc without formatting problems.</p>\n\n<p>Separate attachments lets user choose to view, download, save etc.</p>\n\n<p>This is the most universal way to use mail.</p>\n"}, {'answer_id': 78210, 'author': 'Shoban', 'author_id': 12178, 'author_profile': 'https://Stackoverflow.com/users/12178', 'pm_score': 0, 'selected': False, 'text': '<p>I faced this issue some time back.. most of the clients (including web) block HTML! We just created a web version of the email and added this to the footer of the email "If you are not able to view the message click here (link to web version). It was simply because some people think that its not safe to display images ;-) so a better way to make them open and read beautiful html emails</p>\n'}, {'answer_id': 78320, 'author': 'Scott Swezey', 'author_id': 9439, 'author_profile': 'https://Stackoverflow.com/users/9439', 'pm_score': 1, 'selected': False, 'text': "<p>I have outlook and gmail, but also a blackberry Curve...</p>\n\n<p>The curve is HORRIBLE at dealing with anything other than plain/text emails. Please have a link near the top to view the email on a website, and consider sending a multipart email that also has a text only section for clients that don't support HTML and such.</p>\n"}, {'answer_id': 78365, 'author': 'Shadow2531', 'author_id': 1697, 'author_profile': 'https://Stackoverflow.com/users/1697', 'pm_score': 0, 'selected': False, 'text': '<p>I run M2 (Opera\'s built-in mail client) and always have it set to "prefer plain text" for mail bodies. I also have "Block external elements" turned on.</p>\n'}, {'answer_id': 78425, 'author': 'Robin like the bird', 'author_id': 14405, 'author_profile': 'https://Stackoverflow.com/users/14405', 'pm_score': 2, 'selected': False, 'text': '<p>In absence of general statistics, collect your own.</p>\n\n<p>Check out <a href="http://fingerprintapp.com/email-client-stats" rel="nofollow noreferrer">http://fingerprintapp.com/email-client-stats</a> for a ready-made statistics collection tool, and see <a href="http://www.mattbrindley.com/fingerprint-email-client-usage-1/" rel="nofollow noreferrer">http://www.mattbrindley.com/fingerprint-email-client-usage-1/</a> for a write-up about it. Matt Brindley also offers this gem: "<em>So far only Outlook has proved as popular as we expected, the iPhone was a notable surprise for our own list, with Lotus Notes making an unexpected appearance as well.</em>"</p>\n\n<p>Of course, provide both text/html and text/plain mime types so that readers can choose which version to view, and keep your html extremely basic until your statistics indicate that you can get fancier.</p>\n\n<p>If Fingerprint\'s fee is out of the question, you can collect your own statistics. Include hyperlinks in your HTML. When your CGI application receives requests from these hyperlinks, it can save the HTTP_USER_AGENT in a database for your statistical analysis. This method is not entirely reliable because some readers will stick to plain text, some will never click any of the hyperlinks, and some email clients will not include useful information in the user agent request header, but it may give you enough information to proceed.</p>\n\n<p>Sitepoint, a well-respected source for W3 information, has an article, <a href="http://www.sitepoint.com/article/code-html-email-newsletters/" rel="nofollow noreferrer">http://www.sitepoint.com/article/code-html-email-newsletters/</a>, in which Tom Slavin points out:</p>\n\n<ol>\n<li><p>Use HTML tables to control the design layout and some presentation. You may be used to using pure CSS layouts for your web pages, but that approach just won\'t hold up in an email environment.</p></li>\n<li><p>Use inline CSS to control other presentation elements within your email, such as background colors and fonts.</p></li>\n</ol>\n\n<p>Slavin also recommends templates from Campaign Monitor and MailChimp to get you started.</p>\n'}, {'answer_id': 78457, 'author': 'Shadow2531', 'author_id': 1697, 'author_profile': 'https://Stackoverflow.com/users/1697', 'pm_score': 0, 'selected': False, 'text': '<p>Also, I think if you send as both text/plain and text/html, Gmail users (of the webmail UI) have no choice but to view the text/html version.</p>\n'}, {'answer_id': 3981098, 'author': 'mxb', 'author_id': 481979, 'author_profile': 'https://Stackoverflow.com/users/481979', 'pm_score': 0, 'selected': False, 'text': '<p>I ran across this report / data that clearly shows Outlook 2007 gaining in popularity and heading in an upward curve. Currently this site reports the following top 4 clients (percentage out of 100% of course) but also that Outlook 2007 is on the rise. Hope this helps. </p>\n\n<p><a href="http://www.campaignmonitor.com/stats/email-clients/#most_popular" rel="nofollow">http://www.campaignmonitor.com/stats/email-clients/#most_popular</a></p>\n\n<p>27.77% Outlook 2000, 2003, Express / \n16.23% Hotmail /\n14.14% Yahoo! Mail / \n8.94% Outlook 2007 </p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77891', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4246/'] |
77,900 | <p>Has anyone ever written a function that can convert all of the controls on an aspx page into a read only version? For example, if UserDetails.aspx is used to edit and save a users information, if someone with inappropriate permissions enter the page, I would like to render it as read-only. So, most controls would be converted to labels, loaded with the corresponding data from the editable original control.</p>
<p>I think it would likely be a fairly simple routine, ie: </p>
<pre><code>Dim ctlParent As Control = Me.txtTest.Parent
Dim ctlOLD As TextBox = Me.txtTest
Dim ctlNEW As Label = New Label
ctlNEW.Width = ctlOLD.Width
ctlNEW.Text = ctlOLD.Text
ctlParent.Controls.Remove(ctlOLD)
ctlParent.Controls.Add(ctlNEW)
</code></pre>
<p>...is really all you need for a textbox --> label conversion, but I was hoping someone might know of an existing function out there as there are likely a few pitfalls here and there with certain controls and situations.</p>
<p>Update:<br>
- Just setting the ReadOnly property to true is not a viable solution, as it looks dumb having things greyed out like that.
- Avoiding manually creating a secondary view is the entire point of this, so using an ingenious way to display a read only version of the user interface that was built by hand using labels is wat I am trying to avoid.</p>
<p>Thanks!!</p>
| [{'answer_id': 77938, 'author': 'Quintin Robinson', 'author_id': 12707, 'author_profile': 'https://Stackoverflow.com/users/12707', 'pm_score': 2, 'selected': False, 'text': '<p>You could use a multiview and just have a display view and an edit view.. then do your assignments as:</p>\n\n<pre><code>lblWhatever.Text = txtWhatever.Text = whateverOriginatingSource;\nlblSomethingElse.Text = txtSomethingElse.Text = somethingElseOriginatingSource;\n\nmyViews.SelectedIndex = myConditionOrVariableThatDeterminesEditable ? 0 : 1;\n</code></pre>\n\n<p>then swap the views based on permissions.</p>\n\n<p>not the most elegant but will probably work for your situation.</p>\n\n<p>Maybe I should elaborate a little.. dismiss the psuedo (not sure if I have the selectedindex yada yada right.. but you get the point).</p>\n\n<pre><code><asp:Multiview ID="myViews" SelectedIndex="1">\n <asp:View ID="EditView">\n <asp:TextBox ID="txtWhatever" /><br />\n <asp:TextBox ID="txtSomethingElse" />\n </asp:View>\n <asp:View ID="DisplayView">\n <asp:Label ID="lblWhatever" /><br />\n <asp:Label ID="lblSomethingElse" />\n </asp:View>\n</asp:Multiview>\n</code></pre>\n'}, {'answer_id': 78143, 'author': 'Mark Brackett', 'author_id': 2199, 'author_profile': 'https://Stackoverflow.com/users/2199', 'pm_score': 0, 'selected': False, 'text': '<p>How about creating your own library of controls, that render differently if ReadOnly is true. Something like:</p>\n\n<pre><code>MyTextBox : TextBox {\n public override void RenderControl(HtmlTextWriter writer) {\n if (this.ReadOnly) {\n writer.WriteBeginTag("label");\n writer.Write(this.Value);\n writer.WriteEndTag();\n }\n }\n}\n</code></pre>\n\n<p>There\'s a way to use web.config to replace all asp:TextBox instances with your own control without having to edit to my:TextBox - but I\'m having trouble finding the reference ATM.</p>\n\n<p>Otherwise, I\'d probably just write a jQuery snippet to do it.</p>\n'}, {'answer_id': 78145, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>I don't know of any existing function, but it's not that hard to process the controls yourself. The big thing you'll need to worry about is non ASP.NET controls in the control tree. (eg. )</p>\n\n<p>You can case controls to the appropriate type and just check for null, and then deal with each control correctly. </p>\n"}, {'answer_id': 78197, 'author': 'Tom Kidd', 'author_id': 2577, 'author_profile': 'https://Stackoverflow.com/users/2577', 'pm_score': 0, 'selected': False, 'text': "<p>Short of authoring your own controls, I'm afraid that the route you don't want to go (making a second, label-only page) is probably a pretty good route simply because you don't want someone running Firebug who can edit HTML on the fly to just turn off whatever control you have in place and just use the page as if they had the right to update it.</p>\n"}, {'answer_id': 216684, 'author': 'tvanfosson', 'author_id': 12950, 'author_profile': 'https://Stackoverflow.com/users/12950', 'pm_score': 0, 'selected': False, 'text': '<p>Use a DetailsView. It does exactly what you want based on the current mode of the page.</p>\n'}, {'answer_id': 217738, 'author': 'Keith Patton', 'author_id': 25255, 'author_profile': 'https://Stackoverflow.com/users/25255', 'pm_score': 2, 'selected': False, 'text': '<p>Scott Mitchell posted a good article on this a while back. </p>\n\n<p><a href="https://web.archive.org/web/20210608183803/http://aspnet.4guysfromrolla.com/articles/012506-1.aspx" rel="nofollow noreferrer">https://web.archive.org/web/20210608183803/http://aspnet.4guysfromrolla.com/articles/012506-1.aspx</a></p>\n\n<p>I\'ve used this approach in the past in conjection with css on the \'read only\' fields to make them look and work exactly like a label, even though they are in fact text boxes.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77900', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8678/'] |
77,914 | <p>I have an Apache 2 installation on Debian with mod_ssl installed. The server private key is protected by a passphase that needs to be entered on start-up. The error and access logs are subject to logrotate on a weekly basis. I find that Apache crashes with a passphrase-related error shortly after logrotate runs.</p>
<p>I understand that logrotate fires a SIGHUP to Apache after archiving logs and I suspect this is causing a reload and subsequent failure getting the passphrase for the server key.</p>
<p>Well, enough with my theories, here is the question:</p>
<p>Is there a "best practice" way in which to configure Apache to allow its SSL server keys to be protected by a passphrase (without storing that passphrase in a file somewhere) so that it won't crash when logrotate runs?</p>
<p>It is fine to require user input on server startup, but not restart or reload.</p>
| [{'answer_id': 77928, 'author': 'Yann Ramin', 'author_id': 9167, 'author_profile': 'https://Stackoverflow.com/users/9167', 'pm_score': 2, 'selected': True, 'text': "<p>One option is to use Apache's provided log rotation tool. Its configured a bit differently than the system logrotate, but as it works with pipes, can move files around without an Apache restart.</p>\n"}, {'answer_id': 77987, 'author': 'Andrew Cholakian', 'author_id': 11105, 'author_profile': 'https://Stackoverflow.com/users/11105', 'pm_score': 2, 'selected': False, 'text': '<p>You could use <a href="http://cronolog.org/" rel="nofollow noreferrer">Cronolog</a>, which does not require a sighup. Here\'s an example:</p>\n\n<pre><code>CustomLog "| /usr/sbin/cronolog /pathtologs/%Y_%m/sitename.com-%Y%m%d.log" combined\n</code></pre>\n'}, {'answer_id': 421136, 'author': 'Derek P.', 'author_id': 45615, 'author_profile': 'https://Stackoverflow.com/users/45615', 'pm_score': 2, 'selected': False, 'text': '<p>you can also turn off the passphrase by using the following command:</p>\n\n<pre><code>openssl rsa -in example.tld.key -out example.tld.key\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77914', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13956/'] |
77,934 | <p>I have written code to read a windows bitmap and would now like to display it with ltk. How can I construct an appropriate object? Is there such functionality in ltk? If not how can I do it directly interfacing to tk?</p>
| [{'answer_id': 78937, 'author': 'Bryan Oakley', 'author_id': 7432, 'author_profile': 'https://Stackoverflow.com/users/7432', 'pm_score': 2, 'selected': False, 'text': '<p>Tk does not natively support windows bitmap files. However, the "Img" extension does and is freely available on just about every platform. You do not need to read the data in, you can create the image straight from the file on disk. In plain tcl/tk your code might look something like this:</p>\n\n<pre><code>package require Img\nset image [image create photo -file /path/to/image.bmp]\nlabel .l -image $image\npack .l\n</code></pre>\n\n<p>a little more information can be found at <a href="http://wiki.tcl.tk/6165" rel="nofollow noreferrer">http://wiki.tcl.tk/6165</a></p>\n'}, {'answer_id': 104227, 'author': 'Alasdair', 'author_id': 2654, 'author_profile': 'https://Stackoverflow.com/users/2654', 'pm_score': 3, 'selected': True, 'text': '<p>It has been a while since I used LTK for anything, but the simplest way to display an image with LTK is as follows:</p>\n\n<pre><code>(defpackage #:ltk-image-example\n (:use #:cl #:ltk))\n\n(in-package #:ltk-image-example)\n\n(defun image-example ()\n (with-ltk ()\n (let ((image (make-image)))\n (image-load image "testimage.gif")\n (let ((canvas (make-instance \'canvas)))\n (create-image canvas 0 0 :image image)\n (configure canvas :width 800)\n (configure canvas :height 640)\n (pack canvas)))))\n</code></pre>\n\n<p>Unfortunately what you can do with the image by default is fairly limited, and you can only use gif or ppm images - but the <a href="http://en.wikipedia.org/wiki/Portable_pixmap" rel="nofollow noreferrer">ppm file format</a> is very simple, you could easily create a ppm image from your bitmap. However you say you want to manipulate the displayed image, and looking at the code that defines the image object:</p>\n\n<pre><code>(defclass photo-image(tkobject)\n ((data :accessor data :initform nil :initarg :data)\n )\n )\n\n(defmethod widget-path ((photo photo-image))\n (name photo))\n\n(defmethod initialize-instance :after ((p photo-image)\n &key width height format grayscale data)\n (check-type data (or null string))\n (setf (name p) (create-name))\n (format-wish "image create photo ~A~@[ -width ~a~]~@[ -height ~a~]~@[ -format \\"~a\\"~]~@[ -grayscale~*~]~@[ -data ~s~]"\n (name p) width height format grayscale data))\n\n(defun make-image ()\n (let* ((name (create-name))\n (i (make-instance \'photo-image :name name)))\n ;(create i)\n i))\n\n(defgeneric image-load (p filename))\n(defmethod image-load((p photo-image) filename)\n ;(format t "loading file ~a~&" filename)\n (send-wish (format nil "~A read {~A} -shrink" (name p) filename))\n p)\n</code></pre>\n\n<p>It looks like the the actual data for the image is stored by the Tcl/Tk interpreter and not accessible from within lisp. If you wanted to access it you would probably need to write your own functions using <strong>format-wish</strong> and <strong>send-wish</strong>.</p>\n\n<p>Of course you could simply render each pixel individually on a canvas object, but I don\'t think you would get very good performance doing that, the canvas widget gets a bit slow once you are trying to display more than a few thousand different things on it. So to summarize - if you don\'t care about doing anything in real time, you could save your bitmap as a .ppm image every time you wanted to display it and then simply load it using the code above - that would be the easiest. Otherwise you could try to access the data from tk itself (after loading it once as a ppm image), finally if none of that works you could switch to another toolkit. Most of the decent lisp GUI toolkits are for linux, so you may be out of luck if you are using windows.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77934', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1994377/'] |
77,936 | <p>As part of a project at work I have to calculate the centroid of a set of points in 3D space. Right now I'm doing it in a way that seems simple but naive -- by taking the average of each set of points, as in:</p>
<pre><code>centroid = average(x), average(y), average(z)
</code></pre>
<p>where <code>x</code>, <code>y</code> and <code>z</code> are arrays of floating-point numbers. I seem to recall that there is a way to get a more accurate centroid, but I haven't found a simple algorithm for doing so. Anyone have any ideas or suggestions? I'm using Python for this, but I can adapt examples from other languages.</p>
| [{'answer_id': 77978, 'author': 'deemer', 'author_id': 11192, 'author_profile': 'https://Stackoverflow.com/users/11192', 'pm_score': 4, 'selected': False, 'text': '<p>Nope, that is the only formula for the centroid of a collection of points. See Wikipedia: <a href="http://en.wikipedia.org/wiki/Centroid" rel="noreferrer">http://en.wikipedia.org/wiki/Centroid</a></p>\n'}, {'answer_id': 77985, 'author': 'Dima', 'author_id': 13313, 'author_profile': 'https://Stackoverflow.com/users/13313', 'pm_score': -1, 'selected': False, 'text': '<p>You got it. What you are calculating is the centroid, or the mean vector.</p>\n'}, {'answer_id': 77997, 'author': 'Sarien', 'author_id': 1994377, 'author_profile': 'https://Stackoverflow.com/users/1994377', 'pm_score': 0, 'selected': False, 'text': '<p>A "more accurate centroid" I believe centroid is defined the way you calculated it hence there can be no "more accurate centroid".</p>\n'}, {'answer_id': 78046, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>you can use increase accuracy summation - Kahan summation - was that what you had in mind? </p>\n'}, {'answer_id': 78058, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Yes that is the correct formula.</p>\n\n<p>If you have a large number of points you can exploit the symmetry of the problem (be it cylindrical, spherical, mirror). Otherwise, you can borrow from statistics and average a random number of the points and just have a bit of error.</p>\n'}, {'answer_id': 85787, 'author': 'Gregg Lind', 'author_id': 15842, 'author_profile': 'https://Stackoverflow.com/users/15842', 'pm_score': 2, 'selected': False, 'text': "<p>Potentially more efficient: if you're calculating this multiple times, you can speed this up quite a bit by keeping two standing variables </p>\n\n<pre><code>N # number of points\nsums = dict(x=0,y=0,z=0) # sums of the locations for each point\n</code></pre>\n\n<p>then changing N and sums whenever points are created or destroyed. This changes things from O(N) to O(1) for calculations at the cost of more work every time a point is created, moves, or is destroyed. </p>\n"}, {'answer_id': 88394, 'author': 'AlejoHausner', 'author_id': 14309, 'author_profile': 'https://Stackoverflow.com/users/14309', 'pm_score': 4, 'selected': False, 'text': '<p>You vaguely mention "a way to get a more accurate centroid". Maybe you\'re talking about a centroid that isn\'t affected by outliers. For example, the <i>average</i> household income in the USA is probably very high, because a small number of <i>very</i> rich people skew the average; they are the "outliers". For that reason, statisticians use the <i>median</i> instead. One way to obtain the median is to sort the values, then pick the value halfway down the list.\n<p>\nMaybe you\'re looking for something like this, but for 2D or 3D points. The problem is, in 2D and higher, you can\'t sort. There\'s no natural order. Nevertheless, there are ways to get rid of outliers.\n<p>\nOne way is to find the <a href="http://en.wikipedia.org/wiki/Convex_hull" rel="noreferrer">convex hull</a> of the points. The convex hull has all the points on the "outside" of the set of points. If you do this, and throw out the points that are on the hull, you\'ll be throwing out the outliers, and the points that remain will give a more "representative" centroid. You can even repeat this process several times, and the result is kind like peeling an onion. In fact, it\'s called "convex hull peeling".\n<p></p>\n'}, {'answer_id': 37780869, 'author': 'Chris', 'author_id': 454063, 'author_profile': 'https://Stackoverflow.com/users/454063', 'pm_score': 5, 'selected': True, 'text': '<p>Contrary to the common refrain here, there are different ways to define (and calculate) a center of a point cloud. The first and most common solution has been suggested by you already and I will <strong>not</strong> argue that there is anything wrong with this:</p>\n\n<p><code>centroid = average(x), average(y), average(z)</code></p>\n\n<p>The "problem" here is that it will "distort" your center-point depending on the distribution of your points. If, for example, you assume that all your points are within a cubic box or some other geometric shape, but most of them happen to be placed in the upper half, your center-point will also shift in that direction.</p>\n\n<p>As an alternative you could use the mathematical middle (the mean of the extrema) in each dimension to avoid this:</p>\n\n<p><code>middle = middle(x), middle(y), middle(z)</code></p>\n\n<p>You can use this when you don\'t care much about the number of points, but more about the global bounding box, because that\'s all this is - the center of the bounding box around your points.</p>\n\n<p>Lastly, you could also use the <code>median</code> (the element in the middle) in each dimension:</p>\n\n<p><code>median = median(x), median(y), median(z)</code></p>\n\n<p>Now this will sort of do the opposite to the <code>middle</code> and actually help you ignore outliers in your point cloud and find a centerpoint <strong>based on</strong> the distribution of your points.</p>\n\n<p>A more and robust way to find a "good" centerpoint might be to ignore the top and bottom 10% in each dimension and then calculate the <code>average</code> or <code>median</code>. As you can see you can define the centerpoint in different ways. Below I am showing you examples of 2 2D point clouds with these suggestions in mind.</p>\n\n<p>The dark blue dot is the average (mean) centroid.\nThe median is shown in green.\nAnd the middle is shown in red.\nIn the second image you will see exactly what I was talking about earlier: The green dot is "closer" to the densest part of the point cloud, while the red dot is further way from it, taking into account the most extreme boundaries of the point cloud.</p>\n\n<p><a href="https://i.stack.imgur.com/8qSQA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8qSQA.png" alt="enter image description here"></a>\n<a href="https://i.stack.imgur.com/iZSSi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/iZSSi.png" alt="enter image description here"></a></p>\n'}, {'answer_id': 66577393, 'author': 'Mello', 'author_id': 12392216, 'author_profile': 'https://Stackoverflow.com/users/12392216', 'pm_score': 0, 'selected': False, 'text': '<p>If your <strong>n-dimensional</strong> vector is in a list <strong>[[a0, a1, ..., an],[b0, b1, ..., bn],[c0, c1, ..., cn]]</strong>, just convert the list to array, and than calculate the centroid like this:</p>\n<pre><code>import numpy as np\n\nvectors = np.array(Listv)\ncentroid = np.mean(vectors, axis=0)\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77936', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/676/'] |
77,954 | <p>How do you get Perl to stop and give a stack trace when you reference an undef value, rather than merely warning? It seems that <code>use strict;</code> isn't sufficient for this purpose.</p>
| [{'answer_id': 77969, 'author': 'Neil', 'author_id': 14193, 'author_profile': 'https://Stackoverflow.com/users/14193', 'pm_score': 2, 'selected': False, 'text': '<p>Include this:</p>\n\n<pre><code>use Carp ();\n</code></pre>\n\n<p>Then include <em>one</em> of these lines at the top of your source file:</p>\n\n<pre><code>local $SIG{__WARN__} = \\&Carp::confess;\nlocal $SIG{__WARN__} = \\&Carp::cluck;\n</code></pre>\n\n<p>The <code>confess</code> line will give a stack trace, and the <code>cluck</code> line is much more terse.</p>\n'}, {'answer_id': 77971, 'author': 'cjm', 'author_id': 8355, 'author_profile': 'https://Stackoverflow.com/users/8355', 'pm_score': 5, 'selected': True, 'text': "<pre><code>use warnings FATAL => 'uninitialized';\n\nuse Carp ();\n$SIG{__DIE__} = \\&Carp::confess;\n</code></pre>\n<p>The first line makes the warning fatal. The next two cause a stack trace when your program dies.</p>\n<p>See also <code>man 3pm warnings</code> for more details.</p>\n"}, {'answer_id': 77972, 'author': 'mopoke', 'author_id': 14054, 'author_profile': 'https://Stackoverflow.com/users/14054', 'pm_score': 1, 'selected': False, 'text': "<p>Referencing an undef value wouldn't be a problem in itself, but it may cause warnings if your code is expecting it to be something other than undef. (particularly if you're trying to use that variable as an object reference).\nYou could put something in your code such as:</p>\n\n<pre><code>use Carp qw();\n\n[....]\n\nCarp::confess '$variableName is undef' unless defined $variableName;\n\n[....]\n</code></pre>\n"}, {'answer_id': 77980, 'author': 'zigdon', 'author_id': 4913, 'author_profile': 'https://Stackoverflow.com/users/4913', 'pm_score': 2, 'selected': False, 'text': '<p>One way to make those warnings fatal is to install a signal handler for the <strong>WARN</strong> virtual-signal:</p>\n\n<pre><code>$SIG{__WARN__} = sub { die "Undef value: @_" if $_[0] =~ /undefined/ };\n</code></pre>\n'}, {'answer_id': 78239, 'author': 'Aristotle Pagaltzis', 'author_id': 9410, 'author_profile': 'https://Stackoverflow.com/users/9410', 'pm_score': 4, 'selected': False, 'text': '<p>Instead of the messy fiddling with <code>%SIG</code> proposed by everyone else, just <code>use <a href="http://search.cpan.org/perldoc?Carp::Always" rel="noreferrer">Carp::Always</a></code> and be done.</p>\n\n<p>Note that you can inject modules into a script without source modifications simply by running it with <code>perl -MCarp::Always</code>; furthermore, you can set the <code>PERL5OPT</code> environment variable to <code>-MCarp::Always</code> to have it loaded without even changing the invocation of the script. (See <a href="http://p3rl.org/run" rel="noreferrer"><code>perldoc perlrun</code></a>.)</p>\n'}, {'answer_id': 5873113, 'author': 'user736584', 'author_id': 736584, 'author_profile': 'https://Stackoverflow.com/users/736584', 'pm_score': 0, 'selected': False, 'text': '<p>You have to do this manually. The above "answers" do not work! Just test out this:</p>\n\n<pre><code>use strict;\nuse warnings FATAL => \'uninitialized\';\nuse Carp ();\n$SIG{__DIE__} = \\&Carp::confess;\n\nmy $x = undef; # it would be enough to say my $x;\nif (!$x->{test}) {\nprint "no warnings, no errors\\n";\n}\n</code></pre>\n\n<p>You will see that dereferencing did not cause any error messages or warnings. I know of no way of causing Perl to automatically detecting the use of undef as an invalid reference. I suspect this is so by design, so that autovivification works seamlessly.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77954', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14193/'] |
77,957 | <p>I'm using Visual Studio 2008 for an ASP .Net application, and Visual Studio keeps adding blank lines to my aspx file whenever I save, switch to design mode and back to code view, switch to split mode, or switch between files. Before I save, I will have:</p>
<pre><code> </ContentTemplate></asp:UpdatePanel>
</ContentTemplate>
</ajax:TabPanel>
</ajax:TabContainer>
</code></pre>
<p>Then, it will magically transform into:</p>
<pre><code> </ContentTemplate></asp:UpdatePanel>
</ContentTemplate>
</ajax:TabPanel>
</ajax:TabContainer>
</code></pre>
<p>I know it's mostly an aesthetics issue, but it's also adding 17 lines of nothing to each tab container (and making the file that much longer to scroll through) and it's very annoying. I've checked that I don't have a misplaced quotation mark, there's no misaligned tags earlier in the file, any ideas?</p>
| [{'answer_id': 78486, 'author': 'LizB', 'author_id': 13616, 'author_profile': 'https://Stackoverflow.com/users/13616', 'pm_score': 0, 'selected': False, 'text': "<p>I can't say I've ever experience this with any Visual Studio yet, but try this</p>\n\n<p><strong>Ctrl-E, D</strong> command will automatically reformat the document. (Assuming C# Development Enviroment)</p>\n\n<p><strong>Ctrl-K, Ctrl-D</strong> for Web Development Enviroment</p>\n\n<p>If the document remains as it is with the incorrect spacing then the auto format is the problem. Simple disable the auto-format inside <strong>Options</strong>-><strong>Text Editors</strong>-><strong>HTML</strong>-><strong>Formatting</strong></p>\n"}, {'answer_id': 78562, 'author': 'tbreffni', 'author_id': 637, 'author_profile': 'https://Stackoverflow.com/users/637', 'pm_score': 3, 'selected': True, 'text': "<p>The only time I've seen Visual Studio do something close to this is when the XML/HTML in question is invalid, for example you are missing a closing tag somewhere.</p>\n"}, {'answer_id': 3225944, 'author': 'lauren', 'author_id': 388677, 'author_profile': 'https://Stackoverflow.com/users/388677', 'pm_score': 0, 'selected': False, 'text': '<p>For reasons unknown tab container appears to temporarily render in design environment with long string which seems to cause insertion of blank lines with default settings. Turing off the tag wrapping, seemed to work for me.</p>\n\n<p>Tool/Options/</p>\n\n<p>[Show all settings]</p>\n\n<p>Text Editor/HTML</p>\n\n<p>Wrap tags when exceeding specified lenght</p>\n\n<p>If any interested.</p>\n'}, {'answer_id': 56666421, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>I had the same problem and none of the previous answers here solved it; but I found the solution here: <a href="https://github.com/Microsoft/vscode/issues/12076" rel="nofollow noreferrer">https://github.com/Microsoft/vscode/issues/12076</a>. Go to the <strong>.editor.config</strong> file and set <strong>insert_final_newline = false</strong> (or simply remove that line).</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77957', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13208/'] |
77,960 | <p>I recently came across a ASP 1.1 web application that put a whole heap of stuff in the session variable - including all the DB data objects and even the DB connection object. It ends up being huge. When the web session times out (four hours after the user has finished using the application) sometimes their database transactions get rolled back. I'm assuming this is because the DB connection is not being closed properly when IIS kills the session.</p>
<p>Anyway, my question is what should be in the session variable? Clearly some things need to be in there. The user selects which plan they want to edit on the main screen, so the plan id goes into the session variable. Is it better to try and reduce the load on the DB by storing all the details about the user (and their manager etc.) and the plan they are editing in the session variable or should I try to minimise the stuff in the session variable and query the DB for everything I need in the Page_Load event?</p>
| [{'answer_id': 77991, 'author': 'cori', 'author_id': 8151, 'author_profile': 'https://Stackoverflow.com/users/8151', 'pm_score': 4, 'selected': True, 'text': "<p>This is pretty hard to answer because it's so application-specific, but here are a few guidelines I use:</p>\n\n<ol>\n<li>Put as little as possible in the session.</li>\n<li>User-specific selections that should only last during a given visit are a good choice</li>\n<li>often, variables that need to be accessible to multiple pages throughout the user's visit to your site (to avoid passing them from page to page) are also good to put in the session.</li>\n</ol>\n\n<p>From what little you've said about your application, I'd probably select your data from the db and try to find ways to minimize the impact of those queries instead of loading down the session.</p>\n"}, {'answer_id': 77995, 'author': 'Darren Kopp', 'author_id': 77, 'author_profile': 'https://Stackoverflow.com/users/77', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://blogs.msdn.com/tess/archive/2008/05/28/asp-net-memory-thou-shalt-not-store-ui-objects-in-cache-or-session-scope.aspx" rel="nofollow noreferrer"><strong>DO NOT</strong> put UI objects in session.</a></p>\n\n<p>beyond that, i\'d say it varies. too much in session can slow you down if you aren\'t using the in process session because you are going to be serializing a lot + the speed of the provider. Cache and Session should be used sparingly and carefully. Don\'t just put in session because you can or is convenient. Sit down and analyze if it makes sense.</p>\n'}, {'answer_id': 78000, 'author': 'Jonathan Rupp', 'author_id': 12502, 'author_profile': 'https://Stackoverflow.com/users/12502', 'pm_score': 3, 'selected': False, 'text': "<p>Do <strong>not</strong> put database connection information in the session.</p>\n\n<p>As far as caching, I'd avoid using the session for caching if possible -- you'll run into issues where someone else changes the data a user is using, plus you can't share the cached data between users. Use the ASP.NET Cache, or some other caching utility (like Memcached or Velocity).</p>\n\n<p>As far as what <strong>should</strong> go in the session, anything that applies to <strong>all</strong> browser windows a user has open to your site (login, security settings, etc.) should be in the session. Things like what object is being viewed/edited should really be GET/POST variables passed around between the screens so a user can use multiple browser windows to work with your application (unless you'd like to prevent that).</p>\n"}, {'answer_id': 78001, 'author': 'pix0r', 'author_id': 72, 'author_profile': 'https://Stackoverflow.com/users/72', 'pm_score': 0, 'selected': False, 'text': '<p>A <a href="https://stackoverflow.com/questions/77826/php-session-what-are-the-pros-and-cons-of-storing-temporarily-used-data-in-the">very similar question</a> was asked regarding PHP sessions earlier. Basically, Sessions are a great place to store user-specific data that you need to access across several page loads. Sessions are NOT a great place to store database connection references; you\'d be better to use some sort of connection pooling software or open/close your connection on each page load. As far as caching data in the session, this depends on how session data is being stored, how much security you need, and whether or not the data is specific to the user. A better bet would be to use something else for caching data.</p>\n'}, {'answer_id': 78009, 'author': 'Jimmy', 'author_id': 4435, 'author_profile': 'https://Stackoverflow.com/users/4435', 'pm_score': 0, 'selected': False, 'text': '<p>storing navigation cues in sessions is tricky. The same user can have multiple windows open and then changes get propagated in a confusing manner. DB connections should <em>definitely</em> not be stored. ASP.NET maintains the connection pool for you, no need to resort to your own sorcery. If you need to cache stuff for short periods and the data set size is relatively small, look into ViewState as a possible option (at the cost of loading more bulk onto the page size) </p>\n'}, {'answer_id': 78011, 'author': 'Oli', 'author_id': 12870, 'author_profile': 'https://Stackoverflow.com/users/12870', 'pm_score': 0, 'selected': False, 'text': "<p>A: Data that is only relative to one user. IE: a username, a user ID. At <strong>most</strong> an object representing a user. Sometimes URL-relative data (like where to take somebody) or an error message stack are useful to push into the session.</p>\n\n<p>If you want to share stuff potentially between different users, use the Application store or the Cache. They're far superior.</p>\n"}, {'answer_id': 78042, 'author': 'Danimal', 'author_id': 2757, 'author_profile': 'https://Stackoverflow.com/users/2757', 'pm_score': 0, 'selected': False, 'text': '<p>Stephen,<br />\nDo you work for a company that starts with "I", that has a website that starts with "BC"? That sounds exactly like what I did when I first started developing in .net (and was young and stupid) -- I crammed everything I could think of in session and application. Needless to say, that was double-plus ungood.<br />\nIn general, eschew session as much as possible. Certainly, non-serializable objects shouldn\'t be stored there (database connections and such), but even big, serializable objects shouldn\'t be either. You just don\'t want the overhead.</p>\n'}, {'answer_id': 78055, 'author': 'JohnFx', 'author_id': 30018, 'author_profile': 'https://Stackoverflow.com/users/30018', 'pm_score': 1, 'selected': False, 'text': "<p>Ideally, the session in ASP should store the least amount of data that you can get away with. Storing a reference to any object that is holding system resources open (particularly a database connection) is a definite scalability killer. Also, storing uncommitted data in a session variable is just a bad idea in most cases. Overall it sounds like the current implementation is abusively using session objects to try and simulate a stateful application in a supposedly stateless environment. </p>\n\n<p>Although it is much maligned, the ASP.NET model of managing state automatically through hidden fields should really eliminate the majority of the need to keep anything in session variables.</p>\n\n<p>My rule of thumb is that the more scalable (in terms of users/hits) that the app needs to be, the less you can get away with using session state. There is, however, a trade-off. For web applications where the user is repeatedly accessing the same data and typically has a fairly long session per use of the site, some caching (if necessary in session objects) can actually help scalability by reducing the load on the DB server. The idea here is that it is much cheaper and less complex to farm the presentation layer than the back-end DB. Of course, with all things, this advice should be taken in moderation and doesn't apply in all situations, but for a fairly simple in-house CRUD app, it should serve you well.</p>\n"}, {'answer_id': 125693, 'author': 'Aravind', 'author_id': 19536, 'author_profile': 'https://Stackoverflow.com/users/19536', 'pm_score': 0, 'selected': False, 'text': '<p>I would always keep very little information in session. Sessions use server memory resources which is expensive. Saving too many values in session increases the load on server and eventualy the performance of the site will go down. When you use load balance servers, usage of session can run into problems. So what I do is use minimal or no sessions, use cookies if the information is not very critical, use hidden fields more and database sessions.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77960', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
77,982 | <p>How can I dismiss dialog in Cocoa application when user presses Esc or Enter key? I have OK button, is it possible to make it default button?</p>
| [{'answer_id': 78110, 'author': 'Chris Hanson', 'author_id': 714, 'author_profile': 'https://Stackoverflow.com/users/714', 'pm_score': 4, 'selected': True, 'text': '<p>If you present the alert panel using the <a href="http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSAlert_Class/Reference/Reference.html" rel="noreferrer"><code>NSAlert</code></a> class or, <code>NSRunAlertPanel</code> family of functions, or the <code>NSBeginAlertSheet</code> family of functions, you will get support for default and cancel buttons automatically.</p>\n\n<p>If you\'re presenting a sheet that needs OK/Cancel buttons, and you\'re not using any of the above, you should be able to assign your buttons appropriate keyboard equivalents in Interface Builder using the attributes inspector. (Just highlight the <strong>Key Equiv.</strong> area and press the key you want to be equivalent to pressing that button.)</p>\n\n<p>If you\'re presenting a dialog that\'s not either an alert or a document/window-modal sheet — don\'t. :) Document-modal alerts aren\'t Mac-like, and shouldn\'t be used for things like preferences windows.</p>\n'}, {'answer_id': 61266602, 'author': 'Kergorian', 'author_id': 2216361, 'author_profile': 'https://Stackoverflow.com/users/2216361', 'pm_score': 0, 'selected': False, 'text': '<p>Just assign the "escapeKey" or "cancelKey" in the IB in the property "key equivalent" for the buttons you want and it will work fine. Also if you assign that keys the buttons gets a different highlighting.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77982', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14131/'] |
77,990 | <p>How do some programs edit whats being displayed on the terminal (to pick a random example, the program 'sl')? I'm thinking of the Linux terminal here, it may happen in other OS's too, I don't know. I've always thought once some text was displayed, it stayed there. How do you change it without redrawing the entire screen? </p>
| [{'answer_id': 78007, 'author': 'Sarien', 'author_id': 1994377, 'author_profile': 'https://Stackoverflow.com/users/1994377', 'pm_score': 2, 'selected': False, 'text': '<p>There are characters that can be sent to the terminal that move the cursor back. Then text can be overwritten.</p>\n\n<p>There is a list <a href="http://ascii-table.com/ansi-escape-sequences-vt-100.php" rel="nofollow noreferrer">here</a>. Note the "move cursor something" lines.</p>\n'}, {'answer_id': 78017, 'author': 'deemer', 'author_id': 11192, 'author_profile': 'https://Stackoverflow.com/users/11192', 'pm_score': 2, 'selected': False, 'text': '<p>If you terminate a line sent to the terminal with a carriage return (\'\\r\') instead of a linefeed (\'\\n\'), it will move the cursor to the beginning of the current line, allowing the program to print more text over top of what it printed before. I use this occasionally for progress messages for long tasks.</p>\n\n<p>If you ever need to do more terminal editing than that, use <a href="http://www.gnu.org/software/ncurses/ncurses.html" rel="nofollow noreferrer">ncurses</a> or a variant thereof.</p>\n'}, {'answer_id': 78028, 'author': 'pix0r', 'author_id': 72, 'author_profile': 'https://Stackoverflow.com/users/72', 'pm_score': 0, 'selected': False, 'text': '<p>To build on @Corporal Touchy\'s answer, there are libraries available that will handle some of this functionality for you such as <a href="http://en.wikipedia.org/wiki/Curses_(programming_library)" rel="nofollow noreferrer">curses/ncurses</a></p>\n'}, {'answer_id': 78039, 'author': 'mana', 'author_id': 12016, 'author_profile': 'https://Stackoverflow.com/users/12016', 'pm_score': 3, 'selected': False, 'text': '<p>try this shellscript </p>\n\n<pre><code>#!/bin/bash\ni=1\nwhile [ true ]\n do\n echo -e -n "\\r $i"\n i=$((i+1))\n done\n</code></pre>\n\n<p>the -n options prevents the newline ... and the \\r does the carriage return ... you write again and again into the same line - no scroling or what so ever</p>\n'}, {'answer_id': 78041, 'author': 'danio', 'author_id': 12663, 'author_profile': 'https://Stackoverflow.com/users/12663', 'pm_score': 1, 'selected': False, 'text': '<p>Corporal Touchy has answered how this is done at the lowest level. For easier development the <a href="http://www.manpagez.com/man/3/ncurses/" rel="nofollow noreferrer">curses library</a> gives a higher level of control than simply sending characters to the terminal. </p>\n'}, {'answer_id': 78050, 'author': 'Mike Tunnicliffe', 'author_id': 13956, 'author_profile': 'https://Stackoverflow.com/users/13956', 'pm_score': 4, 'selected': True, 'text': '<p>Many applications make use of the <a href="http://en.wikipedia.org/wiki/Curses_(programming_library)" rel="noreferrer">curses</a> library, or some language binding to it.</p>\n\n<p>For rewriting on a single line, such as updating progress information, the special character "<a href="http://en.wikipedia.org/wiki/Carriage_return" rel="noreferrer">carriage return</a>", often specified by the escape sequence "\\r", can return the cursor to the start of the current line allowing subsequent output to overwrite what was previously written there.</p>\n'}, {'answer_id': 78051, 'author': 'Jacob Krall', 'author_id': 3140, 'author_profile': 'https://Stackoverflow.com/users/3140', 'pm_score': 1, 'selected': False, 'text': '<p>NCurses is a cross-platform library that lets you draw user interfaces on smart terminals.</p>\n'}, {'answer_id': 78073, 'author': 'Adam Pierce', 'author_id': 5324, 'author_profile': 'https://Stackoverflow.com/users/5324', 'pm_score': 0, 'selected': False, 'text': '<p>I agree with danio, ncurses is the way to go. Here\'s a good tutorial:</p>\n\n<p><a href="http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/" rel="nofollow noreferrer">http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/</a></p>\n'}, {'answer_id': 2222556, 'author': 'Yamodax', 'author_id': 268321, 'author_profile': 'https://Stackoverflow.com/users/268321', 'pm_score': 3, 'selected': False, 'text': '<p>Depending on the terminal you send control seuqences. Common sequences are for example esc[;H to send the cursor to a specific position (e.g. on Ansi, Xterm, Linux, VT100). However, this will vary with the type or terminal the user has ... curses (in conjunction with the terminfo files) will wrap that information for you.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77990', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14210/'] |
77,993 | <p>We are using a software program at our school to enter IEPs (Individualized Education Programs). When entering goals and objectives for a student, users are provided with a Save and a Close button. Close is meant for users not wishing to save the goal they just chose. However, our users are sometimes wanting to back out of the screen and close the Window by clicking on the X in the upper right hand corner. Unfortunately, this somehow corrupts data and the user has difficulty later entering goals. The software company tells us to educate our staff not to click on the X and that there is no way to disable it. The software is web-based and our school has standardized on IE7.</p>
| [{'answer_id': 78027, 'author': 'Christian P.', 'author_id': 9479, 'author_profile': 'https://Stackoverflow.com/users/9479', 'pm_score': 0, 'selected': False, 'text': "<p>A lot of browsers have a full-screen mode (F11 in Firefox), where they take up the entire screen real estate, hiding any other UI elements, including the top bar (at least for Windows, dunno about *nix). This is a very simple solution, but afaik there's no way to disable the [x] for windows in general, you'd have to find a browser that does not use the default Windows look and doesn't implement it's own [x] in the corner.</p>\n"}, {'answer_id': 78032, 'author': 'Mark Brackett', 'author_id': 2199, 'author_profile': 'https://Stackoverflow.com/users/2199', 'pm_score': 1, 'selected': False, 'text': '<p>If it\'s web based, then you\'re probably just running a webpage in Internet Explorer. If that\'s the case, I\'d recommend <a href="http://samanathon.com/internet-explorer-7s-kiosk-mode/" rel="nofollow noreferrer">IE\'s kiosk mode</a>.</p>\n\n<p>If you need something a bit more heavyweight, <a href="http://www.teamsoftwaresolutions.com" rel="nofollow noreferrer">Public Web Browser</a> is a good and cheap choice that I\'ve had good experiences with.</p>\n'}, {'answer_id': 78037, 'author': 'jamuraa', 'author_id': 9805, 'author_profile': 'https://Stackoverflow.com/users/9805', 'pm_score': 1, 'selected': False, 'text': '<p>There is no way to disable the close button on the window (can you imagine!? ad popups that never go away! eek!). </p>\n\n<p>However, you can catch it and do something useful (like click the "close" button on the form). See: \n<a href="http://blogs.x2line.com/al/archive/2004/09/15/561.aspx" rel="nofollow noreferrer">http://blogs.x2line.com/al/archive/2004/09/15/561.aspx</a></p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77993', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
77,996 | <p>Is it possible to create custom events in C++? For example, say I have the variable X, and the variable Y. Whenever X changes, I would like to execute a function that sets Y equal to 3X. Is there a way to create such a trigger/event? (triggers are common in some databases)</p>
| [{'answer_id': 78013, 'author': 'epatel', 'author_id': 842, 'author_profile': 'https://Stackoverflow.com/users/842', 'pm_score': 1, 'selected': False, 'text': '<p>Think you should read a little about <a href="http://en.wikipedia.org/wiki/Design_pattern_(computer_science)" rel="nofollow noreferrer">Design Patterns</a>, specifically the <a href="http://en.wikipedia.org/wiki/Observer_pattern" rel="nofollow noreferrer">Observer Pattern</a>.</p>\n\n<p>Qt from <a href="http://trolltech.com/" rel="nofollow noreferrer">Trolltech</a> have implemented a nice solutions they call <a href="http://www.youtube.com/watch?v=yPhbgrApNx0" rel="nofollow noreferrer">Signals and Slots</a>.</p>\n'}, {'answer_id': 78016, 'author': 'slf', 'author_id': 13263, 'author_profile': 'https://Stackoverflow.com/users/13263', 'pm_score': 1, 'selected': False, 'text': '<p>Use the Observer pattern</p>\n\n<p><a href="http://www.codeproject.com/KB/cpp/CppEvents.aspx" rel="nofollow noreferrer">code project example</a></p>\n\n<p><a href="http://en.wikipedia.org/wiki/Observer_pattern" rel="nofollow noreferrer">wiki page</a></p>\n'}, {'answer_id': 78025, 'author': 'Denice', 'author_id': 14178, 'author_profile': 'https://Stackoverflow.com/users/14178', 'pm_score': 1, 'selected': False, 'text': "<p>As far as I am aware you can't do it with default variables, however if you wrote a class that took a callback function you could let other classes register that they want to be notified of any changes.</p>\n"}, {'answer_id': 78135, 'author': 'Adam Wright', 'author_id': 1200, 'author_profile': 'https://Stackoverflow.com/users/1200', 'pm_score': 3, 'selected': False, 'text': '<p>This is basically an instance of the Observer pattern (as others have mentioned and linked). However, you can use template magic to render it a little more syntactically palettable. Consider something like...</p>\n\n<pre><code>template <typename T>\nclass Observable\n{\n T underlying;\n\npublic:\n Observable<T>& operator=(const T &rhs) {\n underlying = rhs;\n fireObservers();\n\n return *this;\n }\n operator T() { return underlying; }\n\n void addObserver(ObsType obs) { ... }\n void fireObservers() { /* Pass every event handler a const & to this instance /* }\n};\n</code></pre>\n\n<p>Then you can write...</p>\n\n<pre><code>Observable<int> x;\nx.registerObserver(...);\n\nx = 5;\nint y = x;\n</code></pre>\n\n<p>What method you use to write your observer callback functions are entirely up to you; I suggest <a href="http://www.boost.org" rel="noreferrer">http://www.boost.org</a>\'s function or functional modules (you can also use simple functors). I also caution you to be careful about this type of operator overloading. Whilst it can make certain coding styles clearer, reckless use an render something like</p>\n\n<p>seemsLikeAnIntToMe = 10;</p>\n\n<p>a <em>very</em> expensive operation, that might well explode, and cause debugging nightmares for years to come.</p>\n'}, {'answer_id': 78863, 'author': 'Doug T.', 'author_id': 8123, 'author_profile': 'https://Stackoverflow.com/users/8123', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://www.boost.org/doc/libs/1_36_0/doc/html/signals.html" rel="nofollow noreferrer">Boost signals</a> is another commonly used library you might come across to do Observer Pattern (aka Publish-Subscribe). Buyer beware here, I\'ve heard its performance is terrible.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/77996', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13790/'] |
78,004 | <p>I intend to develop a system that is entirely based on modules. The system base should have support for finding out about plugins, starting them up and being able to provide ways for those modules to communicate. Ideally, one should be able to put in new modules and yank out unused modules at will, and modules should be able to use each other's funcionality if it is available.</p>
<p>This system should be used as a basis for simulation systems where a lot of stuff happens in different modules, and other modules might want to do something based on that.</p>
<p>The system I intend to develop is going to be in Java. The way I see it, I intend to have a folder with a subfolder for each module that includes a XML that describes the module with information such as name, maybe which events it might raise, stuff like that. I suppose I might need to write a custom ClassLoader to work this stuff out.</p>
<p>The thing is, I don't know if my idea actually holds any water and, of course, I intend on building a working prototype. However, I never worked on a truly modular system before, and I'm not really sure what is the best way to take on this problem.</p>
<p>Where should I start? Are there common problems and pitfalls that are found while developing this kind of system? How do I make the modules talk with each other while maintaining isolation (i.e, you remove a module and another module that was using it stays sane)? Are there any guides, specifications or articles I can read that could give me some ideas on where to start? It would be better if they were based on Java, but this is not a requirement, as what I'm looking for right now are ideas, not code.</p>
<p>Any feedback is appreciated.</p>
| [{'answer_id': 78031, 'author': 'Joe Skora', 'author_id': 14057, 'author_profile': 'https://Stackoverflow.com/users/14057', 'pm_score': 2, 'selected': False, 'text': '<p>Without getting into great detail, you should be looking at <a href="http://springframework.org/" rel="nofollow noreferrer">Spring</a> and a familiarization with OSGI or the Eclipse RCP frameworks will also give you some fundamental concepts you will need to keep in mind.</p>\n'}, {'answer_id': 78047, 'author': 'Patrick Desjardins', 'author_id': 13913, 'author_profile': 'https://Stackoverflow.com/users/13913', 'pm_score': 1, 'selected': False, 'text': '<p>They are many way to do it but something simple can be by using Reflection. You write in your XML file name of file (that would be a class in reallity). You can than check what type is it and create it back with reflection. The class could have a common Interface that will let you find if the external file/class is really one of your module. Here is some information about <a href="http://java.sun.com/docs/books/tutorial/reflect/index.html" rel="nofollow noreferrer">Reflexion</a>.</p>\n\n<p>You can also use a precoded framework like this SourceForge one<a href="http://sourceforge.net/projects/javasps/" rel="nofollow noreferrer">link text</a> that will give you a first good step to create module/plugin.</p>\n'}, {'answer_id': 78063, 'author': 'Alexander Klimetschek', 'author_id': 2709, 'author_profile': 'https://Stackoverflow.com/users/2709', 'pm_score': 4, 'selected': True, 'text': '<p>You should definitely look at <a href="http://www2.osgi.org/Specifications/HomePage" rel="noreferrer">OSGi</a>. It aims at being <em>the</em> component/plugin mechanism for Java. It allows you to modularize your code (in so-called bundles) and update bundles at runtime. You can also completely hide implementation packages from unwanted access by other bundles, eg. only provide the API.</p>\n\n<p>Eclipse was the first major open-source project to implement and use OSGi, but they didn\'t fully leverage it (no plugin installations/updates without restarts). If you start from scratch though, it will give you a very good framework for a plugin system.</p>\n\n<p><a href="http://felix.apache.org" rel="noreferrer">Apache Felix</a> is a complete open-source implementation (and there are others, such as <a href="http://www.eclipse.org/equinox/" rel="noreferrer">Eclipse Equinox</a>).</p>\n'}, {'answer_id': 78247, 'author': 'John Meagher', 'author_id': 3535, 'author_profile': 'https://Stackoverflow.com/users/3535', 'pm_score': 2, 'selected': False, 'text': '<p>Another option is the <a href="http://java.sun.com/javase/6/docs/api/java/util/ServiceLoader.html" rel="nofollow noreferrer">ServiceLoader</a> added in Java 1.6. </p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78004', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
78,018 | <p>In our development environment each developer has their own dev server. Often times they do not actually develop on that server but develop from their local machine, deploy to their dev server, and then attach with the remote debugger to do debugging.</p>
<p>My question is; how can I use MSBuild to execute a different set of tasks for each user?</p>
<p>I want to enable each user to define their own build process with MSBuild tasks but I don't want that to necessarily affect the other developers. I also want a default set of tasks to execute if a given user explicitly defined their own process.</p>
<p>Example:</p>
<ul>
<li>SomeProj.csproj
<ul>
<li>Default MS Build process is to copy to test server or staging server</li>
<li>Custom process for Steve is to copy to Steve's dev server</li>
<li>Custom process for Eric is to copy to Eric's dev server</li>
</ul></li>
</ul>
| [{'answer_id': 78067, 'author': 'slf', 'author_id': 13263, 'author_profile': 'https://Stackoverflow.com/users/13263', 'pm_score': 3, 'selected': True, 'text': '<p>You could use the project user file (*.suo / *.user) to do some \'poor mans dependency injection\'.</p>\n\n<p><a href="http://ahmed0192.blogspot.com/2006/11/customize-msbuild-without-modifying.html" rel="nofollow noreferrer">looks like this guy did something similar</a></p>\n'}, {'answer_id': 102482, 'author': 'Jay Bazuzi', 'author_id': 5314, 'author_profile': 'https://Stackoverflow.com/users/5314', 'pm_score': 0, 'selected': False, 'text': "<p>Yeah, I've done this before. Try trick is to key off <code>$(USERNAME)</code> in your msbuild script. If you haven't tried editing msbuild scripts before, you've got a lot of learning to do.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78018', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3957/'] |
78,043 | <p>I'm designing a user interface for a large touchscreen device running Linux. What would be the best toolkit/developer kit/SDK to use? The only requirement is that its able to run on a semi-low performace device, and that there is a Linux version.</p>
<p>Nice-to-haves would be build in support for effects/animations and a modern look-and-feel, but they are not necessary.</p>
<p>I'm looking at Adobe Flex/AIR already, but I'm not sure if the device will meet the minimum specs.</p>
| [{'answer_id': 78054, 'author': 'mopoke', 'author_id': 14054, 'author_profile': 'https://Stackoverflow.com/users/14054', 'pm_score': 2, 'selected': False, 'text': '<p>Try QTopia (<a href="http://trolltech.com/products/qtopia" rel="nofollow noreferrer">http://trolltech.com/products/qtopia</a>)\nIt\'s from the same stable as the popular Qt desktop toolkit.</p>\n'}, {'answer_id': 78093, 'author': 'Branan', 'author_id': 13894, 'author_profile': 'https://Stackoverflow.com/users/13894', 'pm_score': 2, 'selected': False, 'text': "<p>I agree with Mopoke, QTopia is what you want.</p>\n\n<ul>\n<li><p>It has support from some graphics hardware (2d and 3d), and can also use the kernel framebuffer device if that's all you need.</p></li>\n<li><p>It's based on Qt, a very well-designed object-oriented GUI framework</p></li>\n<li><p>It's available for both open-source and commercial projects, although closed-source projects need to pay a license fee.</p></li>\n</ul>\n"}, {'answer_id': 85415, 'author': 'pjz', 'author_id': 8002, 'author_profile': 'https://Stackoverflow.com/users/8002', 'pm_score': 0, 'selected': False, 'text': '<p>QTopia is indeed a good option; others are <a href="http://www.directfb.org/" rel="nofollow noreferrer">DirectFB</a>, and of course X11 generally running <a href="http://matchbox-project.org/" rel="nofollow noreferrer">Matchbox</a>.</p>\n'}, {'answer_id': 171060, 'author': 'Nate', 'author_id': 11760, 'author_profile': 'https://Stackoverflow.com/users/11760', 'pm_score': 2, 'selected': False, 'text': '<p>You should check out whatever tool-kits are used for the <a href="http://www.chumby.com/" rel="nofollow noreferrer">Chumby</a>. It\'s a completely open-source Linux device (open schematic, open source software, etc) with a very rich user-interface (color touch-screen, builtin wifi, USB ports, etc). I believe it\'s user-submitted "applications" are Adobe Flex/Flash based but there are a variety of open "hacks" including <a href="http://www.bunniestudios.com/blog/?p=262" rel="nofollow noreferrer">a port of Quake</a> that can be easily downloaded and run.</p>\n'}, {'answer_id': 5036348, 'author': 'Torsten', 'author_id': 622366, 'author_profile': 'https://Stackoverflow.com/users/622366', 'pm_score': 2, 'selected': False, 'text': '<p>You can try <a href="http://diskohq.com" rel="nofollow">Disko</a>.</p>\n'}, {'answer_id': 5039204, 'author': 'avra', 'author_id': 368260, 'author_profile': 'https://Stackoverflow.com/users/368260', 'pm_score': 0, 'selected': False, 'text': '<p>CodeTyphon can let you easily code, visually design and cross compile GUI touch screen applications for embedded linux.</p>\n\n<p><a href="http://www.pilotlogic.com/sitejoom/index.php?option=com_content&view=article&id=96&catid=68&Itemid=147" rel="nofollow">http://www.pilotlogic.com/sitejoom/index.php?option=com_content&view=article&id=96&catid=68&Itemid=147</a></p>\n'}, {'answer_id': 6553133, 'author': 'waffleman', 'author_id': 197108, 'author_profile': 'https://Stackoverflow.com/users/197108', 'pm_score': 2, 'selected': False, 'text': '<p>Check out <a href="http://www.clutter-project.org/" rel="nofollow">Clutter.</a> </p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78043', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14204/'] |
78,045 | <p>I do work in theoretical chemistry on a high performance cluster, often involving molecular dynamics simulations. One of the problems my work addresses involves a static field of N-dimensional (typically N = 2-5) hyper-spheres, that a test particle may collide with. I'm looking to optimize (read: overhaul) the the data structure I use for representing the field of spheres so I can do rapid collision detection. Currently I use a dead simple array of pointers to an N-membered struct (doubles for each coordinate of the center) and a nearest-neighbor list. I've heard of oct- and quad- trees but haven't found a clear explanation of how they work, how to efficiently implement one, or how to then do fast collision detection with one. Given the size of my simulations, memory is (almost) no object, but cycles are.</p>
| [{'answer_id': 78104, 'author': 'Don Neufeld', 'author_id': 13097, 'author_profile': 'https://Stackoverflow.com/users/13097', 'pm_score': 0, 'selected': False, 'text': '<p>A Quad tree is a 2 dimensional tree, in which at each level a node has 4 children, each of which covers 1/4 of the area of the parent node.</p>\n\n<p>An Oct tree is a 3 dimensional tree, in which at each level a node has 8 children, each of which contains 1/8th of the volume of the parent node. Here is picture to help you visualize it: <a href="http://en.wikipedia.org/wiki/Octree" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Octree</a></p>\n\n<p>If you\'re doing N dimensional intersection tests, you could generalize this to an N tree.</p>\n\n<p>Intersection algorithms work by starting at the top of the tree and recursively traversing into any child nodes that intersect the object being tested, at some point you get to leaf nodes, which contain the actual objects.</p>\n'}, {'answer_id': 78117, 'author': 'Marcel Levy', 'author_id': 676, 'author_profile': 'https://Stackoverflow.com/users/676', 'pm_score': 1, 'selected': False, 'text': '<p>It sounds like you\'d want to implement a <a href="http://en.wikipedia.org/wiki/Kd-tree" rel="nofollow noreferrer">kd-tree,</a> which would allow you to more quickly search the N-dimensional space. There\'s some more information and links to implementations at <a href="http://www.cs.sunysb.edu/~algorith/files/kd-trees.shtml" rel="nofollow noreferrer">the Stony Brook Algorithm Repository.</a></p>\n'}, {'answer_id': 78139, 'author': 'user14273', 'author_id': 14273, 'author_profile': 'https://Stackoverflow.com/users/14273', 'pm_score': 1, 'selected': False, 'text': '<p>Since your field is static (by which I\'m assuming you mean that the hyper spheres don\'t move), then the fastest solution I know of is a Kdtree.<br>\nYou can either make your own, or use someone else\'s, like this one:\n<a href="http://libkdtree.alioth.debian.org/" rel="nofollow noreferrer">http://libkdtree.alioth.debian.org/</a></p>\n'}, {'answer_id': 81455, 'author': 'danio', 'author_id': 12663, 'author_profile': 'https://Stackoverflow.com/users/12663', 'pm_score': 2, 'selected': False, 'text': '<p>How best to approach this for your problem depends on several factors that you have not described:\n- Will the same hypersphere arrangement be used for many particle collision calculations?\n- Are the hyperspheres uniform size?\n- What is the movement of the particle (e.g. straight line/curve) and is that movement affected by the spheres?\n- Do you consider the particle to have zero volume?</p>\n\n<p>I assume that the particle does not have simple straight line movement as that would be the relatively fast calculation of finding the closest point between a line and a point, which is likely going to be about the same speed as finding which of the boxes the line intersects with (to determine where in the n-tree to examine).</p>\n\n<p>If your hypersphere positions are fixed for a lot of particle collisions then computing a <a href="http://en.wikipedia.org/wiki/Voronoi_diagram" rel="nofollow noreferrer">voronoi decomposition/Dirichlet tessellation</a> would give you a fast way of later finding exactly which sphere is closest to your particle for any given point in the space.</p>\n\n<p>However to answer your original question about octrees/quadtrees/2^n-trees, in n dimensions you start with a (hyper)-cube that contains the area of space that you are interested in. This will be subdivided into 2^n hypercubes if you deem the contents to be too complicated. This continues recursively until you have only simple elements (e.g. one hypersphere centroid) in the leaf nodes.\nNow that the n-tree is built you use it for collision detection by taking the path of your particle and intersecting it with the outer hypercube. The intersection position will tell you which hypercube in the next level down of the tree to visit next, and you determine the position of intersection with all 2^n hypercubes at that level, following downwards until you reach a leaf node. Once you reach the leaf you can examine interactions between your particle path and the hypersphere stored at that leaf. If you have collision you have finished, otherwise you have to find the exit point of the particle path from the current hypercube leaf and determine which hypercube it moves to next. Continue until you find a collision or entirely leave the overall bounding hypercube.</p>\n\n<p>Efficiently finding the neighbouring hypercube when exiting a hypercube is one of the most challenging parts of this approach. For 2^n trees Samet\'s approaches {1, 2} can be adapted. For kd-trees (binary trees) an approach is suggested in {3} section 4.3.3.</p>\n\n<p>Efficient implementation can be as simple as storing a list of 8 pointers from each hypercube to its children hypercubes, and marking the hypercube in a special way if it is a leaf (e.g. make all pointers NULL).</p>\n\n<p>A description of dividing space to create a quadtree (which you can generalise to n-tree) can be found in Klinger & Dyer {4}</p>\n\n<p>As others have mentioned kd-trees may be more suited than 2^n-trees as extension to an arbitrary number of dimensions is more straightforward, however they will result in a deeper tree. It is also easier to adapt the split positions to match the geometry of your \nhyperspheres with a kd-tree. The description above of collision detection in a 2^n tree is equally applicable to a kd-tree.</p>\n\n<p>{1} <a href="http://portal.acm.org/citation.cfm?id=322267&dl=ACM&coll=ACM" rel="nofollow noreferrer">Connected Component Labeling, Hanan Samet, Using Quadtrees Journal of the ACM Volume 28 , Issue 3 (July 1981)</a></p>\n\n<p>{2} <a href="http://portal.acm.org/citation.cfm?id=65329" rel="nofollow noreferrer">Neighbor finding in images represented by octrees, Hanan Samet, Computer Vision, Graphics, and Image Processing Volume 46 , Issue 3 (June 1989)</a></p>\n\n<p>{3} <a href="http://people.bath.ac.uk/ensab/G_mod/Distances/" rel="nofollow noreferrer">Convex hull generation, connected component labelling, and minimum distance\ncalculation for set-theoretically defined models, Dan Pidcock, 2000</a></p>\n\n<p>{4} Experiments in picture representation using regular decomposition, Klinger, A., and Dyer, C.R. E, Comptr. Graphics and Image Processing 5 (1976), 68-105.</p>\n'}, {'answer_id': 81527, 'author': 'ConcernedOfTunbridgeWells', 'author_id': 15401, 'author_profile': 'https://Stackoverflow.com/users/15401', 'pm_score': 0, 'selected': False, 'text': '<p>An octree will work as long as you can specify the spheres by their centres - it hierarchically bins points into cubic regions with eight children. Working out neighbours in an octree data structure will require you to do sphere-intersecting-cube calculations (to some extent easier than they look) to work out which cubic regions in an octree are within the sphere.</p>\n\n<p>Finding the nearest neighbours means walking back up the tree until you get a node with more than one populated child and all surrounding nodes included (this ensures the query gets all sides).</p>\n\n<p>From memory, this is the (somewhat naive) basic algorithm for sphere-cube intersection:</p>\n\n<p>i. Is the centre within the cube (this gets the eponymous situation)</p>\n\n<p>ii. Are any of the corners of the cube within radius r of the centre (corners within the sphere)</p>\n\n<p>iii. For each surface of the cube (you can eliminate some of the surfaces by working out which side of the surface the centre lies on) work out (this is all first-year vector arithmetic):</p>\n\n<p>a. A normal of the surface that goes to the centre of the sphere</p>\n\n<p>b. The distance from the centre of the sphere to the intersection of the normal with the plane of the surface (chord intersets plane the surface of the cube)</p>\n\n<p>c. Intersection of the plane lies within the side of the cube (one condition of chord intersection to the cube)</p>\n\n<p>iv. Calculate the size of the chord (Sin of Cos^-1 of ratio of normal length to radius of sphere)</p>\n\n<p>v. If the nearest point on the line is less than the distance of the chord and the point lies between the ends of the line the chord intersects one of the edges of the cube (chord intersects cube surface somewhere along one of the edges).</p>\n\n<p>Slightly dimly remembered but this is something I did for a situation involving spherical regions using an octee data structure (many years ago). You may also wish to check out KD-trees as some of the other posters suggest but your initial question sounds very similar to what I did.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78045', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
78,048 | <p>What's the best way to detect an application crash in XP (produces the same pair of 'error' windows each time - each with same window title) and then restart it?</p>
<p>I'm especially interested to hear of solutions that use minimal system resources as the system in question is quite old. </p>
<p>I had thought of using a scripting language like AutoIt (<a href="http://www.autoitscript.com/autoit3/" rel="noreferrer">http://www.autoitscript.com/autoit3/</a>), and perhaps triggering a 'detector' script every few minutes? </p>
<p>Would this be better done in Python, Perl, PowerShell or something else entirely?</p>
<p>Any ideas, tips, or thoughts much appreciated.</p>
<p>EDIT: It doesn't actually crash (i.e. exit/terminate - thanks @tialaramex). It displays a dialog waiting for user input, followed by another dialog waiting for further user input, then it actually exits. It's these dialogs that I'd like to detect and deal with.</p>
| [{'answer_id': 78095, 'author': 'Vinko Vrsalovic', 'author_id': 5190, 'author_profile': 'https://Stackoverflow.com/users/5190', 'pm_score': 3, 'selected': True, 'text': '<p>How about creating a wrapper application that launches the faulty app as a child and waits for it? If the exit code of the child indicates an error, then restart it, else exit.</p>\n'}, {'answer_id': 78242, 'author': 'Jorge Córdoba', 'author_id': 2695, 'author_profile': 'https://Stackoverflow.com/users/2695', 'pm_score': 4, 'selected': False, 'text': '<p>Best way is to use a named <a href="http://msdn.microsoft.com/en-us/library/ms684266(VS.85).aspx" rel="noreferrer">mutex</a>.</p>\n\n<ol>\n<li>Start your application.</li>\n<li>Create a new named mutex and take ownership over it</li>\n<li>Start a new process (process not thread) or a new application, what you preffer.</li>\n<li>From that process / application try to aquire the mutex. The process will block</li>\n<li>When application finish release the mutex (signal it)</li>\n<li>The "control" process will only aquire the mutex if either the application finishes or the application crashes.</li>\n<li>Test the resulting state after aquiring the mutex. If the application had crashed it will be WAIT_ABANDONED</li>\n</ol>\n\n<p><strong>Explanation:</strong> When a thread finishes without releasing the mutex any other process waiting for it can aquire it but it will obtain a WAIT_ABANDONED as return value, meaning the mutex is abandoned and therfore the state of the section it was protected can be unsafe.</p>\n\n<p>This way your second app won\'t consume any CPU cycles as it will keep waiting for the mutex (and that\'s enterely handled by the operating system)</p>\n'}, {'answer_id': 86066, 'author': 'Eclipse', 'author_id': 8701, 'author_profile': 'https://Stackoverflow.com/users/8701', 'pm_score': 2, 'selected': False, 'text': '<p>I realize that you\'re dealing with Windows XP, but for people in a similar situation under Vista, there are new <a href="http://msdn.microsoft.com/en-us/library/aa373347.aspx" rel="nofollow noreferrer">crash recovery API</a>s available. <a href="http://community.bartdesmet.net/blogs/bart/archive/2006/11/11/Windows-Vista-Application-Recovery-with-C_2300_.aspx" rel="nofollow noreferrer">Here\'s a good introduction</a> to what they can do. </p>\n'}, {'answer_id': 783527, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>I think the main problem is that Dr. Watson displays a dialog\nand keeps your process alive. </p>\n\n<p>You can write your own debugger using the Windows API and\nrun the crashing application from there. \nThis will prevent other debuggers from catching the crash of\nyour application and you could also catch the Exception event.</p>\n\n<p>Since I have not found any sample code, I have written this\nPython quick-and-dirty sample. I am not sure how robust it is\nespecially the declaration of DEBUG_EVENT could be improved.</p>\n\n<pre><code>from ctypes import windll, c_int, Structure\nimport subprocess\n\nWaitForDebugEvent = windll.kernel32.WaitForDebugEvent \nContinueDebugEvent = windll.kernel32.ContinueDebugEvent\nDBG_CONTINUE = 0x00010002L \nDBG_EXCEPTION_NOT_HANDLED = 0x80010001L\n\nevent_names = { \n 3: 'CREATE_PROCESS_DEBUG_EVENT',\n 2: 'CREATE_THREAD_DEBUG_EVENT',\n 1: 'EXCEPTION_DEBUG_EVENT',\n 5: 'EXIT_PROCESS_DEBUG_EVENT',\n 4: 'EXIT_THREAD_DEBUG_EVENT',\n 6: 'LOAD_DLL_DEBUG_EVENT',\n 8: 'OUTPUT_DEBUG_STRING_EVENT', \n 9: 'RIP_EVENT',\n 7: 'UNLOAD_DLL_DEBUG_EVENT',\n}\nclass DEBUG_EVENT(Structure):\n _fields_ = [\n ('dwDebugEventCode', c_int),\n ('dwProcessId', c_int),\n ('dwThreadId', c_int),\n ('u', c_int*20)]\n\ndef run_with_debugger(args):\n proc = subprocess.Popen(args, creationflags=1)\n event = DEBUG_EVENT()\n\n while True:\n if WaitForDebugEvent(pointer(event), 10):\n print event_names.get(event.dwDebugEventCode, \n 'Unknown Event %s' % event.dwDebugEventCode)\n ContinueDebugEvent(event.dwProcessId, event.dwThreadId, DBG_CONTINUE)\n retcode = proc.poll()\n if retcode is not None:\n return retcode\n\nrun_with_debugger(['python', 'crash.py'])\n</code></pre>\n"}, {'answer_id': 949667, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>Here is a slightly improved version.</p>\n\n<p>In my test the previous code run in an infinite loop when the faulty exe generated an "access violation".</p>\n\n<p>I\'m not totally satisfied by my solution because I have no clear criteria to know which exception should be continued and which one couldn\'t be (The ExceptionFlags is of no help).</p>\n\n<p>But it works on the example I run.</p>\n\n<p>Hope it helps,\nVivian De Smedt</p>\n\n<pre><code>from ctypes import windll, c_uint, c_void_p, Structure, Union, pointer\nimport subprocess\n\nWaitForDebugEvent = windll.kernel32.WaitForDebugEvent\nContinueDebugEvent = windll.kernel32.ContinueDebugEvent\nDBG_CONTINUE = 0x00010002L\nDBG_EXCEPTION_NOT_HANDLED = 0x80010001L\n\nevent_names = {\n 1: \'EXCEPTION_DEBUG_EVENT\',\n 2: \'CREATE_THREAD_DEBUG_EVENT\',\n 3: \'CREATE_PROCESS_DEBUG_EVENT\',\n 4: \'EXIT_THREAD_DEBUG_EVENT\',\n 5: \'EXIT_PROCESS_DEBUG_EVENT\',\n 6: \'LOAD_DLL_DEBUG_EVENT\',\n 7: \'UNLOAD_DLL_DEBUG_EVENT\',\n 8: \'OUTPUT_DEBUG_STRING_EVENT\',\n 9: \'RIP_EVENT\',\n}\n\nEXCEPTION_MAXIMUM_PARAMETERS = 15\n\nEXCEPTION_DATATYPE_MISALIGNMENT = 0x80000002\nEXCEPTION_ACCESS_VIOLATION = 0xC0000005\nEXCEPTION_ILLEGAL_INSTRUCTION = 0xC000001D\nEXCEPTION_ARRAY_BOUNDS_EXCEEDED = 0xC000008C\nEXCEPTION_INT_DIVIDE_BY_ZERO = 0xC0000094\nEXCEPTION_INT_OVERFLOW = 0xC0000095\nEXCEPTION_STACK_OVERFLOW = 0xC00000FD\n\n\nclass EXCEPTION_DEBUG_INFO(Structure):\n _fields_ = [\n ("ExceptionCode", c_uint),\n ("ExceptionFlags", c_uint),\n ("ExceptionRecord", c_void_p),\n ("ExceptionAddress", c_void_p),\n ("NumberParameters", c_uint),\n ("ExceptionInformation", c_void_p * EXCEPTION_MAXIMUM_PARAMETERS),\n ]\n\nclass EXCEPTION_DEBUG_INFO(Structure):\n _fields_ = [\n (\'ExceptionRecord\', EXCEPTION_DEBUG_INFO),\n (\'dwFirstChance\', c_uint),\n ]\n\nclass DEBUG_EVENT_INFO(Union):\n _fields_ = [\n ("Exception", EXCEPTION_DEBUG_INFO),\n ]\n\nclass DEBUG_EVENT(Structure):\n _fields_ = [\n (\'dwDebugEventCode\', c_uint),\n (\'dwProcessId\', c_uint),\n (\'dwThreadId\', c_uint),\n (\'u\', DEBUG_EVENT_INFO)\n ]\n\ndef run_with_debugger(args):\n proc = subprocess.Popen(args, creationflags=1)\n event = DEBUG_EVENT()\n\n num_exception = 0\n\n while True:\n if WaitForDebugEvent(pointer(event), 10):\n print event_names.get(event.dwDebugEventCode, \'Unknown Event %s\' % event.dwDebugEventCode)\n\n if event.dwDebugEventCode == 1:\n num_exception += 1\n\n exception_code = event.u.Exception.ExceptionRecord.ExceptionCode\n\n if exception_code == 0x80000003L:\n print "Unknow exception:", hex(exception_code)\n\n else:\n if exception_code == EXCEPTION_ACCESS_VIOLATION:\n print "EXCEPTION_ACCESS_VIOLATION"\n\n elif exception_code == EXCEPTION_INT_DIVIDE_BY_ZERO:\n print "EXCEPTION_INT_DIVIDE_BY_ZERO"\n\n elif exception_code == EXCEPTION_STACK_OVERFLOW:\n print "EXCEPTION_STACK_OVERFLOW"\n\n else:\n print "Other exception:", hex(exception_code)\n\n break\n\n ContinueDebugEvent(event.dwProcessId, event.dwThreadId, DBG_CONTINUE)\n\n retcode = proc.poll()\n if retcode is not None:\n return retcode\n\nrun_with_debugger([\'crash.exe\'])\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78048', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13967/'] |
78,053 | <p>I've been trying to retrieve the locations of all the page breaks on a given Excel 2003 worksheet over COM. Here's an example of the kind of thing I'm trying to do:</p>
<pre><code>Excel::HPageBreaksPtr pHPageBreaks = pSheet->GetHPageBreaks();
long count = pHPageBreaks->Count;
for (long i=0; i < count; ++i)
{
Excel::HPageBreakPtr pHPageBreak = pHPageBreaks->GetItem(i+1);
Excel::RangePtr pLocation = pHPageBreak->GetLocation();
printf("Page break at row %d\n", pLocation->Row);
pLocation.Release();
pHPageBreak.Release();
}
pHPageBreaks.Release();
</code></pre>
<p>I expect this to print out the row numbers of each of the horizontal page breaks in <code>pSheet</code>. The problem I'm having is that although <code>count</code> correctly indicates the number of page breaks in the worksheet, I can only ever seem to retrieve the first one. On the second run through the loop, calling <code>pHPageBreaks->GetItem(i)</code> throws an exception, with error number 0x8002000b, "invalid index".</p>
<p>Attempting to use <code>pHPageBreaks->Get_NewEnum()</code> to get an enumerator to iterate over the collection also fails with the same error, immediately on the call to <code>Get_NewEnum()</code>.</p>
<p>I've looked around for a solution, and the closest thing I've found so far is <a href="http://support.microsoft.com/kb/210663/en-us" rel="nofollow noreferrer">http://support.microsoft.com/kb/210663/en-us</a>. I have tried activating various cells beyond the page breaks, including the cells just beyond the range to be printed, as well as the lower-right cell (IV65536), but it didn't help.</p>
<p>If somebody can tell me how to get Excel to return the locations of all of the page breaks in a sheet, that would be awesome!</p>
<p>Thank you.</p>
<p>@Joel: Yes, I have tried displaying the user interface, and then setting <code>ScreenUpdating</code> to true - it produced the same results. Also, I have since tried combinations of setting <code>pSheet->PrintArea</code> to the entire worksheet and/or calling <code>pSheet->ResetAllPageBreaks()</code> before my call to get the <code>HPageBreaks</code> collection, which didn't help either.</p>
<p>@Joel: I've used <code>pSheet->UsedRange</code> to determine the row to scroll past, and Excel does scroll past all the horizontal breaks, but I'm still having the same issue when I try to access the second one. Unfortunately, switching to Excel 2007 did not help either.</p>
| [{'answer_id': 78519, 'author': 'Joel Spolsky', 'author_id': 4, 'author_profile': 'https://Stackoverflow.com/users/4', 'pm_score': 0, 'selected': False, 'text': '<p>Did you set ScreenUpdating to True, as mentioned in the KB article?</p>\n\n<p>You may want to actually toggle it to True to force a screen repaint. It sounds like the calculation of page breaks is a side-effect of actually rendering the page, rather than something Excel does on demand, so you have to trigger a page rendering on the screen.</p>\n'}, {'answer_id': 78866, 'author': 'Joel Spolsky', 'author_id': 4, 'author_profile': 'https://Stackoverflow.com/users/4', 'pm_score': 3, 'selected': True, 'text': '<p>Experimenting with Excel 2007 from Visual Basic, I discovered that the page break isn\'t known unless it has been displayed on the screen at least once.</p>\n\n<p>The best workaround I could find was to page down, from the top of the sheet to the last row containing data. Then you can enumerate all the page breaks.</p>\n\n<p>Here\'s the VBA code... let me know if you have any problem converting this to COM:</p>\n\n<pre><code>Range("A1").Select\nnumRows = Range("A1").End(xlDown).Row\n\nWhile ActiveWindow.ScrollRow < numRows\n ActiveWindow.LargeScroll Down:=1\nWend\n\nFor Each x In ActiveSheet.HPageBreaks\n Debug.Print x.Location.Row\nNext\n</code></pre>\n\n<p>This code made one simplifying assumption:</p>\n\n<ul>\n<li>I used the .End(xlDown) method to figure out how far the data goes... this assumes that you have continuous data from A1 down to the bottom of the sheet. If you don\'t, you need to use some other method to figure out how far to keep scrolling.</li>\n</ul>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78053', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14238/'] |
78,061 | <p>I would like to have some suggestions about which third-part controls can we use in our Visual C++ MFC application? </p>
| [{'answer_id': 78326, 'author': 'user14317', 'author_id': 14317, 'author_profile': 'https://Stackoverflow.com/users/14317', 'pm_score': 0, 'selected': False, 'text': '<p>If you don\'t mind paying, there\'s FarPoint Spread:</p>\n\n<p><a href="http://www.componentsource.com/selec/products/farpoint-spread/summary.html" rel="nofollow noreferrer">http://www.componentsource.com/selec/products/farpoint-spread/summary.html</a></p>\n'}, {'answer_id': 78412, 'author': 'rec', 'author_id': 14022, 'author_profile': 'https://Stackoverflow.com/users/14022', 'pm_score': 1, 'selected': False, 'text': '<p>Xtreme Toolkit Pro controls\n<a href="http://www.codejock.com/products/toolkitpro/" rel="nofollow noreferrer">http://www.codejock.com/products/toolkitpro/</a></p>\n'}, {'answer_id': 78632, 'author': 'Aidan Ryan', 'author_id': 1042, 'author_profile': 'https://Stackoverflow.com/users/1042', 'pm_score': 3, 'selected': True, 'text': '<p>We\'ve deployed <a href="http://iocomp.com/" rel="nofollow noreferrer">IOComp</a>\'s Plot Pack in both ActiveX and .Net flavors with great success. Great API, incredibly flexible, provides a toolbar that lets users pan/zoom/customize. It\'s solid, has a long track record, relatively inexpensive, and is very fast.</p>\n\n<p>(I\'m not affiliated, by the way.) </p>\n'}, {'answer_id': 87282, 'author': 'ravenspoint', 'author_id': 16582, 'author_profile': 'https://Stackoverflow.com/users/16582', 'pm_score': 1, 'selected': False, 'text': '<p>The IOComp package (<a href="http://iocomp.com/" rel="nofollow noreferrer">http://iocomp.com/</a> ) looks great, but does seem quite expensive to me at around $850 for a developer license</p>\n\n<p>The TeeChart package ( <a href="http://www.steema.com" rel="nofollow noreferrer">http://www.steema.com</a> ) looks comparable at a smaller prices of $450. They have a free 50 day evaluation license</p>\n\n<p>There are a couple of <em>free</em> chart controls at codeproject:</p>\n\n<p><a href="http://www.codeproject.com/KB/miscctrl/CBarChart.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/miscctrl/CBarChart.aspx</a></p>\n\n<p><a href="http://www.codeproject.com/KB/miscctrl/High-speedCharting.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/miscctrl/High-speedCharting.aspx</a></p>\n\n<p><a href="http://www.codeproject.com/KB/miscctrl/graph2d.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/miscctrl/graph2d.aspx</a> This one I have used. The integration procedure is awkward, but it does the job.</p>\n\n<p>FarPoint and codejock, AFAIK, do not have chart controls.</p>\n'}, {'answer_id': 92795, 'author': 'Roel', 'author_id': 11449, 'author_profile': 'https://Stackoverflow.com/users/11449', 'pm_score': 1, 'selected': False, 'text': '<p>We have used the ActiveX version of TeeChart (<a href="http://www.steema.com/" rel="nofollow noreferrer">http://www.steema.com/</a>), which works nicely and comes with many MFC examples. It\'s ActiveX though, that may or may not be a problem in your case.</p>\n'}, {'answer_id': 378628, 'author': 'mem64k', 'author_id': 47418, 'author_profile': 'https://Stackoverflow.com/users/47418', 'pm_score': 1, 'selected': False, 'text': '<p>Just for completeness <a href="http://www.codeproject.com/KB/miscctrl/xgraph.aspx" rel="nofollow noreferrer">Scientific charting control</a>. I used it some time ago and it was pretty easy.</p>\n'}, {'answer_id': 4210932, 'author': 'Keith', 'author_id': 511556, 'author_profile': 'https://Stackoverflow.com/users/511556', 'pm_score': 1, 'selected': False, 'text': '<p>Best chart for MFC I have seen, modern, stable and very well written</p>\n\n<p><a href="http://www.codejock.com/products/chart/" rel="nofollow">http://www.codejock.com/products/chart/</a></p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78061', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14053/'] |
78,062 | <p>The Matrix in SSRS (SQL Server Reporting Services 2005) seems to have issues with certain the border styles when exporting to XLS (but not PDF or web view; maybe other formats, not sure?).</p>
<p>For example: Create a matrix and set the Matrix border style to Black Solid 1px, but all 4 of the cells to have a border style of Black None 1px. When viewed via the ASP.NET control, it looks correct. But after export to XLS, it creates borders around all of the header cells (column and row headers, and the top left cell), and even the right most data column. But all the cells in the middle of the report correctly have no border set.</p>
<p>Update:</p>
<p>If the Matrix borders are set to None, then the borders on the cells don't show up in XLS. So, how do you set an outer border around the Matrix, but not have it apply the 'all sides' border to every cell that touches the edge of the Matrix when exported to Excel?</p>
| [{'answer_id': 78343, 'author': 'Liron Yahdav', 'author_id': 62, 'author_profile': 'https://Stackoverflow.com/users/62', 'pm_score': 3, 'selected': True, 'text': "<p>This seems to be a bug in SSRS 2005 Excel rendering. I've been able to fix this by explicitly setting all sides of the matrix BorderStyle property (Left, Right, Top, Bottom) to Solid.</p>\n\n<p>Also, when you do this, it seems like setting the BorderStyle.Default property to Solid or None doesn't matter. The value explicitly set for the other sides overrides that Default value.</p>\n"}, {'answer_id': 2947733, 'author': 'Robert dennyson', 'author_id': 348879, 'author_profile': 'https://Stackoverflow.com/users/348879', 'pm_score': 0, 'selected': False, 'text': '<p>I had this problem while exporting it to xls. but here is a cool trick to solve this....!\nUse custom formating in borders...solved</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78062', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2291/'] |
78,064 | <p>I've read this <a href="https://stackoverflow.com/questions/40122/exceptions-in-web-services">thread</a> for WCF has inbuilt Custom Fault codes and stuff.</p>
<p>But what is the best practice for <em>ASP.Net</em> web services? Do I throw exceptions and let the client handle the exception or send an Error code (success, failure etc) that the client would rely upon to do its processing.</p>
<p>Update: Just to discuss further in case of <em>SOAP</em>, let's say the client makes a <em>web svc</em> call which is supposed to be a notification message (no return value expected), so everything goes smooth and no exceptions are thrown by the svc. </p>
<p>Now how will the client know if the notification call has gotten lost due to a communication/network problem or something in between the server and the client? compare this with not having any exception thrown. Client might assume it's a success. But it's not. The call got lost somewhere.</p>
<p>Does send a 'success' error code ensures to the client that the call went smooth? is there any other way to achieve this or is the scenario above even possible?</p>
| [{'answer_id': 78171, 'author': 'Sunny Milenov', 'author_id': 8220, 'author_profile': 'https://Stackoverflow.com/users/8220', 'pm_score': 1, 'selected': False, 'text': '<p>Depends on how you are going to consume the web service - i.e. which protocol are you going to use.</p>\n\n<p>If it is GET or POST, better return error code, as the calling HttpWebRequest (.Net) or other code will receive server error, and have to deal with it to extract the exception code.</p>\n\n<p>If it is SOAP - then it is perfectly ok to throw custom exceptions (you do not want to return internal framework exceptions, as they may reveal some stack trace, etc. to external parties).</p>\n\n<p>As the SOAP web services are exactly meant to look to the calling code as a normal method call, the corresponding calling framework should be able to handle and propagate the exception just fine, thus making the calling code look and behave as it deals with internal calls.</p>\n'}, {'answer_id': 91536, 'author': 'Paul van Brenk', 'author_id': 1837197, 'author_profile': 'https://Stackoverflow.com/users/1837197', 'pm_score': 3, 'selected': True, 'text': '<p>Jeff Atwood posted <a href="http://www.codinghorror.com/blog/archives/000054.html" rel="nofollow noreferrer">an interesting aerticle</a> about this subject some time ago. Allthough a .NET exception is converted to a SoapFault, which is compatible with most other toolkits, the information in the faults isn\'t very good. Therefor, the conlusion of the article is that .NET webservices don\'t throw very good exception messages and you should add additional information:</p>\n\n<pre><code>Private Sub WebServiceExceptionHandler(ByVal ex As Exception)\n Dim ueh As New AspUnhandledExceptionHandler\n ueh.HandleException(ex)\n\n \'-- Build the detail element of the SOAP fault.\n Dim doc As New System.Xml.XmlDocument\n Dim node As System.Xml.XmlNode = doc.CreateNode(XmlNodeType.Element, _\n SoapException.DetailElementName.Name, _\n SoapException.DetailElementName.Namespace)\n\n \'-- append our error detail string to the SOAP detail element\n Dim details As System.Xml.XmlNode = doc.CreateNode(XmlNodeType.Element, _\n "ExceptionInfo", _\n SoapException.DetailElementName.Namespace)\n details.InnerText = ueh.ExceptionToString(ex)\n node.AppendChild(details)\n\n \'-- re-throw the exception so we can package additional info\n Throw New SoapException("Unhandled Exception: " & ex.Message, _\n SoapException.ClientFaultCode, _\n Context.Request.Url.ToString, node)\nEnd Sub\n</code></pre>\n\n<p>More info why soapfaults are better <a href="https://stackoverflow.com/questions/81306/wcf-faults-exceptions-versus-messages">in this question</a>.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78064', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1747/'] |
78,069 | <p>Anyone know of any good MSBuild tasks that will execute a PowerShell script and pass it different parameters?</p>
<p>I was able to find <a href="http://bartdesmet.net/blogs/bart/archive/2008/02/16/invoking-powershell-scripts-from-msbuild.aspx" rel="nofollow noreferrer">B# .NET Blog: Invoking PowerShell scripts from MSBuild</a>, but I'm hoping for something that is a little more polished.</p>
<p>If I can't find anything I will of course just go ahead and polish my own using that blog post as a starter.</p>
| [{'answer_id': 80276, 'author': 'Steven Murawski', 'author_id': 1233, 'author_profile': 'https://Stackoverflow.com/users/1233', 'pm_score': 3, 'selected': False, 'text': '<p>You might also want to look at <a href="https://github.com/psake/psake" rel="nofollow noreferrer">Psake</a> - a PowerShell based build environment.</p>\n'}, {'answer_id': 3465029, 'author': 'Ruben Bartelink', 'author_id': 11635, 'author_profile': 'https://Stackoverflow.com/users/11635', 'pm_score': 3, 'selected': False, 'text': '<p>One could use <a href="http://powershellmsbuild.codeplex.com/" rel="nofollow noreferrer">http://powershellmsbuild.codeplex.com/</a> for 3.5. <a href="https://web.archive.org/web/20171226175241/http://powershellmsbuild.codeplex.com/discussions/348378" rel="nofollow noreferrer">It\'d be nice if there was a NuGet package for it that one could leverage via NuGet package restore</a>.</p>\n<p>4.0 has a <a href="https://devblogs.microsoft.com/visualstudio/msbuild-task-factories-guest-starring-windows-powershell/" rel="nofollow noreferrer">Windows Powershell Task Factory</a> which <strike>you can get <a href="https://learn.microsoft.com/en-us/samples/browse/" rel="nofollow noreferrer">in the code gallery</a></strike> has been rolled into\n<a href="https://archive.codeplex.com/?p=msbuildextensionpack" rel="nofollow noreferrer">MSBuild Extension Pack (one of the top task libraries - 400+ Tasks & recommended in Inside MSBuild)</a> has <code>PowerShellTaskFactory</code> (download the help file from <a href="https://web.archive.org/web/20150203103526/http://msbuildextensionpack.codeplex.com:80/releases/view/77212" rel="nofollow noreferrer">the download section of this example release</a> to have a peek).</p>\n'}, {'answer_id': 12817556, 'author': 'Ruben Bartelink', 'author_id': 11635, 'author_profile': 'https://Stackoverflow.com/users/11635', 'pm_score': 3, 'selected': False, 'text': '<p><a href="https://stackoverflow.com/questions/11648530/in-msbuild-how-do-i-run-something-powershell-and-have-all-errors-reported">Duplicate Question and Answer I Posted</a>, here for posterity for when it has been vote to closed. The key difference is that this question was constrained to being <strong>OOTB</strong> and my self-answer stays within that constraint.</p>\n\n<h1>Question</h1>\n\n<p>Powershell doesn\'t seem to have an easy way to trigger it with an arbitrary command and then bubble up parse and execution errors in a way that correctly interoperates with callers that are not PowerShell - e.g., <code>cmd.exe</code>, <a href="https://stackoverflow.com/questions/11647987/how-do-i-get-errors-to-propagate-in-the-teamcity-powershell-runner">TeamCity</a> etc.</p>\n\n<p>My question is simple. What\'s the best way for me with OOTB MSBuild v4 and PowerShell v3 (open to suggestions-wouldnt rule out a suitably production ready MSBuild Task, but it would need to be a bit stronger than suggesting "it\'s easy - taking the PowerShell Task Factory sample and tweak it and/or becoming it\'s maintainer/parent") to run a command (either a small script segment, or (most commonly) an invocation of a <code>.ps1</code> script.</p>\n\n<p>I\'m thinking it should be something normal like:</p>\n\n<pre><code><Exec \n IgnoreStandardErrorWarningFormat="true"\n Command="PowerShell &quot;$(ThingToDo)&quot;" />\n</code></pre>\n\n<hr>\n\n<p>That sadly doesn\'t work:-</p>\n\n<ol>\n<li>if <code>ThingToDo</code> fails to parse, it fails silently</li>\n<li>if <code>ThingToDo</code> is a script invocation that doesn\'t exist, it fails</li>\n<li>if you want to propagate an <code>ERRORLEVEL</code> based <code>.cmd</code> result, it gets hairy</li>\n<li>if you want to embed <code>"</code> quotes in the <code>ThingToDo</code>, it won\'t work</li>\n</ol>\n\n<p>So, what is the bullet proof way of running PowerShell from MSBuild supposed to be? Is there something I can <a href="http://psget.net/" rel="nofollow noreferrer">PsGet</a> to make everything OK?</p>\n\n<h1>Answer</h1>\n\n<p>Weeeeelll, you could use something long winded like this until you find a better way:-</p>\n\n<pre><code><PropertyGroup>\n <__PsInvokeCommand>powershell "Invoke-Command</__PsInvokeCommand>\n <__BlockBegin>-ScriptBlock { $errorActionPreference=\'Stop\';</__BlockBegin>\n <__BlockEnd>; exit $LASTEXITCODE }</__BlockEnd>\n <_PsCmdStart>$(__PsInvokeCommand) $(__BlockBegin)</_PsCmdStart>\n <_PsCmdEnd>$(__BlockEnd)"</_PsCmdEnd>\n</PropertyGroup>\n</code></pre>\n\n<p>And then \'all\' you need to do is:</p>\n\n<pre><code><Exec \n IgnoreStandardErrorWarningFormat="true"\n Command="$(_PsCmdStart)$(ThingToDo)$(_PsCmdEnd)" />\n</code></pre>\n\n<p>The single redeeming feature of this (other than trapping all error types I could think of), is that it works OOTB with any PowerShell version and any MSBuild version.</p>\n\n<p>I\'ll get my coat.</p>\n'}, {'answer_id': 41051774, 'author': 'Garrett Serack', 'author_id': 181469, 'author_profile': 'https://Stackoverflow.com/users/181469', 'pm_score': 2, 'selected': False, 'text': '<p>With a bit of fun, I managed to come up with a fairly clean way of making this work:</p>\n\n<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>\n<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\n <!-- #1 Place this line at the top of any msbuild script (ie, csproj, etc) -->\n <PropertyGroup><PowerShell># 2>nul || type %~df0|find /v "setlocal"|find /v "errorlevel"|powershell.exe -noninteractive -&amp; exit %errorlevel% || #</PowerShell></PropertyGroup>\n\n <!-- #2 in any target you want to run a script -->\n <Target Name="default" >\n\n <PropertyGroup> <!-- #3 prefix your powershell script with the $(PowerShell) variable, then code as normal! -->\n <myscript>$(PowerShell)\n #\n # powershell script can do whatever you need.\n #\n dir ".\\*.cs" -recurse |% {\n write-host Examining file named: $_.FullName\n # do other stuff here...\n } \n $answer = 2+5\n write-host Answer is $answer !\n </myscript>\n </PropertyGroup>\n\n <!-- #4 and execute the script like this -->\n <Exec Command="$(myscript)" EchoOff="true" /> \n </Target>\n</Project>\n</code></pre>\n\n<h1>Notes:</h1>\n\n<ul>\n<li>You can still use the standard Exec Task features! (see: <a href="https://msdn.microsoft.com/en-us/library/x8zx72cd.aspx" rel="nofollow noreferrer">https://msdn.microsoft.com/en-us/library/x8zx72cd.aspx</a>)</li>\n<li><p>if your powershell script needs to use < > or & characters, just place the contents in a CDATA wrapper:</p>\n\n<pre><code><script2><![CDATA[ $(PowerShell)\n # your powershell code goes here!\n write-host "<<Hi mom!>>"\n]]></script2>\n</code></pre></li>\n<li><p>if you want return items to the msbuild script you can get them:</p>\n\n<pre><code><script3>$(PowerShell)\n # your powershell code goes here!\n (dir "*.cs" -recurse).FullName\n</script3>\n\n<Exec Command="$(script3)" EchoOff="true" ConsoleToMSBuild="true"> \n <Output TaskParameter="ConsoleOutput" PropertyName="items" />\n</Exec>\n<Touch Files="$(items)" /> \n</code></pre></li>\n</ul>\n\n<p>See! then you can use those items with another msbuild Task :D</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78069', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3957/'] |
78,077 | <p>What is the best/fastest way to sort Alphanumeric fields? </p>
| [{'answer_id': 78096, 'author': 'senfo', 'author_id': 10792, 'author_profile': 'https://Stackoverflow.com/users/10792', 'pm_score': 0, 'selected': False, 'text': '<p>You will find that most development libraries ship with an implementation of the quicksort algorithm, which is often the fastest sorting algorithm. Check out the <a href="http://en.wikipedia.org/wiki/Quicksort" rel="nofollow noreferrer">Wikipedia link here</a>.</p>\n'}, {'answer_id': 78118, 'author': 'Ciaran', 'author_id': 5048, 'author_profile': 'https://Stackoverflow.com/users/5048', 'pm_score': 1, 'selected': False, 'text': '<p>You don\'t specify your target language, but whatever it is, it should have reliable, built-in sorting methods, so use one of them! For PHP...</p>\n\n<p>Load into an array and sort($array);</p>\n\n<p><a href="http://ie.php.net/sort" rel="nofollow noreferrer">php sort</a>...</p>\n\n<pre><code>$fruits = array("lemon", "orange", "banana", "apple");\nsort($fruits);\n\nforeach ($fruits as $key => $val)\n{\n echo "fruits[" . $key . "] = " . $val . "\\n";\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>fruits[0] = apple\nfruits[1] = banana\nfruits[2] = lemon\nfruits[3] = orange\n</code></pre>\n'}, {'answer_id': 78121, 'author': 'Brian R. Bondy', 'author_id': 3153, 'author_profile': 'https://Stackoverflow.com/users/3153', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://en.wikipedia.org/wiki/Bubble_sort" rel="nofollow noreferrer">Bubble sort</a>! Just kidding :)</p>\n\n<p>Probably your best bet would be <a href="http://en.wikipedia.org/wiki/Quicksort" rel="nofollow noreferrer">quicksort</a> or <a href="http://en.wikipedia.org/wiki/Merge_sort" rel="nofollow noreferrer">mergesort</a>. </p>\n\n<p>Both are O(nlogn) as opposed to bubble sort\'s O(n^2)</p>\n'}, {'answer_id': 78122, 'author': 'Patrick Desjardins', 'author_id': 13913, 'author_profile': 'https://Stackoverflow.com/users/13913', 'pm_score': 0, 'selected': False, 'text': '<p>In C#, List has .Sort().</p>\n\n<p>In general QuickSort is very fast on many situations but it always depend of the size of the array,</p>\n\n<p>Here is the <a href="http://en.wikipedia.org/wiki/Quicksort" rel="nofollow noreferrer">link</a></p>\n'}, {'answer_id': 78132, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>The answer to your question is intimately related to some details you haven\'t provided. The "best/fastest" way depends on how long the fields are, how many you have to sort, how much memory you have available, the relative speeds of disk and memory, the details of what\'s in the strings, ..., <em>ad nauseam</em>.</p>\n\n<p>Knuth Vol 3 has the details on a wide variety of approaches. I don\'t recall if he discusses Radix Sorting, but he probably does. If he doesn\'t, you should look up some references on Radix Sorting. It\'s only useful in a narrow set of circumstances, but positively flies there. If you\'ve got a small set of short strings, Bubble Sort will perform better than complex sorts on some architectures, due to lower overhead. The C Run Time Library includes a version of Quick Sort because that can be a very efficient algorithm for larger data sets in some circumstances.</p>\n\n<p>Net-net, the answer is "It depends".</p>\n'}, {'answer_id': 78133, 'author': 'Aaron', 'author_id': 14153, 'author_profile': 'https://Stackoverflow.com/users/14153', 'pm_score': 1, 'selected': False, 'text': '<p>The "best" way depends on a lot of factors:</p>\n\n<ol>\n<li>Do you need to support more than language?</li>\n<li>Do you need to support more than one language simultaniously?</li>\n<li>Do you need to support languages other than the current Operating System or user language? (ex, web applications)</li>\n<li>Do you need to support more than one encoding? (unicode, utf-16le/utf-8, ansi code pages, etc)</li>\n<li>Do you need to support long or highly redundant inputs? (where precomputation or compression may speed up sorting operations)</li>\n<li>Do you need to support a large number of inputs, ex: million, or billion inputs? </li>\n</ol>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78077', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14239/'] |
78,091 | <p>In the middle of a Perl script, there is a system command I want to execute. I have a string that contains the data that needs to be fed into stdin (the command only accepts input from stdin), and I need to capture the output written to stdout. I've looked at the various methods of executing system commands in Perl, and the <code>open</code> function seems to be what I need, except that it looks like I can only capture stdin or stdout, not both.</p>
<p>At the moment, it seems like my best solution is to use <code>open</code>, redirect stdout into a temporary file, and read from the file after the command finishes. Is there a better solution?</p>
| [{'answer_id': 78102, 'author': 'mopoke', 'author_id': 14054, 'author_profile': 'https://Stackoverflow.com/users/14054', 'pm_score': 2, 'selected': False, 'text': '<p>IPC::Open3 would probably do what you want. It can capture STDERR and STDOUT.</p>\n\n<p><a href="http://metacpan.org/pod/IPC::Open3" rel="nofollow noreferrer">http://metacpan.org/pod/IPC::Open3</a></p>\n'}, {'answer_id': 78109, 'author': 'Leon Timmermans', 'author_id': 4727, 'author_profile': 'https://Stackoverflow.com/users/4727', 'pm_score': 2, 'selected': True, 'text': '<p>I think you want to take a look at <a href="http://search.cpan.org/~rgarcia/perl-5.10.0/lib/IPC/Open2.pm" rel="nofollow noreferrer">IPC::Open2</a></p>\n'}, {'answer_id': 78154, 'author': 'X-Istence', 'author_id': 13986, 'author_profile': 'https://Stackoverflow.com/users/13986', 'pm_score': 1, 'selected': False, 'text': '<p>There is a special perl command for it</p>\n\n<pre><code>open2()\n</code></pre>\n\n<p>More info can be found on: <a href="http://sunsite.ualberta.ca/Documentation/Misc/perl-5.6.1/lib/IPC/Open2.html" rel="nofollow noreferrer">http://sunsite.ualberta.ca/Documentation/Misc/perl-5.6.1/lib/IPC/Open2.html</a></p>\n'}, {'answer_id': 78201, 'author': 'benzado', 'author_id': 10947, 'author_profile': 'https://Stackoverflow.com/users/10947', 'pm_score': 2, 'selected': False, 'text': "<p>Somewhere at the top of your script, include the line</p>\n\n<pre><code>use IPC::Open2;\n</code></pre>\n\n<p>That will include the necessary module, usually installed with most Perl distributions by default. (If you don't have it, you could install it using CPAN.) Then, instead of open, call:</p>\n\n<pre><code>$pid = open2($cmd_out, $cmd_in, 'some cmd and args');\n</code></pre>\n\n<p>You can send data to your command by sending it to $cmd_in and then read your command's output by reading from $cmd_out.</p>\n\n<p>If you also want to be able to read the command's stderr stream, you can use the IPC::Open3 module instead.</p>\n"}, {'answer_id': 78323, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>I always do it this way if I'm only expecting a single line of output or want to split the result on something other than a newline:</p>\n\n<pre><code>my $result = qx( command args 2>&1 ); \nmy $rc=$?; \n# $rc >> 8 is the exit code of the called program.\n\nif ($rc != 0 ) { \n error(); \n} \n</code></pre>\n\n<p>If you want to deal with a multi-line response, get the result as an array:</p>\n\n<pre><code>my @lines = qx( command args 2>&1 ); \n\nforeach ( my $line ) (@lines) { \n if ( $line =~ /some pattern/ ) { \n do_something(); \n } \n} \n</code></pre>\n"}, {'answer_id': 79308, 'author': 'brian d foy', 'author_id': 2766176, 'author_profile': 'https://Stackoverflow.com/users/2766176', 'pm_score': 2, 'selected': False, 'text': '<p>The <a href="http://perldoc.perl.org/perlipc.html" rel="nofollow noreferrer">perlipc documentation</A> covers many ways that you can do this, including IPC::Open2 and IPC::Open3.</p>\n'}, {'answer_id': 79723, 'author': 'xdg', 'author_id': 11800, 'author_profile': 'https://Stackoverflow.com/users/11800', 'pm_score': 3, 'selected': False, 'text': '<p>IPC::Open2/3 are fine, but I\'ve found that usually all I really need is <a href="http://metacpan.org/pod/IPC::Run3" rel="nofollow noreferrer">IPC::Run3</a>, which handles the simple cases really well with minimal complexity:</p>\n\n<pre><code>use IPC::Run3; # Exports run3() by default\n\nrun3( \\@cmd, \\$in, \\$out, \\$err );\n</code></pre>\n\n<p>The documentation compares IPC::Run3 to other alternatives. It\'s worth a read even if you don\'t decide to use it.</p>\n'}, {'answer_id': 81251, 'author': 'stephanea', 'author_id': 8776, 'author_profile': 'https://Stackoverflow.com/users/8776', 'pm_score': 0, 'selected': False, 'text': '<p>If you do not want to include extra packages, you can just do</p>\n\n<pre><code>open(TMP,">tmpfile");\nprint TMP $tmpdata ;\nopen(RES,"$yourcommand|");\n$res = "" ;\nwhile(<RES>){\n$res .= $_ ;\n}\n</code></pre>\n\n<p>which is the contrary of what you suggested, but should work also.</p>\n'}, {'answer_id': 82219, 'author': 'Aristotle Pagaltzis', 'author_id': 9410, 'author_profile': 'https://Stackoverflow.com/users/9410', 'pm_score': 2, 'selected': False, 'text': '<p>A very easy way to do this that I recently found is <strong>the <a href="http://p3rl.org/IPC::Filter" rel="nofollow noreferrer">IPC::Filter</a> module</strong>. It lets you do the job extremely intuitively:</p>\n\n<pre><code>$output = filter $input, \'somecmd\', \'--with\', \'various=args\', \'--etc\';\n</code></pre>\n\n<p>Note how it invokes your command without going through the shell if you pass it a list. It also does a reasonable job of handling errors for common utilities. (On failure, it <code>die</code>s, using the text from STDERR as its error message; on success, STDERR is just discarded.)</p>\n\n<p>Of course, it’s not suitable for huge amounts of data since it provides no way of doing any streaming processing; also, the error handling might not be granular enough for your needs. But it makes the many simple cases really <em>really</em> simple.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
78,108 | <p><strong>E.g.</strong> Is it more secure to use <code>mod_php</code> instead of <code>php-cgi</code>?
Or is it more secure to use <code>mod_perl</code> instead of traditional <code>cgi-scripts</code>?</p>
<p>I'm mainly interested in security concerns, but speed might be an issue if there are significant differences.</p>
| [{'answer_id': 78131, 'author': 'Leon Timmermans', 'author_id': 4727, 'author_profile': 'https://Stackoverflow.com/users/4727', 'pm_score': 2, 'selected': False, 'text': "<p>Using a builtin module is definitely going to be faster than using CGI. The security implications depend on the configuration. In the default configuration they are pretty much the same, but cgi allows some more secure configurations that builtin modules can't provide, specially in the context of shared hosting. What exactly do you want to secure yourself against?</p>\n"}, {'answer_id': 78138, 'author': 'Vinko Vrsalovic', 'author_id': 5190, 'author_profile': 'https://Stackoverflow.com/users/5190', 'pm_score': 3, 'selected': False, 'text': "<p>Most security holes occur due to lousy programming in the script itself, so it's really kind of moot if they are ran as cgi or in modules. That said, apache modules can potentially crash the whole webserver (especially if using a threaded MPM) and mod_php is kind of famous for it.</p>\n\n<p>cgi will be slower, but nowadays there are solutions to that, mainly FastCGI and friends.</p>\n\n<p>What is your threat model?</p>\n"}, {'answer_id': 78188, 'author': 'X-Istence', 'author_id': 13986, 'author_profile': 'https://Stackoverflow.com/users/13986', 'pm_score': 5, 'selected': True, 'text': "<p>Security in what sense? Either way it really depends on what script is running and how well it is written. Too many scripts these days are half-assed and do not properly do input validation.</p>\n\n<p>I personally prefer FastCGI to mod_php since if a FastCGI process dies a new one will get spawned, whereas I have seen mod_php kill the entirety of Apache.</p>\n\n<p>As for security, with FastCGI you could technically run the php process under a different user from the default web servers user.</p>\n\n<p>On a seperate note, if you are using Apache's new worker threading support you will want to make sure that you are not using mod_php as some of the extensions are not thread safe and will cause race conditions.</p>\n"}, {'answer_id': 78271, 'author': 'Scott Swezey', 'author_id': 9439, 'author_profile': 'https://Stackoverflow.com/users/9439', 'pm_score': 2, 'selected': False, 'text': '<p><strong>From the PHP install.txt doc for PHP 5.2.6:</strong></p>\n\n<p>Server modules provide significantly better performance and additional\n functionality compared to the CGI binary.\n<br /><br /></p>\n\n<p><strong>For IIS/PWS:</strong></p>\n\n<p>Warning</p>\n\n<p>By using the CGI setup, your server is open to several possible\n attacks. Please read our CGI security section to learn how to defend\n yourself from those attacks.</p>\n'}, {'answer_id': 78291, 'author': 'djn', 'author_id': 9673, 'author_profile': 'https://Stackoverflow.com/users/9673', 'pm_score': 3, 'selected': False, 'text': "<p>If you run your own server go the module way, it's somewhat faster.\nIf you're on a shared server the decision has already been taken for you, usually on the CGI side. The reason for this are filesystem permissions. PHP as a module runs with the permissions of the http server (usually 'apache') and unless you can chmod your scripts to that user you have to chmod them to 777 - world readable. This means, alas, that your server neighbour can take a look at them - think of where you store the database access password. Most shared servers have solved this using stuff like phpsuexec and such, which run scripts with the permissions of the script owner, so you can (must) have your code chmoded to 644. Phpsuexec runs only with PHP as CGI - that's more or less all, it's just a local machine thing - makes no difference to the world at large.</p>\n"}, {'answer_id': 79279, 'author': 'DGM', 'author_id': 14253, 'author_profile': 'https://Stackoverflow.com/users/14253', 'pm_score': 2, 'selected': False, 'text': "<p>A module such as mod_php or FastCGI is incredibly faster than plain CGI.. just don't do CGI. As others have said, the PHP program itself is the greatest security threat, but ignoring that there is one other consideration, on shared hosts. </p>\n\n<p>If your script is on a shared host with other php programs and the host is not running in safe mode, then it is likely that all server processes are running as the same user. This could mean that any other php script can read your own, including database passwords. So be sure to investigate the server configuration to be sure your code is not readable to others.</p>\n\n<p>Even if you control your own hosting, keep in mind that another hacked web application on the server could be a conduit into others.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78108', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1994377/'] |
78,125 | <p>The following code snippet (correctly) gives a warning in C and an error in C++ (using gcc & g++ respectively, tested with versions 3.4.5 and 4.2.1; MSVC does not seem to care):</p>
<pre><code>char **a;
const char** b = a;
</code></pre>
<p>I can understand and accept this.<br>
The C++ solution to this problem is to change b to be a const char * const *, which disallows reassignment of the pointers and prevents you from circumventing const-correctness (<a href="http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.17" rel="nofollow noreferrer">C++ FAQ</a>).<br></p>
<pre><code>char **a;
const char* const* b = a;
</code></pre>
<p>However, in pure C, the corrected version (using const char * const *) still gives a warning, and I don't understand why.
Is there a way to get around this without using a cast?</p>
<p>To clarify:<br>
1) Why does this generate a warning in C? It should be entirely const-safe, and the C++ compiler seems to recognize it as such.<br>
2) What is the correct way to go about accepting this char** as a parameter while saying (and having the compiler enforce) that I will not be modifying the characters it points to?
For example, if I wanted to write a function:</p>
<pre><code>void f(const char* const* in) {
// Only reads the data from in, does not write to it
}
</code></pre>
<p>And I wanted to invoke it on a char**, what would be the correct type for the parameter?</p>
| [{'answer_id': 78202, 'author': 'Kevin', 'author_id': 6386, 'author_profile': 'https://Stackoverflow.com/users/6386', 'pm_score': 7, 'selected': True, 'text': "<p>I had this same problem a few years ago and it irked me to no end.</p>\n\n<p>The rules in C are more simply stated (i.e. they don't list exceptions like converting <code>char**</code> to <code>const char*const*</code>). Consequenlty, it's just not allowed. With the C++ standard, they included more rules to allow cases like this.</p>\n\n<p>In the end, it's just a problem in the C standard. I hope the next standard (or technical report) will address this.</p>\n"}, {'answer_id': 78218, 'author': 'Aaron', 'author_id': 14153, 'author_profile': 'https://Stackoverflow.com/users/14153', 'pm_score': 3, 'selected': False, 'text': '<blockquote>\n <p>However, in pure C, this still gives a warning, and I don\'t understand why</p>\n</blockquote>\n\n<p>You\'ve already identified the problem -- this code is not const-correct. "Const correct" means that, except for <code>const_cast</code> and C-style casts removing <code>const</code>, you can never modify a <code>const</code> object through those const pointers or references.</p>\n\n<p>The value of <code>const</code>-correctness -- <code>const</code> is there, in large part, to detect programmer errors. If you declare something as <code>const</code>, you\'re stating that you don\'t think it should be modified -- or at least, those with access to the <code>const</code> version only should not be able to modifying it. Consider:</p>\n\n<pre><code>void foo(const int*);\n</code></pre>\n\n<p>As declared, <code>foo</code> doesn\'t have <em>permission</em> to modify the integer pointed to by its argument. </p>\n\n<p>If you\'re not sure why the code you posted isn\'t <code>const</code>-correct, consider the following code, only slightly different from HappyDude\'s code:</p>\n\n<pre><code>char *y;\n\nchar **a = &y; // a points to y\nconst char **b = a; // now b also points to y\n\n// const protection has been violated, because:\n\nconst char x = 42; // x must never be modified\n*b = &x; // the type of *b is const char *, so set it \n // with &x which is const char* ..\n // .. so y is set to &x... oops;\n*y = 43; // y == &x... so attempting to modify const \n // variable. oops! undefined behavior!\ncout << x << endl;\n</code></pre>\n\n<p>Non-<code>const</code> types can only convert to const types in particular ways to prevent any circumvention of <code>const</code> on a data-type without an explicit cast. </p>\n\n<p>Objects initially declared <code>const</code> are particularly special -- the compiler can assume they never change. However, if <code>b</code> can be assigned the value of <code>a</code> without a cast, then you could inadvertently attempt to modify a <code>const</code> variable. This would not only break the check you asked the compiler to make, to disallow you from changing that variables value -- it would also allow you break the compiler optimizations!</p>\n\n<p>On some compilers, this will print <code>42</code>, on some <code>43</code>, and others, the program will crash. </p>\n\n<p><strong>Edit-add:</strong></p>\n\n<p>HappyDude: Your comment is spot on. Either the C langauge, or the C compiler you\'re using, treats <code>const char * const *</code> fundamentally differently than the C++ language treats it. Perhaps consider silencing the compiler warning for this source line only.</p>\n'}, {'answer_id': 78410, 'author': 'user7116', 'author_id': 7116, 'author_profile': 'https://Stackoverflow.com/users/7116', 'pm_score': 0, 'selected': False, 'text': '<p>I\'m not able to get an error when implicitly casting char** to const char * const *, at least on MSVC 14 (VS2k5) and g++ 3.3.3. GCC 3.3.3 issues a warning, which I\'m not exactly sure if it is correct in doing.</p>\n\n<p>test.c:</p>\n\n<pre><code>#include <stdlib.h> \n#include <stdio.h>\nvoid foo(const char * const * bar)\n{\n printf("bar %s null\\n", bar ? "is not" : "is");\n}\n\nint main(int argc, char **argv) \n{\n char **x = NULL; \n const char* const*y = x;\n foo(x);\n foo(y);\n return 0; \n}\n</code></pre>\n\n<p>Output with compile as C code: cl /TC /W4 /Wp64 test.c</p>\n\n<pre><code>test.c(8) : warning C4100: \'argv\' : unreferenced formal parameter\ntest.c(8) : warning C4100: \'argc\' : unreferenced formal parameter\n</code></pre>\n\n<p>Output with compile as C++ code: cl /TP /W4 /Wp64 test.c</p>\n\n<pre><code>test.c(8) : warning C4100: \'argv\' : unreferenced formal parameter\ntest.c(8) : warning C4100: \'argc\' : unreferenced formal parameter\n</code></pre>\n\n<p>Output with gcc: gcc -Wall test.c</p>\n\n<pre><code>test2.c: In function `main\':\ntest2.c:11: warning: initialization from incompatible pointer type\ntest2.c:12: warning: passing arg 1 of `foo\' from incompatible pointer type\n</code></pre>\n\n<p>Output with g++: g++ -Wall test.C</p>\n\n<p><em>no output</em></p>\n'}, {'answer_id': 78427, 'author': 'Skizz', 'author_id': 1898, 'author_profile': 'https://Stackoverflow.com/users/1898', 'pm_score': 0, 'selected': False, 'text': "<p>I'm pretty sure that the const keyword does not imply the data can't be changed/is constant, only that the data will be treated as read-only. Consider this:</p>\n\n<pre><code>const volatile int *const serial_port = SERIAL_PORT;\n</code></pre>\n\n<p>which is valid code. How can volatile and const co-exist? Simple. volatile tells the compiler to always read the memory when using the data and const tells the compiler to create an error when an attempt is made to write to the memory using the serial_port pointer.</p>\n\n<p>Does const help the compiler's optimiser? No. Not at all. Because constness can be added to and removed from data through casting, the compiler cannot figure out if const data really is constant (since the cast could be done in a different translation unit). In C++ you also have the mutable keyword to complicate matters further.</p>\n\n<pre><code>char *const p = (char *) 0xb000;\n//error: p = (char *) 0xc000;\nchar **q = (char **)&p;\n*q = (char *)0xc000; // p is now 0xc000\n</code></pre>\n\n<p>What happens when an attempt is made to write to memory that really is read only (ROM, for example) probably isn't defined in the standard at all.</p>\n"}, {'answer_id': 78534, 'author': 'Fabio Ceconello', 'author_id': 8999, 'author_profile': 'https://Stackoverflow.com/users/8999', 'pm_score': 4, 'selected': False, 'text': "<p>To be considered compatible, the source pointer should be const in the immediately anterior indirection level. So, this will give you the warning in GCC:</p>\n\n<pre><code>char **a;\nconst char* const* b = a;\n</code></pre>\n\n<p>But this won't:</p>\n\n<pre><code>const char **a;\nconst char* const* b = a;\n</code></pre>\n\n<p>Alternatively, you can cast it:</p>\n\n<pre><code>char **a;\nconst char* const* b = (const char **)a;\n</code></pre>\n\n<p>You would need the same cast to invoke the function f() as you mentioned. As far as I know, there's no way to make an implicit conversion in this case (except in C++). </p>\n"}, {'answer_id': 98399, 'author': 'wnoise', 'author_id': 15464, 'author_profile': 'https://Stackoverflow.com/users/15464', 'pm_score': 1, 'selected': False, 'text': "<p>This is annoying, but if you're willing to add another level of redirection, you can often do the following to push down into the pointer-to-pointer:</p>\n\n<pre><code>char c = 'c';\nchar *p = &c;\nchar **a = &p;\n\nconst char *bi = *a;\nconst char * const * b = &bi;\n</code></pre>\n\n<p>It has a slightly different meaning, but it's usually workable, and it doesn't use a cast.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78125', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14266/'] |
78,127 | <p>Apple's CoreGraphics library defines two functions for describing an arc.</p>
<ul>
<li>CGPathAddArc adds an arc based on a center point, radius, and pair of angles.</li>
<li>CGPathAddArcToPoint adds an arc based on a radius and a pair of tangent lines.</li>
</ul>
<p>The details are explained in <a href="http://developer.apple.com/documentation/GraphicsImaging/Reference/CGPath/Reference/reference.html" rel="noreferrer">the CGPath API reference</a>. Why two functions? Simple convenience? Is one more efficient than the other? Is one defined in terms of the other?</p>
| [{'answer_id': 78169, 'author': 'Chris Hanson', 'author_id': 714, 'author_profile': 'https://Stackoverflow.com/users/714', 'pm_score': 4, 'selected': True, 'text': "<p>The former gets you a portion of a circle (really, an approximation of one), while the latter exposes the fact that you're creating a Bézier path. Depending on what you're actually drawing, one or the other might be more convenient. You could really consider both of them conveniences for CGPathAddCurveToPoint.</p>\n"}, {'answer_id': 19065433, 'author': 'James Snook', 'author_id': 2599552, 'author_profile': 'https://Stackoverflow.com/users/2599552', 'pm_score': 6, 'selected': False, 'text': '<p><code>CGContextAddArc</code> does this:</p>\n\n<p><img src="https://twistedape.me.uk/blog/images/AddArc.png" alt="addArc"></p>\n\n<p>where the red line is what will be drawn, sA is <code>startAngle</code>, eA is the <code>endAngle</code>, r is <code>radius</code>, and x and y are <code>x</code> and <code>y</code>. If you have a previous point the function will line from this point to the start of the arc (unless you are careful this line won\'t be going in the same direction as the arc).</p>\n\n<p><code>CGContextAddArcToPoint</code> works like this:</p>\n\n<p><img src="https://www.twistedape.me.uk/blog/images/2013-09-23-what-arctopoint-does-addArcToPoint.png" alt="addArc"></p>\n\n<p>Where P1 is the current point of the path, the x1, x2, y1, y2 match the functions <code>x1</code>, <code>x2</code>, <code>y1</code>, <code>y2</code> and r is <code>radius</code>. The arc will start in the same direction as the line between the current point and <code>(x1, y1)</code> and end in the direction between <code>(x1, y1)</code> and <code>(x2, y2)</code>. it won\'t line to <code>(x2, y2)</code> It will stop at the end of the circle.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78127', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10947/'] |
78,141 | <h2>Edit - New Question</h2>
<p>Ok lets rephrase the question more generically. </p>
<p>Using reflection, is there a way to dynamically call at runtime a base class method that you may be overriding. You cannot use the 'base' keyword at compile time because you cannot be sure it exists. At runtime I want to list my ancestors methods and call the ancestor methods.</p>
<p>I tried using GetMethods() and such but all they return are "pointers" to the most derived implementation of the method. Not an implementation on a base class.</p>
<h2>Background</h2>
<p>We are developing a system in C# 3.0 with a relatively big class hierarchy. Some of these classes, anywhere in the hierarchy, have resources that need to be
disposed of, those implement the <strong>IDisposable</strong> interface.</p>
<h2>The Problem</h2>
<p>Now, to facilitate maintenance and refactoring of the code I would like to find a way, for classes implementing IDisposable,
to "automatically" call <strong>base.Dispose(bDisposing)</strong> if any ancestors also implements IDisposable. This way, if some class higher up in the hierarchy starts implementing
or stops implementing IDisposable that will be taken care of automatically.</p>
<p>The issue is two folds. </p>
<ul>
<li>First, finding if any ancestors implements IDisposable. </li>
<li>Second, calling base.Dispose(bDisposing) conditionally.</li>
</ul>
<p>The first part, finding about ancestors implementing IDisposable, I have been able to deal with. </p>
<p>The second part is the tricky one. Despite all my
efforts, I haven't been able to call base.Dispose(bDisposing) from a derived class. All my attempts failed. They either caused
compilation errors or called the wrong Dispose() method, that is the most derived one, thus looping forever.</p>
<p>The main issue is that you <strong>cannot actually refer to base.Dispose()</strong> directly in your code if there is no such thing as an
ancestor implementing it (<em>be reminded that there might have no ancestors yet implementing IDisposable, but I want the derived code to be ready when and if such
a thing happens in the future</em>). That leave us with the <strong>Reflection</strong> mechanisms, but I did not find a proper way of doing it. Our code is quite filled with
advanced reflection techniques and I think I did not miss anything obvious there.</p>
<h2>My Solution</h2>
<p>My best shot yet was to have some conditional code using in commented code. Changing the IDisposable hierarchy would either break the build
(if no IDisposable ancestor exists) or throw an exception (if there are IDisposable ancestors but base.Dispose is not called).</p>
<p>Here is some code I am posting to show you what my Dispose(bDisposing) method looks like. I am putting this code at the end of all the Dispose()
methods throughout the hierarchy. Any new classes are created from templates that also includes this code. </p>
<pre><code>public class MyOtherClassBase
{
// ...
}
public class MyDerivedClass : MyOtherClassBase, ICalibrable
{
private bool m_bDisposed = false;
~MyDerivedClass()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool bDisposing)
{
if (!m_bDisposed) {
if (bDisposing) {
// Dispose managed resources
}
// Dispose unmanaged resources
}
m_bDisposed = true;
Type baseType = typeof(MyDerivedClass).BaseType;
if (baseType != null) {
if (baseType.GetInterface("IDisposable") != null) {
// If you have no ancestors implementing base.Dispose(...), comment
// the following line AND uncomment the throw.
//
// This way, if any of your ancestors decide one day to implement
// IDisposable you will know about it right away and proceed to
// uncomment the base.Dispose(...) in addition to commenting the throw.
//base.Dispose(bDisposing);
throw new ApplicationException("Ancestor base.Dispose(...) not called - "
+ baseType.ToString());
}
}
}
}
</code></pre>
<p><strong>So, I am asking is there a way to call base.Dispose() automatically/conditionally instead?</strong></p>
<h2>More Background</h2>
<p>There is another mechanism in the application where all objects are registered with a main class. The class checks if they implement IDisposable.
If so, they are disposed of properly by the application. This avoids having the code using the classes to deal with
calling Dispose() all around by themselves. Thus, adding IDisposable to a class that has no ancestor history of IDisposable still works perfectly.</p>
| [{'answer_id': 78226, 'author': 'Bryant', 'author_id': 10893, 'author_profile': 'https://Stackoverflow.com/users/10893', 'pm_score': 2, 'selected': False, 'text': '<p>Personally, I think you might be better off handling this with something like FxCop. You should be able to write a rule that check so see if when an object is created that implements IDisposable that you use a using statement. </p>\n\n<p>It seems a little dirty (to me) to automatically dispose an object.</p>\n'}, {'answer_id': 78259, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>If you wanted to use [basetype].Invoke("Dispose"...) then you could implement the function call without the debugger complaining. Then later when the base type actually implements the IDisposable interface it will execute the proper call.</p>\n'}, {'answer_id': 78287, 'author': 'Adam Driscoll', 'author_id': 13688, 'author_profile': 'https://Stackoverflow.com/users/13688', 'pm_score': 0, 'selected': False, 'text': '<p>If you wanted to use [basetype].Invoke("Dispose"...) then you could implement the function call without the debugger complaining. Then later when the base type actually implements the IDisposable interface it will execute the proper call.</p>\n'}, {'answer_id': 78315, 'author': 'Mike Dimmick', 'author_id': 6970, 'author_profile': 'https://Stackoverflow.com/users/6970', 'pm_score': 3, 'selected': False, 'text': "<p>The standard pattern is for your base class to implement IDisposable and the non-virtual Dispose() method, and to implement a virtual Dispose(bool) method, which those classes which hold disposable resources must override. They should always call their base Dispose(bool) method, which will chain up to the top class in the hierarchy eventually. Only those classes which override it will be called, so the chain is usually quite short.</p>\n\n<p>Finalizers, spelled ~Class in C#: Don't. Very few classes will need one, and it's very easy to accidentally keep large object graphs around, because the finalizers require at least two collections before the memory is released. On the first collection after the object is no longer referenced, it's put on a queue of finalizers to be run. These are run <em>on a separate, dedicated thread</em> which only runs finalizers (if it gets blocked, no more finalizers run and your memory usage explodes). Once the finalizer has run, the next collection that collects the appropriate generation will free the object and anything else it was referencing that isn't otherwise referenced. Unfortunately, because it survives the first collection, it will be placed into the older generation which is collected less frequently. For this reason, you should Dispose early and often.</p>\n\n<p>Generally, you should implement a small resource wrapper class that <em>only</em> manages the resource lifetime and implement a finalizer on that class, plus IDisposable. The user of the class should then call Dispose on this when it is disposed. There shouldn't be a back-link to the user. That way, only the thing that actually needs finalization ends up on the finalization queue.</p>\n\n<p>If you are going to need them anywhere in the hierarchy, the base class that implements IDisposable should implement the finalizer and call Dispose(bool), passing false as the parameter.</p>\n\n<p>WARNING for Windows Mobile developers (VS2005 and 2008, .NET Compact Framework 2.0 and 3.5): many non-controls that you drop onto your designer surface, e.g. menu bars, timers, HardwareButtons, derive from System.ComponentModel.Component, which implements a finalizer. For desktop projects, Visual Studio adds the components to a System.ComponentModel.Container named <code>components</code>, which it generates code to Dispose when the form is Disposed - it in turn Disposes all the components that have been added. For the mobile projects, the code to Dispose <code>components</code> is generated, <em>but dropping a component onto the surface does not generate the code to add it to <code>components</code></em>. You have to do this yourself in your constructor after calling InitializeComponent.</p>\n"}, {'answer_id': 78322, 'author': 'Sunny Milenov', 'author_id': 8220, 'author_profile': 'https://Stackoverflow.com/users/8220', 'pm_score': 0, 'selected': False, 'text': '<pre><code>public class MyVeryBaseClass {\n protected void RealDispose(bool isDisposing) {\n IDisposable tryme = this as IDisposable;\n if (tryme != null) { // we implement IDisposable\n this.Dispose();\n base.RealDispose(isDisposing);\n }\n }\n}\npublic class FirstChild : MyVeryBaseClasee {\n //non-disposable\n}\npublic class SecondChild : FirstChild, IDisposable {\n ~SecondChild() {\n Dispose(false);\n }\n public void Dispose() {\n Dispose(true);\n GC.SuppressFinalize(this);\n base.RealDispose(true);\n }\n protected virtual void Dispose(bool bDisposing) {\n if (!m_bDisposed) {\n if (bDisposing) {\n }// Dispose managed resources\n } // Dispose unmanaged resources\n }\n}\n</code></pre>\n\n<p>That way, you are responsible to implement right only the first class which is IDisposable.</p>\n'}, {'answer_id': 78458, 'author': 'Steve Cooper', 'author_id': 6722, 'author_profile': 'https://Stackoverflow.com/users/6722', 'pm_score': 0, 'selected': False, 'text': '<p>Try this. It\'s a one-line addition to the Dispose() method, and calls the ancestor\'s dispose, if it exists. (Note that <code>Dispose(bool)</code> is not a member of <code>IDisposable</code>)</p>\n\n<pre><code>// Disposal Helper Functions\npublic static class Disposing\n{\n // Executes IDisposable.Dispose() if it exists.\n public static void DisposeSuperclass(object o)\n {\n Type baseType = o.GetType().BaseType;\n bool superclassIsDisposable = typeof(IDisposable).IsAssignableFrom(baseType);\n if (superclassIsDisposable)\n {\n System.Reflection.MethodInfo baseDispose = baseType.GetMethod("Dispose", new Type[] { });\n baseDispose.Invoke(o, null);\n }\n }\n}\n\nclass classA: IDisposable\n{\n public void Dispose()\n {\n Console.WriteLine("Disposing A");\n }\n}\n\nclass classB : classA, IDisposable\n{\n}\n\nclass classC : classB, IDisposable\n{\n public void Dispose()\n {\n Console.WriteLine("Disposing C");\n Disposing.DisposeSuperclass(this);\n }\n}\n</code></pre>\n'}, {'answer_id': 211599, 'author': 'Scott Dorman', 'author_id': 1559, 'author_profile': 'https://Stackoverflow.com/users/1559', 'pm_score': 2, 'selected': False, 'text': '<p>There is not an "accepted" way of doing this. You really want to make your clean up logic (whether it runs inside of a Dispose or a finalizer) as simple as possible so it won\'t fail. Using reflection inside of a dispose (and especially a finalizer) is generally a bad idea.</p>\n\n<p>As far as implementing finalizers, in general you don\'t need to. Finalizers add a cost to your object and are hard to write correctly as most of the assumptions you can normally make about the state of the object and the runtime are not valid.</p>\n\n<p>See this <a href="http://www.codeproject.com/KB/cs/idisposable.aspx" rel="nofollow noreferrer">article</a> for more information on the Dispose pattern.</p>\n'}, {'answer_id': 3681224, 'author': 'SUmeet Khandelwal', 'author_id': 443903, 'author_profile': 'https://Stackoverflow.com/users/443903', 'pm_score': 2, 'selected': False, 'text': '<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace TestDisposeInheritance\n{\n class Program\n {\n static void Main(string[] args)\n {\n classC c = new classC();\n c.Dispose();\n }\n }\n\n class classA: IDisposable \n { \n private bool m_bDisposed;\n protected virtual void Dispose(bool bDisposing)\n {\n if (!m_bDisposed)\n {\n if (bDisposing)\n {\n // Dispose managed resources\n Console.WriteLine("Dispose A"); \n }\n // Dispose unmanaged resources \n }\n }\n public void Dispose() \n {\n Dispose(true);\n GC.SuppressFinalize(this);\n Console.WriteLine("Disposing A"); \n } \n } \n\n class classB : classA, IDisposable \n {\n private bool m_bDisposed;\n public void Dispose()\n {\n Dispose(true);\n base.Dispose();\n GC.SuppressFinalize(this);\n Console.WriteLine("Disposing B");\n }\n\n protected override void Dispose(bool bDisposing)\n {\n if (!m_bDisposed)\n {\n if (bDisposing)\n {\n // Dispose managed resources\n Console.WriteLine("Dispose B");\n }\n // Dispose unmanaged resources \n }\n }\n } \n\n class classC : classB, IDisposable \n {\n private bool m_bDisposed;\n public void Dispose() \n {\n Dispose(true);\n base.Dispose();\n GC.SuppressFinalize(this);\n Console.WriteLine("Disposing C"); \n }\n protected override void Dispose(bool bDisposing)\n {\n if (!m_bDisposed)\n {\n if (bDisposing)\n {\n // Dispose managed resources\n Console.WriteLine("Dispose C"); \n }\n // Dispose unmanaged resources \n }\n }\n } \n\n}\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78141', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7984/'] |
78,153 | <p>Does anyone know of an RTF control that can be used on Linux/Windows/Mac? It's unfortunate that I have to mention it, but it actually has to be able to save and open rtf files... unlike wxWidgets wxRichTextCtrl for instance.</p>
<p>Edit: Thanks to HappySmileMan for his reply. Better still if it's more of a standalone and not a part of a large library that it would depend on.</p>
<p>Edit: ... and it doesn't look like it can open rtf files... ugh.</p>
| [{'answer_id': 78176, 'author': 'HappySmileMan', 'author_id': 14073, 'author_profile': 'https://Stackoverflow.com/users/14073', 'pm_score': 0, 'selected': False, 'text': '<p>If I understand the question correctly, the feature you are looking for is in the Qt toolkit.</p>\n\n<p>Some info on this can be found at <a href="https://doc.qt.io/qt-5/richtext.html" rel="nofollow noreferrer">https://doc.qt.io/qt-5/richtext.html</a></p>\n'}, {'answer_id': 78214, 'author': 'puetzk', 'author_id': 14312, 'author_profile': 'https://Stackoverflow.com/users/14312', 'pm_score': 0, 'selected': False, 'text': "<p>Qt's control is HTML, not RTF (though foobar may just mean rich text, in which case it would be fine)</p>\n"}, {'answer_id': 107051, 'author': 'foobar', 'author_id': 14278, 'author_profile': 'https://Stackoverflow.com/users/14278', 'pm_score': 0, 'selected': False, 'text': "<p>It seems that what I want (cross platform rtf control that reads and writes actual rtf files) doesn't exist, at least not for free and open source.\n...I'd accept this answer but it doesn't seem possible.</p>\n"}, {'answer_id': 124637, 'author': 'puetzk', 'author_id': 14312, 'author_profile': 'https://Stackoverflow.com/users/14312', 'pm_score': 1, 'selected': False, 'text': '<p>RTF is simply not that common; it\'s a messy format controlled by Microsoft, basically a text dump of the .doc format. The only open source RTF implementations I know of are in Abiword, OpenOffice, and KWord. All are cross-platform, but none probably qualify as "controls" to your liking (though abiword has a bonobo interface, and KWord has a KPart, so they can be embedded, albeit in a heavyweight fashion).</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78153', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14278/'] |
78,157 | <p>I'm working on an embedded Linux project that interfaces an ARM9 to a hardware video encoder chip, and writes the video out to SD card or USB stick. The software architecture involves a kernel driver that reads data into a pool of buffers, and a userland app that writes the data to a file on the mounted removable device.</p>
<p>I am finding that above a certain data rate (around 750kbyte/sec) I start to see the userland video-writing app stalling for maybe half a second, about every 5 seconds. This is enough to cause the kernel driver to run out of buffers - and even if I could increase the number of buffers, the video data has to be synchronised (ideally within 40ms) with other things that are going on in real time. Between these 5 second "lag spikes", the writes complete well within 40ms (as far as the app is concerned - I appreciate they're buffered by the OS)</p>
<p>I think this lag spike is to do with the way Linux is flushing data out to disk - I note that pdflush is designed to wake up every 5s, my understanding is that this would be what does the writing. As soon as the stall is over the userland app is able to quickly service and write the backlog of buffers (that didn't overflow).</p>
<p>I think the device I'm writing to has reasonable ultimate throughput: copying a 15MB file from a memory fs and waiting for sync to complete (and the usb stick's light to stop flashing) gave me a write speed of around 2.7MBytes/sec.</p>
<p>I'm looking for two kinds of clues:</p>
<ol>
<li><p>How can I stop the bursty writing from stalling my app - perhaps process priorities, realtime patches, or tuning the filesystem code to write continuously rather than burstily?</p></li>
<li><p>How can I make my app(s) aware of what is going on with the filesystem in terms of write backlog and throughput to the card/stick? I have the ability to change the video bitrate in the hardware codec on the fly which would be much better than dropping frames, or imposing an artificial cap on maximum allowed bitrate.</p></li>
</ol>
<p>Some more info: this is a 200MHz ARM9 currently running a Montavista 2.6.10-based kernel.</p>
<p>Updates:<ul>
<li>Mounting the filesystem SYNC causes throughput to be much too poor.
<li>The removable media is FAT/FAT32 formatted and must be as the purpose of the design is that the media can be plugged into any Windows PC and read.
<li>Regularly calling sync() or fsync() say, every second causes regular stalls and unacceptably poor throughput
<li>I am using write() and open(O_WRONLY | O_CREAT | O_TRUNC) rather than fopen() etc.
<li>I can't immediately find anything online about the mentioned "Linux realtime filesystems". Links?
</ul></p>
<p>I hope this makes sense. First embedded Linux question on stackoverflow? :)</p>
| [{'answer_id': 78200, 'author': 'jfs', 'author_id': 6223, 'author_profile': 'https://Stackoverflow.com/users/6223', 'pm_score': 0, 'selected': False, 'text': "<p>Well obvious first, have you tried explicitly telling the file to flush? I also think there might be some ioctl you can use to do it, but I honestly haven't done much C/POSIX file programming.</p>\n\n<p>Seeing you're on a Linux kernel you should be able to tune and rebuild the kernel to something that suits your needs better, eg. much more frequent but then also smaller flushes to the permanent storage.</p>\n\n<hr>\n\n<p>A quick check in my man pages finds this:</p>\n\n<pre>SYNC(2) Linux Programmer’s Manual SYNC(2)\n\nNAME\n sync - commit buffer cache to disk\n\nSYNOPSIS\n #include <unistd.h>\n\n void sync(void);\n\n Feature Test Macro Requirements for glibc (see feature_test_macros(7)):\n\n sync(): _BSD_SOURCE || _XOPEN_SOURCE >= 500\n\nDESCRIPTION\n sync() first commits inodes to buffers, and then buffers to disk.\n\nERRORS\n This function is always successful.</pre>\n"}, {'answer_id': 78231, 'author': 'Ori Pessach', 'author_id': 9047, 'author_profile': 'https://Stackoverflow.com/users/9047', 'pm_score': 1, 'selected': False, 'text': "<p>Without knowing more about your particular circumstances, I can only offer the following guesses:</p>\n\n<p>Try using fsync()/sync() to force the kernel to flush data to the storage device more frequently. It sounds like the kernel buffers all your writes and then ties up the bus or otherwise stalls your system while performing the actual write. With careful calls to fsync() you can try to schedule writes over the system bus in a more fine grained way.</p>\n\n<p>It might make sense to structure the application in such a way that the encoding/capture (you didn't mention video capture, so I'm making an assumption here - you might want to add more information) task runs in its own thread and buffers its output in userland - then, a second thread can handle writing to the device. This will give you a smoothing buffer to allow the encoder to always finish its writes without blocking.</p>\n\n<p>One thing that sounds suspicious is that you only see this problem at a certain data rate - if this really was a buffering issue, I'd expect the problem to happen less frequently at lower data rates, but I'd still expect to see this issue.</p>\n\n<p>In any case, more information might prove useful. What's your system's architecture? (In very general terms.)</p>\n\n<p>Given the additional information you provided, it sounds like the device's throughput is rather poor for small writes and frequent flushes. If you're sure that for larger writes you can get sufficient throughput (and I'm not sure that's the case, but the file system might be doing something stupid, like updating the FAT after every write) then having an encoding thread piping data to a writing thread with sufficient buffering in the writing thread to avoid stalls. I've used shared memory ring buffers in the past to implement this kind of scheme, but any IPC mechanism that would allow the writer to write to the I/O process without stalling unless the buffer is full should do the trick.</p>\n"}, {'answer_id': 78281, 'author': 'JBB', 'author_id': 12332, 'author_profile': 'https://Stackoverflow.com/users/12332', 'pm_score': 2, 'selected': False, 'text': "<p>Sounds like you're looking for linux realtime filesystems. Be sure to search Google et al for that.</p>\n\n<p>XFS has a realtime option, though I haven't played with it. </p>\n\n<p>hdparm might let you turn off the caching altogether.</p>\n\n<p>Tuning the filesystem options (turn off all the extra unneeded file attributes) might reduce what you need to flush, thus speeding the flush. I doubt that'd help much, though.</p>\n\n<p>But my suggestion would be to avoid using the stick as a filesystem at all and instead use it as a raw device. Stuff data on it like you would using 'dd'. Then elsewhere read that raw data and write it out after baking.</p>\n\n<p>Of course, I don't know if that's an option for you.</p>\n"}, {'answer_id': 78284, 'author': 'Drew Frezell', 'author_id': 10954, 'author_profile': 'https://Stackoverflow.com/users/10954', 'pm_score': 3, 'selected': False, 'text': "<p>I'll throw out some suggestions, advice is cheap.</p>\n\n<ul>\n<li>make sure you are using a lower level API for writing to the disk, don't use user-mode caching functions like <code>fopen, fread, fwrite</code> use the lower level functions <code>open, read, write</code>.</li>\n<li>pass the <code>O_SYNC</code> flag when you open the file, this will cause each write operation to block until written to disk, which will remove the bursty behavior of your writes...with the expense of each write being slower.</li>\n<li>If you are doing reads/ioctls from a device to grab a chunk of video data, you may want to consider allocating a shared memory region between the application and kernel, otherwise you are getting hit with a bunch of <code>copy_to_user</code> calls when transferring video data buffers from kernel space to user space.</li>\n<li>You may need to validate that your USB flash device is fast enough with sustained transfers to write the data.</li>\n</ul>\n\n<p>Just a couple thoughts, hope this helps.</p>\n"}, {'answer_id': 83438, 'author': 'JBB', 'author_id': 12332, 'author_profile': 'https://Stackoverflow.com/users/12332', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://www.westnet.com/~gsmith/content/linux-pdflush.htm" rel="nofollow noreferrer">Here</a> is some information about tuning pdflush for write-heavy operations.</p>\n'}, {'answer_id': 84160, 'author': 'shodanex', 'author_id': 11589, 'author_profile': 'https://Stackoverflow.com/users/11589', 'pm_score': 1, 'selected': False, 'text': '<p>Has a debugging aid, you could use strace to see what operations is taking time.\nThere might be some surprising thing with the FAT/FAT32.</p>\n\n<p>Do you write into a single file, or in multiple file ?</p>\n\n<p>You can make a reading thread, that will maintain a pool of video buffer ready to be written in a queue. \nWhen a frame is received, it is added to the queue, and the writing thread is signaled</p>\n\n<p>Shared data</p>\n\n<pre><code>empty_buffer_queue\nready_buffer_queue\nvideo_data_ready_semaphore\n</code></pre>\n\n<p>Reading thread :</p>\n\n<pre><code>buf=get_buffer()\nbufer_to_write = buf_dequeue(empty_buffer_queue)\nmemcpy(bufer_to_write, buf)\nbuf_enqueue(bufer_to_write, ready_buffer_queue)\nsem_post(video_data_ready_semaphore)\n</code></pre>\n\n<p>Writing thread</p>\n\n<pre><code>sem_wait(vido_data_ready_semaphore)\nbufer_to_write = buf_dequeue(ready_buffer_queue)\nwrite_buffer\nbuf_enqueue(bufer_to_write, empty_buffer_queue)\n</code></pre>\n\n<p>If your writing threaded is blocked waiting for the kernel, this could work.\nHowever, if you are blocked inside the kerne space, then thereis nothing much you can do, except looking for a more recent kernel than your 2.6.10</p>\n'}, {'answer_id': 85358, 'author': 'pjz', 'author_id': 8002, 'author_profile': 'https://Stackoverflow.com/users/8002', 'pm_score': 0, 'selected': False, 'text': "<p>Doing your own flush()ing sounds right to me - you want to be in control, not leave it to the vagaries of the generic buffer layer.</p>\n\n<p>This may be obvious, but make sure you're not calling write() too often - make sure every write() has enough data to be written to make the syscall overhead worth it. Also, in the other direction, don't call it too seldom, or it'll block for long enough to cause a problem.</p>\n\n<p>On a more difficult-to-reimplement track, have you tried switching to asynchronous i/o? Using aio you could fire off a write and hand it one set of buffers while you're sucking video data into the other set, and when the write finishes you switch sets of buffers.</p>\n"}, {'answer_id': 93050, 'author': 'Zan Lynx', 'author_id': 13422, 'author_profile': 'https://Stackoverflow.com/users/13422', 'pm_score': 1, 'selected': False, 'text': "<p>A useful Linux function and alternative to sync or fsync is sync_file_range. This lets you schedule data for writing without waiting for the in-kernel buffer system to get around to it.</p>\n\n<p>To avoid long pauses, make sure your IO queue (for example: /sys/block/hda/queue/nr_requests) is large enough. That queue is where data goes in between being flushed from memory and arriving on disk.</p>\n\n<p>Note that sync_file_range isn't portable, and is only available in kernels 2.6.17 and later.</p>\n"}, {'answer_id': 215547, 'author': 'blueshift', 'author_id': 14200, 'author_profile': 'https://Stackoverflow.com/users/14200', 'pm_score': 4, 'selected': True, 'text': "<p>For the record, there turned out to be two main aspects that seem to have eliminated the problem in all but the most extreme cases. This system is still in development and hasn't been thoroughly torture-tested yet but is working fairly well (touch wood).</p>\n\n<p>The big win came from making the userland writer app multi-threaded. It is the calls to write() that block sometimes: other processes and threads still run. So long as I have a thread servicing the device driver and updating frame counts and other data to sychronise with other apps that are running, the data can be buffered and written out a few seconds later without breaking any deadlines. I tried a simple ping-pong double buffer first but that wasn't enough; small buffers would be overwhelmed and big ones just caused bigger pauses while the filesystem digested the writes. A pool of 10 1MB buffers queued between threads is working well now.</p>\n\n<p>The other aspect is keeping an eye on ultimate write throughput to physical media. For this I am keeping an eye on the stat Dirty: reported by /proc/meminfo. I have some rough and ready code to throttle the encoder if Dirty: climbs above a certain threshold, seems to vaguely work. More testing and tuning needed later. Fortunately I have lots of RAM (128M) to play with giving me a few seconds to see my backlog building up and throttle down smoothly.</p>\n\n<p>I'll try to remember to pop back and update this answer if I find I need to do anything else to deal with this issue. Thanks to the other answerers.</p>\n"}, {'answer_id': 4211588, 'author': 'David Cary', 'author_id': 238320, 'author_profile': 'https://Stackoverflow.com/users/238320', 'pm_score': 1, 'selected': False, 'text': '<p>I\'ve been told that after the host sends a command, MMC and SD cards "must respond within 0 to 8 bytes".</p>\n\n<p>However, the spec allows these cards to respond with "busy" until they have finished the operation, and apparently there is no limit to how long a card can claim to be busy (please, please tell me if there is such a limit).</p>\n\n<p>I see that some low-cost flash chips such as the M25P80 have a guaranteed "maximum single-sector erase time" of 3 seconds, although typically it "only" requires 0.6 seconds.</p>\n\n<p>That 0.6 seconds sounds suspiciously similar to your "stalling for maybe half a second".</p>\n\n<p>I suspect the tradeoff between cheap, slow flash chips and expensive, fast flash chips has something to do with the wide variation in USB flash drive results:</p>\n\n<ul>\n<li><a href="http://www.testfreaks.com/blog/information/16gb-usb-drive-comparison-17-drives-compared/" rel="nofollow">http://www.testfreaks.com/blog/information/16gb-usb-drive-comparison-17-drives-compared/</a></li>\n<li><a href="http://www.tomshardware.com/reviews/data-transfer-run,1037-10.html" rel="nofollow">http://www.tomshardware.com/reviews/data-transfer-run,1037-10.html</a></li>\n</ul>\n\n<p>I\'ve heard rumors that every time a flash sector is erased and then re-programmed, it takes a little bit longer than the last time.</p>\n\n<p>So if you have a time-critical application, you may need to (a) test your SD cards and USB sticks to make sure they meet the minimum latency, bandwidth, etc. required by your application, and (b) peridically re-test or pre-emptively replace these memory devices.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78157', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14200/'] |
78,161 | <p>In a C++ app, I have an hWnd pointing to a window running in a third party process. This window contains controls which extend the COM TreeView control. I am interested in obtaining the CheckState of this control.<br>
I use the hWnd to get an HTREEITEM using TreeView_GetRoot(hwnd) from commctrl.h</p>
<p>hwnd points to the window and hItem is return value from TreeView_GetRoot(hwnd). They are used as follows:</p>
<pre><code>int iCheckState = TreeView_GetCheckState(hwnd, hItem);
switch (iCheckState)
{
case 0:
// (unchecked)
case 1:
// checked
...
}
</code></pre>
<p>I'm looking to port this code into a C# app which does the same thing (switches off the CheckState of the TreeView control). I have never used COM and am quite unfamiliar.</p>
<p>I have tried using the .NET mscomctl but can't find equivalent methods to TreeView_GetRoot or TreeView_GetCheckState. I'm totally stuck and don't know how to recreate this code in C# :(</p>
<p>Suggestions?</p>
| [{'answer_id': 78229, 'author': 'Mike Dimmick', 'author_id': 6970, 'author_profile': 'https://Stackoverflow.com/users/6970', 'pm_score': 1, 'selected': False, 'text': "<p>Why are you not using a Windows Forms TreeView control? If you are using this control, set the control's CheckBoxes property to true to enable check boxes, and set the Checked property on the nodes you want to display checked.</p>\n\n<p>To get the collection of root nodes, use the TreeView's Nodes property. This returns a TreeNodeCollection which you can then index or add items to.</p>\n"}, {'answer_id': 79794, 'author': 'Frank Krueger', 'author_id': 338, 'author_profile': 'https://Stackoverflow.com/users/338', 'pm_score': 3, 'selected': True, 'text': '<p>We have these definitions from CommCtrl.h:</p>\n\n<pre><code>#define TreeView_SetItemState(hwndTV, hti, data, _mask) \\\n{ TVITEM _ms_TVi;\\\n _ms_TVi.mask = TVIF_STATE; \\\n _ms_TVi.hItem = (hti); \\\n _ms_TVi.stateMask = (_mask);\\\n _ms_TVi.state = (data);\\\n SNDMSG((hwndTV), TVM_SETITEM, 0, (LPARAM)(TV_ITEM *)&_ms_TVi);\\\n}\n\n#define TreeView_SetCheckState(hwndTV, hti, fCheck) \\\n TreeView_SetItemState(hwndTV, hti, INDEXTOSTATEIMAGEMASK((fCheck)?2:1), TVIS_STATEIMAGEMASK)\n</code></pre>\n\n<p>We can translate this to C# using PInvoke. First, we implement these macros as functions, and then add whatever\nother support is needed to make those functions work. Here is my first shot at it. You should double check my\ncode especially when it comes to the marshalling of the struct. Further, you may want to Post the message cross-thread\ninstead of calling SendMessage.</p>\n\n<p>Lastly, I am not sure if this will work at all since I believe that the common\ncontrols use WM_USER+ messages. When these messages are sent cross-process, the data parameter\'s addresses\nare unmodified and the resulting process may cause an Access Violation. This would be a problem in whatever\nlanguage you use (C++ or C#), so perhaps I am wrong here (you say you have a working C++ program).</p>\n\n<pre><code>static class Interop {\n\npublic static IntPtr TreeView_SetCheckState(HandleRef hwndTV, IntPtr hti, bool fCheck) {\n return TreeView_SetItemState(hwndTV, hti, INDEXTOSTATEIMAGEMASK((fCheck) ? 2 : 1), (uint)TVIS.TVIS_STATEIMAGEMASK);\n}\n\npublic static IntPtr TreeView_SetItemState(HandleRef hwndTV, IntPtr hti, uint data, uint _mask) {\n TVITEM _ms_TVi = new TVITEM();\n _ms_TVi.mask = (uint)TVIF.TVIF_STATE;\n _ms_TVi.hItem = (hti);\n _ms_TVi.stateMask = (_mask);\n _ms_TVi.state = (data);\n IntPtr p = Marshal.AllocCoTaskMem(Marshal.SizeOf(_ms_TVi));\n Marshal.StructureToPtr(_ms_TVi, p, false);\n IntPtr r = SendMessage(hwndTV, (int)TVM.TVM_SETITEMW, IntPtr.Zero, p);\n Marshal.FreeCoTaskMem(p);\n return r;\n}\n\nprivate static uint INDEXTOSTATEIMAGEMASK(int i) { return ((uint)(i) << 12); }\n\n[DllImport("user32.dll", CharSet = CharSet.Auto)]\nprivate static extern IntPtr SendMessage(HandleRef hWnd, int msg, IntPtr wParam, IntPtr lParam);\n\nprivate enum TVIF : uint {\n TVIF_STATE = 0x0008\n}\n\nprivate enum TVIS : uint {\n TVIS_STATEIMAGEMASK = 0xF000\n}\n\nprivate enum TVM : int {\n TV_FIRST = 0x1100,\n TVM_SETITEMA = (TV_FIRST + 13),\n TVM_SETITEMW = (TV_FIRST + 63)\n}\n\nprivate struct TVITEM {\n public uint mask;\n public IntPtr hItem;\n public uint state;\n public uint stateMask;\n public IntPtr pszText;\n public int cchTextMax;\n public int iImage;\n public int iSelectedImage;\n public int cChildren;\n public IntPtr lParam;\n}\n}\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78161', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/165305/'] |
78,172 | <p>In the C programming language and Pthreads as the threading library; do variables/structures that are shared between threads need to be declared as volatile? Assuming that they might be protected by a lock or not (barriers perhaps).</p>
<p>Does the pthread POSIX standard have any say about this, is this compiler-dependent or neither?</p>
<p>Edit to add: Thanks for the great answers. But what if you're <em>not</em> using locks; what if you're using <a href="http://en.wikipedia.org/wiki/Barrier_(computer_science)" rel="noreferrer">barriers</a> for example? Or code that uses primitives such as <a href="http://en.wikipedia.org/wiki/Compare_and_swap" rel="noreferrer">compare-and-swap</a> to directly and atomically modify a shared variable...</p>
| [{'answer_id': 78185, 'author': 'Tom Leys', 'author_id': 11440, 'author_profile': 'https://Stackoverflow.com/users/11440', 'pm_score': 0, 'selected': False, 'text': "<p>Volatile means that we have to go to memory to get or set this value. If you don't set volatile, the compiled code might store the data in a register for a long time. </p>\n\n<p>What this means is that you should mark variables that you share between threads as volatile so that you don't have situations where one thread starts modifying the value but doesn't write its result before a second thread comes along and tries to read the value. </p>\n\n<p>Volatile is a compiler hint that disables certain optimizations. The output assembly of the compiler might have been safe without it but you should always use it for shared values. </p>\n\n<p>This is especially important if you are NOT using the expensive thread sync objects provided by your system - you might for example have a data structure where you can keep it valid with a series of atomic changes. Many stacks that do not allocate memory are examples of such data structures, because you can add a value to the stack then move the end pointer or remove a value from the stack after moving the end pointer. When implementing such a structure, volatile becomes crucial to ensure that your atomic instructions are actually atomic.</p>\n"}, {'answer_id': 78196, 'author': 'Dark Shikari', 'author_id': 11206, 'author_profile': 'https://Stackoverflow.com/users/11206', 'pm_score': 2, 'selected': False, 'text': "<p>In my experience, no; you just have to properly mutex yourself when you write to those values, or structure your program such that the threads will stop before they need to access data that depends on another thread's actions. My project, x264, uses this method; threads share an enormous amount of data but the vast majority of it doesn't need mutexes because its either read-only or a thread will wait for the data to become available and finalized before it needs to access it.</p>\n\n<p>Now, if you have many threads that are all heavily interleaved in their operations (they depend on each others' output on a very fine-grained level), this may be a lot harder--in fact, in such a case I'd consider revisiting the threading model to see if it can possibly be done more cleanly with more separation between threads.</p>\n"}, {'answer_id': 78221, 'author': 'Don Neufeld', 'author_id': 13097, 'author_profile': 'https://Stackoverflow.com/users/13097', 'pm_score': 5, 'selected': False, 'text': '<p>As long as you are using locks to control access to the variable, you do not need volatile on it. In fact, if you\'re putting volatile on any variable you\'re probably already wrong.</p>\n\n<p><a href="http://web.archive.org/web/20190219170904/https://software.intel.com/en-us/blogs/2007/11/30/volatile-almost-useless-for-multi-threaded-programming/" rel="nofollow noreferrer">https://software.intel.com/en-us/blogs/2007/11/30/volatile-almost-useless-for-multi-threaded-programming/</a></p>\n'}, {'answer_id': 78228, 'author': 'Branan', 'author_id': 13894, 'author_profile': 'https://Stackoverflow.com/users/13894', 'pm_score': 0, 'selected': False, 'text': "<p>Volatile would only be useful if you need absolutely no delay between when one thread writes something and another thread reads it. Without some sort of lock, though, you have no idea of <em>when</em> the other thread wrote the data, only that it's the most recent possible value.</p>\n\n<p>For simple values (int and float in their various sizes) a mutex might be overkill if you don't need an explicit synch point. If you don't use a mutex or lock of some sort, you should declare the variable volatile. If you use a mutex you're all set.</p>\n\n<p>For complicated types, you must use a mutex. Operations on them are non-atomic, so you could read a half-changed version without a mutex.</p>\n"}, {'answer_id': 166767, 'author': 'jakobengblom2', 'author_id': 23054, 'author_profile': 'https://Stackoverflow.com/users/23054', 'pm_score': 4, 'selected': True, 'text': '<p>I think one very important property of volatile is that it makes the variable be written to memory when modified, and reread from memory each time it accessed. The other answers here mix volatile and synchronization, and it is clear from some other answers than this that volatile is NOT a sync primitive (credit where credit is due). </p>\n\n<p>But unless you use volatile, the compiler is free to cache the shared data in a register for any length of time... if you want your data to be written to be predictably written to actual memory and not just cached in a register by the compiler at its discretion, you will need to mark it as volatile. Alternatively, if you only access the shared data after you have left a function modifying it, you might be fine. But I would suggest not relying on blind luck to make sure that values are written back from registers to memory. </p>\n\n<p>Especially on register-rich machines (i.e., not x86), variables can live for quite long periods in registers, and a good compiler can cache even parts of structures or entire structures in registers. So you should use volatile, but for performance, also copy values to local variables for computation and then do an explicit write-back. Essentially, using volatile efficiently means doing a bit of load-store thinking in your C code. </p>\n\n<p>In any case, you positively have to use some kind of OS-level provided sync mechanism to create a correct program. </p>\n\n<p>For an example of the weakness of volatile, see my Decker\'s algorithm example at <a href="http://jakob.engbloms.se/archives/65" rel="noreferrer">http://jakob.engbloms.se/archives/65</a>, which proves pretty well that volatile does not work to synchronize. </p>\n'}, {'answer_id': 559133, 'author': 'cmcginty', 'author_id': 64313, 'author_profile': 'https://Stackoverflow.com/users/64313', 'pm_score': 2, 'selected': False, 'text': '<p>NO. </p>\n\n<p><code>Volatile</code> is only required when reading a memory location that can change independently of the CPU read/write commands. In the situation of threading, the CPU is in full control of read/writes to memory for each thread, therefore the compiler can assume the memory is coherent and optimizes the CPU instructions to reduce unnecessary memory access.</p>\n\n<p>The primary usage for <code>volatile</code> is for accessing memory-mapped I/O. In this case, the underlying device can change the value of a memory location independently from CPU. If you do not use <code>volatile</code> under this condition, the CPU may use a previously cached memory value, instead of reading the newly updated value.</p>\n'}, {'answer_id': 784840, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': "<p>The answer is absolutely, unequivocally, NO. You do not need to use 'volatile' in addition to proper synchronization primitives. Everything that needs to be done are done by these primitives.</p>\n\n<p>The use of 'volatile' is neither necessary nor sufficient. It's not necessary because the proper synchronization primitives are sufficient. It's not sufficient because it only disables some optimizations, not all of the ones that might bite you. For example, it does not guarantee either atomicity or visibility on another CPU.</p>\n\n<blockquote>\n <p>But unless you use volatile, the compiler is free to cache the shared data in a register for any length of time... if you want your data to be written to be predictably written to actual memory and not just cached in a register by the compiler at its discretion, you will need to mark it as volatile. Alternatively, if you only access the shared data after you have left a function modifying it, you might be fine. But I would suggest not relying on blind luck to make sure that values are written back from registers to memory.</p>\n</blockquote>\n\n<p>Right, but even if you do use volatile, the CPU is free to cache the shared data in a write posting buffer for any length of time. The set of optimizations that can bite you is not precisely the same as the set of optimizations that 'volatile' disables. So if you use 'volatile', you <em>are</em> relying on blind luck.</p>\n\n<p>On the other hand, if you use sychronization primitives with defined multi-threaded semantics, you are guaranteed that things will work. As a plus, you don't take the huge performance hit of 'volatile'. So why not do things that way?</p>\n"}, {'answer_id': 3770959, 'author': 'Stephen Nuchia', 'author_id': 455224, 'author_profile': 'https://Stackoverflow.com/users/455224', 'pm_score': -1, 'selected': False, 'text': '<p>Some people obviously are assuming that the compiler treats the synchronization calls as memory barriers. "Casey" is assuming there is exactly one CPU.</p>\n\n<p>If the sync primitives are external functions and the symbols in question are visible outside the compilation unit (global names, exported pointer, exported function that may modify them) then the compiler will treat them -- or any other external function call -- as a memory fence with respect to all externally visible objects.</p>\n\n<p>Otherwise, you are on your own. And volatile may be the best tool available for making the compiler produce correct, fast code. It generally won\'t be portable though, when you need volatile and what it actually does for you depends a lot on the system and compiler.</p>\n'}, {'answer_id': 4074757, 'author': 'Adam Soffer', 'author_id': 352241, 'author_profile': 'https://Stackoverflow.com/users/352241', 'pm_score': -1, 'selected': False, 'text': "<p>Variables that are shared among threads should be declared 'volatile'. This tells the\ncompiler that when one thread writes to such variables, the write should be to memory\n(as opposed to a register).</p>\n"}, {'answer_id': 8120128, 'author': 'IOException', 'author_id': 230803, 'author_profile': 'https://Stackoverflow.com/users/230803', 'pm_score': 2, 'selected': False, 'text': '<p>There is a widespread notion that the keyword volatile is good for multi-threaded programming. </p>\n\n<p>Hans Boehm <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2016.html" rel="nofollow">points out</a> that there are only three portable uses for volatile:</p>\n\n<ul>\n<li><em>volatile</em> may be used to mark local variables in the same scope as a setjmp whose value should be preserved across a longjmp. It is unclear what fraction of such uses would be slowed down, since the atomicity and ordering constraints have no effect if there is no way to share the local variable in question. (It is even unclear what fraction of such uses would be slowed down by requiring all variables to be preserved across a longjmp, but that is a separate matter and is not considered here.)</li>\n<li><em>volatile</em> may be used when variables may be "externally modified", but the modification in fact is triggered synchronously by the thread itself, e.g. because the underlying memory is mapped at multiple locations.</li>\n<li>A <em>volatile</em> sigatomic_t may be used to communicate with a signal handler in the same thread, in a restricted manner. One could consider weakening the requirements for the sigatomic_t case, but that seems rather counterintuitive.</li>\n</ul>\n\n<p>If you are <em>multi-threading</em> for the sake of speed, slowing down code is definitely not what you want. For multi-threaded programming, there two key issues that volatile is often mistakenly thought to address:</p>\n\n<ul>\n<li><em>atomicity</em></li>\n<li><em>memory consistency</em>, i.e. the order of a thread\'s operations as seen by another thread.</li>\n</ul>\n\n<p>Let\'s deal with (1) first. Volatile does not guarantee atomic reads or writes. For example, a volatile read or write of a 129-bit structure is not going to be atomic on most modern hardware. A volatile read or write of a 32-bit int is atomic on most modern hardware, but <em>volatile has nothing to do with it</em>. It would likely be atomic without the volatile. The atomicity is at the whim of the compiler. There\'s nothing in the C or C++ standards that says it has to be atomic.</p>\n\n<p>Now consider issue (2). Sometimes programmers think of volatile as turning off optimization of volatile accesses. That\'s largely true in practice. But that\'s only the volatile accesses, not the non-volatile ones. Consider this fragment:</p>\n\n<pre><code> volatile int Ready; \n\n int Message[100]; \n\n void foo( int i ) { \n\n Message[i/10] = 42; \n\n Ready = 1; \n\n }\n</code></pre>\n\n<p>It\'s trying to do something very reasonable in multi-threaded programming: write a message and then send it to another thread. The other thread will wait until Ready becomes non-zero and then read Message. Try compiling this with "gcc -O2 -S" using gcc 4.0, or icc. Both will do the store to Ready first, so it can be overlapped with the computation of i/10. The reordering is not a compiler bug. It\'s an aggressive optimizer doing its job.</p>\n\n<p>You might think the solution is to mark all your memory references volatile. That\'s just plain silly. As the earlier quotes say, it will just slow down your code. Worst yet, it might not fix the problem. Even if the compiler does not reorder the references, the hardware might. In this example, x86 hardware will not reorder it. Neither will an Itanium(TM) processor, because Itanium compilers insert memory fences for volatile stores. That\'s a clever Itanium extension. But chips like Power(TM) will reorder. What you really need for ordering are <em>memory fences</em>, also called <em>memory barriers</em>. A memory fence prevents reordering of memory operations across the fence, or in some cases, prevents reordering in one direction.Volatile has nothing to do with memory fences.</p>\n\n<p>So what\'s the solution for multi-threaded programming? Use a library or language extension that implements the atomic and fence semantics. When used as intended, the operations in the library will insert the right fences. Some examples:</p>\n\n<ul>\n<li>POSIX threads</li>\n<li>Windows(TM) threads</li>\n<li>OpenMP</li>\n<li>TBB</li>\n</ul>\n\n<p>Based on <a href="http://software.intel.com/en-us/blogs/2007/11/30/volatile-almost-useless-for-multi-threaded-programming/" rel="nofollow">article by Arch Robison (Intel)</a></p>\n'}, {'answer_id': 36608264, 'author': 'David Schwartz', 'author_id': 721269, 'author_profile': 'https://Stackoverflow.com/users/721269', 'pm_score': -1, 'selected': False, 'text': "<p>No.</p>\n\n<p>First, <code>volatile</code> is not necessary. There are numerous other operations that provide guaranteed multithreaded semantics that don't use <code>volatile</code>. These include atomic operations, mutexes, and so on.</p>\n\n<p>Second, <code>volatile</code> is not sufficient. The C standard does not provide any guarantees about multithreaded behavior for variables declared <code>volatile</code>.</p>\n\n<p>So being neither necessary nor sufficient, there's not much point in using it.</p>\n\n<p>One exception would be particular platforms (such as Visual Studio) where it does have documented multithreaded semantics.</p>\n"}, {'answer_id': 46987303, 'author': 'Patrick Pan', 'author_id': 2376062, 'author_profile': 'https://Stackoverflow.com/users/2376062', 'pm_score': 0, 'selected': False, 'text': '<p>The underlying reason is that the C language semantic is based upon a <strong>single-threaded abstract machine</strong>. And the compiler is within its own right to transform the program as long as the program\'s \'observable behaviors\' on the abstract machine stay unchanged. It can merge adjacent or overlapping memory accesses, redo a memory access multiple times (upon register spilling for example), or simply discard a memory access, if it thinks the program\'s behaviors, when executed in <strong>a single thread</strong>, doesn\'t change. Therefore as you may suspect, the behaviors <strong>do</strong> change if the program is actually supposed to be executing in a multi-threaded way.</p>\n\n<p>As Paul Mckenney pointed out in a famous <a href="http://elixir.free-electrons.com/linux/latest/source/Documentation/memory-barriers.txt#L264" rel="nofollow noreferrer" title="memory-barriers.txt">Linux kernel document</a>:</p>\n\n<blockquote>\n <p>It _must_not_ be assumed that the compiler will do what you want\n with memory references that are not protected by READ_ONCE() and\n WRITE_ONCE(). Without them, the compiler is within its rights to\n do all sorts of "creative" transformations, which are covered in\n the COMPILER BARRIER section.</p>\n</blockquote>\n\n<p>READ_ONCE() and WRITE_ONCE() are defined as volatile casts on referenced variables. Thus:</p>\n\n<pre><code>int y;\nint x = READ_ONCE(y);\n</code></pre>\n\n<p>is equivalent to:</p>\n\n<pre><code>int y;\nint x = *(volatile int *)&y;\n</code></pre>\n\n<p>So, unless you make a \'volatile\' access, you are not assured that the access happens <strong>exactly once</strong>, no matter what synchronization mechanism you are using. Calling an external function (pthread_mutex_lock for example) may force the compiler do memory accesses to global variables. But this happens only when the compiler fails to figure out whether the external function changes these global variables or not. Modern compilers employing sophisticated inter-procedure analysis and link-time optimization make this trick simply useless.</p>\n\n<p>In summary, you should mark variables shared by multiple threads volatile or access them using volatile casts.</p>\n\n<hr>\n\n<p>As Paul McKenney has also pointed out:</p>\n\n<blockquote>\n <p>I have seen the glint in their eyes when they discuss optimization techniques that you would not want your children to know about!</p>\n</blockquote>\n\n<hr>\n\n<p>But see what happens to <strong>C11/C++11</strong>.</p>\n'}, {'answer_id': 58935671, 'author': 'Ciro Santilli OurBigBook.com', 'author_id': 895245, 'author_profile': 'https://Stackoverflow.com/users/895245', 'pm_score': 1, 'selected': False, 'text': '<p><strong>POSIX 7 guarantees that functions such as <code>pthread_lock</code> also synchronize memory</strong></p>\n\n<p><a href="https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_11" rel="nofollow noreferrer">https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_11</a> "4.12 Memory Synchronization" says:</p>\n\n<blockquote>\n <p>The following functions synchronize memory with respect to other threads:</p>\n\n<pre><code>pthread_barrier_wait()\npthread_cond_broadcast()\npthread_cond_signal()\npthread_cond_timedwait()\npthread_cond_wait()\npthread_create()\npthread_join()\npthread_mutex_lock()\npthread_mutex_timedlock()\npthread_mutex_trylock()\npthread_mutex_unlock()\npthread_spin_lock()\npthread_spin_trylock()\npthread_spin_unlock()\npthread_rwlock_rdlock()\npthread_rwlock_timedrdlock()\npthread_rwlock_timedwrlock()\npthread_rwlock_tryrdlock()\npthread_rwlock_trywrlock()\npthread_rwlock_unlock()\npthread_rwlock_wrlock()\nsem_post()\nsem_timedwait()\nsem_trywait()\nsem_wait()\nsemctl()\nsemop()\nwait()\nwaitpid()\n</code></pre>\n</blockquote>\n\n<p>Therefore if your variable is guarded between <code>pthread_mutex_lock</code> and <code>pthread_mutex_unlock</code> then it does not need further synchronization as you might attempt to provide with <code>volatile</code>.</p>\n\n<p>Related questions:</p>\n\n<ul>\n<li><a href="https://stackoverflow.com/questions/3208060/does-guarding-a-variable-with-a-pthread-mutex-guarantee-its-also-not-cached">Does guarding a variable with a pthread mutex guarantee it's also not cached?</a></li>\n<li><a href="https://stackoverflow.com/questions/24137964/does-pthread-mutex-lock-contains-memory-fence-instruction">Does pthread_mutex_lock contains memory fence instruction?</a></li>\n</ul>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11688/'] |
78,181 | <p>If I am given a <code>MemoryStream</code> that I know has been populated with a <code>String</code>, how do I get a <code>String</code> back out?</p>
| [{'answer_id': 78189, 'author': 'Darren Kopp', 'author_id': 77, 'author_profile': 'https://Stackoverflow.com/users/77', 'pm_score': 6, 'selected': False, 'text': '<p>use a <a href="http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx" rel="nofollow noreferrer">StreamReader</a>, then you can use the <a href="http://msdn.microsoft.com/en-us/library/system.io.streamreader.readtoend.aspx" rel="nofollow noreferrer">ReadToEnd</a> method that returns a string.</p>\n'}, {'answer_id': 78190, 'author': 'Brian', 'author_id': 320, 'author_profile': 'https://Stackoverflow.com/users/320', 'pm_score': 7, 'selected': False, 'text': "<p>Using a StreamReader to convert the MemoryStream to a String.</p>\n\n<pre><code><Extension()> _\nPublic Function ReadAll(ByVal memStream As MemoryStream) As String\n ' Reset the stream otherwise you will just get an empty string.\n ' Remember the position so we can restore it later.\n Dim pos = memStream.Position\n memStream.Position = 0\n\n Dim reader As New StreamReader(memStream)\n Dim str = reader.ReadToEnd()\n\n ' Reset the position so that subsequent writes are correct.\n memStream.Position = pos\n\n Return str\nEnd Function\n</code></pre>\n"}, {'answer_id': 149993, 'author': 'Brian', 'author_id': 320, 'author_profile': 'https://Stackoverflow.com/users/320', 'pm_score': 10, 'selected': True, 'text': '<p>This sample shows how to read and write a string to a MemoryStream. </p>\n\n<hr>\n\n<pre><code>Imports System.IO\n\nModule Module1\n Sub Main()\n \' We don\'t need to dispose any of the MemoryStream \n \' because it is a managed object. However, just for \n \' good practice, we\'ll close the MemoryStream.\n Using ms As New MemoryStream\n Dim sw As New StreamWriter(ms)\n sw.WriteLine("Hello World")\n \' The string is currently stored in the \n \' StreamWriters buffer. Flushing the stream will \n \' force the string into the MemoryStream.\n sw.Flush()\n \' If we dispose the StreamWriter now, it will close \n \' the BaseStream (which is our MemoryStream) which \n \' will prevent us from reading from our MemoryStream\n \'sw.Dispose()\n\n \' The StreamReader will read from the current \n \' position of the MemoryStream which is currently \n \' set at the end of the string we just wrote to it. \n \' We need to set the position to 0 in order to read \n \' from the beginning.\n ms.Position = 0\n Dim sr As New StreamReader(ms)\n Dim myStr = sr.ReadToEnd()\n Console.WriteLine(myStr)\n\n \' We can dispose our StreamWriter and StreamReader \n \' now, though this isn\'t necessary (they don\'t hold \n \' any resources open on their own).\n sw.Dispose()\n sr.Dispose()\n End Using\n\n Console.WriteLine("Press any key to continue.")\n Console.ReadKey()\n End Sub\nEnd Module\n</code></pre>\n'}, {'answer_id': 234262, 'author': 'Coderer', 'author_id': 26286, 'author_profile': 'https://Stackoverflow.com/users/26286', 'pm_score': 9, 'selected': False, 'text': "<p>You can also use</p>\n\n<pre><code>Encoding.ASCII.GetString(ms.ToArray());\n</code></pre>\n\n<p>I don't <em>think</em> this is less efficient, but I couldn't swear to it. It also lets you choose a different encoding, whereas using a StreamReader you'd have to specify that as a parameter.</p>\n"}, {'answer_id': 2592074, 'author': 'James', 'author_id': 310910, 'author_profile': 'https://Stackoverflow.com/users/310910', 'pm_score': 3, 'selected': False, 'text': "<p>A slightly modified version of Brian's answer allows optional management of read start, This seems to be the easiest method. probably not the most efficient, but easy to understand and use.</p>\n\n<pre><code>Public Function ReadAll(ByVal memStream As MemoryStream, Optional ByVal startPos As Integer = 0) As String\n ' reset the stream or we'll get an empty string returned\n ' remember the position so we can restore it later\n Dim Pos = memStream.Position\n memStream.Position = startPos\n\n Dim reader As New StreamReader(memStream)\n Dim str = reader.ReadToEnd()\n\n ' reset the position so that subsequent writes are correct\n memStream.Position = Pos\n\n Return str\nEnd Function\n</code></pre>\n"}, {'answer_id': 13086317, 'author': 'Arek Bal', 'author_id': 1749204, 'author_profile': 'https://Stackoverflow.com/users/1749204', 'pm_score': 5, 'selected': False, 'text': '<p>Previous solutions wouldn\'t work in cases where encoding is involved. Here is - kind of a "real life" - example how to do this properly... </p>\n\n<pre class="lang-cs prettyprint-override"><code>using(var stream = new System.IO.MemoryStream())\n{\n var serializer = new DataContractJsonSerializer(typeof(IEnumerable<ExportData>), new[]{typeof(ExportData)}, Int32.MaxValue, true, null, false); \n serializer.WriteObject(stream, model); \n\n\n var jsonString = Encoding.Default.GetString((stream.ToArray()));\n}\n</code></pre>\n'}, {'answer_id': 26559972, 'author': 'Mehdi Khademloo', 'author_id': 4038978, 'author_profile': 'https://Stackoverflow.com/users/4038978', 'pm_score': 5, 'selected': False, 'text': '<p>In this case, if you really want to use <code>ReadToEnd</code> method in <code>MemoryStream</code> in an easy way, you can use this Extension Method to achieve this:</p>\n<pre class="lang-cs prettyprint-override"><code>public static class SetExtensions\n{\n public static string ReadToEnd(this MemoryStream BASE)\n {\n BASE.Position = 0;\n StreamReader R = new StreamReader(BASE);\n return R.ReadToEnd();\n }\n}\n</code></pre>\n<p>And you can use this method in this way:</p>\n<pre class="lang-cs prettyprint-override"><code>using (MemoryStream m = new MemoryStream())\n{\n //for example i want to serialize an object into MemoryStream\n //I want to use XmlSeralizer\n XmlSerializer xs = new XmlSerializer(_yourVariable.GetType());\n xs.Serialize(m, _yourVariable);\n\n //the easy way to use ReadToEnd method in MemoryStream\n MessageBox.Show(m.ReadToEnd());\n}\n</code></pre>\n'}, {'answer_id': 26892264, 'author': 'Alexandru', 'author_id': 982639, 'author_profile': 'https://Stackoverflow.com/users/982639', 'pm_score': 3, 'selected': False, 'text': "<p>Why not make a nice extension method on the MemoryStream type?</p>\n\n<pre><code>public static class MemoryStreamExtensions\n{\n\n static object streamLock = new object();\n\n public static void WriteLine(this MemoryStream stream, string text, bool flush)\n {\n byte[] bytes = Encoding.UTF8.GetBytes(text + Environment.NewLine);\n lock (streamLock)\n {\n stream.Write(bytes, 0, bytes.Length);\n if (flush)\n {\n stream.Flush();\n }\n }\n }\n\n public static void WriteLine(this MemoryStream stream, string formatString, bool flush, params string[] strings)\n {\n byte[] bytes = Encoding.UTF8.GetBytes(String.Format(formatString, strings) + Environment.NewLine);\n lock (streamLock)\n {\n stream.Write(bytes, 0, bytes.Length);\n if (flush)\n {\n stream.Flush();\n }\n }\n }\n\n public static void WriteToConsole(this MemoryStream stream)\n {\n lock (streamLock)\n {\n long temporary = stream.Position;\n stream.Position = 0;\n using (StreamReader reader = new StreamReader(stream, Encoding.UTF8, false, 0x1000, true))\n {\n string text = reader.ReadToEnd();\n if (!String.IsNullOrEmpty(text))\n {\n Console.WriteLine(text);\n }\n }\n stream.Position = temporary;\n }\n }\n}\n</code></pre>\n\n<p>Of course, be careful when using these methods in conjunction with the standard ones. :) ...you'll need to use that handy streamLock if you do, for concurrency.</p>\n"}, {'answer_id': 31437966, 'author': 'Sebastian Ferrari', 'author_id': 1231657, 'author_profile': 'https://Stackoverflow.com/users/1231657', 'pm_score': 4, 'selected': False, 'text': '<p>This sample shows how to read a string from a MemoryStream, in which I\'ve used a serialization (using DataContractJsonSerializer), pass the string from some server to client, and then, how to recover the MemoryStream from the string passed as parameter, then, deserialize the MemoryStream.</p>\n\n<p>I\'ve used parts of different posts to perform this sample.</p>\n\n<p>Hope that this helps.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Runtime.Serialization;\nusing System.Runtime.Serialization.Json;\nusing System.Threading;\n\nnamespace JsonSample\n{\n class Program\n {\n static void Main(string[] args)\n {\n var phones = new List<Phone>\n {\n new Phone { Type = PhoneTypes.Home, Number = "28736127" },\n new Phone { Type = PhoneTypes.Movil, Number = "842736487" }\n };\n var p = new Person { Id = 1, Name = "Person 1", BirthDate = DateTime.Now, Phones = phones };\n\n Console.WriteLine("New object \'Person\' in the server side:");\n Console.WriteLine(string.Format("Id: {0}, Name: {1}, Birthday: {2}.", p.Id, p.Name, p.BirthDate.ToShortDateString()));\n Console.WriteLine(string.Format("Phone: {0} {1}", p.Phones[0].Type.ToString(), p.Phones[0].Number));\n Console.WriteLine(string.Format("Phone: {0} {1}", p.Phones[1].Type.ToString(), p.Phones[1].Number));\n\n Console.Write(Environment.NewLine);\n Thread.Sleep(2000);\n\n var stream1 = new MemoryStream();\n var ser = new DataContractJsonSerializer(typeof(Person));\n\n ser.WriteObject(stream1, p);\n\n stream1.Position = 0;\n StreamReader sr = new StreamReader(stream1);\n Console.Write("JSON form of Person object: ");\n Console.WriteLine(sr.ReadToEnd());\n\n Console.Write(Environment.NewLine);\n Thread.Sleep(2000);\n\n var f = GetStringFromMemoryStream(stream1);\n\n Console.Write(Environment.NewLine);\n Thread.Sleep(2000);\n\n Console.WriteLine("Passing string parameter from server to client...");\n\n Console.Write(Environment.NewLine);\n Thread.Sleep(2000);\n\n var g = GetMemoryStreamFromString(f);\n g.Position = 0;\n var ser2 = new DataContractJsonSerializer(typeof(Person));\n var p2 = (Person)ser2.ReadObject(g);\n\n Console.Write(Environment.NewLine);\n Thread.Sleep(2000);\n\n Console.WriteLine("New object \'Person\' arrived to the client:");\n Console.WriteLine(string.Format("Id: {0}, Name: {1}, Birthday: {2}.", p2.Id, p2.Name, p2.BirthDate.ToShortDateString()));\n Console.WriteLine(string.Format("Phone: {0} {1}", p2.Phones[0].Type.ToString(), p2.Phones[0].Number));\n Console.WriteLine(string.Format("Phone: {0} {1}", p2.Phones[1].Type.ToString(), p2.Phones[1].Number));\n\n Console.Read();\n }\n\n private static MemoryStream GetMemoryStreamFromString(string s)\n {\n var stream = new MemoryStream();\n var sw = new StreamWriter(stream);\n sw.Write(s);\n sw.Flush();\n stream.Position = 0;\n return stream;\n }\n\n private static string GetStringFromMemoryStream(MemoryStream ms)\n {\n ms.Position = 0;\n using (StreamReader sr = new StreamReader(ms))\n {\n return sr.ReadToEnd();\n }\n }\n }\n\n [DataContract]\n internal class Person\n {\n [DataMember]\n public int Id { get; set; }\n [DataMember]\n public string Name { get; set; }\n [DataMember]\n public DateTime BirthDate { get; set; }\n [DataMember]\n public List<Phone> Phones { get; set; }\n }\n\n [DataContract]\n internal class Phone\n {\n [DataMember]\n public PhoneTypes Type { get; set; }\n [DataMember]\n public string Number { get; set; }\n }\n\n internal enum PhoneTypes\n {\n Home = 1,\n Movil = 2\n }\n}\n</code></pre>\n'}, {'answer_id': 43770727, 'author': 'Sadjad Khazaie', 'author_id': 2116150, 'author_profile': 'https://Stackoverflow.com/users/2116150', 'pm_score': 5, 'selected': False, 'text': '<pre><code>byte[] array = Encoding.ASCII.GetBytes("MyTest1 - MyTest2");\nMemoryStream streamItem = new MemoryStream(array);\n\n// convert to string\nStreamReader reader = new StreamReader(streamItem);\nstring text = reader.ReadToEnd();\n</code></pre>\n'}, {'answer_id': 61205864, 'author': 'Riccardo Bassilichi', 'author_id': 218415, 'author_profile': 'https://Stackoverflow.com/users/218415', 'pm_score': 1, 'selected': False, 'text': '<p>I need to integrate with a class that need a Stream to Write on it:</p>\n\n<pre><code>XmlSchema schema;\n// ... Use "schema" ...\n\nvar ret = "";\n\nusing (var ms = new MemoryStream())\n{\n schema.Write(ms);\n ret = Encoding.ASCII.GetString(ms.ToArray());\n}\n//here you can use "ret"\n// 6 Lines of code\n</code></pre>\n\n<p>I create a simple class that can help to reduce lines of code for multiples use:</p>\n\n<pre><code>public static class MemoryStreamStringWrapper\n{\n public static string Write(Action<MemoryStream> action)\n {\n var ret = "";\n using (var ms = new MemoryStream())\n {\n action(ms);\n ret = Encoding.ASCII.GetString(ms.ToArray());\n }\n\n return ret;\n }\n}\n</code></pre>\n\n<p>then you can replace the sample with a single line of code </p>\n\n<pre><code>var ret = MemoryStreamStringWrapper.Write(schema.Write);\n</code></pre>\n'}, {'answer_id': 65290459, 'author': 'Harlin Acero', 'author_id': 8921881, 'author_profile': 'https://Stackoverflow.com/users/8921881', 'pm_score': -1, 'selected': False, 'text': '<p>Only use method Convert.ToBase64String</p>\n<pre><code>Convert.ToBase64String(inputStream.ToArray());\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78181', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/320/'] |
78,184 | <p>I'm a beginning C++ programmer / network admin, but I figure I can learn how to do this if someone points me in the right direction. Most of the tutorials are demonstrated using old code that no longer works for some reason. </p>
<p>Since I'm on Linux, all I need is an explanation on how to write raw Berkeley sockets. Can someone give me a quick run down?</p>
| [{'answer_id': 78204, 'author': 'Tom Leys', 'author_id': 11440, 'author_profile': 'https://Stackoverflow.com/users/11440', 'pm_score': 2, 'selected': False, 'text': '<p>A good place to start would be to use <a href="http://www.boost.org/doc/libs/1_36_0/doc/html/boost_asio/overview.html" rel="nofollow noreferrer">Asio</a> which is a great cross-platform (incl Linux) library for network communication.</p>\n'}, {'answer_id': 78206, 'author': 'X-Istence', 'author_id': 13986, 'author_profile': 'https://Stackoverflow.com/users/13986', 'pm_score': 4, 'selected': False, 'text': '<p>Start by reading <a href="http://beej.us/guide/bgnet/output/html/multipage/index.html" rel="noreferrer">Beej\'s guide on socket programming</a> . It will bring you up to speed on how to start writing network code. After that you should be able to pick up more and more information from reading the man pages.</p>\n\n<p>Most of it will consist of reading the documentation for your favourite library, and a basic understanding of man pages.</p>\n'}, {'answer_id': 78208, 'author': 'Ben Collins', 'author_id': 3279, 'author_profile': 'https://Stackoverflow.com/users/3279', 'pm_score': 1, 'selected': False, 'text': '<p>There are tons of references on this (of course, Stevens\' book comes to mind), but I found the <a href="http://beej.us/guide/bgnet/output/html/multipage/index.html" rel="nofollow noreferrer">Beej guide</a> to be incredibly useful for getting started. It\'s meaty enough that you can understand what\'s really happening, but it\'s simple enough that it doesn\'t take you several days to write a \'hello world\' udp client/server.</p>\n'}, {'answer_id': 78209, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>easy:</p>\n\n<pre><code>#include <sys/socket.h>\n#include <sys/types.h>\n\nint socket(int protocolFamily, int Type, int Protocol)\n// returns a socket descriptor\n\nint bind(int socketDescriptor, struct sockaddr* localAddress, unsigned int addressLength)\n// returns 0 \n</code></pre>\n\n<p>...etc.</p>\n\n<p>it's all in sys/socket.h</p>\n"}, {'answer_id': 78211, 'author': 'HappySmileMan', 'author_id': 14073, 'author_profile': 'https://Stackoverflow.com/users/14073', 'pm_score': 2, 'selected': False, 'text': '<p>You do this the exact same way you would in regular C, there is no C++ specific way to do this in the standard library.</p>\n\n<p>The tutorial I used for learning this was <a href="http://beej.us/guide/bgnet/" rel="nofollow noreferrer">http://beej.us/guide/bgnet/</a>. It was the best tutorial I found after looking around, it gave clear examples and good explanations of all functions it describes.</p>\n'}, {'answer_id': 78251, 'author': 'Brian R. Bondy', 'author_id': 3153, 'author_profile': 'https://Stackoverflow.com/users/3153', 'pm_score': 3, 'selected': False, 'text': '<p><strong>For TCP client side:</strong></p>\n\n<p>Use gethostbyname to lookup dns name to IP, it will return a hostent structure. Let\'s call this returned value host. </p>\n\n<pre><code>hostent *host = gethostbyname(HOSTNAME_CSTR);\n</code></pre>\n\n<p>Fill the socket address structure:</p>\n\n<pre><code>sockaddr_in sock;\nsock.sin_family = AF_INET;\nsock.sin_port = htons(REMOTE_PORT);\nsock.sin_addr.s_addr = ((struct in_addr *)(host->h_addr))->s_addr;\n</code></pre>\n\n<p>Create a socket and call connect:</p>\n\n<pre><code>s = socket(AF_INET, SOCK_STREAM, 0); \nconnect(s, (struct sockaddr *)&sock, sizeof(sock))\n</code></pre>\n\n<p><strong>For TCP server side:</strong></p>\n\n<p>Setup a socket</p>\n\n<p>Bind your address to that socket using bind.</p>\n\n<p>Start listening on that socket with listen</p>\n\n<p>Call accept to get a connected client. <-- at this point you spawn a new thread to handle the connection while you make another call to accept to get the next connected client. </p>\n\n<p><strong>General communication:</strong></p>\n\n<p>Use send and recv to read and write between the client and server.</p>\n\n<p><strong>Source code example of BSD sockets:</strong></p>\n\n<p>You can find some good example code of this at <a href="http://en.wikipedia.org/wiki/Berkeley_sockets" rel="nofollow noreferrer">wikipedia</a>.</p>\n\n<p><strong>Further reading:</strong></p>\n\n<p>I highly recommend <a href="https://rads.stackoverflow.com/amzn/click/com/0131411551" rel="nofollow noreferrer" rel="nofollow noreferrer">this book</a> and <a href="http://beej.us/guide/bgnet/output/html/multipage/index.html" rel="nofollow noreferrer">this online tutorial</a>:</p>\n\n<p><img src="https://i.stack.imgur.com/CIP1b.jpg" alt="alt text"></p>\n\n<p><a href="https://i.stack.imgur.com/CIP1b.jpg" rel="nofollow noreferrer">4</a>: </p>\n'}, {'answer_id': 78273, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>Poster, please clarify your question.</p>\n\n<p>Almost all responses seem to think you\'re asking for a sockets tutorial; I read your question to mean you need to create a raw socket capable of sending arbitrary IP packets.\nAs I said in my previous answer, some OSes restrict the use of raw sockets.</p>\n\n<p><a href="http://linux.die.net/man/7/raw" rel="nofollow noreferrer">http://linux.die.net/man/7/raw</a>\n"Only processes with an effective user ID of 0 or the CAP_NET_RAW capability are allowed to open raw sockets."</p>\n'}, {'answer_id': 78294, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>For starters, it would be helpful if you clarify what you mean by "raw". Traditionally this means that you want to craft all of the layer 4 header (TCP/UDP/ICMP... header), and perhaps some of the IP header on your own. For this you will need more than beej\'s tutorial which has been mentioned my many here already. In this case you want raw IP sockets obtained using the SOCK_RAW argument in your call to socket (see <a href="http://mixter.void.ru/rawip.html" rel="noreferrer">http://mixter.void.ru/rawip.html</a> for some basics).</p>\n\n<p>If what you really want is just to be able to establish a TCP connection to some remote host such as port 80 on stackoverflow.com, then you probably don\'t need "raw" sockets and beej\'s guide will serve you well.</p>\n\n<p>For an authoritative reference on the subject, you should really pick up Unix Network Programming, Volume 1: The Sockets Networking API (3rd Edition) by Stevens et al.</p>\n'}, {'answer_id': 78349, 'author': 'Charles Graham', 'author_id': 7705, 'author_profile': 'https://Stackoverflow.com/users/7705', 'pm_score': 1, 'selected': False, 'text': '<p>Read <a href="https://rads.stackoverflow.com/amzn/click/com/0131411551" rel="nofollow noreferrer" rel="nofollow noreferrer">Unix Network Programming</a> by Richard Stevens. It\'s a must. It explains how it all works, gives you code, and even gives you helper methods. You might want to check out some of his other books. <a href="https://rads.stackoverflow.com/amzn/click/com/0201433079" rel="nofollow noreferrer" rel="nofollow noreferrer">Advanced Programming In The Unix Enviernment</a> is a must for lower level programming in Unix is general. I don\'t even do stuff on the Unix stack anymore, and the stuf from these books still helps how I code.</p>\n'}, {'answer_id': 595529, 'author': 'jdizzle', 'author_id': 70603, 'author_profile': 'https://Stackoverflow.com/users/70603', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://www.tcpdump.org/" rel="nofollow noreferrer">Libpcap</a> will let you craft complete packets (layer2 through layer 7) and send them out over the wire. As fun as that sounds, there\'s some caveats with it. You need to create all the appropriate headers and do all the checksumming yourself. <a href="http://libnet.sourceforge.net/" rel="nofollow noreferrer">Libnet</a> can help with that, though.</p>\n\n<p>If you want to get out of the C++ programming pool, there is <a href="http://www.secdev.org/projects/scapy/" rel="nofollow noreferrer">scapy</a> for python. It makes it trivial to craft and transmit TCP/IP packets.</p>\n'}, {'answer_id': 14752331, 'author': 'mfontanini', 'author_id': 525217, 'author_profile': 'https://Stackoverflow.com/users/525217', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve been developing <a href="http://libtins.github.io/" rel="nofollow">libtins</a> for the past year. It\'s a high level C++ packet crafting and sniffing library. </p>\n\n<p>Unless you want to reinvent the wheel and implement every protocol\'s internals, I\'d recommend you to use some higher level library which already does that for you.</p>\n'}, {'answer_id': 69956983, 'author': 'Arseny Semenov', 'author_id': 16639307, 'author_profile': 'https://Stackoverflow.com/users/16639307', 'pm_score': 1, 'selected': False, 'text': '<p>in any case, if you want to use the tcp/ip stack, their headers will be added to your packet. If you want to control the packet down to the byte, I advise you npcap. Libpcap, unfortunately, is already outdated, although it is much easier to use. However, I have personally used npcap and it provides full control over the package</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78184', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
78,194 | <p>My employer just asked me to run a timed batch process in a Java EE WebSphere application they have running. It's supposed to run a certain class at 11:30 pm everyday.</p>
<p>I'm not very familiar with Java EE nor WebSphere server (or tomcat, in the development environment), and I've been digging around but all I've found is about the java timer class but not how to set it or invoke it.</p>
<p>It seems that editing the web.xml file is required as well.</p>
<p>Any help will be appreciated!</p>
| [{'answer_id': 78227, 'author': 'Cheekysoft', 'author_id': 1820, 'author_profile': 'https://Stackoverflow.com/users/1820', 'pm_score': 4, 'selected': True, 'text': '<p>You should look at the open-source <a href="http://www.quartz-scheduler.org/" rel="noreferrer">Quartz library</a> from OpenSymphony. Very easy to use and perfect for this kind of thing.</p>\n\n<p>TimerTasks are best suited for running something in a short time in the future. But for a repeated execution in a large timeframe such as this, Quartz excels. You can even keep your list of upcoming tasks in persistent storage such as a file or database, so upcoming timed jobs are not lost if your application is restarted.</p>\n\n<p>Also, there\'s a fantastic abstraction for Quartz in the Spring framework.</p>\n'}, {'answer_id': 78241, 'author': 'user13276', 'author_id': 13276, 'author_profile': 'https://Stackoverflow.com/users/13276', 'pm_score': 0, 'selected': False, 'text': "<p>In your web.xml you can configure a servlet to load at startup.<br>\nSyntax:</p>\n\n<p><servlet servlet-name='hello'\n servlet-class='test.HelloWorld'><br>\n <load-on-startup/><br>\n</servlet></p>\n\n<p>Do this, then in the init method in the servlet you can set up a Timer / TimerTask to do whatever it is you need to do. TimerTasks are like Threads except you can schedule them when to run.</p>\n"}, {'answer_id': 79243, 'author': 'feniix', 'author_id': 14664, 'author_profile': 'https://Stackoverflow.com/users/14664', 'pm_score': 0, 'selected': False, 'text': '<p>Quartz is part of the standard JBoss 4.2.x distribution.</p>\n\n<p>And is a really good library, that without much work you can also define simple workflows.</p>\n'}, {'answer_id': 96446, 'author': 'boes', 'author_id': 17746, 'author_profile': 'https://Stackoverflow.com/users/17746', 'pm_score': 0, 'selected': False, 'text': '<p>There is no support for scheduling in WebSphere.</p>\n\n<p>If you are on unix you can use crontab to schedule a request to a page of your websphere application. I suppose on windows there is also a possibility to schedule a request to a page. In my crontab I schedule a request to a webpage each day at 8:45</p>\n\n<p>45 8 * * * GET <a href="http://www.domain.com/myBatch?securitykey=verysecret" rel="nofollow noreferrer">http://www.domain.com/myBatch?securitykey=verysecret</a></p>\n\n<p>Now every morning the myBatch servlet is called and there I can do whatever needs to be done at that time. To avoid others calling this page and start the batch, I added the securitykey parameter. </p>\n'}, {'answer_id': 96584, 'author': 'Martin Klinke', 'author_id': 1793, 'author_profile': 'https://Stackoverflow.com/users/1793', 'pm_score': 1, 'selected': False, 'text': '<p>EJB 3.1 will have improved timer services, as well as application lifecycle hooks that remove the need to use servlets to start tasks without user interaction.</p>\n\n<p>This may answer the question title, but for the "real" question concerning a legacy application (written more than 6 months ago ;)) running on websphere I\'d recommend to go with the start-up servlet and the EJB timer service. </p>\n\n<p><a href="http://java.sun.com/j2ee/1.4/docs/tutorial/doc/Session5.html" rel="nofollow noreferrer">Timer Service in J2EE 1.4 (EJB 2.1)</a></p>\n\n<p>For EJB 3.0 (and 3.1 as soon as available), there are some nice annotations ;)</p>\n\n<p>I\'d not introduce another <a href="http://www.quartz-scheduler.org/" rel="nofollow noreferrer">library</a> unless you REALLY need it. The timer service should suffice for performing an arbitrary job on a daily basis.</p>\n\n<p>HTH,<br>\nMartin</p>\n'}, {'answer_id': 313512, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>In WebSphere, you can use the Scheduler Service to trigger the execution of a method in a java class. \nThe scheduler provides a calendar for scheduling the execution of jobs (similar to cron) or you could develop your own.</p>\n\n<p>Here\'s a link to the page describing the scheduler in the WAS 6.1 documentation:</p>\n\n<p><a href="http://publib.boulder.ibm.com/infocenter/wasinfo/v6r1/index.jsp" rel="nofollow noreferrer">http://publib.boulder.ibm.com/infocenter/wasinfo/v6r1/index.jsp</a></p>\n'}, {'answer_id': 966360, 'author': 'Everett Toews', 'author_id': 25991, 'author_profile': 'https://Stackoverflow.com/users/25991', 'pm_score': 0, 'selected': False, 'text': '<p>There is support for scheduling included in WebSphere.</p>\n\n<p>WAS v7.0\n<a href="http://publib.boulder.ibm.com/infocenter/wasinfo/v7r0/topic/com.ibm.websphere.base.doc/info/aes/ae/welc6tech_sch.html" rel="nofollow noreferrer">http://publib.boulder.ibm.com/infocenter/wasinfo/v7r0/topic/com.ibm.websphere.base.doc/info/aes/ae/welc6tech_sch.html</a></p>\n\n<p>WAS v6.1\n<a href="http://publib.boulder.ibm.com/infocenter/wasinfo/v6r1/topic/com.ibm.websphere.base.doc/info/aes/ae/welc6tech_sch.html" rel="nofollow noreferrer">http://publib.boulder.ibm.com/infocenter/wasinfo/v6r1/topic/com.ibm.websphere.base.doc/info/aes/ae/welc6tech_sch.html</a></p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78194', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14284/'] |
78,217 | <p>How would you implement a system with the following objectives:</p>
<ul>
<li>Manage authentication,
authorization for
<strong>hundreds of thousands</strong> of <em>existing users</em> currently tightly integrated with a 3rd party vendor's application (We want to bust these users out into something we manage and make our apps work against it, plus our 3rd party vendors work against it).</li>
<li>Manage profile information linked to those users</li>
<li>Must be able to be accessed from any number of web applications on just about any platform (Windows, *nix, PHP, ASP/C#, Python/Django, et cetera).</li>
</ul>
<p>Here some sample implementations:</p>
<ul>
<li>LDAP/AD Server to manage everything. Use custom schema for all profile data. Everything can authenticate against LDAP/AD and we can store all sorts of ACLs and profile data in a custom schema.</li>
<li>Use LDAP/AD for authentication only, tie LDAP users to a most robust profile/authorization server using some sort of traditional database (MSSQL/PostgreSQL/MySQL) or document based DB (CouchDB, SimpleDB, et cetera). Use LDAP for authorization, then hit the DB for more advanced stuff.</li>
<li>Use a traditional database (Relational or Document) for everything.</li>
</ul>
<p>Are any of these three the best? Are there other solutions which fit the objectives above and are easier to implement?</p>
<p>** I should add that almost all applications that will be authenticating against the user database will be under our control. The lone few outsiders will be the applications we're removing the current user database from and perhaps 1 or 2 others. Nothing so broad as to need an openID server.</p>
<p>Its also important to know that a lot of these users have had these accounts for 5-8 years and know their logins and passwords, et cetera.</p>
| [{'answer_id': 78255, 'author': 'zuber', 'author_id': 9812, 'author_profile': 'https://Stackoverflow.com/users/9812', 'pm_score': -1, 'selected': False, 'text': '<p>You can always implement your own <a href="http://openid.net/what/" rel="nofollow noreferrer">OpenID</a> server. There is already a <a href="http://openidenabled.com/python-openid/" rel="nofollow noreferrer">Python library for OpenID</a> so it should be fairly easy. </p>\n\n<p>Of course you don\'t need to accept logins authorized by other servers in your applications. Accept credentials authorized only by your own server.</p>\n\n<p><strong>Edit:</strong> I have found an <a href="http://trac.nicolast.be/djangoid" rel="nofollow noreferrer">implementation of OpenID server protocol in Django</a>.</p>\n\n<p><strong>Edit2:</strong> There is an obvious advantage in implementing OpenID for your users. They will be able to login to StackOverflow with their logins :-)</p>\n'}, {'answer_id': 78289, 'author': 'Jon Limjap', 'author_id': 372, 'author_profile': 'https://Stackoverflow.com/users/372', 'pm_score': 2, 'selected': False, 'text': '<p>If you have an existing ActiveDirectory infrastructure, that will be the way to go. This will be particularly advantageous to companies that have already had Windows servers set up for authentication. If this is the case, I\'m leaning towards your first bullet point in "sample implementations".</p>\n\n<p>Otherwise it will be a toss-up between AD and opensource LDAP options.</p>\n\n<p>It might be not viable to roll your own authentication schema for single-sign-on (especially considering the high amount of documentation and integration work you might have to do), and obviously do not bundle your authentication server with any of the applications running on your system (since you want it to be able to be independent of the load of such applications).</p>\n\n<p>Goodluck!</p>\n'}, {'answer_id': 78327, 'author': 'dacracot', 'author_id': 13930, 'author_profile': 'https://Stackoverflow.com/users/13930', 'pm_score': 4, 'selected': True, 'text': "<p>There is a difference between authentication and authorization/profiling so don't force both necessarily into a single tool. Your second solution of using LDAP for authentication and a DB for authorization seems more robust as the LDAP data is controlled by the user and the DB would be controlled by an admin. The latter would likely morph in structure and complexity over time, but authentication is just that authentication. Separation of these functions will prove more manageable.</p>\n"}, {'answer_id': 78340, 'author': 'jason saldo', 'author_id': 1293, 'author_profile': 'https://Stackoverflow.com/users/1293', 'pm_score': 0, 'selected': False, 'text': '<p>Use LDAP/AD for authentication only, tie LDAP users to a most robust profile/authorization server using some sort of traditional database (MSSQL/PostgreSQL/MySQL) or document based DB (CouchDB, SimpleDB, et cetera). Use LDAP for authorization, then hit the DB for more advanced stuff.</p>\n'}, {'answer_id': 78358, 'author': 'Sklivvz', 'author_id': 7028, 'author_profile': 'https://Stackoverflow.com/users/7028', 'pm_score': 0, 'selected': False, 'text': '<p>We have different sites with around 100k users and they all work with normal databases. If most applications can access the db you can use this solution.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78217', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
78,230 | <p>I am just getting started with flex and am using the SDK (not Flex Builder). I was wondering what's the best way to compile a mxml file from an ant build script. </p>
| [{'answer_id': 78248, 'author': 'mikechambers', 'author_id': 10232, 'author_profile': 'https://Stackoverflow.com/users/10232', 'pm_score': 4, 'selected': True, 'text': '<p>The Flex SDK ships with a set of ant tasks. More info at:</p>\n\n<p><a href="http://livedocs.adobe.com/flex/3/html/help.html?content=anttasks_1.html" rel="noreferrer">http://livedocs.adobe.com/flex/3/html/help.html?content=anttasks_1.html</a></p>\n\n<p>Here is an example of compiling Flex SWCs with ant:</p>\n\n<p><a href="http://www.mikechambers.com/blog/2006/05/19/example-using-ant-with-compc-to-compile-swcs/" rel="noreferrer">http://www.mikechambers.com/blog/2006/05/19/example-using-ant-with-compc-to-compile-swcs/</a></p>\n\n<p>mike chambers</p>\n'}, {'answer_id': 80511, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>If you\'re open to Maven, try the flex-compiler-mojo plugin:</p>\n\n<p><a href="http://code.google.com/p/flex-mojos/" rel="nofollow noreferrer">http://code.google.com/p/flex-mojos/</a></p>\n\n<p>Christiaan</p>\n'}, {'answer_id': 222331, 'author': 'jgormley', 'author_id': 29738, 'author_profile': 'https://Stackoverflow.com/users/29738', 'pm_score': 3, 'selected': False, 'text': '<p>I would definitely go with the ant tasks that are included with Flex, they make your build script so much cleaner. Here is a sample build script that will compile and then run your flex project</p>\n\n<pre><code><?xml version="1.0"?>\n\n<project name="flexapptest" default="buildAndRun" basedir=".">\n\n <!-- \n make sure this jar file is in the ant lib directory \n classpath="${ANT_HOME}/lib/flexTasks.jar" \n -->\n <taskdef resource="flexTasks.tasks" />\n <property name="appname" value="flexapptest"/>\n <property name="appname_main" value="Flexapptest"/>\n <property name="FLEX_HOME" value="/Applications/flex_sdk_3"/>\n <property name="APP_ROOT" value="."/>\n <property name="swfOut" value="dist/${appname}.swf" />\n <!-- point this to your local copy of the flash player -->\n <property name="flash.player" location="/Applications/Adobe Flash CS3/Players/Flash Player.app" />\n\n <target name="compile">\n <mxmlc file="${APP_ROOT}/src/${appname_main}.mxml"\n output="${APP_ROOT}/${swfOut}" \n keep-generated-actionscript="true">\n\n <default-size width="800" height="600" />\n <load-config filename="${FLEX_HOME}/frameworks/flex-config.xml"/>\n <source-path path-element="${FLEX_HOME}/frameworks"/>\n <compiler.library-path dir="${APP_ROOT}/libs" append="true">\n <include name="*.swc" />\n </compiler.library-path>\n </mxmlc>\n </target>\n\n <target name="buildAndRun" depends="compile">\n <exec executable="open">\n <arg line="-a \'${flash.player}\'"/>\n <arg line="${APP_ROOT}/${swfOut}" />\n </exec>\n </target>\n\n <target name="clean">\n <delete dir="${APP_ROOT}/src/generated"/>\n <delete file="${APP_ROOT}/${swfOut}"/>\n </target>\n\n</project>\n</code></pre>\n'}, {'answer_id': 1670928, 'author': 'Luke Bayes', 'author_id': 105023, 'author_profile': 'https://Stackoverflow.com/users/105023', 'pm_score': 2, 'selected': False, 'text': '<p>There is another option - it\'s called <a href="http://projectsprouts.org" rel="nofollow noreferrer">Project Sprouts</a>.</p>\n\n<p>This is a system built with Ruby, RubyGems and Rake that provides many of the features found in Maven and ANT, but with a much cleaner syntax and simpler build scripts.</p>\n\n<p>For example, the ANT script shown above would look like this in Sprouts:</p>\n\n<pre><code>require \'rubygems\'\nrequire \'sprout\'\n\ndesc \'Compile and run the SWF\'\nflashplayer :run => \'bin/SomeProject.swf\'\n\nmxmlc \'bin/SomeProject.swf\' do |t|\n t.input = \'src/SomeProject.as\'\n t.default_size = \'800 600\'\n t.default_background_color = \'#ffffff\'\n t.keep_generated_actionscript = true\n t.library_path << \'libs\'\nend\n\ntask :default => :run\n</code></pre>\n\n<p>After installing Ruby and RubyGems, you would simply call this script with:</p>\n\n<pre><code>rake\n</code></pre>\n\n<p>To remove generated files, run:</p>\n\n<pre><code>rake clean\n</code></pre>\n\n<p>To see available tasks:</p>\n\n<pre><code>rake -T\n</code></pre>\n\n<p>Another great benefit of Sprouts, once installed, is that it provides project, class and test generators that will get any development box ready to run with a couple simple command line actions.</p>\n\n<pre><code># Generate a project and cd into it:\nsprout -n mxml SomeProject\ncd SomeProject\n\n# Compile and run the main debug SWF:\nrake\n\n# Generate a new class, test case and test suite:\nscript/generate class utils.MathUtil\n\n# Compile and run the test harness:\nrake test\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78230', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1227001/'] |
78,233 | <p>I have a dataset that I have modified into an xml document and then used a xsl sheet to transform into an Excel xml format in order to allow the data to be opened programatically from my application. I have run into two problems with this:</p>
<ol>
<li><p>Excel is not the default Windows application to open Excel files, therefore when Program.Start("xmlfilename.xml") is run, IE is opened and the XML file is not very readable.</p></li>
<li><p>If you rename the file to .xlsx, you receive a warning, "This is not an excel file, do you wish to continue". This is not ideal for customers.</p></li>
</ol>
<p>Ideally, I would like Windows to open the file in Excel without modifying the default OS setting for opening Excel files. Office interop is a possibility, but seems like a little overkill for this application. Does anyone have any ideas to make this work?</p>
<p>The solution is in .Net/C#, but I am open to other possibilities to create a clean solution.</p>
| [{'answer_id': 78246, 'author': 'sgwill', 'author_id': 1204, 'author_profile': 'https://Stackoverflow.com/users/1204', 'pm_score': 1, 'selected': False, 'text': '<p>What if you save the file as an xlsx, the extension for XML-Excel?</p>\n'}, {'answer_id': 78292, 'author': 'MagicKat', 'author_id': 8505, 'author_profile': 'https://Stackoverflow.com/users/8505', 'pm_score': 2, 'selected': True, 'text': '<pre><code>Process.Start(@"C:\\Program Files\\Microsoft Office\\Officexx\\excel.exe", "yourfile.xml");\n</code></pre>\n\n<p>That being said, you will still get the message box. I suppose that you could use the Interop, but I am not sure how well it will work for you.</p>\n'}, {'answer_id': 78298, 'author': 'Bryant', 'author_id': 10893, 'author_profile': 'https://Stackoverflow.com/users/10893', 'pm_score': 0, 'selected': False, 'text': '<p>As Sam mentioned, the xlsx file extension is probably a good route to go. However, there is more involved than just saving the xml file as xlsx. An xlsx is actually a zip file with a bunch of xml files inside folders. I found some good sample code <a href="http://www.gemboxsoftware.com/Excel2007/DemoApp.htm" rel="nofollow noreferrer">here</a> which seems to give some good explanations although I haven\'t personally given it a try.</p>\n'}, {'answer_id': 78818, 'author': 'Dave Neeley', 'author_id': 9660, 'author_profile': 'https://Stackoverflow.com/users/9660', 'pm_score': 0, 'selected': False, 'text': '<p>Apologies in advance for plugging a third party library, and I know it\'s not free, but I use <a href="http://www.tmssoftware.com/site/flexcelnet.asp" rel="nofollow noreferrer">FlexCel Studio</a> from TMS Software. If you\'re looking to do more than just dump data (formatting, dynamic cross-tabs, etc) it works very well. We generate hundreds of reports a week using it. </p>\n\n<p>FlexCel accepts strongly-typed datasets, it can group data according to relationships, and the generated Excel file looks so much cleaner than what you can get from a Crystal Reports excel export. I\'ve done the crystal reports thing, and the OLE automation thing. FlexCel is a steal at $125 EU.</p>\n'}, {'answer_id': 82799, 'author': 'Jason Z', 'author_id': 2470, 'author_profile': 'https://Stackoverflow.com/users/2470', 'pm_score': 2, 'selected': False, 'text': '<p>If you insert the following into the 2nd line of your XML it directs Windows to open with Excel</p>\n\n<pre><code><?mso-application progid="Excel.Sheet"?>\n</code></pre>\n'}, {'answer_id': 15773216, 'author': 'aked', 'author_id': 1060656, 'author_profile': 'https://Stackoverflow.com/users/1060656', 'pm_score': 0, 'selected': False, 'text': '<p>Hope this helps.</p>\n\n<p>OpenXML in MSDN - <a href="http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.workbooks.openxml%28v=office.11%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.workbooks.openxml(v=office.11).aspx</a></p>\n\n<pre><code>using Excel = Microsoft.Office.Interop.Excel;\n\nstring workbookPath= @"C:\\temp\\Results_2013Apr02_110133_6692.xml";\n\n this.lblResultFile.Text = string.Format(@" File:{0}",workbookPath);\n if (File.Exists(workbookPath))\n {\n Excel.Application excelApp = new Excel.Application();\n excelApp.Visible = true;\n Excel.Workbook excelWorkbook = excelApp.Workbooks.OpenXML(workbookPath, Type.Missing, Excel.XlXmlLoadOption.xlXmlLoadPromptUser);\n }\n else\n {\n MessageBox.Show(String.Format("File:{0} does not exists", workbookPath));\n }\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78233', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2916/'] |
78,238 | <p>I'm developing a graphical application to present data (not a game but a real workhorse app). It needs to be cross platform, so I have chosen:</p>
<ul>
<li>python</li>
<li>openGL (I need 3D, blending, textures etc)</li>
<li>pyopengl</li>
<li>wx/pywx - windowing, dialogs etc.</li>
</ul>
<p>The last component - WX - raises the question. I can put together a very nice looking app (the prototypes look slick) - but when I need to interact with the user to ask questions, get input, I have to use WX. It makes the app look inconsistent to have traditional UI with traditional dialogs and combos and text entry on top of a full screen 3D app with blending, smooth motion, textures etc.</p>
<p>Has anyone developed a GUI using OpenGL and python? Can you share with me the toolkits and/or tricks you used? I need combos, text entry, buttons, radios, option buttons, tree view.</p>
<p>There are some toolkits out there, but they are either incomplete or old and unmaintained. A great example is pyUI (<a href="http://pyui.sourceforge.net/" rel="nofollow noreferrer">http://pyui.sourceforge.net/</a>) - looks slick but untouched for years.</p>
| [{'answer_id': 78397, 'author': 'SCdF', 'author_id': 1666, 'author_profile': 'https://Stackoverflow.com/users/1666', 'pm_score': 1, 'selected': False, 'text': '<p>You might want to look at <a href="http://clutter-project.org/" rel="nofollow noreferrer">Clutter</a>, it looks pretty cool. I haven\'t used it yet but I intend to in an upcoming personal project.</p>\n'}, {'answer_id': 78404, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': "<p>This is not an answer, more of a plea: Please don't do that.</p>\n\n<p>Your reimplemented widgets will lack all sorts of functionality that users will miss. Will your text-entry boxes support drag'n'drop? Copy/paste? Right-to-left scripts? Drag-select? Double-click-select? Will all these mechanisms follow the native conventions of each platform you support?</p>\n\n<p>With Wx your widgets might look inconsistant with the app, but at least they'll look consistant with the OS which is just as important. And more importantly, they'll do what users expect.</p>\n\n<p>(edit) Three posts, and -3 points? Screw this den of karma-whores. Original poster: I have implemented a basic set of widgets in OpenGL (for a game UI) and it was an endless nightmare of a job.</p>\n"}, {'answer_id': 78483, 'author': 'pobk', 'author_id': 7829, 'author_profile': 'https://Stackoverflow.com/users/7829', 'pm_score': 1, 'selected': False, 'text': "<p>Try Qt instead of wx.</p>\n\n<p>QT is cross platform, and you can style things alot using CSS. It's extremely well documented and has excellent python bindings. In point of fact, I use the C++ documentation and not the PyQT documentation.</p>\n"}, {'answer_id': 78589, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>Python + Qt + OpenGL -\nI surely believe any application can be written faster and better using python.\nQT4 is cross-platform, beautifull, implements everything you need from widgets (acessibility, etc...), and...it integrates with OpenGL. That means, you can simply have a widget that is a viewport to openGL stuff you render in your code.</p>\n\n<p>Another 3D capable solution that would cover most things, but not so nioce on user interface is to extend Blender3D with a python script. It has the 3d capabilities and rendering , you script it in python all of the same, and it would be cross platform - and you get higher level tools for woriking with the 3D things than openGL alone.\nThere are obvious drawbacks, mainly from the UI standpoint when compared with PyQT but it could be done. </p>\n'}, {'answer_id': 85490, 'author': 'Martin Beckett', 'author_id': 10897, 'author_profile': 'https://Stackoverflow.com/users/10897', 'pm_score': 1, 'selected': False, 'text': '<p>Both wx and QT do an excellent job of creating an application that matches the OS look and feel.\nIt is also possible to implment all the widgets yourself directly in openg, this slashdot post lists some of the sets available </p>\n\n<p><a href="http://ask.slashdot.org/askslashdot/02/12/24/1813219.shtml?tid=156" rel="nofollow noreferrer">http://ask.slashdot.org/askslashdot/02/12/24/1813219.shtml?tid=156</a>\nfox is probably the most developed but looks like windows on all platforms.</p>\n'}, {'answer_id': 138630, 'author': 'Harald Scheirich', 'author_id': 22080, 'author_profile': 'https://Stackoverflow.com/users/22080', 'pm_score': 3, 'selected': False, 'text': '<p>In the latest releases of QT you can draw widgets <em>into</em> your OpenGL context, if you really would like to do something like that. Otherwise there is <a href="http://www.cegui.org.uk/wiki/index.php/Main_Page" rel="noreferrer">CEGui</a> that is used in some game engines. </p>\n\n<p>Implementing GUI Widgets yourself unless you want to edify yourself is a waste of your time, unless you would be satisfied with the most rudimentary of looks and functionality. </p>\n'}, {'answer_id': 7697287, 'author': 'Tcll', 'author_id': 985411, 'author_profile': 'https://Stackoverflow.com/users/985411', 'pm_score': 1, 'selected': False, 'text': '<p>Blender is the only app I know of with a GUI written fully in OpenGL...\nthe only problem is it\'s in C++.</p>\n\n<p>I\'m a Python developer as well, but I\'m just getting into using OGL</p>\n\n<p>I honestly don\'t think there are any toolkits to develop a GUI in OGL...</p>\n\n<p>the Blender developers are giving me runaround documentation instead of direct help...\nbut I\'ll let you know what I figure out ;)</p>\n\n<p>EDIT:\nhere\'s a bit of documentation on PyOpenGL\'s functions:\n<a href="http://pyopengl.sourceforge.net/documentation/manual/reference-GLUT.html" rel="nofollow">http://pyopengl.sourceforge.net/documentation/manual/reference-GLUT.html</a></p>\n'}, {'answer_id': 7697572, 'author': 'Tcll', 'author_id': 985451, 'author_profile': 'https://Stackoverflow.com/users/985451', 'pm_score': -1, 'selected': False, 'text': '<p>my friend.<br>\nI believe I have found your answer ;)<br>\n<a href="http://glinter.sourceforge.net/" rel="nofollow">http://glinter.sourceforge.net/</a></p>\n\n<p>I havn\'t yet tried it, but it seems quite promising.\n(I\'ll edit this if it doesn\'t work)</p>\n\n<p>EDIT:<br>\neh...<br>\nit uses Tk, PMW, and WX...<br>\n(not quite what I want)</p>\n\n<p>you can give the CVS download a try...<br>\n(there\'s no released packages, but the CVS runs)</p>\n'}, {'answer_id': 26485404, 'author': 'Silvester Mühlhaus', 'author_id': 4165606, 'author_profile': 'https://Stackoverflow.com/users/4165606', 'pm_score': 0, 'selected': False, 'text': '<p>"<a href="http://cegui.org.uk" rel="nofollow">cegui</a>" is a good choise there is also a gui editor called "ceed" to generate the layout xml files. cegui also has python bindings and its well documented and used in many game engines</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78238', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
78,257 | <p>Lot of googling did not help me! Are there any good dictionary web based available? </p>
<p>I am looking for a site which can send me the meaning of words if we pass the word through query string!</p>
| [{'answer_id': 78295, 'author': 'Jacob Krall', 'author_id': 3140, 'author_profile': 'https://Stackoverflow.com/users/3140', 'pm_score': 5, 'selected': True, 'text': '<p>I found you a <a href="http://words.bighugelabs.com/" rel="noreferrer">Big Huge Thesaurus</a> with a web API, and a dictionary at <a href="http://services.aonaware.com/DictService/" rel="noreferrer">Aonaware</a> that looks like it uses SOAP</p>\n'}, {'answer_id': 203818, 'author': 'Greg Hewgill', 'author_id': 893, 'author_profile': 'https://Stackoverflow.com/users/893', 'pm_score': 2, 'selected': False, 'text': '<p>There also exists the <a href="http://dict.org" rel="nofollow noreferrer">dict</a> protocol which has been around for a long time. One of the things I like about dict is the command-line query program that is available.</p>\n\n<p>I have also created a <a href="http://hewgill.com/dict/" rel="nofollow noreferrer">Wiktionary to dict gateway</a> which provides access to the Wiktionary database through the dict protocol.</p>\n'}, {'answer_id': 18439691, 'author': 'Fernando Vezzali', 'author_id': 1086241, 'author_profile': 'https://Stackoverflow.com/users/1086241', 'pm_score': 2, 'selected': False, 'text': '<p>I found another three:</p>\n\n<ul>\n<li>Programmable Web: <a href="http://www.programmableweb.com/api/oxford-english-dictionary" rel="nofollow">http://www.programmableweb.com/api/oxford-english-dictionary</a></li>\n<li>Glosbe API: <a href="http://glosbe.com/a-api" rel="nofollow">http://glosbe.com/a-api</a></li>\n<li>DictService: <a href="http://services.aonaware.com/DictService/DictService.asmx" rel="nofollow">http://services.aonaware.com/DictService/DictService.asmx</a></li>\n</ul>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78257', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12178/'] |
78,262 | <p>The two connection limit can be particularly troublesome when you have multiple tabs open simultaneously. Besides "ignore the problem," what coping mechanisms have you seen used to get multiple tabs both doing heavily interactive Ajax despite the two connection limit?</p>
| [{'answer_id': 78381, 'author': 'Joe Skora', 'author_id': 14057, 'author_profile': 'https://Stackoverflow.com/users/14057', 'pm_score': 1, 'selected': False, 'text': '<p>The two connection limit is a "suggestion" and this <a href="http://www.oreillynet.com/xml/blog/2006/10/what_i_didnt_know_about_xhr.html" rel="nofollow noreferrer">article</a> describes how to get around it where possible. Other Firefox configuration is discussed on this about the <a href="http://kb.mozillazine.org/Firefox_:_FAQs_:_About:config_Entries" rel="nofollow noreferrer">about:config</a> capability in Firefox.</p>\n\n<p>Also, if you own the website, you can tweak the performance of the site using suggestions form this <a href="https://rads.stackoverflow.com/amzn/click/com/0596529309" rel="nofollow noreferrer" rel="nofollow noreferrer">book</a> from the Chief Performance Yahoo. </p>\n'}, {'answer_id': 78679, 'author': 'rpetrich', 'author_id': 4007, 'author_profile': 'https://Stackoverflow.com/users/4007', 'pm_score': 2, 'selected': False, 'text': "<p>If you send your Ajax requests to a different subdomain they won't interfere with the connection limit of your regular pages. It will cost an extra DNS lookup though </p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78262', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
78,263 | <p>I installed both the Delphi 2009 trial and actual release via the web installer when I received them and experienced the same errors when installing both.</p>
<p>Both times it appears that the core web installer failed when it went to spawn the additional install packages for boost, documentation and dbtools. (It brought up a findfile dialog asking for a setup.msi that didn't exist on my machine). When cancelling out of this, the installer reported a fatal error.</p>
<p>The uninstaller did not appear in my program list, and would did not launch from the installation folder.</p>
<p>Future attempts to bring up the installer had it in a state where it thought Delphi 2009 was already installed and it wouldn't correct or repair or uninstall it.</p>
| [{'answer_id': 78283, 'author': 'Zartog', 'author_id': 9467, 'author_profile': 'https://Stackoverflow.com/users/9467', 'pm_score': 0, 'selected': False, 'text': '<p>The problems seem to originate with the web installer not having all the files needed.</p>\n\n<p>Download the 2009 ISO: <a href="http://cc.codegear.com/item/26049" rel="nofollow noreferrer">http://cc.codegear.com/item/26049</a></p>\n\n<p>Mounted it using this free tool from Microsoft: <a href="http://download.microsoft.com/download/7/b/6/7b6abd84-7841-4978-96f5-bd58df02efa2/winxpvirtualcdcontrolpanel_21.exe" rel="nofollow noreferrer">http://download.microsoft.com/download/7/b/6/7b6abd84-7841-4978-96f5-bd58df02efa2/winxpvirtualcdcontrolpanel_21.exe</a> (You can burn it to a DVD too)</p>\n\n<p>Then reran the installer. At this point, both the repair and uninstall worked.</p>\n'}, {'answer_id': 79912, 'author': 'Tim Knipe', 'author_id': 10493, 'author_profile': 'https://Stackoverflow.com/users/10493', 'pm_score': 3, 'selected': True, 'text': '<h2>Step 1</h2>\n\n<p>Clean out the registry of all things Delphi 2009.</p>\n\n<p>You\'re looking for <em>HKLM\\Software\\Codegear\\BDS\\6.0</em> and everything under it. Purge the HKCU equivalent while you\'re at it.</p>\n\n<p>Search under HKEY.CLASSES.ROOT for anything that contains "CodeGear\\RAD Studio\\6.0" - assuming you installed into the default folder. Purge all those items from the CLSID level.</p>\n\n<h2>Step 2</h2>\n\n<p>Clean up Windows Installer using the <a href="http://support.microsoft.com/kb/290301" rel="nofollow noreferrer" title="Microsoft Windows Installer Cleanup Utility">Microsoft Windows Installer Cleanup</a> utility. </p>\n\n<h2>Step 3</h2>\n\n<p>I suggest a reboot at this stage.</p>\n\n<h2>Step 4</h2>\n\n<p>Try to install again.</p>\n\n<p>Good Luck!</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78263', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9467/'] |
78,277 | <p>When can 64-bit writes be guaranteed to be atomic, when programming in C on an Intel x86-based platform (in particular, an Intel-based Mac running MacOSX 10.4 using the Intel compiler)? For example:</p>
<pre><code>unsigned long long int y;
y = 0xfedcba87654321ULL;
/* ... a bunch of other time-consuming stuff happens... */
y = 0x12345678abcdefULL;
</code></pre>
<p>If another thread is examining the value of y after the first assignment to y has finished executing, I would like to ensure that it sees either the value 0xfedcba87654321 or the value 0x12345678abcdef, and not some blend of them. I would like to do this without any locking, and if possible without any extra code. My hope is that, when using a 64-bit compiler (the 64-bit Intel compiler), on an operating system capable of supporting 64-bit code (MacOSX 10.4), that these 64-bit writes will be atomic. Is this always true?</p>
| [{'answer_id': 78285, 'author': 'Dark Shikari', 'author_id': 11206, 'author_profile': 'https://Stackoverflow.com/users/11206', 'pm_score': 1, 'selected': False, 'text': '<p>GCC has intrinsics for atomic operations; I suspect you can do similar with other compilers, too. Never rely on the compiler for atomic operations; optimization will almost certainly run the risk of making even obviously atomic operations into non-atomic ones unless you explicitly tell the compiler not to do so.</p>\n'}, {'answer_id': 78321, 'author': 'Allen', 'author_id': 6043, 'author_profile': 'https://Stackoverflow.com/users/6043', 'pm_score': 4, 'selected': False, 'text': '<p>On x86_64, both the Intel compiler and gcc support some intrinsic atomic-operation functions. Here\'s gcc\'s documentation of them: <a href="http://gcc.gnu.org/onlinedocs/gcc-4.1.0/gcc/Atomic-Builtins.html" rel="noreferrer">http://gcc.gnu.org/onlinedocs/gcc-4.1.0/gcc/Atomic-Builtins.html</a></p>\n\n<p>The Intel compiler docs also talk about them here: <a href="http://softwarecommunity.intel.com/isn/downloads/softwareproducts/pdfs/347603.pdf" rel="noreferrer">http://softwarecommunity.intel.com/isn/downloads/softwareproducts/pdfs/347603.pdf</a> (page 164 or thereabouts).</p>\n'}, {'answer_id': 78383, 'author': 'Chris Hanson', 'author_id': 714, 'author_profile': 'https://Stackoverflow.com/users/714', 'pm_score': 5, 'selected': False, 'text': '<p>Your best bet is to avoid trying to build your own system out of primitives, and instead use locking unless it <strong>really</strong> shows up as a hot spot when profiling. (If you think you can be clever and avoid locks, don\'t. You aren\'t. That\'s the general "you" which includes me and everybody else.) You should at minimum use a spin lock, see <a href="http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/spinlock.3.html" rel="noreferrer">spinlock(3)</a>. And whatever you do, <strong>don\'t</strong> try to implement "your own" locks. You will get it wrong.</p>\n\n<p>Ultimately, you need to use whatever locking or atomic operations your operating system provides. Getting these sorts of things <strong>exactly right</strong> in <strong>all cases</strong> is <strong>extremely difficult</strong>. Often it can involve knowledge of things like the errata for specific versions of specific processor. ("Oh, version 2.0 of that processor didn\'t do the cache-coherency snooping at the right time, it\'s fixed in version 2.0.1 but on 2.0 you need to insert a <code>NOP</code>.") Just slapping a <code>volatile</code> keyword on a variable in C is almost always insufficient.</p>\n\n<p>On Mac OS X, that means you need to use the functions listed in <a href="http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/atomic.3.html" rel="noreferrer">atomic(3)</a> to perform truly atomic-across-all-CPUs operations on 32-bit, 64-bit, and pointer-sized quantities. (Use the latter for any atomic operations on pointers so you\'re 32/64-bit compatible automatically.) That goes whether you want to do things like atomic compare-and-swap, increment/decrement, spin locking, or stack/queue management. Fortunately the <a href="http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/spinlock.3.html" rel="noreferrer">spinlock(3)</a>, <a href="http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/atomic.3.html" rel="noreferrer">atomic(3)</a>, and <a href="http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/barrier.3.html" rel="noreferrer">barrier(3)</a> functions should all work correctly on all CPUs that are supported by Mac OS X.</p>\n'}, {'answer_id': 78399, 'author': 'Mike Dimmick', 'author_id': 6970, 'author_profile': 'https://Stackoverflow.com/users/6970', 'pm_score': 4, 'selected': False, 'text': '<p>According to Chapter 7 of <a href="http://download.intel.com/design/processor/manuals/253668.pdf" rel="noreferrer">Part 3A - System Programming Guide</a> of Intel\'s <a href="http://www.intel.com/products/processor/manuals/index.htm" rel="noreferrer">processor manuals</a>, quadword accesses will be carried out atomically if aligned on a 64-bit boundary, on a Pentium or newer, and unaligned (if still within a cache line) on a P6 or newer. You should use <code>volatile</code> to ensure that the compiler doesn\'t try to cache the write in a variable, and you may need to use a memory fence routine to ensure that the write happens in the proper order.</p>\n\n<p>If you need to base the value written on an existing value, you should use your operating system\'s Interlocked features (e.g. Windows has InterlockedIncrement64).</p>\n'}, {'answer_id': 78405, 'author': 'Michael Burr', 'author_id': 12711, 'author_profile': 'https://Stackoverflow.com/users/12711', 'pm_score': 2, 'selected': False, 'text': '<p>If you want to do something like this for interthread or interprocess communication, then you need to have more than just an atomic read/write guarantee. In your example, it appears that you want the values written to indicate that some work is in progress and/or has been completed. You will need to do several things, not all of which are portable, to ensure that the compiler has done things in the order you want them done (the volatile keyword may help to a certain extent) and that memory is consistent. Modern processors and caches can perform work out of order unbeknownst to the compiler, so you really need some platform support (ie., locks or platform-specific interlocked APIs) to do what it appears you want to do.</p>\n\n<p>"Memory fence" or "memory barrier" are terms you may want to research.</p>\n'}, {'answer_id': 78439, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': "<p>On Intel MacOSX, you can use the built-in system atomic operations. There isn't a provided atomic get or set for either 32 or 64 bit integers, but you can build that out of the provided CompareAndSwap. You may wish to search XCode documentation for the various OSAtomic functions. I've written the 64-bit version below. The 32-bit version can be done with similarly named functions.</p>\n\n<pre><code>#include <libkern/OSAtomic.h>\n// bool OSAtomicCompareAndSwap64Barrier(int64_t oldValue, int64_t newValue, int64_t *theValue);\n\nvoid AtomicSet(uint64_t *target, uint64_t new_value)\n{\n while (true)\n {\n uint64_t old_value = *target;\n if (OSAtomicCompareAndSwap64Barrier(old_value, new_value, target)) return;\n }\n}\n\nuint64_t AtomicGet(uint64_t *target)\n{\n while (true)\n {\n int64 value = *target;\n if (OSAtomicCompareAndSwap64Barrier(value, value, target)) return value;\n }\n}\n</code></pre>\n\n<p>Note that Apple's OSAtomicCompareAndSwap functions atomically perform the operation:</p>\n\n<pre><code>if (*theValue != oldValue) return false;\n*theValue = newValue;\nreturn true;\n</code></pre>\n\n<p>We use this in the example above to create a Set method by first grabbing the old value, then attempting to swap the target memory's value. If the swap succeeds, that indicates that the memory's value is still the old value at the time of the swap, and it is given the new value during the swap (which itself is atomic), so we are done. If it doesn't succeed, then some other thread has interfered by modifying the value in-between when we grabbed it and when we tried to reset it. If that happens, we can simply loop and try again with only minimal penalty.</p>\n\n<p>The idea behind the Get method is that we can first grab the value (which may or may not be the actual value, if another thread is interfering). We can then try to swap the value with itself, simply to check that the initial grab was equal to the atomic value.</p>\n\n<p>I haven't checked this against my compiler, so please excuse any typos.</p>\n\n<p>You mentioned OSX specifically, but in case you need to work on other platforms, Windows has a number of Interlocked* functions, and you can search the MSDN documentation for them. Some of them work on Windows 2000 Pro and later, and some (particularly some of the 64-bit functions) are new with Vista. On other platforms, GCC versions 4.1 and later have a variety of __sync* functions, such as __sync_fetch_and_add(). For other systems, you may need to use assembly, and you can find some implementations in the SVN browser for the HaikuOS project, inside src/system/libroot/os/arch.</p>\n"}, {'answer_id': 1651862, 'author': 'Adisak', 'author_id': 14904, 'author_profile': 'https://Stackoverflow.com/users/14904', 'pm_score': 3, 'selected': False, 'text': '<p>On X86, the fastest way to atomically write an aligned 64-bit value is to use FISTP. For unaligned values, you need to use a CAS2 (_InterlockedExchange64). The CAS2 operation is quite slow due to BUSLOCK though so it can often be faster to check alignment and do the FISTP version for aligned addresses. Indeed, this is how the <a href="http://www.threadingbuildingblocks.org/" rel="noreferrer">Intel Threaded building Blocks</a> implements Atomic 64-bit writes.</p>\n'}, {'answer_id': 29480621, 'author': 'Jeff Hammond', 'author_id': 2189128, 'author_profile': 'https://Stackoverflow.com/users/2189128', 'pm_score': 2, 'selected': False, 'text': '<p>The latest version of ISO C (C11) defines a set of atomic operations, including <code>atomic_store(_explicit)</code>. See e.g. <a href="http://en.cppreference.com/w/c/atomic" rel="nofollow">this page</a> for more information.</p>\n\n<p>The second most portable implementation of atomics are the GCC intrinsics, which have already been mentioned. I find that they are fully supported by GCC, Clang, Intel, and IBM compilers, and - as of the last time I checked - partially supported by the Cray compilers.</p>\n\n<p>One clear advantage of C11 atomics - in addition to the whole ISO standard thing - is that they support a more precise memory consistency prescription. The GCC atomics imply a full memory barrier as far as I know.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78277', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
78,278 | <p>How do I write a clean implementation of the strategy pattern in Perl? I want to do it in a way that leverages Perl's features.</p>
| [{'answer_id': 78301, 'author': 'Leon Timmermans', 'author_id': 4727, 'author_profile': 'https://Stackoverflow.com/users/4727', 'pm_score': 2, 'selected': False, 'text': '<p>Use sub references, and closures. A good perlish example of this</p>\n\n<pre><code>sort { lc($a) cmp lc($b) } @items\n</code></pre>\n'}, {'answer_id': 83715, 'author': 'tsee', 'author_id': 13164, 'author_profile': 'https://Stackoverflow.com/users/13164', 'pm_score': 4, 'selected': True, 'text': '<p>It really depends on what you mean by "clean implementation". As in any other language, you can use Perl\'s object system with polymorphism to do this for you. However, since Perl has first class functions, this pattern isn\'t normally coded explicitly. Leon Timmermans\' example of</p>\n\n<pre><code>sort { lc($a) cmp lc($b) } @items\n</code></pre>\n\n<p>demonstrates this quite elegantly.</p>\n\n<p>However, if you\'re looking for a "formal" implementation as you would do in C++, here\'s what it may look like using Perl+<a href="http://search.cpan.org/dist/Moose" rel="noreferrer">Moose</a>. This is just a translation of the C++ code from <a href="http://en.wikipedia.org/wiki/Strategy_pattern" rel="noreferrer">Wikipedia -- Strategy pattern</a>, except I\'m using Moose\'s support for delegation.</p>\n\n<pre><code>package StrategyInterface;\nuse Moose::Role;\nrequires \'run\';\n\n\npackage Context;\nuse Moose;\nhas \'strategy\' => (\n is => \'rw\',\n isa => \'StrategyInterface\',\n handles => [ \'run\' ],\n);\n\n\npackage SomeStrategy;\nuse Moose;\nwith \'StrategyInterface\';\nsub run { warn "applying SomeStrategy!\\n"; }\n\n\npackage AnotherStrategy;\nuse Moose;\nwith \'StrategyInterface\';\nsub run { warn "applying AnotherStrategy!\\n"; }\n\n\n###############\npackage main;\nmy $contextOne = Context->new(\n strategy => SomeStrategy->new()\n);\n\nmy $contextTwo = Context->new(\n strategy => AnotherStrategy->new()\n);\n\n$contextOne->run();\n$contextTwo->run();\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78278', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1227001/'] |
78,282 | <p>I have this idea for a free backup application.</p>
<p>The largest problem I need to solve at the moment is how to access files which are being used or are system files. I would like the application to be able to perform a full backup of files (i.e. not on a disk sector by sector level).</p>
<p>I'll turn the server part of the application into a service. First of all this service will need to be run with administrative privileges I guess? And secondly, is it possible to access locked files and files used by the system? Maybe take those files after the next reboot? (I've seen some anti virus applications work that way.)</p>
<p>I will use C# and the .NET platform, as it seems to be the easiest way to develop Windows applications these days.</p>
| [{'answer_id': 78314, 'author': 'Darrel Miller', 'author_id': 6819, 'author_profile': 'https://Stackoverflow.com/users/6819', 'pm_score': 1, 'selected': False, 'text': '<p>Do a Google on HoboCopy. It is an open source backup tool for windows that can backup files that are in use using Windows Volume Shadow Service.</p>\n'}, {'answer_id': 78344, 'author': 'Adrian Clark', 'author_id': 148, 'author_profile': 'https://Stackoverflow.com/users/148', 'pm_score': 4, 'selected': True, 'text': '<p>What you\'re looking for regarding the files in use is the "<a href="http://msdn.microsoft.com/en-us/library/bb968832(VS.85).aspx" rel="nofollow noreferrer" title="MSDN - Volume Shadow Copy Service">Volume Shadow Copy Service</a>" which is available on Windows XP, Server 2003 and above. This will allow you to copy files even when they are in use.</p>\n\n<p>I have found a CodeProject article "<a href="http://www.codeproject.com/KB/dotnet/makeshadowcopy.aspx?display=Print" rel="nofollow noreferrer" title="CodeProject - Volume Shadow Copies from .NET">Volume Shadow Copies from .NET</a>" which describes a simple Outlook PST backup application written against Volume Shadow Copy.</p>\n'}, {'answer_id': 78350, 'author': 'chakrit', 'author_id': 3055, 'author_profile': 'https://Stackoverflow.com/users/3055', 'pm_score': 1, 'selected': False, 'text': '<p>Nothing in .NET that could do that directly AFAIK.</p>\n\n<p>I think you are looking for <strong><a href="http://msdn.microsoft.com/en-us/library/bb968832(VS.85).aspx" rel="nofollow noreferrer">Volume Shadow Copy</a></strong> on XP/Vista which is designed for this kind of task.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78282', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
78,296 | <p>What are some reasons why PHP would force errors to show, no matter what you tell it to disable?</p>
<p>I have tried </p>
<pre><code>error_reporting(0);
ini_set('display_errors', 0);
</code></pre>
<p>with no luck.</p>
| [{'answer_id': 78324, 'author': 'Adam Wright', 'author_id': 1200, 'author_profile': 'https://Stackoverflow.com/users/1200', 'pm_score': 5, 'selected': True, 'text': '<p>Note the caveat in the manual at <a href="http://uk.php.net/error_reporting" rel="noreferrer">http://uk.php.net/error_reporting</a>:</p>\n\n<blockquote>\n <blockquote>\n <p>Most of E_STRICT errors are evaluated at the compile time thus such errors are not reported in the file where error_reporting is enhanced to include E_STRICT errors (and vice versa).</p>\n </blockquote>\n</blockquote>\n\n<p>If your underlying system is configured to report E_STRICT errors, these may be output before your code is even considered. Don\'t forget, error_reporting/ini_set are runtime evaluations, and anything performed in a "before-run" phase will not see their effects.</p>\n\n<hr>\n\n<p>Based on your comment that your error is...</p>\n\n<blockquote>\n <p>Parse error: syntax error, unexpected T_VARIABLE, expecting \',\' or \';\' in /usr/home/REDACTED/public_html/dev.php on line 11</p>\n</blockquote>\n\n<p>Then the same general concept applies. Your code is never run, as it is syntactically invalid (you forgot a \';\'). Therefore, your change of error reporting is never encountered.</p>\n\n<p>Fixing this requires a change of the system level error reporting. For example, on Apache you may be able to place...</p>\n\n<p>php_value error_reporting 0</p>\n\n<p>in a .htaccess file to suppress them all, but this is system configuration dependent.</p>\n\n<p>Pragmatically, don\'t write files with syntax errors :)</p>\n'}, {'answer_id': 78370, 'author': 'Vinko Vrsalovic', 'author_id': 5190, 'author_profile': 'https://Stackoverflow.com/users/5190', 'pm_score': 0, 'selected': False, 'text': '<p>Use <em>log_errors</em> for them to be logged instead of displayed.</p>\n'}, {'answer_id': 92354, 'author': 'Willem', 'author_id': 15447, 'author_profile': 'https://Stackoverflow.com/users/15447', 'pm_score': 2, 'selected': False, 'text': '<p>To prevent errors from displaying you can</p>\n\n<ul>\n<li>Write in a .htaccess: <em>php_flag display_errors 0</em></li>\n<li>Split your code in separate modules where the\nmain (parent) PHP file only sets the\nerror_logging and then include() the\nother files.</li>\n</ul>\n'}, {'answer_id': 97149, 'author': 'troelskn', 'author_id': 18180, 'author_profile': 'https://Stackoverflow.com/users/18180', 'pm_score': 0, 'selected': False, 'text': '<p>If the setting is specified in Apache using <em>php_admin_value</em>, it can\'t be changed in .htaccess or at runtime.</p>\n\n<p>See: <em><a href="http://docs.php.net/configuration.changes" rel="nofollow noreferrer">How to change configuration settings</a></em></p>\n'}, {'answer_id': 4579143, 'author': 'khalid', 'author_id': 560416, 'author_profile': 'https://Stackoverflow.com/users/560416', 'pm_score': 1, 'selected': False, 'text': '<p>Use <a href="http://php.net/manual/en/function.phpinfo.php" rel="nofollow noreferrer">phpinfo</a> to find the loaded php.ini and edit it to hide errors. It overrides what you put in your script.</p>\n'}, {'answer_id': 17019832, 'author': 'komodosp', 'author_id': 1495940, 'author_profile': 'https://Stackoverflow.com/users/1495940', 'pm_score': 1, 'selected': False, 'text': '<p>Is <code>set_error_handler()</code> used anywhere in your script? This overrides <code>error_reporting(0)</code>.</p>\n'}, {'answer_id': 34137690, 'author': 'ob-ivan', 'author_id': 2184166, 'author_profile': 'https://Stackoverflow.com/users/2184166', 'pm_score': 0, 'selected': False, 'text': "<blockquote>\n <p>Pragmatically, don't write files with syntax errors :)</p>\n</blockquote>\n\n<p>To ensure there's no syntax errors in your file, run the following:</p>\n\n<pre><code>php -l YOUR_FILE_HERE.php\n</code></pre>\n\n<p>This will output something like this:</p>\n\n<pre><code>PHP Parse error: syntax error, unexpected '}' in Connection.class.php on line 31\n</code></pre>\n"}, {'answer_id': 47844586, 'author': 'dheerendra', 'author_id': 7879171, 'author_profile': 'https://Stackoverflow.com/users/7879171', 'pm_score': 0, 'selected': False, 'text': "<p>Just add the below code in your <strong>index.php</strong> file:</p>\n\n<pre><code>ini_set('display_errors', False);\n</code></pre>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78296', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14322/'] |
78,303 | <p>I'm toying with my first remoting project and I need to create a RemotableType DLL. I know I can compile it by hand with csc, but I wonder if there are some facilities in place on Visual Studio to handle the Remoting case, or, more specificly, to tell it that a specific file should be compiled as a .dll without having to add another project to a solution exclusively to compile a class or two into DLLs. </p>
<p>NOTE: I know I should toy with my first WCF project, but this has to run on 2.0.</p>
| [{'answer_id': 78324, 'author': 'Adam Wright', 'author_id': 1200, 'author_profile': 'https://Stackoverflow.com/users/1200', 'pm_score': 5, 'selected': True, 'text': '<p>Note the caveat in the manual at <a href="http://uk.php.net/error_reporting" rel="noreferrer">http://uk.php.net/error_reporting</a>:</p>\n\n<blockquote>\n <blockquote>\n <p>Most of E_STRICT errors are evaluated at the compile time thus such errors are not reported in the file where error_reporting is enhanced to include E_STRICT errors (and vice versa).</p>\n </blockquote>\n</blockquote>\n\n<p>If your underlying system is configured to report E_STRICT errors, these may be output before your code is even considered. Don\'t forget, error_reporting/ini_set are runtime evaluations, and anything performed in a "before-run" phase will not see their effects.</p>\n\n<hr>\n\n<p>Based on your comment that your error is...</p>\n\n<blockquote>\n <p>Parse error: syntax error, unexpected T_VARIABLE, expecting \',\' or \';\' in /usr/home/REDACTED/public_html/dev.php on line 11</p>\n</blockquote>\n\n<p>Then the same general concept applies. Your code is never run, as it is syntactically invalid (you forgot a \';\'). Therefore, your change of error reporting is never encountered.</p>\n\n<p>Fixing this requires a change of the system level error reporting. For example, on Apache you may be able to place...</p>\n\n<p>php_value error_reporting 0</p>\n\n<p>in a .htaccess file to suppress them all, but this is system configuration dependent.</p>\n\n<p>Pragmatically, don\'t write files with syntax errors :)</p>\n'}, {'answer_id': 78370, 'author': 'Vinko Vrsalovic', 'author_id': 5190, 'author_profile': 'https://Stackoverflow.com/users/5190', 'pm_score': 0, 'selected': False, 'text': '<p>Use <em>log_errors</em> for them to be logged instead of displayed.</p>\n'}, {'answer_id': 92354, 'author': 'Willem', 'author_id': 15447, 'author_profile': 'https://Stackoverflow.com/users/15447', 'pm_score': 2, 'selected': False, 'text': '<p>To prevent errors from displaying you can</p>\n\n<ul>\n<li>Write in a .htaccess: <em>php_flag display_errors 0</em></li>\n<li>Split your code in separate modules where the\nmain (parent) PHP file only sets the\nerror_logging and then include() the\nother files.</li>\n</ul>\n'}, {'answer_id': 97149, 'author': 'troelskn', 'author_id': 18180, 'author_profile': 'https://Stackoverflow.com/users/18180', 'pm_score': 0, 'selected': False, 'text': '<p>If the setting is specified in Apache using <em>php_admin_value</em>, it can\'t be changed in .htaccess or at runtime.</p>\n\n<p>See: <em><a href="http://docs.php.net/configuration.changes" rel="nofollow noreferrer">How to change configuration settings</a></em></p>\n'}, {'answer_id': 4579143, 'author': 'khalid', 'author_id': 560416, 'author_profile': 'https://Stackoverflow.com/users/560416', 'pm_score': 1, 'selected': False, 'text': '<p>Use <a href="http://php.net/manual/en/function.phpinfo.php" rel="nofollow noreferrer">phpinfo</a> to find the loaded php.ini and edit it to hide errors. It overrides what you put in your script.</p>\n'}, {'answer_id': 17019832, 'author': 'komodosp', 'author_id': 1495940, 'author_profile': 'https://Stackoverflow.com/users/1495940', 'pm_score': 1, 'selected': False, 'text': '<p>Is <code>set_error_handler()</code> used anywhere in your script? This overrides <code>error_reporting(0)</code>.</p>\n'}, {'answer_id': 34137690, 'author': 'ob-ivan', 'author_id': 2184166, 'author_profile': 'https://Stackoverflow.com/users/2184166', 'pm_score': 0, 'selected': False, 'text': "<blockquote>\n <p>Pragmatically, don't write files with syntax errors :)</p>\n</blockquote>\n\n<p>To ensure there's no syntax errors in your file, run the following:</p>\n\n<pre><code>php -l YOUR_FILE_HERE.php\n</code></pre>\n\n<p>This will output something like this:</p>\n\n<pre><code>PHP Parse error: syntax error, unexpected '}' in Connection.class.php on line 31\n</code></pre>\n"}, {'answer_id': 47844586, 'author': 'dheerendra', 'author_id': 7879171, 'author_profile': 'https://Stackoverflow.com/users/7879171', 'pm_score': 0, 'selected': False, 'text': "<p>Just add the below code in your <strong>index.php</strong> file:</p>\n\n<pre><code>ini_set('display_errors', False);\n</code></pre>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78303', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5190/'] |
78,336 | <p>I need to figure out the hard drive name for a solaris box and it is not clear to me what the device name is. On linux, it would be something like <code>/dev/hda</code> or <code>/dev/sda</code>, but on solaris I am getting a bit lost in the partitions and what the device is called. I think that entries like <code>/dev/rdsk/c0t0d0s0</code> are the partitions, how is the whole hard drive referenced?</p>
| [{'answer_id': 78366, 'author': 'JBB', 'author_id': 12332, 'author_profile': 'https://Stackoverflow.com/users/12332', 'pm_score': 5, 'selected': True, 'text': '<p>/dev/rdsk/c0t0d0s0 means Controller 0, SCSI target (ID) 0, and s means Slice (partition) 0.</p>\n\n<p>Typically, by convention, s2 is the entire disk. This partition overlaps with the other partitions.</p>\n\n<p>prtvtoc /dev/rdsk/c0t0d0s0 will show you the partition table for the disk, to make sure.</p>\n'}, {'answer_id': 78372, 'author': 'raldi', 'author_id': 7598, 'author_profile': 'https://Stackoverflow.com/users/7598', 'pm_score': -1, 'selected': False, 'text': '<p>c0t0d0s0 <em>is</em> the entire drive. The breakdown is:</p>\n\n<p>/dev/[r]dsk/c <strong>C</strong> t <strong>A</strong> d0s <strong>S</strong></p>\n\n<p>...where <strong>C</strong> is the controller number, <strong>A</strong> is the SCSI address, and <strong>S</strong> is the "slice". Slice 0 is the whole disk; the other slices are the partition numbers.</p>\n\n<p>See <a href="http://www.washington.edu/R870/DevicesDrivers.html" rel="nofollow noreferrer">this</a> for more info.</p>\n'}, {'answer_id': 79899, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': -1, 'selected': False, 'text': '<p>cXtYdZs2 is the whole drive. period.</p>\n'}, {'answer_id': 391942, 'author': 'tpgould', 'author_id': 32161, 'author_profile': 'https://Stackoverflow.com/users/32161', 'pm_score': 2, 'selected': False, 'text': "<p>What do you want to do to the whole disk? Look at the EXAMPLES section of the man page for the command in question to see how much of a disk name the command requires.</p>\n\n<p>zpool doesn't require a partition, as in: c0t0d0\nnewfs does: c0t0d0s0\ndd would use the whole disk partition: c0t0d0s2</p>\n\n<p>Note: s2 as the entire disk is just a convention. A root user can use the Solaris format command and change the extent of any of the partitions.</p>\n"}, {'answer_id': 657320, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>The comments about slice 2 are only correct for drives with an SMI label.</p>\n\n<p>If the drive is greater than 1TB, or if the drive has been used for ZFS, the drive will have an EFI label and slice 2 will NOT be the entire disk. With an EFI label, slice 2 is "just another slice". You would then refer to the whole disk by using the device name without a slice, e.g. c0t0d0.</p>\n'}, {'answer_id': 8568676, 'author': 'jlliagre', 'author_id': 211665, 'author_profile': 'https://Stackoverflow.com/users/211665', 'pm_score': 2, 'selected': False, 'text': "<p>If you run Solaris on non SPARC hardware and don't use EFI, the whole hard drive is not <code>c0t0d0s2</code> but <code>c0t0d0p0</code>, <code>s2</code> is in that case just the Solaris primary partition. </p>\n"}, {'answer_id': 19933001, 'author': 'user2983806', 'author_id': 2983806, 'author_profile': 'https://Stackoverflow.com/users/2983806', 'pm_score': 1, 'selected': False, 'text': '<p>There are two types for disk label, one is SMI(vtoc), the other is GPT(EFI).</p>\n\n<p>On X86 platform and the disk is SMI labeled(default behavior):\ncXtXdXp0 is the whole physical disk\ncXtXdXp1-cXtXdXp4 are primary partitions, included the solaris partitions.</p>\n\n<p>cXtXdXs0-cXtXdXs8 are the partitions(slices) of the activate Solaris partitions.\ncXtXdXs2 is the whole activate Solaris partition, maybe not the whole disk.</p>\n\n<p>Hope I am clear.</p>\n\n<p>/Meng</p>\n'}, {'answer_id': 64383384, 'author': 'Kim.K.H', 'author_id': 7681987, 'author_profile': 'https://Stackoverflow.com/users/7681987', 'pm_score': 0, 'selected': False, 'text': '<p>C0 - Controller\nT0 - Target\nD0 - Disk\nS- - Slice</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78336', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13912/'] |
78,352 | <p>I've been running into a peculiar issue with certain Java applications in the HP-UX environment. </p>
<p>The heap is set to -mx512, yet, looking at the memory regions for this java process using gpm, it shows it using upwards of 1.6GBs of RSS memory, with 1.1GB allocated to the DATA region. Grows quite rapidly over a 24-48hour period and then slows down substantially, still growing 2MB every few hours. However, the Java heap shows no sign of leakage.</p>
<p>Curious how this was possible I researched a bit and found this HP write-up on memory leaks in java heap and c heap: <a href="http://docs.hp.com/en/JAVAPERFTUNE/Memory-Management.pdf" rel="nofollow noreferrer">http://docs.hp.com/en/JAVAPERFTUNE/Memory-Management.pdf</a></p>
<p>My question is what determines what is ran in the C heap vs the java heap, and for things that do not run through the java heap, how would you identify those objects being run on the C heap? Additionally does the java heap sit inside the C heap?</p>
| [{'answer_id': 78472, 'author': 'Bill K', 'author_id': 12943, 'author_profile': 'https://Stackoverflow.com/users/12943', 'pm_score': 1, 'selected': False, 'text': "<p>My only guess with the figures you have given is a memory leak in the Java VM. You might want to try one of the other VMs they listed in the paper you referred. Another (much more difficult) alternative might be to compile the open java on the HP platform.</p>\n\n<p>Sun's Java isn't 100% open yet, they are working on it, but I believe that there is one in sourceforge that is.</p>\n\n<p>Java also thrashes memory by the way. Sometimes it confuses OS memory management a little (you see it when windows runs out of memory and asks Java to free some up, Java touches all it's objects causing them to be loaded in from the swapfile, windows screams in agony and dies), but I don't think that's what you are seeing.</p>\n"}, {'answer_id': 78533, 'author': 'Mike Tunnicliffe', 'author_id': 13956, 'author_profile': 'https://Stackoverflow.com/users/13956', 'pm_score': 2, 'selected': False, 'text': '<p>In general, only the data in Java objects is stored on the Java heap, all other memory required by the Java VM is allocated from the "native" or "C" heap (in fact, the Java heap itself is just one contiguous chunk allocated from the C heap).</p>\n\n<p>Since the JVM requires the Java heap (or heaps if generational garbage collection is in use) to be a contiguous piece of memory, the whole maximum heap size (-mx value) is usually allocated at JVM start time. In practice, the Java VM will attempt to minimise its use of this space so that the Operating System doesn\'t need to reserve any real memory to it (the OS is canny enough to know when a piece of storage has never been written to).</p>\n\n<p>The Java heap, therefore, will occupy a certain amount of space in memory.</p>\n\n<p>The rest of the storage will be used by the Java VM and any JNI code in use. For example, the JVM requires memory to store Java bytecode and constant pools from loaded classes, the result of JIT compiled code, work areas for compiling JIT code, native thread stacks and other such sundries. </p>\n\n<p>JNI code is just platform-specific (compiled) C code that can be bound to a Java object in the form of a "native" method. When this method is executed the bound code is executed and can allocate memory using standard C routines (eg malloc) which will consume memory on the C heap.</p>\n'}, {'answer_id': 78634, 'author': 'Will Hartung', 'author_id': 13663, 'author_profile': 'https://Stackoverflow.com/users/13663', 'pm_score': 3, 'selected': False, 'text': '<p>Consider what makes up a Java process.</p>\n\n<p>You have:</p>\n\n<ul>\n<li>the JVM (a C program) </li>\n<li>JNI Data</li>\n<li>Java byte codes</li>\n<li>Java data </li>\n</ul>\n\n<p>Notably, they ALL live in the C heap (the JVM Heap is part of the C heap, naturally).</p>\n\n<p>In the Java heap is simply Java byte codes and the Java data. But what is also in the Java heap is "free space".</p>\n\n<p>The typical (i.e. Sun) JVM only grows it Java Heap as necessary, but never shrinks it. Once it reaches its defined maximum (-Xmx512M), it stops growing and deals with whatever is left. When that maximum heap is exhausted, you get the OutOfMemory exception.</p>\n\n<p>What that Xmx512M option DOES NOT do, is limit the overall size of the process. It limits only the Java Heap part of the process.</p>\n\n<p>For example, you could have a contrived Java program that uses 10mb of Java heap, but calls a JNI call that allocates 500MB of C Heap. You can see how your process size is large, even though the Java heap is small. Also, with the new NIO libraries, you can attach memory outside of the heap as well.</p>\n\n<p>The other aspect that you must consider is that the Java GC is typically a "Copying Collector". Which means it takes the "live" data from memory it\'s collecting, and copies it to a different section of memory. This empty space that is copies to IS NOT PART OF THE HEAP, at least, not in terms of the Xmx parameter. It\'s, like, "the new Heap", and becomes part of the heap after the copy (the old space is used for the next GC). If you have a 512MB heap, and it\'s at 510MB, Java is going to copy the live data someplace. The naive thought would be to another large open space (like 500+MB). If all of your data were "live", then it would need a large chunk like that to copy into.</p>\n\n<p>So, you can see that in the most extreme edge case, you need at least double the free memory on your system to handle a specific heap size. At least 1GB for a 512MB heap.</p>\n\n<p>Turns out that not the case in practice, and memory allocation and such is more complicated than that, but you do need a large chunk of free memory to handle the heap copies, and this impacts the overall process size.</p>\n\n<p>Finally, note that the JVM does fun things like mapping in the rt.jar classes in to the VM to ease startup. They\'re mapped in a read only block, and can be shared across other Java processes. These shared pages will "count" against all Java processes, even though it is really only consuming physical memory once (the magic of virtual memory).</p>\n\n<p>Now as to why your process continues to grow, if you never hit the Java OOM message, that means that your leak is NOT in the Java heap, but that doesn\'t mean it may not be in something else (the JRE runtime, a 3rd party JNI librariy, a native JDBC driver, etc.).</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78352', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9628/'] |
78,380 | <p>Our application commonly used an ActiveX control to download and install our client on IE (XP and prior), however as our user base has drifted towards more Vista boxes with "Protected Mode" on, we are required to investigate.</p>
<p>So going forward, is it worth the headache of trying to use the protected mode API? Is this going to result in a deluge of dialog boxes and admin rights to do the things our app needs to do (write to some local file places, access some other applications, etc)?</p>
<p>I'm half bent on just adding a non-browser based installer app that will do the dirty work of downloading and installing the client, if need be... this would only need to be installed once and in large corporate structures it could be pushed out by IT.</p>
<p>Are there some other ideas I'm missing?</p>
| [{'answer_id': 78406, 'author': 'chakrit', 'author_id': 3055, 'author_profile': 'https://Stackoverflow.com/users/3055', 'pm_score': 0, 'selected': False, 'text': '<p>Have you checked out Microsoft\'s <a href="http://msdn.microsoft.com/en-us/library/t71a733d(VS.80).aspx" rel="nofollow noreferrer">ClickOnce Deployment</a>?</p>\n\n<p>If I remember correctly you can embed a manifests which would help with dealing with protected modes automatically, saving you those headaches with the APIs.</p>\n\n<p>I believe ClickOnce is geared for the same thing your ActiveX installer was designed to do.</p>\n\n<p>Since you say your IT dept could push this out, I assume you could use this kind of technology as well.</p>\n\n<p>Even though you might not be writing applications on the .NET CLR, you can use Visual Studio to generate those manifest and installers for you.</p>\n'}, {'answer_id': 78407, 'author': 'jfs', 'author_id': 6223, 'author_profile': 'https://Stackoverflow.com/users/6223', 'pm_score': 1, 'selected': False, 'text': "<p>This client, is it a desktop application and not some software that runs inside the browser? In that case, please just supply a regular download installer application. My personal experience with browser-hosted installers is that they are just confusing and the few I have seen seemed to be poorly coded in some way.</p>\n\n<p>If you use an MSI based installer I'm sure lots of Windows domain administrators will love you too, as Microsoft has tools to deploy MSI based installations onto large sets of machines remotely.</p>\n"}, {'answer_id': 78411, 'author': 'Nidonocu', 'author_id': 483, 'author_profile': 'https://Stackoverflow.com/users/483', 'pm_score': 0, 'selected': False, 'text': "<p>Its far better to do this right than put it off any longer. Vista is Microsoft's way of saying they aren't letting people get away with ignoring security issues any more and encouraging people to update their code.</p>\n\n<p>I'm sure other users here will be able to point you are some MSDN best practices about writing ActiveX controls.</p>\n"}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78380', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
78,389 | <p>I'm new to RhinoMocks, and trying to get a grasp on the syntax in addition to what is happening under the hood.</p>
<p>I have a user object, we'll call it User, which has a property called IsAdministrator. The value for IsAdministrator is evaluated via another class that checks the User's security permissions, and returns either true or false based on those permissions. I'm trying to mock this User class, and fake the return value for IsAdministrator in order to isolate some Unit Tests.</p>
<p>This is what I'm doing so far:</p>
<pre><code>public void CreateSomethingIfUserHasAdminPermissions()
{
User user = _mocks.StrictMock<User>();
SetupResult.For(user.IsAdministrator).Return(true);
// do something with my User object
}
</code></pre>
<p>Now, I'm expecting that Rhino is going to 'fake' the call to the property getter, and just return true to me. Is this incorrect? Currently I'm getting an exception because of dependencies in the IsAdministrator property.</p>
<p>Can someone explain how I can achieve my goal here?</p>
| [{'answer_id': 78428, 'author': 'Aaron Jensen', 'author_id': 11229, 'author_profile': 'https://Stackoverflow.com/users/11229', 'pm_score': 1, 'selected': False, 'text': '<p>Make sure IsAdministrator is virtual.</p>\n\n<p>Also, be sure you call _mocks.ReplayAll()</p>\n'}, {'answer_id': 79719, 'author': 'Josh', 'author_id': 11702, 'author_profile': 'https://Stackoverflow.com/users/11702', 'pm_score': 5, 'selected': True, 'text': '<p>One quick note before I jump into this. Typically you want to avoid the use of a "Strict" mock because it makes for a brittle test. A strict mock will throw an exception if anything occurs that you do not explicitly tell Rhino will happen. Also I think you may be misunderstanding exactly what Rhino is doing when you make a call to create a mock. Think of it as a custom Object that has either been derived from, or implements the System.Type you defined. If you did it yourself it would look like this:</p>\n\n<pre><code>public class FakeUserType: User\n{\n //overriding code here\n}\n</code></pre>\n\n<p>Since IsAdministrator is probably just a public property on the User type you can\'t override it in the inheriting type.</p>\n\n<p>As far as your question is concerned there are multiple ways you could handle this. You could implement IsAdministrator as a virtual property on your user class as <a href="https://stackoverflow.com/questions/78389/rhinomocks-correct-way-to-mock-property-getter#78428">aaronjensen</a> mentioned as follows:</p>\n\n<pre><code>public class User\n{\n public virtual Boolean IsAdministrator { get; set; }\n}\n</code></pre>\n\n<p>This is an ok approach, but only if you plan on inheriting from your User class. Also if you wan\'t to fake other members on this class they would also have to be virtual, which is probably not the desired behavior.</p>\n\n<p>Another way to accomplish this is through the use of interfaces. If it is truly the User class you are wanting to Mock then I would extract an interface from it. Your above example would look something like this:</p>\n\n<pre><code>public interface IUser\n{\n Boolean IsAdministrator { get; }\n}\n\npublic class User : IUser\n{\n private UserSecurity _userSecurity = new UserSecurity();\n\n public Boolean IsAdministrator\n {\n get { return _userSecurity.HasAccess("AdminPermissions"); }\n }\n}\n\npublic void CreateSomethingIfUserHasAdminPermissions()\n{\n IUser user = _mocks.StrictMock<IUser>();\n SetupResult.For(user.IsAdministrator).Return(true);\n\n // do something with my User object\n}\n</code></pre>\n\n<p>You can get fancier if you want by using <a href="http://martinfowler.com/articles/injection.html" rel="nofollow noreferrer">dependency injection and IOC</a> but the basic principle is the same across the board. Typically you want your classes to depend on interfaces rather than concrete implementations anyway.</p>\n\n<p>I hope this helps. I have been using RhinoMocks for a long time on a major project now so don\'t hesitate to ask me questions about TDD and mocking.</p>\n'}, {'answer_id': 2598593, 'author': 'Pavlo Neiman', 'author_id': 164001, 'author_profile': 'https://Stackoverflow.com/users/164001', 'pm_score': 0, 'selected': False, 'text': '<p>_mocks.ReplayAll() will do nothing. It is just because you use SetupResult.For() that does not count. Use Expect.Call() to be sure that your code do everything correct.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78389', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/769/'] |
78,392 | <p>I have an application that works pretty well in Ubuntu, Windows and the Xandros that come with the Asus EeePC.</p>
<p>Now we are moving to the <a href="http://en.wikipedia.org/wiki/Aspire_One" rel="nofollow noreferrer">Acer Aspire One</a> but I'm having a lot of trouble making php-gtk to compile under the Fedora-like (Linpus Linux Lite) Linux that come with it.</p>
| [{'answer_id': 87995, 'author': 'X-Istence', 'author_id': 13986, 'author_profile': 'https://Stackoverflow.com/users/13986', 'pm_score': 0, 'selected': False, 'text': '<p>If you could give us more to go on than just trouble making it compile; we might be better able to help you with your issues.</p>\n'}, {'answer_id': 99021, 'author': 'levhita', 'author_id': 7946, 'author_profile': 'https://Stackoverflow.com/users/7946', 'pm_score': 2, 'selected': True, 'text': '<p>Hi Guys well I finally got this thing to work the basic workflow was this:</p>\n\n<pre><code>#!/bin/bash\nsudo yum install yum-utils\n#We don\'t want to update the main gtk2 by mistake so we download them\n#manually and install with no-deps[1](and forced because gtk version\n#version of AA1 and the gtk2-devel aren\'t compatible).\nsudo yumdownloader --disablerepo=updates gtk2-devel glib2-devel\nsudo rpm --force --nodeps -i gtk2*rpm glib2*rpm\n\n#We install the rest of the libraries needed.\nsudo yum --disablerepo=updates install atk-devel pango-devel libglade2-devel\nsudo yum install php-cli php-devel make gcc\n\n#We Download and compile php-gtk\nwget http://gtk.php.net/do_download.php?download_file=php-gtk-2.0.1.tar.gz\ntar -xvzf php-gtk-2.0.1.tar.gz\ncd php-gtk-2.0.1\n./buildconf\n./configure\nmake\nsudo make install\n</code></pre>\n\n<p>If you want to add more libraries like gtk-extra please type <code>./configure -help</code> before making it to see the different options available.</p>\n\n<p>After installing you\'ll need to add <code>php_gtk2.so</code> to the <em>Dynamic Extensions</em> of <code>/etc/php.ini</code></p>\n\n<pre><code>extension=php_gtk2.so\n</code></pre>\n\n<p>Sources:</p>\n\n<p>[1]: <a href="http://macles.blogspot.com/2008/08/dependency-problems-on-acer-aspire-one.html" rel="nofollow noreferrer">Dependency problems on Acer Aspire One Linux</a></p>\n'}, {'answer_id': 4031145, 'author': 'Valent Turkovic', 'author_id': 488518, 'author_profile': 'https://Stackoverflow.com/users/488518', 'pm_score': 2, 'selected': False, 'text': '<p>I managed to get all components needed for Phoronix test suite installed on Fedora but still have one issue.</p>\n\n<pre><code># phoronix-test-suite gui\nshell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory\npwd: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory\npwd: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory\n/usr/bin/phoronix-test-suite: line 28: [: /usr/share/phoronix-test-suite: unary operator expected\n</code></pre>\n\n<p>You need two packages that aren\'t in Fedora, php-gtk, but php-gtk also has it\'s dependency - pecl-cairo</p>\n\n<p>php-gtk needs to be downloaded from svn because tar.gz version is really old and doesn\'t work with php 5.3</p>\n\n<p>Here is how I got all components built.</p>\n\n<pre><code>su -c "yum install php-cli php-devel make gcc gtk2-devel svn"\n\nsvn co http://svn.php.net/repository/pecl/cairo/trunk pecl-cairo\ncd pecl-cairo/\nphpize\n./configure\nmake\nsu -c "make install"\n\ncd ..\n\nsvn co http://svn.php.net/repository/gtk/php-gtk/trunk php-gtk\ncd php-gtk\n./buildconf\n./configure\nmake\nsu -c "make install"\n\ncd ..\n\nwget http://www.phoronix-test-suite.com/download.php?file=phoronix-test-suite-2.8.1\ntar xvzf phoronix-test-suite-2.8.1.tar.gz\ncd phoronix-test-suite\nsu -c "./install-sh"\n</code></pre>\n\n<p>So please take where I left to get Phoronix test suite running on Fedora.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7946/'] |
78,422 | <p>When writing a custom server, what are the best practices or techniques to determine maximum number of users that can connect to the server at any given time?</p>
<p>I would assume that the capabilities of the computer hardware, network capacity, and server protocol would all be important factors. </p>
<p>Also, do you think it is a good practice to limit the number of network connections to a certain maximum number of users? Or should the server not limit the number of network connections and let performance degrade until the response time is extremely high?</p>
| [{'answer_id': 78437, 'author': 'Don Neufeld', 'author_id': 13097, 'author_profile': 'https://Stackoverflow.com/users/13097', 'pm_score': 3, 'selected': False, 'text': '<p>In general modern servers can handle very large numbers of concurrent connections. I\'ve worked on systems having over 8,000 concurrently open TCP/IP sockets.</p>\n\n<p>You will need a high quality servicing interface to handle that kind of load, check out <a href="http://monkey.org/~provos/libevent/" rel="noreferrer">libevent</a> or <a href="http://software.schmorp.de/pkg/libev.html" rel="noreferrer">libev</a>.</p>\n'}, {'answer_id': 78454, 'author': 'zxcv', 'author_id': 9628, 'author_profile': 'https://Stackoverflow.com/users/9628', 'pm_score': 0, 'selected': False, 'text': '<p>One of the biggest setbacks in high concurrency connections is actually the routers involved. Home user oriented routers usually have a small NAT table, preventing the router from actually servicing the server the connections. </p>\n\n<p>Be sure to research your router/ network infrastructure setup just as well.</p>\n'}, {'answer_id': 78466, 'author': 'Svet', 'author_id': 8934, 'author_profile': 'https://Stackoverflow.com/users/8934', 'pm_score': 0, 'selected': False, 'text': "<p>I think you shouldn't limit the number of connections your server will allow - just catch and handle properly any exceptions that might occur when accepting and closing connections and you should be fine. You should leave that kind of lower level programming to the underlying OS layers - that way you can port your server easier etc. </p>\n"}, {'answer_id': 78467, 'author': 'William', 'author_id': 9193, 'author_profile': 'https://Stackoverflow.com/users/9193', 'pm_score': 0, 'selected': False, 'text': '<p>This really depends on your operating system.</p>\n\n<p>Different Unix flavors will support "unlimited" number of file handles / sockets others have high values like 32768.</p>\n\n<p>A typical user limit is 8192 but it can usually be set higher.</p>\n\n<p>I think windows is more limiting but the server version may have higher limits.</p>\n'}, {'answer_id': 78470, 'author': 'Michael Brown', 'author_id': 14359, 'author_profile': 'https://Stackoverflow.com/users/14359', 'pm_score': 2, 'selected': False, 'text': '<p>That is a good question and it definitely is situational. What is your computer? Do you have a 4 socket machine filled with Quad Core Xeons, 128 GB of RAM, and Fiber Channel Connectivity (like the pair of Dell R900s we just bought)? Or are you running on a p3 550 with 256 MB of RAM, and 56K modem? How much load does each connection place on your server? What kind of response is acceptible?</p>\n\n<p>These are the questions you need to answer. I guess the best way to find the answer is through load testing. Create a unit test of the expected (and maybe some unexpected) paths that your code will perform against your server. Find a load testing framework that will allow you to simulate 10, 100, 1000, 10000 users performing those tasks at the same time.</p>\n\n<p>That will tell you how many connections your computer can support.</p>\n\n<p>The great thing about the load/unit test scenario is that you can put in response time expectations in your unit tests and increase the load until you fall outside of your response time. If you have a requirement of supporting X number of Users with Y second response, you will be able to demonstrate it with your load tests.</p>\n'}, {'answer_id': 78578, 'author': 'Allen', 'author_id': 6043, 'author_profile': 'https://Stackoverflow.com/users/6043', 'pm_score': 4, 'selected': True, 'text': '<p>Dan Kegel put together a summary of techniques for handling large amounts of network connections from a single server, here: <a href="http://www.kegel.com/c10k.html" rel="noreferrer">http://www.kegel.com/c10k.html</a></p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78422', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10216/'] |
78,423 | <p>The error I'm getting:</p>
<pre><code>in /Users/robert/Documents/funWithFrameworks/build/Debug-iphonesimulator/funWithFrameworks.framework/funWithFrameworks, can't link with a main executable
</code></pre>
<p>Cliff notes:</p>
<ul>
<li>trying to include framework</li>
<li>doesn't want to link</li>
</ul>
<p>More detail:
I'm developing for a <em>mobile device... hint, hint</em> using Xcode and I'm trying to make my
own custom framework which I can include from another application. So far, I've done the following:</p>
<ol>
<li>Create a new project; an iPhone OS window based app.</li>
<li>Go to target info-> under packaging, change the wrapper extension from app to framework</li>
<li>Go to Action->new build phase -> copy headers. Change roles of headers to 'public'</li>
<li>From my application, I add the framework to the frameworks group.</li>
</ol>
| [{'answer_id': 79109, 'author': 'amrox', 'author_id': 4468, 'author_profile': 'https://Stackoverflow.com/users/4468', 'pm_score': 0, 'selected': False, 'text': '<p>I haven\'t tried it for so called <em>mobile device</em>, but I would guess its very similar to the method for a regular Cocoa application. Check out this tutorial:</p>\n\n<p><a href="http://rentzsch.com/cocoa/embeddedFrameworks" rel="nofollow noreferrer">Embedded Cocoa Frameworks</a></p>\n'}, {'answer_id': 81659, 'author': 'user8030', 'author_id': 8030, 'author_profile': 'https://Stackoverflow.com/users/8030', 'pm_score': 4, 'selected': True, 'text': '<p>Apple clearly said that you can <strong>not</strong> use dynamic libraries on their mobiles. And a private framework is just this.</p>\n\n<p>You can, however, use static libraries.</p>\n'}, {'answer_id': 383810, 'author': 'Tom Harrington', 'author_id': 43832, 'author_profile': 'https://Stackoverflow.com/users/43832', 'pm_score': 1, 'selected': False, 'text': '<p>Egil, that\'s usually considered as one of the implications of section 3.3.2 of the iPhone developer agreement, which (in part) forbids plug-in architectures or other frameworks. The fact that they don\'t provide an Xcode project template for an iPhone-compatible framework tends to reinforce the idea, though of course it could just be an oversight or something they\'re discouraging without actually forbidding.</p>\n\n<p>Whether this is the intended meaning of that section is something you\'d have to ask Apple about, and possibly consult a lawyer, but this is where the oft-stated "no frameworks" idea comes from.</p>\n\n<p>For those who have framework code they\'d like to use in an iPhone app, an alternative approach is to use the framework code to build a static library. That then gets compiled into the application instead of getting dynamically loaded at run time. The fact that it\'s part of the application executable avoids any potential concerns about this part of the agreement.</p>\n'}, {'answer_id': 2879475, 'author': 'jbenet', 'author_id': 346736, 'author_profile': 'https://Stackoverflow.com/users/346736', 'pm_score': 1, 'selected': False, 'text': '<p>Though dynamic libraries are not allowed, you CAN create a framework (using static libraries and lipo). </p>\n\n<p>Check out: <a href="http://accu.org/index.php/journals/1594" rel="nofollow noreferrer">http://accu.org/index.php/journals/1594</a></p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78423', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
78,431 | <p>I would like to replicate this in python:</p>
<pre><code>gvimdiff <(hg cat file.txt) file.txt
</code></pre>
<p>(hg cat file.txt outputs the most recently committed version of file.txt)</p>
<p>I know how to pipe the file to gvimdiff, but it won't accept another file:</p>
<pre><code>$ hg cat file.txt | gvimdiff file.txt -
Too many edit arguments: "-"
</code></pre>
<p>Getting to the python part...</p>
<pre><code># hgdiff.py
import subprocess
import sys
file = sys.argv[1]
subprocess.call(["gvimdiff", "<(hg cat %s)" % file, file])
</code></pre>
<p>When subprocess is called it merely passes <code><(hg cat file)</code> onto <code>gvimdiff</code> as a filename.</p>
<p>So, is there any way to redirect a command as bash does?
For simplicity's sake just cat a file and redirect it to diff:</p>
<pre><code>diff <(cat file.txt) file.txt
</code></pre>
| [{'answer_id': 78459, 'author': 'Mark Hattarki', 'author_id': 14424, 'author_profile': 'https://Stackoverflow.com/users/14424', 'pm_score': 2, 'selected': False, 'text': '<p>There is also the commands module:</p>\n\n<pre><code>import commands\n\nstatus, output = commands.getstatusoutput("gvimdiff <(hg cat file.txt) file.txt")\n</code></pre>\n\n<p>There is also the popen set of functions, if you want to actually grok the data from a command as it is running.</p>\n'}, {'answer_id': 78481, 'author': 'Mark Hattarki', 'author_id': 14424, 'author_profile': 'https://Stackoverflow.com/users/14424', 'pm_score': -1, 'selected': False, 'text': '<p>It just dawned on me that you are probably looking for one of the popen functions.</p>\n\n<p>from: <a href="http://docs.python.org/lib/module-popen2.html" rel="nofollow noreferrer">http://docs.python.org/lib/module-popen2.html</a></p>\n\n<p>popen3(cmd[, bufsize[, mode]])\n Executes cmd as a sub-process. Returns the file objects (child_stdout, child_stdin, child_stderr). </p>\n\n<p>namaste,\nMark</p>\n'}, {'answer_id': 78482, 'author': 'Charles Duffy', 'author_id': 14122, 'author_profile': 'https://Stackoverflow.com/users/14122', 'pm_score': 4, 'selected': True, 'text': "<p>It can be done. As of Python 2.5, however, this mechanism is Linux-specific and not portable:</p>\n\n<pre><code>import subprocess\nimport sys\n\nfile = sys.argv[1]\np1 = subprocess.Popen(['hg', 'cat', file], stdout=subprocess.PIPE)\np2 = subprocess.Popen([\n 'gvimdiff',\n '/proc/self/fd/%s' % p1.stdout.fileno(),\n file])\np2.wait()\n</code></pre>\n\n<p>That said, in the specific case of diff, you can simply take one of the files from stdin, and remove the need to use the bash-alike functionality in question:</p>\n\n<pre><code>file = sys.argv[1]\np1 = subprocess.Popen(['hg', 'cat', file], stdout=subprocess.PIPE)\np2 = subprocess.Popen(['diff', '-', file], stdin=p1.stdout)\ndiff_text = p2.communicate()[0]\n</code></pre>\n"}, {'answer_id': 78923, 'author': 'pjz', 'author_id': 8002, 'author_profile': 'https://Stackoverflow.com/users/8002', 'pm_score': 2, 'selected': False, 'text': '<p>This is actually an example in the <a href="https://docs.python.org/2.4/lib/node242.html" rel="nofollow noreferrer">docs</a>:</p>\n\n<pre><code>p1 = Popen(["dmesg"], stdout=PIPE)\np2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)\noutput = p2.communicate()[0]\n</code></pre>\n\n<p>which means for you:</p>\n\n<pre><code>import subprocess\nimport sys\n\nfile = sys.argv[1]\np1 = Popen(["hg", "cat", file], stdout=PIPE)\np2 = Popen(["gvimdiff", "file.txt"], stdin=p1.stdout, stdout=PIPE)\noutput = p2.communicate()[0]\n</code></pre>\n\n<p>This removes the use of the linux-specific /proc/self/fd bits, making it probably work on other unices like Solaris and the BSDs (including MacOS) and maybe even work on Windows.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78431', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12650/'] |
78,447 | <p>How to create a DOM from a User's input in PHP5?</p>
| [{'answer_id': 78465, 'author': 'Adam Wright', 'author_id': 1200, 'author_profile': 'https://Stackoverflow.com/users/1200', 'pm_score': 2, 'selected': False, 'text': '<p>I would use the DOM API that has been part of the core since 5. For an XML string $xml, you can build a DOM object with</p>\n\n<pre><code>$dom = new DOMDocument();\n$dom->loadXML($xml);\n</code></pre>\n\n<p>Manipulate it with the rest of the DOM API, defined at <a href="http://uk.php.net/DOM" rel="nofollow noreferrer">http://uk.php.net/DOM</a></p>\n'}, {'answer_id': 89750, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>And when you need to inject it back into some other DOM (like your HTML page) you can export it again using the $dom->saveXML() method. The problem however is that it also exports an xml header (it\'s even worse for the saveHTML version). To get rid of that use this:</p>\n\n<pre><code>$xml = $dom->saveXML();\n$xml = substr( $xml, strlen( "<?xml version=\\"1.0\\"?>" ) );\n</code></pre>\n'}, {'answer_id': 97408, 'author': 'troelskn', 'author_id': 18180, 'author_profile': 'https://Stackoverflow.com/users/18180', 'pm_score': 0, 'selected': False, 'text': '<p>If the input is HTML, use the loadHTML method. Be ware that the input has to be valid code, so you might want to pipe it through <a href="http://docs.php.net/manual/en/book.tidy.php" rel="nofollow noreferrer">html tidy</a> first.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78447', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12854/'] |
78,450 | <p>I'm trying to use Python with ReportLab 2.2 to create a PDF report.<br>
According to the <a href="http://www.reportlab.com/docs/userguide.pdf" rel="noreferrer">user guide</a>,</p>
<blockquote>
<p>Special TableStyle Indeces [sic]</p>
<p>In any style command the first row index may be set to one of the special strings 'splitlast' or 'splitfirst' to indicate that the style should be used only for the last row of a split table, or the first row of a continuation. This allows splitting tables with nicer effects around the split.</p>
</blockquote>
<p>I've tried using several style elements, including:</p>
<pre><code>('TEXTCOLOR', (0, 'splitfirst'), (1, 'splitfirst'), colors.black)
('TEXTCOLOR', (0, 'splitfirst'), (1, 0), colors.black)
('TEXTCOLOR', (0, 'splitfirst'), (1, -1), colors.black)
</code></pre>
<p>and none of these seems to work. The first generates a TypeError with the message: </p>
<pre><code>TypeError: cannot concatenate 'str' and 'int' objects
</code></pre>
<p>and the latter two generate TypeErrors with the message:</p>
<pre><code>TypeError: an integer is required
</code></pre>
<p>Is this functionality simply broken or am I doing something wrong? If the latter, what am I doing wrong?</p>
| [{'answer_id': 78702, 'author': 'dF.', 'author_id': 3002, 'author_profile': 'https://Stackoverflow.com/users/3002', 'pm_score': 0, 'selected': False, 'text': "<blockquote>\n <p>[...] In any style command <strong>the first row\n index</strong> may be set to one of the special strings [...]</p>\n</blockquote>\n\n<p>In your first example you're setting the <em>second</em> row index to a special string as well.</p>\n\n<p>Not sure why the other two don't work... Are you sure this is where the exception is coming from?</p>\n"}, {'answer_id': 94869, 'author': 'DLJessup', 'author_id': 14382, 'author_profile': 'https://Stackoverflow.com/users/14382', 'pm_score': 2, 'selected': False, 'text': '<p>Well, it looks as if I will be answering my own question.</p>\n\n<p>First, the documentation flat out lies where it reads "In any style command the first row index may be set to one of the special strings \'splitlast\' or \'splitfirst\' to indicate that the style should be used only for the last row of a split table, or the first row of a continuation." In the current release, the "splitlast" and "splitfirst" row indices break with the aforementioned TypeErrors on the TEXTCOLOR and BACKGROUND commnds.</p>\n\n<p>My suspicion, based on reading the source code, is that only the tablestyle line commands (GRID, BOX, LINEABOVE, and LINEBELOW) are currently compatible with the \'splitfirst\' and \'splitlast\' row indices. I suspect that all cell commands break with the aforementioned TypeErrors.</p>\n\n<p>However, I was able to do what I wanted by subclassing the Table class and overriding the onSplit method. Here is my code:</p>\n\n<pre><code>class XTable(Table):\n def onSplit(self, T, byRow=1):\n T.setStyle(TableStyle([\n (\'TEXTCOLOR\', (0, 1), (1, 1), colors.black)]))\n</code></pre>\n\n<p>What this does is apply the text color black to the first and second cell of the second row of each page. (The first row is a header, repeated by the repeatRows parameter of the Table.) More precisely, it is doing this to the first and second cell of each frame, but since I am using the SimpleDocTemplate, frames and pages are identical.</p>\n'}, {'answer_id': 2623783, 'author': 'Robin Macharg', 'author_id': 314737, 'author_profile': 'https://Stackoverflow.com/users/314737', 'pm_score': 1, 'selected': False, 'text': '<p>This seems to be a bug in the ReportLab Table class. Another fix for this in addition to <a href="https://stackoverflow.com/a/94869/669202">DLJessup\'s own answer</a> is to modify the ReportLab code that\'s causing the error, in <code>Table._drawBkgrnd()</code>, around line 1301. For \'splitlast\', change:</p>\n\n<pre><code>y0 = rowpositions[sr]\n</code></pre>\n\n<p>to: </p>\n\n<pre><code>if sr == \'splitlast\':\n y0 = rowpositions[-2] # last value is 0. Second last is the one we want.\nelse:\n y0 = rowpositions[sr]\n</code></pre>\n\n<p>This is easily done in your own code without hacking ReportLab by subclassing Table and overwriting this method. I\'ve not had need to use \'splitfirst\'; if I do I\'ll post the rest of the hack here.</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78450', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14382/'] |
78,453 | <p>What are the steps to estimating using function points?</p>
<p>Is there a quick-reference guide of some sort out there?</p>
| [{'answer_id': 78496, 'author': 'Jim McKeeth', 'author_id': 255, 'author_profile': 'https://Stackoverflow.com/users/255', 'pm_score': 4, 'selected': True, 'text': '<p>I took a conference session on Function Point Analysis a few years back. There is a lot too it. You can check out the <a href="http://www.softwaremetrics.com/freemanual.htm" rel="noreferrer">Free Function Point Training Manual</a> online, the <a href="http://www.softwaremetrics.com/fpafund.html" rel="noreferrer">Fundamentals of Function Points</a>, or I suspect you can get a book on it at a computer store.</p>\n\n<p>You might also check out the <a href="http://www.ifpug.org/" rel="noreferrer">International Function Point Users Group</a> and see if they have some resources or a local meeting for you.</p>\n'}, {'answer_id': 160198, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>You really need to get some training on it. Check with IFPUG. You will unknowingly pick up some destructive bad habits if self-taught. It also helps to have an experienced FP analyst review some of your early attempts.</p>\n\n<p>It\'s the kind of thing that appears overwhelmingly complex until you "get it" and then it\'s fairly quick to do. It improved my requirements analysis a lot too. I often spot contradictions and gaps when doing a count.</p>\n\n<p>It isn\'t limited to BDUF Waterfall projects either. I spent three years using FP and Planning Poker as cross-checks on one another when contracting agile methods projects.</p>\n\n<p>I was IFPUG-certified from 2002-2005 and am still using FP analysis. I\'ve seen it misused a lot, and I think that\'s why it has such a bad reputation.</p>\n'}, {'answer_id': 70471204, 'author': 'colinrh', 'author_id': 9420742, 'author_profile': 'https://Stackoverflow.com/users/9420742', 'pm_score': 0, 'selected': False, 'text': '<p>I recommend you take a look at COSMIC Function points. <a href="https://cosmic-sizing.org" rel="nofollow noreferrer">https://cosmic-sizing.org</a>. COSMIC Function points are also an ISO standard for measuring software size. They are an evolved improvement over IFPUG.</p>\n<p>You can quickly estimate size by counting the entries, exits, reads and writes.</p>\n<p>Compared with the IFPUG manual, learning COSMIC is much easier, the free book below is all you need, and you can read it in a day.</p>\n<p>Recommended reading: <a href="https://cosmic-sizing.org/publications/measurement-guide/" rel="nofollow noreferrer">https://cosmic-sizing.org/publications/measurement-guide/</a></p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78453', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1541/'] |
78,468 | <p>I am trying to understand left outer joins in LINQ to Entity. For example I have the following 3 tables:</p>
<p>Company, CompanyProduct, Product</p>
<p>The CompanyProduct is linked to its two parent tables, Company and Product.</p>
<p>I want to return all of the Company records and the associated CompanyProduct whether the CompanyProduct exists or not for a given product. In Transact SQL I would go from the Company table using left outer joins as follows: </p>
<pre><code>SELECT * FROM Company AS C
LEFT OUTER JOIN CompanyProduct AS CP ON C.CompanyID=CP.CompanyID
LEFT OUTER JOIN Product AS P ON CP.ProductID=P.ProductID
WHERE P.ProductID = 14 OR P.ProductID IS NULL
</code></pre>
<p>My database has 3 companies, and 2 CompanyProduct records assocaited with the ProductID of 14. So the results from the SQL query are the expected 3 rows, 2 of which are connected to a CompanyProduct and Product and 1 which simply has the Company table and nulls in the CompanyProduct and Product tables. </p>
<p>So how do you write the same kind of join in LINQ to Entity to acheive a similiar result? </p>
<p>I have tried a few different things but can't get the syntax correct.</p>
<p>Thanks.</p>
| [{'answer_id': 78714, 'author': 'dimarzionist', 'author_id': 10778, 'author_profile': 'https://Stackoverflow.com/users/10778', 'pm_score': 0, 'selected': False, 'text': '<p>Please try something like this:</p>\n\n<pre><code>from s in db.Employees\njoin e in db.Employees on s.ReportsTo equals e.EmployeeId\njoin er in EmployeeRoles on s.EmployeeId equals er.EmployeeId\njoin r in Roles on er.RoleId equals r.RoleId\nwhere e.EmployeeId == employeeId &&\ner.Status == (int)DocumentStatus.Draft\nselect s;\n</code></pre>\n\n<p>Cheers!</p>\n'}, {'answer_id': 175482, 'author': 'liggett78', 'author_id': 19762, 'author_profile': 'https://Stackoverflow.com/users/19762', 'pm_score': 0, 'selected': False, 'text': "<p>What about this one (you do have a many-to-many relationship between Company and Product in your Entity Designer, don't you?):</p>\n\n<pre><code>from s in db.Employees\nwhere s.Product == null || s.Product.ProductID == 14\nselect s;\n</code></pre>\n\n<p>Entity Framework should be able to figure out the type of join to use.</p>\n"}, {'answer_id': 175636, 'author': 'KyleLanser', 'author_id': 12923, 'author_profile': 'https://Stackoverflow.com/users/12923', 'pm_score': 4, 'selected': False, 'text': '<p>Solved it!</p>\n\n<p><strong>Final Output:</strong></p>\n\n<pre><code>theCompany.id: 1 \ntheProduct.id: 14 \ntheCompany.id: 2 \ntheProduct.id: 14 \ntheCompany.id: 3 \n</code></pre>\n\n<hr>\n\n<p><strong>Here is the Scenario</strong></p>\n\n<p><strong>1 - The Database</strong></p>\n\n<pre class="lang-sql prettyprint-override"><code>--Company Table\nCREATE TABLE [theCompany](\n [id] [int] IDENTITY(1,1) NOT NULL,\n [value] [nvarchar](50) NULL,\n CONSTRAINT [PK_theCompany] PRIMARY KEY CLUSTERED \n( [id] ASC ) WITH (\n PAD_INDEX = OFF, \n STATISTICS_NORECOMPUTE = OFF, \n IGNORE_DUP_KEY = OFF, \n ALLOW_ROW_LOCKS = ON, \n ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n) ON [PRIMARY];\nGO\n\n\n--Products Table\nCREATE TABLE [theProduct](\n [id] [int] IDENTITY(1,1) NOT NULL,\n [value] [nvarchar](50) NULL,\n CONSTRAINT [PK_theProduct] PRIMARY KEY CLUSTERED \n( [id] ASC\n) WITH ( \n PAD_INDEX = OFF, \n STATISTICS_NORECOMPUTE = OFF, \n IGNORE_DUP_KEY = OFF, \n ALLOW_ROW_LOCKS = ON, \n ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n) ON [PRIMARY];\nGO\n\n\n--CompanyProduct Table\nCREATE TABLE [dbo].[CompanyProduct](\n [fk_company] [int] NOT NULL,\n [fk_product] [int] NOT NULL\n) ON [PRIMARY]; \nGO\n\nALTER TABLE [CompanyProduct] WITH CHECK ADD CONSTRAINT\n [FK_CompanyProduct_theCompany] FOREIGN KEY([fk_company]) \n REFERENCES [theCompany] ([id]);\nGO\n\nALTER TABLE [dbo].[CompanyProduct] CHECK CONSTRAINT \n [FK_CompanyProduct_theCompany];\nGO\n\nALTER TABLE [CompanyProduct] WITH CHECK ADD CONSTRAINT \n [FK_CompanyProduct_theProduct] FOREIGN KEY([fk_product]) \n REFERENCES [dbo].[theProduct] ([id]);\nGO\n\nALTER TABLE [dbo].[CompanyProduct] CHECK CONSTRAINT \n [FK_CompanyProduct_theProduct];\n</code></pre>\n\n<p><strong>2 - The Data</strong></p>\n\n<pre><code>SELECT [id] ,[value] FROM theCompany\nid value\n----------- --------------------------------------------------\n1 company1\n2 company2\n3 company3\n\nSELECT [id] ,[value] FROM theProduct\nid value\n----------- --------------------------------------------------\n14 Product 1\n\n\nSELECT [fk_company],[fk_product] FROM CompanyProduct;\nfk_company fk_product\n----------- -----------\n1 14\n2 14\n</code></pre>\n\n<p><strong>3 - The Entity in VS.NET 2008</strong> </p>\n\n<p><a href="http://i478.photobucket.com/albums/rr148/KyleLanser/companyproduct.png" rel="nofollow noreferrer">alt text http://i478.photobucket.com/albums/rr148/KyleLanser/companyproduct.png</a><br>\nThe Entity Container Name is \'testEntities\' (as seen in model Properties window) </p>\n\n<p><strong>4 - The Code (FINALLY!)</strong></p>\n\n<pre class="lang-c# prettyprint-override"><code>testEntities entity = new testEntities();\n\nvar theResultSet = from c in entity.theCompany\nselect new { company_id = c.id, product_id = c.theProduct.Select(e=>e) };\n\nforeach(var oneCompany in theResultSet)\n{\n Debug.WriteLine("theCompany.id: " + oneCompany.company_id);\n foreach(var allProducts in oneCompany.product_id)\n {\n Debug.WriteLine("theProduct.id: " + allProducts.id);\n }\n}\n</code></pre>\n\n<p><strong>5 - The Final Output</strong></p>\n\n<pre><code>theCompany.id: 1 \ntheProduct.id: 14 \ntheCompany.id: 2 \ntheProduct.id: 14 \ntheCompany.id: 3 \n</code></pre>\n'}, {'answer_id': 1511650, 'author': 'StriplingWarrior', 'author_id': 120955, 'author_profile': 'https://Stackoverflow.com/users/120955', 'pm_score': 3, 'selected': False, 'text': '<p>You\'ll want to use the Entity Framework to set up a many-to-many mapping from Company to Product. This will use the CompanyProduct table, but will make it unnecessary to have a CompanyProduct entity set in your entity model. Once you\'ve done that, the query will be very simple, and it will depend on personal preference and how you want to represent the data. For example, if you just want all the companies who have a given product, you could say:</p>\n\n<pre><code>var query = from p in Database.ProductSet\n where p.ProductId == 14\n from c in p.Companies\n select c;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>var query = Database.CompanySet\n .Where(c => c.Products.Any(p => p.ProductId == 14));\n</code></pre>\n\n<p>Your SQL query returns the product information along with the companies. If that\'s what you\'re going for, you might try:</p>\n\n<pre><code>var query = from p in Database.ProductSet\n where p.ProductId == 14\n select new\n {\n Product = p,\n Companies = p.Companies\n };\n</code></pre>\n\n<p>Please use the "Add Comment" button if you would like to provide more information, rather than creating another answer.</p>\n'}, {'answer_id': 3529660, 'author': 'Martin', 'author_id': 426177, 'author_profile': 'https://Stackoverflow.com/users/426177', 'pm_score': 1, 'selected': False, 'text': "<p>The normal group join represents a left outer join. Try this:</p>\n\n<pre><code>var list = from a in _datasource.table1\n join b in _datasource.table2\n on a.id equals b.table1.id\n into ab\n where ab.Count()==0\n select new { table1 = a, \n table2Count = ab.Count() };\n</code></pre>\n\n<p>That example gives you all records from <code>table1</code> which don't have a reference to <code>table2</code>.\nIf you omit the <code>where</code> sentence, you get all records of <code>table1</code>.</p>\n"}, {'answer_id': 4054699, 'author': 'Mitch', 'author_id': 491618, 'author_profile': 'https://Stackoverflow.com/users/491618', 'pm_score': 2, 'selected': False, 'text': '<p>LEFT OUTER JOINs are done by using the GroupJoin in Entity Framework:</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/bb896266.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/bb896266.aspx</a></p>\n'}, {'answer_id': 5351728, 'author': 'Deepak ', 'author_id': 665993, 'author_profile': 'https://Stackoverflow.com/users/665993', 'pm_score': 3, 'selected': False, 'text': '<p>IT should be something like this....</p>\n\n<pre><code>var query = from t1 in db.table1\n join t2 in db.table2\n on t1.Field1 equals t2.field1 into T1andT2\n from t2Join in T1andT2.DefaultIfEmpty()\n\n\n join t3 in db.table3\n on t2Join.Field2 equals t3.Field3 into T2andT3\n from t3Join in T2andT3.DefaultIfEmpty()\n where t1.someField = "Some value" \n select \n {\n t2Join.FieldXXX\n t3Join.FieldYYY\n\n\n };\n</code></pre>\n\n<p>This is how I did....</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78468', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] |
78,471 | <p>How can I find out the date a MS SQL Server 2000 object was last modified?</p>
<p>I need to get a list of all the views, procs, functions etc that were modified since Aug 15th. In sysObjects I can see the date objects were created but I need to know when they were last altered.</p>
<p>NB: this is an SQL 2000 database.</p>
| [{'answer_id': 78628, 'author': 'Portman', 'author_id': 1690, 'author_profile': 'https://Stackoverflow.com/users/1690', 'pm_score': 4, 'selected': True, 'text': '<p>Note that SQL Server actually does <strong>not</strong> record the last modification date. It does not exist in any system tables. </p>\n\n<p>The Schema Changes History report is actually constructed from the <a href="http://msdn.microsoft.com/en-us/library/ms191006.aspx" rel="noreferrer">Default Trace</a>. Since many admins (and web hosts) turn that off, it may not work for you.\nBuck Woody had a good explanation of how this report works <a href="http://blogs.msdn.com/buckwoody/archive/2007/10/12/sql-server-management-studio-standard-reports-schema-changes-history.aspx" rel="noreferrer">here</a>. The data is also temporary.</p>\n\n<p>For this reason, you should never RELY on the Schema Changes History report. Alternatives:</p>\n\n<ul>\n<li>Use <a href="http://msdn.microsoft.com/en-us/library/ms186406.aspx" rel="noreferrer">DDL Triggers</a> to log all schema modification to a table of your choosing.</li>\n<li>Enforce a protocol where views and procs are never altered, they are only dropped and recreated. This means the created date will also be the last updated date (this does not work with tables obviously). </li>\n<li>Vigilantly version your SQL objects and schema in source control. </li>\n</ul>\n\n<p>--</p>\n\n<p>Edit: saw that this is SQL 2000. That rules out Default Trace and DDL Triggers. You\'re left with one of the more tedious options I listed above.</p>\n'}, {'answer_id': 2342967, 'author': 'Allov', 'author_id': 130480, 'author_profile': 'https://Stackoverflow.com/users/130480', 'pm_score': 4, 'selected': False, 'text': '<p>I know this is a bit old, but it is possible to view the last altered date of <strong>stored procs and functions</strong> with this query:</p>\n\n<pre><code>USE [Your_DB] \nSELECT * FROM INFORMATION_SCHEMA.ROUTINES\n</code></pre>\n\n<p>Just thought it would be nice to mention this since I searched for this very solution and this thread was misleading.</p>\n'}, {'answer_id': 22472528, 'author': 'Sudhir v. Usnale', 'author_id': 3431963, 'author_profile': 'https://Stackoverflow.com/users/3431963', 'pm_score': 3, 'selected': False, 'text': "<p>I have got confirmed Answer for above any procedure History for modified date with below query </p>\n\n<p>Step -1 Execute the procedure on DB</p>\n\n<pre><code>SELECT name, create_date, modify_date \nFROM sys.objects\nWHERE type = 'p' \n</code></pre>\n\n<p>Step -2 \nThen copy the text to Excel with headers</p>\n\n<p>select route coloumn and then paste the exact procedure name into ^F window and press enter \nyou will get exact modified date.</p>\n\n<p>Regards,\nSudhir \nPune</p>\n"}, {'answer_id': 30715530, 'author': 'Saurabh Sinha', 'author_id': 3252237, 'author_profile': 'https://Stackoverflow.com/users/3252237', 'pm_score': 1, 'selected': False, 'text': '<p>This is not always correct because modify_date is Date the object was last modified by using an ALTER statement. <strong>If the object is a table or a view, modify_date also changes when a clustered index on the table or view is created or altered.</strong></p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78471', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10422/'] |
78,474 | <p>Using only ANSI C, what is the best way to, with fair certainty, determine if a C style string is either a integer or a real number (i.e float/double)?</p>
| [{'answer_id': 78485, 'author': 'nutbar', 'author_id': 14425, 'author_profile': 'https://Stackoverflow.com/users/14425', 'pm_score': 2, 'selected': False, 'text': "<p>I suppose you could step through the string and check if there are any <code>.</code> characters in it. That's just the first thing that popped into my head though, so I'm sure there are other (better) ways to be more certain.</p>\n"}, {'answer_id': 78487, 'author': 'itsmatt', 'author_id': 7862, 'author_profile': 'https://Stackoverflow.com/users/7862', 'pm_score': 2, 'selected': False, 'text': "<p>atoi and atof will convert or return a 0 if it can't.</p>\n"}, {'answer_id': 78540, 'author': 'Vincent Robert', 'author_id': 268, 'author_profile': 'https://Stackoverflow.com/users/268', 'pm_score': 1, 'selected': False, 'text': "<p>It really depends on why you are asking in the first place. </p>\n\n<p>If you just want to parse a number and don't know if it is a float or an integer, then just parse a float, it will correctly parse an integer as well.</p>\n\n<p>If you actually want to know the type, maybe for triage, then you should really consider testing the types in the order that you consider the most relevant. Like try to parse an integer and if you can't, then try to parse a float. (The other way around will just produce a little more floats...)</p>\n"}, {'answer_id': 78565, 'author': 'Patrick_O', 'author_id': 11084, 'author_profile': 'https://Stackoverflow.com/users/11084', 'pm_score': 6, 'selected': True, 'text': '<p>Don\'t use atoi and atof as these functions return 0 on failure. Last time I checked 0 is a valid integer and float, therefore no use for determining type.</p>\n\n<p>use the strto{l,ul,ull,ll,d} functions, as these set errno on failure, and also report where the converted data ended.</p>\n\n<p>strtoul: <a href="http://www.opengroup.org/onlinepubs/007908799/xsh/strtoul.html" rel="noreferrer">http://www.opengroup.org/onlinepubs/007908799/xsh/strtoul.html</a></p>\n\n<p>this example assumes that the string contains a single value to be converted.</p>\n\n<pre><code>#include <errno.h>\n\nchar* to_convert = "some string";\nchar* p = to_convert;\nerrno = 0;\nunsigned long val = strtoul(to_convert, &p, 10);\nif (errno != 0)\n // conversion failed (EINVAL, ERANGE)\nif (to_convert == p)\n // conversion failed (no characters consumed)\nif (*p != 0)\n // conversion failed (trailing data)\n</code></pre>\n\n<p>Thanks to Jonathan Leffler for pointing out that I forgot to set errno to 0 first.</p>\n'}, {'answer_id': 78569, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>atoi and atof will convert the number even if there are trailing non numerical characters. However, if you use strtol and strtod it will not only skip leading white space and an optional sign, but leave you with a pointer to the first character not in the number. Then you can check that the rest is whitespace.</p>\n'}, {'answer_id': 78580, 'author': 'Patrick', 'author_id': 429, 'author_profile': 'https://Stackoverflow.com/users/429', 'pm_score': 3, 'selected': False, 'text': '<p>Using <a href="http://www.cplusplus.com/reference/clibrary/cstdio/sscanf.html" rel="noreferrer">sscanf</a>, you can be certain if the string is a float or int or whatever without having to special case 0, as is the case with atoi and atof solution.</p>\n\n<p>Here\'s some example code:</p>\n\n<pre><code>int i;\nfloat f;\nif(sscanf(str, "%d", &i) != 0) //It\'s an int.\n ...\nif(sscanf(str "%f", &f) != 0) //It\'s a float.\n ...\n</code></pre>\n'}, {'answer_id': 78627, 'author': 'Steve Jessop', 'author_id': 13005, 'author_profile': 'https://Stackoverflow.com/users/13005', 'pm_score': 2, 'selected': False, 'text': "<p>Use strtol/strtoll (not atoi) to check integers.\nUse strtof/strtod (not atof) to check doubles. </p>\n\n<p>atoi and atof convert the initial part of the string, but don't tell you whether or not they used all of the string. strtol/strtod tell you whether there was extra junk after the characters converted.</p>\n\n<p>So in both cases, remember to pass in a non-null TAIL parameter, and check that it points to the end of the string (that is, **TAIL == 0). Also check the return value for underflow and overflow (see the man pages or ANSI standard for details).</p>\n\n<p>Note also that strod/strtol skip initial whitespace, so if you want to treat strings with initial whitespace as ill-formatted, you also need to check the first character.</p>\n"}, {'answer_id': 80730, 'author': 'Jonathan Leffler', 'author_id': 15168, 'author_profile': 'https://Stackoverflow.com/users/15168', 'pm_score': 2, 'selected': False, 'text': "<p>I agree with Patrick_O that the strto{l,ul,ull,ll,d} functions are the best way to go. There are a couple of points to watch though.</p>\n\n<ol>\n<li>Set errno to zero before calling the functions; no function does that for you.</li>\n<li>The Open Group page linked to (which I went to before noticing that Patrick had linked to it too) points out that errno may not be set. It is set to ERANGE if the value is out of range; it <em>may</em> be set (but equally, <em>may</em> <em>not</em> be set) to EINVAL if the argument is invalid.</li>\n</ol>\n\n<p>Depending on the job at hand, I'll sometimes arrange to skip over trailing white space from the end of conversion pointer returned, and then complain (reject) if the last character is not the terminating null '\\0'. Or I can be sloppy and let garbage appear at the end, or I can accept optional multipliers like 'K', 'M', 'G', 'T' for kilobytes, megabytes, gigabytes, terabytes, ... or any other requirement based on the context.</p>\n"}, {'answer_id': 21791935, 'author': 'Katie', 'author_id': 3312224, 'author_profile': 'https://Stackoverflow.com/users/3312224', 'pm_score': 0, 'selected': False, 'text': '<p>Well, if you don\'t feel like using a new function like strtoul, you could just add another strcmp statement to see if the string is 0.</p>\n\n<p>i.e.</p>\n\n<pre><code>if(atof(token) != NULL || strcmp(token, "0") == 0)\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78474', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9418/'] |
78,475 | <p>I'd like to be able to open a TDataSet asynchronously in its own thread so that the main VCL thread can continue until that's done, and then have the main VCL thread read from that TDataSet afterwards. I've done some experimenting and have gotten into some very weird situations, so I'm wondering if anyone has done this before.</p>
<p>I've seen some sample apps where a TDataSet is created in a separate thread, it's opened and then data is read from it, but that's all done in the separate thread. I'm wondering if it's safe to read from the TDataSet from the main VCL thread after the other thread opens the data source.</p>
<p>I'm doing Win32 programming in Delphi 7, using TmySQLQuery from <a href="http://www.microolap.com/products/connectivity/mysqldac/" rel="noreferrer">DAC for MySQL</a> as my TDataSet descendant.</p>
| [{'answer_id': 78559, 'author': 'Cyphus', 'author_id': 1150, 'author_profile': 'https://Stackoverflow.com/users/1150', 'pm_score': 2, 'selected': False, 'text': '<p>I have seen it done with other implementations of TDataSet, namely in the <a href="http://www.astatech.com" rel="nofollow noreferrer">Asta</a> components. These would contact the server, return immediately, and then fire an event once the data had been loaded.</p>\n\n<p>However, I believe it depends very much on the component. For example, those same Asta components could not be opened in a synchronous manner from anything other than the main VCL thread.</p>\n\n<p>So in short, I don\'t believe it is a limitation of TDataSet per se, but rather something that is implementation specific, and I don\'t have access to the components you\'ve mentioned.</p>\n'}, {'answer_id': 78899, 'author': 'Jim McKeeth', 'author_id': 255, 'author_profile': 'https://Stackoverflow.com/users/255', 'pm_score': 2, 'selected': False, 'text': '<p>One thing to keep in mind about using the same <strong>TDataSet</strong> between multiple threads is you can only read the current record at any given time. So if you are reading the record in one thread and then the other thread calls <strong>Next</strong> then you are in trouble.</p>\n'}, {'answer_id': 79499, 'author': 'skamradt', 'author_id': 9217, 'author_profile': 'https://Stackoverflow.com/users/9217', 'pm_score': 2, 'selected': False, 'text': '<p>Also remember the thread will most likely need its own database connection. I believe what is needed here is a multi-threaded "holding" object to load the data from the thread into (write only) which is then read only from the main VCL thread. Before reading use some sort of syncronization method to insure that your not reading the same moment your writing, or writing the same moment your reading, or load everything into a memory file and write a sync method to tell the main app where in the file to stop reading.</p>\n\n<p>I have taken the last approach a few times, depdending on the number of expected records (and the size of the dataset) I have even taken this to a physical disk file on the local system. It works quite well.</p>\n'}, {'answer_id': 81129, 'author': 'Francesca', 'author_id': 9842, 'author_profile': 'https://Stackoverflow.com/users/9842', 'pm_score': 4, 'selected': True, 'text': '<p>Provided you only want to use the dataset in its own thread, you can just use synchronize to communicate with the main thread for any VCL/UI update, like with any other component.<br>\nOr, better, you can implement communication between the mainthread and worker threads with your own messaging system. </p>\n\n<p>check Hallvard\'s solution for threading here:<br>\n<a href="http://hallvards.blogspot.com/2008/03/tdm6-knitting-your-own-threads.html" rel="noreferrer">http://hallvards.blogspot.com/2008/03/tdm6-knitting-your-own-threads.html</a> </p>\n\n<p>or this other one:<br>\n<a href="http://dn.codegear.com/article/22411" rel="noreferrer">http://dn.codegear.com/article/22411</a> </p>\n\n<p>for some explanation on synchronize and its inefficiencies:<br>\n<a href="http://www.eonclash.com/Tutorials/Multithreading/MartinHarvey1.1/Ch3.html" rel="noreferrer">http://www.eonclash.com/Tutorials/Multithreading/MartinHarvey1.1/Ch3.html</a></p>\n'}, {'answer_id': 82002, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>I've done multithreaded data access, and it's not straightforward:</p>\n\n<p>1) You need to create a session per thread. </p>\n\n<p>2) Everything done to that TDataSet instance must be done in context of the thread where it was created. That's not easy if you wanted to place e.g. a db grid on top of it.</p>\n\n<p>3) If you want to let e.g. main thread play with your data, the straight-forward solution is to move it into a separate container of some kind,e.g. a Memory dataset.</p>\n\n<p>4) You need some kind of signaling mechanism to notify main thread once your data retrieval is complete.</p>\n\n<p>...and exception handling isn't straightforward, either...</p>\n\n<p>But: Once you've succeeded, the application will be really elegant !</p>\n"}, {'answer_id': 106960, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Most TDatasets are not thread safe. One that I know is thread safe is <a href="http://www.components4programmers.com/products/kbmmemtable/index.htm" rel="nofollow noreferrer" title="kbmMemtable">kbmMemtable</a>. It also has the ability to clone a dataset so that the problem of moving the record pointer (as explained by Jim McKeeth) does occur. They\'re one of the best datasets you can get (bought or free).</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78475', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/62/'] |
78,477 | <p>How can I get a ASP.NET (inc MVC) application talking to a Flex UI over AMF. I am wanting to push approx 100+ records around at a time and AMF would appear to be the way forward, but there doesn't appear to be anything obvious.</p>
| [{'answer_id': 78821, 'author': 'Cameron A. Ellis', 'author_id': 1748529, 'author_profile': 'https://Stackoverflow.com/users/1748529', 'pm_score': 4, 'selected': True, 'text': '<p>If you\'re pressed for time, you can just use the RemoteObject to hit a compiled DLL (like WebORB - its free for .NET, but you need a VS copy above Express to compile your classes that you want to expose to Flex)</p>\n\n<p>and Retrieve the object that way...</p>\n\n<p>Obviously your objects should have a DAL in place or be generated so you can communicate with your database.</p>\n\n<p>But i suggest using Cairngorm for any data intensive Flex application. It isn\'t simple and development won\'t feel as fast, but once you understand it, things go alot smoother and it just feels right. I could go into the details, but there are people that are much smarter than I am that have already explained it, in depth. Someone like yourself should be able to grasp the concepts pretty quickly.</p>\n\n<p>here are the links to learning WebORB and Cairngorm:</p>\n\n<ul>\n<li>weborb : <a href="http://www.themidnightcoders.com/weborb/" rel="noreferrer">http://www.themidnightcoders.com/weborb/</a></li>\n<li>cairngorm : <a href="http://opensource.adobe.com/wiki/display/cairngorm/Cairngorm" rel="noreferrer">http://opensource.adobe.com/wiki/display/cairngorm/Cairngorm</a></li>\n<li>learning Cairngorm : <a href="http://www.adobe.com/devnet/flex/articles/cairngorm_pt1.html" rel="noreferrer">http://www.adobe.com/devnet/flex/articles/cairngorm_pt1.html</a></li>\n</ul>\n'}, {'answer_id': 99616, 'author': 'user10440', 'author_id': 10440, 'author_profile': 'https://Stackoverflow.com/users/10440', 'pm_score': 0, 'selected': False, 'text': '<p>One minor correction to the answer above: you can actually use the Express edition to compile your assembly. With WebORB you can simply deploy your DLLs into the /bin folder of the virtual directory and it will take care of enabling your classes as Flex Remoting services. You do not need to implement any special interfaces or use any special attributes. Just create a class that returns the data you want to deliver to the client, deploy that class into weborb and use the RemoteObject API on the client side. Here\'s a link to the getting started article:</p>\n\n<p><a href="http://www.themidnightcoders.com/articles/flextodotnet.htm" rel="nofollow noreferrer">http://www.themidnightcoders.com/articles/flextodotnet.htm</a></p>\n'}, {'answer_id': 106881, 'author': 'marstonstudio', 'author_id': 19447, 'author_profile': 'https://Stackoverflow.com/users/19447', 'pm_score': 2, 'selected': False, 'text': '<p>An alternative to WebORB for .Net AMF remoting is <a href="http://www.fluorinefx.com/" rel="nofollow noreferrer">FlourineFx</a>. I haven\'t used it, but it looks interesting. I have used WebORB which is quite powerful. It has some great code generation tools which speed up the process of building a database driven application. </p>\n'}, {'answer_id': 215073, 'author': 'Lieven Cardoen', 'author_id': 26521, 'author_profile': 'https://Stackoverflow.com/users/26521', 'pm_score': 0, 'selected': False, 'text': '<p>I would definetely check WebORB and the MSMQ support (FluorineFX has the same functionality. Both are free). You could let WebORB listen to a certain queue in MSMQ. On the flex side you would need to create a Consumer and suscribe it to that queue. WebORB will then push every message in the queue to all the Consumers created in the swf. Other applications like your ASP.NET application could put messages in that queue (serialized objects or xml for instance) and will be delivered to your Flex GUI.</p>\n\n<p>I wrote some posts on the subect on <a href="http://blog.johlero.eu" rel="nofollow noreferrer">http://blog.johlero.eu</a>.</p>\n\n<p>Another very good example is at <a href="http://www.themidnightcoders.com/articles/msmqtoflexdatapush.shtm" rel="nofollow noreferrer">http://www.themidnightcoders.com/articles/msmqtoflexdatapush.shtm</a> where they use a Windows Form Application to send messages to a flex Gui.</p>\n\n<p>Lieven Cardoen aka Johlero</p>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78477', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4787/'] |
78,493 | <p>I once read that one way to obtain a unique filename in a shell for temp files was to use a double dollar sign (<code>$$</code>). This does produce a number that varies from time to time... but if you call it repeatedly, it returns the same number. (The solution is to just use the time.)</p>
<p>I am curious to know what <code>$$</code> actually is, and why it would be suggested as a way to generate unique filenames.</p>
| [{'answer_id': 78501, 'author': 'Flint', 'author_id': 11877, 'author_profile': 'https://Stackoverflow.com/users/11877', 'pm_score': 5, 'selected': False, 'text': '<p>$$ is the id of the current process.</p>\n'}, {'answer_id': 78502, 'author': 'leif', 'author_id': 14257, 'author_profile': 'https://Stackoverflow.com/users/14257', 'pm_score': 2, 'selected': False, 'text': "<p>$$ is the pid of the current shell process. It isn't a good way to generate unique filenames.</p>\n"}, {'answer_id': 78504, 'author': 'Joe Skora', 'author_id': 14057, 'author_profile': 'https://Stackoverflow.com/users/14057', 'pm_score': 8, 'selected': True, 'text': '<p>In Bash <code>$$</code> is the process ID, as noted in the comments it is not safe to use as a temp filename for a variety of reasons.</p>\n\n<p>For temporary file names, use the <code>mktemp</code> command.</p>\n'}, {'answer_id': 78508, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>It's the process ID of the bash process. No concurrent processes will ever have the same PID.</p>\n"}, {'answer_id': 78528, 'author': 'Adam Wright', 'author_id': 1200, 'author_profile': 'https://Stackoverflow.com/users/1200', 'pm_score': 3, 'selected': False, 'text': '<p>Every process in a UNIX like operating system has a (temporarily) unique identifier, the PID. No two processes running at the same time can have the same PID, and $$ refers to the PID of the bash instance running the script.</p>\n\n<p>This is very much <em>not</em> a unique idenifier in the sense that it will never be reused (indeed, PIDs are reused constantly). What it does give you is a number such that, if another person runs your script, they will get a different identifier whilst yours is still running. Once yours dies, the PID may be recycled and someone else might run your script, get the same PID, and so get the same filename.</p>\n\n<p>As such, it is only really sane to say "$$ gives a filename such that if someone else runs the same script whist my instance is still running, they will get a different name".</p>\n'}, {'answer_id': 78529, 'author': 'Shannon Nelson', 'author_id': 14450, 'author_profile': 'https://Stackoverflow.com/users/14450', 'pm_score': 2, 'selected': False, 'text': '<p>The $$ is the process id of the shell in which your script is running. For more details, see the man page for sh or bash. The man pages can be found be either using a command line "man sh", or by searching the web for "shell manpage"</p>\n'}, {'answer_id': 78531, 'author': 'JBB', 'author_id': 12332, 'author_profile': 'https://Stackoverflow.com/users/12332', 'pm_score': 3, 'selected': False, 'text': '<p>$$ is your PID. It doesn\'t really generate a unique filename, unless you are careful and no one else does it exactly the same way. </p>\n\n<p>Typically you\'d create something like /tmp/myprogramname$$</p>\n\n<p>There\'re so many ways to break this, and if you\'re writing to locations other folks can write to it\'s not too difficult on many OSes to predict what PID you\'re going to have and screw around -- imagine you\'re running as root and I create /tmp/yourprogname13395 as a symlink pointing to /etc/passwd -- and you write into it.</p>\n\n<p>This is a bad thing to be doing in a shell script. If you\'re going to use a temporary file for something, you ought to be using a better language which will at least let you add the "exclusive" flag for opening (creating) the file. Then you can be sure you\'re not clobbering something else.</p>\n'}, {'answer_id': 78546, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>$$ is the pid (process id) of the shell interpreter running your script. It\'s different for each process running on a system at the moment, but over time the pid wraps around, and after you exit there will be another process with same pid eventually.As long as you\'re running, the pid is unique to you.</p>\n\n<p>From the definition above it should be obvious that no matter how many times you use $$ in a script, it will return the same number. </p>\n\n<p>You can use, e.g. /tmp/myscript.scratch.$$ as your temp file for things that need not be extremely reliable or secure. It\'s a good practice to delete such temp files at the end of your script, using, for example, trap command:</p>\n\n<pre><code>trap "echo \'Cleanup in progress\'; rm -r $TMP_DIR" EXIT\n</code></pre>\n'}, {'answer_id': 78581, 'author': 'emk', 'author_id': 12089, 'author_profile': 'https://Stackoverflow.com/users/12089', 'pm_score': 7, 'selected': False, 'text': '<p><code>$$</code> is the process ID (PID) in bash. Using <code>$$</code> is a bad idea, because it will usually create a race condition, and allow your shell-script to be subverted by an attacker. See, for example, all <a href="http://www.google.com/search?q=tmp+race" rel="noreferrer">these people</a> who created insecure temporary files and had to issue security advisories.</p>\n\n<p>Instead, use <code>mktemp</code>. The <a href="http://linux.die.net/man/1/mktemp" rel="noreferrer">Linux man page for mktemp</a> is excellent. Here\'s some example code from it:</p>\n\n<pre><code>tempfoo=`basename $0`\nTMPFILE=`mktemp -t ${tempfoo}` || exit 1\necho "program output" >> $TMPFILE\n</code></pre>\n'}, {'answer_id': 78667, 'author': 'Kevin Little', 'author_id': 14028, 'author_profile': 'https://Stackoverflow.com/users/14028', 'pm_score': 2, 'selected': False, 'text': '<p>Let me second emk\'s answer -- don\'t use $$ by itself as a "unique" anything. For files, use mktemp. For other IDs within the same bash script, use "$$$(date +%s%N)" for a <em>reasonably</em> good chance of uniqueness.</p>\n\n<pre><code> -k\n</code></pre>\n'}, {'answer_id': 48744969, 'author': 'Obivan', 'author_id': 5444646, 'author_profile': 'https://Stackoverflow.com/users/5444646', 'pm_score': 0, 'selected': False, 'text': '<blockquote>\n <p>Also, You can grab login username via this command. Eg.</p>\n</blockquote>\n\n<pre><code>echo $(</proc/$$/login id). After that, you need to use getent command.\n</code></pre>\n'}, {'answer_id': 64850457, 'author': 'Édouard Lopez', 'author_id': 802365, 'author_profile': 'https://Stackoverflow.com/users/802365', 'pm_score': 1, 'selected': False, 'text': '<p>In <strong>Fish</strong> shell (<code>3.1.2</code>):</p>\n<blockquote>\n<p>The <code>$</code> symbol can also be used multiple times, as a kind of "dereference" operator (the * in C or C++)</p>\n</blockquote>\n<pre><code>set bar bazz\nset foo bar\necho $foo # bar\necho $$foo # same as echo $bar → bazz\n</code></pre>\n'}] | 2008/09/16 | ['https://Stackoverflow.com/questions/78493', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14345/'] |
78,497 | <p>Does anyone know of any resources that talk about best practices or design patterns for shell scripts (sh, bash etc.)?</p>
| [{'answer_id': 78509, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': "<p>Easy:\nuse python instead of shell scripts.\nYou get a near 100 fold increase in readablility, without having to complicate anything you don't need, and preserving the ability to evolve parts of your script into functions, objects, persistent objects (zodb), distributed objects (pyro) nearly without any extra code.</p>\n"}, {'answer_id': 78526, 'author': 'user10392', 'author_id': 10392, 'author_profile': 'https://Stackoverflow.com/users/10392', 'pm_score': 3, 'selected': False, 'text': "<p>use set -e so you don't plow forward after errors. Try making it sh compatible without relying on bash if you want it to run on not-linux.</p>\n"}, {'answer_id': 79400, 'author': 'jtimberman', 'author_id': 7672, 'author_profile': 'https://Stackoverflow.com/users/7672', 'pm_score': 5, 'selected': False, 'text': '<p>Take a look at the <a href="http://www.tldp.org/LDP/abs/html/index.html" rel="noreferrer">Advanced Bash-Scripting Guide</a> for a lot of wisdom on shell scripting - not just Bash, either. </p>\n\n<p>Don\'t listen to people telling you to look at other, arguably more complex languages. If shell scripting meets your needs, use that. You want functionality, not fanciness. New languages provide valuable new skills for your resume, but that doesn\'t help if you have work that needs to be done and you already know shell.</p>\n\n<p>As stated, there aren\'t a lot of "best practices" or "design patterns" for shell scripting. Different uses have different guidelines and bias - like any other programming language. </p>\n'}, {'answer_id': 80140, 'author': 'Fhoxh', 'author_id': 14785, 'author_profile': 'https://Stackoverflow.com/users/14785', 'pm_score': 4, 'selected': False, 'text': '<p>There was a great session at OSCON this year (2008) on just this topic: <a href="http://assets.en.oreilly.com/1/event/12/Shell%20Scripting%20Craftsmanship%20Presentation%201.pdf" rel="noreferrer">http://assets.en.oreilly.com/1/event/12/Shell%20Scripting%20Craftsmanship%20Presentation%201.pdf</a></p>\n'}, {'answer_id': 86712, 'author': 'Paweł Hajdan', 'author_id': 9403, 'author_profile': 'https://Stackoverflow.com/users/9403', 'pm_score': 4, 'selected': False, 'text': "<p><strong>Know when to use it.</strong> For quick and dirty gluing commands together it's okay. If you need to make any more than few non-trivial decisions, loops, anything, go for Python, Perl, and <strong>modularize</strong>.</p>\n\n<p>The biggest problem with shell is often that end result just looks like a big ball of mud, 4000 lines of bash and growing... and you can't get rid of it because now your whole project depends on it. Of course, <strong>it started at 40 lines</strong> of beautiful bash.</p>\n"}, {'answer_id': 87339, 'author': 'Willem', 'author_id': 15447, 'author_profile': 'https://Stackoverflow.com/users/15447', 'pm_score': 3, 'selected': False, 'text': '<p>To find some "best practices", look how Linux distro\'s (e.g. Debian) write their init-scripts (usually found in /etc/init.d)</p>\n\n<p>Most of them are without "bash-isms" and have a good separation of configuration settings, library-files and source formatting.</p>\n\n<p>My personal style is to write a master-shellscript which defines some default variables, and then tries to load ("source") a configuration file which may contain new values.</p>\n\n<p>I try to avoid functions since they tend to make the script more complicated. (Perl was created for that purpose.)</p>\n\n<p>To make sure the script is portable, test not only with #!/bin/sh, but also use #!/bin/ash, #!/bin/dash, etc. You\'ll spot the Bash specific code soon enough.</p>\n'}, {'answer_id': 88790, 'author': 'pixelbeat', 'author_id': 4421, 'author_profile': 'https://Stackoverflow.com/users/4421', 'pm_score': 4, 'selected': False, 'text': '<p>shell script is a language designed to manipulate files and processes.\nWhile it\'s great for that, it\'s not a general purpose language,\nso always try to glue logic from existing utilities rather than\nrecreating new logic in shell script.</p>\n\n<p>Other than that general principle I\'ve collected some <a href="http://www.pixelbeat.org/programming/shell_script_mistakes.html" rel="noreferrer" title="common shell script mistakes">common shell script mistakes</a>.</p>\n'}, {'answer_id': 739034, 'author': 'Stefano Borini', 'author_id': 78374, 'author_profile': 'https://Stackoverflow.com/users/78374', 'pm_score': 9, 'selected': True, 'text': '<p>I wrote quite complex shell scripts and my first suggestion is "don\'t". The reason is that is fairly easy to make a small mistake that hinders your script, or even make it dangerous.</p>\n\n<p>That said, I don\'t have other resources to pass you but my personal experience. \nHere is what I normally do, which is overkill, but tends to be solid, although <em>very</em> verbose.</p>\n\n<p><strong>Invocation</strong></p>\n\n<p>make your script accept long and short options. be careful because there are two commands to parse options, getopt and getopts. Use getopt as you face less trouble.</p>\n\n<pre><code>CommandLineOptions__config_file=""\nCommandLineOptions__debug_level=""\n\ngetopt_results=`getopt -s bash -o c:d:: --long config_file:,debug_level:: -- "$@"`\n\nif test $? != 0\nthen\n echo "unrecognized option"\n exit 1\nfi\n\neval set -- "$getopt_results"\n\nwhile true\ndo\n case "$1" in\n --config_file)\n CommandLineOptions__config_file="$2";\n shift 2;\n ;;\n --debug_level)\n CommandLineOptions__debug_level="$2";\n shift 2;\n ;;\n --)\n shift\n break\n ;;\n *)\n echo "$0: unparseable option $1"\n EXCEPTION=$Main__ParameterException\n EXCEPTION_MSG="unparseable option $1"\n exit 1\n ;;\n esac\ndone\n\nif test "x$CommandLineOptions__config_file" == "x"\nthen\n echo "$0: missing config_file parameter"\n EXCEPTION=$Main__ParameterException\n EXCEPTION_MSG="missing config_file parameter"\n exit 1\nfi\n</code></pre>\n\n<p>Another important point is that a program should always return zero if completes successfully, non-zero if something went wrong.</p>\n\n<p><strong>Function calls</strong></p>\n\n<p>You can call functions in bash, just remember to define them before the call. Functions are like scripts, they can only return numeric values. This means that you have to invent a different strategy to return string values. My strategy is to use a variable called RESULT to store the result, and returning 0 if the function completed cleanly. \nAlso, you can raise exceptions if you are returning a value different from zero, and then set two "exception variables" (mine: EXCEPTION and EXCEPTION_MSG), the first containing the exception type and the second a human readable message.</p>\n\n<p>When you call a function, the parameters of the function are assigned to the special vars $0, $1 etc. I suggest you to put them into more meaningful names. declare the variables inside the function as local:</p>\n\n<pre><code>function foo {\n local bar="$0"\n}\n</code></pre>\n\n<p><strong>Error prone situations</strong></p>\n\n<p>In bash, unless you declare otherwise, an unset variable is used as an empty string. This is very dangerous in case of typo, as the badly typed variable will not be reported, and it will be evaluated as empty. use</p>\n\n<pre><code>set -o nounset\n</code></pre>\n\n<p>to prevent this to happen. Be careful though, because if you do this, the program will abort every time you evaluate an undefined variable. For this reason, the only way to check if a variable is not defined is the following:</p>\n\n<pre><code>if test "x${foo:-notset}" == "xnotset"\nthen\n echo "foo not set"\nfi\n</code></pre>\n\n<p>You can declare variables as readonly:</p>\n\n<pre><code>readonly readonly_var="foo"\n</code></pre>\n\n<p><strong>Modularization</strong></p>\n\n<p>You can achieve "python like" modularization if you use the following code:</p>\n\n<pre><code>set -o nounset\nfunction getScriptAbsoluteDir {\n # @description used to get the script path\n # @param $1 the script $0 parameter\n local script_invoke_path="$1"\n local cwd=`pwd`\n\n # absolute path ? if so, the first character is a /\n if test "x${script_invoke_path:0:1}" = \'x/\'\n then\n RESULT=`dirname "$script_invoke_path"`\n else\n RESULT=`dirname "$cwd/$script_invoke_path"`\n fi\n}\n\nscript_invoke_path="$0"\nscript_name=`basename "$0"`\ngetScriptAbsoluteDir "$script_invoke_path"\nscript_absolute_dir=$RESULT\n\nfunction import() { \n # @description importer routine to get external functionality.\n # @description the first location searched is the script directory.\n # @description if not found, search the module in the paths contained in $SHELL_LIBRARY_PATH environment variable\n # @param $1 the .shinc file to import, without .shinc extension\n module=$1\n\n if test "x$module" == "x"\n then\n echo "$script_name : Unable to import unspecified module. Dying."\n exit 1\n fi\n\n if test "x${script_absolute_dir:-notset}" == "xnotset"\n then\n echo "$script_name : Undefined script absolute dir. Did you remove getScriptAbsoluteDir? Dying."\n exit 1\n fi\n\n if test "x$script_absolute_dir" == "x"\n then\n echo "$script_name : empty script path. Dying."\n exit 1\n fi\n\n if test -e "$script_absolute_dir/$module.shinc"\n then\n # import from script directory\n . "$script_absolute_dir/$module.shinc"\n elif test "x${SHELL_LIBRARY_PATH:-notset}" != "xnotset"\n then\n # import from the shell script library path\n # save the separator and use the \':\' instead\n local saved_IFS="$IFS"\n IFS=\':\'\n for path in $SHELL_LIBRARY_PATH\n do\n if test -e "$path/$module.shinc"\n then\n . "$path/$module.shinc"\n return\n fi\n done\n # restore the standard separator\n IFS="$saved_IFS"\n fi\n echo "$script_name : Unable to find module $module."\n exit 1\n} \n</code></pre>\n\n<p>you can then import files with the extension .shinc with the following syntax</p>\n\n<p>import "AModule/ModuleFile"</p>\n\n<p>Which will be searched in SHELL_LIBRARY_PATH. As you always import in the global namespace, remember to prefix all your functions and variables with a proper prefix, otherwise you risk name clashes. I use double underscore as the python dot.</p>\n\n<p>Also, put this as first thing in your module</p>\n\n<pre><code># avoid double inclusion\nif test "${BashInclude__imported+defined}" == "defined"\nthen\n return 0\nfi\nBashInclude__imported=1\n</code></pre>\n\n<p><strong>Object oriented programming</strong></p>\n\n<p>In bash, you cannot do object oriented programming, unless you build a quite complex system of allocation of objects (I thought about that. it\'s feasible, but insane).\nIn practice, you can however do "Singleton oriented programming": you have one instance of each object, and only one.</p>\n\n<p>What I do is: i define an object into a module (see the modularization entry). Then I define empty vars (analogous to member variables) an init function (constructor) and member functions, like in this example code</p>\n\n<pre><code># avoid double inclusion\nif test "${Table__imported+defined}" == "defined"\nthen\n return 0\nfi\nTable__imported=1\n\nreadonly Table__NoException=""\nreadonly Table__ParameterException="Table__ParameterException"\nreadonly Table__MySqlException="Table__MySqlException"\nreadonly Table__NotInitializedException="Table__NotInitializedException"\nreadonly Table__AlreadyInitializedException="Table__AlreadyInitializedException"\n\n# an example for module enum constants, used in the mysql table, in this case\nreadonly Table__GENDER_MALE="GENDER_MALE"\nreadonly Table__GENDER_FEMALE="GENDER_FEMALE"\n\n# private: prefixed with p_ (a bash variable cannot start with _)\np_Table__mysql_exec="" # will contain the executed mysql command \n\np_Table__initialized=0\n\nfunction Table__init {\n # @description init the module with the database parameters\n # @param $1 the mysql config file\n # @exception Table__NoException, Table__ParameterException\n\n EXCEPTION=""\n EXCEPTION_MSG=""\n EXCEPTION_FUNC=""\n RESULT=""\n\n if test $p_Table__initialized -ne 0\n then\n EXCEPTION=$Table__AlreadyInitializedException \n EXCEPTION_MSG="module already initialized"\n EXCEPTION_FUNC="$FUNCNAME"\n return 1\n fi\n\n\n local config_file="$1"\n\n # yes, I am aware that I could put default parameters and other niceties, but I am lazy today\n if test "x$config_file" = "x"; then\n EXCEPTION=$Table__ParameterException\n EXCEPTION_MSG="missing parameter config file"\n EXCEPTION_FUNC="$FUNCNAME"\n return 1\n fi\n\n\n p_Table__mysql_exec="mysql --defaults-file=$config_file --silent --skip-column-names -e "\n\n # mark the module as initialized\n p_Table__initialized=1\n\n EXCEPTION=$Table__NoException\n EXCEPTION_MSG=""\n EXCEPTION_FUNC=""\n return 0\n\n}\n\nfunction Table__getName() {\n # @description gets the name of the person \n # @param $1 the row identifier\n # @result the name\n\n EXCEPTION=""\n EXCEPTION_MSG=""\n EXCEPTION_FUNC=""\n RESULT=""\n\n if test $p_Table__initialized -eq 0\n then\n EXCEPTION=$Table__NotInitializedException\n EXCEPTION_MSG="module not initialized"\n EXCEPTION_FUNC="$FUNCNAME"\n return 1\n fi\n\n id=$1\n\n if test "x$id" = "x"; then\n EXCEPTION=$Table__ParameterException\n EXCEPTION_MSG="missing parameter identifier"\n EXCEPTION_FUNC="$FUNCNAME"\n return 1\n fi\n\n local name=`$p_Table__mysql_exec "SELECT name FROM table WHERE id = \'$id\'"`\n if test $? != 0 ; then\n EXCEPTION=$Table__MySqlException\n EXCEPTION_MSG="unable to perform select"\n EXCEPTION_FUNC="$FUNCNAME"\n return 1\n fi\n\n RESULT=$name\n EXCEPTION=$Table__NoException\n EXCEPTION_MSG=""\n EXCEPTION_FUNC=""\n return 0\n}\n</code></pre>\n\n<p><strong>Trapping and handling signals</strong></p>\n\n<p>I found this useful to catch and handle exceptions.</p>\n\n<pre><code>function Main__interruptHandler() {\n # @description signal handler for SIGINT\n echo "SIGINT caught"\n exit\n} \nfunction Main__terminationHandler() { \n # @description signal handler for SIGTERM\n echo "SIGTERM caught"\n exit\n} \nfunction Main__exitHandler() { \n # @description signal handler for end of the program (clean or unclean). \n # probably redundant call, we already call the cleanup in main.\n exit\n} \n\ntrap Main__interruptHandler INT\ntrap Main__terminationHandler TERM\ntrap Main__exitHandler EXIT\n\nfunction Main__main() {\n # body\n}\n\n# catch signals and exit\ntrap exit INT TERM EXIT\n\nMain__main "$@"\n</code></pre>\n\n<p><strong>Hints and tips</strong></p>\n\n<p>If something does not work for some reason, try to reorder the code. Order is important and not always intuitive.</p>\n\n<p>do not even consider working with tcsh. it does not support functions, and it\'s horrible in general. </p>\n\n<p>Hope it helps, although please note. If you have to use the kind of things I wrote here, it means that your problem is too complex to be solved with shell. use another language. I had to use it due to human factors and legacy.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/78497', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14437/'] |
78,523 | <p>I'm curious about OpenID. While I agree that the idea of unified credentials is great, I have a few reservations. What is to prevent an OpenID provider from going crazy and holding the OpenID accounts they have hostage until you pay $n? If I decide I don't like the provider I'm with this there a way to migrate to a different provider with out losing all my information at various sites?</p>
<p><b>Edit:</b> I feel like my question is being misunderstood. It has been said that I can simple create a delegation and this is partially true. I can do this if I haven't already created an account at, for example, SO. If I decide to set up my own OpenID provider at some point, there is no way that I can see to move and keep my account information. That is the sort of think I was wondering about.</p>
<p><b>Second Edit:</b>
I see that there is a uservoice about adding this to SO. <a href="https://web.archive.org/web/20090424075552/http://stackoverflow.uservoice.com:80/pages/general/suggestions/16685" rel="nofollow noreferrer">Link</a></p>
| [{'answer_id': 78538, 'author': 'Ian P', 'author_id': 10853, 'author_profile': 'https://Stackoverflow.com/users/10853', 'pm_score': 2, 'selected': False, 'text': '<p>This may help:\n<a href="http://openid.net/foundation/intellectual-property/" rel="nofollow noreferrer">OpenID</a></p>\n'}, {'answer_id': 78542, 'author': 'thenickdude', 'author_id': 14431, 'author_profile': 'https://Stackoverflow.com/users/14431', 'pm_score': 3, 'selected': False, 'text': '<p>Nothing prevents the provider from holding your account to ransom. You should pick a provider that you know to be reliable. Or, if you trust nobody but yourself, you can be your own provider:</p>\n\n<p><a href="http://wiki.openid.net/Run_your_own_identity_server" rel="noreferrer">http://wiki.openid.net/Run_your_own_identity_server</a></p>\n'}, {'answer_id': 78549, 'author': 'Jan Krüger', 'author_id': 12471, 'author_profile': 'https://Stackoverflow.com/users/12471', 'pm_score': 5, 'selected': True, 'text': '<p>This is why you can use <a href="http://wiki.openid.net/Delegation" rel="noreferrer">OpenID delegation</a>, i.e. you set up two META tags on your personal website and then you can use that site\'s URL as an alias for your current OpenID provider of choice. Should it get unfriendly you just switch to another and update your tags.</p>\n\n<p>Additionally you can always operate your own OpenID identity provider (if you have a server with, for example, a web server and PHP on it). I use <a href="http://siege.org/projects/phpMyID/" rel="noreferrer">phpMyID</a> for this.</p>\n\n<p><strong>Update</strong>: regarding the updated question: OpenID consumers (sites where you log in using OpenID) may allow you to switch the OpenID used for sign-on at their discretion. Sourceforge, for example, does. To prevent problems it\'s best to use delegation right from the start. Otherwise this is a necessary limitation imposed by OpenID\'s design.</p>\n'}, {'answer_id': 78652, 'author': 'galets', 'author_id': 14395, 'author_profile': 'https://Stackoverflow.com/users/14395', 'pm_score': 0, 'selected': False, 'text': '<p>I think you might be mixing free-market providers with governments. Latter abuse their power because you got nobody else to go to (try to get an "alternative" passport). Since the OpenID prividers have competition, you can always leave one provider and go to another.</p>\n'}, {'answer_id': 78851, 'author': 'mislav', 'author_id': 11687, 'author_profile': 'https://Stackoverflow.com/users/11687', 'pm_score': 0, 'selected': False, 'text': "<p>A site that implements OpenID authentication in a good way would allow you to switch your ID to another URL or to specify a secondary ID in cases when your primary provider happens to be down.</p>\n\n<p>Currently, most sites still don't have this option, and yes -- if our OpenID providers would delete our accounts one day, we'd have trouble getting to our accounts on some sites. We trust them in not denying us the service.</p>\n"}, {'answer_id': 78865, 'author': 'user14563', 'author_id': 14563, 'author_profile': 'https://Stackoverflow.com/users/14563', 'pm_score': 2, 'selected': False, 'text': "<p>There's no way to stop Google from holding my gmail inbox hostage until I pay them $n. It's a trust thing, I guess.</p>\n"}, {'answer_id': 78888, 'author': 'Jim', 'author_id': 8427, 'author_profile': 'https://Stackoverflow.com/users/8427', 'pm_score': 3, 'selected': False, 'text': '<p>It\'s <a href="http://wiki.openid.net/Relying_Party_Best_Practices#Many-to-one_relationship_between_Identity_URLs_and_.22user_accounts.22" rel="nofollow noreferrer">an OpenID relying party best practice</a> to allow multiple OpenIDs to be associated with a single account.</p>\n\n<p>It\'s also <a href="http://wiki.openid.net/Relying_Party_Best_Practices#Provide_.22Lost_Identifier.22_functionality_to_switch_to_a_new_identifier_without_access_to_the_old_one" rel="nofollow noreferrer">an OpenID relying party best practice</a> to allow people to recover their accounts without access to their old OpenID.</p>\n\n<p>If Stack Overflow doesn\'t do these things, then this is a shortcoming of Stack Overflow, not OpenID.</p>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/78523', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10738/'] |
78,536 | <p>I want to do something like:</p>
<pre><code>MyObject myObj = GetMyObj(); // Create and fill a new object
MyObject newObj = myObj.Clone();
</code></pre>
<p>And then make changes to the new object that are not reflected in the original object.</p>
<p>I don't often need this functionality, so when it's been necessary, I've resorted to creating a new object and then copying each property individually, but it always leaves me with the feeling that there is a better or more elegant way of handling the situation.</p>
<p>How can I clone or deep copy an object so that the cloned object can be modified without any changes being reflected in the original object?</p>
| [{'answer_id': 78552, 'author': 'HappyDude', 'author_id': 14266, 'author_profile': 'https://Stackoverflow.com/users/14266', 'pm_score': 4, 'selected': False, 'text': '<p>In general, you implement the ICloneable interface and implement Clone yourself.\nC# objects have a built-in MemberwiseClone method that performs a shallow copy that can help you out for all the primitives.</p>\n\n<p>For a deep copy, there is no way it can know how to automatically do it.</p>\n'}, {'answer_id': 78568, 'author': 'dimarzionist', 'author_id': 10778, 'author_profile': 'https://Stackoverflow.com/users/10778', 'pm_score': 5, 'selected': False, 'text': "<ol>\n<li>Basically you need to implement ICloneable interface and then realize object structure copying. </li>\n<li>If it's deep copy of all members, you need to insure (not relating on solution you choose) that all children are clonable as well. </li>\n<li>Sometimes you need to be aware of some restriction during this process, for example if you copying the ORM objects most of frameworks allow only one object attached to the session and you MUST NOT make clones of this object, or if it's possible you need to care about session attaching of these objects.</li>\n</ol>\n\n<p>Cheers.</p>\n"}, {'answer_id': 78577, 'author': 'Nick', 'author_id': 1490, 'author_profile': 'https://Stackoverflow.com/users/1490', 'pm_score': 7, 'selected': False, 'text': '<p>I prefer a copy constructor to a clone. The intent is clearer.</p>\n'}, {'answer_id': 78587, 'author': 'Zach Burlingame', 'author_id': 2233, 'author_profile': 'https://Stackoverflow.com/users/2233', 'pm_score': 5, 'selected': False, 'text': '<p>The short answer is you inherit from the ICloneable interface and then implement the .clone function. Clone should do a memberwise copy and perform a deep copy on any member that requires it, then return the resulting object. This is a recursive operation ( it requires that all members of the class you want to clone are either value types or implement ICloneable and that their members are either value types or implement ICloneable, and so on).</p>\n\n<p>For a more detailed explanation on Cloning using ICloneable, check out <a href="https://web.archive.org/web/20120113123300/http://www.ondotnet.com/pub/a/dotnet/2002/11/25/copying.html" rel="noreferrer">this article</a>.</p>\n\n<p>The <em>long</em> answer is "it depends". As mentioned by others, ICloneable is not supported by generics, requires special considerations for circular class references, and is actually viewed by some as a <a href="http://blogs.msdn.com/brada/archive/2004/05/03/125427.aspx" rel="noreferrer">"mistake"</a> in the .NET Framework. The serialization method depends on your objects being serializable, which they may not be and you may have no control over. There is still much debate in the community over which is the "best" practice. In reality, none of the solutions are the one-size fits all best practice for all situations like ICloneable was originally interpreted to be.</p>\n\n<p>See the this <a href="http://developerscon.blogspot.com/2008/06/c-object-clone-wars.html" rel="noreferrer">Developer\'s Corner article</a> for a few more options (credit to Ian).</p>\n'}, {'answer_id': 78612, 'author': 'johnc', 'author_id': 5302, 'author_profile': 'https://Stackoverflow.com/users/5302', 'pm_score': 12, 'selected': True, 'text': '<p>Whereas one approach is to implement the <a href="http://msdn.microsoft.com/en-us/library/system.icloneable.aspx" rel="noreferrer"><code>ICloneable</code></a> interface (described <a href="https://stackoverflow.com/questions/78536/cloning-objects-in-c/78568#78568">here</a>, so I won\'t regurgitate), here\'s a nice deep clone object copier I found on <a href="http://www.codeproject.com/Articles/23832/Implementing-Deep-Cloning-via-Serializing-objects" rel="noreferrer">The Code Project</a> a while ago and incorporated it into our code.\nAs mentioned elsewhere, it requires your objects to be serializable.</p>\n<pre><code>using System;\nusing System.IO;\nusing System.Runtime.Serialization;\nusing System.Runtime.Serialization.Formatters.Binary;\n\n/// <summary>\n/// Reference Article http://www.codeproject.com/KB/tips/SerializedObjectCloner.aspx\n/// Provides a method for performing a deep copy of an object.\n/// Binary Serialization is used to perform the copy.\n/// </summary>\npublic static class ObjectCopier\n{\n /// <summary>\n /// Perform a deep copy of the object via serialization.\n /// </summary>\n /// <typeparam name="T">The type of object being copied.</typeparam>\n /// <param name="source">The object instance to copy.</param>\n /// <returns>A deep copy of the object.</returns>\n public static T Clone<T>(T source)\n {\n if (!typeof(T).IsSerializable)\n {\n throw new ArgumentException("The type must be serializable.", nameof(source));\n }\n\n // Don\'t serialize a null object, simply return the default for that object\n if (ReferenceEquals(source, null)) return default;\n\n using var Stream stream = new MemoryStream();\n IFormatter formatter = new BinaryFormatter();\n formatter.Serialize(stream, source);\n stream.Seek(0, SeekOrigin.Begin);\n return (T)formatter.Deserialize(stream);\n }\n}\n</code></pre>\n<p>The idea is that it serializes your object and then deserializes it into a fresh object. The benefit is that you don\'t have to concern yourself about cloning everything when an object gets too complex.</p>\n<p>In case of you prefer to use the new <a href="http://en.wikipedia.org/wiki/Extension_method" rel="noreferrer">extension methods</a> of C# 3.0, change the method to have the following signature:</p>\n<pre><code>public static T Clone<T>(this T source)\n{\n // ...\n}\n</code></pre>\n<p>Now the method call simply becomes <code>objectBeingCloned.Clone();</code>.</p>\n<p><strong>EDIT</strong> (January 10 2015) Thought I\'d revisit this, to mention I recently started using (Newtonsoft) Json to do this, it <a href="http://maxondev.com/serialization-performance-comparison-c-net-formats-frameworks-xmldatacontractserializer-xmlserializer-binaryformatter-json-newtonsoft-servicestack-text/" rel="noreferrer">should be</a> lighter, and avoids the overhead of [Serializable] tags. (<strong>NB</strong> @atconway has pointed out in the comments that private members are not cloned using the JSON method)</p>\n<pre><code>/// <summary>\n/// Perform a deep Copy of the object, using Json as a serialization method. NOTE: Private members are not cloned using this method.\n/// </summary>\n/// <typeparam name="T">The type of object being copied.</typeparam>\n/// <param name="source">The object instance to copy.</param>\n/// <returns>The copied object.</returns>\npublic static T CloneJson<T>(this T source)\n{ \n // Don\'t serialize a null object, simply return the default for that object\n if (ReferenceEquals(source, null)) return default;\n\n // initialize inner objects individually\n // for example in default constructor some list property initialized with some values,\n // but in \'source\' these items are cleaned -\n // without ObjectCreationHandling.Replace default constructor values will be added to result\n var deserializeSettings = new JsonSerializerSettings {ObjectCreationHandling = ObjectCreationHandling.Replace};\n\n return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source), deserializeSettings);\n}\n</code></pre>\n'}, {'answer_id': 78856, 'author': 'Ryan Lundy', 'author_id': 5486, 'author_profile': 'https://Stackoverflow.com/users/5486', 'pm_score': 8, 'selected': False, 'text': '<p>The reason not to use <a href="http://referencesource.microsoft.com/mscorlib/system/icloneable.cs.html#fb795e239ce05299" rel="nofollow noreferrer">ICloneable</a> is <strong>not</strong> because it doesn\'t have a generic interface. <a href="https://learn.microsoft.com/en-us/archive/blogs/brada/should-we-obsolete-icloneable-the-slar-on-system-icloneable" rel="nofollow noreferrer">The reason not to use it is because it\'s vague</a>. It doesn\'t make clear whether you\'re getting a shallow or a deep copy; that\'s up to the implementer.</p>\n<p>Yes, <code>MemberwiseClone</code> makes a shallow copy, but the opposite of <code>MemberwiseClone</code> isn\'t <code>Clone</code>; it would be, perhaps, <code>DeepClone</code>, which doesn\'t exist. When you use an object through its ICloneable interface, you can\'t know which kind of cloning the underlying object performs. (And XML comments won\'t make it clear, because you\'ll get the interface comments rather than the ones on the object\'s Clone method.)</p>\n<p>What I usually do is simply make a <code>Copy</code> method that does exactly what I want.</p>\n'}, {'answer_id': 1497125, 'author': 'Daniel Mošmondor', 'author_id': 166251, 'author_profile': 'https://Stackoverflow.com/users/166251', 'pm_score': 4, 'selected': False, 'text': '<p>I came up with this to overcome a <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="noreferrer">.NET</a> shortcoming having to manually deep copy List<T>.</p>\n\n<p>I use this:</p>\n\n<pre><code>static public IEnumerable<SpotPlacement> CloneList(List<SpotPlacement> spotPlacements)\n{\n foreach (SpotPlacement sp in spotPlacements)\n {\n yield return (SpotPlacement)sp.Clone();\n }\n}\n</code></pre>\n\n<p>And at another place:</p>\n\n<pre><code>public object Clone()\n{\n OrderItem newOrderItem = new OrderItem();\n ...\n newOrderItem._exactPlacements.AddRange(SpotPlacement.CloneList(_exactPlacements));\n ...\n return newOrderItem;\n}\n</code></pre>\n\n<p>I tried to come up with oneliner that does this, but it\'s not possible, due to yield not working inside anonymous method blocks.</p>\n\n<p>Better still, use generic List<T> cloner:</p>\n\n<pre><code>class Utility<T> where T : ICloneable\n{\n static public IEnumerable<T> CloneList(List<T> tl)\n {\n foreach (T t in tl)\n {\n yield return (T)t.Clone();\n }\n }\n}\n</code></pre>\n'}, {'answer_id': 1834578, 'author': 'Michael White', 'author_id': 223103, 'author_profile': 'https://Stackoverflow.com/users/223103', 'pm_score': 5, 'selected': False, 'text': '<p>Well I was having problems using ICloneable in Silverlight, but I liked the idea of seralization, I can seralize XML, so I did this:</p>\n<pre><code>static public class SerializeHelper\n{\n //Michael White, Holly Springs Consulting, 2009\n //[email protected]\n public static T DeserializeXML<T>(string xmlData) \n where T:new()\n {\n if (string.IsNullOrEmpty(xmlData))\n return default(T);\n\n TextReader tr = new StringReader(xmlData);\n T DocItms = new T();\n XmlSerializer xms = new XmlSerializer(DocItms.GetType());\n DocItms = (T)xms.Deserialize(tr);\n\n return DocItms == null ? default(T) : DocItms;\n }\n\n public static string SeralizeObjectToXML<T>(T xmlObject)\n {\n StringBuilder sbTR = new StringBuilder();\n XmlSerializer xmsTR = new XmlSerializer(xmlObject.GetType());\n XmlWriterSettings xwsTR = new XmlWriterSettings();\n \n XmlWriter xmwTR = XmlWriter.Create(sbTR, xwsTR);\n xmsTR.Serialize(xmwTR,xmlObject);\n \n return sbTR.ToString();\n }\n\n public static T CloneObject<T>(T objClone) \n where T:new()\n {\n string GetString = SerializeHelper.SeralizeObjectToXML<T>(objClone);\n return SerializeHelper.DeserializeXML<T>(GetString);\n }\n}\n</code></pre>\n'}, {'answer_id': 3968577, 'author': 'xr280xr', 'author_id': 263832, 'author_profile': 'https://Stackoverflow.com/users/263832', 'pm_score': 3, 'selected': False, 'text': "<p>I've seen it implemented through reflection as well. Basically there was a method that would iterate through the members of an object and appropriately copy them to the new object. When it reached reference types or collections I think it did a recursive call on itself. Reflection is expensive, but it worked pretty well.</p>\n"}, {'answer_id': 5324679, 'author': 'Konstantin Salavatov', 'author_id': 204647, 'author_profile': 'https://Stackoverflow.com/users/204647', 'pm_score': 6, 'selected': False, 'text': '<p>Simple extension method to copy all the public properties. Works for any objects and <strong>does not</strong> require class to be <code>[Serializable]</code>. Can be extended for other access level.</p>\n\n<pre><code>public static void CopyTo( this object S, object T )\n{\n foreach( var pS in S.GetType().GetProperties() )\n {\n foreach( var pT in T.GetType().GetProperties() )\n {\n if( pT.Name != pS.Name ) continue;\n ( pT.GetSetMethod() ).Invoke( T, new object[] \n { pS.GetGetMethod().Invoke( S, null ) } );\n }\n };\n}\n</code></pre>\n'}, {'answer_id': 7316457, 'author': 'dougajmcdonald', 'author_id': 777733, 'author_profile': 'https://Stackoverflow.com/users/777733', 'pm_score': 3, 'selected': False, 'text': "<p>Here is a deep copy implementation:</p>\n\n<pre><code>public static object CloneObject(object opSource)\n{\n //grab the type and create a new instance of that type\n Type opSourceType = opSource.GetType();\n object opTarget = CreateInstanceOfType(opSourceType);\n\n //grab the properties\n PropertyInfo[] opPropertyInfo = opSourceType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);\n\n //iterate over the properties and if it has a 'set' method assign it from the source TO the target\n foreach (PropertyInfo item in opPropertyInfo)\n {\n if (item.CanWrite)\n {\n //value types can simply be 'set'\n if (item.PropertyType.IsValueType || item.PropertyType.IsEnum || item.PropertyType.Equals(typeof(System.String)))\n {\n item.SetValue(opTarget, item.GetValue(opSource, null), null);\n }\n //object/complex types need to recursively call this method until the end of the tree is reached\n else\n {\n object opPropertyValue = item.GetValue(opSource, null);\n if (opPropertyValue == null)\n {\n item.SetValue(opTarget, null, null);\n }\n else\n {\n item.SetValue(opTarget, CloneObject(opPropertyValue), null);\n }\n }\n }\n }\n //return the new item\n return opTarget;\n}\n</code></pre>\n"}, {'answer_id': 8422769, 'author': 'supercat', 'author_id': 363751, 'author_profile': 'https://Stackoverflow.com/users/363751', 'pm_score': 3, 'selected': False, 'text': "<p>Follow these steps:</p>\n\n<ul>\n<li>Define an <code>ISelf<T></code> with a read-only <code>Self</code> property that returns <code>T</code>, and <code>ICloneable<out T></code>, which derives from <code>ISelf<T></code> and includes a method <code>T Clone()</code>.</li>\n<li>Then define a <code>CloneBase</code> type which implements a <code>protected virtual generic VirtualClone</code> casting <code>MemberwiseClone</code> to the passed-in type. </li>\n<li>Each derived type should implement <code>VirtualClone</code> by calling the base clone method and then doing whatever needs to be done to properly clone those aspects of the derived type which the parent VirtualClone method hasn't yet handled.</li>\n</ul>\n\n<p>For maximum inheritance versatility, classes exposing public cloning functionality should be <code>sealed</code>, but derive from a base class which is otherwise identical except for the lack of cloning. Rather than passing variables of the explicit clonable type, take a parameter of type <code>ICloneable<theNonCloneableType></code>. This will allow a routine that expects a cloneable derivative of <code>Foo</code> to work with a cloneable derivative of <code>DerivedFoo</code>, but also allow the creation of non-cloneable derivatives of <code>Foo</code>.</p>\n"}, {'answer_id': 12609692, 'author': 'cregox', 'author_id': 274502, 'author_profile': 'https://Stackoverflow.com/users/274502', 'pm_score': 7, 'selected': False, 'text': '<p>After much much reading about many of the options linked here, and possible solutions for this issue, I believe <a href="https://developerscon.blogspot.com/2008/06/c-object-clone-wars.html" rel="noreferrer">all the options are summarized pretty well at <em>Ian P</em>\'s link</a> (all other options are variations of those) and the best solution is provided by <a href="http://www.agiledeveloper.com/articles/cloning072002.htm" rel="noreferrer"><em>Pedro77</em>\'s link</a> on the question comments.</p>\n\n<p>So I\'ll just copy relevant parts of those 2 references here. That way we can have:</p>\n\n<h2>The best thing to do for cloning objects in C sharp!</h2>\n\n<p>First and foremost, those are all our options:</p>\n\n<ul>\n<li>Manually with <strong><a href="https://learn.microsoft.com/en-us/dotnet/api/system.icloneable" rel="noreferrer">ICloneable</a></strong>, which is <em>Shallow</em> and not <em>Type-Safe</em></li>\n<li><strong><a href="https://learn.microsoft.com/en-us/dotnet/api/system.object.memberwiseclone" rel="noreferrer">MemberwiseClone</a></strong>, which uses ICloneable</li>\n<li><strong><a href="https://www.codeproject.com/Articles/3441/Base-class-for-cloning-an-object-in-C" rel="noreferrer">Reflection</a></strong> by using <a href="https://learn.microsoft.com/en-us/dotnet/api/system.activator.createinstance" rel="noreferrer">Activator.CreateInstance</a> and <a href="https://github.com/Burtsev-Alexey/net-object-deep-copy/" rel="noreferrer">recursive MemberwiseClone</a></li>\n<li><strong><a href="https://learn.microsoft.com/en-us/dotnet/api/system.serializableattribute" rel="noreferrer">Serialization</a></strong>, as pointed by <a href="https://stackoverflow.com/a/78612/274502">johnc\'s preferred answer</a></li>\n<li><strong>Intermediate Language</strong>, which I got no idea <a href="https://whizzodev.blogspot.com/2008/03/object-cloning-using-il-in-c.html" rel="noreferrer">how works</a></li>\n<li><strong>Extension Methods</strong>, such as this <a href="https://circlesandcrossesblogarchive.blogspot.com/2008/01/extension-methods-for-copying-or.html" rel="noreferrer">custom clone framework by Havard Straden</a></li>\n<li><strong><a href="https://www.codeproject.com/Articles/1111658/Fast-Deep-Copy-of-Objects-by-Expression-Trees-Csha" rel="noreferrer">Expression Trees</a></strong></li>\n</ul>\n\n<p>The <a href="https://www.codeproject.com/Articles/1111658/Fast-Deep-Copy-of-Objects-by-Expression-Trees-Csha" rel="noreferrer">article Fast Deep Copy by Expression Trees</a> has also performance comparison of cloning by Serialization, Reflection and Expression Trees.</p>\n\n<h1>Why I choose <em>ICloneable</em> (i.e. manually)</h1>\n\n<p><a href="http://www.agiledeveloper.com/articles/cloning072002.htm" rel="noreferrer">Mr Venkat Subramaniam (redundant link here) explains in much detail why</a>.</p>\n\n<p>All his article circles around an example that tries to be applicable for most cases, using 3 objects: <em>Person</em>, <em>Brain</em> and <em>City</em>. We want to clone a person, which will have its own brain but the same city. You can either picture all problems any of the other methods above can bring or read the article.</p>\n\n<p>This is my slightly modified version of his conclusion:</p>\n\n<blockquote>\n <p>Copying an object by specifying <code>New</code> followed by the class name often leads to code that is not extensible. Using clone, the application of prototype pattern, is a better way to achieve this. However, using clone as it is provided in C# (and Java) can be quite problematic as well. It is better to provide a protected (non-public) copy constructor and invoke that from the clone method. This gives us the ability to delegate the task of creating an object to an instance of a class itself, thus providing extensibility and also, safely creating the objects using the protected copy constructor.</p>\n</blockquote>\n\n<p>Hopefully this implementation can make things clear:</p>\n\n<pre><code>public class Person : ICloneable\n{\n private final Brain brain; // brain is final since I do not want \n // any transplant on it once created!\n private int age;\n public Person(Brain aBrain, int theAge)\n {\n brain = aBrain; \n age = theAge;\n }\n protected Person(Person another)\n {\n Brain refBrain = null;\n try\n {\n refBrain = (Brain) another.brain.clone();\n // You can set the brain in the constructor\n }\n catch(CloneNotSupportedException e) {}\n brain = refBrain;\n age = another.age;\n }\n public String toString()\n {\n return "This is person with " + brain;\n // Not meant to sound rude as it reads!\n }\n public Object clone()\n {\n return new Person(this);\n }\n …\n}\n</code></pre>\n\n<p>Now consider having a class derive from Person.</p>\n\n<pre><code>public class SkilledPerson extends Person\n{\n private String theSkills;\n public SkilledPerson(Brain aBrain, int theAge, String skills)\n {\n super(aBrain, theAge);\n theSkills = skills;\n }\n protected SkilledPerson(SkilledPerson another)\n {\n super(another);\n theSkills = another.theSkills;\n }\n\n public Object clone()\n {\n return new SkilledPerson(this);\n }\n public String toString()\n {\n return "SkilledPerson: " + super.toString();\n }\n}\n</code></pre>\n\n<p>You may try running the following code:</p>\n\n<pre><code>public class User\n{\n public static void play(Person p)\n {\n Person another = (Person) p.clone();\n System.out.println(p);\n System.out.println(another);\n }\n public static void main(String[] args)\n {\n Person sam = new Person(new Brain(), 1);\n play(sam);\n SkilledPerson bob = new SkilledPerson(new SmarterBrain(), 1, "Writer");\n play(bob);\n }\n}\n</code></pre>\n\n<p>The output produced will be:</p>\n\n<pre><code>This is person with Brain@1fcc69\nThis is person with Brain@253498\nSkilledPerson: This is person with SmarterBrain@1fef6f\nSkilledPerson: This is person with SmarterBrain@209f4e\n</code></pre>\n\n<p>Observe that, if we keep a count of the number of objects, the clone as implemented here will keep a correct count of the number of objects.</p>\n'}, {'answer_id': 12901265, 'author': 'Michael Cox', 'author_id': 372698, 'author_profile': 'https://Stackoverflow.com/users/372698', 'pm_score': 5, 'selected': False, 'text': '<p>If you\'re already using a 3rd party application like <a href="https://github.com/omuleanu/ValueInjecter" rel="noreferrer">ValueInjecter</a> or <a href="https://github.com/AutoMapper/AutoMapper" rel="noreferrer">Automapper</a>, you can do something like this:</p>\n\n<pre><code>MyObject oldObj; // The existing object to clone\n\nMyObject newObj = new MyObject();\nnewObj.InjectFrom(oldObj); // Using ValueInjecter syntax\n</code></pre>\n\n<p>Using this method you don\'t have to implement <code>ISerializable</code> or <code>ICloneable</code> on your objects. This is common with the MVC/MVVM pattern, so simple tools like this have been created.</p>\n\n<p>see <a href="https://github.com/omuleanu/ValueInjecter/blob/dae7956439cac8516979fe254a520a1942c5cdeb/Tests/Cloning.cs" rel="noreferrer">the ValueInjecter deep cloning sample on GitHub</a>.</p>\n'}, {'answer_id': 15788750, 'author': 'craastad', 'author_id': 1111732, 'author_profile': 'https://Stackoverflow.com/users/1111732', 'pm_score': 9, 'selected': False, 'text': '<p>I wanted a cloner for very simple objects of mostly primitives and lists. If your object is out of the box JSON serializable then this method will do the trick. This requires no modification or implementation of interfaces on the cloned class, just a JSON serializer like JSON.NET.</p>\n\n<pre><code>public static T Clone<T>(T source)\n{\n var serialized = JsonConvert.SerializeObject(source);\n return JsonConvert.DeserializeObject<T>(serialized);\n}\n</code></pre>\n\n<p>Also, you can use this extension method</p>\n\n<pre><code>public static class SystemExtension\n{\n public static T Clone<T>(this T source)\n {\n var serialized = JsonConvert.SerializeObject(source);\n return JsonConvert.DeserializeObject<T>(serialized);\n }\n}\n</code></pre>\n'}, {'answer_id': 18123706, 'author': 'Ylli Prifti', 'author_id': 693312, 'author_profile': 'https://Stackoverflow.com/users/693312', 'pm_score': 1, 'selected': False, 'text': '<p>This will copy all readable and writable properties of an object to another.</p>\n\n<pre><code> public class PropertyCopy<TSource, TTarget> \n where TSource: class, new()\n where TTarget: class, new()\n {\n public static TTarget Copy(TSource src, TTarget trg, params string[] properties)\n {\n if (src==null) return trg;\n if (trg == null) trg = new TTarget();\n var fulllist = src.GetType().GetProperties().Where(c => c.CanWrite && c.CanRead).ToList();\n if (properties != null && properties.Count() > 0)\n fulllist = fulllist.Where(c => properties.Contains(c.Name)).ToList();\n if (fulllist == null || fulllist.Count() == 0) return trg;\n\n fulllist.ForEach(c =>\n {\n c.SetValue(trg, c.GetValue(src));\n });\n\n return trg;\n }\n }\n</code></pre>\n\n<p>and this is how you use it: </p>\n\n<pre><code> var cloned = Utils.PropertyCopy<TKTicket, TKTicket>.Copy(_tmp, dbsave,\n "Creation",\n "Description",\n "IdTicketStatus",\n "IdUserCreated",\n "IdUserInCharge",\n "IdUserRequested",\n "IsUniqueTicketGenerated",\n "LastEdit",\n "Subject",\n "UniqeTicketRequestId",\n "Visibility");\n</code></pre>\n\n<p>or to copy everything: </p>\n\n<pre><code>var cloned = Utils.PropertyCopy<TKTicket, TKTicket>.Copy(_tmp, dbsave);\n</code></pre>\n'}, {'answer_id': 20767567, 'author': 'MarcinJuraszek', 'author_id': 1163867, 'author_profile': 'https://Stackoverflow.com/users/1163867', 'pm_score': 5, 'selected': False, 'text': '<p>I\'ve just created <strong><a href="https://github.com/MarcinJuraszek/CloneExtensions"><code>CloneExtensions</code> library</a></strong> project. It performs fast, deep clone using simple assignment operations generated by Expression Tree runtime code compilation.</p>\n\n<p><strong>How to use it?</strong></p>\n\n<p>Instead of writing your own <code>Clone</code> or <code>Copy</code> methods with a tone of assignments between fields and properties make the program do it for yourself, using Expression Tree. <code>GetClone<T>()</code> method marked as extension method allows you to simply call it on your instance:</p>\n\n<pre><code>var newInstance = source.GetClone();\n</code></pre>\n\n<p>You can choose what should be copied from <code>source</code> to <code>newInstance</code> using <code>CloningFlags</code> enum:</p>\n\n<pre><code>var newInstance \n = source.GetClone(CloningFlags.Properties | CloningFlags.CollectionItems);\n</code></pre>\n\n<p><strong>What can be cloned?</strong></p>\n\n<ul>\n<li>Primitive (int, uint, byte, double, char, etc.), known immutable\ntypes (DateTime, TimeSpan, String) and delegates (including\nAction, Func, etc)</li>\n<li>Nullable</li>\n<li>T[] arrays</li>\n<li>Custom classes and structs, including generic classes and structs.</li>\n</ul>\n\n<p>Following class/struct members are cloned internally:</p>\n\n<ul>\n<li>Values of public, not readonly fields</li>\n<li>Values of public properties with both get and set accessors</li>\n<li>Collection items for types implementing ICollection</li>\n</ul>\n\n<p><strong>How fast it is?</strong></p>\n\n<p>The solution is faster then reflection, because members information has to be gathered only once, before <code>GetClone<T></code> is used for the first time for given type <code>T</code>.</p>\n\n<p>It\'s also faster than serialization-based solution when you clone more then couple instances of the same type <code>T</code>.</p>\n\n<p><strong>and more...</strong></p>\n\n<p>Read more about generated expressions on <a href="https://github.com/MarcinJuraszek/CloneExtensions/blob/master/EXPRESSION_TREES.md">documentation</a>.</p>\n\n<p>Sample expression debug listing for <code>List<int></code>:</p>\n\n<pre><code>.Lambda #Lambda1<System.Func`4[System.Collections.Generic.List`1[System.Int32],CloneExtensions.CloningFlags,System.Collections.Generic.IDictionary`2[System.Type,System.Func`2[System.Object,System.Object]],System.Collections.Generic.List`1[System.Int32]]>(\n System.Collections.Generic.List`1[System.Int32] $source,\n CloneExtensions.CloningFlags $flags,\n System.Collections.Generic.IDictionary`2[System.Type,System.Func`2[System.Object,System.Object]] $initializers) {\n .Block(System.Collections.Generic.List`1[System.Int32] $target) {\n .If ($source == null) {\n .Return #Label1 { null }\n } .Else {\n .Default(System.Void)\n };\n .If (\n .Call $initializers.ContainsKey(.Constant<System.Type>(System.Collections.Generic.List`1[System.Int32]))\n ) {\n $target = (System.Collections.Generic.List`1[System.Int32]).Call ($initializers.Item[.Constant<System.Type>(System.Collections.Generic.List`1[System.Int32])]\n ).Invoke((System.Object)$source)\n } .Else {\n $target = .New System.Collections.Generic.List`1[System.Int32]()\n };\n .If (\n ((System.Byte)$flags & (System.Byte).Constant<CloneExtensions.CloningFlags>(Fields)) == (System.Byte).Constant<CloneExtensions.CloningFlags>(Fields)\n ) {\n .Default(System.Void)\n } .Else {\n .Default(System.Void)\n };\n .If (\n ((System.Byte)$flags & (System.Byte).Constant<CloneExtensions.CloningFlags>(Properties)) == (System.Byte).Constant<CloneExtensions.CloningFlags>(Properties)\n ) {\n .Block() {\n $target.Capacity = .Call CloneExtensions.CloneFactory.GetClone(\n $source.Capacity,\n $flags,\n $initializers)\n }\n } .Else {\n .Default(System.Void)\n };\n .If (\n ((System.Byte)$flags & (System.Byte).Constant<CloneExtensions.CloningFlags>(CollectionItems)) == (System.Byte).Constant<CloneExtensions.CloningFlags>(CollectionItems)\n ) {\n .Block(\n System.Collections.Generic.IEnumerator`1[System.Int32] $var1,\n System.Collections.Generic.ICollection`1[System.Int32] $var2) {\n $var1 = (System.Collections.Generic.IEnumerator`1[System.Int32]).Call $source.GetEnumerator();\n $var2 = (System.Collections.Generic.ICollection`1[System.Int32])$target;\n .Loop {\n .If (.Call $var1.MoveNext() != False) {\n .Call $var2.Add(.Call CloneExtensions.CloneFactory.GetClone(\n $var1.Current,\n $flags,\n\n\n $initializers))\n } .Else {\n .Break #Label2 { }\n }\n }\n .LabelTarget #Label2:\n }\n } .Else {\n .Default(System.Void)\n };\n .Label\n $target\n .LabelTarget #Label1:\n}\n</code></pre>\n\n<p>}</p>\n\n<p>what has the same meaning like following c# code:</p>\n\n<pre><code>(source, flags, initializers) =>\n{\n if(source == null)\n return null;\n\n if(initializers.ContainsKey(typeof(List<int>))\n target = (List<int>)initializers[typeof(List<int>)].Invoke((object)source);\n else\n target = new List<int>();\n\n if((flags & CloningFlags.Properties) == CloningFlags.Properties)\n {\n target.Capacity = target.Capacity.GetClone(flags, initializers);\n }\n\n if((flags & CloningFlags.CollectionItems) == CloningFlags.CollectionItems)\n {\n var targetCollection = (ICollection<int>)target;\n foreach(var item in (ICollection<int>)source)\n {\n targetCollection.Add(item.Clone(flags, initializers));\n }\n }\n\n return target;\n}\n</code></pre>\n\n<p>Isn\'t it quite like how you\'d write your own <code>Clone</code> method for <code>List<int></code>?</p>\n'}, {'answer_id': 23017515, 'author': 'Jeroen Ritmeijer', 'author_id': 79448, 'author_profile': 'https://Stackoverflow.com/users/79448', 'pm_score': 2, 'selected': False, 'text': '<p>I have created a version of the accepted answer that works with both \'[Serializable]\' and \'[DataContract]\'. It has been a while since I wrote it, but if I remember correctly [DataContract] needed a different serializer.</p>\n\n<p>Requires <em>System, System.IO, System.Runtime.Serialization, System.Runtime.Serialization.Formatters.Binary, System.Xml</em>;</p>\n\n<pre><code>public static class ObjectCopier\n{\n\n /// <summary>\n /// Perform a deep Copy of an object that is marked with \'[Serializable]\' or \'[DataContract]\'\n /// </summary>\n /// <typeparam name="T">The type of object being copied.</typeparam>\n /// <param name="source">The object instance to copy.</param>\n /// <returns>The copied object.</returns>\n public static T Clone<T>(T source)\n {\n if (typeof(T).IsSerializable == true)\n {\n return CloneUsingSerializable<T>(source);\n }\n\n if (IsDataContract(typeof(T)) == true)\n {\n return CloneUsingDataContracts<T>(source);\n }\n\n throw new ArgumentException("The type must be Serializable or use DataContracts.", "source");\n }\n\n\n /// <summary>\n /// Perform a deep Copy of an object that is marked with \'[Serializable]\'\n /// </summary>\n /// <remarks>\n /// Found on http://stackoverflow.com/questions/78536/cloning-objects-in-c-sharp\n /// Uses code found on CodeProject, which allows free use in third party apps\n /// - http://www.codeproject.com/KB/tips/SerializedObjectCloner.aspx\n /// </remarks>\n /// <typeparam name="T">The type of object being copied.</typeparam>\n /// <param name="source">The object instance to copy.</param>\n /// <returns>The copied object.</returns>\n public static T CloneUsingSerializable<T>(T source)\n {\n if (!typeof(T).IsSerializable)\n {\n throw new ArgumentException("The type must be serializable.", "source");\n }\n\n // Don\'t serialize a null object, simply return the default for that object\n if (Object.ReferenceEquals(source, null))\n {\n return default(T);\n }\n\n IFormatter formatter = new BinaryFormatter();\n Stream stream = new MemoryStream();\n using (stream)\n {\n formatter.Serialize(stream, source);\n stream.Seek(0, SeekOrigin.Begin);\n return (T)formatter.Deserialize(stream);\n }\n }\n\n\n /// <summary>\n /// Perform a deep Copy of an object that is marked with \'[DataContract]\'\n /// </summary>\n /// <typeparam name="T">The type of object being copied.</typeparam>\n /// <param name="source">The object instance to copy.</param>\n /// <returns>The copied object.</returns>\n public static T CloneUsingDataContracts<T>(T source)\n {\n if (IsDataContract(typeof(T)) == false)\n {\n throw new ArgumentException("The type must be a data contract.", "source");\n }\n\n // ** Don\'t serialize a null object, simply return the default for that object\n if (Object.ReferenceEquals(source, null))\n {\n return default(T);\n }\n\n DataContractSerializer dcs = new DataContractSerializer(typeof(T));\n using(Stream stream = new MemoryStream())\n {\n using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateBinaryWriter(stream))\n {\n dcs.WriteObject(writer, source);\n writer.Flush();\n stream.Seek(0, SeekOrigin.Begin);\n using (XmlDictionaryReader reader = XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max))\n {\n return (T)dcs.ReadObject(reader);\n }\n }\n }\n }\n\n\n /// <summary>\n /// Helper function to check if a class is a [DataContract]\n /// </summary>\n /// <param name="type">The type of the object to check.</param>\n /// <returns>Boolean flag indicating if the class is a DataContract (true) or not (false) </returns>\n public static bool IsDataContract(Type type)\n {\n object[] attributes = type.GetCustomAttributes(typeof(DataContractAttribute), false);\n return attributes.Length == 1;\n }\n\n} \n</code></pre>\n'}, {'answer_id': 23042982, 'author': 'will_m', 'author_id': 3528734, 'author_profile': 'https://Stackoverflow.com/users/3528734', 'pm_score': 1, 'selected': False, 'text': '<p>how about just recasting inside a method \nthat should invoke basically a automatic copy constructor</p>\n\n<pre><code>T t = new T();\nT t2 = (T)t; //eh something like that\n\n List<myclass> cloneum;\n public void SomeFuncB(ref List<myclass> _mylist)\n {\n cloneum = new List<myclass>();\n cloneum = (List < myclass >) _mylist;\n cloneum.Add(new myclass(3));\n _mylist = new List<myclass>();\n }\n</code></pre>\n\n<p>seems to work to me</p>\n'}, {'answer_id': 23289451, 'author': 'Chtioui Malek', 'author_id': 1254684, 'author_profile': 'https://Stackoverflow.com/users/1254684', 'pm_score': 2, 'selected': False, 'text': '<p>To clone your class object you can use the Object.MemberwiseClone method,</p>\n\n<p>just add this function to your class :</p>\n\n<pre><code>public class yourClass\n{\n // ...\n // ...\n\n public yourClass DeepCopy()\n {\n yourClass othercopy = (yourClass)this.MemberwiseClone();\n return othercopy;\n }\n}\n</code></pre>\n\n<p>then to perform a deep independant copy, just call the DeepCopy method :</p>\n\n<pre><code>yourClass newLine = oldLine.DeepCopy();\n</code></pre>\n\n<p>hope this helps.</p>\n'}, {'answer_id': 28540467, 'author': 'Michael Sander', 'author_id': 564508, 'author_profile': 'https://Stackoverflow.com/users/564508', 'pm_score': 4, 'selected': False, 'text': '<p>EDIT: project is discontinued</p>\n\n<p>If you want true cloning to unknown types you can take a look at\n<a href="http://fastclone.codeplex.com/" rel="nofollow noreferrer">fastclone</a>.</p>\n\n<p>That\'s expression based cloning working about 10 times faster than binary serialization and maintaining complete object graph integrity.</p>\n\n<p>That means: if you refer multiple times to the same object in your hierachy, the clone will also have a single instance beeing referenced.</p>\n\n<p>There is no need for interfaces, attributes or any other modification to the objects being cloned.</p>\n'}, {'answer_id': 28900160, 'author': 'LuckyLikey', 'author_id': 4099159, 'author_profile': 'https://Stackoverflow.com/users/4099159', 'pm_score': 3, 'selected': False, 'text': '<p>I like Copyconstructors like that:</p>\n\n<pre><code> public AnyObject(AnyObject anyObject)\n {\n foreach (var property in typeof(AnyObject).GetProperties())\n {\n property.SetValue(this, property.GetValue(anyObject));\n }\n foreach (var field in typeof(AnyObject).GetFields())\n {\n field.SetValue(this, field.GetValue(anyObject));\n }\n }\n</code></pre>\n\n<p>If you have more things to copy add them</p>\n'}, {'answer_id': 29749841, 'author': 'LuckyLikey', 'author_id': 4099159, 'author_profile': 'https://Stackoverflow.com/users/4099159', 'pm_score': 2, 'selected': False, 'text': "<p>If your Object Tree is Serializeable you could also use something like this</p>\n\n<pre><code>static public MyClass Clone(MyClass myClass)\n{\n MyClass clone;\n XmlSerializer ser = new XmlSerializer(typeof(MyClass), _xmlAttributeOverrides);\n using (var ms = new MemoryStream())\n {\n ser.Serialize(ms, myClass);\n ms.Position = 0;\n clone = (MyClass)ser.Deserialize(ms);\n }\n return clone;\n}\n</code></pre>\n\n<p>be informed that this Solution is pretty easy but it's not as performant as other solutions may be.</p>\n\n<p>And be sure that if the Class grows, there will still be only those fields cloned, which also get serialized.</p>\n"}, {'answer_id': 29856064, 'author': 'TarmoPikaro', 'author_id': 2338477, 'author_profile': 'https://Stackoverflow.com/users/2338477', 'pm_score': 2, 'selected': False, 'text': '<p>It\'s unbelievable how much effort you can spend with IClonable interface - especially if you have heavy class hierarchies. Also MemberwiseClone works somehow oddly - it does not exactly clone even normal List type kind of structures.</p>\n\n<p>And of course most interesting dilemma for serialization is to serialize back references - e.g. class hierarchies where you have child-parent relationships.\nI doubt that binary serializer will be able to help you in this case. (It will end up with recursive loops + stack overflow).</p>\n\n<p>I somehow liked solution proposed here: <a href="https://stackoverflow.com/questions/129389/how-do-you-do-a-deep-copy-an-object-in-net-c-specifically">How do you do a deep copy of an object in .NET (C# specifically)?</a></p>\n\n<p>however - it did not support Lists, added that support, also took into account re-parenting. \nFor parenting only rule which I have made that field or property should be named "parent", then it will be ignored by DeepClone. You might want to decide your own rules for back-references - for tree hierarchies it might be "left/right", etc...</p>\n\n<p>Here is whole code snippet including test code: </p>\n\n<pre><code>using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Reflection;\nusing System.Text;\n\nnamespace TestDeepClone\n{\n class Program\n {\n static void Main(string[] args)\n {\n A a = new A();\n a.name = "main_A";\n a.b_list.Add(new B(a) { name = "b1" });\n a.b_list.Add(new B(a) { name = "b2" });\n\n A a2 = (A)a.DeepClone();\n a2.name = "second_A";\n\n // Perform re-parenting manually after deep copy.\n foreach( var b in a2.b_list )\n b.parent = a2;\n\n\n Debug.WriteLine("ok");\n\n }\n }\n\n public class A\n {\n public String name = "one";\n public List<String> list = new List<string>();\n public List<String> null_list;\n public List<B> b_list = new List<B>();\n private int private_pleaseCopyMeAsWell = 5;\n\n public override string ToString()\n {\n return "A(" + name + ")";\n }\n }\n\n public class B\n {\n public B() { }\n public B(A _parent) { parent = _parent; }\n public A parent;\n public String name = "two";\n }\n\n\n public static class ReflectionEx\n {\n public static Type GetUnderlyingType(this MemberInfo member)\n {\n Type type;\n switch (member.MemberType)\n {\n case MemberTypes.Field:\n type = ((FieldInfo)member).FieldType;\n break;\n case MemberTypes.Property:\n type = ((PropertyInfo)member).PropertyType;\n break;\n case MemberTypes.Event:\n type = ((EventInfo)member).EventHandlerType;\n break;\n default:\n throw new ArgumentException("member must be if type FieldInfo, PropertyInfo or EventInfo", "member");\n }\n return Nullable.GetUnderlyingType(type) ?? type;\n }\n\n /// <summary>\n /// Gets fields and properties into one array.\n /// Order of properties / fields will be preserved in order of appearance in class / struct. (MetadataToken is used for sorting such cases)\n /// </summary>\n /// <param name="type">Type from which to get</param>\n /// <returns>array of fields and properties</returns>\n public static MemberInfo[] GetFieldsAndProperties(this Type type)\n {\n List<MemberInfo> fps = new List<MemberInfo>();\n fps.AddRange(type.GetFields());\n fps.AddRange(type.GetProperties());\n fps = fps.OrderBy(x => x.MetadataToken).ToList();\n return fps.ToArray();\n }\n\n public static object GetValue(this MemberInfo member, object target)\n {\n if (member is PropertyInfo)\n {\n return (member as PropertyInfo).GetValue(target, null);\n }\n else if (member is FieldInfo)\n {\n return (member as FieldInfo).GetValue(target);\n }\n else\n {\n throw new Exception("member must be either PropertyInfo or FieldInfo");\n }\n }\n\n public static void SetValue(this MemberInfo member, object target, object value)\n {\n if (member is PropertyInfo)\n {\n (member as PropertyInfo).SetValue(target, value, null);\n }\n else if (member is FieldInfo)\n {\n (member as FieldInfo).SetValue(target, value);\n }\n else\n {\n throw new Exception("destinationMember must be either PropertyInfo or FieldInfo");\n }\n }\n\n /// <summary>\n /// Deep clones specific object.\n /// Analogue can be found here: https://stackoverflow.com/questions/129389/how-do-you-do-a-deep-copy-an-object-in-net-c-specifically\n /// This is now improved version (list support added)\n /// </summary>\n /// <param name="obj">object to be cloned</param>\n /// <returns>full copy of object.</returns>\n public static object DeepClone(this object obj)\n {\n if (obj == null)\n return null;\n\n Type type = obj.GetType();\n\n if (obj is IList)\n {\n IList list = ((IList)obj);\n IList newlist = (IList)Activator.CreateInstance(obj.GetType(), list.Count);\n\n foreach (object elem in list)\n newlist.Add(DeepClone(elem));\n\n return newlist;\n } //if\n\n if (type.IsValueType || type == typeof(string))\n {\n return obj;\n }\n else if (type.IsArray)\n {\n Type elementType = Type.GetType(type.FullName.Replace("[]", string.Empty));\n var array = obj as Array;\n Array copied = Array.CreateInstance(elementType, array.Length);\n\n for (int i = 0; i < array.Length; i++)\n copied.SetValue(DeepClone(array.GetValue(i)), i);\n\n return Convert.ChangeType(copied, obj.GetType());\n }\n else if (type.IsClass)\n {\n object toret = Activator.CreateInstance(obj.GetType());\n\n MemberInfo[] fields = type.GetFieldsAndProperties();\n foreach (MemberInfo field in fields)\n {\n // Don\'t clone parent back-reference classes. (Using special kind of naming \'parent\' \n // to indicate child\'s parent class.\n if (field.Name == "parent")\n {\n continue;\n }\n\n object fieldValue = field.GetValue(obj);\n\n if (fieldValue == null)\n continue;\n\n field.SetValue(toret, DeepClone(fieldValue));\n }\n\n return toret;\n }\n else\n {\n // Don\'t know that type, don\'t know how to clone it.\n if (Debugger.IsAttached)\n Debugger.Break();\n\n return null;\n }\n } //DeepClone\n }\n\n}\n</code></pre>\n'}, {'answer_id': 31223335, 'author': 'Contango', 'author_id': 107409, 'author_profile': 'https://Stackoverflow.com/users/107409', 'pm_score': 4, 'selected': False, 'text': '<h3>Q. Why would I choose this answer?</h3>\n<ul>\n<li>Choose this answer if you want the fastest speed .NET is capable of.</li>\n<li>Ignore this answer if you want a really, really easy method of cloning.</li>\n</ul>\n<p>In other words, <a href="http://c2.com/cgi/wiki?PrematureOptimization" rel="noreferrer">go with another answer unless you have a performance bottleneck that needs fixing, and you can prove it with a profiler</a>.</p>\n<h3>10x faster than other methods</h3>\n<p>The following method of performing a deep clone is:</p>\n<ul>\n<li>10x faster than anything that involves serialization/deserialization;</li>\n<li>Pretty darn close to the theoretical maximum speed .NET is capable of.</li>\n</ul>\n<h3>And the method ...</h3>\n<p>For ultimate speed, you can use <strong>Nested MemberwiseClone to do a deep copy</strong>. Its almost the same speed as copying a value struct, and is much faster than (a) reflection or (b) serialization (as described in other answers on this page).</p>\n<p>Note that <strong>if</strong> you use <strong>Nested MemberwiseClone for a deep copy</strong>, you have to manually implement a ShallowCopy for each nested level in the class, and a DeepCopy which calls all said ShallowCopy methods to create a complete clone. This is simple: only a few lines in total, see the demo code below.</p>\n<p>Here is the output of the code showing the relative performance difference for 100,000 clones:</p>\n<ul>\n<li>1.08 seconds for Nested MemberwiseClone on nested structs</li>\n<li>4.77 seconds for Nested MemberwiseClone on nested classes</li>\n<li>39.93 seconds for Serialization/Deserialization</li>\n</ul>\n<p>Using Nested MemberwiseClone on a class almost as fast as copying a struct, and copying a struct is pretty darn close to the theoretical maximum speed .NET is capable of.</p>\n<pre><code>Demo 1 of shallow and deep copy, using classes and MemberwiseClone:\n Create Bob\n Bob.Age=30, Bob.Purchase.Description=Lamborghini\n Clone Bob >> BobsSon\n Adjust BobsSon details\n BobsSon.Age=2, BobsSon.Purchase.Description=Toy car\n Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:\n Bob.Age=30, Bob.Purchase.Description=Lamborghini\n Elapsed time: 00:00:04.7795670,30000000\n\nDemo 2 of shallow and deep copy, using structs and value copying:\n Create Bob\n Bob.Age=30, Bob.Purchase.Description=Lamborghini\n Clone Bob >> BobsSon\n Adjust BobsSon details:\n BobsSon.Age=2, BobsSon.Purchase.Description=Toy car\n Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:\n Bob.Age=30, Bob.Purchase.Description=Lamborghini\n Elapsed time: 00:00:01.0875454,30000000\n\nDemo 3 of deep copy, using class and serialize/deserialize:\n Elapsed time: 00:00:39.9339425,30000000\n</code></pre>\n<p>To understand how to do a deep copy using MemberwiseCopy, here is the demo project that was used to generate the times above:</p>\n<pre><code>// Nested MemberwiseClone example. \n// Added to demo how to deep copy a reference class.\n[Serializable] // Not required if using MemberwiseClone, only used for speed comparison using serialization.\npublic class Person\n{\n public Person(int age, string description)\n {\n this.Age = age;\n this.Purchase.Description = description;\n }\n [Serializable] // Not required if using MemberwiseClone\n public class PurchaseType\n {\n public string Description;\n public PurchaseType ShallowCopy()\n {\n return (PurchaseType)this.MemberwiseClone();\n }\n }\n public PurchaseType Purchase = new PurchaseType();\n public int Age;\n // Add this if using nested MemberwiseClone.\n // This is a class, which is a reference type, so cloning is more difficult.\n public Person ShallowCopy()\n {\n return (Person)this.MemberwiseClone();\n }\n // Add this if using nested MemberwiseClone.\n // This is a class, which is a reference type, so cloning is more difficult.\n public Person DeepCopy()\n {\n // Clone the root ...\n Person other = (Person) this.MemberwiseClone();\n // ... then clone the nested class.\n other.Purchase = this.Purchase.ShallowCopy();\n return other;\n }\n}\n// Added to demo how to copy a value struct (this is easy - a deep copy happens by default)\npublic struct PersonStruct\n{\n public PersonStruct(int age, string description)\n {\n this.Age = age;\n this.Purchase.Description = description;\n }\n public struct PurchaseType\n {\n public string Description;\n }\n public PurchaseType Purchase;\n public int Age;\n // This is a struct, which is a value type, so everything is a clone by default.\n public PersonStruct ShallowCopy()\n {\n return (PersonStruct)this;\n }\n // This is a struct, which is a value type, so everything is a clone by default.\n public PersonStruct DeepCopy()\n {\n return (PersonStruct)this;\n }\n}\n// Added only for a speed comparison.\npublic class MyDeepCopy\n{\n public static T DeepCopy<T>(T obj)\n {\n object result = null;\n using (var ms = new MemoryStream())\n {\n var formatter = new BinaryFormatter();\n formatter.Serialize(ms, obj);\n ms.Position = 0;\n result = (T)formatter.Deserialize(ms);\n ms.Close();\n }\n return (T)result;\n }\n}\n</code></pre>\n<p>Then, call the demo from main:</p>\n<pre><code>void MyMain(string[] args)\n{\n {\n Console.Write("Demo 1 of shallow and deep copy, using classes and MemberwiseCopy:\\n");\n var Bob = new Person(30, "Lamborghini");\n Console.Write(" Create Bob\\n");\n Console.Write(" Bob.Age={0}, Bob.Purchase.Description={1}\\n", Bob.Age, Bob.Purchase.Description);\n Console.Write(" Clone Bob >> BobsSon\\n");\n var BobsSon = Bob.DeepCopy();\n Console.Write(" Adjust BobsSon details\\n");\n BobsSon.Age = 2;\n BobsSon.Purchase.Description = "Toy car";\n Console.Write(" BobsSon.Age={0}, BobsSon.Purchase.Description={1}\\n", BobsSon.Age, BobsSon.Purchase.Description);\n Console.Write(" Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:\\n");\n Console.Write(" Bob.Age={0}, Bob.Purchase.Description={1}\\n", Bob.Age, Bob.Purchase.Description);\n Debug.Assert(Bob.Age == 30);\n Debug.Assert(Bob.Purchase.Description == "Lamborghini");\n var sw = new Stopwatch();\n sw.Start();\n int total = 0;\n for (int i = 0; i < 100000; i++)\n {\n var n = Bob.DeepCopy();\n total += n.Age;\n }\n Console.Write(" Elapsed time: {0},{1}\\n\\n", sw.Elapsed, total);\n }\n { \n Console.Write("Demo 2 of shallow and deep copy, using structs:\\n");\n var Bob = new PersonStruct(30, "Lamborghini");\n Console.Write(" Create Bob\\n");\n Console.Write(" Bob.Age={0}, Bob.Purchase.Description={1}\\n", Bob.Age, Bob.Purchase.Description);\n Console.Write(" Clone Bob >> BobsSon\\n");\n var BobsSon = Bob.DeepCopy();\n Console.Write(" Adjust BobsSon details:\\n");\n BobsSon.Age = 2;\n BobsSon.Purchase.Description = "Toy car";\n Console.Write(" BobsSon.Age={0}, BobsSon.Purchase.Description={1}\\n", BobsSon.Age, BobsSon.Purchase.Description);\n Console.Write(" Proof of deep copy: If BobsSon is a true clone, then adjusting BobsSon details will not affect Bob:\\n");\n Console.Write(" Bob.Age={0}, Bob.Purchase.Description={1}\\n", Bob.Age, Bob.Purchase.Description); \n Debug.Assert(Bob.Age == 30);\n Debug.Assert(Bob.Purchase.Description == "Lamborghini");\n var sw = new Stopwatch();\n sw.Start();\n int total = 0;\n for (int i = 0; i < 100000; i++)\n {\n var n = Bob.DeepCopy();\n total += n.Age;\n }\n Console.Write(" Elapsed time: {0},{1}\\n\\n", sw.Elapsed, total);\n }\n {\n Console.Write("Demo 3 of deep copy, using class and serialize/deserialize:\\n");\n int total = 0;\n var sw = new Stopwatch();\n sw.Start();\n var Bob = new Person(30, "Lamborghini");\n for (int i = 0; i < 100000; i++)\n {\n var BobsSon = MyDeepCopy.DeepCopy<Person>(Bob);\n total += BobsSon.Age;\n }\n Console.Write(" Elapsed time: {0},{1}\\n", sw.Elapsed, total);\n }\n Console.ReadKey();\n}\n</code></pre>\n<p>Again, note that <strong>if</strong> you use <strong>Nested MemberwiseClone for a deep copy</strong>, you have to manually implement a ShallowCopy for each nested level in the class, and a DeepCopy which calls all said ShallowCopy methods to create a complete clone. This is simple: only a few lines in total, see the demo code above.</p>\n<h3>Value types vs. References Types</h3>\n<p>Note that when it comes to cloning an object, there is is a big difference between a "<strong>struct</strong>" and a "<strong>class</strong>":</p>\n<ul>\n<li>If you have a "<strong>struct</strong>", it\'s a <strong>value type</strong> so you can just copy it, and the contents will be cloned (but it will only make a shallow clone unless you use the techniques in this post).</li>\n<li>If you have a "<strong>class</strong>", it\'s a <strong>reference type</strong>, so if you copy it, all you are doing is copying the pointer to it. To create a true clone, you have to be more creative, and use <a href="https://msdn.microsoft.com/en-us/library/system.object.memberwiseclone(v=vs.110).aspx" rel="noreferrer">differences between value types and references types</a> which creates another copy of the original object in memory.</li>\n</ul>\n<p>See <a href="https://msdn.microsoft.com/en-us/library/system.object.memberwiseclone(v=vs.110).aspx" rel="noreferrer">differences between value types and references types</a>.</p>\n<h3>Checksums to aid in debugging</h3>\n<ul>\n<li>Cloning objects incorrectly can lead to very difficult-to-pin-down bugs. In production code, I tend to implement a checksum to double check that the object has been cloned properly, and hasn\'t been corrupted by another reference to it. This checksum can be switched off in Release mode.</li>\n<li>I find this method quite useful: often, you only want to clone parts of the object, not the entire thing.</li>\n</ul>\n<h3>Really useful for decoupling many threads from many other threads</h3>\n<p>One excellent use case for this code is feeding clones of a nested class or struct into a queue, to implement the producer / consumer pattern.</p>\n<ul>\n<li>We can have one (or more) threads modifying a class that they own, then pushing a complete copy of this class into a <code>ConcurrentQueue</code>.</li>\n<li>We then have one (or more) threads pulling copies of these classes out and dealing with them.</li>\n</ul>\n<p>This works extremely well in practice, and allows us to decouple many threads (the producers) from one or more threads (the consumers).</p>\n<p>And this method is blindingly fast too: if we use nested structs, it\'s 35x faster than serializing/deserializing nested classes, and allows us to take advantage of all of the threads available on the machine.</p>\n<h1>Update</h1>\n<p>Apparently, ExpressMapper is as fast, if not faster, than hand coding such as above. I might have to see how they compare with a profiler.</p>\n'}, {'answer_id': 32155648, 'author': 'KeyNone', 'author_id': 1807643, 'author_profile': 'https://Stackoverflow.com/users/1807643', 'pm_score': 1, 'selected': False, 'text': '<p>When using Marc Gravells protobuf-net as your serializer the accepted answer needs some slight modifications, as the object to copy won\'t be attributed with <code>[Serializable]</code> and, therefore, isn\'t serializable and the Clone-method will throw an exception.<br>\nI modified it to work with protobuf-net:</p>\n\n<pre><code>public static T Clone<T>(this T source)\n{\n if(Attribute.GetCustomAttribute(typeof(T), typeof(ProtoBuf.ProtoContractAttribute))\n == null)\n {\n throw new ArgumentException("Type has no ProtoContract!", "source");\n }\n\n if(Object.ReferenceEquals(source, null))\n {\n return default(T);\n }\n\n IFormatter formatter = ProtoBuf.Serializer.CreateFormatter<T>();\n using (Stream stream = new MemoryStream())\n {\n formatter.Serialize(stream, source);\n stream.Seek(0, SeekOrigin.Begin);\n return (T)formatter.Deserialize(stream);\n }\n}\n</code></pre>\n\n<p>This checks for the presence of a <code>[ProtoContract]</code> attribute and uses protobufs own formatter to serialize the object.</p>\n'}, {'answer_id': 34368738, 'author': 'Roma Borodov', 'author_id': 4711853, 'author_profile': 'https://Stackoverflow.com/users/4711853', 'pm_score': 2, 'selected': False, 'text': '<p>Ok, there are some obvious example with reflection in this post, BUT reflection is usually slow, until you start to cache it properly.</p>\n\n<p>if you\'ll cache it properly, than it\'ll deep clone 1000000 object by 4,6s (measured by Watcher).</p>\n\n<pre><code>static readonly Dictionary<Type, PropertyInfo[]> ProperyList = new Dictionary<Type, PropertyInfo[]>();\n</code></pre>\n\n<p>than you take cached properties or add new to dictionary and use them simply</p>\n\n<pre><code>foreach (var prop in propList)\n{\n var value = prop.GetValue(source, null); \n prop.SetValue(copyInstance, value, null);\n}\n</code></pre>\n\n<p>full code check in my post in another answer</p>\n\n<p><a href="https://stackoverflow.com/a/34365709/4711853">https://stackoverflow.com/a/34365709/4711853</a></p>\n'}, {'answer_id': 34998894, 'author': 'kalisohn', 'author_id': 2792931, 'author_profile': 'https://Stackoverflow.com/users/2792931', 'pm_score': 3, 'selected': False, 'text': '<p>As I couldn\'t find a cloner that meets all my requirements in different projects, I created a deep cloner that can be configured and adapted to different code structures instead of adapting my code to meet the cloners requirements. Its achieved by adding annotations to the code that shall be cloned or you just leave the code as it is to have the default behaviour. It uses reflection, type caches and is based on <a href="https://fasterflect.codeplex.com/" rel="noreferrer">fasterflect</a>. The cloning process is very fast for a huge amount of data and a high object hierarchy (compared to other reflection/serialization based algorithms). </p>\n\n<p><a href="https://github.com/kalisohn/CloneBehave" rel="noreferrer">https://github.com/kalisohn/CloneBehave</a></p>\n\n<p>Also available as a nuget package:\n<a href="https://www.nuget.org/packages/Clone.Behave/1.0.0" rel="noreferrer">https://www.nuget.org/packages/Clone.Behave/1.0.0</a></p>\n\n<p>For example: The following code will deepClone Address, but only perform a shallow copy of the _currentJob field. </p>\n\n<pre><code>public class Person \n{\n [DeepClone(DeepCloneBehavior.Shallow)]\n private Job _currentJob; \n\n public string Name { get; set; }\n\n public Job CurrentJob \n { \n get{ return _currentJob; }\n set{ _currentJob = value; }\n }\n\n public Person Manager { get; set; }\n}\n\npublic class Address \n{ \n public Person PersonLivingHere { get; set; }\n}\n\nAddress adr = new Address();\nadr.PersonLivingHere = new Person("John");\nadr.PersonLivingHere.BestFriend = new Person("James");\nadr.PersonLivingHere.CurrentJob = new Job("Programmer");\n\nAddress adrClone = adr.Clone();\n\n//RESULT\nadr.PersonLivingHere == adrClone.PersonLivingHere //false\nadr.PersonLivingHere.Manager == adrClone.PersonLivingHere.Manager //false\nadr.PersonLivingHere.CurrentJob == adrClone.PersonLivingHere.CurrentJob //true\nadr.PersonLivingHere.CurrentJob.AnyProperty == adrClone.PersonLivingHere.CurrentJob.AnyProperty //true\n</code></pre>\n'}, {'answer_id': 36575152, 'author': 'GorvGoyl', 'author_id': 3073272, 'author_profile': 'https://Stackoverflow.com/users/3073272', 'pm_score': 3, 'selected': False, 'text': '<p>This method solved the problem for me:</p>\n\n<pre><code>private static MyObj DeepCopy(MyObj source)\n {\n\n var DeserializeSettings = new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace };\n\n return JsonConvert.DeserializeObject<MyObj >(JsonConvert.SerializeObject(source), DeserializeSettings);\n\n }\n</code></pre>\n\n<p>Use it like this: <code>MyObj a = DeepCopy(b);</code></p>\n'}, {'answer_id': 37498183, 'author': 'Stacked', 'author_id': 1372621, 'author_profile': 'https://Stackoverflow.com/users/1372621', 'pm_score': 4, 'selected': False, 'text': '<p>Keep things simple and use <a href="http://automapper.org/" rel="nofollow noreferrer">AutoMapper</a> as others mentioned, it\'s a simple little library to map one object to another... To copy an object to another with the same type, all you need is three lines of code:</p>\n\n<pre><code>MyType source = new MyType();\nMapper.CreateMap<MyType, MyType>();\nMyType target = Mapper.Map<MyType, MyType>(source);\n</code></pre>\n\n<p>The target object is now a copy of the source object.\nNot simple enough? Create an extension method to use everywhere in your solution:</p>\n\n<pre><code>public static T Copy<T>(this T source)\n{\n T copy = default(T);\n Mapper.CreateMap<T, T>();\n copy = Mapper.Map<T, T>(source);\n return copy;\n}\n</code></pre>\n\n<p>The extension method can be used as follow:</p>\n\n<pre><code>MyType copy = source.Copy();\n</code></pre>\n'}, {'answer_id': 37736016, 'author': 'Toxantron', 'author_id': 6082960, 'author_profile': 'https://Stackoverflow.com/users/6082960', 'pm_score': 3, 'selected': False, 'text': '<h1>Code Generator</h1>\n\n<p>We have seen a lot of ideas from serialization over manual implementation to reflection and I want to propose a totally different approach using the <a href="https://github.com/Toxantron/CGbR#cloneable" rel="noreferrer">CGbR Code Generator</a>. The generate clone method is memory and CPU efficient and therefor 300x faster as the standard DataContractSerializer.</p>\n\n<p>All you need is a partial class definition with <code>ICloneable</code> and the generator does the rest:</p>\n\n<pre><code>public partial class Root : ICloneable\n{\n public Root(int number)\n {\n _number = number;\n }\n private int _number;\n\n public Partial[] Partials { get; set; }\n\n public IList<ulong> Numbers { get; set; }\n\n public object Clone()\n {\n return Clone(true);\n }\n\n private Root()\n {\n }\n} \n\npublic partial class Root\n{\n public Root Clone(bool deep)\n {\n var copy = new Root();\n // All value types can be simply copied\n copy._number = _number; \n if (deep)\n {\n // In a deep clone the references are cloned \n var tempPartials = new Partial[Partials.Length];\n for (var i = 0; i < Partials.Length; i++)\n {\n var value = Partials[i];\n value = value.Clone(true);\n tempPartials[i] = value;\n }\n copy.Partials = tempPartials;\n var tempNumbers = new List<ulong>(Numbers.Count);\n for (var i = 0; i < Numbers.Count; i++)\n {\n var value = Numbers[i];\n tempNumbers.Add(value);\n }\n copy.Numbers = tempNumbers;\n }\n else\n {\n // In a shallow clone only references are copied\n copy.Partials = Partials; \n copy.Numbers = Numbers; \n }\n return copy;\n }\n}\n</code></pre>\n\n<p><strong>Note:</strong> Latest version has a more null checks, but I left them out for better understanding.</p>\n'}, {'answer_id': 38660465, 'author': 'Daniele D.', 'author_id': 4454567, 'author_profile': 'https://Stackoverflow.com/users/4454567', 'pm_score': 3, 'selected': False, 'text': "<p>Here a solution fast and easy that worked for me without relaying on Serialization/Deserialization. </p>\n\n<pre><code>public class MyClass\n{\n public virtual MyClass DeepClone()\n {\n var returnObj = (MyClass)MemberwiseClone();\n var type = returnObj.GetType();\n var fieldInfoArray = type.GetRuntimeFields().ToArray();\n\n foreach (var fieldInfo in fieldInfoArray)\n {\n object sourceFieldValue = fieldInfo.GetValue(this);\n if (!(sourceFieldValue is MyClass))\n {\n continue;\n }\n\n var sourceObj = (MyClass)sourceFieldValue;\n var clonedObj = sourceObj.DeepClone();\n fieldInfo.SetValue(returnObj, clonedObj);\n }\n return returnObj;\n }\n}\n</code></pre>\n\n<p><strong>EDIT</strong>:\nrequires </p>\n\n<pre><code> using System.Linq;\n using System.Reflection;\n</code></pre>\n\n<p>That's How I used it</p>\n\n<pre><code>public MyClass Clone(MyClass theObjectIneededToClone)\n{\n MyClass clonedObj = theObjectIneededToClone.DeepClone();\n}\n</code></pre>\n"}, {'answer_id': 38754644, 'author': 'frakon', 'author_id': 2094687, 'author_profile': 'https://Stackoverflow.com/users/2094687', 'pm_score': 5, 'selected': False, 'text': '<p>The best is to implement an <strong>extension method</strong> like</p>\n\n<pre><code>public static T DeepClone<T>(this T originalObject)\n{ /* the cloning code */ }\n</code></pre>\n\n<p>and then use it anywhere in the solution by</p>\n\n<pre><code>var copy = anyObject.DeepClone();\n</code></pre>\n\n<p>We can have the following three implementations:</p>\n\n<ol>\n<li><a href="https://stackoverflow.com/a/129395/2094687"><strong>By Serialization</strong></a> (the shortest code)</li>\n<li><a href="https://github.com/Burtsev-Alexey/net-object-deep-copy/" rel="noreferrer"><strong>By Reflection</strong></a> - <strong>5x faster</strong></li>\n<li><a href="http://www.codeproject.com/Articles/1111658/Fast-Deep-Copy-by-Expression-Trees-C-Sharp" rel="noreferrer"><strong>By Expression Trees</strong></a> - <strong>20x faster</strong></li>\n</ol>\n\n<p>All linked methods are well working and were deeply tested.</p>\n'}, {'answer_id': 39044123, 'author': 'Sudhanva Kotabagi', 'author_id': 5198209, 'author_profile': 'https://Stackoverflow.com/users/5198209', 'pm_score': 2, 'selected': False, 'text': '<p>I think you can try this.</p>\n\n<pre><code>MyObject myObj = GetMyObj(); // Create and fill a new object\nMyObject newObj = new MyObject(myObj); //DeepClone it\n</code></pre>\n'}, {'answer_id': 41988090, 'author': 'gaa', 'author_id': 1842492, 'author_profile': 'https://Stackoverflow.com/users/1842492', 'pm_score': -1, 'selected': False, 'text': '<p>I know that this question and <a href="https://stackoverflow.com/a/78612/1842492">answer</a> sits here for a while and following is not quite answer but rather observation, to which I came across recently when I was checking whether indeed privates are not being cloned (I wouldn\'t be myself if I have not ;) when I happily copy-pasted @johnc <a href="https://stackoverflow.com/a/78612/1842492">updated answer</a>.</p>\n\n<p>I simply made myself extension method (which is pretty much copy-pasted form aforementioned answer):</p>\n\n<pre><code>public static class CloneThroughJsonExtension\n{\n private static readonly JsonSerializerSettings DeserializeSettings = new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace };\n\n public static T CloneThroughJson<T>(this T source)\n {\n return ReferenceEquals(source, null) ? default(T) : JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source), DeserializeSettings);\n }\n}\n</code></pre>\n\n<p>and dropped naively class like this (in fact there was more of those but they are unrelated):</p>\n\n<pre><code>public class WhatTheHeck\n{\n public string PrivateSet { get; private set; } // matches ctor param name\n\n public string GetOnly { get; } // matches ctor param name\n\n private readonly string _indirectField;\n public string Indirect => $"Inception of: {_indirectField} "; // matches ctor param name\n public string RealIndirectFieldVaule => _indirectField;\n\n public WhatTheHeck(string privateSet, string getOnly, string indirect)\n {\n PrivateSet = privateSet;\n GetOnly = getOnly;\n _indirectField = indirect;\n }\n}\n</code></pre>\n\n<p>and code like this:</p>\n\n<pre><code>var clone = new WhatTheHeck("Private-Set-Prop cloned!", "Get-Only-Prop cloned!", "Indirect-Field clonned!").CloneThroughJson();\nConsole.WriteLine($"1. {clone.PrivateSet}");\nConsole.WriteLine($"2. {clone.GetOnly}");\nConsole.WriteLine($"3.1. {clone.Indirect}");\nConsole.WriteLine($"3.2. {clone.RealIndirectFieldVaule}");\n</code></pre>\n\n<p>resulted in:</p>\n\n<pre><code>1. Private-Set-Prop cloned!\n2. Get-Only-Prop cloned!\n3.1. Inception of: Inception of: Indirect-Field cloned!\n3.2. Inception of: Indirect-Field cloned!\n</code></pre>\n\n<p>I was whole like: WHAT THE F... so I grabbed Newtonsoft.Json Github repo and started to dig.\nWhat it comes out, is that: while deserializing a type which happens to have only one ctor and its param names match (<a href="https://github.com/JamesNK/Newtonsoft.Json/blob/cf6a917a46b532558578c53d34cdc4f39ec0560a/Src/Newtonsoft.Json/Serialization/JsonPropertyCollection.cs#L126" rel="nofollow noreferrer">case insensitive</a>) public property names they will be passed to ctor as those params. Some clues can be found in the code <a href="https://github.com/JamesNK/Newtonsoft.Json/blob/744be1a712ee0e0bbc264b800368a7b7f5026884/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs#L606" rel="nofollow noreferrer">here</a> and <a href="https://github.com/JamesNK/Newtonsoft.Json/blob/744be1a712ee0e0bbc264b800368a7b7f5026884/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs#L309" rel="nofollow noreferrer">here</a>.</p>\n\n<p><strong>Bottom line</strong></p>\n\n<p>I know that it is rather not common case and example code is bit abusive, but hey! It got me by surprise when I was checking whether there is any dragon waiting in the bushes to jump out and bite me in the ass. ;)</p>\n'}, {'answer_id': 43569318, 'author': 'Mauro Sampietro', 'author_id': 711061, 'author_profile': 'https://Stackoverflow.com/users/711061', 'pm_score': 2, 'selected': False, 'text': '<p>A mapper performs a deep-copy. Foreach member of your object it creates a new object and assign all of its values. It works recursively on each non-primitive inner member.</p>\n\n<p>I suggest you one of the fastest, currently actively developed ones.\nI suggest UltraMapper <a href="https://github.com/maurosampietro/UltraMapper" rel="nofollow noreferrer">https://github.com/maurosampietro/UltraMapper</a></p>\n\n<p>Nuget packages: <a href="https://www.nuget.org/packages/UltraMapper/" rel="nofollow noreferrer">https://www.nuget.org/packages/UltraMapper/</a></p>\n'}, {'answer_id': 45557629, 'author': 'lindexi', 'author_id': 6116637, 'author_profile': 'https://Stackoverflow.com/users/6116637', 'pm_score': 1, 'selected': False, 'text': '<p>I found a new way to do it that is Emit.</p>\n\n<p>We can use Emit to add the IL to app and run it. But I dont think its a good way for I want to perfect this that I write my answer.</p>\n\n<p>The Emit can see the <a href="https://msdn.microsoft.com/en-us/library/system.reflection.emit(v=vs.110).aspx" rel="nofollow noreferrer">official document</a> and <a href="http://www.c-sharpcorner.com/uploadfile/puranindia/reflection-and-reflection-emit-in-C-Sharp/" rel="nofollow noreferrer">Guide</a></p>\n\n<p>You should learn some IL to read the code. I will write the code that can copy the property in class.</p>\n\n<pre><code>public static class Clone\n{ \n // ReSharper disable once InconsistentNaming\n public static void CloneObjectWithIL<T>(T source, T los)\n {\n //see http://lindexi.oschina.io/lindexi/post/C-%E4%BD%BF%E7%94%A8Emit%E6%B7%B1%E5%85%8B%E9%9A%86/\n if (CachedIl.ContainsKey(typeof(T)))\n {\n ((Action<T, T>) CachedIl[typeof(T)])(source, los);\n return;\n }\n var dynamicMethod = new DynamicMethod("Clone", null, new[] { typeof(T), typeof(T) });\n ILGenerator generator = dynamicMethod.GetILGenerator();\n\n foreach (var temp in typeof(T).GetProperties().Where(temp => temp.CanRead && temp.CanWrite))\n {\n //do not copy static that will except\n if (temp.GetAccessors(true)[0].IsStatic)\n {\n continue;\n }\n\n generator.Emit(OpCodes.Ldarg_1);// los\n generator.Emit(OpCodes.Ldarg_0);// s\n generator.Emit(OpCodes.Callvirt, temp.GetMethod);\n generator.Emit(OpCodes.Callvirt, temp.SetMethod);\n }\n generator.Emit(OpCodes.Ret);\n var clone = (Action<T, T>) dynamicMethod.CreateDelegate(typeof(Action<T, T>));\n CachedIl[typeof(T)] = clone;\n clone(source, los);\n }\n\n private static Dictionary<Type, Delegate> CachedIl { set; get; } = new Dictionary<Type, Delegate>();\n}\n</code></pre>\n\n<p>The code can be deep copy but it can copy the property. If you want to make it to deep copy that you can change it for the IL is too hard that I cant do it.</p>\n'}, {'answer_id': 49276795, 'author': 'Matthew Watson', 'author_id': 106159, 'author_profile': 'https://Stackoverflow.com/users/106159', 'pm_score': 2, 'selected': False, 'text': "<p>Yet another JSON.NET answer. This version works with classes that don't implement ISerializable.</p>\n\n<pre><code>public static class Cloner\n{\n public static T Clone<T>(T source)\n {\n if (ReferenceEquals(source, null))\n return default(T);\n\n var settings = new JsonSerializerSettings { ContractResolver = new ContractResolver() };\n\n return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source, settings), settings);\n }\n\n class ContractResolver : DefaultContractResolver\n {\n protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)\n {\n var props = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)\n .Select(p => base.CreateProperty(p, memberSerialization))\n .Union(type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)\n .Select(f => base.CreateProperty(f, memberSerialization)))\n .ToList();\n props.ForEach(p => { p.Writable = true; p.Readable = true; });\n return props;\n }\n }\n}\n</code></pre>\n"}, {'answer_id': 50150204, 'author': 'Sameera R.', 'author_id': 2016932, 'author_profile': 'https://Stackoverflow.com/users/2016932', 'pm_score': 1, 'selected': False, 'text': '<p>C# Extension that\'ll support for "not <strong>ISerializable</strong>" types too.</p>\n\n<pre><code> public static class AppExtensions\n { \n public static T DeepClone<T>(this T a)\n {\n using (var stream = new MemoryStream())\n {\n var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));\n\n serializer.Serialize(stream, a);\n stream.Position = 0;\n return (T)serializer.Deserialize(stream);\n }\n } \n }\n</code></pre>\n\n<p>Usage</p>\n\n<pre><code> var obj2 = obj1.DeepClone()\n</code></pre>\n'}, {'answer_id': 52780057, 'author': 'qubits', 'author_id': 1444319, 'author_profile': 'https://Stackoverflow.com/users/1444319', 'pm_score': 2, 'selected': False, 'text': "<p>The generic approaches are all technically valid, but I just wanted to add a note from myself since we rarely actually need a real deep copy, and I would strongly oppose using generic deep copying in actual business applications since that makes it so you might have many places where the objects are copied and then modified explicitly, its easy to get lost. </p>\n\n<p>In most real-life situations also you want to have as much granular control over the copying process as possible since you are not only coupled to the data access framework but also in practice the copied business objects should rarely be 100% the same. Think an example referenceId's used by the ORM to identify object references, a full deep copy will also copy this id's so while in-memory the objects will be different, as soon as you submit it to the datastore, it will complain, so you will have to modify this properties manually after copying anyway and if the object changes you need to adjust it in all of the places which use the generic deep copying.</p>\n\n<p>Expanding on @cregox answer with ICloneable, what actually is a deep copy? Its just a newly allocated object on the heap that is identical to the original object but occupies a different memory space, as such rather than using a generic cloner functionality why not just create a new object?</p>\n\n<p>I personally use the idea of static factory methods on my domain objects.</p>\n\n<p>Example:</p>\n\n<pre><code> public class Client\n {\n public string Name { get; set; }\n\n protected Client()\n {\n }\n\n public static Client Clone(Client copiedClient)\n {\n return new Client\n {\n Name = copiedClient.Name\n };\n }\n }\n\n public class Shop\n {\n public string Name { get; set; }\n\n public string Address { get; set; }\n\n public ICollection<Client> Clients { get; set; }\n\n public static Shop Clone(Shop copiedShop, string newAddress, ICollection<Client> clients)\n {\n var copiedClients = new List<Client>();\n foreach (var client in copiedShop.Clients)\n {\n copiedClients.Add(Client.Clone(client));\n }\n\n return new Shop\n {\n Name = copiedShop.Name,\n Address = newAddress,\n Clients = copiedClients\n };\n }\n }\n</code></pre>\n\n<p>If someone is looking how he can structure object instantiation while retaining full control over the copying process that's a solution that I have been personally very successful with. The protected constructors also make it so, other developers are forced to use the factory methods which gives a neat single point of object instantiation encapsulating the construction logic inside of the object. You can also overload the method and have several clone logic's for different places if necessary.</p>\n"}, {'answer_id': 53332691, 'author': 'Michael Brown', 'author_id': 1395182, 'author_profile': 'https://Stackoverflow.com/users/1395182', 'pm_score': 3, 'selected': False, 'text': '<p>As nearly all of the answers to this question have been unsatisfactory or plainly don\'t work in my situation, I have authored <a href="https://github.com/replaysMike/AnyClone" rel="noreferrer">AnyClone</a> which is entirely implemented with reflection and solved all of the needs here. I was unable to get serialization to work in a complicated scenario with complex structure, and <code>IClonable</code> is less than ideal - in fact it shouldn\'t even be necessary.</p>\n\n<p>Standard ignore attributes are supported using <code>[IgnoreDataMember]</code>, <code>[NonSerialized]</code>. Supports complex collections, properties without setters, readonly fields etc.</p>\n\n<p>I hope it helps someone else out there who ran into the same problems I did.</p>\n'}, {'answer_id': 56691124, 'author': 'Ted Mucuzany', 'author_id': 11652382, 'author_profile': 'https://Stackoverflow.com/users/11652382', 'pm_score': 2, 'selected': False, 'text': '<p>Deep cloning is about copying <strong>state</strong>. For <code>.net</code> <strong>state</strong> means <strong>fields</strong>.</p>\n\n<p>Let\'s say one have an hierarchy:</p>\n\n<pre><code>static class RandomHelper\n{\n private static readonly Random random = new Random();\n\n public static int Next(int maxValue) => random.Next(maxValue);\n}\n\nclass A\n{\n private readonly int random = RandomHelper.Next(100);\n\n public override string ToString() => $"{typeof(A).Name}.{nameof(random)} = {random}";\n}\n\nclass B : A\n{\n private readonly int random = RandomHelper.Next(100);\n\n public override string ToString() => $"{typeof(B).Name}.{nameof(random)} = {random} {base.ToString()}";\n}\n\nclass C : B\n{\n private readonly int random = RandomHelper.Next(100);\n\n public override string ToString() => $"{typeof(C).Name}.{nameof(random)} = {random} {base.ToString()}";\n}\n</code></pre>\n\n<p>Cloning can be done:</p>\n\n<pre><code>static class DeepCloneExtension\n{\n // consider instance fields, both public and non-public\n private static readonly BindingFlags bindingFlags =\n BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;\n\n public static T DeepClone<T>(this T obj) where T : new()\n {\n var type = obj.GetType();\n var result = (T)Activator.CreateInstance(type);\n\n do\n // copy all fields\n foreach (var field in type.GetFields(bindingFlags))\n field.SetValue(result, field.GetValue(obj));\n // for every level of hierarchy\n while ((type = type.BaseType) != typeof(object));\n\n return result;\n }\n}\n</code></pre>\n\n<p><strong>Demo1</strong>:</p>\n\n<pre><code>Console.WriteLine(new C());\nConsole.WriteLine(new C());\n\nvar c = new C();\nConsole.WriteLine($"{Environment.NewLine}Image: {c}{Environment.NewLine}");\n\nConsole.WriteLine(new C());\nConsole.WriteLine(new C());\n\nConsole.WriteLine($"{Environment.NewLine}Clone: {c.DeepClone()}{Environment.NewLine}");\n\nConsole.WriteLine(new C());\nConsole.WriteLine(new C());\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>C.random = 92 B.random = 66 A.random = 71\nC.random = 36 B.random = 64 A.random = 17\n\nImage: C.random = 96 B.random = 18 A.random = 46\n\nC.random = 60 B.random = 7 A.random = 37\nC.random = 78 B.random = 11 A.random = 18\n\nClone: C.random = 96 B.random = 18 A.random = 46\n\nC.random = 33 B.random = 63 A.random = 38\nC.random = 4 B.random = 5 A.random = 79\n</code></pre>\n\n<p>Notice, all new objects have random values for <code>random</code> field, but <code>clone</code> exactly matches the <code>image</code></p>\n\n<p><strong>Demo2</strong>:</p>\n\n<pre><code>class D\n{\n public event EventHandler Event;\n public void RaiseEvent() => Event?.Invoke(this, EventArgs.Empty);\n}\n\n// ...\n\nvar image = new D();\nConsole.WriteLine($"Created obj #{image.GetHashCode()}");\n\nimage.Event += (sender, e) => Console.WriteLine($"Event from obj #{sender.GetHashCode()}");\nConsole.WriteLine($"Subscribed to event of obj #{image.GetHashCode()}");\n\nimage.RaiseEvent();\nimage.RaiseEvent();\n\nvar clone = image.DeepClone();\nConsole.WriteLine($"obj #{image.GetHashCode()} cloned to obj #{clone.GetHashCode()}");\n\nclone.RaiseEvent();\nimage.RaiseEvent();\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>Created obj #46104728\nSubscribed to event of obj #46104728\nEvent from obj #46104728\nEvent from obj #46104728\nobj #46104728 cloned to obj #12289376\nEvent from obj #12289376\nEvent from obj #46104728\n</code></pre>\n\n<p>Notice, event backing field is copied too and client is subscribed to clone\'s event too.</p>\n'}, {'answer_id': 56805986, 'author': 'Konrad', 'author_id': 2828480, 'author_profile': 'https://Stackoverflow.com/users/2828480', 'pm_score': 1, 'selected': False, 'text': '<p>Using <code>System.Text.Json</code>:</p>\n\n<p><a href="https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/" rel="nofollow noreferrer">https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/</a></p>\n\n<pre><code>public static T DeepCopy<T>(this T source)\n{\n return source == null ? default : JsonSerializer.Parse<T>(JsonSerializer.ToString(source));\n}\n</code></pre>\n\n<p>The new API is using <code>Span<T></code>. This should be fast, would be nice to do some benchmarks.</p>\n\n<p><strong>Note:</strong> there\'s no need for <code>ObjectCreationHandling.Replace</code> like in Json.NET as it will replace collection values by default. You should forget about Json.NET now as everything is going to be replaced with the new official API.</p>\n\n<p>I\'m not sure this will work with private fields.</p>\n'}, {'answer_id': 56933017, 'author': 'alelom', 'author_id': 3873799, 'author_profile': 'https://Stackoverflow.com/users/3873799', 'pm_score': 5, 'selected': False, 'text': '<h2>DeepCloner: Quick, easy, effective NuGet package to solve cloning</h2>\n\n<p>After reading all answers I was surprised no one mentioned this excellent package: </p>\n\n<p><a href="https://github.com/force-net/DeepCloner" rel="noreferrer">DeepCloner GitHub project</a> </p>\n\n<p><a href="https://www.nuget.org/packages/DeepCloner" rel="noreferrer">DeepCloner NuGet package</a></p>\n\n<p>Elaborating a bit on its README, here are the reason why we chose it at work:</p>\n\n<blockquote>\n <ul>\n <li>It can deep or shallow copy </li>\n <li>In deep cloning all object graph is maintained. </li>\n <li>Uses code-generation in runtime, as result cloning is blazingly fast</li>\n <li>Objects copied by internal structure, no methods or ctors called</li>\n <li>You don\'t need to mark classes somehow (like Serializable-attribute, or implement interfaces)</li>\n <li>No requirement to specify object type for cloning. Object can be casted to interface or as an abstract object (e.g. you can clone array of ints as abstract Array or IEnumerable; even null can be cloned without any errors)</li>\n <li>Cloned object doesn\'t have any ability to determine that he is clone (except with very specific methods)</li>\n </ul>\n</blockquote>\n\n<h3>Usage:</h3>\n\n<pre class="lang-cs prettyprint-override"><code>var deepClone = new { Id = 1, Name = "222" }.DeepClone();\nvar shallowClone = new { Id = 1, Name = "222" }.ShallowClone();\n</code></pre>\n\n<h3>Performance:</h3>\n\n<p>The README contains a performance comparison of various cloning libraries and methods: <a href="https://github.com/force-net/DeepCloner#performance" rel="noreferrer">DeepCloner Performance</a>.</p>\n\n<h3>Requirements:</h3>\n\n<ul>\n<li><em>.NET 4.0 or higher or .NET Standard 1.3 (.NET Core)</em></li>\n<li><em>Requires Full Trust permission set or Reflection permission (MemberAccess)</em></li>\n</ul>\n'}, {'answer_id': 57279815, 'author': 'Marcell Toth', 'author_id': 10614791, 'author_profile': 'https://Stackoverflow.com/users/10614791', 'pm_score': 4, 'selected': False, 'text': '<p><em>Disclaimer: I\'m the author of the mentioned package.</em></p>\n\n<p>I was surprised how the top answers to this question in 2019 still use serialization or reflection. </p>\n\n<h2>Serialization is limiting (requires attributes, specific constructors, etc.) and is very slow</h2>\n\n<p><code>BinaryFormatter</code> requires the <code>Serializable</code> attribute, <code>JsonConverter</code> requires a parameterless constructor or attributes, neither handle read only fields or interfaces very well and both are 10-30x slower than necessary.</p>\n\n<h2>Expression Trees</h2>\n\n<p>You can instead use <em>Expression Trees</em> or <em>Reflection.Emit</em> to generate cloning code only once, then use that compiled code instead of slow reflection or serialization.</p>\n\n<p>Having come across the problem myself and seeing no satisfactory solution, I decided to create a package that does just that and <strong>works with every type and is a almost as fast as custom written code</strong>.</p>\n\n<p>You can find the project on GitHub: <a href="https://github.com/marcelltoth/ObjectCloner" rel="noreferrer">https://github.com/marcelltoth/ObjectCloner</a></p>\n\n<h2>Usage</h2>\n\n<p>You can install it from NuGet. Either get the <code>ObjectCloner</code> package and use it as:</p>\n\n<pre class="lang-cs prettyprint-override"><code>var clone = ObjectCloner.DeepClone(original);\n</code></pre>\n\n<p>or if you don\'t mind polluting your object type with extensions get <code>ObjectCloner.Extensions</code> as well and write:</p>\n\n<pre class="lang-cs prettyprint-override"><code>var clone = original.DeepClone();\n</code></pre>\n\n<h2>Performance</h2>\n\n<p>A simple benchmark of cloning a class hierarchy showed performance ~3x faster than using Reflection, ~12x faster than Newtonsoft.Json serialization and ~36x faster than the highly suggested <code>BinaryFormatter</code>.</p>\n'}, {'answer_id': 58975653, 'author': 'Erçin Dedeoğlu', 'author_id': 2426367, 'author_profile': 'https://Stackoverflow.com/users/2426367', 'pm_score': 2, 'selected': False, 'text': '<p>Shortest way but need dependency:</p>\n\n<pre><code>using Newtonsoft.Json;\n public static T Clone<T>(T source) =>\n JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source));\n</code></pre>\n'}, {'answer_id': 61976233, 'author': 'Hidayet R. Colkusu', 'author_id': 8614792, 'author_profile': 'https://Stackoverflow.com/users/8614792', 'pm_score': 0, 'selected': False, 'text': '<p>For the cloning process, the object can be converted to the byte array first and then converted back to the object.</p>\n\n<pre><code>public static class Extentions\n{\n public static T Clone<T>(this T obj)\n {\n byte[] buffer = BinarySerialize(obj);\n return (T)BinaryDeserialize(buffer);\n }\n\n public static byte[] BinarySerialize(object obj)\n {\n using (var stream = new MemoryStream())\n {\n var formatter = new BinaryFormatter(); \n formatter.Serialize(stream, obj); \n return stream.ToArray();\n }\n }\n\n public static object BinaryDeserialize(byte[] buffer)\n {\n using (var stream = new MemoryStream(buffer))\n {\n var formatter = new BinaryFormatter(); \n return formatter.Deserialize(stream);\n }\n }\n}\n</code></pre>\n\n<p>The object must be serialized for the serialization process.</p>\n\n<pre><code>[Serializable]\npublic class MyObject\n{\n public string Name { get; set; }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>MyObject myObj = GetMyObj();\nMyObject newObj = myObj.Clone();\n</code></pre>\n'}, {'answer_id': 62564309, 'author': 'Sean McAvoy', 'author_id': 12367139, 'author_profile': 'https://Stackoverflow.com/users/12367139', 'pm_score': 3, 'selected': False, 'text': '<p>Create an extension:</p>\n<pre><code>public static T Clone<T>(this T theObject)\n{\n string jsonData = JsonConvert.SerializeObject(theObject);\n return JsonConvert.DeserializeObject<T>(jsonData);\n}\n</code></pre>\n<p>And call it like this:</p>\n<pre><code>NewObject = OldObject.Clone();\n</code></pre>\n'}, {'answer_id': 66538192, 'author': 'Ogglas', 'author_id': 3850405, 'author_profile': 'https://Stackoverflow.com/users/3850405', 'pm_score': 0, 'selected': False, 'text': '<p>An addition to @Konrad and @craastad with using built in <code>System.Text.Json</code> for <code>.NET >5</code></p>\n<p><a href="https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-5-0" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-5-0</a></p>\n<p>Method:</p>\n<pre><code>public static T Clone<T>(T source)\n{\n var serialized = JsonSerializer.Serialize(source);\n return JsonSerializer.Deserialize<T>(serialized);\n}\n</code></pre>\n<p>Extension method:</p>\n<pre><code>public static class SystemExtension\n{\n public static T Clone<T>(this T source)\n {\n var serialized = JsonSerializer.Serialize(source);\n return JsonSerializer.Deserialize<T>(serialized);\n }\n}\n</code></pre>\n'}, {'answer_id': 67402990, 'author': 'Adel Tabareh', 'author_id': 5007985, 'author_profile': 'https://Stackoverflow.com/users/5007985', 'pm_score': 1, 'selected': False, 'text': '<p>using System.Text.Json;</p>\n<pre><code>public static class CloneExtensions\n{\n public static T Clone<T>(this T cloneable) where T : new()\n {\n var toJson = JsonSerializer.Serialize(cloneable);\n return JsonSerializer.Deserialize<T>(toJson);\n }\n}\n</code></pre>\n'}, {'answer_id': 68663921, 'author': 'Izzy', 'author_id': 1918179, 'author_profile': 'https://Stackoverflow.com/users/1918179', 'pm_score': 2, 'selected': False, 'text': '<p>C# 9.0 is introducing the <code>with</code> keyword that requires a <code>record</code> (Thanks Mark Nading). This should allow very simple object cloning (and mutation if required) with very little boilerplate, but only with a <code>record</code>.</p>\n<p>You cannot seem to be able to clone (by value) a class by putting it into a generic <code>record</code>;</p>\n<pre><code>using System;\n \npublic class Program\n{\n public class Example\n {\n public string A { get; set; }\n }\n \n public record ClonerRecord<T>(T a)\n {\n }\n\n public static void Main()\n {\n var foo = new Example {A = "Hello World"};\n var bar = (new ClonerRecord<Example>(foo) with {}).a;\n foo.A = "Goodbye World :(";\n Console.WriteLine(bar.A);\n }\n}\n</code></pre>\n<p>This writes "Goodbye World :("- the string was copied by reference (undesired). <a href="https://dotnetfiddle.net/w3IJgG" rel="nofollow noreferrer">https://dotnetfiddle.net/w3IJgG</a></p>\n<p>(Incredibly, the above works correctly with a <code>struct</code>! <a href="https://dotnetfiddle.net/469NJv" rel="nofollow noreferrer">https://dotnetfiddle.net/469NJv</a>)</p>\n<p>But cloning a <code>record</code> does seem to work as indented, cloning by value.</p>\n<pre><code>using System;\n\npublic class Program\n{\n public record Example\n {\n public string A { get; set; }\n }\n \n public static void Main()\n {\n var foo = new Example {A = "Hello World"};\n var bar = foo with {};\n foo.A = "Goodbye World :(";\n Console.WriteLine(bar.A);\n }\n}\n</code></pre>\n<p>This returns "Hello World", the string was copied by value! <a href="https://dotnetfiddle.net/MCHGEL" rel="nofollow noreferrer">https://dotnetfiddle.net/MCHGEL</a></p>\n<p>More information can be found on the blog post:</p>\n<p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/with-expression" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/with-expression</a></p>\n'}, {'answer_id': 69211283, 'author': 'Cinorid', 'author_id': 6338072, 'author_profile': 'https://Stackoverflow.com/users/6338072', 'pm_score': 1, 'selected': False, 'text': '<p>I did some benchmark on current answers and found some interesting facts.</p>\n<p>Using BinarySerializer => <a href="https://stackoverflow.com/a/78612/6338072">https://stackoverflow.com/a/78612/6338072</a></p>\n<p>Using XmlSerializer => <a href="https://stackoverflow.com/a/50150204/6338072">https://stackoverflow.com/a/50150204/6338072</a></p>\n<p>Using Activator.CreateInstance => <a href="https://stackoverflow.com/a/56691124/6338072">https://stackoverflow.com/a/56691124/6338072</a></p>\n<p>These are the results</p>\n<pre><code>BenchmarkDotNet=v0.13.1, OS=Windows 10.0.18363.1734 (1909/November2019Update/19H2)\n</code></pre>\n<p>Intel Core i5-6200U CPU 2.30GHz (Skylake), 1 CPU, 4 logical and 2 physical cores\n[Host] : .NET Framework 4.8 (4.8.4400.0), X86 LegacyJIT\nDefaultJob : .NET Framework 4.8 (4.8.4400.0), X86 LegacyJIT</p>\n<div class="s-table-container">\n<table class="s-table">\n<thead>\n<tr>\n<th>Method</th>\n<th style="text-align: right;">Mean</th>\n<th style="text-align: right;">Error</th>\n<th style="text-align: right;">StdDev</th>\n<th style="text-align: right;">Gen 0</th>\n<th style="text-align: right;">Allocated</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>BinarySerializer</td>\n<td style="text-align: right;">220.69 us</td>\n<td style="text-align: right;">4.374 us</td>\n<td style="text-align: right;">9.963 us</td>\n<td style="text-align: right;">49.8047</td>\n<td style="text-align: right;">77 KB</td>\n</tr>\n<tr>\n<td>XmlSerializer</td>\n<td style="text-align: right;">182.72 us</td>\n<td style="text-align: right;">3.619 us</td>\n<td style="text-align: right;">9.405 us</td>\n<td style="text-align: right;">21.9727</td>\n<td style="text-align: right;">34 KB</td>\n</tr>\n<tr>\n<td>Activator.CreateInstance</td>\n<td style="text-align: right;">49.99 us</td>\n<td style="text-align: right;">0.992 us</td>\n<td style="text-align: right;">2.861 us</td>\n<td style="text-align: right;">1.9531</td>\n<td style="text-align: right;">3 KB</td>\n</tr>\n</tbody>\n</table>\n</div>'}, {'answer_id': 69471766, 'author': 'ʞᴉɯ', 'author_id': 182331, 'author_profile': 'https://Stackoverflow.com/users/182331', 'pm_score': -1, 'selected': False, 'text': '<p>Found this package, who seems quicker of <code>DeepCloner</code>, and with no dependencies, compared to it.</p>\n<p><a href="https://github.com/AlenToma/FastDeepCloner" rel="nofollow noreferrer">https://github.com/AlenToma/FastDeepCloner</a></p>\n'}, {'answer_id': 70899238, 'author': 'vivek nuna', 'author_id': 6527049, 'author_profile': 'https://Stackoverflow.com/users/6527049', 'pm_score': 2, 'selected': False, 'text': '<p>I’ll use the below simple way to implement this.\nJust create an abstract class and implement method to serialize and deserialize again and return.</p>\n<pre><code>public abstract class CloneablePrototype<T>\n{\n public T DeepCopy()\n {\n string result = JsonConvert.SerializeObject(this);\n return JsonConvert.DeserializeObject<T>(result);\n }\n}\npublic class YourClass : CloneablePrototype< YourClass>\n…\n…\n…\n</code></pre>\n<p>And the use it like this to create deep copy.</p>\n<pre><code>YourClass newObj = (YourClass)oldObj.DeepCopy();\n</code></pre>\n<p>This solution is easy to extend as well if you need to implement the shallow copy method as well.</p>\n<p>Just implement a new method in the abstract class.</p>\n<pre><code>public T ShallowCopy()\n{\n return (T)this.MemberwiseClone();\n}\n</code></pre>\n'}, {'answer_id': 71863562, 'author': 'David Oganov', 'author_id': 7741097, 'author_profile': 'https://Stackoverflow.com/users/7741097', 'pm_score': 2, 'selected': False, 'text': '<p>Besides some of the brilliant answers here, what you can do in C# 9.0 & higher, is the following (assuming you can convert your class to a record):</p>\n<pre><code>record Record\n{\n public int Property1 { get; set; }\n\n public string Property2 { get; set; }\n}\n</code></pre>\n<p>And then, simply use <a href="https://stackoverflow.com/questions/69616749/what-is-the-with-operator-for-in-c">with operator</a> to copy values of one object to the new one.</p>\n<pre><code>var object1 = new Record()\n{\n Property1 = 1,\n Property2 = "2"\n};\n\nvar object2 = object1 with { };\n// object2 now has Property1 = 1 & Property2 = "2"\n</code></pre>\n<p>I hope this helps :)</p>\n'}, {'answer_id': 73228716, 'author': 'Efreeto', 'author_id': 2680660, 'author_profile': 'https://Stackoverflow.com/users/2680660', 'pm_score': 0, 'selected': False, 'text': "<p>Building upon @craastad's answer, for derived classes.</p>\n<p>In the original answer, if the caller is calling <code>DeepCopy</code> on a base class object, the cloned object is of a base class. But the following code will return the derived class.</p>\n<pre><code>using Newtonsoft.Json;\n\npublic static T DeepCopy<T>(this T source)\n{\n return (T)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(source), source.GetType());\n}\n</code></pre>\n"}, {'answer_id': 73300838, 'author': 'Adamy', 'author_id': 657926, 'author_profile': 'https://Stackoverflow.com/users/657926', 'pm_score': -1, 'selected': False, 'text': "<p>If you use net.core and the object is serializable, you can use</p>\n<pre><code>var jsonBin = BinaryData.FromObjectAsJson(yourObject);\n</code></pre>\n<p>then</p>\n<pre><code>var yourObjectCloned = jsonBin.ToObjectFromJson<YourType>();\n</code></pre>\n<p>BinaryData is in dotnet therefore you don't need a third party lib. It also can handle the situation that the property on your class is Object type (the actual data in your property still need to be serializable)</p>\n"}, {'answer_id': 73580774, 'author': 'Daniel Jonsson', 'author_id': 595990, 'author_profile': 'https://Stackoverflow.com/users/595990', 'pm_score': 2, 'selected': False, 'text': '<p>In the codebase I am working with, we had a copy of the file <code>ObjectExtensions.cs</code> from the GitHub project <a href="https://github.com/Burtsev-Alexey/net-object-deep-copy/blob/master/ObjectExtensions.cs" rel="nofollow noreferrer">Burtsev-Alexey/net-object-deep-copy</a>. It is 9 years old. It worked, although we later realized it was very slow for larger object structures.</p>\n<p>Instead, we found a fork of the file <code>ObjectExtensions.cs</code> in the GitHub project <a href="https://github.com/jpmikkers/Baksteen.Extensions.DeepCopy" rel="nofollow noreferrer">jpmikkers/Baksteen.Extensions.DeepCopy</a>. A deep copy operation of a large data structure that previously took us about 30 minutes, now feels almost instantaneous.</p>\n<p>This improved version has the following documentation:</p>\n<blockquote>\n<h2>C# extension method for fast object cloning.</h2>\n<p>This is a speed-optimized fork of Alexey Burtsev\'s deep copier. Depending on your usecase, this will be 2x - 3x faster than the original. It also fixes some bugs which are present in the original code. Compared to the classic binary serialization/deserialization deep clone technique, this version is about seven times faster (the more arrays your objects contain, the bigger the speedup factor).</p>\n<p>The speedup is achieved via the following techniques:</p>\n<ul>\n<li>object reflection results are cached</li>\n<li>don\'t deep copy primitives or immutable structs & classes (e.g. enum and string)</li>\n<li>to improve locality of reference, process the \'fast\' dimensions or multidimensional arrays in the inner loops</li>\n<li>use a compiled lamba expression to call MemberwiseClone</li>\n</ul>\n<h3>How to use:</h3>\n<pre class="lang-cs prettyprint-override"><code>using Baksteen.Extensions.DeepCopy;\n...\nvar myobject = new SomeClass();\n...\nvar myclone = myobject.DeepCopy()!; // creates a new deep copy of the original object \n</code></pre>\n<p>Note: the exclamation mark (null-forgiving operator) is only required if you enabled nullable referency types in your project</p>\n</blockquote>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/78536', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3742/'] |
78,548 | <p>What is your way of passing data to Master Page (using ASP.NET MVC) without breaking MVC rules?</p>
<p>Personally, I prefer to code abstract controller (base controller) or base class which is passed to all views.</p>
| [{'answer_id': 78571, 'author': 'Ian P', 'author_id': 10853, 'author_profile': 'https://Stackoverflow.com/users/10853', 'pm_score': 3, 'selected': False, 'text': "<p>Abstract controllers are a good idea, and I haven't found a better way. I'm interested to see what other people have done, as well.</p>\n"}, {'answer_id': 78576, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>The Request.Params object is mutable. It's pretty easy to add scalar values to it as part of the request processing cycle. From the view's perspective, that information could have been provided in the QueryString or FORM POST. hth</p>\n"}, {'answer_id': 78594, 'author': 'David Negron', 'author_id': 981, 'author_profile': 'https://Stackoverflow.com/users/981', 'pm_score': 2, 'selected': False, 'text': '<p>I did some research and came across these two sites. Maybe they could help.</p>\n<p><a href="https://stephenwalther.com/archive/2008/08/12/asp-net-mvc-tip-31-passing-data-to-master-pages-and-user-controls" rel="nofollow noreferrer">ASP.NET MVC Tip #31 – Passing Data to Master Pages and User Controls</a></p>\n<p><a href="https://web.archive.org/web/20200221095802/http://geekswithblogs.net:80/scarpenter/archive/2007/12/14/117724.aspx" rel="nofollow noreferrer">Passing Data to Master Pages with ASP.NET MVC</a></p>\n'}, {'answer_id': 78616, 'author': 'dimarzionist', 'author_id': 10778, 'author_profile': 'https://Stackoverflow.com/users/10778', 'pm_score': 0, 'selected': False, 'text': '<p>I thing that another good way could be to create Interface for view with some Property like ParentView of some interface, so you can use it both for controls which need a reference to the page(parent control) and for master views which should be accessed from views.</p>\n'}, {'answer_id': 78658, 'author': 'Matt Mitchell', 'author_id': 364, 'author_profile': 'https://Stackoverflow.com/users/364', 'pm_score': 2, 'selected': False, 'text': '<p>I find that a common parent for all model objects you pass to the view is exceptionally useful.</p>\n\n<p>There will always tend to be some common model properties between pages anyway.</p>\n'}, {'answer_id': 746011, 'author': 'Generic Error', 'author_id': 40944, 'author_profile': 'https://Stackoverflow.com/users/40944', 'pm_score': 7, 'selected': True, 'text': '<p>If you prefer your views to have strongly typed view data classes this might work for you. Other solutions are probably more <em>correct</em> but this is a nice balance between design and practicality IMHO.</p>\n\n<p>The master page takes a strongly typed view data class containing only information relevant to it:</p>\n\n<pre><code>public class MasterViewData\n{\n public ICollection<string> Navigation { get; set; }\n}\n</code></pre>\n\n<p>Each view using that master page takes a strongly typed view data class containing its information and deriving from the master pages view data:</p>\n\n<pre><code>public class IndexViewData : MasterViewData\n{\n public string Name { get; set; }\n public float Price { get; set; }\n}\n</code></pre>\n\n<p>Since I don\'t want individual controllers to know anything about putting together the master pages data I encapsulate that logic into a factory which is passed to each controller:</p>\n\n<pre><code>public interface IViewDataFactory\n{\n T Create<T>()\n where T : MasterViewData, new()\n}\n\npublic class ProductController : Controller\n{\n public ProductController(IViewDataFactory viewDataFactory)\n ...\n\n public ActionResult Index()\n {\n var viewData = viewDataFactory.Create<ProductViewData>();\n\n viewData.Name = "My product";\n viewData.Price = 9.95;\n\n return View("Index", viewData);\n }\n}\n</code></pre>\n\n<p>Inheritance matches the master to view relationship well but when it comes to rendering partials / user controls I will compose their view data into the pages view data, e.g.</p>\n\n<pre><code>public class IndexViewData : MasterViewData\n{\n public string Name { get; set; }\n public float Price { get; set; }\n public SubViewData SubViewData { get; set; }\n}\n\n<% Html.RenderPartial("Sub", Model.SubViewData); %>\n</code></pre>\n\n<p><em>This is example code only and is not intended to compile as is. Designed for ASP.Net MVC 1.0.</em></p>\n'}, {'answer_id': 948875, 'author': 'Michael La Voie', 'author_id': 65843, 'author_profile': 'https://Stackoverflow.com/users/65843', 'pm_score': 4, 'selected': False, 'text': '<p><strong>EDIT</strong></p>\n\n<p><a href="https://stackoverflow.com/users/40944/generic-error">Generic Error</a> has provided a better answer below. Please read it!</p>\n\n<p><strong>Original Answer</strong></p>\n\n<p>Microsoft has actually posted an entry on <a href="http://www.asp.net/LEARN/mvc/tutorial-13-cs.aspx" rel="nofollow noreferrer">the "official" way</a> to handle this. This provides a step-by-step walk-through with an explanation of their reasoning.</p>\n\n<p>In short, they recommend using an abstract controller class, but see for yourself.</p>\n'}, {'answer_id': 1496250, 'author': 'rasx', 'author_id': 22944, 'author_profile': 'https://Stackoverflow.com/users/22944', 'pm_score': 0, 'selected': False, 'text': '<p>The other solutions lack elegance and take too long. I apologize for doing this very sad and impoverished thing almost an entire year later:</p>\n\n<pre><code><script runat="server" type="text/C#">\n protected override void OnLoad(EventArgs e)\n {\n base.OnLoad(e);\n MasterModel = SiteMasterViewData.Get(this.Context);\n }\n\n protected SiteMasterViewData MasterModel;\n</script>\n</code></pre>\n\n<p>So clearly I have this static method Get() on SiteMasterViewData that returns SiteMasterViewData.</p>\n'}, {'answer_id': 3444472, 'author': 'Todd Menier', 'author_id': 62600, 'author_profile': 'https://Stackoverflow.com/users/62600', 'pm_score': 6, 'selected': False, 'text': '<p>I prefer breaking off the data-driven pieces of the master view into partials and rendering them using <strong>Html.RenderAction</strong>. This has several distinct advantages over the popular view model inheritance approach:</p>\n\n<ol>\n<li>Master view data is completely decoupled from "regular" view models. This is composition over inheritance and results in a more loosely coupled system that\'s easier to change.</li>\n<li>Master view models are built up by a completely separate controller action. "Regular" actions don\'t need to worry about this, and there\'s no need for a view data factory, which seems overly complicated for my tastes.</li>\n<li>If you happen to use a tool like <a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/01/22/automapper-the-object-object-mapper.aspx" rel="noreferrer">AutoMapper</a> to map your domain to your view models, you\'ll find it easier to configure because your view models will more closely resemble your domain models when they don\'t inherit master view data.</li>\n<li>With separate action methods for master data, you can easily apply output caching to certain regions of the page. Typically master views contain data that changes less frequently than the main page content.</li>\n</ol>\n'}] | 2008/09/17 | ['https://Stackoverflow.com/questions/78548', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/347616/'] |
Subsets and Splits