instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I'm filtering the messages that come to a form with PreFilterMessage like this:</p> <p><code>print("code sample");</code></p> <pre><code> public bool PreFilterMessage(ref Message m) { if (m.Msg == WM_KEYDOWN &amp;&amp; (int)m.WParam == VK_ESCAPE) { this.Close(); return true; } return false; } </code></pre> <p><code>print("code sample");</code></p> <p>but the matter is that form closes only for the first time. After reopening a form it won't close anymore by pressing ESC.</p> <p>How can I accomplish this?</p> <p>Thanks</p>
<p>I don't know if this fits with what you are doing. I usually set Form.CancelButton to the close or cancel button on my form, and it will automatically call the button OnClick when the user hits Esc on the keyboard.</p>
<p>According to MSDN</p> <blockquote> <p>The two conditions when a form is not disposed on Close is when (1) it is part of a multiple-document interface (MDI) application, and the form is not visible; and (2) you have displayed the form using ShowDialog. In these cases, you will need to call Dispose manually to mark all of the form's controls for garbage collection. </p> </blockquote> <p>If you Indeed shown you form using <code>ShowDialog()</code>, then calling <code>Close()</code> doesn't dispose off your form. You could still be able to "reopen" it later, and probably taht's what you're doing. I'm suspecting that you might have distrupted <code>PreFilterMessage()</code> when you first close it. Have you check if the message loop is still working? Or you should actually do <code>this.Visible = false;</code> or <code>Control.Hide</code>, </p> <blockquote> <p>When the Close method is called on a Form displayed as a modeless window, you cannot call the Show method to make the form visible, because the form's resources have already been released. To hide a form and then make it visible, use the Control..::.Hide method.</p> </blockquote> <p>since you need to "reopen" it later. If you are actually expecting the form dispose off, and show a new instance later, then manually call dispose on it, after closing</p>
27,879
<p>When presenting preformatted text on the web (e.g. code samples), line wrapping can be a problem. You want to wrap for readability without scrolling, but also need it to be unambiguous to the user that it is all one line with no line break.</p> <p>For example, you may have a really long command line to display, like this:</p> <pre><code>c:\Program Files\My Application\Module\bin\..&gt; Some_really_long_command line "with parameters" "that just go on and on" " that should all be typed on one line" "but need to be wrapped for display and I'd like the text style to indicate that it has wrapped" </code></pre> <p>(Stackoverflow forces a line like this not to wrap.)</p> <p>Is there a way of styling with CSS to give the same treatment as you see in books? i.e. to wrap the line, but include an image or glyph that indicates a line continuation. </p> <p>Obviously I am looking for a style that can be applied to all text, and let the browser's XHTML/CSS rendering engine figure out which lines have wrapped and therefore need the special treatment.</p> <h1>The Solution so far..</h1> <h2>Adding line continuation glyphs</h2> <p>Thanks to Jack Ryan and Maarten Sander, have a reasonably workable solution to add continuation glyphs to either the left or right of wrapped lines. It requires an image with repeating glyphs in the vertical, which is offset so that it is invisible if only one unwrapped line. The main requirement of this technique is that every line needs to be within a block (e.g. p, span or div). This means it cannot easily be used manually with existing text that is just sitting in a pre block.</p> <p>The fragment below summarises the essential technique. I posted a live example <a href="http://blog.tardate.com/2008/12/code-formatting-and-line-continuations.html" rel="nofollow noreferrer">here</a>.</p> <pre><code>.wrap-cont-l { margin-left: 24px; margin-bottom: 14px; width: 400px; } .wrap-cont-l p { font-family: Courier New, Monospace; font-size: 12px; line-height: 14px; background: url(wrap-cont-l.png) no-repeat 0 14px; /* move the background down so it starts on line 2 */ text-indent: -21px; padding-left: 14px; margin: 0 0 2px 7px; } .wrap-cont-r { margin-left: 24px; margin-bottom: 14px; width: 400px; } .wrap-cont-r p { font-family: Courier New, Monospace; font-size: 12px; line-height: 14px; background: url(wrap-cont-r.png) no-repeat right 14px; /* move the background down so it starts on line 2 */ text-indent: -28px; margin: 0 0 2px 28px; padding-right: 14px; } </code></pre> <p>To be used like this:</p> <pre><code>&lt;div class="wrap-cont-l"&gt; &lt;p&gt;take a long line&lt;/p&gt; &lt;p&gt;take a long line&lt;/p&gt; &lt;/div&gt; &lt;div class="wrap-cont-r"&gt; &lt;p&gt;take a long line&lt;/p&gt; &lt;p&gt;reel him in&lt;/p&gt; &lt;/div&gt; </code></pre> <h2>But wait, there's more!</h2> <p>I recently discovered <a href="http://code.google.com/p/syntaxhighlighter" rel="nofollow noreferrer">syntaxhighlighter</a> by Alex Gorbatchev. It is a fantastic tool for dynamically and automatically formatting text blocks. It is principally intended for syntax highlighting code, but could be used for any text. In v1.5.1 however, it does not wrap lines (in fact it forces them not to wrap).</p> <p>I did a little hacking around though, and was able to add a simple line wrap option syntaxhighlighter and also incorporate the continuation glyph idea. </p> <p>I've added this to the <a href="http://blog.tardate.com/2008/12/code-formatting-and-line-continuations.html" rel="nofollow noreferrer">live examples</a> and included a few notes on the hacks required (they are trivial). So with this as the text in the page:</p> <pre><code>&lt;textarea name="code" class="java:wraplines" cols="60" rows="10"&gt; public class HelloWorld { public static void main (String[] args) { System.out.println("Hello World! But that's not all I have to say. This line is going to go on for a very long time and I'd like to see it wrapped in the display. Note that the line styling clearly indicates a continuation."); } } &lt;/textarea&gt; </code></pre> <p>This is a snapshot of the formatted result:</p> <p><a href="http://tardate.com/syntaxhighlighter/line-continuation-example.jpg" rel="nofollow noreferrer">screenshot http://tardate.com/syntaxhighlighter/line-continuation-example.jpg</a></p>
<p>Here is one (unpleasant) way of doing this. It requires a number of bad practices. But SO is about solutions to real problems so here we go...</p> <p>First each line needs to be wrapped in some sort of containing block. Span or p are probably the most appropriate.</p> <p>Then the style of the containing block needs to have line height set. and a background image that contains a number of newLine glyphs at the start of every line except the first one. As this is code it would be resonable to expect it to not wrap more than 5 times. So repeating 5 times is probably enoygh.</p> <p>This can then be set as the background image, and should display at the beginning of every line except the first one. I guess the resulting CSS might look like this:</p> <pre><code>p.codeLine { font-size: 12px; line-height: 12px; font-family: Monospace; background: transparent url(lineGlyph) no-repeat 0 12px; /* move the background down so it starts on line 2 */ padding-left: 6px; /* move the text over so we can see the newline glyph*/ } </code></pre>
<p>This cannot be done with CSS. Sorry. :(</p>
42,782
<p>Every morning, after logging into your machine, you do a variety of routine stuffs. The list can include stuffs like opening/checking your email clients, rss readers, launching visual studio, running some business apps, typing some replies, getting latest version from Source Control, compiling, connecting to a different domain etc. To a big extend, we can automate using scripting solutions like <a href="http://www.autoitscript.com/autoit3/" rel="nofollow noreferrer">AutoIt</a>, nightly jobs etc. </p> <p>I would love to hear from you geeks out there for the list of stuffs you found doing repeatedly and how you solved it by automating it. Any cool tips?</p>
<p>A favorite way is to leave the computer on at night or better, if it's a laptop, put it to sleep. Running a web browsing virtual machine in VMware or similar works also, you can set the VM start along with the machine and save its state on shutdown, so your web pages and email client stay open. This works for development also if you're doing scripting or something similar where the performance hit of the VM on large compiles won't negate the benefits.</p>
<p><strong><a href="http://www.bayden.com/SlickRun/" rel="nofollow noreferrer">SlickRun</a></strong> is very handy for this, just a few keys to navigate to anything common and a very small footprint. With input variables and file path recognition all part of it I can quick remote desktop to any machine, search anything, pull up whatever's needed.</p>
13,691
<p>I am looking for information about providing a license, or "terms of use", for a web application. The <a href="http://en.wikipedia.org/wiki/Terms_of_Use" rel="nofollow noreferrer">Wikipedia article</a> is very limited, and it seems that unlike "downloadable" software (or perhaps "installable" software, for lack of a better term), for which there is <a href="http://en.wikipedia.org/wiki/Software_license" rel="nofollow noreferrer">much more information</a>, not so much has been written specifically for the licensing of web applications.</p> <p>Would you say that hiring a lawyer to construct a legally sound "terms of use", or disclaimer, for your web application is absolutely necessary?</p> <p>Someone asked: Which jurisdiction? My response here is: World-wide. I guess this opens up another topic, i.e. what jurisdictional limits you should take into consideration.</p>
<p>Hire a lawyer. Undesirable (and costly) as it seems, it can cost you a helluva lot more to get your TOS wrong.</p>
<p>What are you hoping to cover? Are you worried about your code being stolen or someone doing something stupid on the back of something they see on your site? (Or something else entirely.) </p> <p>Could you edit to widen what you hope your disclaimer or terms would hope to cover? </p> <p>Hiring a lawyer might well turn out to be the soundest advice, but the wrong lawyer being asked the wrong questions could end in disaster ... </p>
49,876
<p>I've just received my Ender 3v2 and tried multiple SD cards, all have been formatted to FAT32 with no luck. Under the Print selection, all I get is the back button. I looked and I have the V4.2.2 and the firmware is up to date, Showing 1.0.2 unless this is not right and this is why I'm having this issue. Even when plugging directly into the computer, nothing is showing up.</p>
<p>Abd to follow along with J Boughtons advice, I've noticed if the word &quot;end&quot; is in the first file, it won't read any of the files.</p>
<p>I have the same issue but whilst none of these worked for me they have worked for other people:</p> <ul> <li>Make sure the name of the G-code file begins with a letter or number</li> <li>Make sure the G-code is not in a subfolder</li> <li>Make sure the name of the G-code file is less than or equal to 8 characters long</li> </ul> <p>After I attempted all of these, reinserting the SD card multiple times worked but I don't know what fixed it or if it was just I had been putting it in wrong though I didn't try anything different.</p>
1,906
<p>I know how to use tags in subversion. I create a tag every time I get to a release milestone.</p> <p>What I don't quite understand is how they work. </p> <p>Is a tag just a copy, made from what ever revision I specify? Or is a tag more like a reference, where internally subversion just says <code>GO TO /trunk/project/ Revision 5</code> or whatever.</p> <p>The command to create a tag (<code>svn copy</code>) seems to imply that it's a copy, but I've seen other people write that subversion doesn't really copy anything.</p> <p>Say I dump just the HEAD revision of a repository. I don't care about any history except the tags. Are those tags dumped along with the rest of the Head revision?</p> <p>Finally, is all this just programming magic that I don't really want to know.</p>
<p>Yes, a svn copy (whether you are thinking of it as a tag, a branch, or copying a file in trunk) is all the same. SVN will internally create a pointer to the source location at that revision. If you then make changes to the copy (which you are likely to do if it is a branch or a copied file in trunk, but shouldn't do for tags), SVN will only store what was changed, rather than creating a whole new copy.</p>
<p>an example:</p> <pre><code>$ svn copy https://jorgesysgr.com/svn/AndNews/branches \ https://jorgesysgr.com/svn/AndNews/tags/release-1.1 \ -m "release 1.1 Android News." </code></pre> <p>More info:: <a href="http://svnbook.red-bean.com/nightly/en/svn.branchmerge.tags.html" rel="nofollow">Creating a Simple Tag</a></p>
6,116
<p>We have a (non-web app) Spring application that throws a NoSuchBeanDefinitionException when running tests on our CruiseControl continuous integration linux box. The test runs fine on Windows in Eclipse.</p> <p>The exception is thrown on the getBean() method:</p> <pre><code>ApplicationContext context = new ClassPathXmlApplicationContext(CONTEXT_FILE); MyBean bean = (MyBean)context.getBean("myBean"); </code></pre> <p>The context file is rather large and complicated. The context file is in the classpath and Spring is finding it. I'd prefer it if Spring would throw an exception when trying to load the context file and build the dependencies so that we could have an idea as to where to start. Is there a way to force Spring to throw an exception at the time of creating the context?</p>
<p>Solved. The instantiation of "myBean" in CONTEXT_FILE occurred after another bean that depended on it. This really should not be an issue, but I suspect that the parser on the Linux box must be stricter. Anyway, changing the order of definitions made it work on both Windows and Linux.</p>
<p>I had the same problem. It turned out that it was a subtle classpath issue. Specifically - my classpath on linux was set up so that my config directory containing my build.xml file came after my x-jars (external jars) directory - and some other beans.xml was being picked up from my x-jars which, as the log message correctly said, did not contain the required bean. It would have helped if the full path to the beans.xml file had been loggged with the Spring error message.</p>
49,166
<p>I'm building a shared library with g++ 3.3.4. I cannot link to the library because I am getting </p> <pre><code>./BcdFile.RHEL70.so: undefined symbol: _ZNSt8_Rb_treeIjjSt9_IdentityIjESt4lessIjESaIjEE13insert_uniqueERKj </code></pre> <p>Which c++filt describes as </p> <pre><code>std::_Rb_tree&lt;unsigned int, unsigned int, std::_Identity&lt;unsigned int&gt;, std::less&lt;unsigned int&gt;, std::allocator&lt;unsigned int&gt; &gt;::insert_unique(unsigned int const&amp;) </code></pre> <p>I thought this might have come from using hash_map, but I've taken that all out and switched to regular std::map. I am using g++ to do the linking, which is including <code>-lstdc++</code>.</p> <p>Does anyone know what class would be instantiating this template? Or even better, which library I need to be linking to?</p> <p><em>EDIT:</em> After further review, it appears adding the -frepo flag when compiling has caused this, unfortunately that flag is working around gcc3.3 bug.</p>
<p><code>std::_Rb_Tree</code> might be a red-black tree, which would most likely be from using <code>map</code>. It should be part of <code>libstdc++</code>, unless your library is linking against a different version of <code>libstdc++</code> than the application, which from what you've said so far seems unlikely.</p> <p>EDIT: Just to clarify, the red-black tree is the underlying data structure in <code>map</code>. All that <code>hash_map</code> does is hash the key before using it, rather than using the raw value.</p>
<p>Try <pre><code>#include &lt; map > </code></pre> in the source file where you are using map.</p>
17,158
<p>I'm currently using Subversion to manage my ASP.NET website. I'm finding that whenever I go to upload my website to my server, I'm copying a large number of hidden .svn folders and whatever contents may lie within them.</p> <p>Does anyone have any suggestions for avoiding this? I don't particularly want those hidden .svn folders on the production server, but short of manually deleting each .svn folder before I upload my website, I'm at a loss for how to have a .svn-folder-free production environment.</p> <hr> <p>Edit: Thank you everyone, those are great suggestions, I really appreciate it!</p>
<p>How about you run Subversion on the server and then do an svn export from the repository? svn export is like a checkout, but w/o the .svn folders (and w/o the ability to do Subversion work in that directory).</p> <p>Alternately, do a svn export of the repo on your local machine and then FTP up the exported version.</p>
<p>two suggestions:</p> <ul> <li>Use <a href="http://en.wikipedia.org/wiki/Robocopy" rel="nofollow noreferrer">robocopy</a> or xcopy to filter out the <code>.svn</code> folders</li> <li><code>svn export</code> the repository to the webserver (<a href="http://svnbook.red-bean.com/en/1.0/re10.html" rel="nofollow noreferrer">docs</a>). Exporting will not write any <code>.svn</code> folders</li> </ul> <p>see also: <a href="https://stackoverflow.com/questions/222188/tortoise-svn-hidden-svn-folders">Tortoise SVN hidden SVN folders</a></p>
27,725
<p>When I run a particular SQL script in Unix environments, I see a '^M' character at the end of each line of the SQL script as it is echoed to the command line.<br /> I don't know on which OS the SQL script was initially created.</p> <p>What is causing this and how do I fix it?</p>
<p>It's caused by the DOS/Windows line-ending characters. Like Andy Whitfield said, the Unix command dos2unix will help fix the problem. If you want more information, you can read the man pages for that command.</p>
<p>Another vi command that'll do: <code>:%s/.$//</code> This removes the last character of each line in the file. The drawback to this search and replace command is that it doesn't care what the last character is, so be careful not to call it twice.</p>
9,033
<p>I'm having a small problem in Java. I have an interface called Modifiable. Objects implementing this interface are Modifiable.</p> <p>I also have a ModifyCommand class (with the Command pattern) that receive two Modifiable objects (to swap them in a list further on - that's not my question, I designed that solution already).</p> <p>The ModifyCommand class starts by making clones of the Modifiable objects. Logically, I made my Modifiable interface extends Cloneable. The interface then defines a clone() method that its implementing classes must redefine.</p> <p>Then, in ModifyCommand, I can do : firstModifiableObject.clone(). My logic is that classes implementing Modifiable will have to redefine the clone method from Object, as they will be Cloneable (that's what I want to do).</p> <p>The thing is, when I define classes implements Modifiable and I want to override clone(), it won't let me, stating that the clone() method from the Object class hides the one from Modifiable.</p> <p>What should I do? I'm under the impression that "I'm doing it wrong"...</p> <p>Thanks,</p> <p>Guillaume.</p> <p>Edit : it think I will forget the clone() thing. I will either a) assume that the object passed to the Modifiable object (implementing the interface) is already cloned or b) make another method called, for example, copy(), that would basically do a deep-copy of the Modifiable object (or maybe the Generic solution will work...).</p>
<p>If you're using java 1.5 or higher, you can get the behavior you want and remove casting this way:</p> <pre><code>public interface Modifiable&lt;T extends Modifiable&lt;T&gt;&gt; extends Cloneable { T clone(); } public class Foo implements Modifiable&lt;Foo&gt; { public Foo clone() { //this is required return null; //todo: real work } } </code></pre> <p>Since Foo extends Object, this still satisfies the original contract of the Object class. Code that doesn't refine the clone() method correctly will not compile, because of the additional constraints imposed by the Modifiable interface. As a bonus, calling code doesn't have to cast the result of the clone method.</p>
<p>Did you define the signature exactly as it is in object?</p> <pre><code>public Object clone() throws CloneNotSupportedException { return super.clone(); } </code></pre> <p>This should compile - add custom code to the body. <a href="http://en.wikipedia.org/wiki/Clone_(Java_method)" rel="nofollow noreferrer">Wikipedia</a> was surprisingly helpful on this one.</p>
29,801
<p>I have a Simulink xPC target application that has blocks with discrete states at several different sample rates and some sections using continuous states. My intention on keeping the continuous states is for better numerical integration. </p> <p>What creates the problem: One block is reading a device at a very fast rate (500 hz). The rest of the application can and should run at a slower rate (say, 25 or 50 Hz) because it would be overkill to run it at the highest rate, and because the processor simply cannot squeeze a full application cycle into the .002 secs of the faster rate. So I need both rates. However, the continuous states run by definition in Simulink at the faster discrete rate of the whole application! This means everywhere I have continuous states now they're forced to run at 500 Hz when 25 Hz would do!</p> <p>Is there a way to force the continuous states in xPC target to a rate that is not the fastest in the application? Or alternatively, is there a way to allow certain block to run at a faster speed than the rest of the application?</p>
<p>You are thinking about continuous solvers in the wrong way - continuous doesn't only mean that it's run as fast as possible - it uses a fundamentally different algorithm to solve the equations than discrete. Due to this, they must be run at least as fast as the discrete solvers.</p> <p>From <a href="http://www.ece.northwestern.edu/IT/local-apps/matlabhelp/toolbox/simulink/ug/how_simulink_works13.html" rel="nofollow noreferrer">Using Simulink</a>:</p> <blockquote> <p>Continuous solvers use numerical integration to compute a model's continuous states at the current time step from the states at previous time steps and the state derivatives. Continuous solvers rely on the model's blocks to compute the values of the model's discrete states at each time step.</p> <p>Mathematicians have developed a wide variety of numerical integration techniques for solving the ordinary differential equations (ODEs) that represent the continuous states of dynamic systems. Simulink provides an extensive set of fixed-step and variable-step continuous solvers, each implementing a specific ODE solution method (see Solvers).</p> <p>Discrete solvers exist primarily to solve purely discrete models. They compute the next simulation time step for a model and nothing else. They do not compute continuous states and they rely on the model's blocks to update the model's discrete states.</p> </blockquote> <p>So the upshot is that <em>no</em> it's not good enough to have the continuous run more slowly than the fastest discrete solvers - otherwise they are, by definition, not continuous. You should reconsider why you are specifying them as continuous.</p> <p>What are you trying to accomplish by slowing down the continuous solvers? Is this a simulation time/performance issue?</p> <p>-Adam</p>
<p>My take on this is that it cannot be done. One way to approach this is to replace the continuous states by discrete ones (perhaps at an intermediate rate, say 100 Hz), and cross my fingers that the loss of precision is bearable.</p> <p>Maybe it's possible to isolate a block and run it separately at a faster rate somehow, but I don't know.</p>
6,482
<p>I would like to make two database operation in one transaction. Those two operations are</p> <ol> <li>Do one insert operation.</li> <li>Create one user (using membership - sql membership provider)</li> </ol> <p>I tried <strong>TransactionScope</strong> but it went to distributed transaction at that line: -- Membership.CreateUser("test", "password", "test@test.com");</p> <p>How can I do this with lightweight transaction since I have only DB?</p> <p>Thanks in advance.</p>
<p>The current implementation of TransactionScope will only use a lightweight transaction if you use a single database connection. So it is not possible to achieve this in your scenario.</p>
<p>I was looking for this topic and I think I have found an answer. It only applies to SQLServer 2008. It does not require changes to System.Transactions namespace or our Application code. It's interesting. ;)</p> <p><a href="http://blogs.msdn.com/b/adonet/archive/2008/03/26/extending-lightweight-transactions-in-sqlclient.aspx" rel="nofollow">http://blogs.msdn.com/b/adonet/archive/2008/03/26/extending-lightweight-transactions-in-sqlclient.aspx</a></p> <p>Hope this helps!</p>
39,162
<p>My ASP.NET MVC application will take a lot of bandwidth and storage space. How can I setup an ASP.NET upload page so the file the user uploaded will go straight to Amazon S3 without using my web server's storage and bandwidth?</p>
<p>Update Feb 2016:</p> <p>The AWS SDK can handle a lot more of this now. Check out <a href="http://docs.aws.amazon.com/AmazonS3/latest/dev/HTTPPOSTForms.html" rel="nofollow noreferrer">how to build the form</a>, and <a href="http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-authentication-HTTPPOST.html" rel="nofollow noreferrer">how to build the signature</a>. That should prevent you from needing the bandwidth on your end, assuming you need to do no processing of the content yourself before sending it to S3.</p>
<p><a href="http://www.codeplex.com/ThreeSharp" rel="nofollow noreferrer">ThreeSharp</a> is a library to facilitate interactions with Amazon S3 in a .NET environment.</p> <p>You'll still need to host the logic to upload and send files to s3 in your mvc app, but you won't need to persist them on your server.</p>
14,342
<p>I have a generic list of objects in C#, for example sake, here's what the object might be.</p> <pre><code>public class Thing { public string Name { get; set; } public DateTime EditDate { get; set; } } var things = new List&lt;Thing&gt;(); </code></pre> <p>Now I want to call:</p> <pre><code>thing.Sort((t1, t2) =&gt; t1.EditDate.CompareTo(t2.EditDate)); </code></pre> <p>However, some of my EditDate properties are null. I want these objects with a null EditDate property to show up at the top of my list (i.e. closer to the zero index). How can I do this?</p>
<p>You can create a somewhat more complex lambda, such as:</p> <pre><code>things.Sort((t1, t2) =&gt; { if (t1 == null) { return (t2 == null) ? 0 : -1; } if (t2 == null) { return 1; } return t1.EditDate.CompareTo(t2.EditDate); }); </code></pre> <p><code>EndDate</code> cannot be <code>null</code> as it is a value type. However, if you had a specific value of <code>EndDate</code> that you consider as <code>null</code>, you could modify the above code to take that into account in a similar fashion to how I've coped with <code>t1</code> or <code>t2</code> being <code>null</code>.</p>
<p>List has a <a href="http://msdn.microsoft.com/en-us/library/w56d4y5z.aspx" rel="nofollow noreferrer">sort function</a> that takes a delegate.</p> <p>Now that I've read the question </p> <pre><code>TheList.Sort(int delegate(Type a, Type b) { if (a.memeber == null) return -1; if (b.memeber == null) return 1; if (a.memeber&lt;b.memeber) return -1; if (b.memeber&lt;a.memeber) return 1; return 0; } </code></pre>
41,097
<p>I have two unix partitions under debian which I would like to merge (disk space problems :/). What would be the easiest way to do it? I think it would be best to tar or copy files from one partition to the other, delete one and resize the other. I will use parted to resize but how should I copy the files? There are links, permissions and devices which need to be moved without change.</p>
<p>You could run the following (as root) to copy the files. It works for symlinks, devices and ordinary files.</p> <pre><code>cd /partition2 tar cf - . | ( cd /partition1 &amp;&amp; tar xf - ) </code></pre> <p>Another way is to use cpio, but I never remember the correct syntax.</p>
<p>You can also use SquashFS to create a mirror of the partition and copy that over. After resizing your 2nd partition, mount the SquashFS image and copy over the necessary files. Keep in mind that your kernel will need SquashFS support to mount the image.</p> <ul> <li><a href="http://squashfs.sourceforge.net/" rel="nofollow noreferrer">SquashFS</a></li> </ul>
46,340
<p>Is it possible to use Flex 3 component/code inside Flash (cs4) SWF file ?</p> <p>I know its possible in the opposite direction.</p>
<p>With my minimal testing <strong>it seems you can't use Flex components when building a "pure AS3" project.</strong> (Can we start calling it PAS3 or something? Like "passé". Or "pastry". :)</p> <p>I did this admittedly limited testing by creating a test project with one AS class as the "document class", which would instantiate and addChild one mx.controls.Button. I copied the whole mx package from the path mentioned by <a href="https://stackoverflow.com/users/4111/hasseg">hasseg</a> into the project source path. </p> <p>This is what I found out:</p> <ol> <li>By removing the use of mx_internal from a certain Version.as file, I got Flash IDE to compile my test project without warning. Nothing showed up on the stage though.</li> <li>Using Flex Builder (and the flex compiler, obviously) I also managed to compile the project without errors. I put breakpoints in the code and watched it build itself in the debugger. The components were instantiated flawlessly, but still nothing showed up on the stage. This swf also crashed the browser numerous times.</li> </ol>
<p>In general you need to use MXML to initialise the Flex framework and use Flex components. </p> <p>Mike Chambers from Adobe says:</p> <blockquote>There is not support for using the Flex Framework in an AS only project. While it is theoretically possible, you would have to manually bootstrap a lot of the application initialization code that Flex handles (something which would be rather complex). - <a href="http://www.mail-archive.com/flashcoders@chattyfig.figleaf.com/msg17761.html" rel="nofollow">Source</a></blockquote> <p>To see how complex, you can tell the compiler to keep the intermediate AS3 files that it generates from the MXML. Open your AS3 project properties and set <code>-keep-generated-actionscript</code> as an argument to the compiler. Compile your project then look in the obj/generated folder. Using Flex 4, I get 13 small files the main of which extends <code>spark.components.Application</code> and overrides a few methods.</p> <p>So it's possible but you probably wouldn't want to do it. Flex is meant to make your life easier, not harder.</p>
44,701
<p>I have an embedded flash that is transparent so it looks like part of the background. I achieved that by setting wmode to transparent.</p> <p>My problem is that the area underneath the flash becomes inaccessible, even though the flash is transparent. Therefore I cannot click on any links or buttons that are under the flash object.</p> <p>How do I make the flash unobtrusive?</p> <p>Clarifications: <br> - the flash is transparent but it has an animation that shows in the background.<br> - wmode set to transparent lets you click the contents underneath in IE but not Firefox.</p>
<p>The problem is that in your document, the <code>object</code>/<code>embed</code> that contains the Flash animation is on top of the elements you need to access. You need to put these elements on top of the Flash animation instead of the other way around.</p> <p>The way to do this is to set the object's <code>wmode</code> to opaque, and use the CSS <code>z-index</code> property to set it to a <code>z-index</code> lower than the <code>z-index</code> of whatever elements you want to float over it -- you can do this in CSS or just with inline <code>style=""</code> attributes.</p> <p>Here's <a href="http://www.pipwerks.com/lab/swfobject/z-index/2.0/index.html" rel="nofollow noreferrer">an example using SWFObject</a> to create the <code>object</code>/<code>embed</code> tags, but the same principle applies if you are just hardcoding these into your HTML.</p>
<p>What is the purpose of the Flash? If it doesn't do anything visible, then you can make it 1 pixel in size and/or put it in a div that is absolutely positioned off the screen.</p>
29,984
<p>In IIS7 for Vista, you can select your machine and it gives you several options in which you can use to configure your system. Where is this file stored at? It seems like there's a big master.config file which stores all my settings like the "Connection Strings" which are inherited by the webpages. </p> <p>Supposedly it's some file named machine.config but nothing I change in the IIS manager for my machine changes there. </p>
<p>If you're talking about machine-wide ASP.NET configuration, look under your .NET framework config directory, e.g. <code>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG</code> - check web.config and machine.config for the settings you've been configuring.</p> <p>(Note: this is a bit of an educated guess. Don't take it as definitely correct without checking. Unfortunately I can't do so myself at the moment...)</p>
<p>"Connection Strings" do seem to be in the <a href="http://chiragrdarji.wordpress.com/2008/08/11/how-to-encrypt-connection-string-in-webconfig/" rel="nofollow noreferrer">web.config file</a></p> <p>There can be multiple web.config files in a single web project (but not in a single directory), but here, you are referring to the <a href="http://chiragrdarji.wordpress.com/2008/08/11/how-to-encrypt-connection-string-in-webconfig/" rel="nofollow noreferrer">configuration system files</a>, including:</p> <ul> <li><code>windows\microsoft.net\framework\v2.0.50727\config\machine.config</code>: Holds the global defaults for the .NET framework settings, including some of the ASP.NET ones </li> <li><strong>root <code>web.config</code></strong>: same location, with the rest of the settings.</li> </ul>
46,766
<p>I'm trying to learn RegEx in Ruby, based on what I'm reading in "<em>The Rails Way</em>". But, even this simple example has me stumped. I can't tell if it is a typo or not:</p> <pre><code>text.gsub(/\s/, "-").gsub([^\W-], '').downcase </code></pre> <p>It seems to me that this would replace all spaces with <code>-</code>, then anywhere a string starts with a non letter or number followed by a dash, replace that with ''. But, using irb, it fails first on <code>^</code>:</p> <blockquote> <p>syntax error, unexpected '^', expecting ']'</p> </blockquote> <p>If I take out the <code>^</code>, it fails again on the W.</p>
<pre><code>&gt;&gt; text = "I love spaces" =&gt; "I love spaces" &gt;&gt; text.gsub(/\s/, "-").gsub(/[^\W-]/, '').downcase =&gt; "--" </code></pre> <p>Missing //</p> <p>Although this makes a little more sense :-)</p> <pre><code>&gt;&gt; text.gsub(/\s/, "-").gsub(/([^\W-])/, '\1').downcase =&gt; "i-love-spaces" </code></pre> <p>And this is probably what is meant</p> <pre><code>&gt;&gt; text.gsub(/\s/, "-").gsub(/[^\w-]/, '').downcase =&gt; "i-love-spaces" </code></pre> <p>\W means "not a word" \w means "a word"</p> <p>The // generate a regexp object</p> <blockquote> <blockquote> <p>/[^\W-]/.class => Regexp</p> </blockquote> </blockquote>
<p>The slashes are to say that the thing between them is a regular expression, much like quotes say the thing between them is a string.</p>
16,805
<p>Has anybody tried any Unit Test generators for .Net?</p> <p>I assume although it won't be any substitute for any good unit test written by a person who has written the functionality, but I think it will take away some of work and be a starting point on which we can better the unit tests. </p> <p>Thanks.</p>
<p>Unit test generation is the wrong way to perform unit testing. The proper way to do unit testing is to create test cases before you write functional code, then develop your code until the tests validate, this is know as TDD (Test Driven Development).</p> <p>One of the key reasons unit test generation is a bad idea is because if there are any bugs in your existing code, the tests will be generated against those bugs, therefore if you fix them in the future, the bad tests will fail and you'll assume something is broken, when it's actually been fixed.</p> <p>But since the code is written, it's now water under the bridge. And possible buggy unit tests are better than no unit tests at all. I've always preferred NUnit and there's a NUnit compatible test generator <a href="http://www.kellermansoftware.com/p-30-nunit-test-generator.aspx" rel="noreferrer">here</a> (very affordable).</p>
<p>I created ErrorUnit an unit test generator for .Net</p> <p>Using a generator for TDD development is certainly practical; for instance in coding what happens on a button click, a way to use ErrorUnit in a TDD way would be:</p> <p>1) First create a test manually to ensure there is a button press event; then create the event and test as per pure TDD.</p> <p>2) Then run the program, navigate to the screen with the button, and with a breakpoint set in the event method, press the button</p> <p>3) When the breakpoint is hit you can then click ErrorUnit's "Add unit test" to generate a unit test with all the objects and current database state already mocked. (Repeat as needed with different use cases states)</p> <p>4) You would then alter the created unit tests to have an Assert to match the result of what you want the button click to do as per TDD . </p> <p>5) Then write the code behind the click event, and run your test that is part generated by ErrorUnit (for the Arrange and Act) and part custom (for the Assert).</p> <p>This way you save most of your time that would be spent typing the Arrange and Act.</p> <p>ErrorUnit also works with Error Logging to reproduce errors in other environments by serializing and mocking in the unit test the exact state at the time of error; Bringing TDD to production issue resolution.</p>
46,562
<p>Consider the following table structure...</p> <pre><code>Appointment ----------- ID integer Description nvarchar StatusID smallint Status ------ ID smallint DisplayText nvarchar </code></pre> <p>Now, for good or for evil, we want this situation to map to a class that looks like this</p> <pre><code>class Appointment { public int ID {g;s;} public string Description { g;s; } public string Status { g; private s; } } </code></pre> <p>I.e. we want to pull the normalised status display text straight into the entity.</p>
<p>The obvious answer is to create a Status entity and make the appointment class have a reference to that and map it in the normal way.</p>
<p>The obvious answer is to create a Status entity and make the appointment class have a reference to that and map it in the normal way.</p>
44,229
<p>Does Eclipse have a feature that lets you search a project to find all calls to deprecated methods?</p>
<p>You can set the compiler to generate errors or warnings (your choice) for any usage of deprecated API.</p> <blockquote> <p>Preferences -> Java -> Compiler -> Errors/Warnings -> <em>Deprecated and restricted API</em> section. </p> </blockquote> <p>Then, each use of a deprecated method or API will show up as an error/warning in the Problems view.</p>
<p>You can always use the grep facilities under 'Search -> File'. Eclipse can do a recursive search for <code>@deprecated</code> after you check on the 'consider derived resources' option box.</p>
28,914
<p>I'm about to start a project that will record and edit audio files, and I'm looking for a good library (preferably Ruby, but will consider anything other than Java or .NET) for on-the-fly visualization of waveforms.</p> <p>Does anybody know where I should start my search?</p>
<p>That's a lot of data to be streaming into a browser. Flash or Flex charts is probably the only solution that will be memory efficient. Javascript charting tends to break-down for large data sets. </p>
<p>The other option is generating the waveforms on the server-side with GD or RMagick. But good luck getting RubyGD to compile.</p>
6,247
<p>I'm looking for a <em>SimpleGrepSedPerlOrPythonOneLiner</em> that outputs all quotations in a text.</p> <hr> <p>Example 1:</p> <pre><code>echo “HAL,” noted Frank, “said that everything was going extremely well.” | SimpleGrepSedPerlOrPythonOneLiner </code></pre> <p>stdout:</p> <pre><code>"HAL," "said that everything was going extremely well.” </code></pre> <hr> <p>Example 2:</p> <pre><code>cat MicrosoftWindowsXPEula.txt | SimpleGrepSedPerlOrPythonOneLiner </code></pre> <p>stdout:</p> <pre><code>"EULA" "Software" "Workstation Computer" "Device" "DRM" </code></pre> <p>etc.</p> <p>(<a href="http://www.microsoft.com/windowsxp/eula/home.mspx" rel="nofollow noreferrer">link to the corresponding text</a>).</p>
<p>I like this:</p> <pre><code>perl -ne 'print "$_\n" foreach /"((?&gt;[^"\\]|\\+[^"]|\\(?:\\\\)*")*)"/g;' </code></pre> <p>It's a little verbose, but it handles escaped quotes and backtracking a lot better than the simplest implementation. What it's saying is:</p> <pre><code>my $re = qr{ " # Begin it with literal quote ( (?&gt; # prevent backtracking once the alternation has been # satisfied. It either agrees or it does not. This expression # only needs one direction, or we fail out of the branch [^"\\] # a character that is not a dquote or a backslash | \\+ # OR if a backslash, then any number of backslashes followed by [^"] # something that is not a quote | \\ # OR again a backslash (?&gt;\\\\)* # followed by any number of *pairs* of backslashes (as units) " # and a quote )* # any number of *set* qualifying phrases ) # all batched up together " # Ended by a literal quote }x; </code></pre> <p>If you don't need that much power--say it's only likely to be dialog and not structured quotes, then </p> <pre><code>/"([^"]*)"/ </code></pre> <p>probably works about as well as anything else.</p>
<pre><code>grep -o '"[^"]*"' file </code></pre> <blockquote> <p>The option '-o' print only pattern</p> </blockquote>
44,674
<p>I have a UI-dialog something like this: You must choose a book from a list. Optionally, you can either choose a publisher (another class) from a list or enter the publisher-name as as a string. </p> <p>I think this gives me 3 types as the output from the dialog.</p> <ol> <li>book</li> <li>book with publisher-class</li> <li>book with publisher-string</li> </ol> <p>How would you model this in objects? It seems to me that the having a book base-class, and then two subclasses for publisher and publisher name is the correct choice. Are there any alternatives, perhaps favoring composition that would give a better model?</p> <hr> <p>I'll try to explain a bit more. A book doesn't need to have a publisher. The publisher object is not the same as a publisher-name entered as a string.</p> <p>You must<br> -choose a book from an existing list </p> <p>You can one of the following<br> -choose a publisher from an existing list or<br> -you can enter a publisher name or<br> -you can fill nothing about the publisher </p>
<p>Number two would be my approach.</p> <p>I would have a class for Publisher with a property called Name, along with any other properties needed to describe a publisher.</p> <p>Then I would have a class for book with properties to describe it, along with a property of type Publisher. </p> <p>If the user enters a new publisher as a string, create a new Publisher object.</p> <p>If the user does not enter a publisher, leave the property null. That will satisfy the condition that the book has no publishers. Alternatively, you could have publisher with the name "No publisher" but I think that is going too far out of your way to avoid nulls. </p>
<p>I think it's difficult to make a design decision based just on this dialog. For instance, are you picking from a set of existing books? In that case, what if the user enters a publisher who doesn't exist? In this case, you may not want to return an instance of any Book class at all, but raise some kind of exception. </p> <p>Do all books in your case have publishers? If so, then I agree with @Bob that you could make a Publisher class, and have a Book class contain an instance of a Publisher object. If only some books have Publishers, then you could go with the inheritance model you describe, but I would collapse options 2 and 3 into a single choice (again by using a Publisher object) because otherwise you could end up with two instances of the same book that are objects of different types (one where the user entered the publisher as a string, and once by picking from the list).</p> <p>--Phil</p>
46,112
<p>I have a Struts + Velocity structure like for example, a Person class, whose one property is a Car object (with its own getter/setter methods) and it is mapped to a Velocity form that submits to an Action, using ModelDriven and getModel structure.</p> <p>I what to put a button on the form that shows "View Car" if car property is not null or car.id != 0 or show another button "Choose Car" if car is null or car.id = 0.</p> <p>How do I code this. I tried something like that in the template file:</p> <pre><code>#if($car != null) #ssubmit("name=view" "value=View Car") #else #ssubmit("name=new" "value=Choose Car") #end </code></pre> <p>But I keep getting error about Null value in the <em>#if</em> line. </p> <p>I also created a boolean method hasCar() in Person to try, but I can't access it and I don't know why.</p> <p>And Velocity + Struts tutorials are difficult to find or have good information.</p> <p>Thanks</p>
<p>You should change the #if line to:</p> <pre><code>#if($car) </code></pre>
<p>In the upcoming Velocity 1.6 release, you will be able to do <code>#if( $car == $null )</code> without error messages. This will allow you to distinguish easily between when <code>$car</code> is null and when it is false. To do that now requires <code>#if( $car &amp;&amp; $car != false )</code>, which just isn't as friendly.</p>
4,410
<p>I have an access database, with a query made. I need to automate it so that each night this query can run and export to a tab delimited csv file. It is not possible to export a query to a csv file from within access. My question is, are there any tools that can select certain tables, or perform an sql query on an mdb file, and export to a csv file?</p>
<p>Actually, you can export a query to a csv file from within Access.</p> <p>You can do this with a Macro using the TransferText method.</p> <p>Macro:</p> <pre><code> Name = ExportQuery Action = TransferText Transfer Type = Export Delimited Table Name = [name of your Access query] File Name = [path of output file] Has Field Names = [Yes or No, as desired] </code></pre> <p>You can execute the macro from the command line like this:</p> <pre><code>"[your MS Office path]\msaccess.exe" [your databse].mdb /excl /X ExportQuery /runtime </code></pre> <p>Since you're having trouble with TransferText in a macro try this:</p> <p>1) Create a Module named "ExportQuery". In this module, create a function called "ExportQuery":</p> <pre><code>Function ExportQuery() DoCmd.TransferText acExportDelim, , "[your query]", "[output file].csv" End Function </code></pre> <p>2) Create a Macro named RunExportQuery:</p> <pre><code>Action = RunCode Function Name = ExportQuery () </code></pre>
<p>SQL Server Integration Services is able to do the transformation that you are talking about. Don't be fooled by the name, because you don't need SQL Server in order to automate and run the packages.</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms141026.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms141026.aspx</a></p>
35,531
<p>What is the best way to build a loopback URL for an AJAX call? Say I have a page at</p> <pre><code>http://www.mydomain.com/some/subdir/file.php </code></pre> <p>that I want to load with an AJAX call. In Firefox, using jQuery this works fine:</p> <pre><code>$.post('/some/subdir/file.php', ...); </code></pre> <p>Safari/WebKit tries to interpret this as a location on the local filesystem (so it ends up translating to 'file://some/subdir/file.php'). Not only does this not point to anything useful, it also results in a security error.</p> <p>Is there a way to accomplish this without hard-coding the domain into the URL? I'd like to make this as domain-independent as possible.</p> <p><strong>Update</strong></p> <p>I ended up parsing out the base url from location.href and throwing it into an accessible jQuery function like this:</p> <pre><code>/** * Retrieves the current root URL. * * @return string the root URL */ $.fn.rootUrl = function() { var url = location.href; return url.substring(0, url.indexOf('/', 7)); }; </code></pre>
<p><a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.figure.html" rel="noreferrer"><code>figure</code></a> tells you the call signature:</p> <pre><code>from matplotlib.pyplot import figure figure(figsize=(8, 6), dpi=80) </code></pre> <p><code>figure(figsize=(1,1))</code> would create an inch-by-inch image, which would be 80-by-80 pixels unless you also give a different dpi argument.</p>
<p>I've made research and wrote article about <a href="https://mljar.com/blog/matplotlib-change-figure-size/" rel="nofollow noreferrer">3 different ways to change figure size in Matplotlib</a>. It is important to remember that:</p> <ul> <li>figure size in Matplotlib is in <strong>inches</strong>,</li> <li><code>dpi</code> parameter is for dots per inch,</li> <li>the pixel size of figure is computed by multiplying size by <code>dpi</code>.</li> </ul> <h2>1. Set <code>figsize</code> and <code>dpi</code> when creating figure</h2> <pre class="lang-py prettyprint-override"><code>from matplotlib import pyplot as plt plt.figure(figsize=(3, 3), dpi=144) _ = plt.plot([3, 4, 2, 5]) </code></pre> <h2>2. Use setters functions <code>set_figwidth</code>, <code>set_figheight</code>, <code>set_size_inches</code>, <code>set_dpi</code></h2> <pre class="lang-py prettyprint-override"><code># create figure f = plt.figure() # set width, height, dpi f.set_figwidth(4) f.set_figheight(2) f.set_dpi(142) # plot _ = plt.plot([3,4,2,5]) </code></pre> <h2>3. Set size and <code>dpi</code> globally</h2> <p>You can set size and <code>dpi</code> for all figures with:</p> <pre class="lang-py prettyprint-override"><code># set figsize and dpi for all figures plt.rcParams[&quot;figure.figsize&quot;] = (4,2) plt.rcParams[&quot;figure.dpi&quot;] = 144 </code></pre> <p>If you are Jupyter Notebook user please remember to set <code>rcParams</code> in separate cell - not in the same cell as imports.</p>
43,046
<p>Has Object Prevalance mechanisms been used in an actual Production system? I'm referring to something like <a href="http://www.prevayler.org/wiki/" rel="nofollow noreferrer">Prevayler</a> or <a href="http://madeleine.rubyforge.org/" rel="nofollow noreferrer">Madeleine</a></p> <p>The only thing I've found is <a href="http://en.wikipedia.org/wiki/Instiki" rel="nofollow noreferrer">Instiki</a>, a wiki engine. But since they started they've switched to SQLite. (The actual <a href="http://www.instiki.org/" rel="nofollow noreferrer">instiki</a> page is down)</p>
<p>A company I used to work for used Prevayler as part of a computer-based student examination/assessment system for about five or six years.</p> <p>Prevayler was used to store the state of candidates’ tests on a server physically located within a single testing centre. The volume of data stored was fairly low, since at most there would only be a few hundred candidates taking a test at a single testing centre. Therefore it was practical to run Prevayler on commodity hardware in 2004 – the ‘server’ was in most cases just a typical low-end desktop machine temporarily borrowed for the purpose of running an exam.</p> <p>The idea was that if a candidate’s computer crashed while they were taking the test, then they could quickly resume the test on the same or different computer. It worked pretty well.</p> <p>There were occasional difficulties when some new requirement led to a change to the object model, since by default Prevayler close-couples the object model to the representation of data on disk. This wasn’t actually a major problem for us, since changes to the object model occurred between exams at which point we could usually afford to throw old data away (with some exceptions due to bad design on our part).</p> <p>There are lots of things you can do to make it feasible to change the object model, it’s a matter of what’s best for your application. Throwing old data away was generally the best solution for us.</p> <p>There was also a back-end system that aggregated candidates’ tests from all testing centres into an SQL database. That stored a higher volume of data than Prevayler could have reasonably coped with at the time. It would probably be feasible to use Prevayler there today, but I don’t think the usage patterns would have suited Prevayler particularly well, since most of the data tended to be written, read once for marking, then forgotten about and treated as archive data unless the result of a test got queried.</p> <p>That company has sinced moved away from Prevayler but the reason for that was more political than it was technical.</p>
<p>Well, we're using Prevayler in a project that's aiming <em>towards</em> production by sometime next year, but we're not close enough to give any real scouting report. We <em>think</em> it's going to work...</p>
29,194
<p>I am an Ajax developer and I want to build a Flash application. Given my previous experience with JavaScript, what do you thing will be the easiest way to learn ActionScript and what are the obstacles I might encounter? </p>
<p>Don't whatever you do start by buying Flash Pro. It is a designer tool and is really rather crap for developing code. By all means invest in it later, but it is a hindrance to coders getting into ActionScript; not an aid. I'd recommend getting yourself either <a href="http://www.adobe.com/products/flex/features/flex_builder/" rel="nofollow noreferrer">Flex Builder</a> if you can afford it, or an open source ActionScript IDE like <a href="http://www.flashdevelop.org/community/" rel="nofollow noreferrer">FlashDevelop</a> if not. </p> <p>Then grab yourself a couple of books on ActionScript and/ or Flex and start reading. Also it is worth downloading any examples of simple Flash apps you can find that include code in order to learn how others do things.</p> <p>Something to bear in mind when moving from JavaScript to ActionScript is that AS1 was very JavaScript-like, AS2 was less so, and there is little similarity between JavaScript and AS3. Thus if you have the time and inclination, try and pick up a cheap copy of an AS1 and AS2 book and skim through them first to understand the language's history. You'll likely get into AS3 far faster that way. Of course if you are aware of ECMAScript v4 (which will likely now never see the light of day), then you can jump straight to AS3 with confidence.</p>
<p>the best way to learn action script can only through video tutorials. Better tryout video tutorials which helps u lot teach you step by step (very easily understandable) which is very easy to understand. you can also vist <a href="http://www.infoclassi.do.am" rel="nofollow noreferrer">http://www.infoclassi.do.am</a> for all video tutorials. You can also order them if you need any other tutorials at less cost when compared to other tutorials with the same quality.</p>
23,946
<p>I would like to format a price in JavaScript. I'd like a function which takes a <code>float</code> as an argument and returns a <code>string</code> formatted like this:</p> <pre><code>&quot;$ 2,500.00&quot; </code></pre> <p>How can I do this?</p>
<h2><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed" rel="noreferrer">Number.prototype.toFixed</a></h2> <p>This solution is compatible with every single major browser:</p> <pre><code> const profits = 2489.8237; profits.toFixed(3) // Returns 2489.824 (rounds up) profits.toFixed(2) // Returns 2489.82 profits.toFixed(7) // Returns 2489.8237000 (pads the decimals) </code></pre> <p>All you need is to add the currency symbol (e.g. <code>&quot;$&quot; + profits.toFixed(2)</code>) and you will have your amount in dollars.</p> <h2>Custom function</h2> <p>If you require the use of <code>,</code> between each digit, you can use this function:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function formatMoney(number, decPlaces, decSep, thouSep) { decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces, decSep = typeof decSep === "undefined" ? "." : decSep; thouSep = typeof thouSep === "undefined" ? "," : thouSep; var sign = number &lt; 0 ? "-" : ""; var i = String(parseInt(number = Math.abs(Number(number) || 0).toFixed(decPlaces))); var j = (j = i.length) &gt; 3 ? j % 3 : 0; return sign + (j ? i.substr(0, j) + thouSep : "") + i.substr(j).replace(/(\decSep{3})(?=\decSep)/g, "$1" + thouSep) + (decPlaces ? decSep + Math.abs(number - i).toFixed(decPlaces).slice(2) : ""); } document.getElementById("b").addEventListener("click", event =&gt; { document.getElementById("x").innerText = "Result was: " + formatMoney(document.getElementById("d").value); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;label&gt;Insert your amount: &lt;input id="d" type="text" placeholder="Cash amount" /&gt;&lt;/label&gt; &lt;br /&gt; &lt;button id="b"&gt;Get Output&lt;/button&gt; &lt;p id="x"&gt;(press button to get output)&lt;/p&gt;</code></pre> </div> </div> </p> <p>Use it like so:</p> <pre><code>(123456789.12345).formatMoney(2, &quot;.&quot;, &quot;,&quot;); </code></pre> <p>If you're always going to use '.' and ',', you can leave them off your method call, and the method will default them for you.</p> <pre><code>(123456789.12345).formatMoney(2); </code></pre> <p>If your culture has the two symbols flipped (i.e., Europeans) and you would like to use the defaults, just paste over the following two lines in the <code>formatMoney</code> method:</p> <pre><code> d = d == undefined ? &quot;,&quot; : d, t = t == undefined ? &quot;.&quot; : t, </code></pre> <h2>Custom function (ES6)</h2> <p>If you can use modern ECMAScript syntax (i.e., through Babel), you can use this simpler function instead:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function formatMoney(amount, decimalCount = 2, decimal = ".", thousands = ",") { try { decimalCount = Math.abs(decimalCount); decimalCount = isNaN(decimalCount) ? 2 : decimalCount; const negativeSign = amount &lt; 0 ? "-" : ""; let i = parseInt(amount = Math.abs(Number(amount) || 0).toFixed(decimalCount)).toString(); let j = (i.length &gt; 3) ? i.length % 3 : 0; return negativeSign + (j ? i.substr(0, j) + thousands : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands) + (decimalCount ? decimal + Math.abs(amount - i).toFixed(decimalCount).slice(2) : ""); } catch (e) { console.log(e) } }; document.getElementById("b").addEventListener("click", event =&gt; { document.getElementById("x").innerText = "Result was: " + formatMoney(document.getElementById("d").value); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;label&gt;Insert your amount: &lt;input id="d" type="text" placeholder="Cash amount" /&gt;&lt;/label&gt; &lt;br /&gt; &lt;button id="b"&gt;Get Output&lt;/button&gt; &lt;p id="x"&gt;(press button to get output)&lt;/p&gt;</code></pre> </div> </div> </p>
<p>after converting PHP number_format() to javascript this work for me</p> <pre><code>function number_format(number, decimals = 0, dec_point = &quot;.&quot;,thousands_sep = &quot;,&quot;) { number = (number + '').replace(/[^0-9+\-Ee.]/g, ''); var n = !isFinite(+number) ? 0 : +number, prec = !isFinite(+decimals) ? 0 : Math.abs(decimals), s = '', toFixedFix = function(n, prec) { var k = Math.pow(10, prec); return '' + (Math.round(n * k) / k).toFixed(prec); }; // Fix for IE parseFloat(0.55).toFixed(0) = 0; s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.'); if (s[0].length &gt; 3) { s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, thousands_sep); } if ((s[1] || '').length &lt; prec) { s[1] = s[1] || ''; s[1] += new Array(prec - s[1].length + 1).join('0'); } return s.join(dec_point); } </code></pre>
17,964
<p>I have this form:</p> <pre><code>&lt;form name="customize"&gt; Only show results within &lt;select name="distance" id="slct_distance"&gt; &lt;option&gt;25&lt;/option&gt; &lt;option&gt;50&lt;/option&gt; &lt;option&gt;100&lt;/option&gt; &lt;option value="10000" selected="selected"&gt;Any&lt;/option&gt; &lt;/select&gt; miles of zip code &lt;input type="text" class="text" name="zip_code" id="txt_zip_code" /&gt; &lt;span id="customize_validation_msg"&gt;&lt;/span&gt; &lt;/form&gt; </code></pre> <p>How can I select the <code>input</code> and <code>select</code> with one jQuery selector?</p> <p>I tried this but it selected all of the selects and inputs on the page:</p> <pre><code>$("form[name='customize'] select,input") </code></pre>
<p>The comma in the selector string separates completely separate expressions, just like in CSS, so the selector you've given gets the select elements within the form named "customize" and all inputs on the form (as you've described). It sounds like you want something like this:</p> <pre><code>$("form[name='customize'] select, form[name='customize'] input") </code></pre> <p>or if you're not into repitition, this:</p> <pre><code>$("form[name='customize']").children("select, input") </code></pre>
<p>For me your suggestion worked. You could also use</p> <pre><code>form[name='customize'] select, form[name='customize'] input </code></pre> <p>Both selectors work as I see it. Maybe the the problem lies somewhere else?</p> <p>I tried</p> <pre><code>$("form[name='customize'] select, input").css( 'font-size', '80px' ); </code></pre> <p>on your example HTML. The font size for select and input changed.</p> <p>--- edit ---</p> <p>My suggestion above is the right one. It selects just the elements in the customize-form.</p>
34,832
<p>When I try to display the contents of a LOB (large object) column in SQL*Plus, it is truncated. How do I display the whole thing?</p>
<pre><code>SQL&gt; set long 30000 SQL&gt; show long long 30000 </code></pre>
<p>You may also need:</p> <pre><code>SQL&gt; set longchunksize 30000 </code></pre> <p>Otherwise the LOB/CLOB will wrap.</p>
14,936
<p>I've got to get a directory listing that contains about 2 million files, but when I do an <code>ls</code> command on it nothing comes back. I've waited 3 hours. I've tried <code>ls | tee directory.txt</code>, but that seems to hang forever. </p> <p>I assume the server is doing a lot of inode sorting. Is there any way to speed up the <code>ls</code> command to just get a directory listing of filenames? I don't care about size, dates, permission or the like at this time.</p>
<pre><code>ls -U </code></pre> <p>will do the ls without sorting.</p> <p>Another source of slowness is <code>--color</code>. On some linux machines, there is a convenience alias which adds <code>--color=auto'</code> to the ls call, making it look up file attributes for each file found (slow), to color the display. This can be avoided by <code>ls -U --color=never</code> or <code>\ls -U</code>.</p>
<p>Lots of other good solutions here, but in the interest of completeness:</p> <pre><code>echo * </code></pre>
6,142
<p>I have a new Prusa i3 MK3 and I have noticed that my prints consistently turn out worse on 0.05 mm layer heights than on 0.10 mm. The edges of the 0.05 mm prints turn out rough and sometimes stringy.</p> <p><a href="https://i.stack.imgur.com/KOLcv.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/KOLcv.jpg" alt="Detail of a 0.05 mm layer height printed model"></a></p> <p>Seems similar to a retraction problem but I never have this issue on 0.10 mm prints with the same retraction settings. </p> <p>What might be causing this issue?</p>
<p>When printing at small layer heights (high resolution), you probably need to do some test prints first to see if your normal settings work for the lower layer height. You are most probably experiencing an increased pressure build-up in the nozzle due to the nozzle being closer to the bed. A test that might be useful for you is spacing several objects at different distances to see if the retraction, which you already suspect, may be not working optimally or that the nozzle leaks/oozes an excess amount of filament due to pressure build-up. This shows an example of such a test where the nozzle shows oozing.</p> <p><a href="https://i.stack.imgur.com/xsmW1.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/xsmW1.jpg" alt="Effect of object distance"></a></p> <p>Tuning the extruder to alleviate the pressure could be:</p> <ul> <li>an increased retraction length, and/or </li> <li>retraction speed, or </li> <li>looking into the option called coasting where you stop extruding before the printer reaches the end of the deposition path while it still prints material caused by the pressure build-up.</li> </ul> <p><a href="https://i.stack.imgur.com/E1GOE.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/E1GOE.jpg" alt="Tuned extruder"></a></p> <hr> <p><sub><em>When printing at 0.05 mm on my home-build CoreXY I experience much smoother prints opposed to printing in higher layer heights (less resolution), but I also get some very fine stringing, noticeable when printing multiple objects or objects with voids.</em> </sub></p>
<p>One thing that I have learned in my extensive youtubing is that sometimes the hot end can soften the previous layers. Though, take the following advice with a grain of salt as the following is just conceptual for me (I'm still waiting for my first printer to arrive to follow this advice).</p> <p>Tomb of 3D Printed Horrors has a pretty <a href="https://www.youtube.com/watch?v=AqEWl51s9Rw" rel="nofollow noreferrer">good video</a> on printing D&amp;D miniatures that require high detail at small sizes (particularly at the 2 minute mark). His recommendation is to have 0.2 mm thick lines as thinner lines are more susceptible melting when the hot end is laying down subsequent layers. Thicker layers means more plastic to absorb the heat and less deformity. This is probably why your 0.1 mm lines look better than your 0.05 mm lines.</p> <p>Another fix is to keep print speeds somewhat normal or slightly slow. A faster print head heats the previous layers less and can counteract the issue. Running at 60 mm/s may be too quick for quality prints, but running at 10 mm/s is too slow and can reheat the lower layers. Keeping an "average" pace paired with thick enough lines could help you get the prints you want. Though, finding what speeds/thickness is up to you. I don't have the experience to suggest any at the moment.</p>
1,097
<p>Is it possible to host a Maven repository that serves the artifacts (at least the jar files) from SourceForge's file release system (since they are already there and SF provides download statistics and such)? </p> <p>All the repositories I have seen use the same directory layout, but is that a must? Download URLs would have to look more like <em><a href="http://sf.net/something.cgi?file-id=1234567" rel="nofollow noreferrer">http://sf.net/something.cgi?file-id=1234567</a></em></p> <p>There would only be a small number of files in the project, so that maintaining the download URL in some kind of repository metadata XML file semi-manually is still an option.</p> <p><strong>Note:</strong> This is kind of the opposite question to <a href="https://stackoverflow.com/questions/16487/how-can-i-deploy-artifacts-from-a-maven-build-to-the-sourceforge-file-release-s">How can I deploy artifacts from a Maven build to the SourceForge File Release System?</a></p> <p><strong>Clarification:</strong> I want to put the files in the File Release System (Project Downloads), not the project web space or the subversion repository.</p>
<p>Yes you can. But it's a bit convoluted:</p> <p>If you look at a project like this <a href="http://jwebunit.sourceforge.net/m2-repo/" rel="nofollow noreferrer">http://jwebunit.sourceforge.net/m2-repo/</a> you'll see that they are exposing a perfectly legal maven repo. These are the steps to do it:</p> <p>Theoretically you could just add the relevant part of your ~/.m2/repo folder to the root of svn on the project in question (in a folder called m-2repo for instance like jwebunit has done). Sourceforge exposes the full svn structure accessible through web, so there's your repo. </p> <p>But; the problem is that maven requires that remote repositories contain MD5 checksums of all elements. When you run "maven install" towards a lolcal file repo you will not get these checksums generated.</p> <p>The way I have solved this locally is to set up apache/webdav on a specific folder on my machine. I then use THIS folder as a target for "mvn deploy". Then i just keep this full folder checked into subversion on sourceforge. </p>
<p>Very nice solution, thanks to krosenvold. Additionally, you can try to generate checksums with this part of pom:</p> <pre><code>&lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-install-plugin&lt;/artifactId&gt; &lt;executions&gt; &lt;execution&gt; &lt;goals&gt; &lt;goal&gt;install&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;createChecksum&gt;true&lt;/createChecksum&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; </code></pre>
47,254
<p>Have had to write my first "proper" multithreaded coded recently, and realised just how little I knew about how "imperative-style" (ie, concurrency models used by C++/C#/Java, and the like) concurrent programming techniques.</p> <p>What resources are there (both books and online tutorials, etc) in order to learn more about this area of coding-fu?</p> <p>NB: I'm not asking about concurrency models that are arguably better (Erlang's message passing, or Clojure's STM), just paradigms used in imperative languages.</p>
<p><a href="http://www.justsoftwaresolutions.co.uk/reviews/patterns_for_parallel_programming_review.html" rel="noreferrer">Patterns for Parallel Porgramming</a> is a good general book on concurrent programming techniques. It uses Java threads, OpenMP in C and MPI in C for the examples.</p> <p>Pretty much any decent book on multithreaded programming in any of the languages you mention should cover the general principles. I'm covering this ground in <a href="http://www.manning.com/williams/" rel="noreferrer">C++ Concurrency in Action</a>, for example.</p>
<p>You might find my <a href="http://refcardz.dzone.com/refcardz/core-java-concurrency" rel="nofollow noreferrer">Java Concurrency refcard</a> a useful short reference for Java-specific questions.</p>
23,015
<p>I have a working linker script. I want to add another data section whose contents is pulled directly from a file (ld shouldn't parse it and extract the sections and so on). How can I do that?</p> <pre><code>OUTPUT_FORMAT("elf32-i386") ENTRY(start) SECTIONS { .text 0x100000 : { *(.multiboot) *(.text) *(.code) *(.rodata*) } .data : { *(.data) } .bss : { *(.bss) } kernel_end = .; roottask_start = .; .data : { HERE I WANT TO INCLUDE THE ENTIRE CONTENTS OF ANOTHER (BINARY) FILE } roottask_end = .; } </code></pre>
<p>You could try using <code>objcopy</code> to convert it to a normal object you can link in, and then reference its symbols in the linker script like you would do to a normal object. From the <a href="http://linux.die.net/man/1/objcopy" rel="noreferrer"><code>objcopy</code> manual page</a>:</p> <blockquote> <p>-B bfdarch --binary-architecture=bfdarch Useful when transforming a raw binary input file into an object file. In this case the output architecture can be set to bfdarch. This option will be ignored if the input file has a known bfdarch. You can access this binary data inside a program by referencing the special symbols that are created by the conversion process. These symbols are called <code>_binary_objfile_start</code>, <code>_binary_objfile_end</code> and <code>_binary_objfile_size</code>. e.g. you can transform a picture file into an object file and then access it in your code using these symbols.</p> </blockquote> <p>...where <em>objfile</em> will be expanded to the name of the input object file.</p> <p>See also the <code>--rename-section</code> option.</p>
<p>Another way with just the linker is to use <a href="https://sourceware.org/binutils/docs/ld/Format-Commands.html" rel="nofollow noreferrer">TARGET</a> and <a href="https://sourceware.org/binutils/docs/ld/File-Commands.html" rel="nofollow noreferrer">INPUT</a> commands.</p> <pre> <b>TARGET(binary)</b> <b>INPUT (./DATA.bin)</b> <b>INPUT (./CODE.bin)</b> # add more binary files here if needed OUTPUT_FORMAT("elf32-i386") ENTRY(start) SECTIONS { .text 0x100000 : { *(.multiboot) *(.text) *(.code) <b>./CODE.bin</b> *(.rodata*) } .data : { *(.data) } .bss : { *(.bss) } kernel_end = .; roottask_start = .; .data : { <b>./DATA.bin</b> } roottask_end = .; } </pre> <p>Additionally, you may need alignment stanzas around the binary input.</p>
42,461
<p>Is it possible to set an iPhone Xcode project to skip the 'CompressResources' build step?</p> <p>Specifically, I want to skip the stage where it runs pngcrush on all of my .png files, many of which don't survive the experience in a form which my app can read.</p> <p><strong>Edit:</strong> the version of pngcrush used creates png files which contain a non-standard 'mandatory, private' chunk which explicitly prevents decoding. I've modified my png reader to handle these files, but I'd still like a per-project method of skipping this step. One of the other side effects of pngcrush is that it doesn't save the colour value of transparent pixels, so alpha-ed textures show fringing at smaller mip levels.</p> <p>The iphone png format is described here: <a href="https://web.archive.org/web/20110519164905/http://modmyi.com/wiki/index.php/Iphone_PNG_images" rel="nofollow noreferrer">https://web.archive.org/web/20110519164905/http://modmyi.com/wiki/index.php/Iphone_PNG_images</a>. In short,</p> <ul> <li>Skip the CgBI chunk</li> <li>Skip the zlib headers</li> <li>Swap BGR to RGB channel order</li> </ul> <p><strong>Edit:</strong> It appears it also premultiplies the alpha, so:</p> <ul> <li>Divide by alpha</li> </ul>
<p>You can add "IPHONE_OPTIMIZE_OPTIONS=-skip-PNGs" to your project settings to prevent the png mangling, but be careful with it, you might need to optimize the icon and Default.png separately then.</p>
<p>That might be another issue all together. In many cases the problem has to do with naming and can be solved very easily.</p> <p>read this: <a href="http://cocoapi.wordpress.com/2009/03/22/iphone-images-not-appearing-in-real-iphone-this-is-why/" rel="nofollow noreferrer">http://cocoapi.wordpress.com/2009/03/22/iphone-images-not-appearing-in-real-iphone-this-is-why/</a></p>
21,339
<p>I'm having a couple of problems with the JQuery <a href="http://tablesorter.com/docs/" rel="noreferrer">tablesorter</a> plugin. If you click on a column header, it should sort the data by this column, but there are a couple of problems:</p> <ol> <li>The rows are not properly sorted (1, 1, 2183, 236)</li> <li>The total row is included in the sort</li> </ol> <p>Regarding (2), I can't easily move the total row to a table footer, because the HTML is generated by the <a href="http://displaytag.sourceforge.net/11/" rel="noreferrer">displaytag</a> tag library over which I have limited control.</p> <p>Regarding (1), I don't understand why the sort doesn't work as I've used exactly the same JavaScript shown in the simplest example in the <a href="http://tablesorter.com/docs/#Getting-Started" rel="noreferrer">tablesorter tutorials</a>. </p> <p>In fact, there's only a single line of JS code, which is:</p> <pre><code>&lt;body onload="jQuery('#communityStats').tablesorter();"&gt; </code></pre> <p>Thanks in advance, Don</p>
<p>The first problem is due to the fact that the table sorter auto detects the column to a 'text'-column (probably because the empty cells). To solve this use this code to initialize the tablesorter and set all the field to either digit or currency depending on the data:</p> <pre><code>&lt;script type="text/javascript" &gt; jQuery(document).ready(function() { jQuery("#communityStats").tablesorter({ headers: { 2: { sorter:'digit' } , 3: { sorter:'digit' } , 4: { sorter:'digit' } , 5: { sorter:'digit' } , 6: { sorter:'digit' } , 7: { sorter:'digit' } , 8: { sorter:'currency' } , 9: { sorter:'currency' } , 10: { sorter:'currency' } , 11: { sorter:'currency' } } }); }); &lt;/script&gt; </code></pre>
<ol> <li><p>Blank fields could be a problem (e.g they are not 0), try using custom parser which removes any non-numericals and forces values to integers (example: <a href="http://paste.pocoo.org/show/90863/" rel="nofollow noreferrer">http://paste.pocoo.org/show/90863/</a> )</p></li> <li><p>Put your 'total' row inside a &lt;tfoot&gt; &lt;/tfoot&gt; tag right before the end of the table</p></li> </ol>
38,889
<p>What is the string concatenation operator in Oracle SQL? </p> <p>Are there any "interesting" features I should be careful of? </p> <p>(This seems obvious, but I couldn't find a previous question asking it). </p>
<p>It is <code>||</code>, for example:</p> <pre><code>select 'Mr ' || ename from emp; </code></pre> <p>The only "interesting" feature I can think of is that <code>'x' || null</code> returns <code>'x'</code>, not <code>null</code> as you might perhaps expect.</p>
<p>Using <code>CONCAT(CONCAT(,),)</code> worked for me when concatenating more than two strings. </p> <p>My problem required working with date strings (only) and creating <code>YYYYMMDD</code> from <code>YYYY-MM-DD</code> as follows (i.e. without converting to date format):</p> <pre><code>CONCAT(CONCAT(SUBSTR(DATECOL,1,4),SUBSTR(DATECOL,6,2)),SUBSTR(DATECOL,9,2)) AS YYYYMMDD </code></pre>
35,125
<p>I am wondering if there are any well-known algorithms that I should be aware of for spacing objects visually.</p> <p>For instance, a LINQ to SQL diagram has many tables but automatically spaces them for readability. Is this pretty much a "place randomly and move if too close/overlap" type algorithm or is there more to this?</p> <p>Thanks for any advice!</p>
<p>Roughly, you can perform a "connectedness" analysis on your graph of objects, to determine which is (are) more central; i.e. which have a higher degree of connectivity to other objects. Those go in the center. Figure out your individual sizing of objects, determine the amount of space left, divide that by the number of items to place, and place them based upon that data.</p>
<p>Take a look at <a href="http://www.graphviz.org/" rel="nofollow noreferrer">GraphViz</a>. It might be usable right off the shelf or might be a good starting point.</p>
38,543
<p>I have a gridview containing some data from db, and after a check I want to see a small cross/tick image in each row, due to the result of the check.How can I change the image url dynamically? </p>
<p>You could either use inline statement like <br/> <code>&lt;%#Eval("check").ToString() == "1" ? "images/checked.gif" : "images/unchceked.gif")%&gt;</code></p> <p>or use a function to get the result as follows:</p> <pre><code>&lt;%# getImageUrl(Eval("value")) %&gt; Public Function getImageUrl(ByVal value As Integer) As String If value = 0 Then Return "images/unchceked.gif" Else Return "mages/checked.gif" End If End Function </code></pre>
<pre><code>&lt;Columns&gt; &lt;asp:TemplateField&gt; &lt;ItemTemplate&gt; &lt;asp:Image ID="check" runat="server" ImageUrl='&lt;%#If(Eval("check") = 1,"images/checked.gif","images/unchceked.gif") %&gt;' /&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;/Columns&gt; </code></pre>
28,455
<p>Is it possible to somehow change the look/feel of NetBeans? I know it uses Swing and that usually apps using Swing for its UI can usually have their UI scheme changed.</p> <p>The default appearence for OSX is vomitastic and would even settle for just some sort of barebones <code>default</code> look. The whole look is just too distracting and unnecessary.</p>
<p>Looks like this might be what I was looking for:</p> <p><a href="http://wiki.netbeans.org/FaqCustomLaf" rel="nofollow noreferrer">http://wiki.netbeans.org/FaqCustomLaf</a></p>
<p>Looks like this might be what I was looking for:</p> <p><a href="http://wiki.netbeans.org/FaqCustomLaf" rel="nofollow noreferrer">http://wiki.netbeans.org/FaqCustomLaf</a></p>
38,942
<p>Is there a way to limit the rows returned at the Oracle datasource level in a Tomcat application?</p> <p>It seems <code>maxRows</code> is only available if you set it on the datasource in the Java code. Putting <code>maxRows="2"</code> on the datasource doesn't apply.</p> <p>Is there any other way limit the rows returned? Without a code change?</p>
<p>It isn't something that is available at the configuration level. You may want to double check that it does what you want it to do anyway: <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html#setMaxRows(int)" rel="nofollow noreferrer">see the javadoc for setMaxRows</a>. With Oracle it is still going to fetch every row back for the query and then just drop the ones outside the range. You would really need to use rownum to make it work well with Oracle and you can't do that either in the configuration.</p>
<p>If you know you will be dealing with only one table, then define a view with rownum in the where statement to limit the number of rows. In this way, the number of rows is controlled at the DB and does not need to be specified as part of any query from a client application. If you want to change the number of rows returned, then redefine the view prior to executing query.</p> <p>A more dynamic method would be to develop a procedure and pass in a number of rows, and have the procedure return a ref_cursor to your client. This would have the advantage of avoiding hard parsing on the DB, and increase performance. </p>
41,432
<p>I am writing an application that needs to bring window of an external app to the foreground, and not necessarily steal focus (there is a setting the user can toggle to steal/not steal focus).</p> <p>What is the best way to go about this using the win32 API? I have tried SetForeground() but it always steals focus and does not consistenly work.</p> <p>What is the best way to go about this? Any thoughts?</p>
<p>SetForegroundWindow is supposed to steal focus and there are certain cases where it will fail.</p> <blockquote> <p>The SetForegroundWindow function puts the thread that created the specified window into the foreground and activates the window. Keyboard input is directed to the window</p> </blockquote> <p>Try capturing the focus with <a href="http://msdn.microsoft.com/en-us/library/ms646262.aspx" rel="noreferrer">SetCapture</a> prior to making the call. Also look into different ways of bringing the window to the front: SetForeGroundWindow, SetActiveWindow, even simulating a mouse click can do this.</p>
<p>You could use FindWindow to get the HWND of the window, then use the BringWindowToTop function found in the Win32 API.</p>
2,511
<p>I was looking into <a href="https://stackoverflow.com/questions/120936/can-i-add-custom-version-strings-to-a-net-dll">embedding custom version strings</a> using in assemblies a while back, and one approach that the documentation suggested was to embed a windows resource.</p> <p>The only way I can see to create a windows resource is to use the 'Native Resource Template', but the template is a binary file that isn't suitable for using with <a href="http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-subwcrev.html" rel="nofollow noreferrer">subwcrev</a>. Is there a way of creating a windows resource as part of a C# project that starts with a human-editable text file, similarly to the .rc files that C++ projects use? If so, how?</p>
<p>It seems that you don't have VS2005 or VS2008 and are looking to create windows resources. Yes, the ".resources" files are binary, but you can create a XML file or a text file which gets converted to this binary file. Take a look at the documentation of the <a href="http://msdn.microsoft.com/en-us/library/ccec7sz1(VS.80).aspx" rel="nofollow noreferrer">ResGen</a> tool. It is available with .NET.</p>
<p>In VisualStudio 2005 or 2008 (at least), you can add a new "Resources File" item to the project (located under "General" in the "Add new item" dialog). This is a simple XML file, which is perfectly human-editable - all within VisualStudio. I don't know how SubWCRev works, but if it manipulates text files, this should do it.</p>
24,462
<p>I'd like to develop an ecommerce site where I could allow others to sell items, things like pictures, videos, flash, etc. I want to be able to keep a percentage, and pay the rest back to the seller.</p> <p>Is there anything available, DotNetNuke, etc. that would do this or help get this started. If not what's a good way to approach this with the goal to avoid upfront time and cost.</p> <p>I'd like to think there would be some revenue that could be reinvested over time, so might grow into something that has some cost after a while.</p>
<p>You should have a look at <a href="http://www.oscommerce.com/" rel="nofollow noreferrer">osCommerce</a>. </p>
<p>You could use DotNetNuke, or another similar framework if you have additional content that you need to include other than the shopping.</p> <p>If you went with DotNetNuke, you could look at the Catalook store which I believe supports your desired format for selling. It isn't perfect, but it does work, eventually with a little experience. Otherwise ASP .NET Storefront might have what you need as well, either in a DNN based version or their standalone.</p>
28,885
<p>Perhaps this question is not very clear but I didn't find better words for the heading, which describes the problem I like to deal with shortly.</p> <p>I want to restrict access from a java desktop application to postgres. </p> <p><strong>The background:</strong></p> <p>Suppose you have 2 apps running and the first Application has to do some complex calculations on the basis of data in the db. To nail the immutability of the data in the db down i'd like to lock the db for insert, update and delete operations. On client side i think it's impossible to handle this behaviour satisfactory. So i thought about to use a little java-app on server-side which works like a proxy. So the task is to hand over CRUD (Create Read Update Delete) operations until it gets a command to lock. After a lock it rejects all CUD operations until it gets a unlock command from the locking client or a timeout is reached.</p> <p><strong>Questions:</strong></p> <p>What do you think about this approach?</p> <p>Is it possible to lock a Database while using such an approach?</p> <p>Would you prefer Java SE or Java EE as server-side java app?</p> <p>Thanks in advance.</p>
<p>Why not use <a href="http://www.postgresql.org/docs/8.3/static/mvcc.html" rel="nofollow noreferrer">transactions</a> in your operations? The database has features to maintain data integrity itself, rather than resorting to a brute operation such as a total-database lock.</p> <p>This locking mechanism you describe sounds like it would be a pain for the users. Are the users initating the lock or is the software itself? If it's the users, you can expect some problems when Bob hits lock and then goes to lunch for 2 hours, forgetting to unlock the database first...</p>
<p>Year i thought about transactions but in this case i can't use them. I'm sorry i didn't mention it exactly. So assume the follow easy case: A calculation closes one area of responsibility. After calc a new one is opened and new inserts are dedicated to it. But while calculation-process a insert or update or delete is not allowed to the data of the (currently calculated) area of responsibility. More over a delete is strictly prohibited because data has to be archived.</p> <p>So imo the use of transactions doesn't fit this requirement. Or did i miss sth.?</p> <p>ps: (off topic) @jsight: i currently read that intenally postgres mapps "repeatable read" to "serializable", so using "repeatable read" gets you more restriction then you would perhaps expect.</p>
28,533
<p>I am looking for a piece of software that I can schedule to check that our web apps are up and running. I've used HP open view years ago, but remember it being quite expensive, I'm looking for something open source or cheap. </p> <p>So it would login in and do some simple actions maybe submit form and check for some text on screen that means the web app is running ok and then email me if the website is down. </p> <p>I could create a test using the Selenium IDE, and automate it with an Ant script but looking for a more streamlined solution that a non programming could use. </p> <p>Any suggestions? </p> <p>Thanks, Scotty</p>
<p>Decided on site24x7 does login and has a rest api to call to get stats - <a href="http://site24x7.com/index.html" rel="nofollow">site24x7.com/index.html</a> </p>
<p>You can use cron to perform the tests. Cron will run the tests after a specified amount of time such as once per hour.</p> <p>Cron is available in Linux but there are Windows alternatives which you can download. Or you can use Windows' task scheduler.</p>
29,633
<p>I have some C# / asp.net code I inherited which has a textbox which I want to make multiline. I did so by adding textmode="multiline" but when I try to insert a newline, the enter key instead submits the form :P</p> <p>I googled around and it seems like the default behavior should be for enter (or control-enter) to insert a newline. Like I said I inherited the code so I'm not sure if there's javascript monkeying around or if there's just a simple asp.net thing I have to do.</p>
<p>It turns out this is a bug with Firefox + ASP.NET where the generated javascript for the defaultButton stuff doesn't work in Firefox. I had to put a replacement for the WebForm_FireDefatultButton function as described <a href="http://forums.asp.net/t/1294544.aspx" rel="nofollow noreferrer">here</a>:</p> <pre><code>function WebForm_FireDefaultButton(event, target) { var element = event.target || event.srcElement; if (event.keyCode == 13 &amp;&amp; !(element &amp;&amp; element.tagName.toLowerCase() == "textarea")) { var defaultButton; if (__nonMSDOMBrowser) { defaultButton = document.getElementById(target); } else { defaultButton = document.all[target]; } if (defaultButton &amp;&amp; typeof defaultButton.click != "undefined") { defaultButton.click(); event.cancelBubble = true; if (event.stopPropagation) { event.stopPropagation(); } return false; } } return true; } </code></pre>
<p>you can use \n for enter key i.e. [a-zA-Z 0-9/.\n]{20,500}</p>
5,011
<p>i'm using ASP.net with .NET 3.5 on IIS7 (Vista) with the URL Rewrite Module from Microsoft.</p> <p>This means, that i have a </p> <pre><code>&lt;system.webServer&gt; &lt;rewrite&gt;...&lt;/rewrite&gt; ... &lt;/system.webServer&gt; </code></pre> <p>section within the web.config, but i get a warning, that within the system.webServer the element "rewrite" is not allowed.</p> <p>How can i configure my system to allow (and maybe even have Intellisense) on the rewrite-part of the web.config?</p> <p>Thank you Christoph</p>
<p>I was able to get this working in Visual Studio 2010.</p> <p>Start with Ruslan's post <a href="http://ruslany.net/2010/04/visual-studio-xml-intellisense-for-url-rewrite-2-0/" rel="noreferrer">here</a> and download the 2.0 IntelliSense file. Then, just follow the directions he posted previously <a href="http://ruslany.net/2009/08/visual-studio-xml-intellisense-for-url-rewrite-1-1/" rel="noreferrer">here</a>. All I ended up doing was running the following command as Ruslan instructs:</p> <p><code>C:\download_directory\rewrite2_intellisense&gt;cscript UpdateSchemaCache.js</code></p> <p>As Christoph points out in his comment, make sure you replace <code>VS90COMNTOOLS</code> with <code>VS100COMNTOOLS</code> in UpdateSchemaCache.js before running the above command if you are using Visual Studio 2010.</p> <p>I did not need to restart Visual Studio. I added the <code>&lt;rewrite&gt;</code> section only to the applicable Web.config transformation files, as having it in the main Web.config breaks local debugging.</p>
<p>I believe you need to have the URL Rewrite Module "installed" within the web.config file on your system.</p> <p>You either need to install the module on your application via the IIS 7.0 interface or have your hosting firm do it for you.</p>
47,425
<p>I have a strongly typed user control ("partial") and I'd like to be able to pass it some additional information from its containing view. For example, I have view that's bound to a product class and i have a partial that also is strongly typed to that same model, but I also need to pass an additional parameter for imageSize to my partial. I'd like to be able to do something like this:</p> <pre><code>&lt;% Html.RenderPartial("_ProductImage", ViewData.Model, new { imageSize = 100 }); %&gt; </code></pre> <p>As far as I know there is no way to do this, but I'm hoping that someone smarter than me may have a solution ;)</p>
<p>Change the type of the partial model:</p> <pre><code>class PartialModel { public int ImageSize { get; set; } public ParentModelType ParentModel { get; set; } } </code></pre> <p>Now pass it:</p> <pre><code>&lt;% Html.RenderPartial("_ProductImage", new PartialModel() { ImageSize = 100, ParentModel = ViewData.Model }); %&gt; </code></pre>
<p>I use a generic class model - which is similar in concept to the approach suggested by Craig.</p> <p>I kind of wish MS would create an overload to <code>RenderPartial</code> to give us the same functionality. Just an additional <code>object data</code> parameter would be fine.</p> <p>Anyway, my approach is to create a PartialModel which uses generics so it can be used for all .ascx controls.</p> <pre><code> public class PartialControlModel&lt;T&gt; : ModelBase { public T ParentModel { get; set; } public object Data { get; set; } public PartialControlModel(T parentModel, object data) : base() { ParentModel = parentModel; Data = data; } } </code></pre> <p>The .ascx control should inherit from the correct <code>PartialControlModel</code> if you want the view to be strongly typed, which most likely you do if you've got this far.</p> <pre><code>public partial class ThumbnailPanel : ViewUserControl&lt;PartialControlModel&lt;GalleryModel&gt;&gt; </code></pre> <p>Then you render it like this :</p> <pre><code>&lt;% Html.RenderPartial("ThumbnailPanel", new PartialControlModel&lt;GalleryModel&gt;(ViewData.Model, tag)); %&gt; </code></pre> <p>Of course when you refer to any parent model items you must use this syntax :</p> <pre><code>ViewData.Model.ParentModel.Images </code></pre> <p>You can get the data and cast it to the correct type with :</p> <pre><code>ViewData.Model.Data </code></pre> <p>If anyone has a suggestion on how to improve the generics I'm using please let me know.</p>
48,273
<p>I'm working on an application that needs to quickly render simple 3D scenes on the server, and then return them as a JPEG via HTTP. Basically, I want to be able to simply include a dynamic 3D scene in an HTML page, by doing something like:</p> <pre><code>&lt;img src="http://www.myserver.com/renderimage?scene=1&amp;x=123&amp;y=123&amp;z=123"&gt; </code></pre> <p>My question is about what technologies to use to do the rendering. In a desktop application I would quite naturally use DirectX, but I'm afraid it might not be ideal for a server-side application that would be creating images for dozens or even hundreds of users in tandem. Does anyone have any experience with this? Is there a 3D API (preferably freely available) that would be ideal for this application? Is it better to write a software renderer from scratch?</p> <p>My main concerns about using DirectX or OpenGL, is whether it will function well in a virtualized server environment, and whether it makes sense with typical server hardware (over which I have little control). </p>
<p>RealityServer by mental images is designed to do precisely what is described here. More details are available on the product page (including a downloadable Developer Edition).</p> <p><a href="http://www.migenius.com/doc/realityserver/latest/" rel="nofollow noreferrer">RealityServer docs</a></p>
<p>Check out <a href="http://www.wgpu.net" rel="nofollow">wgpu.net</a>.</p> <p>I think it's very helpful.</p>
8,982
<p>Which is better to use in PHP, a 2D array or a class? I've included an example of what I mean by this.</p> <pre><code>// Using a class class someClass { public $name; public $height; public $weight; function __construct($name, $height, $weight) { $this -&gt; name = $name; $this -&gt; height = $height; $this -&gt; weight = $weight; } } $classArray[1] = new someClass('Bob', 10, 20); $classArray[2] = new someClass('Fred', 15, 10); $classArray[3] = new someClass('Ned', 25, 30); // Using a 2D array $normalArray[1]['name'] = 'Bob'; $normalArray[1]['height'] = 10; $normalArray[1]['weight'] = 20; $normalArray[2]['name'] = 'Fred'; $normalArray[2]['height'] = 15; $normalArray[2]['weight'] = 10; $normalArray[3]['name'] = 'Ned'; $normalArray[3]['height'] = 25; $normalArray[3]['weight'] = 30; </code></pre> <hr> <p>Assuming that somebody doesn't come out and show that classes are too slow, it looks like class wins.</p> <p>I've not idea which answer I should accept to I've just upvoted all of them.</p> <hr> <p>And I have now written two near identical pages, one using the 2D array (written before this question was posted) and now one using a class and I must say that the class produces much nicer code. I have no idea how much overhead is going to be generated but I doubt it will rival the improvement to the code itself.</p> <p>Thank you for helping to make me a better programmer.</p>
<p>The "class" that you've constructed above is what most people would use a <em>struct</em> for in other languages. I'm not sure what the performance implications are in PHP, though I suspect instantiating the objects is probably more costly here, if only by a little bit.</p> <p>That being said, if the cost is relatively low, it IS a bit easier to manage the objects, in my opinion.</p> <p>I'm only saying the following based on the title and your question, but: Bear in mind that classes provide the advantage of methods and access control, as well. So if you wanted to ensure that people weren't changing weights to negative numbers, you could make the <code>weight</code> field private and provide some accessor methods, like <code>getWeight()</code> and <code>setWeight()</code>. Inside <code>setWeight()</code>, you could do some value checking, like so:</p> <pre><code>public function setWeight($weight) { if($weight &gt;= 0) { $this-&gt;weight = $weight; } else { // Handle this scenario however you like } } </code></pre>
<p>If your code uses lot of functions that operate on those attributes (name/height/weight), then using class could be a good option.</p>
4,388
<p>I'm interested: What is C#'s analog of <code>std::pair</code> in C++? I found <code>System.Web.UI.Pair</code> class, but I'd prefer something template-based.</p> <p>Thank you!</p>
<p>Tuples <a href="http://msdn.microsoft.com/en-us/library/system.tuple(v=vs.110).aspx" rel="noreferrer">are available since .NET4.0</a> and support generics:</p> <pre><code>Tuple&lt;string, int&gt; t = new Tuple&lt;string, int&gt;("Hello", 4); </code></pre> <hr> <p>In previous versions you can use <code>System.Collections.Generic.KeyValuePair&lt;K, V&gt;</code> or a solution like the following:</p> <pre><code>public class Pair&lt;T, U&gt; { public Pair() { } public Pair(T first, U second) { this.First = first; this.Second = second; } public T First { get; set; } public U Second { get; set; } }; </code></pre> <p>And use it like this:</p> <pre><code>Pair&lt;String, int&gt; pair = new Pair&lt;String, int&gt;("test", 2); Console.WriteLine(pair.First); Console.WriteLine(pair.Second); </code></pre> <p>This outputs:</p> <pre><code>test 2 </code></pre> <p>Or even this chained pairs:</p> <pre><code>Pair&lt;Pair&lt;String, int&gt;, bool&gt; pair = new Pair&lt;Pair&lt;String, int&gt;, bool&gt;(); pair.First = new Pair&lt;String, int&gt;(); pair.First.First = "test"; pair.First.Second = 12; pair.Second = true; Console.WriteLine(pair.First.First); Console.WriteLine(pair.First.Second); Console.WriteLine(pair.Second); </code></pre> <p>That outputs:</p> <pre><code>test 12 true </code></pre>
<p>On order to get the above to work (I needed a pair as the key of a dictionary). I had to add:</p> <pre><code> public override Boolean Equals(Object o) { Pair&lt;T, U&gt; that = o as Pair&lt;T, U&gt;; if (that == null) return false; else return this.First.Equals(that.First) &amp;&amp; this.Second.Equals(that.Second); } </code></pre> <p>and once I did that I also added</p> <pre><code> public override Int32 GetHashCode() { return First.GetHashCode() ^ Second.GetHashCode(); } </code></pre> <p>to suppress a compiler warning.</p>
20,056
<p>In javascript, we can do:</p> <pre><code>["a string", 10, {x : 1}, function() {}].push("another value"); </code></pre> <p>What is the Scala equivalent?</p>
<p>Arrays in Scala are very much homogeneous. This is because Scala is a statically typed language. If you really need pseudo-heterogeneous features, you need to use an immutable data structure that is parametrized covariantly (most immutable data structures are). <code>List</code> is the canonical example there, but <a href="http://www.codecommit.com/blog/misc/implementing-persistent-vectors-in-scala/final/Vector.scala" rel="noreferrer"><code>Vector</code></a> is also an option. Then you can do something like this:</p> <pre><code>Vector("a string", 10, Map("x" -&gt; 1), ()=&gt;()) + "another value" </code></pre> <p>The result will be of type <code>Vector[Any]</code>. Not very useful in terms of static typing, but everything will be in there as promised.</p> <p>Incidentally, the "literal syntax" for <em>arrays</em> in Scala is as follows:</p> <pre><code>Array(1, 2, 3, 4) // =&gt; Array[Int] containing [1, 2, 3, 4] </code></pre> <p><strong>See also</strong>: <a href="http://www.codecommit.com/blog/scala/implementing-persistent-vectors-in-scala/" rel="noreferrer">More info on persistent vectors</a></p>
<p>Scala might get the ability for a "heterogeneous" list soon: <a href="http://jnordenberg.blogspot.com/2008/09/hlist-in-scala-revisited-or-scala.html" rel="nofollow noreferrer">HList in Scala</a></p>
22,499
<p>I do mostly Java and C/C++ development, but I'm starting to do more web development (PHP, Rails) and Eiffel (learning a new language is always good).</p> <p>Currently, I use Eclipse for Java, C/C++, and Ruby (not Rails). Since I know the environment, I'm thinking that it would be easier for me to find a plugin and use Eclipse for all of my development languages. But are there cases where a language-specific IDE (EiffelStudio for Eiffel, as an example) would be better than Eclipse?</p>
<p>I have used many many IDE's and in most cases to me it breaks down to personal preferences. Sometimes the language specific ones have some addins/addons/features that are nice but unless they are things you can not live without you should go with what is most comfortable for you.</p> <p>I would think that if you are comfortable with the multi-language IDE it would be better to stick with that one. This way you dont have to memorize multiple IDE layouts, keyboard shortcuts etc.</p>
<p>It entirely depends on the user and the language itself, if you are comfortable with the keyboard shortcuts then you can consider the plugin else you can go for a IDE . However most of the IDE comes with a cross-functional key maps so you use the key maps which u are more comfortable with.... </p>
7,292
<p>How do I launch an app and capture the output via stdout and maybe stderr?</p> <p>I am writing an automated build system and I need to capture the output to analyze. I'd like to update the svn repo and grab the revision number so I can move the files in autobuild/revNumber/ if successful. I also would like to build using make and upload the compile text to my server for everyone to see the warnings and errors on a failed build.</p> <p>I can't find the <code>system()</code> function, but I found the <code>CreateProcess()</code> function on MSDN. I am able to launch what I need but I have no idea how to capture the stderr and stdout. I notice the process launches separately unless I set a breakpoint and keep my app exiting which it then will keep all the text in my app console window. I would also want to wait until all processes are finished and then scan the data it produced to do any additional operations I need. How do I do any of this?</p>
<p>In real shells (meaning, not sea shells - I mean, not in C Shell or its derivatives), then:</p> <pre><code>program arg1 arg2 &gt;/tmp/log.file 2&gt;&amp;1 </code></pre> <p>This runs program with the given arguments, and redirects the stdout to /tmp/log.file; the notation (<del>hieroglyph</del>) '<code>2&gt;&amp;1</code>' at the end sends stderr (file descriptor 2) to the same place that stdout (file descriptor 1) is going. Note that the sequence of operations is important; if you reverse them, then standard error will go to where standard output was going, and then standard output (but not standard error) will be redirected to the file.</p> <p>The choice of file name shown is abysmal for numerous reasons - you should allow the user to choose the directory, and probably should include the process ID or time stamp in the file name.</p> <pre><code>LOG=${TMPDIR:-/tmp}/log.$$.$(date +%Y%m%d-%H%M%S) program arg1 arg2 &gt;$LOG 2&gt;&amp;1 </code></pre> <p>In C++, you can use the <code>system()</code> function (inherited from C) to run processes. If you need to know the file name in the C++ program (plausible), then generate the name in the program (<code>strftime()</code> is your friend) and create the command string with that file name. (Strictly, you also need <code>getenv()</code> to get $TMPDIR, and the POSIX function <code>getpid()</code> to get the process ID, and then you can simulate the two-line shell script (though the PID used would be of the C++ program, not the launched shell).</p> <p>You could instead use the POSIX <code>popen()</code> function; you'd have to include the '<code>2&gt;&amp;1</code>' notation in the command string that you create to send the standard error of the command to the same place as standard output goes, but you would not need a temporary file:</p> <pre><code>FILE *pp = popen("program arg1 arg2 2&gt;&amp;1", "r"); </code></pre> <p>You can then read off the file stream. I'm not sure whether there's a clean way to map a C file stream into a C++ istream; there probably is.</p>
<p>Microsoft's CRTs and the MSDN library do include the system function and the _popen function.</p>
38,553
<p>I have two threads, one updating an int and one reading it. This is a statistic value where the order of the reads and writes is irrelevant.</p> <p>My question is, do I need to synchronize access to this multi-byte value anyway? Or, put another way, can part of the write be complete and get interrupted, and then the read happen.</p> <p>For example, think of a value = 0x0000FFFF that gets incremented value of 0x00010000.</p> <p>Is there a time where the value looks like 0x0001FFFF that I should be worried about? Certainly the larger the type, the more possible something like this to happen.</p> <p>I've always synchronized these types of accesses, but was curious what the community thinks.</p>
<p>At first one might think that reads and writes of the native machine size are atomic but there are a number of issues to deal with including cache coherency between processors/cores. Use atomic operations like Interlocked* on Windows and the equivalent on Linux. C++0x will have an "atomic" template to wrap these in a nice and cross-platform interface. For now if you are using a platform abstraction layer it may provide these functions. <a href="http://www.cse.wustl.edu/~schmidt/ACE.html" rel="noreferrer">ACE</a> does, see the class template <a href="http://www.dre.vanderbilt.edu/~schmidt/DOC_ROOT/ACE/ace/Atomic_Op.inl" rel="noreferrer">ACE_Atomic_Op</a>.</p>
<p>The only portable way is to use the sig_atomic_t type defined in signal.h header for your compiler. In most C and C++ implementations, that is an int. Then declare your variable as "volatile sig_atomic_t."</p>
7,779
<p>For general code, do I really need to dispose an object? Can I just ignore it for the most part or is it a good idea to always dispose an object when your 100% sure you don't need it anymore? </p>
<p>Dispose of an object the instant your are done with it. Disposable objects represent objects holding a valuable resource which the CLR is not intrinsically aware of. Consequently the GC is also unaware of the resources and is unable to make intelligent decisions as to when it should collect a disposable object and hence free the underlying resource. </p> <p>Eventually the GC will feel memory pressure and collect your object by coincidence (nothing more). If you don't dispose of objects in a deterministic manner then it is completely possible to enter a resource starved state with almost no memory pressure. </p> <p>Quick example of how this can happen. Lets think of the underlying resource as Win32 handle. These are very finite and fairly small. You run an operation that create a lot of Foo objects. Foo objects implement IDisposable and are responsible for creating and disposing of a Win32 handle. They are not manually freed and by a difference quirk make it into the Gen2 heap. This heap is freed fairly infrequently. Over time enough Foo instances make it into the Gen2 heap to take up all of the available handles. New Foo objects are consequently unable to be created regardless of how much memory is being used.</p> <p>In fact to free the handles, it would take a rather large amount of memory to be allocated during a single operation to give enough pressure to free the instances. </p>
<p>Relying on the GC 'works' in most instances. The classic exception is when you have a resource heavy interaction - in that instance it is best to explicilty dispose.</p> <p>obvious eg.</p> <pre><code>using (var conn = new SqlConnection(connString)) {} </code></pre> <p>'Using' blocks are definitely the cleanest and most robust method of ensuring that objects are disposed of correctly. 'Using' blocks can be leveraged with any objects that implements IDisposable.</p>
30,504
<p>In oracle, I want to create a delete sproc that returns an integer based on the outcome of the deletion.</p> <p>this is what i have so far.</p> <pre><code>create or replace PROCEDURE Testing ( iKey IN VARCHAR2 ) AS BEGIN delete from MyTable WHERE TheKey = iKey; END Testing; </code></pre> <p>i've tried putting a RETURNS INTEGER in but the sproc won't compile.</p>
<p>A procedure does not return a value. A function returns a value, but you shouldn't be doing DML in a function (otherwise you cannot do things like reference the function in a SQL statement, you confuse permission grants since normally DBAs want to be able to grant read-only users access to all the functions so that users are doing computations consistently, etc.).</p> <p>You can add an OUT parameter to the procedure to return the status. If "success" means that one or more rows were updated, you can use SQL%ROWCOUNT to get a count of the number of rows modified by the prior SQL statement and use that to populate the return parameter, i.e.</p> <pre><code>CREATE OR REPLACE PROCEDURE test_proc ( p_iKey IN VARCHAR2, p_retVal OUT INTEGER ) AS BEGIN DELETE FROM myTable WHERE theKey = p_iKey; IF( SQL%ROWCOUNT &gt;= 1 ) THEN p_retVal := 1; ELSE p_retVal := 0; END IF; END test_proc; </code></pre> <p>Of course, from a general code clarity standpoint, I'm dubious about OUT parameters that appear to be trying to return a status code. You are generally much better served by assuming success and throwing exceptions in the event of an error.</p>
<p>You are probably looking for a function instead. </p> <pre><code>FUNCTION TESTING (iKEY IN VARCHAR2) RETURN NUMBER IS v_count NUMBER; yourNumber NUMBER; BEGIN SELECT COUNT(*) INTO v_count FROM MyTable WHERE TheKey = iKey; IF v_count &gt; 0 THEN DELETE FROM MyTable WHERE TheKey = iKey; SELECT COUNT(*) INTO v_count FROM MyTable WHERE TheKey = iKey; IF (v_count = 0) THEN yourNumber := 1; --means successful deletion END IF; ELSE yourNumber := 0; --means no items to delete END IF; return yourNumber; EXCEPTION WHEN OTHERS THEN RETURN -1; --means error was encountered END TESTING; </code></pre> <p>Note: Where I work we generally put functions inside a sql package.</p>
32,826
<p>I assist in maintaining an enterprise web-based system (programmed in J2EE, but this is a more general question) and I'd like to know: what good tools are out there to measure the "health" of an enterprise system? For instance, tools to check memory space on servers, check the status of batch runs, the number of records processed in a certain amount of time, etc?</p> <p>I don't wish to limit this to one tool per answer, though, multiple tools per answer are certainly acceptable.</p>
<p><a href="https://www.opennms.org/en/opennms/the-platform" rel="nofollow noreferrer">OpenNMS</a> is a nice monitoring tool. Out of the box it can monitor various aspects of a server, mostly things like memory, network usage, disk space. But it's open source, and can be extended to monitor other things. </p> <p>We use it to monitor thousands of services. It's very good at what it does.</p> <p>It may not be a good fit for the number of records processed, at least we don't use it that way.</p>
<p>+1 for OpenNMS. In addition to its out-of-the-box system-level monitoring, it can be easily extended with JMX, so your applications can expose their innards as JMX attributes, and OpenNMS can monitor them, graph them, raise alerts based on them, etc.</p> <p>We've also extended OpenNMS to send SMS alerts when things go wonky.</p>
16,995
<p>What's the easiest way of me converting the simpler regex format that most users are used to into the correct re python regex string?</p> <p>As an example, I need to convert this:</p> <pre><code>string = "*abc+de?" </code></pre> <p>to this:</p> <pre><code>string = ".*abc.+de.?" </code></pre> <p>Of course I could loop through the string and build up another string character by character, but that's surely an inefficient way of doing this?</p>
<p>Those don't look like regexps you're trying to translate, they look more like unix shell globs. Python has a <a href="http://www.python.org/doc/2.5.2/lib/module-fnmatch.html" rel="nofollow noreferrer">module</a> for doing this already. It doesn't know about the "+" syntax you used, but neither does my shell, and I think the syntax is nonstandard.</p> <pre><code>&gt;&gt;&gt; import fnmatch &gt;&gt;&gt; fnmatch.fnmatch("fooabcdef", "*abcde?") True &gt;&gt;&gt; help(fnmatch.fnmatch) Help on function fnmatch in module fnmatch: fnmatch(name, pat) Test whether FILENAME matches PATTERN. Patterns are Unix shell style: * matches everything ? matches any single character [seq] matches any character in seq [!seq] matches any char not in seq An initial period in FILENAME is not special. Both FILENAME and PATTERN are first case-normalized if the operating system requires it. If you don't want this, use fnmatchcase(FILENAME, PATTERN). &gt;&gt;&gt; </code></pre>
<p>I'd use <a href="http://www.python.org/doc/2.5.2/lib/string-methods.html#l2h-255" rel="nofollow noreferrer"><code>replace</code></a>:</p> <pre><code>def wildcard_to_regex(str): return str.replace("*", ".*").replace("?", .?").replace("#", "\d") </code></pre> <p>This probably isn't the most efficient way but it should be efficient enough for most purposes. Notice that some wildcard formats allow character classes which are more difficult to handle.</p>
26,784
<p>Is it possible to detect, on the client side, whether the user is using an encrypted page or not?</p> <p>Put another way -- I want to know if the URL of the current page starts with http or https.</p>
<p>Use <code>window.location.protocol</code> to check if it is <code>https:</code></p> <pre><code>function isSecure() { return window.location.protocol == 'https:'; } </code></pre> <p>Alternatively you can omit specifying "window" if you don't have a locally scoped location.</p> <pre><code>function isSecure() { return location.protocol == 'https:'; } </code></pre>
<p>Second method for newest browsers: </p> <pre><code>var secure = window.isSecureContext; </code></pre> <p>or just get isSecureContext:</p> <pre><code>if (isSecureContext) { ... } </code></pre> <p>More here: <a href="https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts#Feature_detection#Feature_detection" rel="nofollow noreferrer">https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts#Feature_detection#Feature_detection</a></p>
35,766
<p>I am trying to read an XML-file from another server. However the the company that's hosting me seems to have turned of the file_get_contents function from retrieving files for files from other servers (and their support is not very bright and it takes forever for them to answer). So I need a work around in some way.</p> <p>This is my current code</p> <pre><code> $url = urldecode( $object_list_url ); $xmlstr = file_get_contents ( $url ); $obj = new SimpleXMLElement ( $xmlstr, LIBXML_NOCDATA ); </code></pre>
<p>You could use <a href="http://www.php.net/curl" rel="nofollow noreferrer">cURL</a> (if that's not been disabled). Something like this:</p> <pre><code>$c = curl_init($url); curl_setopt($c, CURLOPT_RETURNTRANSFER, true); $xmlstr = curl_exec($c); </code></pre>
<p>The ini var you're referring to is <code>allow_url_fopen</code>. To check, run this script:</p> <pre><code>var_dump(ini_get('allow_url_fopen')); </code></pre> <p>Ask your host to turn that ini value on (if it's disabled - it's on by default).</p> <p>You should not be able to access any remote url without that ini setting on.</p> <p>Also an idea if they won't could be to try <a href="http://docs.php.net/manual/en/function.copy.php" rel="nofollow noreferrer"><code>copy</code></a>ing the file to your server. I expect all filesystem functions will be covered by that ini setting but it's always worth a try.</p>
30,265
<p>Does anyone happen to know if there is a token I can add to my csv for a certain field so Excel doesn't try to convert it to a date?</p> <p>I'm trying to write a .csv file from my application and one of the values happens to look enough like a date that Excel is automatically converting it from text to a date. I've tried putting all of my text fields (including the one that looks like a date) within double quotes, but that has no effect.</p>
<p>I have found that putting an '=' before the double quotes will accomplish what you want. It forces the data to be text.</p> <p>eg. ="2008-10-03",="more text"</p> <p><strong>EDIT (according to other posts)</strong>: because of the <a href="https://stackoverflow.com/a/4412775/684229">Excel 2007 bug noted by Jeffiekins</a> one should use the <a href="https://stackoverflow.com/a/6023847/684229">solution proposed by Andrew</a>: <code>"=""2008-10-03"""</code></p>
<p>If you put an inverted comma at the start of the field, it will be interpreted as text.</p> <p>Example: <code>25/12/2008</code> becomes <code>'25/12/2008</code></p> <p>You are also able to select the field type when importing.</p>
19,948
<p>I am currently tasked with developing a tool to use JMX to monitor JVMs for things like, but not limited too, memory usage, heap size, thread count. The desired tool is one that can display many graphs for each jvm next to each other (example below). </p> <p>So the question is it best to build your own? Use another tool that is out there? (if so which one(s)) Or is there a tool that has a license, which I can build off of?</p> <p>Example: (Each JVM has many graphs that are viewable at once so you can see if a specific application / server / jvm is acting up fairly easily.</p> <ol> <li>JVM1: PermGen graph, Heap Size graph, Threads graph</li> <li>JVM2: PermGen graph, Heap Size graph, Threads graph</li> <li>JVM3: PermGen graph, Heap Size graph, Threads graph</li> </ol> <p>***Edit: "You forgot the third option... Buy one." Any in particular that could match those requirements? or be extensible enough to handle them?</p>
<p>Sounds like what both jConsole and VisualVM do - both are distributed with JDK-6.</p>
<p><a href="http://jcp.org/en/jsr/detail?id=262" rel="nofollow noreferrer">Web Services Connector for Java Management Extensions (JMX) Agents</a>, which seem to be planned for Java 7, offer an easy way to implement such a tool in any language. It is a web service / http based JMX agent standard, and can also be used to request diagnostic information from the JVM.</p> <p>Actually I am trying this with Delphi and it works quite good already (using the reference implementation <a href="https://ws-jmx-connector.dev.java.net/" rel="nofollow noreferrer">ws-jmx-connector</a>). It is already a very JConsole-like application, but without graphs.</p> <p>I will try to implement a graphical monitor view in a free demo application for my library, which is not yet available for public download. </p>
41,064
<p>How should I store (and present) the text on a website intended for worldwide use, with several languages? The content is mostly in the form of 500+ word articles, although I will need to translate tiny snippets of text on each page too (such as "print this article" or "back to menu").</p> <p>I know there are several CMS packages that handle multiple languages, but I have to integrate with our existing ASP systems too, so I am ignoring such solutions.</p> <p>One concern I have is that Google should be able to find the pages, even for foreign users. I am less concerned about issues with processing dates and currencies.</p> <p>I worry that, left to my own devices, I will invent a way of doing this which work, but eventually lead to disaster! I want to know what professional solutions you have actually used on real projects, not untried ideas! Thanks very much.</p> <hr> <p>I looked at RESX files, but felt they were unsuitable for all but the most trivial translation solutions (I will elaborate if anyone wants to know).</p> <p>Google will help me with translating the text, but not storing/presenting it.</p> <p>Has anyone worked on a multi-language project that relied on their own code for presentation?</p> <hr> <p>Any thoughts on serving up content in the following ways, and which is best?</p> <ul> <li><a href="http://www.website.com/text/view.asp?id=12345&amp;lang=fr" rel="nofollow noreferrer">http://www.website.com/text/view.asp?id=12345&amp;lang=fr</a></li> <li><a href="http://www.website.com/text/12345/bonjour_mes_amis.htm" rel="nofollow noreferrer">http://www.website.com/text/12345/bonjour_mes_amis.htm</a></li> <li><a href="http://fr.website.com/text/12345" rel="nofollow noreferrer">http://fr.website.com/text/12345</a></li> </ul> <p>(these are not real URLs, i was just showing examples)</p>
<p>Firstly put all code for all languages under one domain - it will help your google-rank.</p> <p>We have a fully multi-lingual system, with localisations stored in a database but cached with the web application.</p> <p>Wherever we want a localisation to appear we use:</p> <pre><code>&lt;%$ Resources: LanguageProvider, Path/To/Localisation %&gt; </code></pre> <p>Then in our web.config:</p> <pre><code>&lt;globalization resourceProviderFactoryType="FactoryClassName, AssemblyName"/&gt; </code></pre> <p><code>FactoryClassName</code> then implements <code>ResourceProviderFactory</code> to provide the actual dynamic functionality. Localisations are stored in the DB with a string key "Path/To/Localisation"</p> <p>It is important to cache the localised values - you don't want to have lots of DB lookups on each page, and we cache thousands of localised strings with no performance issues.</p> <p>Use the user's current browser localisation to choose what language to serve up.</p>
<p>If you're just worried about the article content being translated, and do not need a fully integrated option, I have used <a href="http://www.google.com/language_tools" rel="nofollow noreferrer">google translation</a> in the past and it works great on a smaller scale.</p>
9,802
<p>We have a WinForms application which runs on a touch-screen on a bit of industrial equipment. For historical reasons which are not up for changing today, the displayed form has a normal Windows title bar. </p> <p>We would like to stop people using the mouse (i.e. touchscreen) from moving the window by dragging the title bar. We don't care if there's some other way to move the window using the keyboard.</p> <p>What's the most elegant way to achieve this? I can think of trying to subvert mouse messages if there's a mouse-down on the titlebar (though NC hit-testing doesn't at first glance seem completely obvious in Winforms), and I can think of responding to Move messages in some way which restores the window position.</p> <p>But both of these seem clunky, and I have a feeling I am missing something elegant and obvious.</p>
<p>Nc messages are still the go I think. Syncfusion's windows form faq has the code you need. I'd paste a link, but I'm on an iPhone with no copy paste (grumble, grumble!)</p>
<p>How about modify the main form event's LocationChanged, SizeChanged, etc...</p>
28,889
<p>I know what MVC is and I work in webforms but I don't know how MVC will be that much different. I guess the code behind model will be different. So will it be like webforms minus the code behind and instead having it in a controller?</p> <p>I see there are other related posts but I don't they address this.</p>
<p>For starters, MVC does not use the &lt;asp:control&gt; controls, in preference for good old standard &lt;input&gt;'s and the like. Thus, you don't attach "events" to a control that get executed in a code-behind like you would in ASP. It relies on the standard http POST to do that.</p> <p>It does not use the viewstate object.</p> <p>It allows for more intelligent url mapping, though now that the Routing namespace has been spun off, I wonder if it can be used for WebForms?</p> <p>It is much easier to automate testing of web parts.</p> <p>It allows for much easier separation of UI logic from the "backend" components.</p>
<p>Asp.Net Web Forms:</p> <ol> <li>Asp.Net Web Form follows a traditional event driven development model. </li> <li>Asp.Net Web Form has server controls.</li> </ol> <p>Asp.Net MVC model:</p> <ol> <li>Asp.Net MVC is a lightweight and follow MVC (Model, View, and Controller) pattern based development model.Asp.Net MVC does not support view state.</li> </ol> <p><a href="http://asp-net-by-parijat.blogspot.in/2014/09/difference-between-aspnet-webforms-and.html" rel="nofollow">See more..</a></p>
17,183
<p>Just updated build server with rc0 and surprise no chiron. Wondering how you package up a xap file without chiron.</p>
<p>Hey Brian, you can get chiron from <a href="http://www.codeplex.com/sdlsdk" rel="nofollow noreferrer">http://www.codeplex.com/sdlsdk</a> -- it was decided to be removed from the SL SDK core tools, but is still a part of the DLR SDK which is available.</p>
<p>More specifically you can still use MSBuild. The targets should be located at C:\program files\MSBuild\Microsoft\Silverlight\v2.0 if you need to look at them or modify...your .csproj(or.vbproj) can also have pre/post build tasks for MSBuild as well.</p>
21,832
<p>Is there a control out in the world that allows a user to log in to a website with MS Passport (Windows Live ID, whatever), Facebook, OpenID, etc. all in one control?</p> <p>Thanks, everyone!</p>
<p>I am not aware of any control that allows all of them, but the API's are pretty simple that would allow you to implement it yourself.</p>
<p>I am not aware of any control that allows all of them, but the API's are pretty simple that would allow you to implement it yourself.</p>
25,645
<p>I have a large quantity of clearcase data which needs to be migrated into perforce. The revisions span the better part of a decade and I need to preserve as much branch and tag information as possible. Additionally we make extensive use of symbolic links, supported in clearcase but not in perforce. What advice or tools can you suggest which might make this easier? </p>
<p>The first step is to decide if you need to migrate everything, or just certain key versions. If you only migrate the important versions (releases and major milestones) you'll end up with a much simpler history in Perforce, without losing anything important. Then ClearCase can be keep as a historical archive in case it is ever needed. (Unless IBM has changed things ClearCase licenses do not expire when maintainance runs out, you just lose the right to new upgrades and patches and acces to support)</p> <p>Keep in mind that Perforce does not version control directories and does not keep a full per-element version tree - this means a 1:1 with exact results is going to be impossible. Recreating the important snapshots is a much more achievable goal; keeping everything may be impossible, as Perforce lacks features ClearCase relies upon.</p> <p>To see what Perforce says about the miration, check out <a href="http://perforce.com/perforce/ccaseconv.html" rel="nofollow noreferrer">http://perforce.com/perforce/ccaseconv.html</a> This explains the key differences and covers a few approaches you can take.</p>
<p>What you also have to keep in mind is the fact, that your importerscript may slightly commit in another sequence than the clearcase commits(maybe you are traversing dir, may be histories of files, etc.) </p> <p>So, unless you gather all version information into a (large) database and sort them afterwards, you will end up with commits which are not very useful to look into(except of course history of single files). As you (hopefully) change your commit-policy to commit atomic changes into perforce, it will be visible when development started: The commits before just do not make any sense on a project scope.</p> <p>So you really should think of leaving clearcase history behind. Tags/Branches creation is also a different problem, as you need your old configspecs for your old branches. At the end you will get wrong filenames in old tags(as perforce do not support dir-vers.) so you will use clearcase for this(and it is <em>very</em> tricky to get the correct filename for each version of a file!).</p> <p>The last problem you will encounter: importer run time: if you have large VOBs(eg. 10 years, 50 GB size), you will wait days for the importer to gather all information and convert it to a nice shiny perforce repo. All this day your devteam will stop working.</p>
14,501
<p>I have a CompositeDataBoundControl and im trying to add a ItemCommand to it, ala the System.Web.UI.WebControls.Repeater - so like a numpty, I just thought if I reflector'ed and added the code like so, it should work:</p> <pre><code>private static readonly object EventItemCommand = new object(); protected override bool OnBubbleEvent(object sender, EventArgs e) { // throw new Exception(); bool flag = false; if (e is RepeaterCommandEventArgs) { this.OnItemCommand((RepeaterCommandEventArgs)e); flag = true; } return flag; } protected virtual void OnItemCommand(RepeaterCommandEventArgs e) { RepeaterCommandEventHandler handler = (RepeaterCommandEventHandler)base.Events[EventItemCommand]; if (handler != null) { handler(this, e); } } public event RepeaterCommandEventHandler ItemCommand { add { base.Events.AddHandler(EventItemCommand, value); } remove { base.Events.RemoveHandler(EventItemCommand, value); } } </code></pre> <p>Unfortunatly, even though I have the event bound, it does not seem to fire. Iv tried to go down the route of IPostBackEventHandler, but its still not quite right (I can fire an empty event off with no args, but I cant see a decent way to call the OnItemCommand with the RepeaterCommandEventArgs</p> <p>Any ideas how to get this to work? </p> <p>Iv been sitting on the office for the last 4 hours trying to get this to work! Help!</p>
<p>In the case of the Repeater control the RepeaterItem object is actually raising the bubble event and supplying the RepeaterCommandEventArgs:</p> <pre><code>protected override bool OnBubbleEvent(object source, EventArgs e) { if (e is CommandEventArgs) { RepeaterCommandEventArgs args = new RepeaterCommandEventArgs(this, source, (CommandEventArgs) e); base.RaiseBubbleEvent(this, args); return true; } return false; } </code></pre> <p>In case you are not using the RepeaterItem in your control you will probably never get that RepeaterCommandEventArgs. Try checking for CommandEventArgs instead. Also make sure the OnBubbleEvent method of your control is ever called.</p>
<p>Im using a custom "RepeaterItem" (eg. RecipeItem) - I cant seem to get the OnBubbleEvent (have overriden it and stole things from RepeaterItem) to fire in the item.</p> <p>Nevermind, im an idiot. Commented out a DataBind();!</p>
38,445
<p>Could you recommend me a way to place a coundown timer on ASP.NET page?</p> <p>Now I use this code:</p> <p><strong>Default.aspx</strong></p> <pre><code>&lt;asp:ScriptManager ID="ScriptManager1" runat="server"&gt; &lt;/asp:ScriptManager&gt; &lt;asp:UpdatePanel ID="UpdatePanel1" runat="server"&gt; &lt;ContentTemplate&gt; &lt;asp:Label ID="Label1" runat="server"&gt;60&lt;/asp:Label&gt; &lt;asp:Timer ID="Timer1" runat="server" Interval="1000" ontick="Timer1_Tick"&gt; &lt;/asp:Timer&gt; &lt;/ContentTemplate&gt; &lt;/asp:UpdatePanel&gt; </code></pre> <p><strong>Default.aspx.cs</strong></p> <pre><code>protected void Timer1_Tick(object sender, EventArgs e) { int seconds = int.Parse(Label1.Text); if (seconds &gt; 0) Label1.Text = (seconds - 1).ToString(); else Timer1.Enabled = false; } </code></pre> <p>But it is traffic expensive. I would prefer pure client-side method. Is it possible in ASP.NET? </p>
<p>OK, finally I ended with</p> <pre><code>&lt;span id="timerLabel" runat="server"&gt;&lt;/span&gt; &lt;script type="text/javascript"&gt; function countdown() { seconds = document.getElementById("timerLabel").innerHTML; if (seconds &gt; 0) { document.getElementById("timerLabel").innerHTML = seconds - 1; setTimeout("countdown()", 1000); } } setTimeout("countdown()", 1000); &lt;/script&gt; </code></pre> <p>Really simple. Like old good plain HTML with JavaScript.</p>
<p>use this javascript code----</p> <pre><code>var sec=0 ; var min=0; var hour=0; var t; function display(){ if (sec&lt;=0){ sec+=1; } if(sec==60) { sec=0; min+=1; } if(min==60){ hour+=1; min=0; } if (min&lt;=-1){ sec=0; min+=1; } else sec+=1 ; document.getElementById("&lt;%=TextBox1.ClientID%&gt;").value=hour+":"+min+":"+sec; t=setTimeout("display()",1000); } window.onload=display; </code></pre>
13,432
<p>In our Sharepoint implementation users have been granted site collection admin rights. On a few occasions they've managed to delete a subsite or even the entire site collection. I'd like to be able to block this but not being a developer I'm finding it pretty tricky.</p> <p>I've had a look at <a href="http://www.codeplex.com/governance/release/projectreleases.aspx?releaseid=3830" rel="nofollow noreferrer">the MSIT site delete capture tool</a> to try to understand how that's working and it seams fairly straight forward. I want to override the delete function and either block it entirely or have the user type a password. What I can't see is any way to fully override the default behavior as it looks like the MSIT tool simply adds some functionality (backs up the site) then falls back into the default behavior. </p> <p>So my question is, can I prevent the default behavior or can I only add actions before or after it fires?</p> <p>Thanks in advance</p>
<p>Change the user permissions may be the best way to go. site collection admin is a crazy level of access for normal users.</p>
<p>A Site Collection administrator has the permission to delete sites and it should stay that way. We have modified MSIT to do additional stuff</p> <p>The best way to limit user privileges is to put users in the right SharePoint group (ie) Owners, Members, Visitors or you could create a new group with right permission/permission levels.</p>
30,197
<p>What is the accepted practice for indenting SQL statements? For example, consider the following SQL statement:</p> <pre><code>SELECT column1, column2 FROM table1 WHERE column3 IN ( SELECT TOP(1) column4 FROM table2 INNER JOIN table3 ON table2.column1 = table3.column1 ) </code></pre> <p>How should this be indented? Many thanks.</p>
<pre><code>SELECT column1 , column2 FROM table1 WHERE column3 IN ( SELECT TOP(1) column4 FROM table2 INNER JOIN table3 ON table2.column1 = table3.column1 ) </code></pre> <p>I like to have all <strong>"," in front</strong>, this way I never search them when an error at line X from the SQL editor.</p> <p><hr/></p> <h3>This is an example for those who do not use this type of writting SQL statement. Both contain an error of a missing comma.</h3> <pre><code>SELECT sdcolumn123 , dscolumn234 , sdcolumn343 , ffcolumn434 , sdcolumn543 , bvcolumn645 vccolumn754 , cccolumn834 , vvcolumn954 , cvcolumn104 FROM table1 WHERE column3 IN ( ... ) SELECT sdcolumn123, dscolumn234, asdcolumn345, dscolumn456, ascolumn554, gfcolumn645 sdcolumn754, fdcolumn845, sdcolumn954, fdcolumn1054 FROM table1 WHERE column3 IN ( ... ) </code></pre> <p>I found easier and more quick at the first example. Hope this example show you more my point of view.</p>
<p>That's how we would do it here:</p> <pre> select COLUMN1, COLUMN2, case when COLUMN5 = 'X' and COLUMN6 = 'Y' then 'one' when COLUMN5 in ( 'AAA', 'BBB' ) then 'two' else 'three' end as COLUMN7 from TABLE1 where COLUMN2 in ( select top(1) COLUMN4 from TABLE2 inner join TABLE3 on TABLE2.COLUMN1 = TABLE3.COLUMN1 and TABLE2.COLUMN2 between TABLE3.COLUMN2 and TABLE3.COLUMN3 ) </pre> <p>Our idea is: keep sql keywords in lower case and put all changing (and therefore "more interesting") things like table or column names in upper case. The code might look a bit "blown up" here, but it increases readability if you have complex queries with longer names (incl. schema etc.) much longer than in this example. And: indent all objects according to their "level".</p>
34,263
<p>I need to add some simple image renders of STL files to a document. I currently open the STL files in Preview or one of the slicers and grab a screen shot.</p> <p>Is there an easier or automatic way to generate PNG images from STL files on a Mac?</p>
<p>If you have <a href="http://www.openscad.org" rel="noreferrer">OpenSCAD</a> installed, this shell script will generate 100x100 pixel PNG images for each STL file in your current directory.</p> <pre><code>for i in *.stl; do T=__tmp__<span class="math-container">$i b=`basename $</span>i` echo import\(\"<span class="math-container">$i\"\)\; &gt;$</span>T /Applications/OpenSCAD.app/Contents/MacOS/OpenSCAD -o <span class="math-container">$b.png --imgsize=100,100 $</span>T rm $T done </code></pre> <p>Credit to <a href="https://3dprinting.stackexchange.com/users/5740/0scar">0scar</a> for pointing out STL files can be imported into OpenSCAD.</p> <p>Update: This code does the same, and generates an html file with annotated images of the files rendered. When I printed a batch of spare parts for my 3D printer I made a hardcopy and stuck it in the box so I could identify the parts later.</p> <pre><code>n=-1 H=00-catalog.html echo &gt;<span class="math-container">$H '&lt;table&gt;' echo &gt;&gt;$</span>H ' &lt;tr&gt;' for i in <span class="math-container">$*; do n=`expr $</span>n + 1` if test $n = 4; then n=0 echo &gt;&gt;$H ' &lt;/tr&gt;' echo &gt;&gt;$H ' &lt;tr&gt;' fi echo $i T=__tmp__$i B=`basename <span class="math-container">$i .stl` echo import\(\"$</span>i\"\)\; &gt;<span class="math-container">$T /Applications/OpenSCAD.app//Contents/MacOS/OpenSCAD -o $</span>B.png --imgsize=200,200 <span class="math-container">$T echo &gt;&gt;$</span>H echo &gt;&gt;<span class="math-container">$H ' &lt;td&gt;'$</span>i'&lt;br&gt;&lt;img src="'$B'.png"&gt;&lt;/td&gt;' rm <span class="math-container">$T done echo &gt;&gt;$</span>H ' &lt;/tr&gt;' echo &gt;&gt;$H '&lt;/table&gt;' </code></pre>
<p>You can use OpenSCAD, as stated in the accepted answer. Here is a version of that script that works for Windows for anyone who needs it, as I did.</p> <pre><code># Change height and width to the desired output image dimensions, in pixels. # The path to openscad.exe may also have to be adjusted based on your installation. height=1080 width=1080 for i in *.stl; do T=__tmp__<span class="math-container">$i b=`basename "$</span>i"` echo import\(\"./<span class="math-container">$i\"\)\; &gt; "$</span>T" C:/'Program Files'/OpenSCAD/openscad.exe -o "<span class="math-container">$b".png --autocenter --viewall --imgsize=$</span>width,<span class="math-container">$height "$</span>T" rm "$T" done </code></pre>
915
<p>I am getting a runtime error 13 at the end of the following code:</p> <pre><code>Sub plausibilitaet_check() Dim rs As DAO.Recordset Dim rs2 As ADODB.Recordset Dim db As database Dim strsql As String Dim strsql2 As String Dim tdf As TableDef Set db = opendatabase("C:\Codebook.mdb") Set rs = db.OpenRecordset("plausen1") Set rs2 = CreateObject("ADODB.Recordset") rs2.ActiveConnection = CurrentProject.Connection For Each tdf In CurrentDb.TableDefs If Left(tdf.Name, 4) &lt;&gt; "MSys" Then rs.MoveFirst strsql = "SELECT * From [" &amp; tdf.Name &amp; "] WHERE " Do While Not rs.EOF On Error Resume Next strsql2 = "select * from table where GHds &lt;&gt; 0" Set rs2 = CurrentDb.OpenRecordset(strsql2) </code></pre> <p>The error occurs at Set rs2 = CurrentDb.OpenRecordset(strsql2)</p> <p>Can someone see where I am going wrong?</p>
<p>You are mixing up ADO and DAO. In this case rs2 should be a DAO recordset.</p> <pre><code>Sub plausibilitaet_check() Dim rs As DAO.Recordset Dim rs2 As DAO.Recordset Dim db As database Dim strsql As String Dim strsql2 As String Dim tdf As TableDef Set db = opendatabase("C:\Codebook.mdb") Set rs = db.OpenRecordset("plausen1") For Each tdf In CurrentDb.TableDefs If Left(tdf.Name, 4) &lt;&gt; "MSys" Then rs.MoveFirst strsql = "SELECT * From [" &amp; tdf.Name &amp; "] WHERE " Do While Not rs.EOF On Error Resume Next strsql2 = "select * from table where GHds &lt;&gt; 0" Set rs2 = CurrentDb.OpenRecordset(strsql2) </code></pre>
<p>CurrentDB.OpenRecordset returns an instance of DAO.Recordset. You are trying to assign the result to ADODB.Recordset</p> <p>Change the rs2 definition to</p> <p><code> dim rs2 as DAO.Recordset </code></p>
42,132
<p>I have a home project that really needs to be in Source Control. I tried installing Subversion, which I have some experience with, but couldn't get it working. I don't particularly want to use SourceSafe. I'm a bit nervous about Git/Mercury as being somewhat cryptic, although this is only based on opinion rather than my experience.</p> <p>Main requirements are:</p> <ol> <li>Must be open source (well, it needs to be free but that sounds a bit cheap!)</li> <li>Must run on Win32</li> <li>Would prefer a GUI interface if one is available</li> </ol> <p>Many thanks in advance!</p> <p><strong>edit:</strong> Just to let you all know, I installed VisualSVN and had it working in no time. Thanks for the great advice.</p>
<p>I know you mentioned you already tried Subversion and had some issues but you really can't beat the easy install &amp; configuration of</p> <h3><a href="http://www.visualsvn.com/server/" rel="noreferrer">VisualSVN Server</a></h3> <p>Insanely easy to setup &amp; maintain.</p> <hr /> <p>Use VisualSVN for the back-end and <a href="http://tortoisesvn.tigris.org/" rel="noreferrer">TortoiseSVN</a> for the client and you'll be up and running in no time.</p> <p>Plus you can always do an svndump of the VisualSVN repository if you want to switch to something else down the road.</p>
<p>The only options I'm aware of that meet your requirements are CVS and SVN. Of those 2, I would recommend SVN. I know you've already tried it without success, so perhaps you should try posting another question describing exactly what the problem was.</p> <p>Our glorious leader posted a step-by-step guide describing <a href="https://blog.codinghorror.com/setting-up-subversion-on-windows/" rel="nofollow noreferrer">how to setup SVN on windows</a>, which might resolve your problem.</p>
26,884
<p>I'm looking for a builder for <a href="http://www.hibernate.org/hib_docs/reference/en/html/queryhql.html" rel="noreferrer">HQL</a> in Java. I want to get rid of things like:</p> <pre><code>StringBuilder builder = new StringBuilder() .append("select stock from ") .append( Stock.class.getName() ) .append( " as stock where stock.id = ") .append( id ); </code></pre> <p>I'd rather have something like:</p> <pre><code>HqlBuilder builder = new HqlBuilder() .select( "stock" ) .from( Stock.class.getName() ).as( "stock" ) .where( "stock.id" ).equals( id ); </code></pre> <p>I googled a bit, and I couldn't find one.</p> <p>I wrote a quick &amp; dumb <code>HqlBuilder</code> that suits my needs for now, but I'd love to find one that has more users and tests than me alone.</p> <p>Note: I'd like to be able to do things like this and more, which I failed to do with the Criteria API:</p> <pre><code>select stock from com.something.Stock as stock, com.something.Bonus as bonus where stock.someValue = bonus.id </code></pre> <p>ie. select all stocks whose property <code>someValue</code> points to <em>any</em> bonus from the Bonus table.</p> <p>Thanks!</p>
<p>@<a href="https://stackoverflow.com/questions/56843/looking-for-an-hql-builder-hibernate-query-language#57001">Sébastien Rocca-Serra</a><br> Now we're getting somewhere concrete. The sort of join you're trying to do isn't really possible through the Criteria API, but a sub-query should accomplish the same thing. First you create a <code>DetachedCriteria</code> for the bonus table, then use the <code>IN</code> operator for <code>someValue</code>.</p> <pre><code>DetachedCriteria bonuses = DetachedCriteria.forClass(Bonus.class); List stocks = session.createCriteria(Stock.class) .add(Property.forName("someValue").in(bonuses)).list(); </code></pre> <p>This is equivalent to</p> <pre><code>select stock from com.something.Stock as stock where stock.someValue in (select bonus.id from com.something.Bonus as bonus) </code></pre> <p>The only downside would be if you have references to different tables in <code>someValue</code> and your ID's are not unique across all tables. But your query would suffer from the same flaw.</p>
<p>Now are also available the standard <a href="http://www.ibm.com/developerworks/library/j-typesafejpa/" rel="nofollow">JPA Type Safe</a> query and an less standard but also good <a href="https://www.objectquery.org/" rel="nofollow">Object Query</a></p> <p>Examples:</p> <p>JPA Type Safe</p> <pre><code>EntityManager em = ... CriteriaBuilder qb = em.getCriteriaBuilder(); CriteriaQuery&lt;Stock&gt; c = qb.createQuery(Stock.class); Root&lt;Stock&gt; = c.from(Stock.class); Predicate condition = qb.eq(p.get(Stock_.id), id); c.where(condition); TypedQuery&lt;Stock&gt; q = em.createQuery(c); List&lt;Stock&gt; result = q.getResultList(); </code></pre> <p>Object Query</p> <pre><code>EntityManager em = ... ObjectQuery&lt;Stock&gt; query = new GenericObjectQuery&lt;Stock&gt;(Stock.class); Stock toSearch = query.target(); query.eq(toSearch.getId(),id); List&lt;Stock&gt; res = (List&lt;Stock&gt;)JPAObjectQuery.execute(query, em); </code></pre>
8,095
<p>I am developing a web page code, which fetches dynamically the content from the server and then places this content to container nodes using something like</p> <pre><code>container.innerHTML = content; </code></pre> <p>Sometimes I have to overwrite some previous content in this node. This works fine, until it happens that previous content occupied more vertical space then a new one would occupy AND a user scrolled the page down -- scrolled more than new content would allow, provided its height.</p> <p>In this case the page redraws incorrectly -- some artifacts of the old content remain. It works fine, and it is even possible to get rid of artifacts, by minimizing and restoring the browser (or force the window to be redrawn in an other way), however this does not seem very convenient.</p> <p>I am testing this only under Safari (this is a iPhone-optimized website).</p> <p>Does anybody have the idea how to deal with this?</p>
<p>The easiest solution that I have found would be to place an anchor tag <code>&lt;a&gt;</code> at the top of the <code>div</code> you are editing:</p> <pre><code>&lt;a name="ajax-div"&gt;&lt;/a&gt; </code></pre> <p>Then when you change the content of the <code>div</code>, you can do this to have the browser jump to your anchor tag:</p> <pre><code>location.hash = 'ajax-div'; </code></pre> <p>Use this to make sure the user isn't scrolled down too far when you update the content and you shouldn't get the issue in the first place.</p> <p>(tested in the latest FF beta and latest safari)</p>
<p>It sounds like you are having a problem with the browser itself. Does this problem only occur in one browser?</p> <p>One thing you might try is using a lightweight library like <a href="http://jquery.com/" rel="nofollow noreferrer">jQuery</a>. It handles browser differences fairly nicely. To set the inner HTML for a div with the ID of <strong>container</strong> you would simply write this:</p> <pre><code>$('#container').html( content ); </code></pre> <p>That will work in most browsers. I do not know if it will fix your problem specifically or not but it may be worth a try.</p>
8,913
<p>Can't seem to rename an existing Verity collection in ColdFusion without deleting, recreating, and rebuilding the collection. Problem is, I have some very large collections I'd rather not have to delete and rebuild from scratch. Any one have a handy trick for this conundrum?</p>
<p>I don't believe that there is an easy way to rename a Verity collection. You can always use </p> <pre><code>&lt;cfcollection action="map" ...&gt; </code></pre> <p>to assign an alias to an existing collection, provided you do not need to re-use the original name.</p>
<p>Looks like this is not possible. Deleting and re-creating the collection with the desired name appears to be the only approach available.</p>
18,855
<p>Dendrogram is not a regular diagram. Should I use any component from javax.swing.* library, or just draw it with java.awt.Graphics?</p>
<p>Might also be worth checking: <a href="http://www.yworks.com/en/index.html" rel="nofollow noreferrer">yWorks</a> and <a href="http://www.jgraph.com/" rel="nofollow noreferrer">JGraph</a></p>
<p>I don't think there is a standard component for this. Unless some component vendor has done one, you should go the Java 2D way...</p> <p>If you don't want to do the hard work, perhaps one of the above mentioned libraries might help you. Otherwise, GraphViz is good at making this kind of diagram, and has a <a href="http://www.loria.fr/~szathmar/off/projects/java/GraphVizAPI/index.php" rel="nofollow noreferrer" title="Java API">Java API</a> (untested...).</p> <p>Another possible way is to use some physics to let the nodes arrange themselves in an harmonious way. That's how <a href="http://www.aharef.info/static/htmlgraph/" rel="nofollow noreferrer" title="http://www.aharef.info/static/htmlgraph/">Aharef's HTML graph</a> works...</p>
34,432
<p>I'm look for a GIS/Mapping tool that will give me easy SERVER-SIDE access to route information (specifically, trip time and distance) in an ASP.NET web application.</p> <p>From what I can tell, Google and Yahoo maps do everything client-side in javascript, but neither provide services to retrieve just the route information. I'm interested in both free and paid products. Also, if you have experience with a product I like to hear about what you think (complexity of API, runtime performance, likes, dislikes, etc.)</p>
<p>We've had success with using the web services from Map24 (<a href="http://developer.navteq.com/site/global/zones/ms/index.jsp" rel="nofollow noreferrer">http://developer.navteq.com/site/global/zones/ms/index.jsp</a>) to do some GIS-y type things. They have a web service for doing routing (<a href="http://developer.navteq.com/site/global/zones/ms/map24webservices/map24routingservice.jsp" rel="nofollow noreferrer">http://developer.navteq.com/site/global/zones/ms/map24webservices/map24routingservice.jsp</a>) which I had a quick play with last year.</p> <p>There's a bit of a learning curve wih their APIs but once you get past it their stuff is quite powerful and performs really well.</p> <p>Phil</p>
<p>Arc Web Services is going away and is now becoming ArcGIS online. </p> <p>This means a whole new updated sdk for developing arc web applications for web sites. </p> <p>If you need a really advanced routing system developed a company called routesmart makes dll based route solver solutions for client server apps and now web applications using ArcGIS 9.x </p> <p>All ESRI api's are complex. You have to just start using it and when you gain experience in it you will feel more comfortable. </p> <p>Since ESRI has somewhat of a shrinking monopoly on certain aspects of GIS capabilities it will be interesting to see what Google and others develop to create some decent competition for the GIS world. Until then all encompassing GIS solutions will not be flexable or easy to work with and expensive.</p> <p>One major gripe I have with ESRI products is rather ethereal however it seems to be a recurring theme I have experienced in all of their product lines.</p> <p>You do a code\db\whatever update and test. It doesn't work. You try again without making changes and it still doesn't work, but if you try one more time it suddenly works. It's like ESRI has coded everything to fail 2 times first before any change to a point release, mxd, sde data, or python code to begin performing as intended. As strange as this may seem if you have ever worked with their products you know this because you have experienced it yourself. This may have to do with my lack of understanding but all my GIS friends tend to agree with me on this point.</p>
15,389
<p>We are upgrading our servers to SQL Server 2005 from SQL Server 2000. We currently use the jtds drivers.</p> <p>I'm interested to know what peoples opinions are of the different jdbc drivers available (in particular the latest Microsoft driver), how they perform with SQL Server 2005 and any other lessons from your collective experience.</p>
<p>I have used the MS provided driver, the jtds driver, as well as the driver from jnetdirect.</p> <p>Unfortunately none of them is perfect, and all have their own bugs (including of course Microsofts own). The MS provided drivers of course have support for the newest features before the other vendors, but I must say that I have rarely seen significant performance differences between drivers.</p> <p>My advice would be to make sure that your application reads the driver name and connection URL from a properties file somewhere so that you can easily switch between drivers if you run into problems with whichever one you choose. You'll be glad you did later.</p>
<p>We tried using Microsoft JDBC Driver 2.0 with SQL Server 2005. The problem we were running into was - when calling a stored procedure, the driver was generating the following sql statements - </p> <pre><code>declare @P1 int set @P1=1 exec sp_prepexec @P1 output, N'@P0 int', N'EXEC getEmployeeManagers @P0', 50 select @P1 </code></pre> <p>So stored procedures run in the <code>sp_prepexec</code> statements. And later when you close the statement, the <code>sp_unprepare</code> gets called. This seems to be the default behavior of the MS driver. The problem with this is, the overhead to generate a prepared statement and then to close it has performance impact. Why can't the driver just do this - </p> <pre><code>exec getEmployeeManagers @P0=50 </code></pre> <p>We are now using the jTDS driver and it seems to be performing great. </p>
44,354
<p>here is what a I'm doing: </p> <pre><code>object ReturnMatch(System.Type type) { foreach(object obj in myObjects) { if (obj == type) { return obj; } } } </code></pre> <p>However, if obj is a subclass of <code>type</code>, it will not match. But I would like the function to return the same way as if I was using the operator <code>is</code>.</p> <p>I tried the following, but it won't compile:</p> <pre><code>if (obj is type) // won't compile in C# 2.0 </code></pre> <p>The best solution I came up with was:</p> <pre><code>if (obj.GetType().Equals(type) || obj.GetType().IsSubclassOf(type)) </code></pre> <p>Isn't there a way to use operator <code>is</code> to make the code cleaner?</p>
<p>I've used the IsAssignableFrom method when faced with this problem.</p> <pre><code>Type theTypeWeWant; // From argument or whatever foreach (object o in myCollection) { if (theTypeWeWant.IsAssignableFrom(o.GetType)) return o; } </code></pre> <p>Another approach that may or may not work with your problem is to use a generic method:</p> <pre><code>private T FindObjectOfType&lt;T&gt;() where T: class { foreach(object o in myCollection) { if (o is T) return (T) o; } return null; } </code></pre> <p>(Code written from memory and is not tested)</p>
<p>the is operator indicates whether or not it would be 'safe' to cast one object as another obeject (often a super class).</p> <pre><code>if(obj is type) </code></pre> <p>if obj is of type 'type' or a subclass thereof, then the if statement will succeede as it is 'safe' to cast obj as (type)obj.</p> <p>see: <a href="http://msdn.microsoft.com/en-us/library/scekt9xw(VS.71).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/scekt9xw(VS.71).aspx</a></p>
9,798
<p>Out of curiosity, anyone knows the particulars of the internal implementation of </p> <pre><code>ListControl.SelectedIndex = (int) &lt;new valueIndex&gt; </code></pre> <p>VS </p> <pre><code>ListControl.SelectedValue = &lt;new value&gt;.ToString() </code></pre> <p>I'm having difficulties with a custom validation object we've built here to process all validation in one sweep. I suspect using <code>&lt;SelectedValue = &gt;</code> will raise a <code>SelectedIndexChanged</code> event, even though both the value and index remain the same, both before and after the operation.</p> <p>(The ListControl's values are populated declaratively....)</p> <p>As ever, thank you for your time!</p>
<p>Following Jeb's suggeston in a comment, I created a <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-tags" rel="nofollow noreferrer">custom template tag</a>.</p> <p>I replaced <code>{{ forloop.counter }}</code> with <code>{% counter %}</code>, a tag that simply prints how many times it's been called.</p> <p>Here's the code for my counter tag. </p> <pre><code>class CounterNode(template.Node): def __init__(self): self.count = 0 def render(self, context): self.count += 1 return self.count @register.tag def counter(parser, token): return CounterNode() </code></pre>
<p>I think you can use forloop.parentloop.counter inside of the inner loop to achieve the numbering you're after.</p>
37,016
<p>We're looking for a package to help identify and automatically rotate faxed TIFF images based on a watermark or logo. </p> <p>We use libtiff for rotation currently, but don't know of any other libraries or packages I can use for detecting this logo and determining how to rotate the images.</p> <p>I have done some basic work with OpenCV but I'm not sure that it is the right tool for this job. I would prefer to use C/C++ but Java, Perl or PHP would be acceptable too. </p>
<p>You are in the right place using OpenCV, it is an excellent utility. For example, <a href="http://www.nashruddin.com/template-matching-in-opencv-with-example.html" rel="nofollow noreferrer">this guy</a> used it for template matching, which is fairly similar to what you need to do. Also, the link Roddy specified looks similar to what you want to do.</p> <p>I feel that OpenCV is the best library out there for this kind of development.</p> <p>@Brian, OpenCV and the IntelIPP are closely linked and very similar (both Intel libs). As far as I know, if OpenCV finds the intel IPP on your computer it will automatically use it under the hood for improved speed.</p>
<p>The Intel Performance Primitives (IPP) library has a lot of very efficient algorithms that help with this kind of a task. The library is callable from C/C++ and we have found it to be very fast. I should also note that it's not limited to just Intel hardware.</p>
5,263
<p>This is sort of a follow-up to <a href="https://stackoverflow.com/questions/223678">this question</a>.</p> <p>If there are multiple blobs with the same contents, they are only stored once in the git repository because their SHA-1's will be identical. How would one go about finding all duplicate files for a given tree? </p> <p>Would you have to walk the tree and look for duplicate hashes, or does git provide backlinks from each blob to all files in a tree that reference it?</p>
<pre><code>[alias] # find duplicate files from root alldupes = !"git ls-tree -r HEAD | cut -c 13- | sort | uniq -D -w 40" # find duplicate files from the current folder (can also be root) dupes = !"cd `pwd`/$GIT_PREFIX &amp;&amp; git ls-tree -r HEAD | cut -c 13- | sort | uniq -D -w 40" </code></pre>
<p>More general:</p> <pre><code>( for f in `find .`; do test -f $f &amp;&amp; echo $(wc -c &lt;$f) $(md5 -q $f) ; done ) |sort |uniq -c |grep -vE '^\s*1\b' |sed 's/.* //' &gt; ~/dup.md5 ; \ ( for f in `find .`; do test -f $f &amp;&amp; echo $(wc -c &lt;$f) $(md5 -q $f) $f; done ) |fgrep -f ~/dup.md5 |sort </code></pre>
27,768
<p>I have C++ project (VS2005) which includes header file with version number in #define directive. Now I need to include exactly the same number in twin C# project. What is the best way to do it?</p> <p>I'm thinking about including this file as a resource, then parse it at a runtime with regex to recover version number, but maybe there's a better way, what do you think?</p> <p>I cannot move version outside .h file, also build system depends on it and the C# project is one which should be adapted.</p>
<p>You can achieve what you want in just a few steps:</p> <ol> <li>Create a MSBuild Task - <a href="http://msdn.microsoft.com/en-us/library/t9883dzc.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/t9883dzc.aspx</a></li> <li>Update the project file to include a call to the task created prior to build</li> </ol> <p>The task receives a parameter with the location of the header .h file you referred. It then extracts the version and put that version in a C# placeholder file you previously have created. Or you can think using AssemblyInfo.cs that normally holds versions if that is ok for you.</p> <p>If you need extra information please feel free to comment.</p>
<p>I wrote a python script that converts #define FOO "bar" into something usable in C# and I'm using it in a pre-build step in my C# project. It works. </p> <pre><code># translate the #defines in messages.h file into consts in MessagesDotH.cs import re import os import stat def convert_h_to_cs(fin, fout): for line in fin: m = re.match(r"^#define (.*) \"(.*)\"", line) if m != None: if m.group() != None: fout.write( "public const string " \ + m.group(1) \ + " = \"" \ + m.group(2) \ + "\";\n" ) if re.match(r"^//", line) != None: fout.write(line) fin = open ('..\common_cpp\messages.h') fout = open ('..\user_setup\MessagesDotH.cs.tmp','w') fout.write( 'using System;\n' ) fout.write( 'namespace xrisk { class MessagesDotH {\n' ) convert_h_to_cs(fin, fout) fout.write( '}}' ) fout.close() s1 = open('..\user_setup\MessagesDotH.cs.tmp').read() s2 = open('..\user_setup\MessagesDotH.cs').read() if s1 != s2: os.chmod('..\user_setup\MessagesDotH.cs', stat.S_IWRITE) print 'deleting old MessagesDotH.cs' os.remove('..\user_setup\MessagesDotH.cs') print 'remaming tmp to MessagesDotH.cs' os.rename('..\user_setup\MessagesDotH.cs.tmp','..\user_setup\MessagesDotH.cs') else: print 'no differences. using same MessagesDotH.cs' </code></pre>
12,617
<p>Ok we have a number of solutions all with a lot of shared binaries:</p> <p>what we do is the following.</p> <p>In a shared drive we have this following layout where there is a directory for every binary dependency and a sub directory for every version</p> <p>BinaryDep1<br> -----------Volatile<br> -----------1.0<br> -----------1.1<br> -----------1.2 </p> <p>BinaryDep3<br> -----------Volatile<br> -----------1.0<br> -----------1.1<br> -----------2.2 </p> <p>BinaryDep3<br> -----------Volatile<br> -----------1.0<br> -----------1.1<br> -----------1.2 </p> <p>In our solutions we have a XML file that lists out all of the dependencies and versions. We have a script that then goes tothe shared drive and download the dependencies into a sub folder of a solution called /ext</p> <p>This works very well but has a few flaws that we are looking to improve and i wanted to get people's feedback.</p> <ol> <li>We have many solutions so if they all depend on the same version of a binary dependency then we get one copy per solution (as its supposed to be self contained). So if i have 5 solutions that all depend on Syncfusion, i get 5 copies of syncfusion on my desktop. The two issues here are 1) slow download time (5x more than i need to) and takes up lots of disk space.</li> </ol> <p>We like the model where have a local sub directory per solution with /ext so we never have to change project references but these seem like competing forces.</p> <p>any ideas on how to normalize teh download so we are not downloading 5x the data and same the disk size without having to go to manually updating project references where i have to change reference in VS for every version upgrade.</p>
<p>What about the same struture in all developer machines?</p> <p>Like:</p> <p>d:/projects<br> d:/projects/ext (the shared libraries you need here)<br> d:/projects/project1<br> d:/projects/project2<br> d:/projects/project3<br> d:/projects/project4<br> ...</p> <p>ps: I love conventions.</p>
<p>Is any <a href="http://en.wikipedia.org/wiki/Global_Assembly_Cache#Pitfalls" rel="nofollow noreferrer">reason</a> for not putting shared assemblies to <a href="http://msdn.microsoft.com/en-us/library/yf1d93sz.aspx" rel="nofollow noreferrer">GAC</a>?</p>
46,651
<pre><code>echo $_POST["name"]; //returns the value a user typed into the "name" field </code></pre> <p>I would like to be able to also return the text of the key. In this example, I want to return the text "name". Can I do this?</p>
<p>Check out the array_keys() function assuming this is PHP.</p> <p><a href="http://us2.php.net/array_keys" rel="noreferrer">http://us2.php.net/array_keys</a></p>
<pre><code>array_keys($_POST) </code></pre> <p><a href="http://de.php.net/array_keys" rel="nofollow noreferrer">Manual</a></p>
22,238
<p>I am trying to set myself up on a mac to learn Ruby on Rails, however I seem to be having some problems. If I try to run commands such as ./script/server, i get this: </p> <blockquote> <p>Rails requires RubyGems >= 0.9.4 (you have 0.9.2). Please <code>gem update --system</code> and try again.</p> </blockquote> <p>When I run "gem update.." I get this:</p> <blockquote> <p>Updating RubyGems... Attempting remote update of rubygems-update ERROR: While executing gem ... (Errno::EACCES) Permission denied - /opt/local/lib/ruby/gems/1.8/cache/rubygems-update-1.3.0.gem</p> </blockquote>
<p>got it. </p> <p>sudo gem update --system </p>
<p>Starting with El Capitan, Apple prevents user applications to modify <code>/usr/bin</code> for security reasons. So better install/update rubygems in the recommended folder, <code>/usr/local/bin</code>:</p> <pre><code>sudo gem update -n /usr/local/bin --system </code></pre> <p>(recommendation taken from <a href="https://stackoverflow.com/a/39928447/1033581">https://stackoverflow.com/a/39928447/1033581</a>)</p>
20,544
<p>I am writing a key record look up where the I have an index between the key and the rec number. This is sorted on the key. Is there away to do this better that what I have for speed optimization?</p> <pre><code>typedef struct { char key[MAX_KEYLEN]; int rec; } KeyRecPair; typedef struct { KeyRecPair *map; int numRecs; } KeyRecMap; int GetRecFromKey(char *key, KeyRecMap *theMap) { int cmpValue, bottom = 0; int half = theMap-&gt;numRecs / 2; int top = theMap-&gt;numRecs - 1; while (bottom != top) { cmpValue = strncmp(key, theMap-&gt;map[half].key, MAX_KEY_LEN); if (cmpValue &gt; 0) { /*top stays*/ bottom = half + 1; half = bottom + (top - bottom) / 2; continue; } if (cmpValue &lt; 0) { /*bottom stays*/ top = half - 1; half = bottom + (top - bottom) / 2; continue; } return theMap-&gt;map[half].rec; } if (0 == strncmp(key, theMap-&gt;map[half].key, MAX_KEY_LEN)) return theMap-&gt;map[half].rec; return 0; } </code></pre>
<p>A good chunk of your time will be spent in the strncmp.</p> <p>I suggest forcing that to be <a href="http://en.wikipedia.org/wiki/Inlining" rel="nofollow noreferrer">inlined</a>, or rewriting it inline, to avoid the function call over head.</p> <p>If you are feeling brave it may be possible to <a href="http://en.wikipedia.org/wiki/Loop_unwinding" rel="nofollow noreferrer">unroll the loop</a> once or twice and see a performance gain.</p> <p>If your string was actually a fixed length of array of char, you could make the length a multiple of 4 and and compare 4 bytes at a time with an unsigned int compare, instead of 1 byte at a time.</p> <p>If you don't have a <a href="http://en.wikipedia.org/wiki/Profiler_(computer_science)" rel="nofollow noreferrer">profiler</a>, you should get one. Profilers make it easy to see what the relative costs of various implementations are. </p> <p>Another option would be to pick a different way to organize your data. Check out <a href="http://en.wikipedia.org/wiki/Avl_tree" rel="nofollow noreferrer">AVL trees</a> for inspiration. Choosing some sort of <a href="http://en.wikipedia.org/wiki/Hash_function" rel="nofollow noreferrer">Hashing</a> function, like the others mentioned, may be a viable option</p>
<p>The only potential optimization that I can think of is to use something similar to golden ratio in calculating <code>half</code> instead of dividing the remaining subset to two halves with equal number of elements, that is</p> <pre><code> if (cmpValue &gt; 0) { /*top stays*/ bottom = half + 1; half = bottom + (top - bottom) * 3 / 5; continue; } if (cmpValue &lt; 0) { /*bottom stays*/ top = half - 1; half = bottom + (top - bottom) * 2 / 5; continue; } </code></pre>
46,542
<p>As popular as Ruby and Rails are, it seems like this problem would already be solved. JRuby and mod_rails are all fine and dandy, but why isn't there an Apache mod for just straight Ruby?</p>
<p>There is <a href="http://www.modrails.com/" rel="nofollow noreferrer">Phusion Passenger</a>, a robust Apache module that can run <a href="http://rack.rubyforge.org/" rel="nofollow noreferrer">Rack</a> applications with minimum configuration. It's becoming appealing to shared hosts, and turning any program into a Rack application is ridiculously easy:</p> <blockquote> <p>A Rack application is an Ruby <strong>object</strong> (not a class) that responds to <code>call</code>. It takes exactly <em>one argument</em>, the environment and returns an Array of exactly <em>three values</em>: The status, the headers, and the body.</p> </blockquote>
<p>There is <a href="http://www.modrails.com/" rel="nofollow noreferrer">mod_rails</a> and it can run <a href="http://rack.rubyforge.org/" rel="nofollow noreferrer">Rack</a> applications, what more can you need?</p>
10,062
<p>I was looking for a way to remove text from and RTF string and I found the following regex:</p> <pre><code>({\\)(.+?)(})|(\\)(.+?)(\b) </code></pre> <p>However the resulting string has two right angle brackets "}"</p> <p><strong>Before:</strong> <code>{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 MS Shell Dlg 2;}{\f1\fnil MS Shell Dlg 2;}} {\colortbl ;\red0\green0\blue0;} {\*\generator Msftedit 5.41.15.1507;}\viewkind4\uc1\pard\tx720\cf1\f0\fs20 can u send me info for the call pls\f1\par }</code></p> <p><strong>After:</strong> <code>} can u send me info for the call pls }</code></p> <p>Any thoughts on how to improve the regex?</p> <p><strong>Edit:</strong> A more complicated string such as this one does not work: <code>{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 MS Shell Dlg 2;}} {\colortbl ;\red0\green0\blue0;} {\*\generator Msftedit 5.41.15.1507;}\viewkind4\uc1\pard\tx720\cf1\f0\fs20 HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\test\\myapp\\Apps\\\{3423234-283B-43d2-BCE6-A324B84CC70E\}\par }</code></p>
<p>In RTF, { and } marks a group. Groups can be nested. \ marks beginning of a control word. Control words end with either a space or a non alphabetic character. A control word can have a numeric parameter following, without any delimiter in between. Some control words also take text parameters, separated by ';'. Those control words are usually in their own groups.</p> <p>I think I have managed to make a pattern that takes care of most the cases.</p> <pre><code>\{\*?\\[^{}]+}|[{}]|\\\n?[A-Za-z]+\n?(?:-?\d+)?[ ]? </code></pre> <p>It leaves a few spaces when run on your pattern though.</p> <hr> <p>Going trough the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=DD422B8D-FF06-4207-B476-6B5396A18A2B&amp;displaylang=en" rel="noreferrer">RTF specification</a> (some of it), I see that there are a lot of pitfalls for pure regex based strippers. The most obvious one are that some groups should be ignored (headers, footers, etc.), while others should be rendered (formatting).</p> <p>I have written a Python script that should work better than my regex above:</p> <pre><code>def striprtf(text): pattern = re.compile(r"\\([a-z]{1,32})(-?\d{1,10})?[ ]?|\\'([0-9a-f]{2})|\\([^a-z])|([{}])|[\r\n]+|(.)", re.I) # control words which specify a "destionation". destinations = frozenset(( 'aftncn','aftnsep','aftnsepc','annotation','atnauthor','atndate','atnicn','atnid', 'atnparent','atnref','atntime','atrfend','atrfstart','author','background', 'bkmkend','bkmkstart','blipuid','buptim','category','colorschememapping', 'colortbl','comment','company','creatim','datafield','datastore','defchp','defpap', 'do','doccomm','docvar','dptxbxtext','ebcend','ebcstart','factoidname','falt', 'fchars','ffdeftext','ffentrymcr','ffexitmcr','ffformat','ffhelptext','ffl', 'ffname','ffstattext','field','file','filetbl','fldinst','fldrslt','fldtype', 'fname','fontemb','fontfile','fonttbl','footer','footerf','footerl','footerr', 'footnote','formfield','ftncn','ftnsep','ftnsepc','g','generator','gridtbl', 'header','headerf','headerl','headerr','hl','hlfr','hlinkbase','hlloc','hlsrc', 'hsv','htmltag','info','keycode','keywords','latentstyles','lchars','levelnumbers', 'leveltext','lfolevel','linkval','list','listlevel','listname','listoverride', 'listoverridetable','listpicture','liststylename','listtable','listtext', 'lsdlockedexcept','macc','maccPr','mailmerge','maln','malnScr','manager','margPr', 'mbar','mbarPr','mbaseJc','mbegChr','mborderBox','mborderBoxPr','mbox','mboxPr', 'mchr','mcount','mctrlPr','md','mdeg','mdegHide','mden','mdiff','mdPr','me', 'mendChr','meqArr','meqArrPr','mf','mfName','mfPr','mfunc','mfuncPr','mgroupChr', 'mgroupChrPr','mgrow','mhideBot','mhideLeft','mhideRight','mhideTop','mhtmltag', 'mlim','mlimloc','mlimlow','mlimlowPr','mlimupp','mlimuppPr','mm','mmaddfieldname', 'mmath','mmathPict','mmathPr','mmaxdist','mmc','mmcJc','mmconnectstr', 'mmconnectstrdata','mmcPr','mmcs','mmdatasource','mmheadersource','mmmailsubject', 'mmodso','mmodsofilter','mmodsofldmpdata','mmodsomappedname','mmodsoname', 'mmodsorecipdata','mmodsosort','mmodsosrc','mmodsotable','mmodsoudl', 'mmodsoudldata','mmodsouniquetag','mmPr','mmquery','mmr','mnary','mnaryPr', 'mnoBreak','mnum','mobjDist','moMath','moMathPara','moMathParaPr','mopEmu', 'mphant','mphantPr','mplcHide','mpos','mr','mrad','mradPr','mrPr','msepChr', 'mshow','mshp','msPre','msPrePr','msSub','msSubPr','msSubSup','msSubSupPr','msSup', 'msSupPr','mstrikeBLTR','mstrikeH','mstrikeTLBR','mstrikeV','msub','msubHide', 'msup','msupHide','mtransp','mtype','mvertJc','mvfmf','mvfml','mvtof','mvtol', 'mzeroAsc','mzeroDesc','mzeroWid','nesttableprops','nextfile','nonesttables', 'objalias','objclass','objdata','object','objname','objsect','objtime','oldcprops', 'oldpprops','oldsprops','oldtprops','oleclsid','operator','panose','password', 'passwordhash','pgp','pgptbl','picprop','pict','pn','pnseclvl','pntext','pntxta', 'pntxtb','printim','private','propname','protend','protstart','protusertbl','pxe', 'result','revtbl','revtim','rsidtbl','rxe','shp','shpgrp','shpinst', 'shppict','shprslt','shptxt','sn','sp','staticval','stylesheet','subject','sv', 'svb','tc','template','themedata','title','txe','ud','upr','userprops', 'wgrffmtfilter','windowcaption','writereservation','writereservhash','xe','xform', 'xmlattrname','xmlattrvalue','xmlclose','xmlname','xmlnstbl', 'xmlopen', )) # Translation of some special characters. specialchars = { 'par': '\n', 'sect': '\n\n', 'page': '\n\n', 'line': '\n', 'tab': '\t', 'emdash': u'\u2014', 'endash': u'\u2013', 'emspace': u'\u2003', 'enspace': u'\u2002', 'qmspace': u'\u2005', 'bullet': u'\u2022', 'lquote': u'\u2018', 'rquote': u'\u2019', 'ldblquote': u'\201C', 'rdblquote': u'\u201D', } stack = [] ignorable = False # Whether this group (and all inside it) are "ignorable". ucskip = 1 # Number of ASCII characters to skip after a unicode character. curskip = 0 # Number of ASCII characters left to skip out = [] # Output buffer. for match in pattern.finditer(text): word,arg,hex,char,brace,tchar = match.groups() if brace: curskip = 0 if brace == '{': # Push state stack.append((ucskip,ignorable)) elif brace == '}': # Pop state ucskip,ignorable = stack.pop() elif char: # \x (not a letter) curskip = 0 if char == '~': if not ignorable: out.append(u'\xA0') elif char in '{}\\': if not ignorable: out.append(char) elif char == '*': ignorable = True elif word: # \foo curskip = 0 if word in destinations: ignorable = True elif ignorable: pass elif word in specialchars: out.append(specialchars[word]) elif word == 'uc': ucskip = int(arg) elif word == 'u': c = int(arg) if c &lt; 0: c += 0x10000 if c &gt; 127: out.append(unichr(c)) else: out.append(chr(c)) curskip = ucskip elif hex: # \'xx if curskip &gt; 0: curskip -= 1 elif not ignorable: c = int(hex,16) if c &gt; 127: out.append(unichr(c)) else: out.append(chr(c)) elif tchar: if curskip &gt; 0: curskip -= 1 elif not ignorable: out.append(tchar) return ''.join(out) </code></pre> <p>It works by parsing the RTF code, and skipping any groups which has a "destination" specified, and all "ignorable" groups (<code>{\*</code>...<code>}</code>). I also added handling of some special characters.</p> <p>There are lots of features missing to make this a full parser, but should be enough for simple documents.</p> <p><strong>UPDATED:</strong> This url have this script updated to run on Python 3.x:</p> <p><a href="https://gist.github.com/gilsondev/7c1d2d753ddb522e7bc22511cfb08676" rel="noreferrer">https://gist.github.com/gilsondev/7c1d2d753ddb522e7bc22511cfb08676</a></p>
<p>None of the answers were sufficient, so my solution was to use the RichTextBox control (yes, even in a non-Winform app) to extract text from RTF</p>
22,862
<p>We need to reliably get the Quick Launch folder for both All and Current users under both Vista and XP. I'm developing in C++, but this is probably more of a general Windows API question.</p> <p>For reference, here is code to get the Application Data folder under both systems:</p> <pre><code> HRESULT hres; CString basePath; hres = SHGetSpecialFolderPath(this-&gt;GetSafeHwnd(), basePath.GetBuffer(MAX_PATH), CSIDL_APPDATA, FALSE); basePath.ReleaseBuffer(); </code></pre> <p>I suspect this is just a matter of knowing which sub-folder Microsoft uses.</p> <p>Under Windows XP, the app data subfolder is:</p> <p>Microsoft\Internet Explorer\Quick Launch</p> <p>Under Vista, it appears that the sub-folder has been changed to:</p> <p>Roaming\Microsoft\Internet Explorer\Quick Launch</p> <p>but I'd like to make sure that this is the correct way to determine the correct location.</p> <p>Finding the <em>correct</em> way to determine this location is quite important, as relying on hard coded folder names almost always breaks as you move into international installs, etc... The fact that the folder is named 'Roaming' in Vista makes me wonder if there is some special handling related to that folder (akin to the Local Settings folder under XP).</p> <p>EDIT: The following msdn article: <a href="http://msdn.microsoft.com/en-us/library/bb762494.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb762494.aspx</a> indicates that CSIDL_APPDATA has an equivalent ID of FOLDERID_RoamingAppData, which does seem to support StocksR's assertion that CSIDL_APPDATA does return C:\Users\xxxx\AppData\Roaming, so it should be possible to use the same relative path for CSIDL_APPDATA to get to quick launch (\Microsoft\Internet Explorer\Quick Launch).</p> <p>So the following algorithm is correct per MS:</p> <pre><code>HRESULT hres; CString basePath; hres = SHGetSpecialFolderPath(this-&gt;GetSafeHwnd(), basePath.GetBuffer(MAX_PATH), CSIDL_APPDATA, FALSE); basePath.ReleaseBuffer(); CString qlPath = basePath + "\\Microsoft\\Internet Explorer\\Quick Launch"; </code></pre> <p>it would also be a good idea to check hres to ensure that the call to SHGetSpecialFolderPath was successful.</p>
<p>AppData on vista refers to C:\Users\xxxx\AppData\Roaming not the C:\Users\xxxx\AppData folder it's self.</p> <p>Also this artical <a href="http://www.microsoft.com/technet/scriptcenter/resources/qanda/sept05/hey0901.mspx" rel="nofollow noreferrer">http://www.microsoft.com/technet/scriptcenter/resources/qanda/sept05/hey0901.mspx</a> on a microsoft site implies that you simply have to use the path relative to the appdata folder </p>
<p>Great question! </p> <p>Whatever you do, <strong>don't</strong> give into the temptation to <a href="http://blogs.msdn.com/oldnewthing/archive/2003/11/03/55532.aspx" rel="nofollow noreferrer">dig into the registry</a> to find this info!</p> <p>Also, we must resist the temptation to hard code some path, even partially. If we get the special AppData path, then simply append a string onto the end, this may break under non-US installs of the software where the folder name is localized to that language. E.g. <code>GetSpecialFolderPath(APP_DATA) + "\\Fonts"</code> will not work on non-English versions of Windows.</p> <p>Hopefully someone has the proper answer to your question; I'm curious to know it myself!</p>
10,172