instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I am trying to use log4net in an ASP.NET application with Visual Studio 2005. I have declared an instance of the logger like so:</p> <pre><code>Private Shared ReadOnly log As ILog = LogManager.GetLogger("") </code></pre> <p>I am trying to use it in the following manner:</p> <pre><code>If log.IsDebugEnabled Then log.Debug("Integration Services Constructed") End If </code></pre> <p>Here is my configuration:</p> <pre class="lang-xml prettyprint-override"><code>&lt;log4net&gt; &lt;root&gt; &lt;level value="DEBUG" /&gt; &lt;appender-ref ref="RollingFileAppender" /&gt; &lt;/root&gt; &lt;appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender"&gt; &lt;file value="..\\logs\\logfile.log"/&gt; &lt;appendToFile value="true"/&gt; &lt;rollingStyle value="Size"/&gt; &lt;maxSizeRollBackups value="10"/&gt; &lt;maximumFileSize value="1MB"/&gt; &lt;staticLogFileName value="true"/&gt; &lt;layout type="log4net.Layout.PatternLayout"&gt; &lt;conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/&gt; &lt;/layout&gt; &lt;filter type="log4net.Filter.LevelRangeFilter"&gt; &lt;param name="LevelMin" value="DEBUG" /&gt; &lt;param name="LevelMax" value="FATAL" /&gt; &lt;/filter&gt; &lt;/appender&gt; &lt;/log4net&gt; </code></pre> <p>Unfortunately, <code>log.IsDebugEnabled</code> is always false. <br /> How do I configure log4net so that I can log only debug messages?</p>
<p>Before calling LogManager.GetLogger("")</p> <p>You have to call log4net.Config.XmlConfigurator.Configure(); In an ASP.NET app you probably want to put this call in Application_Start </p>
<p>Use this in any method before you use log :</p> <p>log4net.Config.XmlConfigurator.Configure();</p> <p>In App.Config ,the settings should be :</p> <pre><code>&lt;root&gt; &lt;level value="ALL" /&gt; &lt;appender-ref ref="AppenderName" /&gt; &lt;/root&gt; </code></pre>
27,083
<p>In C#4.0 we're going to get dynamic types, or objects whose "static type is dynamic", according to Anders. This will allow any method invocation resolution to happen at runtime rather than compile time. But will there be facility to bind the dynamic object to some sort of contract (and thereby also get full intellisense for it back), rather than allowing any call on it even if you know that is not likely to be valid.</p> <p>I.e. instead of just</p> <pre><code>dynamic foo = GetSomeDynamicObject(); </code></pre> <p>have the ability to cast or transform it to constrain it to a known contract, such as</p> <pre><code>IFoo foo2 = foo.To&lt;IFoo&gt;; </code></pre> <p>or even just</p> <pre><code>IFoo foo2 = foo as IFoo; </code></pre> <p>Can't find anything like that in the existing materials for C#4.0, but it seems like a logical extension of the dynamic paradigm. Anyone with more info?</p>
<p>I'm not aware of anything really resembling duck typing, I'm afraid. I've <a href="http://msmvps.com/blogs/jon_skeet/archive/2008/10/30/c-4-0-dynamic-lt-t-gt.aspx" rel="nofollow noreferrer">blogged about the idea</a>, but I don't expect any support. It probably wouldn't be too hard to use Reflection.Emit to make a class which will generate an implementation of any given interface, taking a dynamic object in the constructor and just proxying each call through to it. Not ideal, but it might be a stopgap.</p>
<p>That's a cool idea. If I understand you, you're describing/proposing a capability of the CLR, whereby, when you try and cast a dynamic object to an interface, it should look at what methods/properties the dynamic object supports and see if it has ones that effectively implement that interface. Then the CLR would take care of 'implementing IFoo' on the object, so you can then cast the dynamic object to an IFoo. Almost certain that that will not be supported, but it's a interesting idea.</p>
32,482
<p>My Flashforge Adventurer 3 is not printing properly. Filament feeder makes repetitive loud thumping noise and not enough filament is extruded. Resulting print (if completed) is not solid.</p> <p>Results vary with filament. Flashforge brand (red) PLA works best. Any other filament fails completely unless I print at High quality, with head temperature at 235 degrees. Nozzle has been un-clogged repeatedly, but right from the start, when feeding filament in, it does not flow through properly. </p> <p>I had used the included tool to clear blockages in the extruder several times before now, but after posting this question I tried again. Ordinary use of the tool made no difference. So I applied more force, and, pushed filament through by hand directly into the extruder and used a pin to try to clear the extruder. It now appears to be working adequately Not perfectly. I am able to print with default settings. It still thumps -or ticks- a bit. I am alarmed at the amount of force I had to use to clear the extruder blockage. </p>
<p>Advice from another source suggested thoroughly cleaning the feed gear on the bowden extruder. When I looked closely there were plastic flakes all over the mechanism. I used compressed air and a brush to clean it. I also discovered expert mode in the FlashPrint software, which enabled me to slow down the speed at which fill is laid down. Now I have good printing results with any filament.</p> <p>EDIT AND UPDATE:: I have continued to have problems with PLA. For most of the last year I printed using ABS with no similar problems. I guess that PLA is simply rougher, scratchier than ABS and catches in the tube. I found a comment that putting olive oil on the filament fixes it. I used Vaseline. Things were fine for a while, but a retailer said this would lead to other problems.</p> <p>So far, no permanent answer to this question.</p>
<p>I had a lot of thumps lately after I moved my printer location.</p> <p>Turns out my printer wasn't level and the extruder was pushing harder (further down) on different places, causing thumps. This really shows because the calibration is only in 1 spot.</p> <p>I used some printer paper and a bubble level then recalibrated. Not a single thump since.</p>
1,133
<p>When an error occurs in a function, I'd like to know the sequence of events that lead up to it, especially when that function is called from a dozen different places. Is there any way to retrieve the call stack in VB6, or do I have to do it the hard way (e.g., log entries in every function and error handler, etc.)?</p>
<p>I'm pretty sure you have to do it the hard way. At a previous job of mine, we had a very elegant error handling process for VB6 with DCOM components. However, it was a lot redundant code that had to be added to every method, so much that we had home-grown tools to insert it all for you.</p> <p>I can't provide too much insight on its implementation (both because I've forgotten most of it and there's a chance they may consider it a trade secret). One thing that does stand out was that the method name couldn't be derived at run-time so it was added as a string variable (some developers would copy-paste instead of using the tool and it would lead to error stacks that lied...).</p> <p>HTH</p>
<p>Compuware (or was it Numega at the time) DevStudio for Visual Basic 6 used to do this. The way was by adding adding instrumenation to every call that called a very small snippet that added to the code stack. On any error it dumped out that callstack, and then did things like mail or post to a webserver all the debuging information. Adding and removing the instrumentation was a potentially lethal operation (especially back then, when we were using VSS as our source control), but if it worked, it work well.</p> <p>As <a href="https://stackoverflow.com/questions/127645/is-it-possible-to-retrieve-the-call-stack-programmatically-in-vb6#128285">Darrel pointed out</a>, you could add something very simlar by using MZTools and setting up a template. It's a lot of working, and is probably more effeort than the reward would be but if you have very difficult to track down bugs, it might help). </p>
15,534
<p>So as the title said my heated bed stopped heating mid print. </p> <p>I'm pretty confident the bed itself is not the problem as I've ran continuity tests from the wires and a resistance check (which showed a total resistance of about 1.5 ohms, which is where it should be). I've done voltage checks across the input terminals which showed a successful output of 12 V. </p> <p>Finally I did a voltage test across the output terminal at D8 where the heated bed should be outputted to. The result came up with nearly 0 V. I then noticed that the LED that usually lights up for D8 was turned off. The weird thing is, I unplugged the wires from D8 and this time the LED lit up like it was supposed to. Due to this, I believe the problem to be with the MOSFET attached to D8. </p> <p>My proposed solution would be to move the heated bed terminal to D9 instead of D8. I wish to this because despite the firmware set up for a fan, I do not have a fan attached to D9. This leaves this terminal open and with a potentially unharmed MOSFET. Despite this I have found no information on how to go about accomplishing this. </p> <p>What do you guys think? Is that even a good idea or should the component (or board be replaced)? Any help would be greatly appreciated.</p>
<p>First you should check if the bed still works when applying 12V directly. You can then also check the voltage over the 12V output terminals to measure the power supply unit while it is powering the bed. It is unclear whether you measured the voltage of the PSU while it was powering a large load.</p> <p>It is also a good idea to get the external MOSFET board out of the equation (the less components you have, the less you need to troubleshoot).</p> <p>From the post can be concluded that you are using the so-called RAMPS EFB setup, e.g. in <a href="https://github.com/MarlinFirmware/Marlin/" rel="nofollow noreferrer">Marlin firmware</a> defined by constant <code>IS_RAMPS_EFB</code> in your firmware printer setup (Extruder on pin 10, fan on pin 9 and bed on pin 8).</p> <p>In the pin configuration file <a href="https://github.com/MarlinFirmware/Marlin/blob/1.1.x/Marlin/pins_RAMPS.h" rel="nofollow noreferrer">pins_RAMPS.h</a> you can find the following lines:</p> <pre><code>#define FAN_PIN RAMPS_D9_PIN #define HEATER_BED_PIN RAMPS_D8_PIN </code></pre> <p>To change the pin layout, switch the values of the constants.</p>
<p>you can swap pins in Marlin firmware. When you download it from GitHub, there is a file called <a href="https://github.com/prusa3d/Prusa-Firmware/blob/MK3/Firmware/pins.h" rel="nofollow noreferrer">pins.h</a> (please be aware that this file is an example), and you can play with your setup to skip the broken mosfet.</p> <p><strong>Sometimes, it could be easier and faster to desolder and swap elements directly on the board - that depends on the skill set we have</strong></p>
930
<p>How do you run an external program and pass it command line parameters using C? If you have to use operating system API, include a solution for Windows, Mac, and Linux.</p>
<p>It really depends on what you're trying to do, exactly, as it's:</p> <ol> <li>OS dependent</li> <li>Not quite clear what you're trying to do.</li> </ol> <p>Nevertheless, I'll try to provide some information for you to decide.<br> On UNIX, <code>fork()</code> creates a clone of your process from the place where you called fork. Meaning, if I have the following process:</p> <pre><code>#include &lt;unistd.h&gt; #include &lt;stdio.h&gt; int main() { printf( "hi 2 u\n" ); int mypid = fork(); if( 0 == mypid ) printf( "lol child\n" ); else printf( "lol parent\n" ); return( 0 ); } </code></pre> <p>The output will look as follows:</p> <blockquote> <blockquote> <p>hi 2 u<br> lol child<br> lol parent </p> </blockquote> </blockquote> <p>When you <code>fork()</code> the pid returned in the child is 0, and the pid returned in the parent is the child's pid. Notice that "hi2u" is only printed once... by the <strong>parent</strong>.</p> <p><code>execve()</code> and its family of functions are almost always used with <code>fork().</code> <code>execve()</code> and the like overwrite the current stackframe with the name of the application you pass to it. <code>execve()</code> is almost always used with <code>fork()</code> where you fork a child process and if you're the parent you do whatever you need to keep doing and if you're the child you exec a new process. <code>execve()</code> is also almost always used with <code>waitpid()</code> -- waitpid takes a pid of a child process and, quite literally, <em>waits</em> until the child terminates and returns the child's exit status to you. </p> <p>Using this information, you should be able to write a very basic shell; one that takes process names on the command line and runs processes you tell it to. Of course, shells do more than that, like piping input and output, but you should be able to accomplish the basics using <code>fork()</code>, <code>execve()</code> and <code>waitpid()</code>.</p> <p><strong>NOTE: This is *nix specific! This will NOT work on Windows.</strong> </p> <p>Hope this helped.</p>
<p>If you need to check/read/parse the output of your external command, I would suggest to use popen() instead of system().</p>
3,785
<p>How does one automatically find categories for text based on content?</p>
<ol> <li>Read <strong><a href="http://www.cs.waikato.ac.nz/~ml/weka/book.html" rel="nofollow noreferrer">Data Mining: Practical Machine Learning Tools and Techniques</a></strong> - Ian H. Witten, Eibe Frank</li> <li>Use <strong><a href="http://www.cs.waikato.ac.nz/~ml/weka/" rel="nofollow noreferrer">Weka</a></strong> or <strong><a href="http://www.ailab.si/orange/" rel="nofollow noreferrer">Orange</a></strong></li> </ol>
<p>There is a good paper written on this: <a href="http://www.cs.utexas.edu/users/hyukcho/classificationAlgorithm.html" rel="nofollow noreferrer">http://www.cs.utexas.edu/users/hyukcho/classificationAlgorithm.html</a></p>
9,122
<p>I have a slow custom data source in a SSIS Dataa Flow Task.I have to run the package with multiple parameters</p> <p>If I want to upload data to a DB using SQL Data Destination(Bulk Insert) the connection times out</p> <p>If I write the data to a flat file I cannot run multiple instances of the package, since they will write to the same file. Can I pass the file name as a parameter somewhere?</p> <p>Do I need to write a custom Script Destination as the last resort?</p>
<p>You can leverage JQuery UI 1.6's Effects (<a href="http://ui.jquery.com/repository/real-world/effects/" rel="nofollow noreferrer">Effects Demo Page</a>). The following accomplished the desired effect for me.</p> <pre><code>$('#toggleButton').bind('click', function(e) { $('#expandingFooter').toggle( 'slide', { easing: 'easeOutQuint', direction: 'down' }, 1000 ); }); </code></pre> <p>Note: You may want to play with the easing parameter to get the desired smoothness of the effect.</p> <p>You'll need to have the latest versions of both <a href="http://docs.jquery.com/Downloading_jQuery" rel="nofollow noreferrer">JQuery</a> and <a href="http://ui.jquery.com/download_builder/" rel="nofollow noreferrer">JQuery UI Slide Effect</a> to do this.</p>
<p>Try something like this: </p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Untitled&lt;/title&gt; &lt;script type="text/javascript" src="shared-scripts/jquery-1.2.4b.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; &lt;!-- $(document).ready(function(){ $("#footer").click(function () { if ($("#expandingFooter").is(":hidden")) { $("#expandingFooter").show("slow"); } else { $("#expandingFooter").slideUp(); } }); $("#expandingFooter").hide(); }); //--&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="footer"&gt; &lt;div id="expandingFooter"&gt; hidden content&lt;/div&gt; content that is always visible &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
47,479
<p>I have a program 'foo' running different threads, fooT1, fooT2, .. fooTn.</p> <p>Now if I want write another program 'bar', which could kill the thread fooTr, is that possible?</p> <p>Reason: One of the thread fooTr tracks product license. If this thread is killed; one may run this product indefinitely. And killing 'foo' itself is tolerable as 'foo' as that is exactly what is being done on license expiry.</p> <p>System: Fedora Distribution of Linux</p> <p>Note: The commands which start JVM and program foo are placed in /etc/init.d and anyone who has a decent knowledge of rc.1/rc.2/rc.3 structure can change/add the starting parameters to these.</p> <p>I hope my question is clear. If not, I can always edit it.</p>
<p>Actually the java debugger will allow you to kill a thread by injecting an exception into it. I was just trying to work out how to use this feature to kill a thread without wiping out the whole jvm, when I came across this question. If you run the jvm with command line options like:</p> <pre><code>java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8888 your.app.Main </code></pre> <p>and connect the debugger with something like:</p> <pre><code>jdb -attach 127.0.0.1:8888 </code></pre> <p>you can type:</p> <pre><code>threads </code></pre> <p>to get a list of the running threads, and use the kill command to kill a running thread. The bit I'm currently not sure about is the syntax of this kill command, I have tried the obvious:</p> <pre><code>kill 0xe2e new java.lang.IllegalArgumentException("er"); </code></pre> <p>and I get the messages:</p> <pre><code>killing thread: Swank REPL Thread Thread not suspended Expression must evaluate to an object </code></pre> <p>("Swank REPL Thread" is the thread I want to kill, and yes, I've tried suspending it first ;)</p> <p>Still my inability to use the java debugger aside, it looks to me like a thread can be killed at random. Maybe you can just make sure you ignore all exceptions and keep running and that will be enough, but I'm not sure about that.</p>
<p>Until now isn´t possible to run to diferent programs in the same JVM, but some people is investigating it, in order to reduce the startup time and the memory and cpu usage of diferent java programs runing in the same machine</p>
21,925
<p>I have a requirement to develop a .NET-based application whose data requirements are likely to exceed the 4 gig limit of SQL 2005 Express Edition.</p> <p>There may be other customers of the same application (in the future) with a requirement to use a specific DB platform (such as Oracle or SQL Server) due to in-house DBA expertise.</p> <h3>Questions</h3> <ol> <li><p>What RDBMS would you guys recommend? From the looks of it the major choices are PostGreSQL, MySQL or FireBird. I've only got experience of MYSQL from these.</p> </li> <li><p>Which ORM tool (if any) would you recommend using - ideally one that can be swapped out between DB platforms with minimal effort? I like the look of the entity framework but unsure as to the degree to which platforms other than SQL Server are supported. If it helps, we'll be using the 3.5 version of the Framework. I'm open to the idea of using a tool such as NHibernate. On the other hand, if it's going to be easier, I'm happy to write my own stored procedures / DAL code - there won't be that many tables (perhaps 30-35).</p> </li> </ol>
<p>I suggest using NHibernate with postgres.</p> <p>You can do all your testing and development on sqlite so you don't need to have an instance of postgres running on your dev machine.</p> <p>If you aren't sure if you want to use mysql or postgres, I suggest trying them both out. Postgres is more compliant, but if you're comfortable with mysql (and you're using an ORM), you should probably use that.</p>
<p><a href="http://www.llblgen.com" rel="nofollow noreferrer">Llbgen</a> is very nice for your ORM mapper. At first there is quite a bit of a learning curve, but once you get the hang of it it's very good. It supports the databases you mentioned here, plus a few more.</p>
32,407
<p>For a registration form I have something simple like:</p> <pre><code> &lt;tr:panelLabelAndMessage label="Zip/City" showRequired="true"&gt; &lt;tr:inputText id="zip" value="#{data['registration'].zipCode}" contentStyle="width:36px" simple="true" required="true" /&gt; &lt;tr:inputText id="city" value="#{data['registration'].city}" contentStyle="width:133px" simple="true" required="true" /&gt; &lt;/tr:panelLabelAndMessage&gt; &lt;tr:message for="zip" /&gt; &lt;tr:message for="city" /&gt; </code></pre> <p>When including the last two lines, I get two messages on validation error. When ommiting last to lines, a javascript alert shows up, which is not what I want. </p> <p>Is there a solution to show only one validation failed message somehow?</p> <p>Thanks a lot!</p>
<p>Problem is, the fields must layout horizontally. It's a no-go to put ZIP field and city not next to each other in one line. At least for me.</p> <p>A co-worker has pointed me to set a faclets variable inside the first tr:message and to put a rendered attribute at the second one that reacts on this variable. Havn't got the time to try nor found the right command for setting a varable yet. Will post results as soon as possible.</p>
<p>I know this won't be ideal, but if you remove the <code>panelLabelAndMessage</code> tag and just use the label attribute on the <code>inputText</code> tag that should remove the extra error message. </p>
11,751
<p>I'm trying to play a sound file from an iPhone program.</p> <p>Here's the code:</p> <pre><code>NSString *path = [[NSBundle mainBundle] pathForResource:@"play" ofType:@"caf"]; NSFileHandle *bodyf = [NSFileHandle fileHandleForReadingAtPath:path]; NSData *body = [bodyf availableData]; NSLog( @"length of play.caf %d",[body length] ); NSURL *url = [NSURL fileURLWithPath:path isDirectory:NO]; NSLog( [url description] ); NSLog( @"%d", AudioServicesCreateSystemSoundID((CFURLRef)url, &amp;soundID) ); </code></pre> <p>The first NSLog is to check that I have access to the file (I did), the second NSLog is to show the file URL, and the third NSLog returns -1500 "An unspecified error has occurred."</p> <p>For the second NSLog, I get the following output:</p> <p>file://localhost/Users/alan/Library/Application 敲慬楴敶瑓楲杮upport/iPhone蒠ꁻތĀ⾅獕牥⽳污湡䰯扩慲祲䄯灰楬慣楴湯匠灵潰瑲椯桐湯⁥楓畭慬潴⽲獕牥䄯灰楬慣楴湯⽳䙂㕅㡂㤱䌭䐳ⴸ䐴䙃㠭㍃ⴷ䍁㈶㠵䙁㤴㈰䰯捯瑡䵥⹥灡⽰汰祡挮晡imulator/User/Applications/BFE5B819-C3D8-4DCF-8C37-AC6258AF4902/LocateMe.app/play.caf</p> <p>This is either due to my misunderstanding of the "description" method, or this contributes to the problem.</p> <p>Any idea what is going wrong?</p>
<p>The first parameter to NSLog is a format string; you're passing <code>[URL description]</code> as the format string to the second use of NSLog. That's bad, because if the description of the URL contains any <code>%</code> characters then it will wind up printing random stuff from the stack.</p> <p>Instead, write</p> <pre><code>NSLog(@"%@", URL); </code></pre> <p>You don't need to even use <code>-description</code> here; NSLog will invoke it for you automatically because <code>%@</code> means "an object," not "an NSString," and it's smart enough to do the right thing for you.</p>
<p>I tried the same with my application that plays sounds just fine. The sounds don’t play in the Simulator and when I try to <code>NSLog</code> the URL, I get the same garbage as You and <code>EXC_BAD_ACCESS</code> on the top of it. When I log the URL on the device, the URL is fine, but I get <code>EXC_BAD_ACCESS</code> nevertheless. When I drop the logging, sounds play and everything works. If somebody could explain this behaviour I’d be grateful. As for Your problem, I’d drop the logging and try the code on the device.</p>
32,197
<p>What security best-practices would you strongly recommend in maintaining a Linux server? <br />(i.e. bring up a firewall, disable unnecessary services, beware of suid executables, and so on.)</p> <p>Also: is there a definitive reference on Selinux?</p> <p>EDIT: Yes, I'm planning to put the machine on the Internet, with at least openvpn, ssh and apache (at the moment, without dynamic content), and to provide shell access to some people.</p>
<p>For SELinux I've found <a href="https://rads.stackoverflow.com/amzn/click/com/0131963694" rel="noreferrer" rel="nofollow noreferrer">SELinux By Example</a> to be really useful. It goes quite in-depth into keeping a sever as secure as possible and is pretty well written for such a wide topic.</p> <p>In general though:</p> <ul> <li>Disable anything you don't need. The wider the attack domain, the more likely you'll have a breach.</li> <li>Use an intrusion detection system (IDS) layer in front of any meaningful servers.</li> <li>Keep servers in a different security zone from your internal network.</li> <li>Deploy updates as fast as possible.</li> <li>Keep up to date on 0-day attacks for your remotely-accessible apps.</li> </ul>
<p>Don't use a DNS Server unless you have to . BIND has been a hotspot of security issues and exploits.</p>
22,606
<p>Is there a (standardized) way to get the name of the current method using c++? </p> <p>Using GNU GCC you can do this by using the macro <code>__FUNCTION__</code> and <code>__PRETTY_FUNCTION__</code> (surrounded by 2 underscores), however, this is of course non portable. Is there a way to do this in standard c++ or a way to make it portable?</p>
<p>The <code>__func__</code> identifier is part of the C99 standard and is in the C++0x draft.</p> <p>The identifier <code>__func__</code> is implicitly declared by the compiler as if the following were at the very start of each function body:</p> <pre><code>static const char __func__[] = "function-name"; </code></pre> <p>where <code>function-name</code> is an implementation-defined string automatically provided by the compiler.</p> <p>Until support for those standards is available (or more widely available) you're stuck with compiler-specific gunk.</p>
<p>No, it is not supported by c++ standard.</p>
30,768
<p>Does anybody know a good place to find things about game development for windows mobile?</p> <p>thanks!</p>
<p>The first thing you will require is the <a href="http://msdn.microsoft.com/en-ca/windowsmobile/bb264337.aspx" rel="nofollow noreferrer">Tools</a> and <a href="http://msdn.microsoft.com/en-us/windowsmobile/bb264330.aspx" rel="nofollow noreferrer">Startup kit</a>. This link is for .Net for Windows Mobile.</p>
<p>You can also check these <a href="http://msdn.microsoft.com/en-us/windowsmobile/bb495180.aspx" rel="nofollow noreferrer">video from MSDN</a> that show you basic coding (not game but can help you) on Windows Mobile.</p>
44,867
<p>What's the easiest way to centre a <code>java.awt.Window</code>, such as a <code>JFrame</code> or a <code>JDialog</code>?</p>
<p>From <a href="https://web.archive.org/web/20080921040824/http://blog.codebeach.com/2008/02/center-dialog-box-frame-or-window-in.html" rel="noreferrer">this link</a></p> <blockquote> <p>If you are using Java 1.4 or newer, you can use the simple method setLocationRelativeTo(null) on the dialog box, frame, or window to center it.</p> </blockquote>
<p>Actually frame<code>.getHeight()</code> and <code>getwidth()</code> doesnt return values , check it by <code>System.out.println(frame.getHeight());</code> directly put the values for width and height ,then it will work fine in center. eg: as below</p> <pre><code>Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize(); int x=(int)((dimension.getWidth() - 450)/2); int y=(int)((dimension.getHeight() - 450)/2); jf.setLocation(x, y); </code></pre> <p>both 450 is my frame width n height</p>
17,473
<p>I'm interested to get a free, WYSIWYG HTML editor that is compatible with Django template. Any ideas?</p> <blockquote> <p>Thanks LainMH.</p> <p>But I afraid fckeditor is used in web app, for the purpose of editing HTML. What I want is an editor that allows me to write HTML that is Django compatible. </p> <p>Hope this clarifies the issue.</p> </blockquote>
<p><a href="http://www.fckeditor.net/" rel="noreferrer">http://www.fckeditor.net/</a> ?</p> <p>EDIT: Just found this: <a href="http://blog.newt.cz/blog/integration-fckeditor-django/" rel="noreferrer">http://blog.newt.cz/blog/integration-fckeditor-django/</a></p>
<p>According to brief Googling (no personal experience with this), Aptana now supports Python development via Pydev. Pydev again can be configured to work with Django.</p> <p>Thus I would expect Aptana to be usable with Django templates aswell, though I have no complete guide these links should be helpful :</p> <ul> <li><a href="http://www.aptana.com/python" rel="nofollow noreferrer">http://www.aptana.com/python</a></li> <li><a href="http://pydev.blogspot.com/2006/09/configuring-pydev-to-work-with-django.html" rel="nofollow noreferrer">http://pydev.blogspot.com/2006/09/configuring-pydev-to-work-with-django.html</a></li> </ul> <p>Hope this helps.</p>
8,639
<p>I need to implement a SSO between a SharePoint site and a custom PHP-based site which resides on a different domain. I need to use the SharePoint user accounts to log in the PHP site. (I'll have a full control over the PHP source)</p> <p>Is this possible? Any tips and tricks?</p>
<p>My assumption is you have full control over your php app/domain, but a different team is managing the sharepoint server. Also assume you can ask the sharepoint team to create a simple webpart for your SSO functionality.</p> <p>If this is the case, you can ask the sharepoint team to create a webpart which has a link to your site on it. When the user clicks the link, the request is made back to the sharepoint server, the sharepoint server takes the user's logon name, encrypts it using your public key, and adds it to a url on your php site then sends this as a redirect back to the browser. So the location looks like this:</p> <p><a href="https://your.php.domain/sso.php?logon=encrypted_users_logon_name&amp;api_key=some_token" rel="nofollow noreferrer">https://your.php.domain/sso.php?logon=encrypted_users_logon_name&amp;api_key=some_token</a></p> <p>Your sso.php script will verify the api_key is a valid token from your sharepoint partner, and then decrypt the logon name of the user trying to get in. You can get more fancy, and have a callback on the sharepoint site to confirm the logon request is legitimate within some time window, or bake that into the encrypted logon name, but this is a barebones way to do it, assuming you trust requests coming from the sharepoint partner.</p> <p>The sharepoint .net developers will probably be able to do any encryption you want, so pick an algorithm you can use on both php and .net sides and give them the key to use for encryption, and the format of the information to encrypt. something like n=logon_name;expire=timestamp; then when you decrypt, if it is after the expire time then you deny the logon.</p>
<p>well, we have been in same situation, but we are using asp.net in combination with php for SSO. the asp.net code does windows authentication, and creates a record in mysql database, which contains username and a unique key, and assign these values to a cookie. then, redirects the user to PHP app. </p> <p>the php app reads those cookie values and compare them with database values to ensure the request to authentic. well thats the workaround to have single signon in PHP and have share point working together with PHP. but i would still recommend to use Kerb_auth_mod for SSO in php. which we eventually did.</p>
30,050
<p>I need to do a join across two different database servers (IPs 10.0.0.50 and 10.0.0.51). What's the best way?</p>
<p>You need to use sp_linkedserver to create a linked server.</p> <pre><code>sp_addlinkedserver [ @server= ] 'server' [ , [ @srvproduct= ] 'product_name' ] [ , [ @provider= ] 'provider_name' ] [ , [ @datasrc= ] 'data_source' ] [ , [ @location= ] 'location' ] [ , [ @provstr= ] 'provider_string' ] [ , [ @catalog= ] 'catalog' ] </code></pre> <p>More information available on <a href="http://msdn.microsoft.com/en-us/library/ms190479.aspx" rel="noreferrer">MSDN</a>.</p>
<p>You can, as mentioned, use sp_addlinkedserver. However, you may also do this via Enterprise Manager (2000) or SQL Server Management Studio (2005). Under the "Security" node, there is a "Linked Servers" node, which you can use to add and configure Linked Servers. You can specify security settings, impersonation, etc.</p> <p>See these for SQL Server 2000:</p> <p><a href="http://msdn.microsoft.com/en-us/library/aa213778(SQL.80).aspx" rel="noreferrer">Configuring Linked Servers</a></p> <p><a href="http://msdn.microsoft.com/en-us/library/aa213768(SQL.80).aspx" rel="noreferrer">Establishing Security For Linked Servers</a></p> <p><a href="http://msdn.microsoft.com/en-us/library/aa213787(SQL.80).aspx" rel="noreferrer">Configuring OLEDB Providers for Distributed Queries</a></p> <p>See these for SQL Server 2005:</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms188279(SQL.90).aspx" rel="noreferrer">Linking Servers</a></p> <p><a href="http://msdn.microsoft.com/en-us/library/ms175537(SQL.90).aspx" rel="noreferrer">Security for Linked Servers</a></p> <p><a href="http://msdn.microsoft.com/en-us/library/ms189580(SQL.90).aspx" rel="noreferrer">Configuring Linked Servers for Delegation</a></p> <p><a href="http://msdn.microsoft.com/en-us/library/ms190918(SQL.90).aspx" rel="noreferrer">Configuring OLEDB Providers for Distributed Queries</a></p>
22,973
<p>Can anyone point me to some decent introductions to WS-Security?</p> <p>I'm looking for tutorials or something that provide a fairly gentle introduction to the subject, though I don't mind if it assumes basic knowledge of web services and SOAP. Most of the stuff I've seen so far is very technical and you need a lot of complex, detailed background knowledge to understand it properly.</p> <p>We have to implement a web service in PHP and one or more clients in .NET, so resources covering both would be much appreciated.</p>
<p>I think the best introduction to the (any) subject are some good examples.<br> <a href="http://www.codeproject.com/KB/webservices/WS-Security.aspx" rel="nofollow noreferrer">This article</a> at codeProject gives a fairly easy to follow guide trough web service security for a .NET application.</p>
<p>You can find some good article on WS-Security and <a href="http://ws.apache.org/rampart/" rel="nofollow noreferrer">Apache Rampart</a> - the open source WS-Security implementation - in <a href="http://wso2.org/library" rel="nofollow noreferrer">WSO2 Online Library</a>.</p> <p><a href="http://wso2.org/downloads/wsf/php" rel="nofollow noreferrer">WSO2 WSF/PHP</a> is a PHP Web services extension that has support for WS-Security and also interops with .NET Web services/clients seamlessly.</p>
2,916
<p>I want to setup a CRON that runs a PHP script that in turn moves XML file (holding non-sensitive information) from one server to another. </p> <p>I have been given the proper username/password, and want to use SFTP protocol. The jobs will run daily. There is the potential that one server is Linux and the other is Windows. Both are on different networks. </p> <p>What is the best way to move that file?</p>
<p>If both servers would be on Linux you could use <a href="http://samba.anu.edu.au/rsync/" rel="noreferrer">rsync</a> for any kind of files (php, xml, html, binary, etc). Even if one of them will be Windows there are rsync ports to Windows.</p>
<p>I had some similar situation. After some tries, I did some thing different</p> <p>We have 2 servers, a (that have the original files) b (files should moved to it)</p> <p>And for sure the data is NOT sensitive</p> <p>Now in server a I made a file to do the following when called: 1. Choose the file to move 2. Zip the file 3. Print the .zip file location 4. Delete the .zip file (and the original file) if delete parameter passes</p> <p>In the server b the file should do: 1. Call the file on the a server 2. Download the zip file 3. Unzip and copy it to the proper location 4. Call the delete function on server a</p> <p>This way I have more control on my functions, tests and operations!</p>
30,352
<p>Hey, I'm really new to Haskell and have been using more classic programming languages my whole life. I have no idea what is going on here. I'm trying to make a very simple Viterbi algorithm implementation, but for only two states (honest and dishonest casino)</p> <p>I have a problem where I want to address my array, but I don't think I'm getting types right. That or I'm making a new array each time I try to address it - equally stupid. Look at myArray, te infix, and dynamicProgram especially, PLEASE. Pretty pretty please </p> <pre> Code <code> import Array import Char trans :: Int -> Int -> Double -> Double -> Double trans from x trans11 trans21 = if (from == 1) && (x == 1) then trans11 else if (from == 1) && (x == 2) then (1-trans11) else if (from == 2) && (x == 1) then trans21 else (1-trans21) em :: Char -> [Double] -> Double em c list = list!! a where a = digitToInt c intToChar :: Int -> Char intToChar n | n == 1 = '1' | n == 2 = '2' casino :: Char -> Int -> Int -> [Double] -> [Double] -> Double -> Double -> Double casino seqchar 1 y em1 em2 t1 t2= 0.5 * (em seqchar em1) casino seqchar 2 y em1 em2 t1 t2= 0.5 * (em seqchar em2) casino seqchar x y em1 em2 t1 t2= maximum[ (1 @@ y-1)*(em seqchar em1)*(trans 1 x t1 t2),(2 @@ y-1)*(em seqchar em2)*(trans 2 x t1 t2) ] dynamicProgram :: [Char] -> (Char -> Int -> Int -> [Double] -> [Double] -> Double -> Double -> Double) -> [Double] -> [Double] -> Double -> Double -> (Array a b) dynamicProgram string score list1 list2 trans11 trans21 = myArray 1 len [score (string!!y) x y list1 list2 trans11 trans21 | x Int -> [Double] -> Array a b myArray startIndex endIndex values = listArray (startIndex,startIndex) (endIndex,endIndex) values traceback :: [Char] -> Int -> Int -> [Double] -> [Double] -> Double -> Double -> [Char] traceback s 1 0 em1 em2 t1 t2 = [] traceback s 2 0 em1 em2 t1 t2 = [] traceback s x y em1 em2 t1 t2 | x@@y == (1 @@ y-1)*(em (s!!y) em1)*(trans 1 x t1 t2) = '1' : traceback s 1 (y-1) em1 em2 t1 t2 | x@@y == (2 @@ y-1)*(em (s!!y) em1)*(trans 2 x t1 t2) = '2' : traceback s 2 (y-1) em1 em2 t1 t2 answer :: [Char] -> [Double] -> [Double] -> Double -> Double -> [Char] answer string list1 list2 t1 t2 = reverse $ maxC : traceback string max end list1 list2 t1 t2 $ dynamicProgram casino string list1 list2 t1 t2 where end = (length string) + 1 max | maximum (1@@end) (2@@end) == 1@@end = 1 | maximum (1@@end) (2@@end) == 2@@end = 2 maxC = intToChar max infix 5 @@ (@@) i j = myArray ! (i, j) main = do putStrLn "What is the sequence to test?" seq state 1 transmission probability?" trp1 state 2 transmission probability is " ++ (1-trp1) putStrLn "What is the state 2 -> state 1 transmission probability?" trp2 state 2 transmission probability is " ++ (1-trp2) putStrLn "I assume that the prob of starting in either state is 1/2. Go!" answer seq st1 st2 trp1 trp2 </code></pre>
<p>I copied the code from the edit window (something in stackoverflow's parser is eating part of the code) and tried it on ghci, which found several errors. The first error was:</p> <pre><code>foo.hs:34:71: Couldn't match expected type `[e]' against inferred type `(a, b)' In the second argument of `listArray', namely `(endIndex, endIndex)' In the expression: listArray (startIndex, startIndex) (endIndex, endIndex) values In the definition of `myArray': myArray startIndex endIndex values = listArray (startIndex, startIndex) (endIndex, endIndex) values </code></pre> <p>The type of listArray is:</p> <pre><code>listArray :: (Ix i) =&gt; (i, i) -&gt; [e] -&gt; Array i e -- Defined in GHC.Arr </code></pre> <p>It takes a tuple with the lower and upper bounds and the list. So, the correct expression would probably be:</p> <pre><code>listArray (startIndex, endIndex) values </code></pre> <p>And the type of myArray is not <code>Array a b</code>, it is <code>Array Int Double</code>.</p> <p>The second error was:</p> <pre><code>foo.hs:43:44: Couldn't match expected type `a -&gt; b' against inferred type `[Char]' In the first argument of `($)', namely `maxC : (traceback string max end list1 list2 t1 t2)' In the second argument of `($)', namely `(maxC : (traceback string max end list1 list2 t1 t2)) $ (dynamicProgram casino string list1 list2 t1 t2)' In the expression: reverse $ ((maxC : (traceback string max end list1 list2 t1 t2)) $ (dynamicProgram casino string list1 list2 t1 t2)) </code></pre> <p><code>$</code> is right associative, so the rightmost <code>$</code> is looked at first. The first parameter to it must be a function, which it will call with its rightmost parameter as the argument. Here, however, it is a list.</p> <p>The third error was:</p> <pre><code>foo.hs:51:11: Couldn't match expected type `Array i e' against inferred type `Int -&gt; Int -&gt; [Double] -&gt; Array a b' In the first argument of `(!)', namely `myArray' In the expression: myArray ! (i, j) In the definition of `@@': @@ i j = myArray ! (i, j) </code></pre> <p><code>myArray</code> is not an array; it is a function which takes three parameters and constructs an array based on them.</p> <p>Here probably your being used to more traditional imperative languages is tripping you. In a traditional imperative language, it would be natural to have a global <code>myArray</code> variable which you then can access from the middle of your program. In Haskell however, absent more advanced trickery which you should not try while you are a beginner, a "global" variable is more like a constant value (which is lazily computed on first use, but which as far as you care could have been computed by the compiler while generating your executable). You cannot initialize it from values you read as input.</p> <p>Your best way around that is to pass the array through the program, which unfortunately will need several changes and negates the usefulness of your <code>@@</code> operator. You can hide the passing of the array in several more advanced ways, but while learning it is best to be more explicit.</p> <p>The last error was:</p> <pre><code>foo.hs:63:4: Couldn't match expected type `[a]' against inferred type `IO ()' In the first argument of `(++)', namely `putStrLn "I assume that the state 1 -&gt; state 2 transmission probability is "' In the expression: (putStrLn "I assume that the state 1 -&gt; state 2 transmission probability is ") ++ (1 - trp1) In a 'do' expression: (putStrLn "I assume that the state 1 -&gt; state 2 transmission probability is ") ++ (1 - trp1) </code></pre> <p>This has two errors: the one the compiler complained about is a precedence problem, as the compiler-added parenthesis readly show, and which can easily be fixed by correct application of either parenthesis or the <code>$</code> operator. The other error, which you will find after you fix this one, is that you cannot concatenate a string and a number; you have to convert the number to a string.</p> <p>This was all without looking at the algorithm or even most of the code, just looking at the compiler errors. If you want a two-dimensional array, for instance, the correct expression for the first error would be:</p> <pre><code>listArray ((startIndex, startIndex), (endIndex, endIndex)) values </code></pre> <p>Now both bounds are tuples, and its type is <code>Array (Int, Int) Double</code>.</p>
<p>You can rewrite the trans-function like this:</p> <pre><code>trans :: Int -&gt; Int -&gt; Double -&gt; Double -&gt; Double trans 1 1 trans11 trans21 = trans11 trans 1 2 trans11 trans21 = 1-trans11 trans 2 1 trans11 trans21 = trans21 trans _ _ trans11 trans21 = 1-trans21 </code></pre>
37,217
<p>I really don't know how to describe it, but if you understood it and had experience on that field, may be you can help me with something 'Open Source' and 'Ready-made'.</p> <p>I want to create something like a box 'or widget', where you can change its content by hitting some buttons on the top of the box. (Hey the box is on a web page and this should use Ajax and Javascript).</p> <p>I have tried some ready scritps, but I found them limited and they drive me crazy, JS frameworks also don't seems to offer such solution. Any body have any idea on that field?</p>
<p>Just because the box is on a Web page doesn't mean it should use AJAX, Omar. Have you thought about using a third-party solution like <a href="http://www.clearspring.com/" rel="nofollow noreferrer">ClearSpring</a> or <a href="http://www.widgetbox.com/" rel="nofollow noreferrer">WidgetBox</a>? If you need to put your widget onto Myspace, you'll want one of these.</p> <p>That said, I've taken a couple of JavaScript-only runs at this problem; see <a href="http://kentbrewster.com/twitterati" rel="nofollow noreferrer">Twitterati</a> and <a href="http://kentbrewster.com/put-your-digg-in-a-box" rel="nofollow noreferrer">Put Your Digg In A Box</a> for examples, and my <a href="http://kentbrewster.com/widget-summit/" rel="nofollow noreferrer">Global Widget Summit</a> presentation for explanations.</p>
<p>Have you tried Jquery?</p> <p>Visit www.jquery.com</p> <p>Some example can be found at <a href="http://www.openjs.com/scripts/events/keyboard_shortcuts/" rel="nofollow noreferrer">http://www.openjs.com/scripts/events/keyboard_shortcuts/</a></p> <p>Also please check the In-place editing example at <a href="http://www.appelsiini.net/projects/jeditable" rel="nofollow noreferrer">http://www.appelsiini.net/projects/jeditable</a> <a href="http://docs.jquery.com/Tutorials:Edit_in_Place_with_Ajax" rel="nofollow noreferrer">http://docs.jquery.com/Tutorials:Edit_in_Place_with_Ajax</a></p>
42,240
<p>Can anyone point me to an example of how to use ServletUnit to test JSP's? Do I need I need to call registerServlet()? If so, what class name do I pass?</p>
<p>You do not need to registerServlet if you are going use the default Jasper compiler. However, I needed Jasper jars and their dependencies on the CLASSPATH. The Maven dependencies I needed to get a basic JSP to compile and render were:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;tomcat&lt;/groupId&gt; &lt;artifactId&gt;jasper&lt;/artifactId&gt; &lt;version&gt;3.3.2&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;tomcat&lt;/groupId&gt; &lt;artifactId&gt;jasper-compiler&lt;/artifactId&gt; &lt;version&gt;5.5.23&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;tomcat&lt;/groupId&gt; &lt;artifactId&gt;tomcat-util&lt;/artifactId&gt; &lt;version&gt;5.5.23&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;tomcat&lt;/groupId&gt; &lt;artifactId&gt;core_util&lt;/artifactId&gt; &lt;version&gt;3.3.2&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; </code></pre> <p>I am stuck in a JDK1.4 project,so you may be able to use newer versions. I haven't gotten standard taglib working yet...</p>
<p>This is what I´m using now for testing JSP render and verify forms and forwards.</p> <p>First Maven dependencies</p> <pre><code> &lt;!-- Testing JSP --&gt; &lt;dependency&gt; &lt;groupId&gt;net.sourceforge.openutils&lt;/groupId&gt; &lt;artifactId&gt;openutils-testing4web&lt;/artifactId&gt; &lt;version&gt;1.2.1&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;exclusions&gt; &lt;exclusion&gt; &lt;artifactId&gt;slf4j-log4j12&lt;/artifactId&gt; &lt;groupId&gt;org.slf4j&lt;/groupId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;artifactId&gt;spring-core&lt;/artifactId&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;artifactId&gt;spring-context&lt;/artifactId&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;artifactId&gt;slf4j-api&lt;/artifactId&gt; &lt;groupId&gt;org.slf4j&lt;/groupId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;artifactId&gt;jcl-over-slf4j&lt;/artifactId&gt; &lt;groupId&gt;org.slf4j&lt;/groupId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;artifactId&gt;jsp-api&lt;/artifactId&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;artifactId&gt;jasper-runtime&lt;/artifactId&gt; &lt;groupId&gt;tomcat&lt;/groupId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;artifactId&gt;jasper-compiler&lt;/artifactId&gt; &lt;groupId&gt;tomcat&lt;/groupId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;artifactId&gt;jasper-compiler-jdt&lt;/artifactId&gt; &lt;groupId&gt;tomcat&lt;/groupId&gt; &lt;/exclusion&gt; &lt;/exclusions&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.tomcat&lt;/groupId&gt; &lt;artifactId&gt;catalina&lt;/artifactId&gt; &lt;version&gt;${tomcat.version}&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.tomcat&lt;/groupId&gt; &lt;artifactId&gt;servlet-api&lt;/artifactId&gt; &lt;version&gt;${tomcat.version}&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.tomcat&lt;/groupId&gt; &lt;artifactId&gt;jasper&lt;/artifactId&gt; &lt;version&gt;${tomcat.version}&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.tomcat&lt;/groupId&gt; &lt;artifactId&gt;jasper-el&lt;/artifactId&gt; &lt;version&gt;${tomcat.version}&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.tomcat&lt;/groupId&gt; &lt;artifactId&gt;jsp-api&lt;/artifactId&gt; &lt;version&gt;${tomcat.version}&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;javax.servlet-api&lt;/artifactId&gt; &lt;version&gt;${javax.servlet.version}&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.tomcat&lt;/groupId&gt; &lt;artifactId&gt;jasper-jdt&lt;/artifactId&gt; &lt;version&gt;6.0.29&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;!-- log configuration --&gt; </code></pre> <p>tomcat.version is 6.0.39 you feel free to try modern tomcat version, 7 or 8 but be care about dependencies sometimes becomes a bit fuzzy.</p> <p>javax.servlet.version is 3.0.1</p> <p>Next I've defined a common testing class which are extended by all my testings. I have a testing class per controller.</p> <pre><code> import it.openutils.testing.junit.AbstractDbUnitJunitSpringContextTests; import org.junit.After; import org.junit.Before; import org.junit.runner.RunWith; import org.springframework.core.io.Resource; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; import org.springframework.test.context.transaction.TransactionalTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.meterware.servletunit.ServletRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "/integration/application-database-test.xml", "/integration/mvc-dispatcher-servlet-test.xml" }) @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class }) public abstract class ControllerIntegrationCommonTest extends AbstractDbUnitJunitSpringContextTests { /** * The Web CLient for JSP rendeting Test */ protected ServletRunner servletRunner; /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { Resource web = this.applicationContext.getResource("/WEB-INF/web.xml"); if (servletRunner == null) { servletRunner = new ServletRunner(web.getFile(),null); } } @After public void setDown() throws Exception { servletRunner.shutDown(); } } </code></pre> <p>The @ContextConfiguration, @TestExecutionListeners are needed if you want to run it all from Spring Junit context, if you delete then you will get a nice java.lang.IllegalStateException : Failed to load ApplicationConext.</p> <p>Notice here that I instantiate the ServletRunner using a Web.xml. This is mandatory of course and very similar to my production one. The second parameter, the contextPath is set to Null. For my testing I don't needed. I refer you to the <a href="http://httpunit.sourceforge.net/doc/api/com/meterware/servletunit/ServletRunner.html" rel="nofollow">API</a> for more complete info.</p> <p>Once you have that configured, make the test is easy. I add to examples:</p> <pre><code>PostMethodWebRequest webRequest = new PostMethodWebRequest("http://myserver/setup/checkXML",true); webRequest.setParameter("param1", "11112"); File file = new File("src/test/resources/datasets/myxml.xml"); webRequest.selectFile("fileData",file,"multipart/form-data"); WebResponse webResponse = servletRunner.getResponse(webRequest); assertNotNull(webResponse); assertTrue(webResponse.getURL().getPath().contains("checkXML")); assertNotNull(webResponse.getElementsByTagName("resultCheck")); log.debug(" ----------------- "); log.debug(webResponse.getText()); log.debug(" ----------------- "); webResponse.getFormWithID("resultsForm").getSubmitButtons()[0].click(); </code></pre> <p>In this example I will make a Post uploading a file. You need to create the PostMethodWebRequest with the parameter mimeencoded set as true. If no, you will get some funny error messages. For add the file just only used the methods. You can see in the API you can upload one file or a set of.</p> <p>This last example is just for make Get request</p> <pre><code> GetMethodWebRequest webRequest = new GetMethodWebRequest("http://myserver/setup/addarea"); webRequest.setParameter("param", "11"); WebResponse webResponse = servletRunner.getResponse(webRequest); assertNotNull(webResponse); assertTrue(webResponse.getURL().getPath().contains("addsomething")); assertNotNull(webResponse.getElementsByTagName("listofsomething")); assertNotNull(webResponse.getElementsByTagName("someelement")); log.debug(" ----------------- "); log.debug(webResponse.getText()); log.debug(" ----------------- "); </code></pre> <p>In this example I make a Get request to my controller. As in the previous on, I send some parameters and then get the Response. There I check if the URL is what I expected and verify the JSP has render some elements.</p> <p>Notice that for build the WebRequest I must use a well format URL but no problem about server name, Servlet Unit not use it at all you don't need to define in in any place.</p> <p>I hope it helps you. Have fun!!</p>
38,003
<p>I am writing a game in python and have decided to create a DSL for the map data files. I know I could write my own parser with regex, but I am wondering if there are existing python tools which can do this more easily, like re2c which is used in the PHP engine.</p> <p>Some extra info:</p> <ul> <li>Yes, I <em>do</em> need a DSL, and even if I didn't I still want the experience of building and using one in a project.</li> <li><p>The DSL contains only data (declarative?), it doesn't get "executed". Most lines look like:</p> <p><code>SOMETHING: !abc @123 #xyz/123</code></p> <p>I just need to read the tree of data.</p></li> </ul>
<p>I've always been impressed by <a href="http://pyparsing.wikispaces.com/" rel="noreferrer">pyparsing</a>. The author, Paul McGuire, is active on the <a href="http://mail.python.org/mailman/listinfo/python-list" rel="noreferrer">python list</a>/<a href="http://groups.google.com/group/comp.lang.python" rel="noreferrer">comp.lang.python</a> and has always been very helpful with any queries concerning it.</p>
<p>On the lines of declarative python, I wrote a helper module called 'bpyml' which lets you declare data in python in a more XML structured way without the verbose tags, it can be converted to/from XML too, but is valid python.</p> <p><a href="https://svn.blender.org/svnroot/bf-blender/trunk/blender/release/scripts/modules/bpyml.py" rel="nofollow">https://svn.blender.org/svnroot/bf-blender/trunk/blender/release/scripts/modules/bpyml.py</a></p> <p>Example Use <a href="http://wiki.blender.org/index.php/User:Ideasman42#Declarative_UI_In_Blender" rel="nofollow">http://wiki.blender.org/index.php/User:Ideasman42#Declarative_UI_In_Blender</a></p>
44,051
<p>I'm working on some code to colorize an image in Java. Basically what I'd like to do is something along the lines of GIMP's colorize command, so that if I have a BufferedImage and a Color, I can colorize the Image with the given color. Anyone got any ideas? My current best guess at doing something like this is to get the rgb value of each pixel in the BufferedImage and add the RGB value of the Color to it with some scaling factor.</p>
<p>Let <code>Y = 0.3*R + 0.59*G + 0.11*B</code> for each pixel in the image, then set them to be</p> <p><code>((R1+Y)/2,(G1+Y)/2,(B1+Y)/2)</code></p> <p>if <code>(R1,G1,B1)</code> is what you are colorizing with.</p>
<p>I wanted to do the exact same thing as the question poster wanted to do but the above conversion did not remove colors like the GIMP does (ie green with a red overlay made an unpleasant brown color etc). So I downloaded the source code for GIMP and converted the c code over to Java.</p> <p>Posting it in this thread just in case anyone else wants to do the same (since it is the first thread that comes up in Google). The conversion still changes the white color when it should not, it's probably a casting issue from double to int. The class converts a BufferedImage in-place.</p> <pre><code>public class Colorize { public static final int MAX_COLOR = 256; public static final float LUMINANCE_RED = 0.2126f; public static final float LUMINANCE_GREEN = 0.7152f; public static final float LUMINANCE_BLUE = 0.0722f; double hue = 180; double saturation = 50; double lightness = 0; int [] lum_red_lookup; int [] lum_green_lookup; int [] lum_blue_lookup; int [] final_red_lookup; int [] final_green_lookup; int [] final_blue_lookup; public Colorize( int red, int green, int blue ) { doInit(); } public Colorize( double t_hue, double t_sat, double t_bri ) { hue = t_hue; saturation = t_sat; lightness = t_bri; doInit(); } public Colorize( double t_hue, double t_sat ) { hue = t_hue; saturation = t_sat; doInit(); } public Colorize( double t_hue ) { hue = t_hue; doInit(); } public Colorize() { doInit(); } private void doInit() { lum_red_lookup = new int [MAX_COLOR]; lum_green_lookup = new int [MAX_COLOR]; lum_blue_lookup = new int [MAX_COLOR]; double temp_hue = hue / 360f; double temp_sat = saturation / 100f; final_red_lookup = new int [MAX_COLOR]; final_green_lookup = new int [MAX_COLOR]; final_blue_lookup = new int [MAX_COLOR]; for( int i = 0; i &lt; MAX_COLOR; ++i ) { lum_red_lookup [i] = ( int )( i * LUMINANCE_RED ); lum_green_lookup[i] = ( int )( i * LUMINANCE_GREEN ); lum_blue_lookup [i] = ( int )( i * LUMINANCE_BLUE ); double temp_light = (double)i / 255f; Color color = new Color( Color.HSBtoRGB( (float)temp_hue, (float)temp_sat, (float)temp_light ) ); final_red_lookup [i] = ( int )( color.getRed() ); final_green_lookup[i] = ( int )( color.getGreen() ); final_blue_lookup [i] = ( int )( color.getBlue() ); } } public void doColorize( BufferedImage image ) { int height = image.getHeight(); int width; while( height-- != 0 ) { width = image.getWidth(); while( width-- != 0 ) { Color color = new Color( image.getRGB( width, height ) ); int lum = lum_red_lookup [color.getRed ()] + lum_green_lookup[color.getGreen()] + lum_blue_lookup [color.getBlue ()]; if( lightness &gt; 0 ) { lum = (int)((double)lum * (100f - lightness) / 100f); lum += 255f - (100f - lightness) * 255f / 100f; } else if( lightness &lt; 0 ) { lum = (int)(((double)lum * lightness + 100f) / 100f); } Color final_color = new Color( final_red_lookup[lum], final_green_lookup[lum], final_blue_lookup[lum], color.getAlpha() ); image.setRGB( width, height, final_color.getRGB() ); } } } </code></pre>
4,362
<p>I just read <a href="https://stackoverflow.com/questions/72271/no-newline-at-end-of-file-compiler-warning">this post</a> about why new-line warnings exist, but to be honest my team has people working on several different platforms and with several different editors (everyone uses what bests suites them), so the warning has become ubiquitous, and since its not really a warning worth taking care of it's become noise and makes finding serious warnings a hassle. </p> <p>Many times important warnings have gone unnoticed because, people got used to having a gazillion useless warnings pass by, so they obviously just stop looking at them carefully, and with reason IMHO. One could say in our case GCC is crying wolf too much for anyone to take it seriously anymore, which is a bad attitude but its just human nature. </p> <p>Right now we compile with <code>-Wall</code>, because we want warnings, but is there a counter flag to avoid the new-line warnings?</p> <p><strong>Note:</strong> I Looked through the manual a bit but didn't find the answer in any place obvious so I gave up.</p> <p><strong>Note:</strong> In response to Robert Gamble's totally reasonable solution, our code is cross-platform and we have people and builds on Linux, Solaris and Windows, so the new-line... is not under consensus. And Somebody's compiler is always going to cry-wolf. Because there are over 40 developers, and other non programmer staff as well.</p>
<p>There isn't one as far as i know, i've used GCC for years.</p> <p><strong>Update:</strong> There should not be any warnings raised with C++11 standard. <a href="https://stackoverflow.com/a/72409/463758">Related Q</a></p>
<p>I'm 90% sure there is no arguemnt to turn this off.</p> <p>The reason for the warning is that files without an endline give undefined behavior when compiled:</p> <p>See standard: <a href="http://c0x.coding-guidelines.com/5.1.1.2.html" rel="nofollow noreferrer">http://c0x.coding-guidelines.com/5.1.1.2.html</a></p> <p>Here's a blog post with some python code (that I have not tried) which says it will fixup source files with this issue.</p> <p><a href="http://www.johndcook.com/blog/tag/gcc/" rel="nofollow noreferrer">http://www.johndcook.com/blog/tag/gcc/</a></p>
35,833
<p>I have multiple layers in an application and i find myself having to bubble up events to the GUI layer for doing status bar changes, etc . . I find myself having to write repeated coded where each layer simply subscribes to events from the lower layer and then in the call back simply raise an event up the chain. Is there a more efficient way of doing this?</p>
<p>If all you're doing is firing an event handler from another event handler, you can cut out the middle man and hook the event handlers directly in the add/remove blocks for the event.</p> <p>For example, if you have a UserControl with a "SaveButtonClick" event, and all you want to do when is call the event handler when the "SaveButton" on your UserControl is clicked, you can do this:</p> <pre><code>public event EventHandler SaveButtonClick { add { this.SaveButton.Click += value; } remove { this.SaveButton.Click -= value; } } </code></pre> <p>Now you don't need any code to fire the SaveButtonClick event - it will automatically be fired when the SaveButton.Click event is raised (ie when someone clicks that button).</p>
<p>You can have a central channel that only support events. This channel must be independent so the layer only publish or subscribe to it.</p>
26,700
<p>I haven't touched sharepoint in years. If I want to setup a development environment to get up to speed, what options do I have? I don't have an MSDN license, is there anyway I can get up and running for free? (for development only)</p>
<p>You <strong>need</strong> a Windows 2003 Server (or 2008 Server, but I have no experience with that), no way around that. You can then of course use Visual C# 2005 Express and the SHarepoint Services 3.0 if that's your target.</p> <p>If you want to do development on Sharepoint 2007, you have to buy a Sharepoint 2007 license, which has a pretty hefty fee attached to it.</p> <p>As a SQL, SQL 2005 Express works fine for development.</p> <p>There is a good Article how to set up Sharepoint on a Single Server:</p> <p><a href="http://blogs.msdn.com/martinkearn/archive/2007/03/28/how-to-install-sharepoint-server-2007-on-a-single-machine.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/martinkearn/archive/2007/03/28/how-to-install-sharepoint-server-2007-on-a-single-machine.aspx</a></p> <p>You CAN use a Trial Version of Windows 2003 and Sharepoint 2007 though if it's only needed for a limited time (i believe the Trials run 180 days).</p>
<p>The action pack is fantastic value, you can use the Windows Server from that, as well as SharePoint Enterprise / Standard.</p>
3,275
<p><code>std::swap()</code> is used by many std containers (such as <code>std::list</code> and <code>std::vector</code>) during sorting and even assignment.</p> <p>But the std implementation of <code>swap()</code> is very generalized and rather inefficient for custom types.</p> <p>Thus efficiency can be gained by overloading <code>std::swap()</code> with a custom type specific implementation. But how can you implement it so it will be used by the std containers?</p>
<p>The right way to overload <code>std::swap</code>'s implemention (aka specializing it), is to write it in the same namespace as what you're swapping, so that it can be found via <a href="https://en.cppreference.com/w/cpp/language/adl" rel="noreferrer">argument-dependent lookup (ADL)</a>. One particularly easy thing to do is:</p> <pre><code>class X { // ... friend void swap(X&amp; a, X&amp; b) { using std::swap; // bring in swap for built-in types swap(a.base1, b.base1); swap(a.base2, b.base2); // ... swap(a.member1, b.member1); swap(a.member2, b.member2); // ... } }; </code></pre>
<p>While it's correct that one shouldn't generally add stuff to the std:: namespace, adding template specializations for user-defined types is specifically allowed. Overloading the functions is not. This is a subtle difference :-)</p> <blockquote> <p>17.4.3.1/1 It is undefined for a C++ program to add declarations or definitions to namespace std or namespaces with namespace std unless otherwise specified. A program may add template specializations for any standard library template to namespace std. Such a specialization (complete or partial) of a standard library results in undefined behaviour unless the declaration depends on a user-defined name of external linkage and unless the template specialization meets the standard library requirements for the original template. </p> </blockquote> <p>A specialization of std::swap would look like:</p> <pre><code>namespace std { template&lt;&gt; void swap(myspace::mytype&amp; a, myspace::mytype&amp; b) { ... } } </code></pre> <p>Without the template&lt;> bit it would be an overload, which is undefined, rather than a specialization, which is permitted. @Wilka's suggest approach of changing the default namespace may work with user code (due to Koenig lookup preferring the namespace-less version) but it's not guaranteed to, and in fact isn't really supposed to (the STL implementation ought to use the fully-qualified std::swap).</p> <p>There is a <a href="http://groups.google.ca/group/comp.lang.c++.moderated/browse_thread/thread/b396fedad7dcdc81" rel="noreferrer">thread on comp.lang.c++.moderated</a> with a <strong>long</strong> dicussion of the topic. Most of it is about partial specialization, though (which there's currently no good way to do).</p>
3,265
<p>I saw Scott Meyers' <a href="https://rads.stackoverflow.com/amzn/click/com/0321334876" rel="nofollow noreferrer" rel="nofollow noreferrer">"Effective C++"</a> third edition book having a small section on "Template Programming".</p> <p>Any other book/links containing information on "effective" usage of templates ?</p>
<p>I like <a href="https://rads.stackoverflow.com/amzn/click/com/0201704315" rel="nofollow noreferrer" rel="nofollow noreferrer">Modern C++ Design: Generic Programming and Design Patterns Applied</a>. I found it very well written and clear. Contains a few advanced topics.</p> <p><a href="https://i.stack.imgur.com/Apkdl.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Apkdl.jpg" alt="alt text"></a> </p>
<p>Scott Meyers deals with the Standard Template Library in <a href="https://rads.stackoverflow.com/amzn/click/com/0201749629" rel="nofollow noreferrer" rel="nofollow noreferrer">Effective STL</a>. That may be relevant for you.</p>
23,171
<p>I'm trying out asp.net mvc for a new project, and I ran across something odd. When I use the MVC UI helpers for textboxes, the values get persisted between calls. But, when I use a series of radio buttons, the checked state doesn't get persisted.</p> <p>Here's an example from my view.</p> <pre><code>&lt;li&gt; &lt;%=Html.RadioButton("providerType","1")%&gt;&lt;label&gt;Hospital&lt;/label&gt; &lt;%=Html.RadioButton("providerType","2")%&gt;&lt;label&gt;Facility&lt;/label&gt; &lt;%=Html.RadioButton("providerType","3")%&gt;&lt;label&gt;Physician&lt;/label&gt; &lt;/li&gt; </code></pre> <p>When the form gets posted back, I build up an object with "ProviderType" as one of it's properties. The value on the object is getting set, and then I RedirectToAction with the provider as a argument. All is well, and I end up at a URL like "<a href="http://localhost/Provider/List?ProviderType=1" rel="noreferrer">http://localhost/Provider/List?ProviderType=1</a>" with ProviderType showing. The value gets persisted to the URL, but the UI helper isn't picking up the checked state.</p> <p>I'm having this problem with listbox, <strike>dropdownlist</strike>, and radiobutton. Textboxes pick up the values just fine. Do you see something I'm doing wrong? I'm assuming that the helpers will do this for me, but maybe I'll just have to take care of this on my own. I'm just feeling my way through this, so your input is appreciated.</p> <p><strong>Edit:</strong> I just found the override for the SelectList constructor that takes a selected value. That took care of my dropdown issue I mentioned above.</p> <p><strong>Edit #2:</strong> I found something that works, but it pains me to do it this way. I feel like this should be inferred.</p> <pre><code>&lt;li&gt; &lt;%=Html.RadioButton("ProviderType","1",Request["ProviderType"]=="1")%&gt;&lt;label&gt;Hospital&lt;/label&gt; &lt;%=Html.RadioButton("ProviderType", "2", Request["ProviderType"] == "2")%&gt;&lt;label&gt;Facility&lt;/label&gt; &lt;%=Html.RadioButton("ProviderType", "3", Request["ProviderType"] == "3")%&gt;&lt;label&gt;Physician&lt;/label&gt; &lt;/li&gt; </code></pre> <p>Hopefully someone will come up with another way.</p>
<p>If you give the radio buttons the same name as the property on your model, then MVC will automatically set the checked attribute on the appropriate button.</p> <p>I think this relies on having a strongly typed Model.</p>
<p>View:</p> <pre><code>&lt;%=Html.RadioButton("providerType","1")%&gt;&lt;label&gt;Hospital&lt;/label&gt; &lt;%=Html.RadioButton("providerType","2")%&gt;&lt;label&gt;Facility&lt;/label&gt; &lt;%=Html.RadioButton("providerType","3")%&gt;&lt;label&gt;Physician&lt;/label&gt; </code></pre> <p>Controller:</p> <pre><code>public ActionResult GetType(FormCollection collection) { string type=collection.Get("providerType"); if(type=="1") //code else if(type=="2") //code else //code return View(); } </code></pre>
32,964
<p>While researching this issue, I found multiple mentions of the following scenario online, invariably as unanswered questions on programming forums. I hope that posting this here will at least serve to document my findings.</p> <p>First, the symptom: While running pretty standard code that uses waveOutWrite() to output PCM audio, I sometimes get this when running under the debugger:</p> <pre><code> ntdll.dll!_DbgBreakPoint@0() ntdll.dll!_RtlpBreakPointHeap@4() + 0x28 bytes ntdll.dll!_RtlpValidateHeapEntry@12() + 0x113 bytes ntdll.dll!_RtlDebugGetUserInfoHeap@20() + 0x96 bytes ntdll.dll!_RtlGetUserInfoHeap@20() + 0x32743 bytes kernel32.dll!_GlobalHandle@4() + 0x3a bytes wdmaud.drv!_waveCompleteHeader@4() + 0x40 bytes wdmaud.drv!_waveThread@4() + 0x9c bytes kernel32.dll!_BaseThreadStart@8() + 0x37 bytes </code></pre> <p>While the obvious suspect would be a heap corruption somewhere else in the code, I found out that that's not the case. Furthermore, I was able to reproduce this problem using the following code (this is part of a dialog based MFC application:)</p> <pre><code>void CwaveoutDlg::OnBnClickedButton1() { WAVEFORMATEX wfx; wfx.nSamplesPerSec = 44100; /* sample rate */ wfx.wBitsPerSample = 16; /* sample size */ wfx.nChannels = 2; wfx.cbSize = 0; /* size of _extra_ info */ wfx.wFormatTag = WAVE_FORMAT_PCM; wfx.nBlockAlign = (wfx.wBitsPerSample &gt;&gt; 3) * wfx.nChannels; wfx.nAvgBytesPerSec = wfx.nBlockAlign * wfx.nSamplesPerSec; waveOutOpen(&amp;hWaveOut, WAVE_MAPPER, &amp;wfx, (DWORD_PTR)m_hWnd, 0, CALLBACK_WINDOW ); ZeroMemory(&amp;header, sizeof(header)); header.dwBufferLength = 4608; header.lpData = (LPSTR)GlobalLock(GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE | GMEM_ZEROINIT, 4608)); waveOutPrepareHeader(hWaveOut, &amp;header, sizeof(header)); waveOutWrite(hWaveOut, &amp;header, sizeof(header)); } afx_msg LRESULT CwaveoutDlg::OnWOMDone(WPARAM wParam, LPARAM lParam) { HWAVEOUT dev = (HWAVEOUT)wParam; WAVEHDR *hdr = (WAVEHDR*)lParam; waveOutUnprepareHeader(dev, hdr, sizeof(WAVEHDR)); GlobalFree(GlobalHandle(hdr-&gt;lpData)); ZeroMemory(hdr, sizeof(*hdr)); hdr-&gt;dwBufferLength = 4608; hdr-&gt;lpData = (LPSTR)GlobalLock(GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE | GMEM_ZEROINIT, 4608)); waveOutPrepareHeader(hWaveOut, &amp;header, sizeof(WAVEHDR)); waveOutWrite(hWaveOut, hdr, sizeof(WAVEHDR)); return 0; } </code></pre> <p>Before anyone comments on this, yes - the sample code plays back uninitialized memory. Don't try this with your speakers turned all the way up.</p> <p>Some debugging revealed the following information: waveOutPrepareHeader() populates header.reserved with a pointer to what appears to be a structure containing at least two pointers as its first two members. The first pointer is set to NULL. After calling waveOutWrite(), this pointer is set to a pointer allocated on the global heap. In pseudo code, that would look something like this:</p> <pre><code>struct Undocumented { void *p1, *p2; } /* This might have more members */ MMRESULT waveOutPrepareHeader( handle, LPWAVEHDR hdr, ...) { hdr-&gt;reserved = (Undocumented*)calloc(sizeof(Undocumented)); /* Do more stuff... */ } MMRESULT waveOutWrite( handle, LPWAVEHDR hdr, ...) { /* The following assignment fails rarely, causing the problem: */ hdr-&gt;reserved-&gt;p1 = malloc( /* chunk of private data */ ); /* Probably more code to initiate playback */ } </code></pre> <p>Normally, the header is returned to the application by waveCompleteHeader(), a function internal to wdmaud.dll. waveCompleteHeader() tries to deallocate the pointer allocated by waveOutWrite() by calling GlobalHandle()/GlobalUnlock() and friends. Sometimes, GlobalHandle() bombs, as shown above.</p> <p>Now, the reason that GlobalHandle() bombs is not due to a heap corruption, as I suspected at first - it's because waveOutWrite() returned without setting the first pointer in the internal structure to a valid pointer. I suspect that it frees the memory pointed to by that pointer before returning, but I haven't disassembled it yet.</p> <p>This only appears to happen when the wave playback system is low on buffers, which is why I'm using a single header to reproduce this.</p> <p>At this point I have a pretty good case against this being a bug in my application - after all, my application is not even running. Has anyone seen this before?</p> <p>I'm seeing this on Windows XP SP2. The audio card is from SigmaTel, and the driver version is 5.10.0.4995.</p> <p>Notes:</p> <p>To prevent confusion in the future, I'd like to point out that the answer suggesting that the problem lies with the use of malloc()/free() to manage the buffers being played is simply wrong. You'll note that I changed the code above to reflect the suggestion, to prevent more people from making the same mistake - it doesn't make a difference. The buffer being freed by waveCompleteHeader() is not the one containing the PCM data, the responsibility to free the PCM buffer lies with the application, and there's no requirement that it be allocated in any specific way.</p> <p>Also, I make sure that none of the waveOut API calls I use fail.</p> <p>I'm currently assuming that this is either a bug in Windows, or in the audio driver. Dissenting opinions are always welcome.</p>
<p>You're not alone with this issue: <a href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=100589" rel="nofollow noreferrer">http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=100589</a></p>
<p>Not sure about this particular problem, but have you considered using a higher-level, cross-platform audio library? There are a lot of quirks with Windows audio programming, and these libraries can save you a lot of headaches.</p> <p>Examples include <a href="http://portaudio.com" rel="nofollow noreferrer">PortAudio</a>, <a href="http://www.music.mcgill.ca/~gary/rtaudio/" rel="nofollow noreferrer">RtAudio</a>, and <a href="http://www.libsdl.org/" rel="nofollow noreferrer">SDL</a>.</p>
23,780
<p>Is there any way to configure SQL Server 2000 Standard Edition (32 bit) to use more than 2Gb of memory on a server running Windows 2003 (64 bit)?</p> <p>Thanks for any help.</p>
<p>32 bit versions of SQL Server with Advanced Windowing Extensions (AWE) disabled can only access 2 GB of memory, (or 3 GB if the /3gb switch is used in boot.ini - although I'm not sure off the top of my head if this will work on 64 bit Windows). This is regardless of whether they are running on Windows 2003 32 bit or 64 bit.</p> <p>Additionally, SQL Server 2000 Standard Edition cannot turn AWE on (it's an Enterprise-only feature), so you're restricted to the 2 GB limit.</p> <p>Your best bet is to see about upgrading to SQL Server 2005 Standard (32 or 64 bit - 32 bit Standard can use AWE), or the much pricier SQL Server 2000 Enterprise Edition. As SQL Server 2000 has reached End of Life, my suggestion would be to go the 2005 Standard route. </p>
<p>It appears that this Microsoft article is of relevance:</p> <p><a href="http://support.microsoft.com/kb/274750" rel="nofollow noreferrer">How to configure SQL Server to use more than 2 GB of physical memory</a></p>
41,616
<p>I'm looking to patch a piece of abandonware with some code.</p> <p>The software is carbon based, so I can not use an InputManager (at least, I do not think I can). My idea was to add a dylib reference to the mach-o header, and launch a new thread when the initialization routine is called.</p> <p>I have mucked around with the mach-o header using a hexeditor to add the appropriate load command (LC_ LOAD_DYLIB). </p> <p>otool reports what I expect to see, so I'm fairly confident that the file is correctly formatted.</p> <pre> Load command 63 cmd LC_LOAD_DYLIB cmdsize 60 name @executable_path/libAltInput.dylib (offset 24) time stamp 1183743291 Fri Jul 6 19:34:51 2007 current version 0.0.0 compatibility version 0.0.0 </pre> <p>However, launching the binary gives me the following error</p> <pre> dyld: bad external relocation length </pre> <p>All I can guess this means is that I need to modify the LC_ SYMTAB or LC_ DYNSYMTAB sections...</p> <p>Anyone have any ideas?</p>
<p>I'm not entirely sure what you're trying to accomplish, but the easiest way to do this is probably to inject a thread into the mach task after it starts. A great source of information on doing this (as well as running code to do it) can be found here: <a href="http://rentzsch.com/mach_inject/" rel="noreferrer">http://rentzsch.com/mach_inject/</a>.</p> <p>Some caveats that you should be aware of:</p> <ol> <li>the mach task_for_pid() call necessary to get the mach port to the task is now privleged and requires authorization to call. The reason for this is pretty self-evident but if you were planning on releasing something with injected code, you should be aware of this.</li> <li>Your code will be running in the same process space as the original application but on a separate thread. You will, therefore, have full access to the application, however, if it is not thread-aware be very careful about using and manipulating data from outside of your injected code. Obviously all multithreaded issues will be amplified here because the original code was never aware of your additions.</li> </ol>
<p>The easiest solution that doesn't involve patching the binary is to simply use the DYLD_INSERT_LIBRARIES environment variable and then run your application.</p> <pre><code>set DYLD_INSERT_LIBRARIES to /my/path/libAltInput.dylib </code></pre> <p>I'm assuming the reason the dynamic linker reported an error is because many fields in the Mach-O file format contain addresses specified as an offset from the beginning of the file so adding another load command would invalidate every address. For example, see the <code>symoff</code> and <code>stroff</code> entries in the <a href="http://developer.apple.com/Mac/library/documentation/DeveloperTools/Conceptual/MachORuntime/Reference/reference.html#//apple_ref/c/tag/symtab_command" rel="nofollow noreferrer">Mac OS X ABI Mach-O File Format Reference</a>.</p>
34,399
<p>It seems that any kind of graphic library like <a href="http://www.directfb.org/" rel="noreferrer">DirectFB</a> or <a href="http://www.minigui.org/" rel="noreferrer">MiniGui</a> requires some sort of underlying operation system like Linux or uClinux.</p> <p>I am challenged with writing a software for a micro controller with just 512kb flash, an LCD display and a touchscreen to display and handle some pictures and GUI parts.</p> <p>Do you know any library which just need a pointer to the video memory that also can handle lines, images and fonts?</p>
<p>We have used "PEG", the C++ version, from Swellsoftware for many years. It is commercial software, not free, but the underlying screen driver can use just a pointer to graphics memory and they provide many sample drivers for different types of graphics hardware. We wrote our own custom driver(s) for our proprietary hardware, using the sample drivers as reference. We have always had some sort of RTOS, but I believe PEG+ can also operate without an OS.</p> <p>Check it out here: <a href="http://www.swellsoftware.com/" rel="noreferrer">http://www.swellsoftware.com/</a></p> <p>good luck,</p>
<p>512kb is small. Good luck!</p> <p>You might want to try a <a href="http://www.damnsmalllinux.org/" rel="nofollow noreferrer">dsl</a> combined with <a href="http://www.mplayerhq.hu/" rel="nofollow noreferrer">mplayer</a>. The latter does not need a GUI to display a movie. I guess it could also display images.</p> <p>Nonetheless I fear it will be too much for your flash. Maybe the source of these links will help.</p>
47,813
<p>I printed a case for my phone, a Motorola G4 Plus. I found the model of the casing on <a href="https://www.thingiverse.com/thing:2482011" rel="nofollow noreferrer">Thingiverse</a></p> <p>I just downloaded the model, used Meshmixer to check for issues, after that, opened Simplify3d and saved it for printing using an SD Card. The printed size of the model was smaller than expected.</p> <p>The model designer, says in the description that he used flexible filament. Is it possible than if I change to that filament, the model result is completely different? </p> <p>Print result - phone casing:</p> <p><a href="https://i.stack.imgur.com/T6V14.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T6V14.jpg" alt="1"></a> <a href="https://i.stack.imgur.com/nDTld.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nDTld.jpg" alt="2"></a> <a href="https://i.stack.imgur.com/S71JO.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/S71JO.jpg" alt="3"></a></p>
<p>In short: Not really.</p> <p>longer version: It depends.</p> <p>The main culprit of losing details in this case would be the weight and speed of the thing moving. So if you have a heavy X-axis carriage, acceleration and decelerating the carriage won't be instant. Same with the bed (Y-axis).</p> <p>Another culprit can be slop in the system, so check your linear bearings and belt tension.</p> <p>Also keep in mind that you are printing on the bed, so the weight of the Y-axis increases while the print progresses. This shouldn't be a problem for small prints, but if your print becomes bigger it can decrease the quality. Another factor is that every print will bend a little the higher it gets, so if you print a tall slender object, don't accelerate the bed too fast ;)</p> <p>To summarize, for high detailed prints:</p> <ul> <li>Lower the speed</li> <li>Check the system for slop (tighten belts, and align linear bearings)</li> <li>Take the lightest axis for the highest detail (keep the weight of the print in mind)</li> </ul> <p>One thing that you can do to test your machine is to test the ghosting on each axis (<a href="https://www.thingiverse.com/thing:277394" rel="nofollow noreferrer">https://www.thingiverse.com/thing:277394</a>).</p>
<p>I'm under the impression that your question hints on rectilinear motion by aligning the print part to the axes motion of the printer. So, placing it under 45&deg; would suggest movement of both steppers to make a straight line opposed to one stepper movement for a straight line.</p> <p>Basically, the weight of the carriage and the play in the system determine the quality of the details. Not how much steppers are involved to print the part. As an example, CoreXY or H-bot style printers use 2 steppers to print a straight line and a single stepper to print diagonally. These printers are capable of producing very accurate prints.</p> <p>On a Prusa i3 style printer it is not expected to see large differences unless you print very fast so that the inertia or play take a predominant role in the quality.</p>
1,302
<p>I have a ASP.net 2.0 app and I have made some changes the the source file ( cs files ). I uploaded the changes with the belief that it would auto-recompile. I also have the compiled dll in MY_APP/bin. I checked it and noticed that it did not recompile. Please understand I am new to this.</p>
<p>my #1 way to do this, add white space to the top of the web config file, after the xml declaration tag.</p> <p>It forces the node to re-cache and recompile. We even have a page deep in the admin called Flush.aspx that does it for us.</p>
<p>In VS menu you have Build -&gt; Rebuild Solution</p>
7,508
<p>I have a DataGridView control in a TabPage, and I listen for the SelectionChanged event. When the TabPage is selected, the DataGridView selects the first row and fires the SelectionChanged event. How can I stop it from automatically selecting a row?</p>
<p>I can think of two ways of working around this, If you know the event always fires, Have a bool flag that is set on the first selection, then only perform the rest of your SelectionChanged code.</p> <p>The other way is to have a hidden control that is the first TabStop for the TabPage and hence is the first control to get focus (I say this without having tested any this of course, just my two cents).</p>
<p>Override the function "OnEnter" of the TabPage.</p> <p>Call the function "ClearSelecton" of the DataGridView within this function.</p>
29,649
<p>How can I find the index in a string that matches a boost regex?</p>
<p>If you use boost::regex_match it's the whole string that's matching.<br> Maybe you mean to use regex_search:</p> <pre><code>void index(boost::regex&amp; re,const std::string&amp; input){ boost::match_results&lt;std::string::const_iterator&gt; what; boost::match_flag_type flags = boost::match_default; std::string::const_iterator s = input.begin(); std::string::const_iterator e = input.end(); while (boost::regex_search(s,e,what,re,flags)){ std::cout &lt;&lt; what.position() &lt;&lt; std::endl; std::string::difference_type l = what.length(); std::string::difference_type p = what.position(); s += p + l; } } </code></pre>
<p>Use the <code>position</code> member function of the <code>match_results</code>:</p> <pre><code>int find_match_offset(std::string const&amp; string_to_search, boost::regex const&amp; expression) { boost::smatch results; if(boost::regex_match(string_to_search,results,expression)) { return results.position() } return -1; } </code></pre>
28,967
<p>I want to be able to run a function in my firefox sidebar js file when the selected tab in the main content window is reloaded or changed. So the sidebar can change depending on the site the user is looking at. </p> <p>Anyone able to point me in the right direction?</p>
<p>My solution pilfered from somewhere but can't remember where: </p> <pre><code>//add the load eventListener to the window object window.addEventListener("load", function() { functioname.init(); }, true); var functionname = { //add the listener for the document load event init: function() { var appcontent = document.getElementById("appcontent"); // browser if(appcontent) appcontent.addEventListener("DOMContentLoaded", functionname.onPageLoad, false); }, //function called on document load onPageLoad: function(aEvent) { if(aEvent.originalTarget.nodeName == "#document"){ } } } </code></pre>
<p>@oly1234 - your answer helped me to find the source:<br> <a href="https://developer.mozilla.org/en/Code_snippets/On_page_load" rel="nofollow noreferrer">Mozilla Developer Center - On page load</a> </p> <p>(<a href="https://developer.mozilla.org/en/Code_snippets/On_page_load" rel="nofollow noreferrer">https://developer.mozilla.org/en/Code_snippets/On_page_load</a>)</p>
30,563
<p>What is the masked text provider used for? Why is it different from regex?</p> <p>Is it possible to translate the regex format to mask or vise versa ?</p> <p>Thanks</p>
<p>A masked edit area forces the user to fill the field in a certain way: e.g. a mask that looks like ### will only allow a maximum of 3 numbers to be entered.</p> <p>A regular expression, on the other hand, is normally only checked for after the user has entered all the text. The validation happens too late to provide feedback on a character by character basis.</p>
<p>A masked edit provides an input mask, with optional separators and placeholders. Users can only input data in the format supplied. As an extra you can set the mask type to Date or Time, so data is also validated for that particlar type.</p>
42,149
<p>I have a Stored Procedure called spGetOrders which accepts a few parameters: @startdate and @enddate. This queries an "Orders" table. One of the columns in the table is called "ClosedDate". This column will hold NULL if an order hasn't been closed or a date value if it has. I'd like to add a @Closed parameter which will take a bit value. In a simple world, I'd be able to do.. </p> <pre><code>select * from orders o where o.orderdate between @startdate AND @enddate and (if @Closed = 1 then o.ClosedDate IS NULL else o.ClosedDate IS NOT NULL) </code></pre> <p>Obviously, that's not going to work.. I'm also looking at dynamic sql which is my last resort, but starting to look like the answer.. </p> <p>Please help.. </p>
<p>Try this:</p> <pre><code>select * from orders o where o.orderdate between @startdate AND @enddate and ((@Closed = 1 And o.ClosedDate IS NULL) Or (@Closed = 0 And o.ClosedDate IS NOT NULL)) </code></pre> <p>Be vary careful about mixing AND's and OR's in the where clause. When doing this, the parenthesis to control the order of evaluation is VERY important.</p>
<p>Or this:</p> <pre><code>select * from orders o where o.orderdate between @startdate AND @enddate and ( (@Closed = 1 AND o.ClosedDate IS NULL) OR (ISNULL(@Closed, 0) &lt;&gt; 1 AND o.ClosedDate IS NOT NULL) ) </code></pre> <p>It looks like you want all the orders between two dates that have inconsistent Close information. The other suggestions are probably as good (or better) but I'm pretty sure that this works and is readable to me (most of the other suggestions appeared as I was typing). </p> <p>Good luck!</p>
46,029
<p>What's the best and most efficient way to count keywords in JavaScript? Basically, I'd like to take a string and get the top N words or phrases that occur in the string, mainly for the use of suggesting tags. I'm looking more for conceptual hints or links to real-life examples than actual code, but I certainly wouldn't mind if you'd like to share code as well. If there are particular functions that would help, I'd also appreciate that. </p> <p>Right now I think I'm at using the split() function to separate the string by spaces and then cleaning punctuation out with a regular expression. I'd also want it to be case-insensitive.</p>
<p>Cut, paste + execute demo:</p> <pre><code>var text = "Text to be examined to determine which n words are used the most"; // Find 'em! var wordRegExp = /\w+(?:'\w{1,2})?/g; var words = {}; var matches; while ((matches = wordRegExp.exec(text)) != null) { var word = matches[0].toLowerCase(); if (typeof words[word] == "undefined") { words[word] = 1; } else { words[word]++; } } // Sort 'em! var wordList = []; for (var word in words) { if (words.hasOwnProperty(word)) { wordList.push([word, words[word]]); } } wordList.sort(function(a, b) { return b[1] - a[1]; }); // Come back any time, straaanger! var n = 10; var message = ["The top " + n + " words are:"]; for (var i = 0; i &lt; n; i++) { message.push(wordList[i][0] + " - " + wordList[i][1] + " occurance" + (wordList[i][1] == 1 ? "" : "s")); } alert(message.join("\n")); </code></pre> <p>Reusable function:</p> <pre><code>function getTopNWords(text, n) { var wordRegExp = /\w+(?:'\w{1,2})?/g; var words = {}; var matches; while ((matches = wordRegExp.exec(text)) != null) { var word = matches[0].toLowerCase(); if (typeof words[word] == "undefined") { words[word] = 1; } else { words[word]++; } } var wordList = []; for (var word in words) { if (words.hasOwnProperty(word)) { wordList.push([word, words[word]]); } } wordList.sort(function(a, b) { return b[1] - a[1]; }); var topWords = []; for (var i = 0; i &lt; n; i++) { topWords.push(wordList[i][0]); } return topWords; } </code></pre>
<p>I would do exactly what you have mentioned above to isolate each word. I would then probably add each word as the index of an array with the number of occurrences as the value. </p> <p>For example:</p> <pre><code>var a = new Array; a[word] = a[word]?a[word]+1:1; </code></pre> <p>Now you know how many unique words there are (a.length) and how many occurrences of each word existed (a[word]).</p>
17,065
<p>Unfortunatly I have to work in a older web application on a <code>PHP4</code> server; It now needs to parse a lot of <code>XM</code>L for calling <code>webservices (custom protocol, no SOAP/REST)</code>;</p> <p>Under <code>PHP5</code> I would use <code>SimpleXML</code> but that isn't available; There is <code>Dom XML</code> in <code>PHP4</code>, but it isn't default any more in <code>PHP5</code>.</p> <p>What are the other options? I'm looking for a solution that still works on <code>PHP5</code> once they migrate.</p> <p>A nice extra would be if the <code>XML</code> can be validated with a schema.</p>
<p>There is a simpleXML backport avaliable: <a href="http://www.ister.org/code/simplexml44/index.html" rel="nofollow noreferrer">http://www.ister.org/code/simplexml44/index.html</a></p> <p>If you can install that, then that will be the best solution.</p>
<p>It might be a bit grass roots, but if it's applicable for the data you're working with, you could use XSLT to transform your XML in to something usable. Obviously once you upgrade to PHP5 the XSLT will still work and you can migrate as and when to DOM parsing.</p> <p>Andrew</p>
16,031
<p>I've been using Eclipse with RDT (not RadRails) a lot lately, and I'm quite happy with it, but I'm wondering if you guys know any decent alternatives. I know NetBeans also supports Ruby these days, but I'm not sure what it has to offer over Eclipse.</p> <p>Please, list any features you think are brilliant or useful when suggesting an IDE, makes it easier to compare.</p> <p>Also, I said Ruby, not Rails. While Rails support is a plus, I prefer things to be none Rails-centric. It should also be available on Linux and optionally Solaris.</p>
<p>Have you tried <a href="http://www.aptana.com/" rel="nofollow noreferrer">Aptana</a>? It's based on Eclipse and they have a sweet <a href="http://www.aptana.com/rails" rel="nofollow noreferrer">Rails</a> plugin.</p>
<p>+1 for TextMate on Mac OS X.</p> <p>See also answers to <a href="https://stackoverflow.com/questions/16064/what-ide-to-use-for-developing-in-ruby-on-rails-on-windows#16086">this question</a>. I <a href="https://stackoverflow.com/questions/16064/what-ide-to-use-for-developing-in-ruby-on-rails-on-windows#16086">recommend</a> trying <a href="http://en.wikipedia.org/wiki/NetBeans" rel="nofollow noreferrer">NetBeans</a> if you're on Windows.</p>
3,770
<p><code>Html.TextBox("ParentPassword", "", new { @class = "required" })</code></p> <p>what the gosh darned heck is the @ for the @class.</p>
<p><code>class</code> is a reserved keyword, so you can't use this as a variable name.</p> <p>The @ operator allows you to get around this rule. The reason why its being done here is that the anonymous object is used to populate attributes on a HTML element. A valid attribute name is "class", which lets you set the CSS class on the element. </p>
<p><code>class</code> is a keyword. To use <code>class</code> as the name of a variable/property, in C#, you can prepend <code>@</code> to it, as <code>@class</code>. In the IL, for all .net is concerned, the name of the variable/property is still <code>class</code> - <code>@</code> is the way you have to do it in C#.</p>
36,105
<p>I think I'm pretty good at using semantic markup on my pages but I still have a handful of classes like this:</p> <pre><code>/**** Aligns ****/ .right_align { text-align: right; } .left_align { text-align: left; } .center_align { text-align: center; } </code></pre> <p>Which, technically, is a no-no. But when you just want to position some text in a table, how crazy am I supposed to get with the semantic markup?</p>
<p>Why do you want to align the text?</p> <p>The answer to the question is the name of the id or class you need to have for your selector. Do you want to align it right because it's a price?</p> <pre><code>table .price { text-align: right } </code></pre> <p>Just ask yourself <em>why</em> do you want to apply a particular style, and all will become clear.</p> <p>I probably overdid it, but my last work project was pretty close 100% semantic- anything I needed which was not semantic (say, a filler div which I could not do without for a layout requirement), I added dynamically using jQuery.</p>
<p>From experience, for usability reasons you should keep tokens on as many lines as possible. </p> <p>I use the following notation </p> <pre> matcher,&para; matcher&para; {&para; &middot;&middot;attribute:&middot;property;&para; }&para; </pre> <p>Why you ask? This solves many problems with collisions, as it reduces the number of places 2 unrelated changes can occur in 2 different places at once ( which causes the collision ), and when the collision <strong>does</strong> occur, its much easier to see what caused it and chose the correct solution. </p> <p>This is because SCM's DIFF is row oriented, and if you have all your content on 1 row, you get 2 choices, hose one complete set, or hose the other. </p> <p>Also, that particular style I find, if adhered to, makes it easy to write lint checking code that detects errors in your CSS. </p> <p>For insance, spot the typos: </p> <pre><code>matcher matcher, { attribute property attribute } </code></pre> <p>In this case, code that simply checks for whitespace and delimiter conformance also detects coding mistakes!. </p>
37,403
<p>When running <a href="https://github.com/MarlinFirmware/Marlin" rel="nofollow noreferrer">Marlin Firmware</a>, is it possible to run <a href="https://reprap.org/wiki/G-code" rel="nofollow noreferrer">G-code</a> scripts/series of commands automatically when you insert the SD card?</p> <hr> <p>I'm running Marlin on a 3D printer board using an ATmega 2560 based board with a reprap discount LCD controller with an SD card slot. I would like to do this without the need to add another computer/board, so native from the board running the Marlin Firmware.</p>
<p>I am not <em>entirely sure</em> if this is what you are after, or if it will work, but from <a href="https://github.com/MarlinFirmware/Marlin/issues/2891#issuecomment-180980733" rel="nofollow noreferrer">this post</a> on <a href="https://github.com/MarlinFirmware/Marlin/issues/2891" rel="nofollow noreferrer">Printing From SD Card when printer is turned On</a></p> <blockquote> <p>While an LCD controller is not needed for auto#.g to work, if you have an LCD controller you can use the <code>MENU_ADDAUTOSTART</code> option to add a menu command that will run the auto0.g, auto1.g, auto2.g whenever you want.</p> </blockquote> <p>This (final) post ended up closing the thread so it appears to answer the OP's question - however, whether it will answer your question is another matter.</p> <hr /> <p><a href="https://reprap.org/forum/read.php?415,833394" rel="nofollow noreferrer">This post</a>, on the Marlin forum, replicates your question and asks about purely insertion of an SD card on a printer which is <em>already</em> powered on.</p> <p><a href="https://reprap.org/forum/read.php?415,833394,833489#msg-833489" rel="nofollow noreferrer">A reply</a> was received and apparently it should be possible by making a code change in <code>ultralcd.ccp</code>:</p> <blockquote> <p>It does not seem like an auto print, when inserting a SD-card, is to be found in the current program code of Marlin.</p> <p>You might consider making a feature request here: [<a href="https://github.com/MarlinFirmware/Marlin/issues" rel="nofollow noreferrer">github.com</a>]</p> <p>I do not think that it would require much work to implement a &quot;card.autoprintfile()&quot; function in Marlin. It seems to me that a call to such a function could happen at line 5172 right after:</p> <pre><code>else LCD_MESSAGEPGM(MSG_SD_INSERTED); </code></pre> <p>in the file <code>ultralcd.ccp</code></p> </blockquote> <p>A subsequent feature request has been made on Marlin's GitHub, see <a href="https://github.com/MarlinFirmware/Marlin/issues/11815" rel="nofollow noreferrer">[FR] Can G-code scripts be run automatically on inserting an SD card when using Marlin Firmware?</a></p> <p>However, from <a href="https://github.com/MarlinFirmware/Marlin/issues/11815#issuecomment-420791259" rel="nofollow noreferrer">this reply</a>, it appears that a feature request is already pending:</p> <blockquote> <p>I'm not in favor of this as a general feature. We already have a feature request to be able to run custom G-code in response to various events, with SD card insertion being one of those events. Would that feature serve your needs?</p> </blockquote> <p>However, as yet, I do not have a link to this other feature request. Will update as and when.</p> <hr /> <p>As an aside, in might be worth mentioning that the SDFat related code could be the place to code this in, see <a href="https://forum.arduino.cc/index.php?topic=360754.0" rel="nofollow noreferrer">if SD card removed, how to flag and restart?</a>, although after looking at the Marlin codebase, in particular <a href="https://github.com/MarlinFirmware/Marlin/blob/1.1.x/Marlin/SdFatUtil.cpp" rel="nofollow noreferrer"><code>SdFatUtils.cpp</code></a>, this would appear to be a <a href="https://en.wikipedia.org/wiki/Red_herring" rel="nofollow noreferrer">red herring</a>.</p>
<p>I don't know what you would like to achieve.</p> <p>As @typo mentioned there is similar functionality which triggers at printer startup: <a href="https://github.com/MarlinFirmware/Marlin/wiki/Autostart" rel="nofollow noreferrer">https://github.com/MarlinFirmware/Marlin/wiki/Autostart</a></p> <p>I found in Marlin's source code that you can enable that autostart feature to be triggered from menu. Just enable <code>MENU_ADDAUTOSTART</code> in <a href="https://github.com/MarlinFirmware/Marlin/blob/1.1.x/Marlin/Configuration_adv.h" rel="nofollow noreferrer">Configuration_adv.h</a>. </p> <p>If you really need a g-code that start after sd-card insert then you have to adjust the marlin source code on your own. I suggest to alter file <a href="https://github.com/MarlinFirmware/Marlin/blob/1.1.x/Marlin/cardreader.cpp" rel="nofollow noreferrer">cardreader.cpp</a>. There you have to trigger the autostart procedure after a sd-card is inserted.</p>
1,021
<p>I'm having trouble ordering by more than one field in my Linq to NHibernate query. Does anyone either know what might be wrong or if there is a work around?</p> <p>Code:</p> <pre><code>IQueryable&lt;AgendaItem&gt; items = _agendaRepository.GetAgendaItems(location) .Where(item =&gt; item.Minutes.Contains(query) || item.Description.Contains(query)); int total = items.Count(); var results = items .OrderBy(item =&gt; item.Agenda.Date) .ThenBy(item =&gt; item.OutcomeType) .ThenBy(item =&gt; item.OutcomeNumber) .Skip((page - 1)*pageSize) .Take(pageSize) .ToArray(); return new SearchResult(query, total, results); </code></pre> <p>I've tried replacing ThenBy with multiple OrderBy calls. Same result. The method works great if I comment out the two ThenBy calls.</p> <p>Error I'm receiving:</p> <pre> [SqlException (0x80131904): Invalid column name '__hibernate_sort_expr_0____hibernate_sort_expr_1__'. Invalid column name '__hibernate_sort_expr_0____hibernate_sort_expr_1__'.] System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +1948826 System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4844747 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194 System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2392 [ADOException: could not execute query [ SELECT this_.Id as Id5_2_, this_.AgendaId as AgendaId5_2_, this_.Description as Descript3_5_2_, this_.OutcomeType as OutcomeT4_5_2_, this_.OutcomeNumber as OutcomeN5_5_2_, this_.Minutes as Minutes5_2_, agenda1_.Id as Id2_0_, agenda1_.LocationId as LocationId2_0_, agenda1_.Date as Date2_0_, location2_.Id as Id7_1_, location2_.Name as Name7_1_ FROM AgendaItem this_ left outer join Agenda agenda1_ on this_.AgendaId=agenda1_.Id left outer join Location location2_ on agenda1_.LocationId=location2_.Id WHERE location2_.Id = ? and (this_.Minutes like ? or this_.Description like ?) ORDER BY agenda1_.Date asc, this_.OutcomeType asc, this_.OutcomeNumber asc ] Positional parameters: #0>1 #0>%Core% #0>%Core% [SQL: SELECT this_.Id as Id5_2_, this_.AgendaId as AgendaId5_2_, this_.Description as Descript3_5_2_, this_.OutcomeType as OutcomeT4_5_2_, this_.OutcomeNumber as OutcomeN5_5_2_, this_.Minutes as Minutes5_2_, agenda1_.Id as Id2_0_, agenda1_.LocationId as LocationId2_0_, agenda1_.Date as Date2_0_, location2_.Id as Id7_1_, location2_.Name as Name7_1_ FROM AgendaItem this_ left outer join Agenda agenda1_ on this_.AgendaId=agenda1_.Id left outer join Location location2_ on agenda1_.LocationId=location2_.Id WHERE location2_.Id = ? and (this_.Minutes like ? or this_.Description like ?) ORDER BY agenda1_.Date asc, this_.OutcomeType asc, this_.OutcomeNumber asc]] NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) +258 NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters) +18 NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces, IType[] resultTypes) +87 NHibernate.Impl.SessionImpl.List(CriteriaImpl criteria, IList results) +342 NHibernate.Impl.CriteriaImpl.List(IList results) +41 NHibernate.Impl.CriteriaImpl.List() +35 NHibernate.Linq.CriteriaResultReader`1.List() in C:\home\dev\tools\NHibernate\NHibernateContribSrc\src\NHibernate.Linq\src\NHibernate.Linq\CriteriaResultReader.cs:22 NHibernate.Linq.d__0.MoveNext() in C:\home\dev\tools\NHibernate\NHibernateContribSrc\src\NHibernate.Linq\src\NHibernate.Linq\CriteriaResultReader.cs:27 </pre>
<p>This looks to me like a bug with Linq to NHybernate. One possible workaround is to convert to an array before sorting. A potentially big downside is that you can't limit the results using Skip() and Take() before enumerating, so this may not be sufficient for you.</p> <pre><code>var results = items .ToArray() .OrderBy(item =&gt; item.Agenda.Date) .ThenBy(item =&gt; item.OutcomeType) .ThenBy(item =&gt; item.OutcomeNumber) .Skip((page - 1)*pageSize) .Take(pageSize) </code></pre>
<p>although i dont think it'd make a difference, what happens if you do your linq like this:</p> <p>(from i in items orderby i.prop1, i.prop2, i.prop3).Skip(...).Take(...).ToArray();</p>
8,582
<p>I am trying to RegisterClientScriptBlock in a method that is only called via an AJAX call. It doesn't appear to actually register the script on the page and I'm guessing this is because it's not actually reloading the entire page. Is there any way to register javascript on a page from within an ajax method call?</p> <pre><code> protected void MyMethod(object sender, EventArgs e) { // This method only called via AJAX call Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "resize", "alert('here');", true); } </code></pre>
<p>With AJAX enabled pages, you should use the ScriptManager to register scripts:</p> <pre><code>ScriptManager.RegisterClientScriptBlock(Page, typeof(MyPage), "MyScript", "GoStuff()", true) </code></pre> <p>You can use this to register all your scripts (Original load, postback, AJAX postback).</p>
<p>As far as I know for this you would be forced to be calling this method via a PostBack and not an ajax call. There may be OTHER ways of doing this, but it is not possible with Page.ClientScript....</p>
38,000
<p>I have a list of structs and I want to change one element. For example :</p> <pre><code>MyList.Add(new MyStruct("john"); MyList.Add(new MyStruct("peter"); </code></pre> <p>Now I want to change one element:</p> <pre><code>MyList[1].Name = "bob" </code></pre> <p>However, whenever I try and do this I get the following error:</p> <blockquote> <p>Cannot modify the return value of System.Collections.Generic.List.this[int]‘ because it is not a variable</p> </blockquote> <p>If I use a list of classes, the problem doesn't occur.</p> <p>I guess the answer has to do with structs being a value type.</p> <p>So, if I have a list of structs should I treat them as <em>read-only</em>? If I need to change elements in a list then I should use classes and not structs?</p>
<pre><code>MyList[1] = new MyStruct("bob"); </code></pre> <p>structs in C# should almost always be designed to be immutable (that is, have no way to change their internal state once they have been created).</p> <p>In your case, what you want to do is to replace the entire struct in specified array index, not to try to change just a single property or field.</p>
<p>As of C#9, I am not aware of any way to pull a struct by reference out of a generic container, including <code>List&lt;T&gt;</code>. As Jason Olson's answer said:</p> <p><em>The real underlying issue is that structs are a Value type, not a Reference type. So when you pull out a &quot;reference&quot; to the struct from the list, it is creating a new copy of the entire struct. So any changes you make on it are changing the copy, not the original version in the list.</em></p> <p>So, this can be pretty inefficient. SuperCat's answer, even though it is correct, compounds that inefficiency by copying the updated struct back into the list.</p> <p>If you are interested in maximizing the performance of structs, then use an array instead of <code>List&lt;T&gt;</code>. The indexer in an array returns a reference to the struct and does not copy the entire struct out like the <code>List&lt;T&gt;</code> indexer. Also, an array is more efficient than <code>List&lt;T&gt;</code>.</p> <p>If you need to grow the array over time, then create a generic class that works like <code>List&lt;T&gt;</code>, but uses arrays underneath.</p> <p>There is an alternative solution. Create a class that incorporates the structure and create public methods to call the methods of that structure for the required functionality. Use a <code>List&lt;T&gt;</code> and specify the class for T. The structure may also be returned via a ref returns method or ref property that returns a reference to the structure.</p> <p>The advantage of this approach is that it can be used with any generic data structure, like <code>Dictionary&lt;TKey, TValue&gt;</code>. When pulling a struct out of a <code>Dictionary&lt;TKey, TValue&gt;</code>, it also copies the struct to a new instance, just like <code>List&lt;T&gt;</code>. I suspect that this is true for all C# generic containers.</p> <p>Code example:</p> <pre><code>public struct Mutable { private int _x; public Mutable(int x) { _x = x; } public int X =&gt; _x; // Property public void IncrementX() { _x++; } } public class MutClass { public Mutable Mut; // public MutClass() { Mut = new Mutable(2); } public MutClass(int x) { Mut = new Mutable(x); } public ref Mutable MutRef =&gt; ref Mut; // Property public ref Mutable GetMutStruct() { return ref Mut; } } private static void TestClassList() { // This test method shows that a list of a class that holds a struct // may be used to efficiently obtain the struct by reference. // var mcList = new List&lt;MutClass&gt;(); var mClass = new MutClass(1); mcList.Add(mClass); ref Mutable mutRef = ref mcList[0].MutRef; // Increment the x value defined in the struct. mutRef.IncrementX(); // Now verify that the X values match. if (mutRef.X != mClass.Mut.X) Console.Error.WriteLine(&quot;TestClassList: Error - the X values do not match.&quot;); else Console.Error.WriteLine(&quot;TestClassList: Success - the X values match!&quot;); } </code></pre> <p>Output on console window:</p> <pre><code>TestClassList: Success - the X values match! </code></pre> <p>For the following line:</p> <pre><code>ref Mutable mutRef = ref mcList[0].MutRef; </code></pre> <p>I initially and inadvertently left out the ref after the equal sign. The compiler didn't complain, but it did produce a copy of the struct and the test failed when it ran. After adding the ref, it ran correctly.</p>
7,461
<p>In VB.Net, I can declare a variable in a function as Static, like this:</p> <pre><code>Function EncodeForXml(ByVal data As String) As String Static badAmpersand As Regex = new Regex("&amp;(?![a-zA-Z]{2,6};|#[0-9]{2,4};)") data = badAmpersand.Replace(data, "&amp;amp;") ''// more processing return data End Function </code></pre> <p>Note that I need to use the keyword <code>Static</code>, rather than <code>Shared</code>, which is the normal way to express this in VB.Net. How can I do this in C#? I can't find its equivalent.</p>
<p>Ha! In posting the question, I found the answer! Rather than googling for C# I should have been looking for details on how VB.Net implements it, and typing up the question made that apparent to me. After applying that insight, I found this:<br> <a href="http://weblogs.asp.net/psteele/articles/7717.aspx" rel="noreferrer">http://weblogs.asp.net/psteele/articles/7717.aspx</a></p> <p>That article explains that it's not really supported by the CLR, and the VB compiler creates a static (shared) variable "under the hood" in the method's class. To do the same in C#, I have to create the variable myself.</p> <p>More than that, it uses the <code>Monitor</code> class to make sure the static member is thread-safe as well. Nice.</p> <p>As a side note: I'd expect to see this in C# sometime soon. The general tactic I've observed from MS is that it doesn't like VB.Net and C# to get too far apart feature-wise. If one language has a feature not supported by the other it tends to become a priority for the language team for the next version.</p>
<p>You have to declare this on the class level:</p> <pre><code>private static readonly RegEx badAmpersand = new RegEx("..."); </code></pre>
19,056
<p>For a particular application, I need the screen saver to be disabled while it's running. The operator COULD manually turn it off, and then back on later, but the easiest thing to do would be to just keep the screen saver at bay while the application is running.</p> <p>How do I do this? I've found code for actually turning off the screen saver with SPI_SETSCREENSAVEACTIVE, but I don't think that's what I want.</p>
<p><a href="https://devblogs.microsoft.com/oldnewthing/20090820-00/?p=17043" rel="nofollow noreferrer" title="Raymond Chen, The New Old Thing">theoldnewthing</a> has your answer: Use <a href="https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-setthreadexecutionstate" rel="nofollow noreferrer"><code>SetThreadExecutionState(ES_DISPLAY_REQUIRED)</code></a>.</p> <p>This is used by video players and PowerPoint.</p>
<p>try making your form topmost value <strong>true</strong> it works for me screen-saver never came even after the idle time...</p>
29,856
<p>Should the "visibility" for the <code>__destruct()</code> function be public or something else? I'm trying to write a standards doc for my group and this question came up.</p>
<p>In Addition to Mark Biek's answer:</p> <p>The __destruct() function must be declared public. Otherwise, the function will not be executed on script shutdown:</p> <pre><code>Warning: Call to protected MyChild1::__destruct() from context '' during shutdown ignored in Unknown on line 0 Warning: Call to private MyChild2::__destruct() from context '' during shutdown ignored in Unknown on line 0 </code></pre> <p>This may not be harmful, but rather unclean.</p> <p>But the most important thing about this: If the destructor is declared private or protected, the runtime will throw a fatal error in the moment the garbage collector tries to free objects:</p> <pre><code>&lt;?php class MyParent { private function __destruct() { echo 'Parent::__destruct'; } } class MyChild extends MyParent { private function __destruct() { echo 'Child::__destruct'; parent::__destruct(); } } $myChild = new MyChild(); $myChild = null; $myChild = new MyChild(); ?&gt; </code></pre> <p>outputs</p> <pre><code>Fatal error: Call to private MyChild::__destruct() from context '' in D:\www\scratchbook\destruct.php on line 20 </code></pre> <p>(Thanks to Mark Biek for the excellent example!)</p>
<p>I think it would need to be public in the case where a subclass needs to explicitly call the <strong>__destruct</strong> method of the parent class.</p> <p>Something like this would throw an error:</p> <pre><code>&lt;?php class MyParent { private function __destruct() { echo 'Parent::__destruct'; } } class MyChild extends MyParent { function __destruct() { echo 'Child::__destruct'; parent::__destruct(); } } $myChild = new MyChild(); ?&gt; </code></pre>
28,500
<p>I'm having a difficult time figuring out how to add a .jar/library to a Netbeans project in such a way that I can get it committed to the repository.</p> <p>The typical way to add a library (per the Netbeans documents I've already gone through) ends up with it just being local to me. Anyone who checks out my project ends up missing my required library.</p> <p>Inserting it manually and trying to work around Netbeans results in Netbeans hanging while trying to scan the project...</p> <p>So, how can I tell Netbeans to pick up a jar as a library and include it in my project in such a way that Subversion will be able to handle it?</p>
<p>There are a couple ways to fix this.</p> <p>A. When you define your Library, use a path to a common location. A location that's identical on everyone's machine--such as the location of a JAR installed with a third-party app into Program Files or /usr/local/ works well or a network drive.</p> <p>Then, when they check-out the code, the path will still be correct and they do not have to define the Library on their Netbeans workspace.</p> <p>B. Edit your project.properties file to use a relative path. Open your project.properties file and look for "<code>libs.LIBRARY_NAME.classpath=...</code>". That will be the "default" location used if the Library is not defined.</p> <p>Change this to use a path relative to your project and store the jar files in your project. For example: <code>libs.Log4J.classpath=lib/log4j.jar</code></p> <p>Keep in mind that the Library definition in your Library Manager will override this value--so make sure you keep them in-sync (i.e. append a version number to the library name!).</p> <p>C. Use Vincent's suggestion of using a build-system such as Maven. The Maven build-process will take care of downloading dependencies, etc. Netbeans has plugins for several popular build systems.</p>
<p>I ended up just downloading my own set and putting them on my local drive for this project. I setup my Netbeans to look there and warned the other guys what I did... Eventually, we'll have to do something a bit more scalable though... :-)</p>
36,482
<p>I know that you can use a dummy "int" parameter on <code>operator++</code> and <code>operator--</code> to override the postfix versions of those operators, but I vaguely recall something about a dummy parameter that you could declare on a destructor. Does anyone know anything about that, and if so, what that dummy parameter did?</p> <p>This was in my old Turbo C++ tutorial books, which I read when I was a teenager (i.e. a <em>long</em> time ago), so I might be completely misremembering it. That was also very early C++, before it was standardized, so it's possible that it was something Turbo C++-specific.</p>
<p>You're possibly thinking of the placement and nothrow forms of operator delete, which have the signatures:</p> <pre><code>void operator delete(void *, void *) throw(); void operator delete(void *, const std::nothrow_t&amp;) throw(); void operator delete[](void *, void *) throw(); void operator delete[](void *, const std::nothrow_t&amp;) throw(); </code></pre> <p>These are never called during normal operation, but would be used in the case where the constructor for an object being constructed with <a href="http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.10" rel="nofollow noreferrer">placement new</a> throws an exception. Generally you don't have to define them, since the compiler already called the destructor(s) on the dead object's bases and members, and for placement new there's no memory to be freed. But can exist if you are overloading placement new and need a corresponding operator.</p> <p>The second argument is not really used, and just distinguishes the signature for the ordinary:</p> <pre><code>void operator delete(void *) </code></pre> <p>These aren't special dummy arguments the way the operator++ ones are, though. They're just an instance of the general rule that call to new with extra arguments, such as:</p> <pre><code>obj = new(x,y,z) Object(a,b,c) </code></pre> <p>will generate implicit code to clean up from constructor errors that passes those same additional arguments to the operator delete, which will function (approximately) like:</p> <pre><code>void *raw = operator new(sizeof(Object), x,y,z) try { obj = new(raw) Object(a,b,c); } catch(...) { operator delete(raw,x,y,z); throw; } </code></pre>
<p>You're not crazy. I have definitely seen an int parameter in a destructor before. Using HP's compiler on OpenVMS, I compiled a sample program show below. The list of symbols does include an destructor with an int parameter. I can only guess this is compiler specific.</p> <pre><code>$ create foo.cxx class foo { ~foo() {} }; $ cxx foo.cxx $ type [.CXX_REPOSITORY]cxx$demangler_db. CX3$_ZN3FOOD1EV31GNTHJ foo::$complete$~foo() CX3$_ZN3FOOD2EV30KQI3A foo::$subobject$~foo() CX3$_ZN3FOOD9EV36HH9SB foo::~foo(int) CXXL$_ZDLPV void operator delete(void *) </code></pre>
33,549
<p>I just want my apache to register some of my predefined environment so that i can retrieve it using getenv function in php. How can i do this? I tried adding /etc/profile.d/foo.sh with export FOO=/bar/baz using root and restarted apache.</p>
<p>Environment variables are inherited by processes in Unix. The files in /etc/profile.d are only executed (in the current shell, not in a subshell) when you log in. Just changing the value there and then restarting a process will not update the environment. </p> <p>Possible Fixes:</p> <ul> <li>log out/log in, then start apache</li> <li>source the file: <code># . /etc/profile.d/foo.sh</code>, then restart apache</li> <li>source the file in the apache init script</li> </ul> <p>You also need to make sure that <code>/etc/profile.d/</code> is sourced when Apache is started by <code>init</code> rather than yourself. </p> <p>The best fix might also depend on the distribution you are using, because they use different schemes for configuration.</p>
<p>You can use <a href="http://httpd.apache.org/docs/2.2/mod/mod_env.html#setenv" rel="nofollow noreferrer">SetEnv</a> in your config files (/etc/httpd/conf.d/*.conf, .htaccess ...). Additionally you should be able to define them in /etc/sysconfig/httpd (on RPM-based distribs) and <em>export</em> them (note: not tested).</p> <p>Note: it wouldn't surprise me if some distributions tried quite hard to hide as much as possible, as far as system config is concerned, from a publically accessible service such as Apache. And if they don't, they might start doing this in a future version. Hence I advise you to do this explicitly. If you need to share such a setting between Apache and your shells, you could try sourcing <em>/etc/profile.d/yourprofile.sh</em> from <em>/etc/sysconfig/httpd</em></p>
13,945
<p>I need to make a mouseover menu that opens diagonally (from top-left to bottom-right). </p>
<p>Assuming your menu has id "mymenu", try this code to show it:</p> <pre><code>$('#mymenu').animate({width: '80px', height: '200px'}) </code></pre> <p>and this code to hide it:</p> <pre><code>$('#mymenu').animate({width: '0px', height: '0px', opacity: 'hide'}) </code></pre>
<p>Use a Tween to tween the height from 0 to whatever height you want, and width from 0 to whatever width you want.</p> <p>You can take examples of making a popup menu show from the code here, as well as examples of performing actions on hover.</p>
25,660
<p>I have clustered applications that requires one of the nodes to be designated as the master. The cluster nodes are tracked in a table with <strong>nodeID</strong>, <strong>isMaster</strong>, <strong>lastTimestamp</strong> columns.</p> <p>Each node in the cluster will try to become a master every <strong>X</strong> seconds. Node can only become a master if either</p> <ul> <li>there is no other master nodes </li> <li>the <strong>lastTimestamp</strong> on current master node is older by <strong>2*X</strong></li> </ul> <p>When one of the above conditions is satisfied</p> <ul> <li>the current master node's <strong>isMaster</strong> should be cleared</li> <li>the new master node's <strong>isMaster</strong> should be set</li> <li>the new master node's <strong>lastTimestamp</strong> should be set to 'now' timestamp.</li> </ul> <p>What is the <strong>single</strong> (portable) SQL statement to achieve the above without the possibility of two or more nodes becoming the master?</p>
<p>The normal way of avoiding the "delete then move fails problem" is:</p> <ul> <li>Write to file.new</li> <li>Move file.current to file.old</li> <li>Move file.new to file.current</li> <li>Delete file.new</li> </ul> <p>Then when you come to read, use file.new if file.current is missing, deleting file.old if you see it.</p> <p>Checking for whether or not the file is available: try opening it for write, but appending to the end. Of course, you'll need to close the handle before you then move it, and in-between someone else could open it - but it would at least be a <em>reasonable</em> optimisation.</p> <p>Not sure about copying summaries etc, I'm afraid.</p>
<p>I found it useful to wrap this pattern in it's own class.</p> <pre><code>class Program { static void Main( string[] args ) { using( var ft = new FileTransaction( @"C:\MyDir\MyFile.txt" ) ) using( var sw = new StreamWriter( ft.TempPath ) ) { sw.WriteLine( "Hello" ); ft.Commit(); } } } public class FileTransaction :IDisposable { public string TempPath { get; private set; } private readonly string filePath; public FileTransaction( string filePath ) { this.filePath = filePath; this.TempPath = Path.GetTempFileName(); } public void Dispose() { if( TempPath != null ) { try { File.Delete( TempPath ); } catch { } } } public void Commit() { try { var oldPath = filePath + ".old"; File.Move( filePath, oldPath ); } catch {} File.Move( TempPath, filePath ); TempPath = null; } } </code></pre>
42,046
<p>How do I store binary data in <a href="http://en.wikipedia.org/wiki/MySQL" rel="noreferrer">MySQL</a>?</p>
<p>The answer by phpguy is correct but I think there is a lot of confusion in the additional details there.</p> <p>The basic answer is in a <code>BLOB</code> data type / attribute domain. <strong>BLOB</strong> is short for Binary Large Object and that column data type is specific for handling binary data.</p> <p>See <a href="http://dev.mysql.com/doc/refman/5.7/en/blob.html" rel="noreferrer">the relevant manual page for MySQL</a>.</p>
<p>The question also arises how to get the data into the BLOB. You can put the data in an INSERT statement, as the PHP example shows (although you should use <a href="http://www.php.net/mysql-real-escape-string" rel="noreferrer">mysql_real_escape_string</a> instead of addslashes). If the file exists on the database server, you can also use MySQL's <a href="http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_load-file" rel="noreferrer" title="LOAD FILE">LOAD_FILE</a></p>
2,237
<p>I am developing a system as an aid to musicians performing transcription. The aim is to perform automatic music transcription (it does not have to be perfect, as the user will correct glitches / mistakes later) on a single instrument monophonic recording. Does anyone here have experience in automatic music transcription? Or digital signal processing in general? Help from anyone is greatly appreciated no matter what your background.</p> <p>So far I have investigated the use of the Fast Fourier Transform for pitch detection, and a number of tests in both MATLAB and my own Java test programs have shown it to be fast and accurate enough for my needs. Another element of the task that will need to be tackled is the display of the produced MIDI data in sheet music form, but this is something I am not concerned with right now.</p> <p>In brief, what I am looking for is a good method for note onset detection, i.e. the position in the signal where a new note begins. As slow onsets can be quite difficult to detect properly, I will initially be using the system with piano recordings. This is also partially due to the fact I play piano and should be in a better position to obtain suitable recordings for testing. As stated above, early versions of this system will be used for simple monophonic recordings, possibly progressing later to more complex input depending on progress made in the coming weeks.</p>
<p>Here is a graphic that illustrates the threshold approach to note onset detection:</p> <p><img src="https://i.imgur.com/MBWzwT8.gif" alt="alt text"></p> <p>This image shows a typical WAV file with three discrete notes played in succession. The red line represents a chosen signal threshold, and the blue lines represent note start positions returned by a simple algorithm that marks a start when the signal level crosses the threshold.</p> <p>As the image shows, selecting a proper absolute threshold is difficult. In this case, the first note is picked up fine, the second note is missed completely, and the third note (barely) is started very late. In general, a low threshold causes you to pick up phantom notes, while raising it causes you to miss notes. One solution to this problem is to use a relative threshold that triggers a start if the signal increases by a certain percentage over a certain time, but this has problems of its own. </p> <p>A simpler solution is to use the somewhat-counterintuitively named compression (<strong>not MP3 compression - that's something else entirely</strong>) on your wave file first. Compression essentially flattens the spikes in your audio data and then amplifies everything so that more of the audio is near the maximum values. The effect on the above sample would look like this (which shows why the name "compression" appears to make no sense - on audio equipment it's usually labelled "loudness"):</p> <p><img src="https://i.imgur.com/ctWBY3Y.gif" alt="alt text"></p> <p>After compression, the absolute threshold approach will work much better (although it's easy to over-compress and start picking up fictional note starts, the same effect as lowering the threshold). There are a lot of wave editors out there that do a good job of compression, and it's better to let them handle this task - you'll probably need to do a fair amount of work "cleaning up" your wave files before detecting notes in them anyway.</p> <p>In coding terms, a WAV file loaded into memory is essentially just an array of two-byte integers, where 0 represents no signal and 32,767 and -32,768 represent the peaks. In its simplest form, a threshold detection algorithm would just start at the first sample and read through the array until it finds a value greater than the threshold. </p> <pre><code>short threshold = 10000; for (int i = 0; i &lt; samples.Length; i++) { if ((short)Math.Abs(samples[i]) &gt; threshold) { // here is one note onset point } } </code></pre> <p>In practice this works horribly, since normal audio has all sorts of transient spikes above a given threshold. One solution is to use a running average signal strength (i.e. don't mark a start until the average of the last n samples is above the threshold).</p> <pre><code>short threshold = 10000; int window_length = 100; int running_total = 0; // tally up the first window_length samples for (int i = 0; i &lt; window_length; i++) { running_total += samples[i]; } // calculate moving average for (int i = window_length; i &lt; samples.Length; i++) { // remove oldest sample and add current running_total -= samples[i - window_length]; running_total += samples[i]; short moving_average = running_total / window_length; if (moving_average &gt; threshold) { // here is one note onset point int onset_point = i - (window_length / 2); } } </code></pre> <p>All of this requires much tweaking and playing around with settings to get it to find the start positions of a WAV file accurately, and usually what works for one file will not work very well on another. This is a very difficult and not-perfectly-solved problem domain you've chosen, but I think it's cool that you're tackling it.</p> <p>Update: this graphic shows a detail of note detection I left out, namely detecting when the note ends:</p> <p><img src="https://i.imgur.com/ARlewTE.gif" alt="alt text"></p> <p>The yellow line represents the off-threshold. Once the algorithm has detected a note start, it assumes the note continues until the running average signal strength drops below this value (shown here by the purple lines). This is, of course, another source of difficulties, as is the case where two or more notes overlap (polyphony).</p> <p>Once you've detected the start and stop points of each note, you can now analyze each slice of WAV file data to determine the pitches.</p> <p>Update 2: I just read your updated question. Pitch-detection through auto-correlation is much easier to implement than FFT if you're writing your own from scratch, but if you've already checked out and used a pre-built FFT library, you're better off using it for sure. Once you've identified the start and stop positions of each note (and included some padding at the beginning and end for the missed attack and release portions), you can now pull out each slice of audio data and pass it to an FFT function to determine the pitch.</p> <p>One important point here is not to use a slice of the compressed audio data, but rather to use a slice of the original, unmodified data. The compression process distorts the audio and may produce an inaccurate pitch reading.</p> <p>One last point about note attack times is that it may be less of a problem than you think. Often in music an instrument with a slow attack (like a soft synth) will begin a note earlier than a sharp attack instrument (like a piano) and both notes will sound as if they're starting at the same time. If you're playing instruments in this manner, the algorithm with pick up the same start time for both kinds of instruments, which is good from a WAV-to-MIDI perspective.</p> <p>Last update (I hope): Forget what I said about including some paddings samples from the early attack part of each note - I forgot this is actually a bad idea for pitch detection. The attack portions of many instruments (especially piano and other percussive-type instruments) contain transients that aren't multiples of the fundamental pitch, and will tend to screw up pitch detection. You actually want to start each slice a little after the attack for this reason.</p> <p>Oh, and kind of important: <strong>the term "compression" here does not refer to MP3-style compression</strong>.</p> <p>Update again: here is a simple function that does non-dynamic compression:</p> <pre><code>public void StaticCompress(short[] samples, float param) { for (int i = 0; i &lt; samples.Length; i++) { int sign = (samples[i] &lt; 0) ? -1 : 1; float norm = ABS(samples[i] / 32768); // NOT short.MaxValue norm = 1.0 - POW(1.0 - norm, param); samples[i] = 32768 * norm * sign; } } </code></pre> <p>When param = 1.0, this function will have no effect on the audio. Larger param values (2.0 is good, which will square the normalized difference between each sample and the max peak value) will produce more compression and a louder overall (but crappy) sound. Values under 1.0 will produce an expansion effect.</p> <p>One other probably obvious point: you should record the music in a small, non-echoic room since echoes are often picked up by this algorithm as phantom notes.</p> <p>Update: here is a version of StaticCompress that will compile in C# and explicity casts everything. This returns the expected result:</p> <pre><code>public void StaticCompress(short[] samples, double param) { for (int i = 0; i &lt; samples.Length; i++) { Compress(ref samples[i], param); } } public void Compress(ref short orig, double param) { double sign = 1; if (orig &lt; 0) { sign = -1; } // 32768 is max abs value of a short. best practice is to pre- // normalize data or use peak value in place of 32768 double norm = Math.Abs((double)orig / 32768.0); norm = 1.0 - Math.Pow(1.0 - norm, param); orig = (short)(32768.0 * norm * sign); // should round before cast, // but won't affect note onset detection } </code></pre> <p>Sorry, my knowledge score on Matlab is 0. If you posted another question on why your Matlab function doesn't work as expected it would get answered (just not by me).</p>
<p>You could try to transform the wav signal into a graph of amplitude against time. Then a way to determine a consistent onset is to calculate the intersection of a tangent in the inflection point of the rising flank of a signal with the x axis.</p>
37,589
<p>So far, in my research I have seen that it is unwise to set AllowUnsafeUpdates on GET request operation to avoid cross site scripting. But, if it is required to allow this, what is the proper way to handle the situation to mitigate any exposure? </p> <p>Here is my best first guess on a reliable pattern if you absolutely need to allow web or site updates on a GET request.</p> <p>Best Practice?</p> <pre><code>protected override void OnLoad(System.EventArgs e) { if(Request.HttpMethod == "POST") { SPUtility.ValidateFormDigest(); // will automatically set AllowSafeUpdates to true } // If not a POST then AllowUnsafeUpdates should be used only // at the point of update and reset immediately after finished // NOTE: Is this true? How is cross-site scripting used on GET // and what mitigates the vulnerability? } // Point of item update using(SPSite site = new SPSite(SPContext.Current.Site.Url, SPContext.Current.Site.SystemAccount.UserToken)) { using (SPWeb web = site.RootWeb) { bool allowUpdates = web.AllowUnsafeUpdates; //store original value web.AllowUnsafeUpdates = true; //... Do something and call Update() ... web.AllowUnsafeUpdates = allowUpdates; //restore original value } } </code></pre> <p>Feedback on the best pattern is appreciated.</p>
<p>If you're performing any operations which modify something, then anyone that can convince the user to click on a link can perform that operation. For instance, let's assume that you have a GET request to a page which lets the user add an administrator to a site, and the user clicks a link to a page which does a Response.Redirect("<a href="http://yourserver/_layouts/admin.aspx?operation=addAdministrator&amp;username=attackerNameHere" rel="nofollow noreferrer">http://yourserver/_layouts/admin.aspx?operation=addAdministrator&amp;username=attackerNameHere</a>").</p> <p>While normally a POST does not offer much protection against this (nothing will stop someone from having a &lt;form method="post" action="http://yourserver/_layouts/admin.aspx">), SharePoint has a concept of form digests, which contain information about the previous request that is generating the post back (including the user's name). This reduces the footprint for this kind of attack significantly.</p> <p>The only time that it is not a security issue to AllowUnsafeUpdates on a GET is if you're not taking input from the user. For instance, if you have a web part which also logs visits to a list, then there's no security vulnerability exposed.</p> <p><strong>Edit</strong>: If you are going to use AllowUnsafeUpdates, there's no need to reset it to its previous value. It does not get persisted. It's just something you need to set on an SPWeb object before performing updates from a GET (or other cases)</p>
<p>Not so sure it is worth remembering the previous value of allow unsafe updates.</p> <p>I would want to wrap the call around the minimum possible amount of code, so that nested calls to it would not occur. </p> <p>Then you can just turn it to false afterwards.</p>
26,294
<p>I've coded some smaller projects using Silverlight 2.0, which is fairly impressive.</p> <p>Does Silverlight 2.0 have what it takes to be a game development platform for the web? <br/> (Are the framerates high enough, will there be 3D engines developed, and many more questions)</p> <p>Yes or no, with detail if desired, and why.</p>
<p>Silverlight is a very viable platform for 2D Web Games.</p> <p>I built <a href="http://www.physicspoweredgames.com/Games/Diver/Diver.aspx" rel="nofollow noreferrer">Diver</a> with it and the development experience was very pleasant. I'm close to releasing my second game and this time the dev experience was even better because the tools were out of beta. </p> <p>The only downside I see right now is the lack of support by web game portals and ad-revenue sharing sites like <a href="http://www.mochiads.com/" rel="nofollow noreferrer">MochiAds</a> </p> <p>Without support from these kind of sites, your options to make money from your games will be a bit limited. Your best option for making money right now is to host your games on your own site with an Google adSense account.</p> <p>I expect the web-game portals and other web-game services to add support for Silverlight once the plug-in becomes more ubiquitous and we reach a tipping point in the number of Silverlight games and game developers.</p> <p>My advice: jump-in! The more people developing Silverliht games the quicker we will reach this tipping point. </p>
<p>i think the main problem with SilverLight today is its very low browser penetration compared to Flash. Even FlashPlayer 10 which has been out for less than 6 months surpasses SilverLight's adoption. There's every reason to believe this <em>could</em> change over time, esp. on Windows platforms, and certainly because the army of .NET programmers is a formidable one. But right now your game would be depending on users agreeing to install a download - something that's not always easy. Whereas if they've been to YouTube, say, then they're gonna have Flash.</p>
47,693
<p>I'm getting this problem:</p> <pre><code>PHP Warning: mail() [function.mail]: SMTP server response: 550 5.7.1 Unable to relay for chris.mahan@gmail.com in c:\inetpub\wwwroot\mailtest.php on line 12 </code></pre> <p>from this script:</p> <pre><code>&lt;?php $to = "chris.mahan@gmail.com"; $subject = "test"; $body = "this is a test"; if (mail($to, $subject, $body)){ echo "mail sent"; } else { echo "problem"; } ?&gt; </code></pre> <p>section from php.ini on the server:</p> <pre><code>[mail function] ; For Win32 only. SMTP = server.domain.com; for Win32 only smtp_port = 25 ; For Win32 only. sendmail_from = support@domain.com ; For Unix only. You may supply arguments as well (default: "sendmail -t -i"). ;sendmail_path = </code></pre> <p>(note that "server" and "domain" refer accurately to the actual server and domain name)</p> <p>In IIS, SMTP is running. Under <code>"Access"</code> tab, <code>"Relay"</code> button, the Select which computers may relay through this virtual server is set to <code>checkbox "only the list below"</code> and on the list is <code>"127.0.0.1(xxx.xxx.xxx.xxx)" (x's representing actual server IP address).</code></p> <p>Server is running <code>Windows Server 2003 Service Pack 2</code>, fully patched as of 5 PM Sept 1st 2008. I assume it is running <code>IIS7</code> (how to check?).</p> <p>Any ideas?</p> <p>In reponse to <a href="https://stackoverflow.com/users/2257/espo">Espo</a>: This machine is hosted at a datacenter. We do not want to use a gmail account (were doing it, want to move away from that). Windows server 2003 comes with its own SMTP server.</p> <p>Update: Per Yaakov Ellis' advice, I dropped all relay restrictions and added the server IP to the allowed list (using the reverse DNS button provided) and the thing started working.</p> <p>Thanks to both Espo and Yaakov for helping me out.</p>
<p>Try removing the IP restrictions for Relaying in the SMTP server, and opening it up to all relays. If it works when this is set, then you know that the problem has to do with the original restrictions. In this case, it may be a DNS issue, or perhaps you had the wrong IP address listed.</p>
<p>@Espo: I'll do that re KB153119. Thanks.</p> <p>About the mail server: I hear you. </p> <p>I'll update when I uncover more.</p>
5,991
<p>I'm writing a web application that <em>dynamically</em> creates URL's based off of some input, to be consumed by a client at another time. For discussion sake these URL's can contain certain characters, like a <strong>forward slash (i.e. '/')</strong>, which should not be interpreted as part of the actual URL, but just as an argument. For example:</p> <pre>http://mycompany.com/PartOfUrl1/PartOfUrl2/ArgumentTo/Url/GoesHere</pre> <p>As you can see, the <strong>ArgumentTo/Url/GoesHere</strong> does indeed have forward slashes but these should be <em>ignored or escaped</em>.</p> <p>This may be a bad example but the question in hand is more general and applies to other <em>special characters</em>.</p> <h3>So, if there are pieces of a URL that are just <em>argument</em>s and should not be used to resolve the actual web request, what's a good way of handling this?</h3> <h1>Update:</h1> <p>Given some of the answers I realized that I failed to point out a few pieces that hopefully will help clarify.</p> <p>I would like to keep this fairly language agnostic as it would be great if the client could just make a request. For example, if the client knew that it wanted to pass <strong>ArgumentTo/Url/GoesHere</strong>, it would be great if that could be <em>encoded</em> into a <em>unique</em> string in which the server could turn around and <em>decode</em> it to use.</p> <p>Can we assume that similar functions like HttpUtility.HtmlEncode/HtmlDecode in the .NET Framework are available on other systems/platforms? The URL does not have to be <em>pretty</em> by any means so having <em>real words</em> in the path does not really matter.</p> <h3>Would something like a base64 encoding of the argument work?</h3> <p>It seems that base64 encoding/decoding is fairly readily available on any platform/language.</p>
<p>You didn't say which language you're using, but PHP has the useful <code>urlencode</code> function and C# has <code>HttpUtility.URLEncode</code> and <code>Server.UrlEncode</code> which should encode parts of your URL nicely.</p> <p>In case you need another way <a href="http://www.december.com/html/spec/esccodes.html" rel="nofollow noreferrer">this page</a> has a list of encoded values. E.g.: <code>/ == %2f</code>.</p> <h3>update</h3> <p>From what you've updated I'd say use Voyagerfan's idea of URLRewriting to make something like:</p> <pre><code>http://www.example.com/([A-Za-z0-9/]+) http://www.example.com/?page=$1 </code></pre> <p>And then use the applications GET parser to filter it out.</p>
<p>I believe what you're looking for, if using .net, is the HttpUtility.EncodeUrl() method, as it has many overrides. Look here: <a href="http://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode.aspx</a></p>
29,912
<p>Right now, I'm particularly interested in reading the data from MP3 files (ID3 tags?), but the more it can do (eg EXIF from images?) the better without compromising the ID3 tag reading abilities.</p> <p>I'm interested in making a script that goes through my media (right now, my music files) and makes sure the file name and directory path correspond to the file's metadata and then create a log of mismatched files so I can check to see which is accurate and make the proper changes. I'm thinking Ruby or Python (see <a href="https://stackoverflow.com/questions/8948/accessing-mp3-meta-data-with-python">a related question specifically for Python</a>) would be best for this, but I'm open to using any language really (and would actually probably prefer an application language like C, C++, Java, C# in case this project goes off).</p>
<p>There is a great post on using PowerShell and TagLibSharp on Joel "Jaykul" Bennet's <a href="http://huddledmasses.org/editing-media-tags-from-powershell/" rel="nofollow noreferrer">site</a>. You could use TagLibSharp to read the metatdata with any .NET based language, but PowerShell is quite appropriate for what you are trying to do.</p>
<p>@Thomas Owens PowerShell is now part of the Common Engineering Criteria (as of Microsoft's 2009 Product Line) and starting with Serve 2008 is included as a feature. It stands as much of a chance to be installed as Python or Ruby. You also mentioned that you were willing to go to C#, which could use TagLibSharp. Or you could use IronPython...</p>
4,828
<p>I'm not looking for bug tracking, per se. But more like a build tool: as a developer, it would be awesome if every time I compiled or tried to run code, I could redirect debugging output and record the bugs I most commonly introduce, how long they take to resolve, etc.</p> <p>Is there anything like this out there?</p>
<p>i know that <a href="http://www.fogcreek.com/FogBugz/" rel="nofollow noreferrer">FogBugz</a> has something that you can hit a webservice of theirs with specific information to log the bug. You might be able to add some code to only hit this service for debugging.</p> <p>We use them for our bug tracking and its an awesome site</p>
<p>I think part of the problem here is thinking that the "mistakes" or "bugs" you make while developing are somehow "abnormal". They are not. They are part of "investigating the fix to the problem". :-)</p> <p>Mistakes in coding are not "Bugs" until they get checked into the master sources. If you find and fix them as part of your "investigation" on how to fix the particular problem assigned to you, that's just called ... "being a programmer".</p> <p>Building and testing your "personal" copy of the code before checking it in is how you avoid introducing "bugs" into the project. :-)</p>
37,124
<p>I want to search for files containing DOS line endings with grep on Linux. Something like this:</p> <pre class="lang-sh prettyprint-override"><code>grep -IUr --color '\r\n' . </code></pre> <p>The above seems to match for literal <code>rn</code> which is not what is desired.</p> <p>The output of this will be piped through xargs into todos to convert crlf to lf like this</p> <pre><code>grep -IUrl --color '^M' . | xargs -ifile fromdos 'file' </code></pre>
<p>grep probably isn't the tool you want for this. It will print a line for every matching line in every file. Unless you want to, say, run todos 10 times on a 10 line file, grep isn't the best way to go about it. Using find to run file on every file in the tree then grepping through that for "CRLF" will get you one line of output for each file which has dos style line endings:</p> <pre><code>find . -not -type d -exec file "{}" ";" | grep CRLF</code></pre> <p>will get you something like:</p> <pre><code>./1/dos1.txt: ASCII text, with CRLF line terminators ./2/dos2.txt: ASCII text, with CRLF line terminators ./dos.txt: ASCII text, with CRLF line terminators</code></pre>
<p>If, like me, your minimalist unix doesn't include niceties like the <strong>file</strong> command, and backslashes in your <strong>grep</strong> expressions just don't cooperate, try this:</p> <pre><code>$ for file in `find . -type f` ; do &gt; dump $file | cut -c9-50 | egrep -m1 -q ' 0d| 0d' &gt; if [ $? -eq 0 ] ; then echo $file ; fi &gt; done </code></pre> <p>Modifications you may want to make to the above include:</p> <ul> <li>tweak the <strong>find</strong> command to locate only the files you want to scan</li> <li>change the <strong>dump</strong> command to <strong>od</strong> or whatever file dump utility you have</li> <li>confirm that the <strong>cut</strong> command includes both a leading and trailing space as well as just the hexadecimal character output from the <strong>dump</strong> utility</li> <li>limit the <strong>dump</strong> output to the first 1000 characters or so for efficiency</li> </ul> <p>For example, something like this may work for you using <strong>od</strong> instead of <strong>dump</strong>:</p> <pre><code> od -t x2 -N 1000 $file | cut -c8- | egrep -m1 -q ' 0d| 0d|0d$' </code></pre>
9,952
<p>I have a BlackBerry app running in the background that needs to know when a "Missed call" system dialog is brought up by the system, and programmatically close it without user intervention. How can I do that?</p> <p>I could actually <em>almost</em> know when the dialog is brought up, i.e. a little later I programmatically end the call...but how can I get a reference to the dialog, and close it?</p>
<p>I don't think this is possible without a plugin. I've used activex in the past, maybe it would be possible to write a cross-platform java applet?</p>
<p>You can use google docs that give the facility of editing the documents. This is free and you can use it in your web application also. you just have to reference the dlls.</p> <p>Please see the following link for more details.<br /> <a href="http://code.google.com/apis/documents/docs/2.0/developers_guide_dotnet.html" rel="nofollow">http://code.google.com/apis/documents/docs/2.0/developers_guide_dotnet.html</a></p> <p>You can download the google data api from here.<br /> <a href="http://code.google.com/p/google-gdata/downloads/list" rel="nofollow">http://code.google.com/p/google-gdata/downloads/list</a></p> <p>Thanks.</p>
39,811
<p>I am using an authentication attribute on some of my actions in an asp.net mvc page to refer people to a login screen if they have not authenticated. My problem is returning them to the referring page after they have logged in. I was just keeping track of the referring action and referring controller but that becomes problematic when I also need to keep track of some parameters. Is there some nifty built in trick about which I don't know?</p>
<p>In case you're using FormsAuthentication, when ASP.NET redirects a user to the login page, the URL looks something like this:</p> <pre><code>http://www.mysite.com/Login?ReturnUrl=/Something </code></pre> <p>The login form's action attribute should have the same ReturnUrl parameter (either as hidden input or as part of Url) so that FormsAuthentication can pick it up and redirect, e.g. </p> <pre><code>&lt;form action="Login?ReturnUrl=&lt;%=Html.AttributeEncode(Request.QueryString["ReturnUrl"]) %&gt;"&gt;&lt;/form&gt; </code></pre> <p>or</p> <pre><code>&lt;form&gt;&lt;input type="hidden" name="ReturnUrl" id="ReturnUrl" value="&lt;%=Html.AttributeEncode(Request.QueryString["ReturnUrl"])"%&gt; /&gt;&lt;/form&gt; </code></pre>
<p>You should always ensure that the referring URL is within your domain and a plausible string that they could be coming from. Otherwise this has the potential of being used with flash or other client side technologies to do things like response splitting or other attacks, known and unknown.</p> <p>The HTTP referer is user input, and it should be validated like any other. </p>
21,872
<p>So, I am a total beginner in any kind of <code>Windows</code> related programming. I have been playing around with the <code>Windows</code> <code>API</code> and came across a couple of examples on how to initialize create windows and such. </p> <p>One example creates a regular window (I abbreviated some of the code):</p> <pre><code>int WINAPI WinMain( [...] ) { [...] // Windows Class setup wndClass.cbSize = sizeof( wndClass ); wndClass.style = CS_HREDRAW | CS_VREDRAW; [...] // Register class RegisterClassEx( &amp;wndClass ); // Create window hWnd = CreateWindow( szAppName, "Win32 App", WS_OVERLAPPEDWINDOW, 0, 0, 512, 384, NULL, NULL, hInstance, NULL ); [...] } </code></pre> <p>The second example creates a dialog box (no abbreviations except the WinMain arguments):</p> <pre><code>int WINAPI WinMain( [...] ) { // Create dialog box DialogBox(hInstance, MAKEINTRESOURCE(IDD_MAIN_DLG), NULL, (DLGPROC)DialogProc); } </code></pre> <p>The second example does not contain any call to the register function. It just creates the DialogBox with its DialogProc process attached. </p> <p>This works fine, but I am wondering if there is a benefit of registering the window class and then creating the dialog box (if this is at all possible). </p>
<p>I would say exposing properties on your custom dialog is the idiomatic way to go because that is how standard dialogs (like the Select/OpenFileDialog) do it. Someone could argue it is more explicit and intention revealing to have a ShowBirthdayDialog() method that returns the result you're looking for, but following the framework's pattern is probably the wise way to go.</p>
<p>I've always done it exactly the way you're describing. I'm curious to see if there's a more accepted approach.</p>
5,761
<p>I'm a big fan of <a href="http://logging.apache.org/log4net" rel="noreferrer">log4net</a>, but recently, some (in my department) have questioned its inclusion in our projects because of the seemingly heaviness of each logging method. I would argue that there are better techniques than others, but that's another question.</p> <p>I'm curious to know, what is the typical impact of a log4net DebugFormat-type call on your applications. I'm going to leave out variables like number of log statements per lines of code, etc, because I'm just looking for anything that you've seen in the real world.</p> <p>And, I am aware of the simple technique of adding a guard clause to long evaluation statements eg:</p> <pre><code>if (log.IsDebug) { log.DebugFormat(...); } </code></pre> <p>So, let's exclude that from consideration for now.</p>
<p>I am not familiar with log4net, or log.DebugFormat(...).</p> <p>But the cost of logging is really in two areas.</p> <p>The first is the logging call, and the second is the actual persisting of the log information.</p> <p>The guards help reduce the logging call to a minimum when the logging is not actually necessary. It tends to be very fast, since it's little more than a method call and a comparison of two scalars.</p> <p>However, when you don't use guards, the cost may well become the price of creating the actual logging arguments.</p> <p>For example, in log4j, this was a common idiom:</p> <pre><code>log.debug("Runtime error. Order #" + order.getOrderNo() + " is not posted."); </code></pre> <p>Here, the cost is the actual evaluation of the string expression making the message. This is because regardless of the logging level, that expression, and the resulting string are created. Imagine if instead you had something like:</p> <pre><code>log.debug("Something wrong with this list: " + longListOfData); </code></pre> <p>That could create a large and expensive string variable that, if the log level wasn't set for DEBUG, would simply be wasted.</p> <p>The guards:</p> <pre><code>if (log.isDebug()) { log.debug(...); } </code></pre> <p>Eliminate that problem, since the isDebug call is cheap, especially compared to the actual creation of the argument.</p> <p>In my code, I have written a wrapper for logging, and I can create logs like this:</p> <pre><code>log.debug("Runtime error. Order # {0} is not posted.", order.getOrderNo()); </code></pre> <p>This is a nice compromise. This relies on Java varargs, and my code checks the logging level, and then formats the message appropriately. This is almost as fast as the guards, but much cleaner to write.</p> <p>Now, log.DebugFormat may well do a similar thing, that I don't know.</p> <p>On top of this, of course, is the actual cost of logging (to the screen, to a file, to a socket, etc.). But that's just a cost you need to accept. My best practice for that, when practical, is to route the actual log messages to a queue, which is then reaped and output to the proper channel using a separate thread. This, at least, helps keep the logging out of line with the main computing, but it has expenses and complexity of its own.</p>
<p>The <a href="http://logging.apache.org/log4net/release/faq.html#perf-not-logging" rel="nofollow noreferrer">log4net FAQ has an answer to this</a>, although not to the level of detail you are looking for.</p> <p>In summary: use those guard clauses.</p>
21,581
<p>I'm using GDI+ in a C++/MFC application and I just can't seem to avoid flickering whenever the window is resized.</p> <p>I have already tried these steps:</p> <ul> <li>returned TRUE on <code>OnEraseBkGnd()</code>;</li> <li>returned NULL on <code>OnCtlColor()</code>;</li> <li>used double buffering according to this code:</li> </ul> <p></p> <pre><code>void vwView::OnDraw(CDC* pDC) { CRect rcClient; GetClientRect(rcClient); Bitmap bmp(rcClient.Width(), rcClient.Height()); Graphics graphics(&amp;bmp); graphics.DrawImage(m_image, rcClient.left, rcClient.top); Graphics grph(pDC-&gt;m_hDC); grph.DrawImage(&amp;bmp, 0, 0); } </code></pre> <p>Am I doing something wrong? Or is there another way to achieve this?</p>
<p>To completely avoid flicker, you would need to complete <em>all</em> drawing in the interval between screen updates. Windows does not provide any easy means of accomplishing this for normal window painting (Vista provides composite drawing via the <a href="https://en.wikipedia.org/wiki/Desktop_Window_Manager" rel="noreferrer">DWM</a>, but this cannot be relied on even on systems running Vista). Therefore, the best you can do to minimize flicker is to draw everything as quickly as possible (<em>reduce</em> tearing by increasing your chances of completing all drawing within a refresh cycle), and avoid overdraw (drawing part of the screen and then drawing something else over the top: risks presenting user with a partially-drawn screen).</p> <p>Let's discuss the techniques presented here so far:</p> <ul> <li><p><strong>Do-nothing <i>OnEraseBkgnd()</i></strong>: helps to avoid over-draw by preventing the invalidated area of the window from being filled with the window's background color. Useful when you will be drawing the entire area again during <i>WM_PAINT</i> handling <em>anyway</em>, as in the case of double-buffered drawing... but see <i>Notes on avoiding overdraw by preventing drawing after your </i>WM_PAINT<i> method</i>.</p> </li> <li><p><strong>Returning NULL for <i>OnCtlColor()</i></strong>: this shouldn't actually do <em>anything</em>... unless you have child controls on your form. In that case, see <i>Notes on avoiding overdraw by preventing drawing after your </i>WM_PAINT<i> method</i> instead.</p> </li> <li><p><strong>Double buffered drawing</strong>: helps to avoid tearing (and potentially overdraw as well), by reducing the actual on-screen drawing to a single <a href="https://en.wikipedia.org/wiki/Bit_blit" rel="noreferrer">BitBLT</a>. May hurt the time needed for drawing though: hardware acceleration cannot be used (although with GDI+, the chances of any hardware-assisted drawing being used are quite slim), an off-screen bitmap must be created and filled for each redraw, and the entire window must be repainted for each redraw. See <em>Notes on efficient double-buffering</em>.</p> </li> <li><p><strong>Using GDI calls rather than GDI+ for the BitBlt</strong>: This is often a good idea - <code>Graphics::DrawImage()</code> can be very slow. I've even found the normal GDI <a href="https://msdn.microsoft.com/en-us/library/dd183370.aspx" rel="noreferrer"><code>BitBlt()</code></a> call to be faster on some systems. Play around with this, but only after trying a few other suggestions first.</p> </li> <li><p><strong>Avoiding window class styles that force a full redraw on each resize (<i>CS_VREDRAW</i>, <i>CS_HREDRAW</i>)</strong>: This will help, but only if you don't <em>need</em> to redraw the entire window when size changes.</p> </li> </ul> <h3>Notes on avoiding overdraw by preventing drawing prior to your <i>WM_PAINT</i> method</h3> <p>When all or a portion of a window is invalidated, it will be erased and repainted. As already noted, you can skip erasing if you plan to repaint the entire invalid area. <strong>However</strong>, if you are working with a child window, then you must ensure that parent window(s) are not also erasing your area of the screen. The <i>WS_CLIPCHILDREN</i> style should be set on all parent windows - this will prevent the areas occupied by child windows (including your view) from being drawn on.</p> <h3>Notes on avoiding overdraw by preventing drawing after your <i>WM_PAINT</i> method</h3> <p>If you have <em>any</em> child controls hosted on your form, you will want to use the <i>WS_CLIPCHILDREN</i> style to avoid drawing over them (and subsequently being over drawn by them. Be aware, this will impact the speed of the BitBlt routine somewhat.</p> <h3>Notes on efficient double-buffering</h3> <p>Right now, you're creating a new back-buffer image each time the view draws itself. For larger windows, this can represent a significant amount of memory being allocated and released, and <em>will</em> result in significant performance problems. I recommend keeping a dynamically-allocated bitmap in your view object, re-allocating it as needed to match the size of your view.</p> <p>Note that while the window is being resized, this will result in just as many allocations as the present system, since each new size will require a new back buffer bitmap to be allocated to match it - you can ease the pain somewhat by rounding dimensions up to the next largest multiple of 4, 8, 16, etc., allowing you to avoid re-allocated on each tiny change in size.</p> <p>Note that, if the size of the window hasn't changed since the last time you rendered into the back buffer, you don't need to re-render it when the window is invalidated - just Blt out the already-rendered image onto the screen.</p> <p>Also, allocate a bitmap that matches the bit depth of the screen. The constructor for <code>Bitmap</code> you're currently using will default to 32bpp, ARGB-layout; if this doesn't match the screen, then it will have to be converted. Consider using the GDI method <a href="https://msdn.microsoft.com/en-us/library/dd183488.aspx" rel="noreferrer"><code>CreateCompatibleBitmap()</code></a> to get a matching bitmap.</p> <p>Finally... I assume your example code is just that, an illustrative snippet. But, if you are actually doing nothing beyond rendering an existing image onto the screen, then you don't really need to maintain a back buffer at all - just Blt directly from the image (and convert the format of the image ahead of time to match the screen).</p>
<p>Are there child windows on the form? The Window manager starts by getting the parent window to erase its background by sending a WM_ERASEBKGND message, THEN it sends a wM_PAINT message - presumably this maps to your wx::OnDraw method. Then it iterates over each child control and gets those to paint themselves. </p> <p>If this is your scenario... using Vistas new aero look would solve your problem as the aero desktop window manager does window compositing automatically. With the older window manager its a pita.</p>
24,097
<p>I have the following tuple, which contains tuples:</p> <pre><code>MY_TUPLE = ( ('A','Apple'), ('C','Carrot'), ('B','Banana'), ) </code></pre> <p>I'd like to sort this tuple based upon the <strong>second</strong> value contained in inner-tuples (i.e., sort Apple, Carrot, Banana rather than A, B, C).</p> <p>Any thoughts?</p>
<pre><code>from operator import itemgetter MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=itemgetter(1))) </code></pre> <p>or without <code>itemgetter</code>:</p> <pre><code>MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=lambda item: item[1])) </code></pre>
<p>I achieved the same thing using this code, but your suggestion is great. Thanks!</p> <pre><code>templist = [ (line[1], line) for line in MY_TUPLE ] templist.sort() SORTED_MY_TUPLE = [ line[1] for line in templist ] </code></pre>
27,485
<p>Recently, I started changing some of our applications to support <code>MS SQL Server</code> as an alternative back end. </p> <p>One of the compatibility issues I ran into is the use of MySQL's CREATE TEMPORARY TABLE to create in-memory tables that hold data for very fast access during a session with no need for permanent storage.</p> <p>What is the equivalent in MS SQL?</p> <p>A requirement is that I need to be able to use the temporary table just like any other, especially <code>JOIN</code> it with the permanent ones.</p>
<p>@Keith</p> <p>This is a common misconception: Table variables are NOT necessarily stored in memory. In fact SQL Server decides whether to keep the variable in memory or to spill it to TempDB. There is no reliable way (at least in SQL Server 2005) to ensure that table data is kept in memory. For more detailed info look <a href="http://blogs.msdn.com/sqlserverstorageengine/archive/2008/03/30/sql-server-table-variable-vs-local-temporary-table.aspx" rel="noreferrer">here</a></p>
<p>CREATE TABLE #tmptablename</p> <p>Use the hash/pound sign prefix</p>
4,749
<p>I was currently developing a desktop application in C# using mono and testing in SuSE and Windows. The concept doesn't matter much, but it is a "web lint" program that will scan a web site and return possible issues with security and/or cross browser compatibility. However, I want to be able to offer binaries for multiple platforms. Should I stay with Mono, or is there another platform that would give me a better availablility of platforms, such as on Macs, Windows, Linux, and others (possibly mobile platforms), and make it easier to port? </p>
<p>C# and Mono is probably cross-platform enough for most desktop environments. The trick will be the "mobile platform" requirement. </p> <p>Mobile operating systems are wildly diverse and there's not a lot you can do to generalize. Some have Java, like the Blackberry. C# may get you onto Windows Mobile-based platforms. iPhones do their own thing. You pretty much have to pick a platform and target that. That may end up informing your desktop platform choice.</p>
<p>It really depends what you want to do. For web development, if HTML/JavaScript is enough then stick with it. If you need more advanced stuff I would use ASP.NET with Mono (what you probably did) since you already know that. (You can use Visual Studio here.)</p> <p>Another option might be (since you are a C# developer) to use Silverlight. That gives you Windows and Mac platforms covered and hopefully <a href="http://www.mono-project.com/Moonlight" rel="nofollow noreferrer">Moonlight</a> will cover Linxu platform later. (You can use Visual Studio and Expression Blend here.)</p> <p>If you need desktop application then Java is probably the easiest since you already know C#. But if you know C/C++ try to take a look at <a href="http://www.wxwidgets.org/" rel="nofollow noreferrer">wxWidgets</a> for example.</p>
18,028
<p>I am working on a Perl script to read CSV file and do some calculations. CSV file has only two columns, something like below.</p> <pre><code>One Two 1.00 44.000 3.00 55.000 </code></pre> <p>Now this CSV file is very big ,can be from 10 MB to 2GB.</p> <p>Currently I am taking CSV file of size 700 MB. I tried to open this file in notepad, excel but it looks like no software is going to open it.</p> <p>I want to read may be last 1000 lines from CSV file and see the values. How can I do that? I cannot open file in notepad or any other program.</p> <p>If I write a Perl script then I need to process complete file to go to end of file and then read last 1000 lines.</p> <p>Is there any better way to that? I am new to Perl and any suggestions will be appreciated. </p> <p>I have searched net and there are some scripts available like <a href="https://metacpan.org/pod/File::Tail" rel="nofollow noreferrer"><code>File::Tail</code></a> but I don't know they will work on windows ?</p>
<p>In *nix, you can use the tail command.</p> <pre><code>tail -1000 yourfile | perl ... </code></pre> <p>That will write only the last 1000 lines to the perl program.</p> <p>On Windows, there are <a href="http://sourceforge.net/project/showfiles.php?group_id=163416" rel="noreferrer">gnuwin32</a> and <a href="http://sourceforge.net/projects/unxutils" rel="noreferrer">unxutils</a> packages both have <code>tail</code> utility.</p>
<p>Without relying on tail, which I probably would do, if you have more than $FILESIZE [2GB?] of memory then I'd just be lazy and do:</p> <pre><code>my @lines = &lt;&gt;; my @lastKlines = @lines[-1000,-1]; </code></pre> <p>Though the other answers involving <code></code>tail<code></code> or <code>seek()</code> are pretty much the way to go on this.</p>
38,930
<p>Do you know any Javascript libraries which can present graph visually in a web page?</p> <p>Clarification: by graphs I mean something like workflow trees or decision trees. Sorry for not being clear.</p>
<p>I've been doing some research, looking for a JS component that would handle the live creation of flow charts / decision trees, mxGraph looks pretty handy: <a href="http://www.jgraph.com/mxgraph.html" rel="noreferrer">http://www.jgraph.com/mxgraph.html</a></p> <p>Disclaimer: I have no relationship at all with the vendor, other than having searched the net for something suitable.</p>
<p>We used <a href="http://developer.yahoo.com/yui/" rel="nofollow noreferrer">YUI</a> in our last project. It's free and has a lot of neat features, check it out!</p> <p><strong>EDIT:</strong> Charts is the component that allows statistical type graphs, scatter plots and other charting stuff. I didn't realize you were looking for a flowchart / hierarchy based graph.</p>
47,469
<p>I'm interested in printing small machine parts (gears, linkages, structural components) so I'm looking for accuracy and mechanical strength over speed and volume.</p> <p>I'm also somewhat concerned about harmful emissions so would like a solution with some sort of filtration, whether it's built into the machine or something added. I'm thinking I will run the machine in an unventilated garage, which is quite warm and humid during the summer in Texas.</p> <p>My price range is \$1500-\$2000 USD. I've looked at several options but I didn't really come across any scenarios like I've described and would like some advice from the experts before committing.</p> <p>Anyone in a similar boat have any suggestions?</p>
<p>Your environmental conditions will preclude finding a machine suitable for your purposes in the budget specified.</p> <p>Humidity is a problem with many material types, especially nylon, but also with PLA and ABS, the more common filaments used in 3D printing.</p> <p>You can likely reject PLA for your mechanical needs, as it is brittle and weak compared to ABS. PLA releases virtually no gases of concern, while some find ABS fumes to be offensive and dangerous. </p> <p>The humidity issue is forefront in your search. You may have to construct within the garage a chamber in which you would operate a portable or window air conditioner unit, to keep the humidity in check. If you can assign a different budget to such a construction, that will leave your printer funding intact and better able to address your goal.</p> <p>Selective Laser Sintering using nylon powder, also susceptible to humidity, which is sintered by a laser, hence the name, making very detailed and strong parts. The process is also self-supporting, allowing for fairly intricate parts. Once the machine is calibrated, the part accuracy can be quite good. Unfortunately, SLS machines are also out of the budget range you've noted.</p> <p>You can use an external service to print the parts you design, at least at first, to get a better indication of how the various materials will work for you. Start with PLA, then move to ABS for a set of test parts, and even perhaps have some printed using SLS.</p> <p>If you find, for example, that ABS will be strong enough, you might find an affordable 3D printer which will generate parts on your budget and timeline. For printing ABS, the warmer temperatures are to your advantage, but the humidity has to be properly addressed in any home/shop/garage installation.</p>
<p>There is more than one question here. Which touches three topics: the choice of appropriate 3D printing technique, the choice of materials, and control of any hazardous, noxious, or annoying out-gassing. </p> <p>It is important to understand the limits of the 3D printing process you will choose. Each process has its own limits on repeatability and resolution of small features, such as gear teeth. A 10 pitch (teeth-per-inch) gear could print acceptably well with a low-cost printer, but the size of a 10-tooth gear would be 1/2" diameter. This could be a small part, or a huge part, depending on the use. To print an 1/8" diameter 10-tooth gear would require a 100 pitch gear likely would not, and would call for an optical process (laser sintering (SLS) or photo-polymerization (like the FormLabs Form 2)) or a dot-jetting process (such as the StrataSys Objet Connex machines). These are not in the budget you've suggested, but are available through service bureaus.</p> <p>Answers here <a href="https://3dprinting.stackexchange.com/questions/3392/how-can-i-print-gears-using-very-high-resolution-material-like-nylon">another community question</a> give some hints for using a plastic-extrusion machine, and information about SLS.</p> <p>Each process has different environmental requirements, and impacts, but first should be to understand the requirements of the parts, based on those choose a process and material, and then mitigate the environmental factors.</p>
674
<p>I have an AI file. I paste it into Expression Blend and then export the XAML for use in my WPF project. Works for most of my files, but some export the XAML plus a seperate png file. What can I do so that the png is embedded into the paths of my image and not a seperate image? Can it be done?</p>
<p>Checkout this page that describes converting raster graphics to vector and then XAML -</p> <p><a href="http://weblogs.asp.net/rrobbins/archive/2007/11/11/how-to-convert-raster-graphics-to-xaml.aspx" rel="nofollow noreferrer">http://weblogs.asp.net/rrobbins/archive/2007/11/11/how-to-convert-raster-graphics-to-xaml.aspx</a></p>
<p>To convert raster images to vectorial images, I found <a href="http://www.inkscape.org/" rel="nofollow noreferrer">Inkscape</a> (free) to do an excellent job (comparable to VectorMagic, which is not free anymore by the way). </p> <p>In Inkscape, import your image and use the Path/Trace Bitmap function. It has a lot of control. </p> <p>Once you converted to a vectorial image, save it as a SVG. Then, using <a href="http://www.wpf-graphics.com/ViewerSvg.aspx" rel="nofollow noreferrer">ViewerSvg</a>, you can convert to XAML vector data. (Path &amp; Canvas)</p>
21,624
<p>Usually the hardness of the material is considered primary for nozzles used with abrasive filaments. Has friction between between nozzle material and abrasive filaments been considered? It seems that friction as well as hardness would play a roll in how long the nozzle lasts. Perhaps, this is considered with ruby tipped nozzles.</p>
<p>I think I found the problem. I think there was some crosstalk between the BLTouch wires and the other wires it was tied together leading to the hotend. When I moved the BLTouch wires away from the others the problem went away.</p> <p>I will be added a sheild to the cable in the future like in this <a href="https://www.youtube.com/watch?v=jkcrRCxPlZM&amp;ab_channel=509Drone" rel="nofollow noreferrer">youtube video</a></p>
<p>The OP already found the problem and <a href="/a/16632/">answered</a> the question hinting to shielding of the cable. If this is the actual problem, of fiddling with the cables might have caused this, an alternative solution is presented as I've experienced similar behavior.</p> <p>If one side of the bed is higher than the rest, even when rotating the glass bed, you might experience that the nozzle carriage is tilting on that side. E.g. when using a Bowden extruder assembly, a too short Bowden tube (or cables in a non-Bowden setup) the tube (or cables) pull at the carriage causing it to lift at the furthest points from the extruder; this tilting can cause the nozzle to go up a few tenths of a millimeter.</p>
1,970
<p>The <a href="http://en.wikipedia.org/wiki/Law_of_Demeter" rel="noreferrer">Law of Demeter</a> indicates that you should only speak to objects that you know about directly. That is, do not perform method chaining to talk to other objects. When you do so, you are establishing improper linkages with the intermediary objects, inappropriately <a href="http://en.wikipedia.org/wiki/Coupling_(computer_science)" rel="noreferrer">coupling</a> your code to other code.</p> <p>That's bad.</p> <p>The solution would be for the class you do know about to essentially expose simple wrappers that delegate the responsibility to the object it has the relationship with.</p> <p>That's good.</p> <p>But, that seems to result in the class having low <a href="http://en.wikipedia.org/wiki/Cohesion_(computer_science)" rel="noreferrer">cohesion</a>. No longer is it simply responsible for precisely what it does, but it also has the delegates that in a sense, making the code less cohesive by duplicating portions of the interface of its related object.</p> <p>That's bad.</p> <p>Does it really result in lowering cohesion? Is it the lesser of two evils?</p> <p>Is this one of those gray areas of development, where you can debate where the line is, or are there strong, principled ways of making a decision of where to draw the line and what criteria you can use to make that decision?</p>
<p>Grady Booch in "Object Oriented Analysis and Design":</p> <p>"The idea of cohesion also comes from structured design. Simply stated, cohesion measures the degree of connectivity among the elements of a single module (and for object-oriented design, a single class or object). The least desirable form of cohesion is coincidental cohesion, in which entirely unrelated abstractions are thrown into the same class or module. For example, consider a class comprising the abstractions of dogs and spacecraft, whose behaviors are quite unrelated. The most desirable form of cohesion is functional cohesion, in which the elements of a class or module all work together to provide some well-bounded behavior. Thus, the class Dog is functionally cohesive if its semantics embrace the behavior of a dog, the whole dog, and nothing but the dog."</p> <p>Subsitute Dog with Customer in the above and it might be a bit clearer. So the goal is really just to aim for functional cohesion and to move away from coincidental cohesion as much as possible. Depending on your abstractions, this may be simple or could require some refactoring.</p> <p>Note cohesion applies just as much to a "module" than to a single class, ie a group of classes working together. So in this case the Customer and Order classes still have decent cohesion because they have this strong relationshhip, customers create orders, orders belong to customers.</p> <p>Martin Fowler says he'd be more comfortable calling it the "Suggestion of Demeter" (see the article <a href="http://martinfowler.com/articles/mocksArentStubs.html" rel="noreferrer">Mocks aren't stubs</a>):</p> <p>"Mockist testers do talk more about avoiding 'train wrecks' - method chains of style of getThis().getThat().getTheOther(). Avoiding method chains is also known as following the Law of Demeter. While method chains are a smell, the opposite problem of middle men objects bloated with forwarding methods is also a smell. (I've always felt I'd be more comfortable with the Law of Demeter if it were called the <strong>Suggestion of Demeter</strong> .)"</p> <p>That sums up nicely where I'm coming from: it is perfectly acceptable and often necessary to have a lower level of cohesion than the strict adherence to the "law" might require. Avoid coincidental cohesion and aim for functional cohesion, but don't get hung up on tweaking where needed to fit in more naturally with your design abstraction.</p>
<p>In the situations where there seems to be a tradeoff between coupling and cohesion, I'd probably ask myself "if somebody else had already written this logic, and I were looking for a bug in it, where would I look first?", and write the code that way.</p>
19,719
<pre><code>import sys words = { 1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5 : 'five', 6 : 'six', 7 : 'seven', 8 : 'eight', 9 : 'nine', 10 : 'ten', 11 : 'eleven', 12 : 'twelve', 13 : 'thirteen', 14 : 'fourteen', 15 : 'fifteen', 16 : 'sixteen', 17 : 'seventeen', 18 : 'eighteen', 19 : 'nineteen' } tens = [ '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety', ] placeholders = [ '', 'thousand', 'million', 'billion', 'trillion', 'quadrillion' ] # segMag = segment magnitude (starting at 1) def convertTrio(number): return ' '.join([words[int(number[0])], 'hundred', convertDuo(number[1:3])]) # convertDuo(number[1:3]) def convertDuo(number): #if teens or less if int(number[0]) == 1: return words[int(number)] #twenty-five else: return tens[int(number[0]) - 1] + '-' + words[int(number[1])] if __name__ == "__main__": string = [] numeralSegments = [] numeral = sys.argv[1] if int(numeral) &lt; 100: print convertDuo(numeral) else: # split number into lists, grouped in threes for i in range (0, len(numeral), 3): numeralSegments.append(numeral[i:i+3]) numeralSegments.reverse() # for every segment, convert to trio word and append thousand, million, etc depending on magnitude for i in range (len(numeralSegments)): string.append(convertTrio(numeralSegments[i]) + ' ' + placeholders[i]) # reverse the list of strings before concatenating to commas string.reverse() print ', '.join(string) </code></pre> <p><strong>Warning</strong>: I'm a total python novice. I'm aware there are probably many times more efficient ways of doing things. I'd appreciate any pointers to them.</p> <p><strong>Edit</strong>: The code currently only works for numbers whose digit counts are multiples of three. I'd appreciate a suggestion for an elegant way to fix that as well. Thanks.</p>
<p>You can't group digits into "segments" going from left-to-right. The <code>range(0,len(),3)</code> is not going to work out well. You'll have to write the same algorithm for inserting digit separators. You start from the right, picking off segments of digits.</p> <p>What's left over (on the left, get it?) will be 1, 2 or 3 digits. You've got convertTrio and convertDuo, which handle 3 and 2 digits, respectively. Somewhere in there is a convert one digit function (can't see it).</p> <p>If it's not homework, then, here's a proper digit clustering algorithm</p> <pre><code>def segment( n ): segList= [] while len(n) &gt; 3: segList.insert( 0, n[-3:] ) n= n[:-3] segList.insert( 0, n ) return segList </code></pre> <p>Edit</p> <p>To be more Pythonic, package this as a tidy, reusable module. The stuff inside the <code>if __name__ == "__main__"</code> does two things, which should be separated.</p> <p>Your command-line parsing (anything having to do with <code>sys.argv</code> is one thing. The actual "convert a number" function is something else entirely. You want to look more like this.</p> <pre><code>if __name__ == "__main__": import sys for number in sys.argv[1:]: print number2string( number ) </code></pre> <p>Then, your <code>number2string</code> function becomes an easily reused piece of this module.</p>
<p>Check out source for <a href="http://search.cpan.org/src/LHOWARD/Number-Spell-0.04/Spell.pm" rel="nofollow noreferrer">Number::Spell</a> Perl module. It is short and can be easily ported to Python (if it has not already been done).</p>
36,910
<p>I found some wild remarks that ASP.NET MVC is 30x faster than ASP.NET WebForms. What real performance difference is there, has this been measured and what are the performance benefits.</p> <p>This is to help me consider moving from ASP.NET WebForms to ASP.NET MVC.</p>
<p>We haven't performed the type of scalability and perf tests necessary to come up with any conclusions. I think ScottGu may have been discussing potential perf targets. As we move towards Beta and RTM, we will internally be doing more perf testing. However, I'm not sure what our policy is on publishing results of perf tests.</p> <p>In any case, any such tests really need to consider real world applications...</p>
<p><img src="https://i.stack.imgur.com/I7eXy.png" alt="enter image description here"></p> <p>I did a small VSTS load test experiment with some basic code and found ASP.NET MVC response time to be twice faster as compared to ASP.NET Webforms. Above is the attached graph with the plot. </p> <p>You can read this load test experiment in details from this CP article <a href="https://www.codeproject.com/Articles/864950/ASP-NET-MVC-vs-ASP-NET-WebForm-performance-compari" rel="nofollow noreferrer">https://www.codeproject.com/Articles/864950/ASP-NET-MVC-vs-ASP-NET-WebForm-performance-compari</a></p> <p>Test was conducted with the below specifications using VSTS and telerik load test software:-</p> <p>User load 25 users.</p> <p>Run duration of test was 10 minutes.</p> <p>Machine config DELL 8 GB Ram, Core i3</p> <p>Project was hosted in IIS 8.</p> <p>Project was created using MVC 5.</p> <p>Network LAN connection was assumed. So this test does not account for network lag for now.</p> <p>Browser in the test selected Chrome and Internet explorer.</p> <p>Multiple reading where taken during the test to average unknown events. 7 readings where taken and all readings are published in this article as reading 1 , 2 and so on.</p>
6,531
<p>We have a Silverlight application that needs to load a number of .png files. We can load the images OK, but Silverlight doesn't support reading the pixel data from the Image class.</p> <p>Can anyone suggest a simple solution for getting at this data? Our current best bet would be a third party .png loading library, but we are having trouble finding a suitable one.</p>
<p>PNG decoding is hard to find.</p> <p>I wrote an article for MSDN that includes some open source code I cobbled together from Joe Stegman, FluxCapacity, and a few others. It includes PNG decoding (as well as GIF, JPG, and BMP) for those in this thread that are looking for that.</p> <p><a href="http://www.microsoft.com/youshapeit/msdn/ExpertKnowledge/2008-10/InnovateWithSilverlight2.aspx" rel="nofollow noreferrer">http://www.microsoft.com/youshapeit/msdn/ExpertKnowledge/2008-10/InnovateWithSilverlight2.aspx</a></p> <p>If you don't care for my implementation of it for Silverlight, then you can go straight to what I modified for PNG decoding: <a href="http://sourceforge.net/projects/pr2/" rel="nofollow noreferrer">http://sourceforge.net/projects/pr2/</a></p> <p>Cheers!</p> <p>Update: It looks like they no longer offer the source code on the site, so I re-posted the content here: <a href="http://dimebrain.com/2009/01/innovate-with-silverlight-2-article-code-available.html" rel="nofollow noreferrer">http://dimebrain.com/2009/01/innovate-with-silverlight-2-article-code-available.html</a></p>
<p>Thanks - I've seen the Joe Stegman blog. It's very handy, but the decoder he doesn't have is a PNG one. We're using PNGs as we need transparency. The fluxtools link seems to be broken too.</p> <p>I'm still looking (unsuccessfully) for a PNG decoder I can drop into Silverlight.</p>
38,048
<p>I wan't to know the real size of a web page (HTML + CSS + Javascript + Images + etc.) but from the browser side, maybe with a software, Firefox Add-On or similar?</p>
<p>Use firefox, and get FireBug.</p> <p>Then get the YSlow addon for firefox.</p> <p>For IE, you can get the DebugBar which comes pretty close to giving the same information. </p>
<p>I think the Firefox Plugin <a href="https://addons.mozilla.org/de/firefox/addon/1433" rel="nofollow noreferrer">Extended Statusbar</a> can do that for you.</p> <p>It will give detailed information about what has been downloaded, including the size of the downloaded data.</p>
19,646
<p><p>In a database I am designing I have implemented profile based object level security. <p>Each user can view, edit, insert, update database tables according to the profiles (roles) he is a member of. <p>Now there is a need to implement "External Users" who can view only the relevant records and edit some of them (but not the bulk of the database).</p> <p><p>I am working on an "record ownership" model. <p>Are there any ideas on how to restrict the users belonging to an "External Users" profile to see and work with some records of each table, but not all.</p>
<p>You should probably create a VIEW which limits the records and then apply the proper rights on the view. </p>
<p><p>I have my first draft. It goes like that: <p>The app is a Project Management/Issue Tracking/Event Management/Collaboration Web app. <p>I created a Role "External User". By default a user in that role </p> <ul> <li>can SELECT FROM Persons <li>can SELECT FROM Units (organizational units-companies-depts etc) <li>can SELECT Projects assigned to him <li>can SELECT Tasks assigned to him <li>can not SELECT any other Projects & Tasks </ul> <p><p>The administrator can create a user group "External Partner" and assign to that some Projects and Products (with Issues) <p>The members of this group can SELECT the assigned Objects.</p> <p><p>It is a complicated solution, but the only one that solves my customers problem (they don't want external partners to have access to all their project database).</p>
27,233
<p>I'm making a web application and I got the design for it from a sub-contracted design company. The design is pretty nice, I like it, but I've stumbled across one thing I'm not sure how to implement nicely.</p> <p>The thing is - they've redesigned the looks of buttons to match the page style. So now I have two images - button up and button down. In Opera and FF I just say in css something like this:</p> <pre><code>input[type="submit"] { background-image: url(btn_up.png); } input[type="submit"]:active { background-image: url(btn_down.png); } </code></pre> <p>And it works like a charm. IE unfortunately does not understand the <code>:active</code> part. As with most web applications the IE crowd are the main intended audience, so it's rather important that it looks good <i>at least</i> there.</p> <p>Currently I've made a bulky workaround using an IE-only JavaScript, but I'm wondering - isn't there a more elegant way of doing this? Google and SO search did not help.</p>
<p>As far as I was aware the CSS Pseudo-classes are for links ONLY in IE. This may have changed in IE8 but I'm not aware of it. So basically I don;t think there is an elegant way of implementing it via CSS.</p> <p>That's not a useful answer so I'll also add that I would implement it using images and client-side script which isn't elegant but should allow do the job across all browsers if the client-side script is right.</p> <p>Cheers</p>
<p><a href="http://www.quirksmode.org/css/contents.html#t16" rel="nofollow">http://www.quirksmode.org/css/contents.html#t16</a></p> <p>"IE 7 supports :hover, but not :active, on all elements."</p>
44,150
<p>When setting up foreign keys in SQL Server, under what circumstances should you have it cascade on delete or update, and what is the reasoning behind it?</p> <p>This probably applies to other databases as well.</p> <p>I'm looking most of all for concrete examples of each scenario, preferably from someone who has used them successfully.</p>
<p>Summary of what I've seen so far:</p> <ul> <li>Some people don't like cascading at all. </li> </ul> <h2>Cascade Delete</h2> <ul> <li>Cascade Delete may make sense when the semantics of the relationship can involve an exclusive <em>"is part of</em>" description. For example, an OrderLine record is part of its parent order, and OrderLines will never be shared between multiple orders. If the Order were to vanish, the OrderLine should as well, and a line without an Order would be a problem.</li> <li>The canonical example for Cascade Delete is SomeObject and SomeObjectItems, where it doesn't make any sense for an items record to ever exist without a corresponding main record.</li> <li>You should <em>not</em> use Cascade Delete if you are preserving history or using a "soft/logical delete" where you only set a deleted bit column to 1/true. </li> </ul> <h2>Cascade Update</h2> <ul> <li>Cascade Update may make sense when you use a real key rather than a surrogate key (identity/autoincrement column) across tables.</li> <li>The canonical example for Cascade Update is when you have a mutable foreign key, like a username that can be changed. </li> <li>You should <em>not</em> use Cascade Update with keys that are Identity/autoincrement columns.</li> <li>Cascade Update is best used in conjunction with a unique constraint. </li> </ul> <h2>When To Use Cascading</h2> <ul> <li>You may want to get an extra strong confirmation back from the user before allowing an operation to cascade, but it depends on your application.</li> <li>Cascading can get you into trouble if you set up your foreign keys wrong. But you should be okay if you do that right.</li> <li>It's not wise to use cascading before you understand it thoroughly. However, it is a useful feature and therefore worth taking the time to understand.</li> </ul>
<p>If you're working on a system with many different modules in different versions, it can be very helpful, if the cascade deleted items are part of / owned by the PK holder. Else, all modules would require immediate patches to clean up their dependent items before deleting the PK owner, or the foreign key relation would be omitted completely, possibly leaving tons of garbage in the system if cleanup is not performed correctly.</p> <p>I just introduced cascade delete for a new intersection table between two already existing tables (the intersection to delete only), after cascade delete had been discouraged from for quite some time. It's also not too bad if data gets lost.</p> <p>It is, however, a bad thing on enum-like list tables: somebody deletes entry 13 - yellow from table "colors", and all yellow items in the database get deleted. Also, these sometimes get updated in a delete-all-insert-all manner, leading to referential integrity totally omitted. Of course it's wrong, but how will you change a complex software which has been running for many years, with introduction of true referential integrity being at risk of unexpected side effects?</p> <p>Another problem is when original foreign key values shall be kept even after the primary key has been deleted. One can create a tombstone column and an ON DELETE SET NULL option for the original FK, but this again requires triggers or specific code to maintain the redundant (except after PK deletion) key value.</p>
8,385
<p>I am a bit of a newbie to Reg Ex and don't fully understand the difference between the different flavors. However, I have a basic Reg Ex that works when I try it via the UNIX system (vi and grep) but not when I try to to use it in PHP's ereg functions. I suspect there is something different about the PHP ereg function that is making this not work:</p> <pre><code>&lt;?php $string = 'Feugiat &lt;em&gt;hendrerit&lt;/em&gt; sit iriuredolor aliquam.'; $string = ereg_replace("&lt;em\b[^&gt;]*&gt;(.*?)&lt;/em&gt;","\\1",$string); echo $string; ?&gt; </code></pre> <p>I would like this to output <strong>Feugiat hendrerit sit iriuredolor aliquam.</strong> without the em tags. However it just returns an empty string.</p>
<p>You may need to escape the backslash:</p> <pre><code>$string = ereg_replace("&lt;em\\b[^&gt;]*&gt;(.*?)&lt;/em&gt;","\\1",$string); </code></pre> <p>This is because <code>\b</code> in a PHP string means something different from a <code>\b</code> in a regular expression. Using <code>\\</code> in the PHP string passes through a single backslash to <code>ereg_replace()</code>. This is the same reason you need to use double backslash in the replacement string <code>"\\1"</code>.</p> <p>Depending on your application, you may also want to consider the possibility that your input <code>$string</code> does not contain any <code>&lt;em&gt;</code> tags. In that case, the above statements would result in an empty string, which is probably not what you intend.</p>
<p>If removing <code>&lt;em&gt;</code> tags is your intention, I would recommend the following:</p> <pre><code>&lt;?php $string = 'Feugiat &lt;em&gt;hendrerit&lt;/em&gt; sit iriuredolor aliquam.'; $string = ereg_replace("&lt;/?em\\b[^&gt;]*&gt;", "", $string); echo $string; ?&gt; </code></pre> <p><a href="https://stackoverflow.com/questions/375563/why-wont-this-standard-reg-ex-work-in-phps-ereg-function#375568">Greg Hewgill</a> is right about the escaping of backslashes in a PHP string. You need to do it to get a literal backslash into your regex pattern string.</p>
49,151
<p>Is there a way to produce a diagram showing existing tables and their relationships given a connection to a database?</p> <p>This is for SQL Server 2008 Express Edition.</p>
<p>Yes you can use SQL Server 2008 itself but you need to install SQL Server Management Studio Express (if not installed ) . Just right Click on Database Diagrams and create new diagram. Select the exisiting tables and if you have specified the references in your tables properly. You will be able to see the complete diagram of selected tables. For further reference see <a href="http://www.mssqltips.com/sqlservertip/1816/getting-started-with-sql-server-database-diagrams/" rel="noreferrer">Getting started with SQL Server database diagrams</a></p>
<p>MySQL WorkBench is free software and is developed by Oracle, you can import an SQL File or specify a database and it will generate an SQL Diagram which you can move around to make it more visually appealing. It runs on GNU/Linux and Windows and it's free and has a professional look..</p>
20,370
<p>I can't seem to be able to disable ViewState for controls that I add to a page dynamically.</p> <p><strong>ASPX</strong></p> <pre><code>&lt;%@ Page Language="C#" AutoEventWireup="true" CodeFile="Page1.aspx.cs" Inherits="Page1" EnableViewState="false" %&gt; ... &lt;asp:PlaceHolder ID="DropDownPlaceHolder" runat="server" EnableViewState="false" /&gt; &lt;asp:Button ID="Submit" runat="server" OnClick="Submit_OnClick" Text="Click Me!" EnableViewState="false"/&gt; ... </code></pre> <p><strong>ASPX.CS</strong></p> <pre><code>protected override void OnInit(EventArgs e) { DropDownList dropDown = new DropDownList(); TextBox textBox = new TextBox(); textBox.EnableViewState = false; dropDown.Items.Add("Apple"); dropDown.Items.Add("Dell"); dropDown.Items.Add("HP"); dropDown.AutoPostBack = true; dropDown.EnableViewState = false; DropDownPlaceHolder.Controls.Add(dropDown); DropDownPlaceHolder.Controls.Add(textBox); base.OnInit(e); } </code></pre> <p>If I can't disable ViewState on these controls, then I can never programmatically override what a user has entered/selected.</p> <p>I've tried placing this code in OnInit and Page_Load, but the effect is the same in either location -- ViewState is enabled (the DropDownList maintains selected value and TextBox retains text that was entered).</p> <p>So, how can I disable ViewState and keep it from populating these controls?</p> <p>Thanks!</p> <hr> <p>Thanks for your response. Unfortunately, this isn't a workable solution in my situation.</p> <p>I will be dynamically loading controls based upon a configuration file, and some of those controls will load child controls.</p> <p>I need to be able to turn the ViewState of controls off individually, without the need to code logic for loading controls in different places (in OnInit vs. LoadComplete method).</p>
<p>It's a "feature" -- <a href="http://support.microsoft.com/?id=316813" rel="nofollow noreferrer">http://support.microsoft.com/?id=316813</a></p> <p>Thanks, Microsoft!!</p>
<p>I tested this a bit and found it a little odd. It seems the post(back) will send the selected value, even if a control has it's viewstate turned off.</p> <p>I did find a good solution around it though, is that if you handle everything after the init and load, you will reload your control after the viewstate has been processed and it will thus, reset the values.</p> <p>I used the LoadComplete event, example below:</p> <blockquote> <pre><code> Public Sub Page_In(ByVal sender As Object, ByVal e As EventArgs) _ Handles Me.LoadComplete Dim ddl As New DropDownList() ddl.EnableViewState = False ddl.Items.Add("Hello") ddl.Items.Add("Stackoverflow") phTest.Controls.Add(ddl) End Sub </code></pre> </blockquote> <p>Hope this helps.</p>
29,032
<p>I have a JSP that allows users to dynamically create additional form fields to create multiple objects. Perhaps I want to allow users to be able to submit as many line items as they want when submitting an invoice form.</p> <p>How do I create a Struts 2 Action that will be able to take in an <code>ArrayList</code> populated with objects created from those dynamically generated fields.</p>
<p>I've seen this question pop up in a number of different forums over time. The original Blackberries were programmable in C++ but I think that RIM ran up against the problems of trying to implement a secure platform in the C/C++ compile to native paradigm. </p> <p>The devices do have JTAG ports, but unless one could get hands on the RIM code as a place to start the problem is enormous. </p> <p>I also have to wonder how useful a Blackberry with a replacement FOSS operating system would be, since it would not likely have the protocols to connect to BES or BIS, send PIN's etc. If one was simply looking for a the power of the hand held computing platform I suspect there are many more likely candidates available. </p>
<p>Unfortunately the official <a href="http://na.blackberry.com/eng/developers/" rel="nofollow noreferrer">SDK website</a> only seems to mention Java. According to <a href="http://en.wikipedia.org/wiki/BlackBerry#CPU" rel="nofollow noreferrer">wikipedia</a>, different versions of the BlackBerry use different processors. Combined with the fact that RIM uses a proprietary operating system for the devices, it becomes pretty difficult to develop native code without official tools. There is also a partial API-level security restriction which would further prohibit advanced tinkering.</p>
16,271
<p>The following doesn't work, because it doesn't wait until the process is finished:</p> <pre><code>import subprocess p = subprocess.Popen('start /WAIT /B MOZILL~1.LNK', shell=True) p.wait() </code></pre> <p>Any idea how to run a shortcut and wait that the subprocess returns ?</p> <p><strong>Edit:</strong> originally I was trying this without the <strong>shell</strong> option in my post, which caused Popen to fail. In effect, <code>start</code> is not an executable but a shell command. This was fixed thanks to Jim.</p>
<p>You will need to invoke a shell to get the subprocess option to work:</p> <pre><code>p = subprocess.Popen('start /B MOZILL~1.LNK', shell=True) p.wait() </code></pre> <p>This however will still exit immediately (see @R. Bemrose).</p> <p>If <code>p.pid</code> contains the correct pid (I'm not sure on windows), then you could use <a href="http://docs.python.org/library/os.html#os.waitpid" rel="nofollow noreferrer"><code>os.waitpid()</code></a> to wait for the program to exit. Otherwise you may need to use some win32 com magic.</p>
<p>Note: I am simply adding on Jim's reply, with a small trick. What about using 'WAIT' option for start?</p> <pre><code>p = subprocess.Popen('start /B MOZILL~1.LNK /WAIT', shell=True) p.wait() </code></pre> <p>This should work.</p>
45,492
<p><em>[NOTE: This questions is similar to but <strong>not the same</strong> as <a href="https://stackoverflow.com/questions/128634/how-to-use-system-environment-variables-in-vs-2008-post-build-events">this one</a>.]</em></p> <p>Visual Studio defines several dozen "Macros" which are sort of simulated environment variables (completely unrelated to C++ macros) which contain information about the build in progress. Examples:</p> <pre> ConfigurationName Release TargetPath D:\work\foo\win\Release\foo.exe VCInstallDir C:\ProgramFiles\Microsoft Visual Studio 9.0\VC\ </pre> <p>Here is the complete set of 43 built-in Macros that I see (yours may differ depending on which version of VS you use and which tools you have enabled):</p> <pre> ConfigurationName IntDir RootNamespace TargetFileName DevEnvDir OutDir SafeInputName TargetFramework FrameworkDir ParentName SafeParentName TargetName FrameworkSDKDir PlatformName SafeRootNamespace TargetPath FrameworkVersion ProjectDir SolutionDir VCInstallDir FxCopDir ProjectExt SolutionExt VSInstallDir InputDir ProjectFileName SolutionFileName WebDeployPath InputExt ProjectName SolutionName WebDeployRoot InputFileName ProjectPath SolutionPath WindowsSdkDir InputName References TargetDir WindowsSdkDirIA64 InputPath RemoteMachine TargetExt </pre> <p>Of these, only four (<code>FrameworkDir</code>, <code>FrameworkSDKDir</code>, <code>VCInstallDir</code> and <code>VSInstallDir</code>) are set in the environment used for build-events.</p> <p>As Brian mentions, user-defined Macros can be defined such as to be set in the environment in which build tasks execute. My problem is with the built-in Macros.</p> <p>I use a Visual Studio Post-Build Event to run a python script as part of my build process. I'd like to pass the entire set of Macros (built-in and user-defined) to my script in the environment but I don't know how. Within my script I can access regular environment variables (e.g., Path, SystemRoot) but NOT these "Macros". All I can do now is pass them on-by-one as named options which I then process within my script. For example, this is what my Post-Build Event command line looks like:</p> <pre> postbuild.py --t="$(TargetPath)" --c="$(ConfigurationName)" </pre> <p>Besides being a pain in the neck, there is a limit on the size of Post-Build Event command line so I can't pass dozens Macros using this method even if I wanted to because the command line is truncated.</p> <p>Does anyone know if there is a way to pass the entire set of Macro names and values to a command that does NOT require switching to MSBuild (which I believe is not available for native VC++) or some other make-like build tool?</p>
<p>You might want to look into PropertySheets. These are files containing Visual C++ settings, including user macros. The sheets can inherit from other sheets and are attached to VC++ projects using the PropertyManager View in Visual Studio. When you create one of these sheets, there is an interface for creating user macros. When you add a macro using this mechanism, there is a checkbox for setting the user macro as an environment variable. We use this type of mechanism in our build system to rapidly set up projects to perform out-of-place builds. Our various build directories are all defined as user macros. I have not actually verified that the environment variables are set in an external script called from post-build. I tend to use these macros as command line arguments to my post-build scripts - but I would expect accessing them as environment variables should work for you.</p>
<p>This is a bit hacky, but it could work.</p> <p>Why not call multiple .py scripts in a row?</p> <p>Each scripts can pass in a small subset of the parameters, and the values to a temp text file. The final script will read and work off of the temp text file.</p> <p>I agree that this method is filled with danger and WTF's, but sometimes you have to just hack stuff together.</p>
15,859
<p>Is it possible to expose an API in a .NET application by embedding a scripting language like IronPython?</p> <p>How is it done?</p>
<p>IronPython has a hosting API which can be used to execute IronPython scripts from a C#\VB application.</p> <p><a href="http://www.voidspace.org.uk/ironpython/dlr_hosting.shtml" rel="nofollow noreferrer">This</a> is a good example of embedding IronPython inside a winforms app.Note that the hosting APIs have changed since that post. <a href="http://blogs.msdn.com/srivatsn/archive/2008/09/16/hosting-ironpython-made-easier.aspx" rel="nofollow noreferrer">This post</a> shows an example of the latest API</p> <p>You can find the latest specs <a href="http://compilerlab.members.winisp.net/dlr-spec-hosting.pdf" rel="nofollow noreferrer">here</a> [Note: URL throws a 404 as of 2010-09-07]</p>
<p>I haven't used it personally, but you should look at <a href="http://msdn.microsoft.com/en-us/vsx2008/products/bb933739.aspx" rel="nofollow noreferrer">Visual Studio Tools for Applications</a></p> <p>I'm not sure if Iron Python is supported as a language for it or not, but that would be the easiest path to enable your application to be programmable.</p>
25,564
<p>Lucky me, I have to work with Oracle. And packages. </p> <p>I have a package that a lot of different developers are touching and it's scaring me. Is it possible to put a package inside of Version Control? Is there some kind of software out there that already does this? If not, is there some kind of export procedure? Can I just grab a file off of a file system?</p>
<p>How are they inputting it? The way we used to work at my last job is editing a text file, and loading it with SQL*Plus. You can just put that source file under version control. </p> <p>The source must be between "<code>CREATE OR REPLACE PACKAGE MYPACKAGE AS</code>" and "<code>END;</code>" followed by a single slash on a line of its own ("/"); and ditto for "PACKAGE BODY" instead of "PACKAGE".</p> <p>And yes, there's a way to pull the source out of Oracle. It's in a table, line by line, look up <a href="http://www.enterprisedb.com/docs/en/8.3/oracompat/EnterpriseDB_OraCompat_EN_8.3-239.htm" rel="nofollow noreferrer">ALL_SOURCE</a> and USER_SOURCE. You can pull it out with a query like</p> <pre><code>SELECT TEXT FROM ALL_SOURCE WHERE TYPE='PACKAGE BODY' AND NAME='MYPACKAGE' AND OWNER='MYPACKAGEOWNER' ORDER BY LINE </code></pre> <p>(untested as I no longer have access to Oracle) and ditto for the 'PACKAGE'.</p> <p>I think it's best to load it again into Oracle using SQL*Plus; make sure to set "SCAN OFF".</p>
<p>Take also a look at <a href="http://deltasql.sourceforge.net" rel="nofollow">this link</a>. It's a PHP/mySQL versioning tool which works with any database type and is fairly simple to learn.</p>
36,563
<p>My company has login integration with GroupWise, and Exchange 5.5/2000+. The Exchange 5.5/GroupWise logic is done using wldap32.dll (win32), and so the login code is in a managed c++ class. When the configuration tool (or the backend service) tries to load the dll built off this managed c++ project on my XP development box, it works fine. On QA/Customer Windows 2003 boxes, a FileLoadException is thrown.</p> <p>First off, this used to work fine. Secondly, I've validated the same working code on my box fails on the qa box. </p> <p>How can I track down the cause of this exception?</p>
<p>Have you changed your development environment recently? In particular have you installed a service pack or new release of Visual Studio?</p> <p>It appears you are linking against a C++ runtime that is not available on the client's server. You can use the Windows Event Viewer to identify the DLL failing to load, or if this shows nothing, use <code>depends.exe</code> to see what runtime DLLs are dependencies for your managed code.</p> <p>Microsoft has moved to using side-by-side installation to handle "DLL hell", basically this allows multiple versions of a DLL to be installed (side-by-side) concurrently on a Windows installations and have applications load the correct version of the DLL at run-time. Recent releases of Visual Studio make use of this technology so I suspect this is the cause of your 'sudden' incompatibility.</p>
<p>Not to answer my own question, but support just updated the bug with the text following this paragraph. I'm still interested in thoughts on tracking down situations like this.</p> <p>Resolved by downloading and installing the Visual C++ 2008 Redistributable Package for Windows on the IMS: <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=a5c84275-3b97-4ab7-a40d-3802b2af5fc2&amp;DisplayLang=en" rel="nofollow noreferrer">http://www.microsoft.com/downloads/details.aspx?FamilyID=a5c84275-3b97-4ab7-a40d-3802b2af5fc2&amp;DisplayLang=en</a></p>
22,425
<p>I designed a data model which is represented by an XSD scheme. The data model also provides the types that are being used as web service parameters in a WSDL descriptor.</p> <p>I would like to send the XSD scheme around and ask the people involved to peer review the data model.</p> <p>What tool or presentation method would you suggest to be used as a basis for peer reviews? The data model should be readable for non-skilled people, at least when it comes to the semantic meanings of the parameters</p> <p><strong>Edit:</strong></p> <p>To be more specific: Of course, syntactically, the scheme validates. Actually I'm already working on code which is based on JAXB generated classes. My goal is </p> <ol> <li>to freeze the data model and thus the input parameters </li> <li>to make sure nothing got lost or forgotten from a semantic (in the meaning of business-relevant) point of view.</li> </ol> <p><strong>Edit 2</strong></p> <p>I've been thinking about how it probably would be best to spread a datamodel around. I'm thinking of something like a JavaDoc for XSD schemas. Anyone knows if something like that exists? Basically it would be done with a set of XSLTs, right?</p>
<p>I know the following tools that generate documentation from XML Schema files (XSD):</p> <ul> <li><a href="http://xml.fiforms.org/xs3p" rel="noreferrer">xs3p </a> <ul> <li>XSLT stylesheet that generates single XHTML from XSD</li> </ul></li> <li><a href="http://xframe.sourceforge.net/xsddoc/index.html" rel="noreferrer">xsddoc </a> <ul> <li>free / LGPL </li> <li>mainly XSLT based</li> <li>JavaDoc like output</li> <li>see <a href="http://xframe.sourceforge.net/xsddoc/examples.html" rel="noreferrer">xsddoc examples</a></li> </ul></li> <li><a href="http://www.buldocs.com/xnsdoc/index.html" rel="noreferrer">xnsdoc</a> <ul> <li>improved commercial version of xsddoc</li> <li>free for personal/educational use</li> <li>JavaDoc like output</li> </ul></li> <li><a href="http://www.bluetetra.com/xsddoc" rel="noreferrer">XSDdoc 2.0</a> <ul> <li>commercial</li> <li>JavaDoc like output</li> </ul></li> </ul> <p>For small a XML schema, I would probably suggest using the <em>xs3p</em> XSLT stylesheet. For more a complex schema, I suggest using <a href="http://xframe.sourceforge.net/xsddoc/index.html" rel="noreferrer">xsddoc</a>.</p>
<p>I recommend <em>using</em> the XSD for something. Specifically, show some actual applications, with examples as real code.</p> <p>Actual applications are what make a schema interesting. The examples don't have to be big, sophisticated or completely realistic. They just have to compile. Other people will want to copy and paste the code samples.</p> <p>These examples are the "hello world" of the schema. And they act as a kind of unit test for the schema.</p>
24,691