instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>Sight is one of the senses most programmers take for granted. Most programmers would spend hours looking at a computer monitor (especially during times when they are <em>in the zone</em>), but I know there are blind programmers (such as T.V. Raman who currently works for Google).</p> <p>If you were a blind person (or slowly becoming blind), how would you set up your development environment to assist you in programming?</p> <p>(One suggestion per answer please. The purpose of this question is to bring the good ideas to the top. In addition, screen readers can read the good ideas earlier.)</p>
<p>I am a totally blind college student who’s had several programming internships so my answer will be based off these. I use windows xp as my operating system and <a href="http://freedomscientific.com/products/fs/jaws-product-page.asp" rel="noreferrer">Jaws</a> to read what appears on the screen to me in synthetic speech. For java programming I use eclipse, since it’s a fully featured IDE that is accessible. </p> <p>In my experience as a general rule java programs that use SWT as the GUI toolkit are more accessible then programs that use Swing which is why I stay away from netbeans. For any .net programming I use visual studio 2005 since it was the standard version used at my internship and is very accessible using Jaws and a set of scripts that were developed to make things such as the form designer more accessible. </p> <p>For C and C++ programming I use cygwin with gcc as my compiler and emacs or vim as my editor depending on what I need to do. A lot of my internship involved programming for Z/OS. I used an rlogin session through Cygwin to access the USS subsystem on the mainframe and C3270 as my 3270 emulator to access the ISPF portion of the mainframe. </p> <p>I usually rely on synthetic speech but do have a Braille display. I find I usually work faster with speech but use the Braille display in situations where punctuation matters and gets complicated. Examples of this are if statements with lots of nested parenthesis’s and JCL where punctuation is incredibly important.</p> <h2>Update</h2> <p>I'm playing with Emacspeak under cygwin <a href="http://emacspeak.sourceforge.net" rel="noreferrer">http://emacspeak.sourceforge.net</a> I'm not sure if this will be usable as a programming editor since it appears to be somewhat unresponsive but I haven't looked at any of the configuration options yet.</p>
<p>What about inventing some kind of device that you plug in a usb port and that would be basically a "sheet of rubber" that would modify itself to show brail of your code, allowing blind people to read it instead to hear it?</p>
14,474
<p>I do TDD, and I've been fairly loose in organizing my unit tests. I tend to start with a file representing the next story or chunk of functionality and write all the unit-tests to make that work. </p> <p>Of course, if I'm introducing a new class, I usually make a separate unit-test module or file for that class, but I don't organize the tests themselves into any higher level structure. The result is I write code fast and I believe my actual program is reasonably well structured, but the unit tests themselves are "messy". Especially, their structure tends to recapitulate the phylogeny of the development process. Sometimes I see myself as trading laziness in the code for laziness in the tests. </p> <p>How big a problem is this? Who here continually refactors and reorganizes their unit tests to try to improve their overall structure? Any tips for this? What should the overall structure of tests look like.</p> <p>(Note, that I'm not so much asking the "how many assertions per function" question asked here : <a href="https://stackoverflow.com/questions/110430/how-do-you-organize-unit-tests">How many unit tests should I write per function/method?</a> I'm talking about the bigger picture.)</p>
<p>Divide your tests in 2 sets:</p> <ul> <li>functional tests</li> <li>units tests</li> </ul> <p>Functional tests are per-user story. Unit tests are per-class. The former check that you actually support the story, the latter exercise and document your functionality.</p> <p>There is one directory (package) for functional tests. Unit tests should be closely bound with functionality they exercise (so they're scattered). You move them around and refactor them as you move &amp; refactor your code around.</p>
<p>I try to look at the unit tests as a project on their own. As with any project the organisation should follow some internal logic. It does not however have to be specific or formally defined - anything you're comfortable with is OK as long as it keeps your project well-organised and clean.</p> <p>So for the unit tests I usually either follow the main project code structure or (sometimes when the situation calls of it) focus on the functional areas instead.</p> <p>Leaving them in one heap is as you might imagine messy and difficult to maintain</p>
18,488
<p>I often use the <code>execv()</code> function in C++, but if some of the arguments are in C++ strings, it annoys me that I cannot do this:</p> <pre><code>const char *args[4]; args[0] = &quot;/usr/bin/whatever&quot;; args[1] = filename.c_str(); args[2] = someparameter.c_str(); args[3] = 0; execv(args[0], args); </code></pre> <p>This doesn't compile because <code>execv()</code> takes <code>char *const argv[]</code> which is not compatible with <code>const char *</code>, so I have to copy my <code>std::string</code>s to character arrays using <code>strdup()</code>, which is a pain.</p> <p>Does anyone know the reason for this?</p>
<p>The Open Group Base Specifications explains why this is: for compatibility with existing C code. Neither the pointers nor the string contents themselves are intended to be changed, though. Thus, in this case, you can get away with <code>const_cast</code>-ing the result of <code>c_str()</code>.</p> <p><a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html" rel="noreferrer">Quote:</a></p> <blockquote> <p>The statement about <code>argv[]</code> and <code>envp[]</code> being constants is included to make explicit to future writers of language bindings that these objects are completely constant. Due to a limitation of the ISO C standard, it is not possible to state that idea in standard C. Specifying two levels of <code>const</code>- qualification for the <code>argv[]</code> and <code>envp[]</code> parameters for the exec functions may seem to be the natural choice, given that these functions do not modify either the array of pointers or the characters to which the function points, but this would disallow existing correct code. Instead, only the array of pointers is noted as constant.</p> </blockquote> <p>The table and text after that is even more insightful. However, Stack Overflow doesn't allow tables to be inserted, so the quote above should be enough context for you to search for the right place in the linked document.</p>
<p>I have usually hacked this with:</p> <pre><code>#define execve xexecve #include &lt;...&gt; #include &lt;...&gt; #include &lt;...&gt; #undef execve // in case of c++ extern "C" { int execve(const char * filename, char ** argvs, char * const * envp); } </code></pre> <p>;/</p>
23,075
<p>How do I detect when an iOS app is launched for the first time?</p>
<p>Pretty much what Marc and Chris said, though I prefer to change the value when the app quits in case there're multiple areas of the application that need to know about it. In code:</p> <p><strong>Objective-C</strong></p> <pre><code>// -applicationDidFinishLaunching: [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"firstLaunch",nil]]; // to check it: [[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"]; // -applicationWillTerminate: [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"firstLaunch"]; </code></pre> <p><strong>Swift 5.0</strong></p> <pre><code>// -applicationDidFinishLaunching: UserDefaults.standard.register(defaults: ["firstLaunch":true]) // to check it: UserDefaults.standard.bool(forKey: "firstLaunch") // -applicationWillTerminate: UserDefaults.standard.set(false, forKey: "firstLaunch") </code></pre>
<p>You can set a boolean value in the user defaults to do this. Set the key to false when you call <code>registerDefaults:</code>, and then set it to true change it to true after you've shown your initial help screen or whatever you need to do.</p> <p>If you have a persistent data file that's always saved after the app closes, checking to see if it exists would be another way.</p>
39,787
<p>I have a PHP application that displays a list of options to a user. The list is generated from a simple query against SQL 2000. What I would like to do is have a specific option at the top of the list, and then have the remaining options sorted alphabetically.</p> <p>For example, here's the options if sorted alphabetically: </p> <pre><code>Calgary Edmonton Halifax Montreal Toronto </code></pre> <p>What I would like the list to be is more like this: </p> <pre><code>**Montreal** Calgary Edmonton Halifax Toronto </code></pre> <p>Is there a way that I can do this using a single query? Or am I stuck running the query twice and appending the results?</p>
<pre><code>SELECT name FROM locations ORDER BY CASE WHEN name = 'Montreal' THEN 0 ELSE 1 END, name </code></pre>
<pre><code>create table Places ( add Name varchar(30), add Priority bit ) select Name from Places order by Priority desc, Name </code></pre>
10,859
<p>What is the Win32 API call to determine the system-wide font (in particular the color) for say Menus.</p> <p>This would be equivalent to going into Appearance Settings - Advanced - and then choosing Menu as the item to look at.</p> <p>I can use GetSysColor to find the colors of various system-wide window elements, but cannot find the equivalent for fonts.</p>
<p>GetSysColor(COLOR_MENUTEXT) gives you the menu font colour.</p> <p>SystemParametersInfo Will allow you to recover some font information, likewise GetStockObject for drawing on the device context.</p> <p>But the system font is (probably) either Tahoma (on XP/W2K) or MS Sans Serif depending on how you set up your Dialog.</p> <p>See <a href="http://blogs.msdn.com/oldnewthing/archive/2005/02/04/366987.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/oldnewthing/archive/2005/02/04/366987.aspx</a> for more.</p>
<p>In C#, there's <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.defaultfont.aspx" rel="nofollow noreferrer">Control.DefaultFont</a>, and for native access, <a href="http://blogs.msdn.com/oldnewthing/archive/2005/03/09/390706.aspx" rel="nofollow noreferrer">this blog</a> describes the win32 API call for getting it. The API call is SystemParametersInfo().</p>
26,550
<p>My application is using <strong>Dojo 1.1.1</strong> on an <em>SSL-only</em> website. It is currently taking advantage of <code>dijit.ProgressBar</code> and a <code>dijit.form.DateTextBox</code>.</p> <p>Everything works fabulous in <em>Firefox 2 &amp; 3</em>, but as soon as I try the same scripts in <em>IE7</em> the results are an annoying Security Information dialog:</p> <blockquote> <p>This page contains both secure and non-secure items. Do you want to display the non-secure items?</p> </blockquote> <p>I have scrutinized the page for any <em>non-HTTPS</em> reference to no avail. It appears to be something specific to <code>dojo.js</code>. There use to be an <code>iframe</code> glitch where the <code>src</code> was set to nothing, but this appears to be fixed now (on review of the source).</p> <p>Anyone else having this problem? What are the best-practices for getting <em>Dojo</em> to play well with <em>IE</em> on an <em>SSL-only</em> web server?</p>
<p>After reviewing the JavaScript sourcecode for Dijit, I thought it was likely the error results from an "insecure" refrence to a dynamically generated IFRAME. Note there are two versions of the script file, the uncompressed represents the original source (dijit.js.uncompressed.js) and the standard (dijit.js) has been compressed for optimal transfer time. </p> <p>Since the uncompressed version is the most readable, I will describe my solution based on that. At line #1023, an IFRAME is rendered in JavaScript:</p> <pre><code>if(dojo.isIE){ var html="&lt;iframe src='javascript:\"\"'" + " style='position: absolute; left: 0px; top: 0px;" + "z-index: -1; filter:Alpha(Opacity=\"0\");'&gt;"; iframe = dojo.doc.createElement(html); }else{... </code></pre> <p>What's the problem? IE doesn't know if the src for the IFRAME is "secure" - so I replaced it with the following:</p> <pre><code>if(dojo.isIE){ var html="&lt;iframe src='javascript:void(0);'" + " style='position: absolute; left: 0px; top: 0px;" + "z-index: -1; filter:Alpha(Opacity=\"0\");'&gt;"; iframe = dojo.doc.createElement(html); }else{... </code></pre> <p>This is the most common problem with JavaScript toolkits and SSL in IE. Since IFRAME's are used as shims due to poor overlay support for DIV's, this problem is extremely prevalent. </p> <p>My first 5-10 page reloads are fine, but then the security error starts popping up again. How is this possible? The same page is "secure" for 5 reloads and then it is selected by IE as "insecure" when loaded the 6th time.</p> <p>As it turns out, there is also a background image being set in the onload event for dijit.wai (line #1325). This reads something like this;</p> <pre><code>div.style.cssText = 'border: 1px solid;' + 'border-color:red green;' + 'position: absolute;' + 'height: 5px;' + 'top: -999px;' + 'background-image: url("' + dojo.moduleUrl("dojo", "resources/blank.gif") + '");'; </code></pre> <p>This won't work because the background-image tag doesn't include HTTPs. Despite the fact that the location is relative, IE7 doesn't know if it's secure so the warning is posed.</p> <p>In this particular instance, this CSS is used to test for Accessibility (A11y) in Dojo. Since this is not something my application will support and since there are other general buggy issues with this method, I opted to remove everything in the onload() for dijit.wai.</p> <p>All is good! No sporadic security problems with the page loads.</p>
<p>If your page is loading files from a non-https URL Firefox should tell you the same thing. Instead of an error the lock symbol at the bottom (in the status bar) should be crossed out. Are you sure that is not the case?</p> <p>If you see the symbol, click on it and check which files are "unsecure".</p>
8,441
<p>In cake 1.2 there is a feature that allows the developer to no have to create models, but rather have cake do the detective work at run time and create the model for you. This process happens each time and is neat but in my case very hazardous. I read about this somewhere and now I'm experiencing the bad side of this.</p> <p>I've created a plugin with all the files and everything appeared to be just great. That is until i tried to use some of the model's associations and functions. Then cake claims that this model i've created doesn't exist. <strong>I've narrowed it down to cake using this auto model feature instead of throwing and error</strong>! So i have no idea what's wrong!</p> <p>Does anybody know how to disable this auto model feature? It's a good thought, but I can't seem to find where i've gone wrong with my plugin and an error would be very helpful!</p>
<p><strong>Cake 1.2</strong></p> <p>It's a hack and it's ugly cus you need to edit core cake files but this is how i do it: \cake\libs\class_registry.php : line 127ish</p> <pre><code>if (App::import($type, $plugin . $class)) { ${$class} =&amp; new $class($options); } elseif ($type === 'Model') { /* Print out whatever debug info we have then exit */ pr($objects); die("unable to find class $type, $plugin$class"); /* We don't want to base this on the app model */ ${$class} =&amp; new AppModel($options); } </code></pre> <p><strong>Cake 2</strong></p> <p>Costa recommends changing $strict to true in the init function on line 95 of <code>Cake\Utility\ClassRegistry.php</code></p> <p><a href="http://api.cakephp.org/2.3/class-ClassRegistry.html#_init" rel="nofollow noreferrer">See Cake Api Docs for init</a></p> <p><a href="https://github.com/cakephp/cakephp/blob/c989624f8053f28d2ac37f5e84dc436965235177/lib/Cake/Utility/ClassRegistry.php#L96" rel="nofollow noreferrer">ClassRegistry.php - init function </a></p>
<p>Uh...where do we start. First, as Alexander suggested, clear your app cache.</p> <p>If you still get the same behaviour, there is probably something wrong with the class and/or file names.</p> <p>Remember <a href="http://book.cakephp.org/view/23/File-and-Classname-Conventions" rel="nofollow noreferrer">the rules</a>, for controller:</p> <pre><code>* classname: BlastsController * filename: blasts_controller.php </code></pre> <p>for model:</p> <pre><code>* classname: Blast * filename: blast.php </code></pre> <p>Don't foget to <a href="http://book.cakephp.org/view/47/Inflections" rel="nofollow noreferrer">handle the irregular inflections</a> properly.</p>
12,566
<p>I've been recently asked to learn some MATLAB basics for a class.</p> <p>What does make it so cool for researchers and people that works in university? I saw it's cool to work with matrices and plotting things... (things that can be done easily in Python using some libraries).</p> <p>Writing a function or parsing a file is just painful. I'm still at the start, what am I missing?</p> <p>In the "real" world, what should I think to use it for? When should it can do better than Python? For better I mean: easy way to write something performing.</p> <hr> <p><strong>UPDATE 1:</strong> One of the things I'd like to know the most is "Am I missing something?" :D</p> <p><strong>UPDATE 2:</strong> Thank you for your answers. My question is not about buy or not to buy MATLAB. The university has the possibility to give me a copy of an old version of MATLAB (MATLAB 5 I guess) for free, without breaking the license. I'm interested in its capabilities and if it deserves a deeper study (I won't need anything more than <em>basic</em> MATLAB in oder to pass the exam :P ) it will really be better than Python for a specific kind of task in the real world.</p>
<p>Adam is only partially right. Many, if not most, mathematicians will never touch it. If there is a computer tool used at all, it's going to be something like <a href="http://en.wikipedia.org/wiki/Mathematica" rel="noreferrer">Mathematica</a> or <a href="http://en.wikipedia.org/wiki/Maple_(software)" rel="noreferrer">Maple</a>. Engineering departments, on the other hand, often rely on it and there are definitely useful things for some applied mathematicians. It's also used heavily in industry in some areas.</p> <p>Something you have to realize about MATLAB is that it started off as a wrapper on <a href="http://en.wikipedia.org/wiki/Fortran" rel="noreferrer">Fortran</a> libraries for linear algebra. For a long time, it had an attitude that "all the world is an array of doubles (floats)". As a language, it has grown very organically, and there are some flaws that are very much baked in, if you look at it just as a programming language.</p> <p>However, if you look at it as an environment for doing certain types of research in, it has some real strengths. It's about as good as it gets for doing floating point linear algebra. The notation is simple and powerful, the implementation fast and trusted. It is very good at generating plots and other interactive tasks. There are a large number of `toolboxes' with good code for particular tasks, that are affordable. There is a large community of users that share numerical codes (Python + <a href="http://en.wikipedia.org/wiki/NumPy" rel="noreferrer">NumPy</a> has nothing in the same league, at least yet)</p> <p>Python, warts and all, is a much better programming language (as are many others). However, it's a decade or so behind in terms of the tools.</p> <p>The key point is that the majority of people who use MATLAB are not programmers really, and don't want to be. </p> <p>It's a lousy choice for a general programming language; it's quirky, slow for many tasks (you need to vectorize things to get efficient codes), and not easy to integrate with the outside world. On the other hand, for the things it is good at, it is very very good. Very few things compare. There's a company with reasonable support and who knows how many man-years put into it. This can matter in industry.</p> <p>Strictly looking at your Python vs. MATLAB comparison, they are mostly different tools for different jobs. In the areas where they do overlap a bit, it's hard to say what the better route to go is (depends a lot on what you're trying to do). But mostly Python isn't all that good at MATLAB's core strengths, and vice versa.</p>
<p>The main reason it is useful in industry is the plug-ins built on top of the core functionality. Almost all active Matlab development for the last few years has focused on these. </p> <p>Unfortunately, you won't have much opportunity to use these in an academic environment.</p>
21,704
<p>First a little intro:</p> <p>Last year i wrote this <a href="http://dragan.yourtree.org/code/canvas-3d-graph/" rel="noreferrer">http://dragan.yourtree.org/code/canvas-3d-graph/</a></p> <p>Now, i want to make complete rewrite of it, because that old version have some limitations, for example: sometimes it happens that bars are not visible, because they are drawn one behind another.</p> <p>In this old version there is no real 3d, just bunck of 2D lines, which emulate 3D.</p> <p>Now, what i want is to go to full blown 3D scene, i want to keep all the objects in memory, and add some kind of 3D navigation buttons that will enable users to rotate whole scene on all 3 axis, and zoom camera in and out.</p> <p>I've already decided that i will use <a href="http://sylvester.jcoglan.com/" rel="noreferrer">http://sylvester.jcoglan.com/</a> for vector/matrix stuff, but i'm still unable to find good tutorial for 3D. There are tons of texts on the Internet, most of them date from the 90s, an are incomplete or written really bad.</p> <p>So, my question is: what is the best online resource/tutorial that will enable me to write my own JS 3D engine from scratch.</p> <p>It should cover all relevant topics:</p> <ul> <li>vectors</li> <li>matrices</li> <li>objects</li> <li>camera</li> <li>scene rendering</li> <li>lighting</li> <li>rotating objects on scene</li> <li>moving the camera</li> </ul> <p>etc.. (i'm fairly familiar with first two)</p> <p>Thank you for your time.</p>
<p>If this is specifically for a JavaScript related project then I understand but if you are simply doing this to grasp the basics of 3d rendering there might be more mature platforms out there for you. </p> <p>In any case..</p> <p>Links that might be useful to your learning:</p> <ul> <li><a href="http://hem.spray.se/vilius/js3Dtutor.html" rel="nofollow noreferrer">Prototyping A Simple 3d Renderer In JavaScript</a></li> <li><a href="http://www.gamedev.net/reference/articles/article673.asp" rel="nofollow noreferrer">3D Basics - A Primer</a></li> <li><a href="http://www.slimeland.com/raytrace/help.html" rel="nofollow noreferrer">The JavaScript Raytracer</a></li> <li><a href="http://www.nihilogic.dk/labs/canvas3dtexture_0.2/" rel="nofollow noreferrer">JavaScript 3D Renderer </a></li> </ul> <p>Also, some fun JavaScript 3d examples:</p> <ul> <li><a href="http://maettig.com/code/javascript/3d_dots.html" rel="nofollow noreferrer">Rotating 3D Cube in JavaScript</a></li> <li><a href="http://blog.nihilogic.dk/2008/04/javascript-wolfenstein-3d.html" rel="nofollow noreferrer">Wolfenstein 3D in JavaScript</a></li> <li>Anything else in this SO Question: <a href="https://stackoverflow.com/questions/254535/stunning-graphic-effects-with-javascript">Stunning graphic effects with JavaScript?</a></li> </ul>
<p>Just a couple of suggestions, but probably not exactly what you're looking for:</p> <p>I suggest that you take a look at Jacob Seidelin's canvas examples at nihilogic.dk : <a href="http://blog.nihilogic.dk/search/label/canvas" rel="nofollow noreferrer"><a href="http://blog.nihilogic.dk/search/label/canvas" rel="nofollow noreferrer">http://blog.nihilogic.dk/search/label/canvas</a></a> .</p> <p>If you're willing to abandon canvas and go with an existing flash library, take a look at Sandy3D : <a href="http://www.flashsandy.org/demos" rel="nofollow noreferrer">http://www.flashsandy.org/demos</a> .</p>
49,838
<p>I'm writing a program that creates a Word document with sensitive information. I'd like to encrypt and password protect the document and distribute it in a self-extracting file so that the user can double-click, provide a password, and then receive the unencrypted file.</p> <p>I'm okay creating the Word document, but I'd like a third-party program, scriptable or not (I can use the command-line), that can:</p> <ol> <li>Encrypt the Word document,</li> <li>Password-Protect the encryption, and</li> <li>Create a self-extracting file.</li> </ol> <p>Can anyone suggest software for this purpose? Anything of SSL security or higher is sufficient since the data was formerly hosted on an SSL-encrypted site.</p>
<p><a href="http://www.finecrypt.net/" rel="nofollow noreferrer">finecrypt.net</a> should met your requirements (free version <a href="http://www.finecrypt.net/download.html" rel="nofollow noreferrer">here</a>)</p> <p><img src="https://i.stack.imgur.com/O5D8n.gif" alt="Finecrypt"></p>
<p>If you want to encrypt a Word document, dinamically on a LAMP server, exactly as MS Word does, you may use the Crypto API of PHPDocX: <a href="http://www.phpdocx.com/documentation/cryptophpdocx-word-document-protection-and-encryption-with-php" rel="nofollow">CryptoPHPDocX</a>.</p> <p>Take into account the encrypted MS Word files are MS Compound File Binaries and not standard OOXML/OPC files.</p> <p>The advantages over other solutions are:</p> <ul> <li>Office recognizes directly the encrypted files as Word files</li> <li>Word prompts you directly to introduce a password </li> <li>Whenever the modified Word document is saved it preserves its encrypted status</li> <li>Encryption algorithm is AES128</li> </ul> <p>The CryptoPHPDocX API also allows for document protection (not secure but pretty useful to exachange documents that you want to protect from direct edition) and can also encrypt PDF files.</p>
37,847
<p>I have a NotifyIcon control that appears in the system tray. How can I find the location (x, y) of the icon on the screen?</p> <p>Thanks</p>
<p>Actually you can do this, here is code that shows you how and much more.</p> <p>In any Mouse Event from NotifyIcon, simply look at Control.MousePosition, this contains the (x,y) of the mouse. The same can be done to position a ContextMenu on a form/control exactly where the form/control was clicked using these (x,y) values.</p> <p>A good example of both of these is here:</p> <p>More Here: <a href="http://code.msdn.microsoft.com/TheNotifyIconExample" rel="noreferrer">http://code.msdn.microsoft.com/TheNotifyIconExample</a></p>
<p>You can't. It isn't hard to get the window handle for the system tray, GetClassName() returns "ToolbarWindow32", the class name of the standard TOOLBAR common control. Beware that a 64-bit OS has two of them. Then you can send messages to it like TB_GETBUTTONINFO. Chief hang-ups are that you won't know what button ID to choose and the returned info does not include the button position.</p> <p>Which is for the better, buttons move around without you being able to lock them.</p>
34,347
<p>I didn't find an explicit answer to this question in the WiX Documentation (or Google, for that matter). Of course I could just write the appropriate registry keys in HKCR, but it makes me feel dirty and I'd expect this to be a standard task which should have a nice default solution.</p> <p>For bonus points, I'd like to know how to make it "safe", i.e. don't overwrite existing registrations for the file type and remove the registration on uninstall only if it has been registered during installation and is unchanged.</p>
<p>After some additional research, I found a partial answer to this question in the <a href="http://www.tramontana.co.hu/wix/lesson1.php#1.7" rel="noreferrer">WiX Tutorial</a>. It shows an advertised solution and does not work with WiX 3.0, but given that information, I figured it out. Add a ProgId element to the component containing your executable, like the following:</p> <pre><code>&lt;ProgId Id=&quot;MyApplication.MyFile&quot; Description=&quot;My file type&quot;&gt; &lt;Extension Id=&quot;myext&quot; ContentType=&quot;application/whatever&quot;&gt; &lt;Verb Id=&quot;open&quot; Command=&quot;open&quot; TargetFile=&quot;MyApplication.exe&quot; Argument=&quot;&amp;quot;%1&amp;quot;&quot;/&gt; &lt;/Extension&gt; &lt;/ProgId&gt; </code></pre> <p>myext is the file extension without the dot, and MyApplication.exe is the file id (not name) of the executable file (i.e. the Id attribute of the File element). This will register the file type with your executable and will supply a default icon (a white page with the application icon on it), which is sufficient for my needs. If you want to specify a dedicated icon, it seems you still have to do this yourself, like the following (code from the linked tutorial):</p> <pre><code>&lt;Registry Id='FooIcon1' Root='HKCR' Key='.xyz' Action='write' Type='string' Value='AcmeFoobar.xyzfile' /&gt; &lt;Registry Id='FooIcon2' Root='HKCR' Key='AcmeFoobar.xyzfile' Action='write' Type='string' Value='Acme Foobar data file' /&gt; &lt;Registry Id='FooIcon3' Root='HKCR' Key='AcmeFoobar.xyzfile\DefaultIcon' Action='write' Type='string' Value='[INSTALLDIR]Foobar.exe,1' /&gt; </code></pre> <p>I didn't find a good solution for my bonus question though.</p> <p>Edit: I started writing this before the previous answer came. However, my solution actually works, in contrast to the previous answer.</p>
<p>"If your application handles its own file data type, you will need to register a file association for it. Put a ProgId inside your component. FileId should refer to the Id attribute of the File element describing the file meant to handle the files of this extension. Note the exclamation mark: it will return the short path of the file instead of the long one:"</p> <pre><code>&lt;ProgId Id='AcmeFoobar.xyzfile' Description='Acme Foobar data file'&gt; &lt;Extension Id='xyz' ContentType='application/xyz'&gt; &lt;Verb Id='open' Sequence='10' Command='Open' Target='[!FileId]' Argument='"%1"' /&gt; &lt;/Extension&gt; &lt;/ProgId&gt; </code></pre> <p>Reference: <a href="https://www.firegiant.com/wix/tutorial/getting-started/beyond-files/" rel="nofollow noreferrer">https://www.firegiant.com/wix/tutorial/getting-started/beyond-files/</a></p>
16,778
<p>I have some very simple code to generate an assembly and invoke a method on a contained type. The method gets called and runs correctly, however when I view the generated assembly using Reflector, I don't see the type.</p> <p>Below is the sample code:</p> <pre><code>namespace ConsoleApplication2 { class Proggy { public static void Main(string[] args) { var ab = AppDomain.CurrentDomain.DefineDynamicAssembly( new AssemblyName() { Name = "MyAssembly" }, AssemblyBuilderAccess.RunAndSave); var module = ab.DefineDynamicModule(ab.GetName().Name); var typeBuilder = module.DefineType("MyType"); var ctr = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes); var ilgc = ctr.GetILGenerator(); ilgc.Emit(OpCodes.Ldarg_0); ilgc.Emit(OpCodes.Call, typeof(object).GetConstructor(Type.EmptyTypes)); ilgc.Emit(OpCodes.Ret); var method = typeBuilder.DefineMethod("MyMethod", MethodAttributes.Public, typeof(int), new[] { typeof(string) }); var ilg = method.GetILGenerator(); ilg.Emit(OpCodes.Ldarg_1); ilg.EmitCall(OpCodes.Callvirt, typeof(string).GetProperty("Length").GetGetMethod(), null); ilg.Emit(OpCodes.Ret); var type = typeBuilder.CreateType(); ab.Save("mytestasm.dll"); var inst = Activator.CreateInstance(type); Console.WriteLine(type.InvokeMember("MyMethod", BindingFlags.InvokeMethod, null, inst, new[] { "MyTestString" })); Console.ReadLine(); } } } </code></pre> <p>and here is the corresponding disassembly from Reflector:</p> <pre><code>.assembly MyAssembly { .ver 0:0:0:0 .hash algorithm 0x00008004 } .module RefEmit_OnDiskManifestModule // MVID: {0B944140-58D9-430E-A867-DE0AD0A8701F} // Target Runtime Version: v2.0.50727 </code></pre> <p>... and ...</p> <pre><code>{ .class private auto ansi &lt;Module&gt; { } } </code></pre> <p>Can anyone help me with getting the assembly properly saved?</p>
<p>The trick is to use a "persistable module" version of DefineDynamicModule method on the AssemblyBuilder instance. That is, instead of:</p> <pre><code>var module = ab.DefineDynamicModule(ab.GetName().Name); </code></pre> <p>use something like:</p> <pre><code>var module = ab.DefineDynamicModule(ab.GetName().Name, ab.GetName().Name + ".mod"); </code></pre> <p>Thereafter the corresponding module appears in the assembly after saving.</p>
<p>I am not sure why the type is not getting added. </p> <p>Another way of doing this however is to dynamically create code by just passing in a string which contains your class code. I think this is a bit easier than the above way of doing it as you can just build up the code using a string builder and test in studio.</p> <p>Here is the code i use to generate a dll:</p> <pre><code>print(" Microsoft.CSharp.CSharpCodeProvider objCodeProvider = new Microsoft.CSharp.CSharpCodeProvider(); string strCode = "using System;" + Environment.NewLine + "using System.Data;" + Environment.NewLine + "using DC.Common;" + Environment.NewLine + "" + Environment.NewLine + "using System.Data.SqlClient;" + Environment.NewLine + "using System.Configuration;" + Environment.NewLine + "" + Environment.NewLine + Environment.NewLine + BaseClassFile + Environment.NewLine + BaseManagerFile + Environment.NewLine; string strSourceModule = BuilderSettings.ExportDir + "/" + BuilderSettings.ProjectName + "/" + "BaseFile.cs"; FileHelper.WriteAllText(strSourceModule, strCode); FileHelper.WriteAllText(BuilderSettings.ExportDir + "/" + BuilderSettings.ProjectName + "/" + "test.txt", strCode); ICodeCompiler icc = objCodeProvider.CreateCompiler(); string OutputPath = BuilderSettings.ExportDir + "/" + BuilderSettings.ProjectName + "/" + BuilderSettings.ProjectName + ".dll"; CompilerParameters parameters = new CompilerParameters(); CompilerResults results; parameters.GenerateExecutable = false; parameters.OutputAssembly = OutputPath; parameters.GenerateInMemory = false; parameters.IncludeDebugInformation = false; //Add required assemblies DynamicLinkLibraries.Clear(); //User defined DynamicLinkLibraries.Add(@"d:\wwwroot\\DC.Common\bin\Debug\DC.Common.dll"); //System DynamicLinkLibraries.Add("System.dll"); DynamicLinkLibraries.Add("System.Data.dll"); DynamicLinkLibraries.Add("mscorlib.dll"); DynamicLinkLibraries.Add("System.xml.dll"); DynamicLinkLibraries.Add("System.web.dll"); DynamicLinkLibraries.Add("System.configuration.dll"); //Any dynamic assembly adding must be done here foreach (string strLibrary in DynamicLinkLibraries) { parameters.ReferencedAssemblies.Add(strLibrary); } results = icc.CompileAssemblyFromSource(parameters, strCode); if (results.Errors.Count &gt; 0) { //report any compilation errors string strErrors = "Compilation failed:" + Environment.NewLine; foreach (CompilerError oError in results.Errors) { strErrors = strErrors + "Line number " + oError.Line + ", Error Number: " + oError.ErrorNumber + ", '" + oError.ErrorText + ";"; } throw new Exception("Error in CompileSourceCode(): " + Environment.NewLine + strErrors); } objCodeProvider = null; icc = null; parameters = null;"); </code></pre>
23,565
<p>I'm stuck with the following:</p> <p>I have an Access2003 report "rptInvoices". Group levels are on CustomerID and PackingListID. </p> <p>What I like to achieve is that every 2nd (or 3rd etc.) page of an invoice starts with a blank section (of say 9cm) at the top of the page. For this I would use an empty PageHeader section. If the Report's property PageHeader had a value like NotWithGroupHeaderX, this would be easy. </p> <p>Since there isn't such a value: how can I hide the PageHeader on a report if there's a GroupHeader named grhCustomerID on that page?</p> <p>Maybe I need a different approach, but I just don't see it.</p>
<p>In the groupheader <code>format event</code> set the <code>pageheadersection.visible</code> to <code>true</code> so the page header prints for pages after the group header. In the group footer format event set the <code>pageheadersection.visible</code> to <code>false</code> so the page header does not print at the top of the next page which has the group header.</p>
<p>You can set the visible property of the page header in the format event of the group header.</p> <pre><code>Private Sub GroupHeader0_Format(Cancel As Integer, FormatCount As Integer) Me.PageHeaderSection.Visible = False End Sub Private Sub Report_Page() Me.PageHeaderSection.Visible = True End Sub </code></pre>
49,442
<p>Is there a way to get the directory of a project in Eclipse? We are writing a plugin that will allow the user to select files, and then run some processes on those files. I would ideally like to be able to get all the files with a certain extension, but that is not necessary.</p>
<p>sure:</p> <pre><code>ResourcesPlugin.getWorkspace().getRoot().getProjects() </code></pre> <p>will get you a list of all the projects in the workspace. you can easily iterate to find the one you want. At that point, you can look for certain files by extensions, etc.</p>
<p>If you want to enable your users to select files inside eclipse workspace with a certain extension, you can look at the class <strong>org.eclipse.ui.dialogs.ElementTreeSelectionDialog</strong> (org.eclipse.ui.dialogs plugin)as a start.</p> <p>Then, to have an example on how to make it filter extensions, you can look at the class <strong>org.eclipse.jdt.internal.ui.viewsupport.FilteredElementTreeSelectionDialog</strong> (org.eclipse.jdt.ui plugin) to see how they do it and then reimplement the stuff.</p> <p>This should give you a higher level of action than going threw files inside projects by hand and reimplement dialogs.</p>
29,962
<p>What would be the best way to port an existing Drupal site to a Django application? I have around 500 pages (mostly books module) and around 50 blog posts. I'm not using any 3rd party modules. I would like to keep the current URLS (for SEO purposes) and migrate database to Django. I will create a simple blog application, so migrating blog posts should be ok. What would be the best way to serve 500+ pages with Django? I would like to use Admin to edit/add new pages.</p>
<p>All Django development is similar, and yours will fit the pattern.</p> <ol> <li><p>Define the Django model for your books and blog posts. </p></li> <li><p>Unit test that model using Django's built-in testing capabilities.</p></li> <li><p>Write some small utilities to load your legacy data into Django. At this point, you'll realize that your Django model isn't perfect. Good. Fix it. Fix the tests. Redo the loads. </p></li> <li><p>Configure the default admin interface to your model. At this point, you'll spend time tweaking the admin interface. You'll realize your data model is wrong. Which is a good thing. Fix your model. Fix your tests. Fix your loads. </p></li> <li><p>Now that your data is correct, you can create templates from your legacy pages.</p></li> <li><p>Create URL mappings and view functions to populate the templates from the data model.</p></li> </ol> <p>Take the time to get the data model right. It really matters, because everything else is very simple if your data model is solid.</p>
<p><a href="https://stackoverflow.com/a/210315/892951">S.Lott answer</a> is still valid after years, I try to complete the analysis with the tools and format to do the job.</p> <p>There are many Drupal export tools out of there by now but with the very same request I go for <a href="https://www.drupal.org/project/views_datasource" rel="nofollow noreferrer">Views Datasource</a> choosing JSON as format. This module is very solid and available for the last version of Drupal. The <a href="http://www.json.org/" rel="nofollow noreferrer">JSON</a> format is very fast in both parsing and encoding and it's easy to read and very Python-friendly (<a href="https://docs.python.org/2/library/json.html" rel="nofollow noreferrer">import json</a>).</p> <p>Using Views Datasource you can create a node view sorted by node id (nid), show a limited number of elements per page, configure a view path, add to it a filter identifier and pass to it the nid to read all elements until you get an empty JSON response.</p> <p>When importing in Django you have a wide set of tools as well, starting from <a href="https://docs.djangoproject.com/en/1.8/howto/initial-data/#providing-initial-data-with-fixtures" rel="nofollow noreferrer">loaddata to load fixtures</a>. Views Datasource exported JSON but it's not formatted as Django expects fixtures: you can write a <a href="https://docs.djangoproject.com/en/1.8/howto/custom-management-commands/" rel="nofollow noreferrer">custom admin command</a> to do the import, where you can have the full control of the import flow.</p> <p>You can start your command passing a nid=0 as argument and then let the procedure read, import and then fetch data from the next page passing simply the last nid read in the previous HTTP request. You can even restrict access to the path on view but you need additional configuration on the import side.</p> <p>Regarding performance, just for example I parsed and imported 15.000+ nodes in less than 10 minutes via a Django 1.8 custom admin command on an 8 core / 8 GB Linux virtual machine and <a href="http://www.postgresql.org/" rel="nofollow noreferrer">PostgreSQL</a> as DBMS, logging success and error information into a custom model for each node.</p> <p>These are the basics for import/export between these two platform, for detailed information I described all the <a href="https://chirale.wordpress.com/2015/10/10/guide-to-migrate-a-drupal-website-to-django-after-the-release-of-drupal-8/" rel="nofollow noreferrer">major steps for export from Drupal and then import to Django in this guide</a>.</p>
25,793
<p>I am writing a web app using TurboGears, and in that app the users must be able to generate different reports. The data the reports need is stored in a database (MySQL). The reports must be returned either as a easily printable html document, or a pdf file.</p> <p>I have previously used jasper and iReport for creating the documents, but if I can avoid having to fire up Java to create the report I would be happy.</p> <p>Ideally I would like to specify reports in a easily readable markup language and then just feed the template data with some kind of library that produces the report.</p> <p>I gladly accept any kind of hints on how I should go about generating these reports!</p>
<p>You can build some fancy PDFs from Python with the <a href="http://www.reportlab.com/opensource/" rel="nofollow noreferrer">ReportLab</a> toolkit.</p>
<p>A partial answer: the easily readable format you are looking for might be <a href="http://www.docbook.org/" rel="nofollow noreferrer">DocBook</a>. From there it is very easy to go to PDF, html, RTF, etc. etc.</p>
13,593
<p>Once again it is time to clean up my emacs setup. Before I go cleaning it up, are there any packages that you would recommend above and beyond c++-mode, cedet, ecb, speedbar etc. ? Especially stuff that's new in the last five years.</p>
<p><a href="https://stackoverflow.com/questions/271924/what-is-your-favourite-plugin-in-emacs">This could be helpful!</a></p>
<p>I use msf-abbrevs package for inserting code snippets as i type special code words - something like for, if, etc, but with highliting of positions, that should be filled out, and moving between them with TAB key</p>
45,659
<p>I'm using VB.net (2003), and calling the SelectNodes method on an xml document.<br> If I have a document:</p> <pre><code>&lt;InqRs&gt; &lt;DetRs&gt; &lt;RefInfo&gt; &lt;RefType&gt;StopNum&lt;/RefType&gt; &lt;RefId&gt;0&lt;/RefId&gt; &lt;/RefInfo&gt; &lt;RefInfo&gt; &lt;RefType&gt;Id&lt;/RefType&gt; &lt;RefId&gt;0&lt;/RefId&gt; &lt;/RefInfo&gt; &lt;/DetRs&gt; &lt;DetRs&gt; &lt;RefInfo&gt; &lt;RefType&gt;StopNum&lt;/RefType&gt; &lt;RefId&gt;0&lt;/RefId&gt; &lt;/RefInfo&gt; &lt;RefInfo&gt; &lt;RefType&gt;Id&lt;/RefType&gt; &lt;RefId&gt;1&lt;/RefId&gt; &lt;/RefInfo&gt; &lt;/DetRs&gt; &lt;/InqRs&gt; </code></pre> <p>How can I select just for the <code>DetRs</code> that has <code>RefType=Id</code> and <code>RefId=0</code>, ie, the 'first' one above?</p> <p>I've tried several different attempts, among others: </p> <pre><code>InqRs/DetRs[RefInfo/RefType='Id' and RefInfo/RefId='0'] InqRs/DetRs[RefInfo/RefType='Id'][RefInfo/RefId='0'] </code></pre> <p>But these select both of the DetRs sections (because of the StopNum RefId of 0, I presume). </p>
<p>You want all <strong><code>DetRs</code></strong> children of the top element:</p> <p>&nbsp;&nbsp;&nbsp;&nbsp;<code>/*/DetRs</code></p> <p>That have a <strong><code>RefInfo</code></strong> child:</p> <p>&nbsp;&nbsp;&nbsp;&nbsp;<code>/*/DetRs</code><br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<code>[RefInfo]</code></p> <p>That has <strong><code>RefType</code></strong> with value "<strong><code>Id</code></strong>": </p> <p>&nbsp;&nbsp;&nbsp;&nbsp;<code>/*/DetRs</code><br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<code>[RefInfo</code><br/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[<code>RefType</code>='<code>Id</code>']<br/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;]</p> <p>and that has a <strong><code>RefId</code></strong> with value <strong>0</strong>:</p> <p>&nbsp;&nbsp;&nbsp;&nbsp;<code>/*/DetRs</code><br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<code>[RefInfo</code><br/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[<code>RefType</code>='<code>Id</code>' <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<code>and</code><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<code>RefId</code>=0<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;]<br/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;]</p> <p><strong>And this XPath expression correctly selects just the wanted first <code>DetRs</code> element in the provided XML document</strong>.</p> <p>Certainly, if someone has other stylistic preferences, the above expression could be written also as:</p> <p>&nbsp;&nbsp;&nbsp;&nbsp;<strong><code>/*/DetRs[RefInfo[RefType='Id' and RefId=0]]</code></strong></p>
<p>Like so. You don't need the top-level InqRs in your XPath expression, though it doesn't hurt. You may not care about the DetRs either, but assuming you do, you want to say "give me the parent of the Refinfo element which has the following specification"</p> <pre><code>DetRs/Refinfo[RefType='Id' and RefId='0']/.. </code></pre>
47,748
<p>If you create a pure ActionScript project in Flex Builder 3 and want to do unit testing using flexunit, what is the best option?</p> <p>The built-in Flex builder will refuse to build the mxml file containing the TestRunnerBase component as it is a pure ActionScript project (no Flex allowed). It is impossible to add the mxml file to the "ActionScript Applications" list in the project settings.</p> <p>Right now I can see two options, both undesirable.</p> <ol> <li>Add the unit testing mxml file to the project and create an external tool setup to build and run it. This is the approach I'm taking now, and it works fine, except that interactive debugging is impossible.</li> <li>Create a new Flex project just for the test mxml file and add the main project's src directory as an additional source directory in the build options. I don't like this approach because it requires that I keep the mxml file in a separate directory tree from all the other source files in addition to the ugliness of maintaining two projects.</li> </ol>
<p>There's always <a href="http://www.asunit.com/" rel="nofollow noreferrer">ASUnit</a>.</p>
<p>Try AS3Unit from libspark. They also have an async beta test kit. </p>
47,785
<p>Ok guys just a small game:</p> <p>I have some specifications for a project. At some point they ask for the following to encrypt a password over the net, saying that it is a challenge response protocol:</p> <pre> CLIENT ----------------------------- SERVER (1)ask for challenge --------------&gt; (2) &lt;---------------------------- send SHA1 taken from the time (this is the challenge) (3) make SHA1 xor PASSWORD --------&gt; if it's equal to SHA1 xor stored password (4) &lt;---------------------------- Grant access </pre> <p>For those who don't know it SHA stands for Secure Hashing Algorithm, a standard algorithm for cryptography.</p> <p>I hope it's clear. Question is: If I sniff packets 2 and 3 (the "challenge" and the "challenge xor password", I do have the actual password just with another xor between them both!?!? There is other way to implement this kind of protocol?? </p>
<p>How about the following:</p> <ol> <li>Server sends a random challenge</li> <li>Client sends SHA1 checksum of (challenge+password)</li> <li>Servers compares against SHA1 checksum of (challenge+stored password)</li> </ol>
<p>The way I would do this is the following:</p> <ol> <li>Challenge the server. </li> <li><p>Server responds with it's public key (for, say RSA encryption) digitally signed.</p></li> <li><p>Client verifies PK, and encrypts password with the key, then digitally signs the encrypted password.</p></li> <li><p>Server verifies signing and decrypts the password to store/check it.</p></li> </ol> <p>The digital signing is important here as it acts as the beginning of preventing man in the middle attacks.</p>
22,789
<p>In a custom role provider (inheriting from RoleProvider) in .NET 2.0, the IsUserInRole method has been hard-coded to always return true:</p> <pre><code>public override bool IsUserInRole(string username, string roleName) { return true; } </code></pre> <p>In an ASP.NET application configured to use this role provider, the following code returns true (as expected):</p> <pre><code>Roles.IsUserInRole("any username", "any rolename"); // results in true </code></pre> <p>However, the following code returns false:</p> <pre><code>Roles.IsUserInRole("any rolename"); // results in false </code></pre> <p>Note that User.IsInRole("any rolename") is also returning false.</p> <ol> <li>Is this the expected behavior?</li> <li>Is it incorrect to assume that the overload that only takes a role name would still be invoking the overridden IsUserInRole?</li> </ol> <p><strong>Update</strong>: Note that there doesn't seem to be an override available for the version that takes a single string, which has led to my assumption in #2.</p>
<p>I looked at Roles.IsUserInRole(string rolename) in .net reflector, and it resolves to the following:</p> <pre><code>public static bool IsUserInRole(string roleName) { return IsUserInRole(GetCurrentUserName(), roleName); } </code></pre> <p>I would take a look at your current user. Here's why:</p> <pre><code>private static string GetCurrentUserName() { IPrincipal currentUser = GetCurrentUser(); if ((currentUser != null) &amp;&amp; (currentUser.Identity != null)) { return currentUser.Identity.Name; } return string.Empty; } </code></pre> <p>I would be willing to bet this is returning an empty string because you either don't have a Current User, or its name is an empty string or null.</p> <p>In the <code>IsUserInRole(string username, string roleName)</code> method, there is the following block of code right near the beginning:</p> <pre><code> if (username.Length &lt; 1) { return false; } </code></pre> <p>If your <code>GetCurrentUserName()</code> doesn't return anything meaningful, then it will return false before it calls your overridden method.</p> <p>Moral to take away from this: Reflector is a great tool :)</p>
<p>Also beware if you have selected cacheRolesInCookie="true" in the RoleManager config. If you have added a new role to the database, it might be looking at the cached version in the cookie.</p> <p>I had this problem and the solution was to delete the cookie and re-login.</p>
47,367
<p>Are there any dictionary classes in the .NET base class library which allow duplicate keys to be used? The only solution I've found is to create, for example, a class like:</p> <pre><code>Dictionary&lt;string, List&lt;object&gt;&gt; </code></pre> <p>But this is quite irritating to actually use. In Java, I believe a MultiMap accomplishes this, but cannot find an analog in .NET.</p>
<p>If you're using .NET 3.5, use the <a href="http://msdn.microsoft.com/en-us/library/bb460184.aspx" rel="noreferrer"><code>Lookup</code></a> class.</p> <p>EDIT: You generally create a <code>Lookup</code> using <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.tolookup.aspx" rel="noreferrer"><code>Enumerable.ToLookup</code></a>. This does assume that you don't need to change it afterwards - but I typically find that's good enough.</p> <p>If that <em>doesn't</em> work for you, I don't think there's anything in the framework which will help - and using the dictionary is as good as it gets :(</p>
<p>Duplicate keys break the entire contract of the Dictionary. In a dictionary each key is unique and mapped to a single value. If you want to link an object to an arbitrary number of additional objects, the best bet might be something akin to a DataSet (in common parlance a table). Put your keys in one column and your values in the other. This is significantly slower than a dictionary, but that's your tradeoff for losing the ability to hash the key objects. </p>
17,609
<p>I have this working definition:</p> <pre><code>IDENTIFIER [a-zA-Z][a-zA-Z0-9]* </code></pre> <p>I don't want to keep repeating the [a-zA-Z] and [0-9], so I made two new definitions</p> <pre><code>DIGIT [0-9] VALID [a-zA-Z] </code></pre> <p>How can I rewrite the IDENTIFIER rule to use the DIGIT and VALID definitions?</p> <p>I don't know how to do the "second" match, I'm stuck here:</p> <pre><code>IDENTIFIER {VALID}[{VALID}{DIGIT}]* // This syntax is incorrect </code></pre> <p>Thanks.</p> <p>Edit: The entire test program that I'm using: <a href="http://pastebin.com/f5b64183f" rel="nofollow noreferrer">http://pastebin.com/f5b64183f</a>.</p>
<p>It looks like you actually want:</p> <pre><code>IDENTIFIER {VALID}({VALID}|{DIGIT})* </code></pre> <p><code>[{VALID}{DIGIT}]</code> resolves to <code>[[A-Za-z][0-9]]</code> which is not a legal construct.</p>
<p>I think this will do it, but I can't test it. Do you have sample data?</p> <pre><code>(?:[a-zA-Z])+(?:[0-9])+ </code></pre>
21,579
<p>For simplicity lets say I have two flex mxml pages. </p> <p>form.mxml<br> button.mxml</p> <p>If the form.mxml page had the following code, it should work fine:</p> <pre><code>&lt;custom:SelectView dSource="{_thedata}" id="form" visible="false"&gt; &lt;/custom:SelectView&gt; &lt;mx:LinkButton label="Show" id="lbShow" click="form.visible=true;&gt; &lt;mx:LinkButton label="Show" id="lbHide" click="form.visible=false;&gt; </code></pre> <p>But if the code was like:</p> <p>form.mxml</p> <pre><code> &lt;custom:SelectView dSource="{_thedata}" id="form" visible="false"&gt; &lt;/custom:SelectView&gt; </code></pre> <p>button.mxml</p> <pre><code>&lt;mx:LinkButton label="Show" id="lbShow" click="form.visible=true;&gt; &lt;mx:LinkButton label="Show" id="lbHide" click="form.visible=false;&gt; </code></pre> <p>how can I make a call from button.mxml to change form.mxml</p> <p>---- a bit more details ---</p> <p>My page actually looks like this: where query:AdvancedSearchFields is basically including a flex form into the page, and I want it to show/hide the custom view below after the search is complete. </p> <pre><code>&lt;query:AdvancedSearchFields searchType="projects" searchCategory="advanced" visible="true" id="AdvancedSearch" /&gt; &lt;custom:SelectView dSource="{_searchResults}" id="sv" visible="false"&gt; </code></pre>
<p>You could write a custom method that handles the button click events and raises a custom event. Then in form.mxml you can handle that event.</p> <p>Splitting it up like this is a bit cleaner, as it makes the button.mxml file work on its own. Having Button.mxml have a direct reference to your form causes a tight-coupling between the two, and generally you should avoid tight-coupling.</p> <p>EDIT: I just had another thought that also avoids tight-coupling and is a bit simpler:</p> <p><em>form.mxml</em></p> <pre><code>&lt;custom:SelectView dSource="{_thedata}" id="form" visible="{buttons.showForm}"&gt; &lt;/custom:SelectView&gt; &lt;!-- include your buttons.mxml component using an ID of "buttons" --&gt; </code></pre> <p><em>buttons.mxml</em></p> <pre><code>&lt;mx:Script&gt; &lt;![CDATA[ [Bindable] public var showForm:Boolean = true; ]]&gt; &lt;/mx:Script&gt; &lt;mx:LinkButton label="Show" id="lbShow" click="this.showForm=true;"&gt; &lt;mx:LinkButton label="Hide" id="lbHide" click="this.showForm=false;"&gt; </code></pre> <p>This essentially emulates using a custom event by using variable binding. Any time the showForm variable in buttons changes the visible property of the SelectView will be updated via the bindings. This is lighter-weight than creating a custom event (though I think custom events are a bit better of a design for it).</p>
<p>Your <code>button.mxml</code> class must have a reference to the instance of the 'form' class which will be affected. Then it can operate on it directly:</p> <p><em>Button.mxml:</em></p> <pre><code>&lt;mx:Script&gt; &lt;![CDATA[ [Bindable] public var myForm:MyFormClass; ]]&gt; &lt;/mx:Script&gt; &lt;mx:LinkButton label="Show" id="lbShow" click="myForm.form.visible=true;"&gt; &lt;mx:LinkButton label="Show" id="lbHide" click="myForm.form.visible=false;"&gt; </code></pre> <p>Generally, the most logical place to set this variable is in the parent of your <code>Button</code> class.</p>
22,755
<p>I am creating a standalone asp.net page that needs to be embedded into a sharepoint site using the Page Viewer Web Part. The asp.net page is published to the same server on a different port, giving me the URL to embed.</p> <p>The requirement is that after a user is authenticated using Sharepoint authentication, they navigate to a page containing the asp.net web part for more options. </p> <p>What I need to do from this asp.net page is query Sharepoint for the currently authenticated username, then display this on the page from the asp.net code. </p> <p>This all works fine when I debug the application from VS, but when published and displayed though Sharepoint, I always get NULL as the user. </p> <p>Any suggestions on the best way to get this to work would be much appreciated.</p>
<p>If you want to retrieve the currently authenticated user from the SharePoint context, you need to remain within the SharePoint context. This means hosting your custom web application within SharePoint (see <a href="http://msdn.microsoft.com/en-us/library/cc297200.aspx" rel="nofollow noreferrer" title="Deploying ASP.NET Web Applications in the Windows SharePoint Services 3.0 _layouts Folder">http://msdn.microsoft.com/en-us/library/cc297200.aspx</a>). Then from your custom application reference Microsoft.SharePoint and use the SPContext object to retrieve the user name. For example:</p> <pre><code>SPContext.Current.Web.CurrentUser.LoginName </code></pre> <p>You can still use the Page Viewer Web Part to reference the URL of the site, now located within the SharePoint context.</p>
<p>When it works in debug, is that being used in SharePoint?</p> <p>Your page and the Sharepoint site might as well be on different servers as far as authentication is concerned -- in order to get the information over you might need to pass it via the QueryString from the webpart if you can -- or you might need to make your own webpart to do this (just put an IFRAME in the part with the src set to your page with the QueryString passing the username).</p> <p>It does seem that this would be a security issue if you use the name for anything though -- if you are just displaying it, then it's probably fine.</p> <p>If you actually need to be authenticated, you might need to add authentication into the web.config of the site hosting your standalone page.</p> <p>edit: I think you'd have better luck putting your page on the same port and server as SharePoint.</p>
13,790
<p>I wrote a simple tool to generate a DBUnit XML dataset using queries that the user enters. I want to include each query entered in the XML as a comment, but the DBUnit API to generate the XML file doesn't support inserting the comment where I would like it (above the data it generates), so I am resorting to putting the comment with ALL queries either at the top or bottom.</p> <p>So my question: is it valid XML to place it at either location? For example, above the XML Declaration:</p> <pre><code>&lt;!-- Queries used: ... --&gt; &lt;?xml version='1.0' encoding='UTF-8'?&gt; &lt;dataset&gt; ... &lt;/dataset&gt; </code></pre> <p>Or below the root node:</p> <pre><code>&lt;?xml version='1.0' encoding='UTF-8'?&gt; &lt;dataset&gt; ... &lt;/dataset&gt; &lt;!-- Queries used: ... --&gt; </code></pre> <p>I plan to initially try above the XML Declaration, but I have doubts on if that is valid XML, despite the claim from <a href="http://en.wikipedia.org/wiki/Xml#Well-formed_documents:_XML_syntax" rel="noreferrer">wikipedia</a>:</p> <blockquote> <p>Comments can be placed anywhere in the tree, including in the text if the content of the element is text or #PCDATA.</p> </blockquote> <p>I plan to post back if this works, but it would be nice to know if it is an official XML standard.</p> <p><strong>UPDATE:</strong> See <a href="https://stackoverflow.com/questions/50824/can-xml-comments-go-anywhere#50976">my response below</a> for the result of my test.</p>
<p>According to the <a href="http://www.w3.org/TR/2006/REC-xml-20060816/#sec-comments" rel="noreferrer">XML specification</a>, a well-formed XML document is:</p> <blockquote> <p><code>document ::= prolog element Misc*</code></p> </blockquote> <p>where <code>prolog</code> is</p> <blockquote> <p><code>prolog ::= XMLDecl? Misc* (doctypedecl Misc*)?</code></p> </blockquote> <p>and <code>Misc</code> is</p> <blockquote> <p><code>Misc ::= Comment | PI | S</code></p> </blockquote> <p>and</p> <blockquote> <p><code>XMLDecl ::= '&lt;?xml' VersionInfo EncodingDecl? SDDecl? S? '?&gt;'</code></p> </blockquote> <p>which means that, if you want to have comments at the top, you cannot have an XML type declaration. </p> <p>You can, however, have comments after the declaration and outside the document element, either at the top or the bottom of the document, because <code>Misc*</code> can contain comments.</p> <p>The specification agrees with Wikipedia on comments:</p> <blockquote> <p>2.5 Comments</p> <p>[Definition: Comments may appear anywhere in a document outside other markup; in addition, they may appear within the document type declaration at places allowed by the grammar. They are not part of the document's character data; an XML processor MAY, but need not, make it possible for an application to retrieve the text of comments. For compatibility, the string "--" (double-hyphen) MUST NOT occur within comments.] Parameter entity references MUST NOT be recognized within comments.</p> </blockquote> <p>All of this together means that you can put comments <strong>anywhere that's not inside other markup</strong>, except that you <strong>cannot have an XML declaration if you lead with a comment</strong>.</p> <p>However, while in theory theory agrees with practice, in practice it doesn't, so I'd be curious to see how your experiment works out.</p>
<p>The processing instruction must be the very first thing in the XML content (see <a href="http://www.w3.org/TR/REC-xml/#sec-comments" rel="nofollow noreferrer">XML comment</a> and <a href="http://www.w3.org/TR/REC-xml/#sec-pi" rel="nofollow noreferrer">processing instructions</a>). The following should work:</p> <pre><code>&lt;?xml version='1.0' encoding='UTF-8'?&gt; &lt;!-- Queries used: ... --&gt; &lt;dataset&gt; ... &lt;/dataset&gt; </code></pre>
7,365
<p>I feel like a fool, but here goes:</p> <pre><code>public interface IHasErrorController{ ErrorController ErrorController { get; set; } } public class DSErrorController: ErrorController{yadi yadi ya} public class DSWebsiteController : Controller, IHasErrorController{ public DSErrorController ErrorController { get; set; } } </code></pre> <p>This gives me an error saying DSWebsiteController.ErrorController cannot implement IHasErrorController despite DSErrorController being inheritted from ErrorController.</p> <p>Also, suggestions for a better naming so that the type ErrorController and the field Errorcontroller don't look the same are welcome (naming is hard).</p>
<p>C# (at the moment) has very little [co|contra]variance support; as such, the interface implementation must be an <em>exact</em> match, including the return type. To keep your concreate type on the class API, I would implement the interface explicitly - i.e. add:</p> <pre><code>ErrorController IHasErrorControlloer.ErrorController { get {return this.ErrorController;} set {this.ErrorController = (DSErrorController)value;} } </code></pre> <p>Alternatively, simply change the type of the property to <code>ErrorController</code> - this may (or may not) give what you need.</p>
<p>This is true; that is not allowed. (The proper name is "Covariant return types")</p> <p>Note that DSWebsiteController.ErrorController can physically return a DSErrorController object; it's just that the property's return value must be defined as ErrorController.</p>
24,560
<p>I have a class like this:</p> <pre><code>public class myClass { public List&lt;myOtherClass&gt; anewlist = new List&lt;myOtherClass&gt;; public void addToList(myOtherClass tmp) { anewList.Add(tmp); } } </code></pre> <p>So I call "addToList" a hundred times, each adding a unique item to the list. I've tested my items to show that before I run the "addToList" method, they are unique. I even put a line in to test "tmp" to make sure it was what I was expecting.</p> <p>However, when I do this (lets say myClass object is called tmpClass):</p> <pre><code>int i = tmpClass.anewList.Count(); for (int j = 0; j&lt;i; j++) { //write out each member of the list based on index j... } </code></pre> <p>I get the same exact item, and it's the last one that was written into my list. It's as if when I add, I'm overwriting the entire list with the last item I've added. </p> <p>Help? This makes no sense. I've also tried List.Insert, where I'm always inserting at the end or at index 0. Still no dice. Yes, I'm doubly source my indexing is correct and when I do my test I'm indexing through each of the elements.</p> <p>:)</p> <p>UPDATE: Okay, I tried this and still had the same problem:</p> <pre><code>foreach(myOtherClass tmpC in tmpClass.anewList) { Console.WriteLine(tmpC.theStringInMyClass.ToString()); } </code></pre> <p>and still for each of the 100 items, I got the same string output... I'm sure I'm doing something completely stupid, but I don't know what yet. I'm still 100% sure that the right string is getting passed in to begin with.</p> <p>-Adeena</p> <hr> <p>Okay, I tried this and still had the same problem:</p> <pre><code>foreach(myOtherClass tmpC in tmpClass.anewList) { Console.WriteLine(tmpC.theStringInMyClass.ToString()); } </code></pre> <p>and still for each of the 100 items, I got the same string output... I'm sure I'm doing something completely stupid, but I don't know what yet. I'm still 100% sure that the right string is getting passed in to begin with.</p> <p>-Adeena</p>
<p>Given the signature of your addToList method:</p> <pre><code>public void addToList(myOtherClass tmp) { anewList.Add(tmp); } </code></pre> <p>Is is possible that in the consumer of that method, you aren't actually creating a new instance?</p> <p>You said that you are calling addToList 100 times. Presumably, that is in a loop. At each loop iteration, you will need to create a new instance of "myOtherClass", otherwise, you'll just be updating the same object in memory.</p> <p>For example, if you do the below, you will have 100 copies of the same object:</p> <pre><code>myOtherClass item = new myOtherClass(); for(int i=0; i &lt; 100; i++) { item.Property = i; addToList(item); } </code></pre> <p>However, if your loop looks like the below, it will work fine:</p> <pre><code>myOtherClass item = null; for(int i=0; i &lt; 100; i++) { item = new myOtherClass(); item.Property = i; addToList(item); } </code></pre> <p>Hope that helps!</p>
<p>Also note that when you use the exact form:</p> <pre><code> for (int j = 0; j &lt; tmpClass.anewList.Count(); j++) </code></pre> <p>The C# compile preforms a special optimization on the loop. If you vary from the syntax (e.g. by pulling the Count property out of the loop into a separate varaible, as you did in you example), the compile skips that optimization.</p> <p>It won't affect what is displayed, but it will take longer.</p>
45,248
<p>I'm new to Spring Security. How do I add an event listener which will be called as a user logs in successfully? Also I need to get some kind of unique session ID in this listener which should be available further on. I need this ID to synchronize with another server.</p>
<p>You need to define a Spring Bean which implements <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/context/ApplicationListener.html" rel="noreferrer">ApplicationListener</a>.</p> <p>Then, in your code, do something like this:</p> <pre class="lang-java prettyprint-override"><code>public void onApplicationEvent(ApplicationEvent appEvent) { if (appEvent instanceof AuthenticationSuccessEvent) { AuthenticationSuccessEvent event = (AuthenticationSuccessEvent) appEvent; UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal(); // .... } } </code></pre> <p>Then, in your applicationContext.xml file, just define that bean and it will automatically start receiving events :)</p>
<p>In Grails, with Spring Security Plugin, you can do this in Config.groovy:</p> <pre><code>grails.plugins.springsecurity.useSecurityEventListener = true grails.plugins.springsecurity.onAuthenticationSuccessEvent = { e, appCtx -&gt; def session = SecurityRequestHolder.request.getSession(false) session.myVar = true } </code></pre>
22,013
<p>When running any kind of server under load there are several resources that one would like to monitor to make sure that the server is healthy. This is specifically true when testing the system under load.</p> <p>Some examples for this would be CPU utilization, memory usage, and perhaps disk space. What other resource should I be monitoring, and what tools are available to do so?</p>
<p>As many as you can afford to, and can then graph/understand/look at the results. Monitoring resources is useful for not only capacity planning, but anomaly detection, and anomaly detection significantly helps your ability to detect security events.</p> <p>You have a decent start with your basic graphs. I'd want to also monitor the number of threads, number of connections, network I/O, disk I/O, page faults (arguably this is related to memory usage), context switches.</p> <p>I really like munin for graphing things related to hosts.</p>
<p>I typically watch <code>top</code> and <code>tail -f /var/log/auth.log</code>.</p>
10,061
<p>I'm building a java/spring application, and i may need to incorporate a stateful web service call. Any opinions if i should totally run away from a stateful services call, or it can be done and is enterprise ready?</p>
<p>Stateful web services are a pain to maintain. The mechanism I have seen for them is to have the first call return an id (basically a transaction id) that is used in subsequent calls. A problem with that is that the web service isn't really stateful so it has to load all the information that it needs from some other data store for each call. </p>
<p>Statefulness runs counter to the basic architecture of HTTP (ask Roy Fielding), and reduces scalability.</p>
12,024
<p>I am trying to convert my C# code to design (Reverese Engineering) using StarUML. I got the error while performing the Reverse engineering </p> <blockquote> <p>"Error occurred in the process of reverse engineering. message : Catastrophic failure". </p> </blockquote> <p>After the error, the application crashed.</p> <p>Could anyone suggest a solution for this please?</p>
<p>One of the problems with staruml is that apparently it does not support generics and when a file has the "&lt;", a parser error occurs</p>
<p>I'm not familiar with StarUML in particular, although there are a couple of ways that it could be going about the process of documenting your assemblies. The most likely method is .Net reflection.</p> <p>Lots of applications struggle with the more recent C# optimisations.</p> <p>The best application for reflecting code back out is <a href="http://www.red-gate.com/products/reflector" rel="nofollow noreferrer">Reflector</a>, and there are plug-ins that will generate UML for you.</p>
13,944
<p>Are there any wizard type controls in WPF? I need functionality where I can go forward and back and use tabs to select a particular item which will show the details of the nested items. I can use the TabControl control but the tab items are dynamic so I cannot nest the region inside the tab item.</p>
<p>WPF has a navigation infrastructure built in:</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms750478.aspx" rel="noreferrer">WPF Navigation Overview</a></p> <p>Also check out the <a href="http://msdn.microsoft.com/en-us/library/aa972123.aspx" rel="noreferrer">wizard sample</a></p>
<p>Found this great example on codeproject that should give you everything that you need:</p> <p><a href="http://www.codeproject.com/Articles/31837/Creating-an-Internationalized-Wizard-in-WPF" rel="nofollow">http://www.codeproject.com/Articles/31837/Creating-an-Internationalized-Wizard-in-WPF</a></p>
36,531
<p>If I have a list of data in a text file seperated by a new line, is there a way to append something to the start, then the data, then append something else then the data again?</p> <p>EG a field X would become new X = X;</p> <p>Can you do this with bash or sed or just unix tools like cut?</p> <p>EDIT:</p> <p>I am trying to get "ITEM_SITE_ID :{$row['ITEM_SITE_ID']} <br>" .</p> <p>I am using this line awk '{ print "\""$1 " {:$row['$1']} <br>" }'</p> <p>And I get this "ITEM_SITE_ID {:$row[]} <br></p> <p>What have I missed?</p>
<p>You simply need to run your batch job in a 64-bit process. The problem is that SharePoint has many COM objects under the hood which are compiled for 64-bit in your test and production environment. The SPSite and SPWeb objects actually wrap the COM objects which is why they fail in your 32-bit process. </p> <p>One work-around could be to interact with SharePoint through its Web Services instead of the object model.</p>
<p>I don't think this is a 32/64bit issue as I am in the same situation as far as developing on 32bit and deploying to 64bit. (Actually, we are running a 32bit and 64bit WFE'S) </p> <p>Since the exception is being thrown from the SPSite constructor, I would investigate further, as to whether the machine you are running you code on (the SP box) actually recognizes that URL.</p>
31,143
<p>Why is Oracle's <code>to_char()</code> function adding spaces?</p> <pre><code>select length('012'), length(to_char('012')), length(to_char('12', '000')) from dual; </code></pre> <p><code>3, 3, 4</code></p>
<p>The extra leading space is for the potential minus sign. To remove the space you can use FM in the format:</p> <pre><code>SQL&gt; select to_char(12,'FM000') from dual; TO_C ---- 012 </code></pre> <p>By the way, note that to_char takes a NUMBER argument; to_char('012') is implicitly converted to to_char(to_number('012')) = to_char(12)</p>
<p>Be aware when using the 'fm' syntax it will not include any values after the decimal place unless specified using zeros. For example:</p> <pre><code>SELECT TO_CHAR(12345, 'fm99,999.00') FROM dual </code></pre> <p>returns: <strong>'12,345.00'</strong> </p> <pre><code>SELECT TO_CHAR(12345, 'fm99,999.99') FROM dual </code></pre> <p>returns: <strong>'12,345.'</strong> </p> <p>As you can see this would be an issue if you are expecting two zeros after the decimals place (maybe in fee reports for example).</p>
29,730
<p>I want to store a URL prefix in an Windows environment variable. The ampersands in the query string makes this troublesome though.</p> <p>For example: I have a URL prefix of <code>http://example.com?foo=1&amp;bar=</code> and want to create a full URL by providing a value for the <code>bar</code> parameter. I then want to launch that URL using the "start" command.</p> <p>Adding quotes around the value for the SET operation is easy enough:</p> <pre><code>set myvar="http://example.com?foo=1&amp;bar=" </code></pre> <p>Windows includes the quotes in the actual value though (thanks Windows!):</p> <pre><code>echo %myvar% "http://example.com?foo=1&amp;bar=true" </code></pre> <p>I know that I can strip quotes away from batch file arguments by using tilde:</p> <pre><code>echo %~1 </code></pre> <p>However, I can't seem to do it to named variables:</p> <pre><code>echo %~myvar% %~myvar% </code></pre> <p>What's the syntax for accomplishing this?</p>
<p>This is not a limitation of the environment variable, but rather the command shell.</p> <p>Enclose the entire assignment in quotes:</p> <pre><code>set "myvar=http://example.com?foo=1&amp;bar=" </code></pre> <p>Though if you try to echo this, it will complain as the shell will see a break in there.</p> <p>You can echo it by enclosing the var name in quotes:</p> <pre><code>echo "%myvar%" </code></pre> <p>Or better, just use the set command to view the contents:</p> <pre><code>set myvar </code></pre>
<p>I think this should do it:</p> <pre><code>for /f "tokens=*" %i in (%myvar%) do set %myvar%=%~i </code></pre> <p>But you do not need this, </p> <pre><code>set myvar="http://example.com?foo=1&amp;bar=" start "" %myvar% </code></pre> <p>Will work too, you just need to supply a title to the start command.</p>
39,530
<p>I was running some dynamic programming code (trying to brute-force disprove the Collatz conjecture =P) and I was using a dict to store the lengths of the chains I had already computed. Obviously, it ran out of memory at some point. Is there any easy way to use some variant of a <code>dict</code> which will page parts of itself out to disk when it runs out of room? Obviously it will be slower than an in-memory dict, and it will probably end up eating my hard drive space, but this could apply to other problems that are not so futile.</p> <p>I realized that a disk-based dictionary is pretty much a database, so I manually implemented one using sqlite3, but I didn't do it in any smart way and had it look up every element in the DB one at a time... it was about 300x slower.</p> <p>Is the smartest way to just create my own set of dicts, keeping only one in memory at a time, and paging them out in some efficient manner?</p>
<p>Hash-on-disk is generally addressed with Berkeley DB or something similar - several options are listed in the <a href="http://docs.python.org/library/persistence.html" rel="noreferrer">Python Data Persistence documentation</a>. You can front it with an in-memory cache, but I'd test against native performance first; with operating system caching in place it might come out about the same.</p>
<p>You should bring more than one item at a time if there's some heuristic to know which are the most likely items to be retrieved next, and don't forget the indexes like Charles mentions.</p>
28,038
<p>I have a binded DataGridView where depending on some BoundItem property value that line will be read only. What is the best way to implement this? Thanks</p>
<p>Try The event CellBeginEdit</p> <pre><code>Private Sub Dgv_CellBeginEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles Dgv.CellBeginEdit If YourCondition(BoundItem.Property) then e.cancel = true End Sub </code></pre> <p>This makes the cell readOnly depending on your condition.</p>
<p>in the rowenter event, set the readonly property of the row accordingly</p> <pre><code>private sub MyView_RowEnter(...) handles MyView.RowEnter MyView.Rows(e.Rowindex).ReadOnly = (condition) end sub </code></pre>
34,173
<p>I've used several modules to make EXEs for Python, but I'm not sure if I'm doing it right.</p> <p>How should I go about this, and why? Please base your answers on personal experience, and provide references where necessary.</p>
<p><a href="https://pypi.org/project/auto-py-to-exe/" rel="noreferrer">Auto PY to EXE</a> - A .py to .exe converter using a simple graphical interface built using Eel and PyInstaller in Python.</p> <hr> <p><a href="http://www.py2exe.org/" rel="noreferrer">py2exe</a> is probably what you want, but it only works on Windows.<br> <a href="http://www.pyinstaller.org/" rel="noreferrer">PyInstaller</a> works on Windows and Linux.<br> <a href="http://pypi.python.org/pypi/py2app/" rel="noreferrer">Py2app</a> works on the Mac.</p>
<p><a href="http://www.py2exe.org/" rel="nofollow noreferrer">py2exe</a>:</p> <blockquote> <p>py2exe is a Python Distutils extension which converts Python scripts into executable Windows programs, able to run without requiring a Python installation.</p> </blockquote>
7,157
<p>I deploy a webapp on two different containers (Tomcat and Jetty), but their default servlets for serving the static content have a different way of handling the URL structure I want to use (<a href="http://issues.apache.org/bugzilla/show_bug.cgi?id=42411" rel="noreferrer">details</a>).</p> <p>I am therefore looking to include a small servlet in the webapp to serve its own static content (images, CSS, etc.). The servlet should have the following properties:</p> <ul> <li>No external dependencies</li> <li>Simple and reliable</li> <li>Support for <a href="http://www.freesoft.org/CIE/RFC/1945/58.htm" rel="noreferrer"><code>If-Modified-Since</code></a> header (i.e. custom <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServlet.html#getLastModified(javax.servlet.http.HttpServletRequest)" rel="noreferrer"><code>getLastModified</code></a> method)</li> <li>(Optional) support for gzip encoding, etags,...</li> </ul> <p>Is such a servlet available somewhere? The closest I can find is <a href="http://www.unix.org.ua/orelly/java-ent/servlet/ch04_04.htm#ch04-35758" rel="noreferrer">example 4-10</a> from the servlet book.</p> <p><strong>Update:</strong> The URL structure I want to use - in case you are wondering - is simply:</p> <pre class="lang-xml prettyprint-override"><code> &lt;servlet-mapping&gt; &lt;servlet-name&gt;main&lt;/servlet-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;default&lt;/servlet-name&gt; &lt;url-pattern&gt;/static/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; </code></pre> <p>So all requests should be passed to the main servlet, unless they are for the <code>static</code> path. The problem is that Tomcat's default servlet does not take the ServletPath into account (so it looks for the static files in the main folder), while Jetty does (so it looks in the <code>static</code> folder).</p>
<p>There is no need for completely custom implementation of the default servlet in this case, you can use this simple servlet to wrap request to the container's implementation:</p> <pre><code> package com.example; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class DefaultWrapperServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { RequestDispatcher rd = getServletContext().getNamedDispatcher("default"); HttpServletRequest wrapped = new HttpServletRequestWrapper(req) { public String getServletPath() { return ""; } }; rd.forward(wrapped, resp); } } </code></pre>
<p>See StaticFile in JSOS: <a href="http://www.servletsuite.com/servlets/staticfile.htm" rel="nofollow noreferrer">http://www.servletsuite.com/servlets/staticfile.htm</a></p>
16,012
<p>Many languages have a facility to check to see if an Object is of a certain type (including parent subclasses), implemented with 'is' and used like this:</p> <pre><code>if(obj is MyType) </code></pre> <p>Or slightly more tediously you can in other languages check by using the 'as' keyword to do a soft typecast and seeing if the result null. </p> <p>I haven't used Java in years and I'm getting back up to speed on it but surely Java has a way to easily do this without delving deep into the Reflection APIs?</p> <p>Thanks in advance for answers. I have searched both here and other places but the keywords involved are so generic that even though I'm sure this has a simple answer, googling for it is hard.</p>
<pre><code>if (objectReference instanceof type){ //Your code goes here } </code></pre> <p>More info <a href="http://www.java2s.com/Tutorial/Java/0060__Operators/TheinstanceofKeyword.htm" rel="nofollow noreferrer">here</a>.</p>
<p><code>obj instanceof TargetType</code> returns true just in case <code>TargetType</code> is in the type hierarchy that contains <code>obj</code>.</p> <p>See <a href="http://java.sun.com/docs/books/tutorial/java/nutsandbolts/op2.html" rel="nofollow noreferrer">Sun's tutorial</a></p>
29,393
<p>Which JDBC jar should I use with java 1.5.0_16 and PostgreSQL 8.3.5?</p>
<p>From the <a href="http://msdn.microsoft.com/en-us/library/1whwt1k7.aspx" rel="nofollow noreferrer">Microsoft Documentation</a>.</p> <blockquote> <p>Use control state only for small amounts of critical data that are essential for the control across postbacks. Do not use control state as an alternative to view state.</p> </blockquote> <p>From this you can guess that GridView and other items would not be storing that large of an amount of information in ControlState, so I'm guessing that if you wanted to do it, against Microsoft's recommendation you would have to extend the base control to do it.</p>
<p>You can disable view state for all page but you need to rebind datagrid, dataview in every postback. </p> <p>Sometimes it works better then saving a huge viewstate on the client.</p> <p>For standard server controls: if you modify Control Properties after init, then all modifications will be saved in ViewState too.</p> <p>Here is awesome Scott Mitchell <a href="http://msdn.microsoft.com/en-us/library/ms972976.aspx" rel="nofollow noreferrer">Post about ViewState</a>. </p>
49,988
<p>I'm applying for a masters in fall of next year and was wondering if anyone had suggestions for interesting/challenging master's degrees in CS. I think that even though picking the right university is important, it is even more important to pick a master's degree where you'll find talented/creative people to interact and learn from.</p> <p>background: never taken AI, discrete math, compilers, operating systems, data structures, cryptography or anything involving c/c++ courses</p> <p>looking for: hci research &amp; applications, the future of mobile tech &amp; social interaction, something tangible and not abstract, somewhere where I can take a minor in music/art/design</p> <p>inspiration: randy pausch, johnny lee, blaise aguera, jeff han, 42entertainment, and jonathan harris (ted.com)</p>
<blockquote> <p>background: never taken AI, discrete math, compilers, operating systems, data structures, cryptography or anything involving c/c++ courses</p> </blockquote> <p>Hmmm ... It would have been OK had you not taken cryptogrophy or AI, but if you dont have an idea of Data Structures, Operating Systems, Compilers etc., I am not sure you have lot of options for good shot at 'hardcore' CS stuff at Master's level.</p>
<p>I would suggest taking a linear algebra course at a community college or at least self-teaching yourself, as regardless of what you go into, you will need this material. This is a generalization, but it seems to be true!</p> <p>That being said, here are my thoughts:</p> <ol> <li><p>Social interaction - The data mining field is heavily into social interaction at the moment, at least at my school. A common thing is to look at datasets from Twitter or Facebook and see what you can do with this. This field relies heavily on linear algebra and graph theory, but the results are a nice mix between theoretical and practical. Forming communities and synergies between people, as well as discovering interesting information from or about specific people is very doable and seems like it would interest you.</p></li> <li><p>HCI - This is a huge field. What kind of HCI are you looking for? New input methods, like multitouch? Computer vision, where you can use a camera to interact with the computer? Speech recognition and synthesis so you can hold a conversation with your computer? Many of the HCI subfields rely on AI. The most widely used AI book on the market is <a href="http://aima.cs.berkeley.edu/" rel="nofollow noreferrer">Artificial Intelligence: A Modern Approach</a>. It is extremely readable and I can recommend it as a beginning text.</p></li> </ol> <p>I would suggest looking at a university that is close to where you are now to see what kind of material they are teaching in their graduate courses. Often you can find seminars for research groups that have a paper list of literature that the research group covers in their group meetings. Reading some of the papers will give you a better idea of what to expect and what the current trends are in fields.</p> <p>Good luck!</p>
29,611
<p>The amount of posts being voted to closed is getting ridiculous. The last two posts have been printing related, one looking for information and the other a design question for 3D printing yet both have been voted to be closed. </p> <p>Yes, I have read the other Meta post about how closing is not permanent (<a href="https://3dprinting.meta.stackexchange.com/questions/111/closing-locking-too-many-questions">Closing/locking too many questions?</a>) but this site does not have much to offer right now and I can tell you if I was new here I wouldn't stick around and edit the post time after time to get an answer when I'm sure most people here can answer the question. The site is now running at 1.2 questions per day and I don't see that going up at all if the criteria isn't changed for how people are voting. If that's how everyone wants the site run then that's fine but I'm sure you'll be alone here.</p>
<p>I absolutely agree. I believe we all want this site to maintain high quality, but right now almost no questions fall within our desired scope and form.</p> <p>I think we either need to:</p> <ul> <li>Change the acceptable scope of questions to be asked</li> <li>Change how we welcome new users</li> </ul> <p>Right now most new users do not ask questions "the SE way", which quickly leads to down-votes and closing votes. For new users this is a direct slap in the face.</p> <p>What we rather should do is to <em>encourage</em> new users to improve their question, and if they do, give them the highly desired up-votes to make them come back for more. </p> <p>I think the reputation system on SE sites is a great motivator for writing good questions and answers. And if we want this site to grow, we need to let our fellow users grow with it.</p>
<p>I've been active on SO since it was in beta, and have participated in numerous SE sites when they were in beta.</p> <p>It's my impression that there is much more enthusiasm for close votes here than in other sites which launched out of beta. I know that seems to discourage me from participating more, and may discourage others likewise.</p> <p>Whereas for programming and electronics my first goto is always stack, I'm finding that other sites are having better answers and a "nicer" approach to my n00bism in 3d printing.</p> <p>Just IMHO and FWIW!</p>
25
<p>I need to read account number from Maestro/Mastercard with smart card reader. I am using Java 1.6 and its javax.smartcardio package. I need to send APDU command which will ask EMV application stored on card's chip for PAN number. Problem is, I cannot find regular byte array to construct APDU command which will return needed data anywhere... </p>
<p>You shouldn't need to wrap the APDU further. The API layer should take care of that.</p> <p>It looks like the 0x6D00 response just means that the application did not support the INS.</p> <p>Just troubleshooting now, but you did start out by selecting the MasterCard application, right?</p> <p>I.e. something like this:</p> <pre><code>void selectApplication(CardChannel channel) throws CardException { byte[] masterCardRid = new byte[]{0xA0, 0x00, 0x00, 0x00, 0x04}; CommandAPDU command = new CommandAPDU(0x00, 0xA4, 0x04, 0x00, masterCardRid); ResponseAPDU response = channel.transmit(command); return response.getData(); } </code></pre>
<p>what about using a scanner, getting a picture of the card, scanning the content of the picture with a good java ocr library ( like <a href="http://ocr4j.sourceforge.net/" rel="nofollow">http://ocr4j.sourceforge.net/</a> for example ) and search for a (usually) 16 digit sequence XXXX-XXXX-XXXX-XXXX , then you will get the PAN from any EMV card using java.</p>
35,899
<p>I want to check that two passwords are the same using Dojo.</p> <p>Here is the HTML I have:</p> <p><code></p> <blockquote> <p><code>&lt;form id="form" action="." dojoType="dijit.form.Form" /</code>></p> <p><code>&lt;p</code>>Password: <code>&lt;input type="password"<br> name="password1"<br> id="password1"<br> dojoType="dijit.form.ValidationTextBox"<br> required="true"<br> invalidMessage="Please type a password" /</code>><code>&lt;/p</code>></p> <p><code>&lt;p</code>>Confirm: <code>&lt;input type="password"<br> name="password2"<br> id="password2"<br> dojoType="dijit.form.ValidationTextBox"<br> required="true"<br> invalidMessage="This password doesn't match your first password" /</code>><code>&lt;/p</code>></p> <p><code>&lt;div dojoType="dijit.form.Button" onClick="onSave"</code>>Save<code>&lt;/div</code>></p> <p><code>&lt;/form</code>> </code></p> </blockquote> <p>Here is the JavaScript I have so far:</p> <blockquote> <p><code> var onSave = function() {<br> if(dijit.byId('form').validate()) { alert('Good form'); }<br> else { alert('Bad form'); }<br> } </code></p> </blockquote> <p>Thanks for your help. I could do this in pure JavaScript, but I'm trying to find the Dojo way of doing it.</p>
<p>This will get you a lot closer</p> <ul> <li>setting intermediateChanges=false keeps the validator running at every keystroke.</li> <li>the validation dijit's constraint object is passed to its validator. Use this to pass in the other password entry</li> <li>dijit.form.Form automatically calls isValid() on all its child dijits when it's submitted, and cancels submittion if they don't all validate. I though the invalid ones would get their error message, but they don't. That's left as an exercise for the reader ;-)</li> </ul> <p>the validation function:</p> <pre><code> function confirmPassword(value, constraints) { var isValid = false; if(constraints && constraints.other) { var otherInput = dijit.byId(constraints.other); if(otherInput) { var otherValue = otherInput.value; console.log("%s == %s ?", value, otherValue); isValid = (value == otherValue); } } return isValid; } function onsubmit() { var p1 = dijit.byId('password1').value; var p2 = dijit.byId('password2').value; return p1 == p2; } </code></pre> <p>and the input objects:</p> <pre><code> &lt;p&gt;Password: &lt;input type=&quot;password&quot; name=&quot;password1&quot; id=&quot;password1&quot; dojoType=&quot;dijit.form.ValidationTextBox&quot; required=&quot;true&quot; intermediateChanges=false invalidMessage=&quot;Please type a password&quot; /&gt;&lt;/p&gt; &lt;p&gt;Confirm: &lt;input type=&quot;password&quot; name=&quot;password2&quot; id=&quot;password2&quot; dojoType=&quot;dijit.form.ValidationTextBox&quot; required=&quot;true&quot; constraints=&quot;{'other': 'password1'}&quot; validator=confirmPassword intermediateChanges=false invalidMessage=&quot;This password doesn't match your first password&quot; /&gt;&lt;/p&gt; </code></pre>
<p>I've solved it!</p> <p>This <a href="http://dojotoolkit.org/forum/dijit-dijit-0-9/dijit-support/password-confirmation-validation" rel="nofollow noreferrer">page on the Dojo forum</a> was helpful.</p> <p>I changed the HTML for the confirm password to:</p> <blockquote> <p><code> <code>&lt;p</code>>Confirm: <code>&lt;input type="password"<br> name="password2"<br> id="password2"<br> dojoType="dijit.form.ValidationTextBox"<br> required="true"<br> validator="return theSame(this, dijit.byId('password1'));"<br> invalidMessage="This password doesn't match your first password" /</code>><code>&lt;/p</code>> </code></p> </blockquote> <p>The only difference is the added <em>validator</em> parameter.</p> <p>And I created the following JavaScript function:</p> <blockquote> <p><code> function(dojoTxt1, dojoTxt2) {<br> return dojoTxt1.getValue() == dojoTxt2.getValue();<br> } </code></p> </blockquote> <p>I think you can also use the <em>validator</em> parameter to create regular expressions to test against, but the <a href="http://api.dojotoolkit.org/jsdoc/dijit/1.2/dijit.form.ValidationTextBox.validator" rel="nofollow noreferrer">documentation</a> isn't very clear.</p>
39,744
<p>I have been asked to provide information on available techniques for assessing our current, and any future websites for security problems. the request is in the form of</p> <blockquote> <p>Do you know of any good free one that examines for security holes?</p> </blockquote> <p>I think our data security is probably worth a small amount of upfront spend so any non-free methods would be appreciated too.</p> <p>Our systems are a mish mash of mySQL, Oracle, SQLServer, PHP, ASP.NET etc etc systems though I guess that that does not matter too much. All the systems are secured in as much as they are patched and the firewalls are set sensibly so outside people cannot get directly to the database boxes etc.</p> <p>It is XSS and similar attacks that we wish to prevent. </p> <p>What do YOU use to give you confidence in your systems? ');DROP TABLE answer;</p>
<p>NO. numerical primary keys will not reused, except you specify them manually(you should really avoid this!)</p>
<p>Yeah, it really depends on the way you generate the id.</p> <p>For example if you are using a GUID as the primary key, most implementations of getting a random new Guid are not likely to pick another guid again, but it will given enough time and if the Guid is not in the table the insert statement will go fine, but if there is already a guid there you will get a primary key constraint violation.</p>
31,606
<p>So far i have got the code below which works lovely when trying an update, delete or select statement. However I run into problems when I try to use an insert. If someone could point me in the correct direction i would be grateful.</p> <pre><code>private function escape($value) { if(get_magic_quotes_gpc()) $value = stripslashes($value); return mysql_real_escape_string($value, $this-&gt;dbConn); } /** * Handles connection to the database. * Die functions are used to catch any errors. */ public function connect($dbHost, $dbName, $dbUser, $dbPass) { $this-&gt;dbConn = mysql_connect( $dbHost, $dbUser, $dbPass ) or die(mysql_error()); mysql_select_db($dbName, $this-&gt;dbConn) or die(mysql_error()); } /** * Loads a raw SQL string into the object $dbSql variable */ public function prep($sql) { $this-&gt;dbSql = $sql; } /** * Load bound hooks and values into object variable */ public function bind($hook, $value) { $this-&gt;dbBind[$hook] = $this-&gt;escape($value); } /** * Runs the SQL string in $dbSql object variable */ public function run() { $sql = $this-&gt;dbSql; if(is_array($this-&gt;dbBind)) foreach($this-&gt;dbBind as $hook =&gt; $value) $sql = str_replace($hook, "'" . $value . "'", $sql); $this-&gt;dbQuery = mysql_query($sql) or die(mysql_error()); $this-&gt;dbBind = array(); return $this-&gt;numRows(); } // Load SQL statment into object $MyDB-&gt;prep("INSERT INTO `demo` (`id`, `name`, `score`, `dept`, `date`) VALUES '1','James Kablammo', '1205550', 'Marketing', '$date'"); // Bind a value to our :id hook // Produces: SELECT * FROM demo_table WHERE id = '23' $MyDB-&gt;bind(':id',1); // Run the query $MyDB-&gt;run(); </code></pre>
<p>It may help to start with using valid insert statements. </p> <pre><code>VALUES ( a , b , c ) </code></pre> <p>Not </p> <pre><code>VALUES a, b , c </code></pre> <p>Additionally, why the dickens are you combining a perpared insert with string substituion?</p> <p>you mean </p> <p>$q->prep("blah blah blah VALUES ( :date , etc etc ) " );<br> $q->bind(":date", $date ); </p> <p>or something along those lines. using both techniques is just nonsensical. </p>
<p>You should probably wrap the values() in parens too, like:</p> <pre><code>$MyDB-&gt;prep("INSERT INTO `demo` (`id`, `name`, `score`, `dept`, `date`) VALUES ('1','James Kablammo', '1205550', 'Marketing', '$date'")); </code></pre>
40,944
<p>I have three related questions. </p> <p>I want to create a word file with a name from C++. I want to be able to sent the printing command to this file, so that the file is being printed without the user having to open the document and do it manually and I want to be able to open the document. Opening the document should just open word which then opens the file.</p>
<p>You can use Office Automation for this task. You can find answers to frequently asked questions about Office Automation with C++ at <a href="http://support.microsoft.com/kb/196776" rel="noreferrer">http://support.microsoft.com/kb/196776</a> and <a href="http://support.microsoft.com/kb/238972" rel="noreferrer">http://support.microsoft.com/kb/238972</a> .</p> <p>Keep in mind that to do Office Automation with C++, you need to understand how to use COM.</p> <p>Here are some examples of how to perform various tasks in word usign C++:</p> <ul> <li><a href="http://support.microsoft.com/kb/220911/en-us" rel="noreferrer">http://support.microsoft.com/kb/220911/en-us</a></li> <li><a href="http://support.microsoft.com/kb/238393/en-us" rel="noreferrer">http://support.microsoft.com/kb/238393/en-us</a></li> <li><a href="http://support.microsoft.com/kb/238611/en-us" rel="noreferrer">http://support.microsoft.com/kb/238611/en-us</a></li> </ul> <p>Most of these samples show how to do it using MFC, but the concepts of using COM to manipulate Word are the same, even if you use ATL or COM directly.</p>
<p>I have no experience from integrating with Microsoft Office, but I guess there are some APIs around that you can use for this.</p> <p>However, if what you want to accomplish is a rudimentary way of printing formatted output and exporting it to a file that can be handled in Word, you might want to look into the RTF format. The format is quite simple to learn, and is supported by the RtfTextBox (or is it RichTextBox?), which also has some printing capabilities. The rtf format is the same format as is used by Windows Wordpad (write.exe).</p> <p>This also has the benefit of not depending on MS Office in order to work.</p>
17,552
<p>I would like to retrieve the ethernet address of the network interface that is used to access a particular website.</p> <p>How can this be done in Java?</p> <p><strong>Solution</strong> Note that the accepted solution of <code>getHardwareAddress</code> is only available in Java 6. There does not seem to be a solution for Java 5 aside from executing i(f|p)confing.</p>
<p><a href="http://java.sun.com/javase/6/docs/api/java/net/NetworkInterface.html#getHardwareAddress%28%29" rel="noreferrer"> java.net.NetworkInterface.getHardwareAddress</a> (method added in Java 6)</p> <p>It has to be called on the machine you are interested in - the MAC is not transferred across network boundaries (i.e. LAN and WAN). If you want to make use of it on a website server to interrogate the clients, you'd have to run an applet that would report the result back to you.</p> <p>For Java 5 and older I found code <a href="http://forums.sun.com/thread.jspa?messageID=3424868#4204392" rel="noreferrer">parsing output of command line tools on various systems</a>.</p>
<p>You can get the address that connects to your ServerSocket using <a href="http://java.sun.com/javase/6/docs/api/java/net/NetworkInterface.html#getInetAddresses()" rel="nofollow noreferrer">http://java.sun.com/javase/6/docs/api/java/net/NetworkInterface.html#getInetAddresses()</a></p> <p>However if your client is connecting via a NAT, then you will get the address of the router and NOT the Ethernet address. If it is on your local network (via a hub/switch, no router with NAT) the it wil work as intended.</p>
5,411
<p>Both are mathematical values, however the float does have more precision. Is that the only reason for the error - the difference in precision? Or is there another potential (and more serious) problem?</p>
<p>It's because the set of integer values does not equal the set of float values for the 'int' and 'float' types. For example, the float value 0.5 has no equal in the integer set and the integer value 4519245367 might not exist in the set of values a float can store. So, the checker flags this as an issue to be checked by the programmer.</p>
<p>If you need to get around this (you have a legitimate reason and are happy none of the issues mentioned in the other answers are an issue for you) then just cast from one type to another.</p>
5,894
<p>Without routing, <code>HttpContext.Current.Session</code> is there so I know that the <code>StateServer</code> is working. When I route my requests, <code>HttpContext.Current.Session</code> is <code>null</code> in the routed page. I am using .NET 3.5 sp1 on IIS 7.0, without the MVC previews. It appears that <code>AcquireRequestState</code> is never fired when using the routes and so the session variable isn't instantiated/filled.</p> <p>When I try to access the Session variables, I get this error:</p> <p><code>base {System.Runtime.InteropServices.ExternalException} = {"Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the &lt;configuration&gt;.</code></p> <p>While debugging, I also get the error that the <code>HttpContext.Current.Session</code> is not accessible in that context.</p> <p>--</p> <p>My <code>web.config</code> looks like this:</p> <pre><code>&lt;configuration&gt; ... &lt;system.web&gt; &lt;pages enableSessionState="true"&gt; &lt;controls&gt; ... &lt;/controls&gt; &lt;/pages&gt; ... &lt;/system.web&gt; &lt;sessionState cookieless="AutoDetect" mode="StateServer" timeout="22" /&gt; ... &lt;/configuration&gt; </code></pre> <p>Here's the IRouteHandler implementation:</p> <pre><code>public class WebPageRouteHandler : IRouteHandler, IRequiresSessionState { public string m_VirtualPath { get; private set; } public bool m_CheckPhysicalUrlAccess { get; set; } public WebPageRouteHandler(string virtualPath) : this(virtualPath, false) { } public WebPageRouteHandler(string virtualPath, bool checkPhysicalUrlAccess) { m_VirtualPath = virtualPath; m_CheckPhysicalUrlAccess = checkPhysicalUrlAccess; } public IHttpHandler GetHttpHandler(RequestContext requestContext) { if (m_CheckPhysicalUrlAccess &amp;&amp; !UrlAuthorizationModule.CheckUrlAccessForPrincipal( m_VirtualPath, requestContext.HttpContext.User, requestContext.HttpContext.Request.HttpMethod)) { throw new SecurityException(); } string var = String.Empty; foreach (var value in requestContext.RouteData.Values) { requestContext.HttpContext.Items[value.Key] = value.Value; } Page page = BuildManager.CreateInstanceFromVirtualPath( m_VirtualPath, typeof(Page)) as Page;// IHttpHandler; if (page != null) { return page; } return page; } } </code></pre> <p>I've also tried to put <code>EnableSessionState="True"</code> on the top of the aspx pages but still, nothing.</p> <p>Any insights? Should I write another <code>HttpRequestHandler</code> that implements <code>IRequiresSessionState</code>?</p> <p>Thanks.</p>
<p>Got it. Quite stupid, actually. It worked after I removed &amp; added the SessionStateModule like so:</p> <pre><code>&lt;configuration&gt; ... &lt;system.webServer&gt; ... &lt;modules&gt; &lt;remove name="Session" /&gt; &lt;add name="Session" type="System.Web.SessionState.SessionStateModule"/&gt; ... &lt;/modules&gt; &lt;/system.webServer&gt; &lt;/configuration&gt; </code></pre> <p>Simply adding it won't work since "Session" should have already been defined in the <code>machine.config</code>.</p> <p>Now, I wonder if that is the usual thing to do. It surely doesn't seem so since it seems so crude...</p>
<p>a better solution is </p> <p></p> <p>runAllManagedModulesForAllRequest is a clever thing to do respect removing and resinserting session module.</p> <p>alk.</p>
26,821
<p>How can I do a script to catch strings as input and open them on a Firefox document? Each link would go to a different window or tab. Any ideas would be much appreciated.</p> <p>I just want to be able to take some links and open them. For example I have 50 Links. And copying and parsing those 50 Links take a really long time and also a lot of work. If I can just write a script to read those links and let the computer do the work, it will be very helpful for me. I just don't know how to write that or where because it does not sound too hard (just gotta know how to). Thanks for any suggestions. </p>
<p>if i got you right, i guess you could do something like this. This will open the four urls listed but it will probably be blocked by the popup blocker.</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Documento sin t&amp;iacute;tulo&lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"&gt; &lt;/head&gt; &lt;body&gt; &lt;script&gt; &lt;!-- var dir = new Array(); dir[0] = "http://www.creativecorner.cl/"; dir[1] = "http://www.sourcing.cl/"; dir[2] = "http://www.feeds.cl/"; dir[3] = "http://www.neonomade.com/"; for(i = 0 ; i &lt; dir.length ; i++){ window.open(dir[i],'autowindow' + i,'width=1024,height=768'); } --&gt; &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>Write this to a file names "links.html" on your hard disk:</p> <pre><code>&lt;html&gt; &lt;head&gt;&lt;title&gt;Your links&lt;/title&gt;&lt;/head&gt; &lt;body&gt; Your links:&lt;br /&gt; &lt;a href="XXX"&gt;XXX&lt;/a&gt;&lt;br /&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Replace the two "XXX" with one link and emit one "link" (a) line per link. You should be able to do that in most text editors with a little search'n'replace. After you're done, save the file and open it in your browser.</p> <p>Another option is to look at the bookmark file of your browser and to duplicate the format. You can usually ignore things like "last visited", etc. Just add the links.</p> <p>If you want to do this in JavaScript, you will need to use a form with a textarea. Create a small HTML document with a form, the JavaScript, the textarea and a div for the result.</p> <p>Add a button which calls a JavaScript function which takes the text from the textarea, split it into lines and create the HTML above (only the link-lines) as a String. Now assign this string to the attribute <code>innerHTML</code> of the div to make the links clickable.</p>
45,281
<p>How does one go about authoring a <em><strong>Regular Expression</strong></em> that matches against all strings that are valid URIs, while failing to match against all strings that are invalid URIs?</p> <p>To be specific about what I am referencing when I say URI, I have added a link below for the most current URI RFC standard. It defines the entity that I want to validate using a regular expression.</p> <p>I don't need it to be able to parse the URI. I just need a regular expression for validating.</p> <p>The <strong>.Net Regular Expression Format</strong> is preferred. (.Net V1.1)</p> <br> <h4>My Current Solution:</h4> <pre><code>^([a-zA-Z0-9+.-]+):(//([a-zA-Z0-9-._~!$&amp;'()*+,;=:]*)@)?([a-zA-Z0-9-._~!$&amp;'()*+,;=]+)(:(\\d*))?(/?[a-zA-Z0-9-._~!$&amp;'()*+,;=:/]+)?(\\?[a-zA-Z0-9-._~!$&amp;'()*+,;=:/?@]+)?(#[a-zA-Z0-9-._~!$&amp;'()*+,;=:/?@]+)?$(:(\\d*))?(/?[a-zA-Z0-9-._~!$&amp;'()*+,;=:/]+)?(\?[a-zA-Z0-9-._~!$&amp;'()*+,;=:/?@]+)?(\#[a-zA-Z0-9-._~!$&amp;'()*+,;=:/?@]+)?$ </code></pre>
<p>Does <a href="http://msdn.microsoft.com/en-us/library/system.uri.iswellformeduristring.aspx" rel="noreferrer">Uri.IsWellFormedUriString</a> work for you?</p>
<p>Are there some specific URIs you care about or are you trying to find a single regex that validates <a href="http://rfc.net/std0066.html" rel="nofollow noreferrer">STD66</a>?</p> <p>I was going to point you to <a href="http://www.unix.com.ua/rfc/std0066.html#p50" rel="nofollow noreferrer">this regex</a> for parsing a URI. You could then, in theory, check to see if all of the elements you care about are there. </p> <p>But I think <a href="https://stackoverflow.com/questions/30847#30858">bdukes</a> answer is better.</p>
5,070
<p><a href="https://stackoverflow.com/questions/180/function-for-creating-color-wheels">Original Question</a></p> <p>I am looking for a function that attempts to quantify how "distant" (or distinct) two colors are. This question is really in two parts: </p> <ol> <li>What color space best represents human vision?</li> <li>What distance metric in that space best represents human vision (euclidean?)</li> </ol>
<p>Convert to La*b* (aka just plain "Lab", and you'll also see reference to "CIELAB"). A good quick measaure of color difference is </p> <blockquote> <p>(L1-L2)^2 + (a1-a2)^2 + (b1-b2)^2</p> </blockquote> <p>Color scientists have other more refined measures, which may not be worth the bother, depending on accuracy needed for what you're doing.</p> <p>The <code>a</code> and <code>b</code> values represent opposing colors in a way similar to how cones work, and may be negative or positive. Neutral colors - white, grays are <code>a=0</code>,<code>b=0</code>. The <code>L</code> is brightness defined in a particular way, from zero (pure darkness) up to whatever. </p> <p>Crude explanation :>> Given a color, our eyes distinguish between two broad ranges of wavelength - blue vs longer wavelengths. and then, thanks to a more recent genetic mutation, the longer wavelength cones bifurcated into two, distinguishing for us red vs. green. </p> <p>By the way, it'll be great for your career to rise above your color caveman collegues who know of only "RGB" or "CMYK" which are great for devices but suck for serious perception work. I've worked for imaging scientists who didn't know a thing about this stuff!</p> <p>For more fun reading on color difference theory, try:</p> <ul> <li><a href="http://white.stanford.edu/~brian/scielab/introduction.html" rel="noreferrer">http://white.stanford.edu/~brian/scielab/introduction.html</a> and info </li> <li>and links on color theory in general, websurf starting with <a href="http://www.efg2.com/Lab/Library/Color/" rel="noreferrer">http://www.efg2.com/Lab/Library/Color/</a> and </li> <li><a href="http://www.poynton.com/Poynton-color.html" rel="noreferrer">http://www.poynton.com/Poynton-color.html</a> </li> </ul> <p>More detail on Lab at <a href="http://en.kioskea.net/video/cie-lab.php3" rel="noreferrer">http://en.kioskea.net/video/cie-lab.php3</a> I can't at this time find a non-ugly page that actually had the conversion formulas but I'm sure someone will edit this answer to include one.</p>
<p>The easiest <em>distance</em> would of course be to just consider the colors as 3d vectors originating from the same origin, and taking the distance between their end points.</p> <p>If you need to consider such factors that green is more prominent in judging intensity, you can weigh the values.</p> <p><a href="http://www.imagemagick.org/Usage/color/#grayscale" rel="nofollow noreferrer">ImageMagic</a> provides the following scales: </p> <ul> <li>red: 0.3</li> <li>green: 0.6</li> <li>blue: 0.1</li> </ul> <p>Of course, values like this would only be meaningful in relation to other values for other colors, not as something that would be meaningful to humans, so all you could use the values for would be similiarity ordering.</p>
2,372
<p>I have a 3D printer at home, the Colido Compact, and for some reason when I 3D print big flat surfaces a really weird thing happens. I'm using some PLA from Colido too I think</p> <p><a href="https://i.stack.imgur.com/QOMPF.jpg" rel="nofollow noreferrer" title="Weeeird surface artefacts"><img src="https://i.stack.imgur.com/QOMPF.jpg" alt="Weeeird surface artefacts" title="Weeeird surface artefacts"></a></p> <p>It almost seems as if the bottom layer does perfectly but when it starts printing out the top surface this happens, because the one on the bottom left is in two parts because the upper part is the bottom one and that one is perfectly flat, then I took them apart and the weird thing just stayed with the top part... and also on the weird warps there are bits of brown goo or something? I don't know it looks as if the filament was burned... It only appears on pretty big surfaces because smaller ones don't seem to have the problem.</p> <p>Anyone knows what is happening?</p>
<p>The oozing is due to hot-end getting hot before the bed leveling procedure: if you move the hot-end warm up command <strong>after</strong> the <code>G29</code> line you avoid that oozing</p> <pre><code>; Ender 3 Custom Start G-code M104 S{material_print_temperature_layer_0} ; Set Extruder temperature M140 S{material_bed_temperature_layer_0} ; Set Heat Bed temperature G28 ; Home all axes G29 ; BLTOUCH Mesh Generation M190 S{material_bed_temperature_layer_0} ; Wait for Heat Bed temperature M109 S{material_print_temperature_layer_0} ; Wait for Extruder temperature G1 F1800 E-3 ; Retract filament 3 mm to prevent oozing G92 E0 ; Reset Extruder G1 Z5.0 F3000 ; Move Z Axis up little to prevent scratching of Heat Bed G1 X0.1 Y20 Z0.3 F5000.0 ; Move to start position G1 X0.1 Y200.0 Z0.3 F1500.0 E15 ; Draw the first line G1 X0.4 Y200.0 Z0.3 F5000.0 ; Move to side a little G1 X0.4 Y20 Z0.3 F1500.0 E30 ; Draw the second line G92 E0 ; Reset Extruder G1 Z5.0 F3000 ; Move Z Axis up little to prevent scratching of Heat Bed </code></pre> <p>The above code will activate the heating elements but starts homing and leveling procedure without waiting for the elements to get up to temperature. Only after the bed leveling is finished the printer will pause and wait for the heating elements reach the desired temperature.</p> <p>This will prevent oozing on a cold start, but you will still be affected if you start a print right after another print, when the hot-end is still close to melting temperature.</p> <p>If you prefer to avoid that condition you might want to also move the <code>M104</code> and <code>M140</code> commands after the <code>G29</code> bed leveling command.</p>
<p>The best solution would be to heat the bed, but not the nozzle at startup. If you level with a cold bed, your ABL mesh is going to be off, since the aluminum heated bed plate expands considerably once the heat is applied. </p> <p>You could also issue a retract command before leveling, and then add a counteracting filament feed command after ABL is complete. I have no idea how that code would look though. Just my 2 cents.</p>
1,142
<p>When A Python exception is thrown by code that spans multiple lines, e.g.:</p> <pre><code> myfoos = [foo("bar", "baz", "quux", i) for i in range(10)] </code></pre> <p>Python will report the line number of the last line, and will show the code fragment from that line:</p> <pre><code>Traceback (most recent call last): File "test.py", line 4, in &lt;module&gt; i) for i in range(10)] NameError: name 'foo' is not defined </code></pre> <p>Is there any way to determine what the first line is? Is there any way to catch the exception and manipulate the <a href="http://docs.python.org/library/traceback.html" rel="nofollow noreferrer">traceback</a> object to be able to report something like this instead:</p> <pre><code>Traceback (most recent call last): File "test.py", lines 1-4 in &lt;module&gt; myfoos = [foo("bar", "baz", "quux", i) for i in range(10)] NameError: name 'foo' is not defined </code></pre>
<p>Finding the beginning of the line will be really hard. You'll have to either parse the Python or maybe dig into the compiled byte code. There are modules in the standard library for parsing Python, but I can tell you from experience that interpreting their output is a black art. And I'm not sure the compiled byte code has the answer either...</p>
<p>In a try/except block you can except NameError and try setting NameError.lineno, though I'm not exactly sure if or how this works, but it's the best I've found thusfar.</p> <pre><code>try: somecode except NameError NameError.lineno = [1,4] </code></pre> <p>You'll have to figure out where the statement begins and ends yourself somehow as well as which statement is raising the error.</p> <p>Hope this helps</p>
37,178
<p>One of my programs requires a reliable way to log across unreliable network (ie internet). The sender or receiver may go offline any time and can come back later. But any message sent by client should not be missed. Obviously syslog does not fit the bill. I am exploring the use of messaging servers like Apache ActiveMQ instead of syslog. Message senders are in perl, ruby and c. So I have Stomp as the message transport. </p> <p>Does this serve my purpose? Is there any pitfall I am missing here?</p> <p>raj</p>
<p>That all sounds fine to me</p>
<p>You may want to check out <A href="http://www.balabit.com/network-security/syslog-ng/" rel="nofollow noreferrer">syslog-ng</A> which has a tcp mode. This allows for reliable delivery, but you have to make sure you configure it correctly.</p>
37,671
<p>Does anybody have a snippet of Java that can return the newest file in a directory (or knowledge of a library that simplifies this sort of thing)?</p>
<p>The following code returns the last modified file or folder:</p> <pre><code>public static File getLastModified(String directoryFilePath) { File directory = new File(directoryFilePath); File[] files = directory.listFiles(File::isFile); long lastModifiedTime = Long.MIN_VALUE; File chosenFile = null; if (files != null) { for (File file : files) { if (file.lastModified() &gt; lastModifiedTime) { chosenFile = file; lastModifiedTime = file.lastModified(); } } } return chosenFile; } </code></pre> <p>Note that it required <code>Java 8</code> or newer due to the lambda expression.</p>
<p>Here's a small modification to Jose's code which makes sure the folder has at least 1 file in it. Work's great in my app!</p> <pre><code>public static File lastFileModified(String dir) { File fl = new File(dir); File choice = null; if (fl.listFiles().length&gt;0) { File[] files = fl.listFiles(new FileFilter() { public boolean accept(File file) { return file.isFile(); } }); long lastMod = Long.MIN_VALUE; for (File file : files) { if (file.lastModified() &gt; lastMod) { choice = file; lastMod = file.lastModified(); } } } return choice; } </code></pre>
36,323
<p>I have a Request object which contains a list of Approvers. An approver has a name and an approval position.</p> <ol> <li>Mathew </li> <li>Mark </li> <li>Luke </li> <li>John</li> </ol> <p>Ultimately, a request will move through this chain, starting at Mathew and ended at John.</p> <p>I need to be able to re-order these allowing adds and deletes as outlined below.</p> <p>An approver can be -</p> <p>Added at a certain position - ie. Add Peter at position 3 in which case the new order would be</p> <ol> <li>Mathew </li> <li>Mark </li> <li>Peter</li> <li>Luke </li> <li>John</li> </ol> <p>Delete - ie. Delete Mark in which case the new order is</p> <ol> <li>Mathew </li> <li>Luke </li> <li>John</li> </ol> <p>Edited - ie you can change John's position to 1 in which case the new order is</p> <ol> <li>John</li> <li>Mathew </li> <li>Mark </li> <li>Luke </li> </ol> <p>I have come up with a number of solutions, however none of them is particular elegant.</p> <p>Any help would be much appreciated</p>
<p>How large are the lists likely to be? <a href="http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx" rel="noreferrer"><code>List&lt;T&gt;</code></a> is likely to be the easiest representation of the collection, but it means a copy is required every time you insert into or remove from the middle of the list. "Editing" the list basically means a remove/insert.</p> <p>Iteration is then straightforward.</p> <p>An alternative might be <a href="http://msdn.microsoft.com/en-us/library/he2s3bh7.aspx" rel="noreferrer"><code>LinkedList&lt;T&gt;</code></a> - which makes iteration simple and "insert after", "insert before" and "delete" cheap <em>if</em> you hang onto the <a href="http://msdn.microsoft.com/en-us/library/d97b9a15.aspx" rel="noreferrer"><code>LinkedListNode&lt;T&gt;</code></a> associated with each of your approvers. But it doesn't make it easy to say "this reviewer should now be at position 3" - you'd have to iterate through to find position 3 first (or 2, anyway). If it's a case of "move this approver after this one" then it's ideal.</p>
<p>Maintaining a position property is a pain, as you need to make lots of modifications to change something (while keeping everything logical). It also makes it hard to serialize/deserialize efficiently.</p> <p>Can you not simply infer the position from the position in a <code>List&lt;T&gt;</code> or similar? Then you can <code>Add()</code> to the end, <code>Insert()</code> to the middle and <code>Remove()</code> from anywhere. To move something you simply <code>Remove()</code> it and <code>Insert()</code> it at the position you want?</p> <p>Like so (formatted for space):</p> <pre><code>using System; using System.Collections.ObjectModel; using System.Linq; // I only added this to use a lazier "collection initializer" below, // which needs an Add(string) method... class ApproverCollection : Collection&lt;Approver&gt; { public void Add(string name) { Add(new Approver(name)); } } class Request { public Request() { Approvers = new ApproverCollection(); } public ApproverCollection Approvers { get; private set; } } class Approver { public Approver(string name) { Name = name; } public string Name { get; set; } } static class Program { static void Main() { Request req = new Request { Approvers = {"Mathew", "Mark", "Luke", "John"} }; req.ShowState("Initial"); req.Approvers.Insert(2, new Approver("Peter")); req.ShowState("Inserted Peter"); Approver mark = req.Approvers.Single(x =&gt; x.Name == "Mark"); req.Approvers.Remove(mark); req.ShowState("Removed Mark"); Approver john = req.Approvers.Single(x =&gt; x.Name == "John"); req.Approvers.Remove(john); req.Approvers.Insert(0, john); req.ShowState("Moved John"); } static void ShowState(this Request request, string caption) { Console.WriteLine(); Console.WriteLine(caption); int pos = 1; foreach(Approver a in request.Approvers) { Console.WriteLine("{0}: {1}", pos++, a.Name); } } } </code></pre>
29,609
<p>How do I programmatically set the record pointer in a C# DataGridView? </p> <p>I've tried "DataGridView.Rows[DesiredRowIndex].Selected=true;", and that does not work. All it does is highlight that row within the grid; it doesn not move the record pointer to that row.</p>
<p>To change the active row for the datagrid you need to set the current cell property of the datagrid to a non-hidden non-disabled, non-header cell on the row that you have selected. You'd do this like:</p> <pre><code>dataGridView1.CurrentCell = this.dataGridView1[YourColumn,YourRow]; </code></pre> <p>Making sure that the cell matches the above criteria. Further information can be found at:</p> <p><a href="http://msdn.microsoft.com/en-us/library/yc4fsbf5.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/yc4fsbf5.aspx</a></p>
<p>Try setting the focus of the <code>DataGrid</code> first . Some thing like this</p> <pre><code>dataGridView1.Focus(); dataGridView1.CurrentCell = this.dataGridView1[YourColumn,YourRow]; </code></pre> <p>This worked in my case, hope it helps you as well</p>
11,750
<p>As a matter of fact you have smth like <code>/java/src</code> and <code>/java/test</code>. But then, how do you name packages/classes the unittests go to? The same as classes they are written against? And when refactoring comes, do you manually rename in /test? Please share your experience.</p>
<p>I keep the tests in the same package as the class they are testing. This allows me to setup tests using package private members (when required). It also provides a nice, easy to remember convention. When I refactor, I usually do manually refactor the corresponding test classes. There was some IDE a while back that had the ability to do this refactoring automatically, but I can't remember it off the top of my head.</p>
<p>In Java, keeping them in the same package as the class being tested, is a must. It's the only way to test methods with default/package-protected visibility.</p>
23,544
<p>I have a sample held in a buffer from DirectX. It's a sample of a note played and captured from an instrument. How do I analyse the frequency of the sample (like a guitar tuner does)? I believe FFTs are involved, but I have no pointers to HOWTOs.</p>
<p>The FFT can help you figure out where the frequency is, but it can't tell you <em>exactly</em> what the frequency is. Each point in the FFT is a &quot;bin&quot; of frequencies, so if there's a peak in your FFT, all you know is that the frequency you want is somewhere within that bin, or range of frequencies.</p> <p>If you want it really accurate, you need a long FFT with a high resolution and lots of bins (= lots of memory and lots of computation). You can also guess the true peak from a low-resolution FFT using <a href="https://ccrma.stanford.edu/%7Ejos/sasp/Quadratic_Interpolation_Spectral_Peaks.html" rel="nofollow noreferrer">quadratic interpolation</a> on the log-scaled spectrum, which works surprisingly well.</p> <p>If computational cost is most important, you can try to get the signal into a form in which you can count zero crossings, and then the more you count, the more accurate your measurement.</p> <p>None of these will work if the <a href="http://en.wikipedia.org/wiki/Missing_fundamental" rel="nofollow noreferrer">fundamental is missing</a>, though. :)</p> <p>I've outlined a few different algorithms <a href="https://gist.github.com/endolith/255291" rel="nofollow noreferrer">here</a>, and the interpolated FFT is usually the most accurate (though this only works <a href="https://www.flickr.com/photos/omegatron/4180172061/" rel="nofollow noreferrer">when the fundamental is the strongest harmonic</a> - otherwise you need to be smarter about finding it), with zero-crossings a close second (though this only works <a href="https://www.flickr.com/photos/omegatron/4180888094/" rel="nofollow noreferrer">for waveforms with one crossing per cycle</a>). Neither of these conditions is typical.</p> <p>Keep in mind that the partials above the fundamental frequency are <strong>not</strong> perfect harmonics in many instruments, like piano or guitar. Each partial is <a href="https://www.flickr.com/photos/omegatron/4166565758/" rel="nofollow noreferrer">actually a little bit out of tune</a>, or <a href="http://en.wikipedia.org/wiki/Inharmonicity" rel="nofollow noreferrer"><em>inharmonic</em></a>. So the higher-frequency peaks in the FFT will not be exactly on the integer multiples of the fundamental, and the wave shape will change slightly from one cycle to the next, which throws off autocorrelation.</p> <p>To get a really accurate frequency reading, I'd say to use the autocorrelation to guess the fundamental, then find the true peak using quadratic interpolation. (You can do the autocorrelation in the frequency domain to save CPU cycles.) There are a lot of gotchas, and the right method to use really depends on your application.</p>
<p>Apply a <a href="http://en.wikipedia.org/wiki/Discrete_Fourier_transform" rel="nofollow noreferrer">DFT</a> and then derive the fundamental frequency from the results. Googling around for DFT information will give you the information you need -- I'd link you to some, but they differ greatly in expectations of math knowledge.</p> <p>Good luck.</p>
9,104
<p>How do I make an instance of gwtext.client.widgets.Window appear at specific DIV in my html ? I tried window.anchorTo(DOM.getElementById("Some_Div"),"left", new int[]{0,0}), thinking the window will anchor itself to div id="Some_Div" in my html. it didnt. </p>
<p>I haven't used the gwt-ext library in a couple of months, but you might want to try this if you haven't already. It <em>should</em> attach the widget where you want it. That said, there are some cases where the gwt-ext widgets react in ways that are not intuitive to someone who really understands the normal GWT widgets.</p> <pre><code>RootPanel.get("Some_Div_Id").add( someWidget ) </code></pre>
<p>You should use </p> <pre><code>window.alignTo(DOM.getElementById("Some_Div"),"tl-tl", new int[]{0,0}); </code></pre> <p>for positioning the window's top left to Some_Div's top left corner.</p> <p>These are the valid strings for position argument:</p> <pre><code>Value Description ----- ----------------------------- tl The top left corner (default) t The center of the top edge tr The top right corner l The center of the left edge c In the center of the element r The center of the right edge bl The bottom left corner b The center of the bottom edge br The bottom right corner </code></pre> <p>Refer the Ext documentation for detailed explanation.</p>
40,614
<p>Could someone explain? I understand the basic concepts behind them but I often see them used interchangeably and I get confused. </p> <p>And now that we're here, how do they differ from a regular function?</p>
<p>A <b>lambda</b> is just an anonymous function - a function defined with no name. In some languages, such as Scheme, they are equivalent to named functions. In fact, the function definition is re-written as binding a lambda to a variable internally. In other languages, like Python, there are some (rather needless) distinctions between them, but they behave the same way otherwise.</p> <p>A <b>closure</b> is any function which <b>closes over</b> the <b>environment</b> in which it was defined. This means that it can access variables not in its parameter list. Examples:</p> <pre><code>def func(): return h def anotherfunc(h): return func() </code></pre> <p>This will cause an error, because <code>func</code> does not <b>close over</b> the environment in <code>anotherfunc</code> - <code>h</code> is undefined. <code>func</code> only closes over the global environment. This will work:</p> <pre><code>def anotherfunc(h): def func(): return h return func() </code></pre> <p>Because here, <code>func</code> is defined in <code>anotherfunc</code>, and in python 2.3 and greater (or some number like this) when they <i>almost</i> got closures correct (mutation still doesn't work), this means that it <b>closes over</b> <code>anotherfunc</code>'s environment and can access variables inside of it. In Python 3.1+, mutation works too when using <a href="http://docs.python.org/release/3.1.3/reference/simple_stmts.html#nonlocal" rel="noreferrer">the <code>nonlocal</code> keyword</a>.</p> <p>Another important point - <code>func</code> will continue to close over <code>anotherfunc</code>'s environment even when it's no longer being evaluated in <code>anotherfunc</code>. This code will also work:</p> <pre><code>def anotherfunc(h): def func(): return h return func print anotherfunc(10)() </code></pre> <p>This will print 10.</p> <p>This, as you notice, has nothing to do with <b>lambda</b>s - they are two different (although related) concepts.</p>
<p>Lambda is an anonymous function <em>definition</em> that is not (necessarily) bound to an identifier.</p> <blockquote> <p>&quot;Anonymous functions originate in the work of Alonzo Church in his invention of the lambda calculus, in which all functions are anonymous&quot; - <a href="https://en.wikipedia.org/wiki/Anonymous_function" rel="nofollow noreferrer">Wikipedia</a></p> </blockquote> <p>Closure is the lambda function implementation.</p> <blockquote> <p>&quot;Peter J. Landin defined the term closure in 1964 as having an environment part and a control part as used by his SECD machine for evaluating expressions&quot; - <a href="https://en.wikipedia.org/wiki/Closure_(computer_programming)#History_and_etymology" rel="nofollow noreferrer">Wikipedia</a></p> </blockquote> <p>The generic explanation of Lambda and Closure is covered in the other responses.</p> <p>For those from a C++ background, Lambda expressions were introduced in C++11. Think of Lambdas as a convenient way to create anonymous functions and function objects.</p> <blockquote> <p>&quot;The distinction between a lambda and the corresponding closure is precisely equivalent to the distinction between a class and an instance of the class. A class exists only in source code; it doesn’t exist at runtime. What exists at runtime are objects of the class type. Closures are to lambdas as objects are to classes. This should not be a surprise, because each lambda expression causes a unique class to be generated (during compilation) and also causes an object of that class type, a closure to be created (at runtime).&quot; - <a href="http://scottmeyers.blogspot.com/2013/05/lambdas-vs-closures.html" rel="nofollow noreferrer">Scott Myers</a></p> </blockquote> <p>C++ allows us to examine the nuances of Lambda and Closure as you have to explicitly specify the free variables to be captured.</p> <p>In the sample below, the Lambda expression has no free variables, an empty capture list (<code>[]</code>). It’s essentially an ordinary function and no closure is required in the strictest sense. So it can even be passed as a function pointer argument.</p> <pre><code>void register_func(void(*f)(int val)) // Works only with an EMPTY capture list { int val = 3; f(val); } int main() { int env = 5; register_func( [](int val){ /* lambda body can access only val variable*/ } ); } </code></pre> <p>As soon as a free variable from the surrounding environment is introduced in the capture list (<code>[env]</code>), a Closure has to be generated.</p> <pre><code> register_func( [env](int val){ /* lambda body can access val and env variables*/ } ); </code></pre> <p>Since this is no longer an ordinary function, but a closure instead, it produces a compilation error.<br /> <code>no suitable conversion function from &quot;lambda []void (int val)-&gt;void&quot; to &quot;void (*)(int val)&quot; exists</code></p> <p>The error can be fixed with a function wrapper <code>std::function</code> which accepts any callable target including a generated closure.</p> <pre><code>void register_func(std::function&lt;void(int val)&gt; f) </code></pre> <p>See <a href="https://cognitivewaves.wordpress.com/lambda-and-closure/" rel="nofollow noreferrer">Lambda and Closure</a> for a detailed explanation with a C++ example.</p>
27,173
<p>Is this functionality going to be put into a later Java version?</p> <p>Can someone explain why I can't do this, as in, the technical way Java's <code>switch</code> statement works?</p>
<p>Switch statements with <code>String</code> cases have been implemented in <a href="http://openjdk.java.net/projects/jdk7/features/" rel="nofollow noreferrer">Java SE 7</a>, at least 16 years <a href="https://bugs.java.com/bugdatabase/view_bug.do?bug_id=1223179" rel="nofollow noreferrer">after they were first requested.</a> A clear reason for the delay was not provided, but it likely had to do with performance.</p> <h2>Implementation in JDK 7</h2> <p>The feature has now been implemented in <code>javac</code> <a href="http://blogs.oracle.com/darcy/entry/project_coin_string_switch_anatomy" rel="nofollow noreferrer">with a &quot;de-sugaring&quot; process;</a> a clean, high-level syntax using <code>String</code> constants in <code>case</code> declarations is expanded at compile-time into more complex code following a pattern. The resulting code uses JVM instructions that have always existed.</p> <p>A <code>switch</code> with <code>String</code> cases is translated into two switches during compilation. The first maps each string to a unique integer—its position in the original switch. This is done by first switching on the hash code of the label. The corresponding case is an <code>if</code> statement that tests string equality; if there are collisions on the hash, the test is a cascading <code>if-else-if</code>. The second switch mirrors that in the original source code, but substitutes the case labels with their corresponding positions. This two-step process makes it easy to preserve the flow control of the original switch.</p> <h2>Switches in the JVM</h2> <p>For more technical depth on <code>switch</code>, you can refer to the JVM Specification, where the <a href="http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-3.html#jvms-3.10" rel="nofollow noreferrer">compilation of switch statements</a> is described. In a nutshell, there are two different JVM instructions that can be used for a switch, depending on the sparsity of the constants used by the cases. Both depend on using integer constants for each case to execute efficiently.</p> <p>If the constants are dense, they are used as an index (after subtracting the lowest value) into a table of instruction pointers—the <code>tableswitch</code> instruction.</p> <p>If the constants are sparse, a binary search for the correct case is performed—the <code>lookupswitch</code> instruction.</p> <p>In de-sugaring a <code>switch</code> on <code>String</code> objects, both instructions are likely to be used. The <code>lookupswitch</code> is suitable for the first switch on hash codes to find the original position of the case. The resulting ordinal is a natural fit for a <code>tableswitch</code>.</p> <p>Both instructions require the integer constants assigned to each case to be sorted at compile time. At runtime, while the <code>O(1)</code> performance of <code>tableswitch</code> generally appears better than the <code>O(log(n))</code> performance of <code>lookupswitch</code>, it requires some analysis to determine whether the table is dense enough to justify the space–time tradeoff. Bill Venners wrote <a href="http://www.artima.com/underthehood/flowP.html" rel="nofollow noreferrer">a great article</a> that covers this in more detail, along with an under-the-hood look at other Java flow control instructions.</p> <h2>Before JDK 7</h2> <p>Prior to JDK 7, <code>enum</code> could approximate a <code>String</code>-based switch. This uses <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.9.3" rel="nofollow noreferrer">the static <code>valueOf</code></a> method generated by the compiler on every <code>enum</code> type. For example:</p> <pre><code>Pill p = Pill.valueOf(str); switch(p) { case RED: pop(); break; case BLUE: push(); break; } </code></pre>
<p>Not very pretty, but here is another way for Java 6 and bellow: </p> <pre><code>String runFct = queryType.equals("eq") ? "method1": queryType.equals("L_L")? "method2": queryType.equals("L_R")? "method3": queryType.equals("L_LR")? "method4": "method5"; Method m = this.getClass().getMethod(runFct); m.invoke(this); </code></pre>
43,894
<p>In an application that is hosting several WCF services, what would be the best way to add custom configuration information for each service? For example you may want to pass or set a company name or specify the connectionString a service or some other parameter. </p> <p>I'm guessing this might be possible by implementing IServiceBehavior.</p> <p>i.e something like....</p> <pre><code>&lt;behaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior name="MyBehavior"&gt; &lt;serviceMetadata httpGetEnabled="true" /&gt; &lt;serviceDebug /&gt; &lt;customBehavior myCompany="ABC" /&gt; &lt;/behavior&gt; &lt;behavior name="MyOtherBehavior"&gt; &lt;serviceMetadata httpGetEnabled="true" /&gt; &lt;serviceDebug /&gt; &lt;customBehavior myCompany="DEF" /&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;/behaviors&gt; &lt;services&gt; &lt;service behaviorConfiguration="MyBehavior" name="MyNameSpace.MyService"&gt; &lt;endpoint address="" behaviorConfiguration="" binding="netTcpBinding" name="TcpEndpoint" contract="MyNameSpace.IMyService" /&gt; &lt;endpoint address="mex" binding="mexTcpBinding" bindingConfiguration="" name="TcpMexEndpoint" contract="IMetadataExchange" /&gt; &lt;host&gt; &lt;baseAddresses&gt; &lt;add baseAddress="net.tcp://localhost:4000/MyService" /&gt; &lt;/baseAddresses&gt; &lt;/host&gt; &lt;/service&gt; &lt;service behaviorConfiguration="MyOtherBehavior" name="MyNameSpace.MyOtherService"&gt; &lt;endpoint address="" behaviorConfiguration="" binding="netTcpBinding" name="TcpEndpoint" contract="MyNameSpace.IMyOtherService" /&gt; &lt;endpoint address="mex" binding="mexTcpBinding" bindingConfiguration="" name="TcpMexEndpoint" contract="IMetadataExchange" /&gt; &lt;host&gt; &lt;baseAddresses&gt; &lt;add baseAddress="net.tcp://localhost:4000/MyOtherService" /&gt; &lt;/baseAddresses&gt; &lt;/host&gt; &lt;/service&gt; &lt;/services&gt; </code></pre> <p>Would set ABC on MyService and DEF on MyOtherService (assuming they have some common interface with a company name).</p> <p>Can anyone elaborate on how you implement this?</p> <p>TIA</p> <p>Michael</p>
<p>I know this is old, but it was never marked answered, so I thought I'd take a shot. If I understand what you're after, you can do it with a custom ServiceHostFactory.<br> Good post on this <a href="http://blogs.msdn.com/dotnetinterop/archive/2008/09/22/custom-service-config-file-for-a-wcf-service-hosted-in-iis.aspx" rel="noreferrer">here</a>. </p> <p>You set up yuour custom ServiceHostFactory like so:</p> <pre><code>&lt;%@ ServiceHost Language="C#" Debug="true" Service="Ionic.Samples.Webservices.Sep20.CustomConfigService" Factory="Ionic.ServiceModel.ServiceHostFactory"%&gt; </code></pre> <p>Then, in your ServiceHostFactory, you can override a method called ApplyConfiguration. Normally for WCF apps hosted in IIS, WCF would automatically look for config in web.config. In this example, we override that behavior to first look for a config file named after the WCF Service Description. </p> <pre><code>protected override void ApplyConfiguration() { // generate the name of the custom configFile, from the service name: string configFilename = System.IO.Path.Combine ( physicalPath, String.Format("{0}.config", this.Description.Name)); if (string.IsNullOrEmpty(configFilename) || !System.IO.File.Exists(configFilename)) base.ApplyConfiguration(); else LoadConfigFromCustomLocation(configFilename); } </code></pre> <p>You could replace this with "anything" - for example, looking for config in a database table. </p> <p>A few more methods complete the puzzle.</p> <pre><code>private string _physicalPath = null; private string physicalPath { get { if (_physicalPath == null) { // if hosted in IIS _physicalPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath; if (String.IsNullOrEmpty(_physicalPath)) { // for hosting outside of IIS _physicalPath= System.IO.Directory.GetCurrentDirectory(); } } return _physicalPath; } } private void LoadConfigFromCustomLocation(string configFilename) { var filemap = new System.Configuration.ExeConfigurationFileMap(); filemap.ExeConfigFilename = configFilename; System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration (filemap, System.Configuration.ConfigurationUserLevel.None); var serviceModel = System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup(config); bool loaded= false; foreach (System.ServiceModel.Configuration.ServiceElement se in serviceModel.Services.Services) { if(!loaded) if (se.Name == this.Description.ConfigurationName) { base.LoadConfigurationSection(se); loaded= true; } } if (!loaded) throw new ArgumentException("ServiceElement doesn't exist"); } </code></pre>
<p>It depends a lot of where and how you expect to use said information. If it's not something that's going to do a lot with the infrastructure (i.e. getting the services to run and processing requests), I'd be tempted to say that trying to push that into the WCF behaviors might be adding more complexity than it's worth. It would probably be simpler to just use a custom configuration section of your own.</p> <p>Could you clarify how you expect to use this information at runtime? Maybe that way we can provide more explicit advice...</p>
25,930
<p>our partners sites leverages our iframes in their own websites. I was wondering if there is a way to track the analytics on the iframes. </p> <p>The problem is, if we also utilize these iframes on our own website, how do i avoid duplicate tracking where a visit is counted on our domain's analytics and also counted again in iframes? is there a way to get around it?</p>
<p>Adding the Google Analytics code to the iframe should work just fine. The easiest way to avoid duplicate tracking is probably to add a query parameter like ?partner=foo to the URLs that your partners use. You can check for your own site's value and not run the Google Analytics code at all, and also pass the partner ID to Google so that you can break down the reports by partner.</p> <p><strong>EDIT</strong><br> Use ?utm_source=foo as the partner parameter, and Google Analytics will pick it up without you doing anything. Filter out your own impressions with</p> <pre><code>if ( location.href.indexOf("utm_source=mysite") &lt; 0 ) { // Google Analytics code here } </code></pre> <p>or you can set up a filter on your Google Analytics profile to filter them out.</p>
<p>You can also add <code>utm_nooverride=1</code> to your iframe source tag. This will make sure that the page that called your iframe on the 3rd party site will not get credit for the referral, but rather the initial source (AdWords campaign, search query, etc.).</p> <p>Example:</p> <pre><code>&lt;iframe src="mypage.html?utm_nooverride=1" width="1" height="1"&gt;&lt;/iframe&gt; </code></pre>
25,865
<p><strong>Scenario:</strong></p> <p>The task I have at hand is to enable a single-signon solution between different organizations/websites. I start as an authenticated user on one organization's website, convert specific information into an Xml document, encrypt the document with triple des, and send that over as a post variable to the second organizations login page.</p> <p><strong>Question:</strong></p> <p>Once I have my xml data packaged, how do I programmatically perform a post to the second website and have the user's browser redirected to the second website as well.</p> <p>This should behave just like having a form like: </p> <p><em>action="http://www.www.com/posthere" method="post"</em></p> <p>... and having a hidden text field like: </p> <p><em>input type="hidden" value="my encrypted xml"</em></p> <p>This is being written in asp.net 2.0 webforms.</p> <p>--</p> <p><strong>Edit:</strong> Nic asks why the html form I describe above will not work. Answer: I have no control over either site; I am building the "middle man" that makes all of this happen. Site 1 is forwarding a user to the page that I am making, I have to build the XML, and then forward it to site 2. Site 1 does not want the user to know about my site, the redirect should be transparent. </p> <p>The process I have described above is what both parties (site A and site B) mandate.</p>
<p>Send back a document that contains the from with hidden input and include an onload handler that posts the form immediately to the other site. Using jquery's document.ready() solves the issue of whether the DOM is loaded before the post occurs, though there are other ways to do this without jquery. You might want to include some small message on the screen to the effect that the user will be redirected shortly and provide a link which also does the post </p> <pre><code>...headers left out... &lt;script type='text/javascript'&gt; $(document).ready( function() { $('form:first').submit(); }); &lt;/script&gt; &lt;body&gt; &lt;form action='othersiteurl' method='POST'&gt; &lt;input type='hidden' value='your-encrypted-xml" /&gt; &lt;/form&gt; &lt;/body&gt; </code></pre>
<p>You are thinking about this too process oriented, it would take you a month of sundays to try and work out all the bugs and moving parts with what you suggest.</p> <p>You are already doing a post to another server so you really don't need to do anything. The form you have is already perfect, and when the other server intercepts the request that is when it makes the decision to either allow to user in and continue in through the site, or redirect them back to their Referer (sic) in the header. When redirecting back to the Referer they may want to tack on a message that says what was wrong, such as ?error=no_auth</p>
28,924
<p>I have a Rails project which has a Postgres database for the actual application but which needs to pull a heck of a lot of data out of an Oracle database. </p> <p>database.yml looks like</p> <pre><code>development: adapter: postgresql database: blah blah ... oracle_db: adapter: oracle database: blah blah </code></pre> <p>My models which descend from data on the Oracle DB look something like </p> <pre><code>class LegacyDataClass &lt; ActiveRecord::Base establish_connection "oracle_db" set_primary_key :legacy_data_class_id has_one :other_legacy_class, :foreign key =&gt; :other_legacy_class_id_with_funny_column_name ... end </code></pre> <p>Now, by habit I often do a lot of my early development (and this is early development) by coding for a bit and then playing in the Rails console. For example, after defining all the associations for LegacyDataClass I'll start trying things like <code>a = LegacyDataClass.find(:first); puts a.some_association.name</code>. Unexpectedly, this dies with LegacyDataClass not being already loaded. </p> <p>I can then <code>require 'LegacyDataClass'</code> which fixes the problem until I either need to <code>reload!</code>, which won't actually reload it, or until I open a new instance of the console.</p> <p>Thus the questions:</p> <ul> <li><strong>Why</strong> does this happen? Clearly there is some Rails magic I am not understanding.</li> <li>What is the convenient Rails <strong>workaround</strong>?</li> </ul>
<p>I believe this might have to do with your model name, rather than your connection. The Rails convention is that model class names are CamelCase, while the files they reside in are lowercase+underscore.</p> <p>The "LegacyModel" class should therefore be in <code>models/legacy_model.rb</code>. Your statement about <code>"require 'LegacyDataClass'"</code> indicates that this is not the case, and therefore Rails doesn't know how to automagically load that model.</p>
<p>I wrote something for an app at work that handles connections to other databases' at runtime, it might be able to help.</p> <p><a href="http://github.com/cherring/connection_ninja" rel="nofollow noreferrer">http://github.com/cherring/connection_ninja</a></p>
19,451
<p>Before the print has actually started I have set up Auto Bed Leveling using a BLTouch sensor, during the period that this runs I find that material leaks out of the nozzle and curls back onto itself and by the time it finishes it is substantial enough to cause problems when the nozzle is primed drawing the line to the left of the print. The material that leaks out catches on the material extruded to prime the nozzle, before printing the model so when the first line of the model are extruded to very quickly pulls up off the bed and becomes a massive tangle of material.</p> <p>I try to catch it my self using various thin instruments to scrape it off the nozzle as it starts the priming but this isn't always successful and is far from ideal. I have also tried adding a retraction before the bed levelling starts suing the gcode commands added to the beginning of every print, at the moment however I find that a retraction large enough to stop the leaking material also means that material doesn't come out for the priming in time so the first lines of the print don't work.</p> <p>The gcode at the beginning of the print is as follows:</p> <pre><code>; Ender 3 Custom Start G-code M104 S{material_print_temperature_layer_0} ; Set Extruder temperature M140 S{material_bed_temperature_layer_0} ; Set Heat Bed temperature M190 S{material_bed_temperature_layer_0} ; Wait for Heat Bed temperature M109 S{material_print_temperature_layer_0} ; Wait for Extruder temperature G28 ; Home all axes G1 F1800 E-3 ; Retract filament 3 mm to prevent oozing G29 ; BLTOUCH Mesh Generation G92 E0 ; Reset Extruder G1 Z5.0 F3000 ; Move Z Axis up little to prevent scratching of Heat Bed G1 X0.1 Y20 Z0.3 F5000.0 ; Move to start position G1 X0.1 Y200.0 Z0.3 F1500.0 E15 ; Draw the first line G1 X0.4 Y200.0 Z0.3 F5000.0 ; Move to side a little G1 X0.4 Y20 Z0.3 F1500.0 E30 ; Draw the second line G92 E0 ; Reset Extruder G1 Z5.0 F3000 ; Move Z Axis up little to prevent scratching of Heat Bed </code></pre> <p>I am using an Ender 3 running Marlin 1.1.9 with BlTouch Auto Leveling, With slicing done by CURA 3.5.6</p> <p>Any suggestions you have that would help to stop this would be greatly appreciated.</p>
<p>The oozing is due to hot-end getting hot before the bed leveling procedure: if you move the hot-end warm up command <strong>after</strong> the <code>G29</code> line you avoid that oozing</p> <pre><code>; Ender 3 Custom Start G-code M104 S{material_print_temperature_layer_0} ; Set Extruder temperature M140 S{material_bed_temperature_layer_0} ; Set Heat Bed temperature G28 ; Home all axes G29 ; BLTOUCH Mesh Generation M190 S{material_bed_temperature_layer_0} ; Wait for Heat Bed temperature M109 S{material_print_temperature_layer_0} ; Wait for Extruder temperature G1 F1800 E-3 ; Retract filament 3 mm to prevent oozing G92 E0 ; Reset Extruder G1 Z5.0 F3000 ; Move Z Axis up little to prevent scratching of Heat Bed G1 X0.1 Y20 Z0.3 F5000.0 ; Move to start position G1 X0.1 Y200.0 Z0.3 F1500.0 E15 ; Draw the first line G1 X0.4 Y200.0 Z0.3 F5000.0 ; Move to side a little G1 X0.4 Y20 Z0.3 F1500.0 E30 ; Draw the second line G92 E0 ; Reset Extruder G1 Z5.0 F3000 ; Move Z Axis up little to prevent scratching of Heat Bed </code></pre> <p>The above code will activate the heating elements but starts homing and leveling procedure without waiting for the elements to get up to temperature. Only after the bed leveling is finished the printer will pause and wait for the heating elements reach the desired temperature.</p> <p>This will prevent oozing on a cold start, but you will still be affected if you start a print right after another print, when the hot-end is still close to melting temperature.</p> <p>If you prefer to avoid that condition you might want to also move the <code>M104</code> and <code>M140</code> commands after the <code>G29</code> bed leveling command.</p>
<p>The best solution would be to heat the bed, but not the nozzle at startup. If you level with a cold bed, your ABL mesh is going to be off, since the aluminum heated bed plate expands considerably once the heat is applied. </p> <p>You could also issue a retract command before leveling, and then add a counteracting filament feed command after ABL is complete. I have no idea how that code would look though. Just my 2 cents.</p>
1,141
<p>How do you programmatically eject(safely remove) an USB mass storage device in Windows (XP)?</p>
<p>In <a href="http://www.autoitscript.com/autoit3/" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wOUx6.jpg" alt="" /> autoit</a>, you have a <a href="http://www.autoitscript.com/forum/index.php?showtopic=48585" rel="nofollow noreferrer">script</a> which does just that.</p> <p>It basically comes from this <a href="http://support.microsoft.com/?scid=kb%3Ben-us%3B165721&amp;x=18&amp;y=13" rel="nofollow noreferrer">Microsoft article</a> and uses kernel32.dll DeviceIoControl function</p> <p>Of course, this question appears to be a duplicate of <a href="https://stackoverflow.com/questions/85649/safe-remove-usb-drive-using-win32-api">Safe remove USB-Drive using Win32 API?</a>, which gives other solutions</p>
<p>You could spawn a process and use a <a href="http://quick.mixnmojo.com/readmes/USBDiskEjector.html" rel="nofollow noreferrer">command line tool</a>. This would also work from other languages such as java where calling the Win32 api is harder.</p>
25,269
<p>I have a sql statement that consists of multiple SELECT statements. I want to limit the total number of rows coming back to let's say 1000 rows. I thought that using the SET ROWCOUNT 1000 directive would do this...but it does not. For example:</p> <pre><code>SET ROWCOUNT 1000 select orderId from TableA select name from TableB </code></pre> <p>My initial thought was that SET ROWCOUNT would apply to the <strong>entire</strong> batch, not the individual statements within it. The behavior I'm seeing is it will limit the first select to 1000 and then the second one to 1000 for a total of 2000 rows returned. Is there any way to have the 1000 limit applied to the batch as a whole?</p>
<p>Not in one statement. You're going to have to subtract @@ROWCOUNT from the total rows you want after each statement, and use a variable (say, "@RowsLeft") to store the remaining rows you want. You can then SELECT TOP @RowsLeft from each individual query...</p>
<p>The following worked for me:</p> <pre><code>CREATE PROCEDURE selectTopN ( @numberOfRecords int ) AS SELECT TOP (@numberOfRecords) * FROM Customers GO </code></pre>
47,413
<p>I use <a href="http://rsync.samba.org/" rel="nofollow noreferrer">rsync</a> to synchronize files to Windows clients in a server agnostic way. What methods are available to send the progress of rsync to the parent process for display in a gui progress bar?</p> <p>I imagine two or three choices exist. (1) Watch STDOUT (2) Watch rsync.exe log file, similar to unix <code>tail</code> (3) Watch rsync console output in memory.</p> <p>Which one is best/preferred?</p>
<p>For this type of tasks, I use my own <a href="http://www.autoitscript.com/autoit3/" rel="nofollow noreferrer">AutoIt</a> script (freeware, Windows only). The script redirects the standard output into a graphical window, displaying it with the ability to scroll back, etc (very useful in long processes like XCOPYs / PKZIPs to check if any error did happen).</p> <p>I use AutoIt because it's free, very easy to use, and can compile quickly into an .EXE. I think it's an excellent alternative to a complete programming language for this type of tasks. The downside is that it's for Windows only.</p> <pre><code>$sCmd = "DIR E:\*.AU3 /S" ; Test command $nAutoTimeout = 10 ; Time in seconds to close window after finish $nDeskPct = 60 ; % of desktop size (if percent) ; $nHeight = 480 ; height/width of the main window (if fixed) ; $nWidth = 480 $sTitRun = "Executing process. Wait...." ; $sTitDone = "Process done" ; $sSound = @WindowsDir &amp; "\Media\Ding.wav" ; End Sound $sButRun = "Cancel" ; Caption of "Exec" button $sButDone = "Close" ; Caption of "Close" button #include &lt;GUIConstants.au3&gt; #include &lt;Constants.au3&gt; #Include &lt;GuiList.au3&gt; Opt("GUIOnEventMode", 1) if $nDeskPct &gt; 0 Then $nHeight = @DesktopHeight * ($nDeskPct / 100) $nWidth = @DesktopWidth * ($nDeskPct / 100) EndIf If $CmdLine[0] &gt; 0 Then $sCmd = "" For $nCmd = 1 To $CmdLine[0] $sCmd = $sCmd &amp; " " &amp; $CmdLine[$nCmd] Next ; MsgBox (1,"",$sCmd) EndIf ; AutoItSetOption("GUIDataSeparatorChar", Chr(13)+Chr(10)) $nForm = GUICreate($sTitRun, $nWidth, $nHeight) GUISetOnEvent($GUI_EVENT_CLOSE, "CloseForm") $nList = GUICtrlCreateList ("", 10, 10, $nWidth - 20, $nHeight - 50, $WS_BORDER + $WS_VSCROLL) GUICtrlSetFont (-1, 9, 0, 0, "Courier New") $nClose = GUICtrlCreateButton ($sButRun, $nWidth - 100, $nHeight - 40, 80, 30) GUICtrlSetOnEvent (-1, "CloseForm") GUISetState(@SW_SHOW) ;, $nForm) $nPID = Run(@ComSpec &amp; " /C " &amp; $sCmd, ".", @SW_HIDE, $STDOUT_CHILD) ; $nPID = Run(@ComSpec &amp; " /C _RunErrl.bat " &amp; $sCmd, ".", @SW_HIDE, $STDOUT_CHILD) ; # Con ésto devuelve el errorlevel en _ERRL.TMP While 1 $sLine = StdoutRead($nPID) If @error Then ExitLoop If StringLen ($sLine) &gt; 0 then $sLine = StringReplace ($sLine, Chr(13), "|") $sLine = StringReplace ($sLine, Chr(10), "") if StringLeft($sLine, 1)="|" Then $sLine = " " &amp; $sLine endif GUICtrlSetData ($nList, $sLine) _GUICtrlListSelectIndex ($nList, _GUICtrlListCount ($nList) - 1) EndIf Wend $sLine = " ||" GUICtrlSetData ($nList, $sLine) _GUICtrlListSelectIndex ($nList, _GUICtrlListCount ($nList) - 1) GUICtrlSetData ($nClose, $sButDone) WinSetTitle ($sTitRun, "", $sTitDone) If $sSound &lt;&gt; "" Then SoundPlay ($sSound) EndIf $rInfo = DllStructCreate("uint;dword") ; # LASTINPUTINFO DllStructSetData($rInfo, 1, DllStructGetSize($rInfo)); DllCall("user32.dll", "int", "GetLastInputInfo", "ptr", DllStructGetPtr($rInfo)) $nLastInput = DllStructGetData($rInfo, 2) $nTime = TimerInit() While 1 If $nAutoTimeout &gt; 0 Then DllCall("user32.dll", "int", "GetLastInputInfo", "ptr", DllStructGetPtr($rInfo)) If DllStructGetData($rInfo, 2) &lt;&gt; $nLastInput Then ; Tocó una tecla $nAutoTimeout = 0 EndIf EndIf If $nAutoTimeout &gt; 0 And TimerDiff ($nTime) &gt; $nAutoTimeOut * 1000 Then ExitLoop EndIf Sleep (100) Wend Func CloseForm() Exit EndFunc </code></pre>
<p>Check out <a href="http://www.download.com/DeltaCopy/3000-2242_4-10471616.html" rel="nofollow noreferrer">DeltaCopy</a>. It is a Windows GUI for rsync.</p>
2,955
<p>Is there a good way to find out which exceptions a procedure/function can raise in Delphi (including it's called procedures/functions)? </p> <p>In Java you always have to declare which exceptions that can be thrown, but this is not the case in Delphi, which could lead to unhandled exceptions. </p> <p>Are there any code analysis tools that detects unhandled exceptions?</p>
<p>(Edit: It is now obvious that the question referred <em>only</em> to design-time checking.)</p> <p>New answer:</p> <p>I cannot state whether there are any tools to check this for you. Pascal Analyzer, for one, does not.</p> <p>I <em>can</em> tell you, however, that in most Delphi applications, even if there was a tool to check this for you, you would get no results.</p> <p><em>Why?</em> Because the main message loop in TApplication.Run() wraps all HandleMessage() calls in an exception handling block, which catches all exception types. Thus you will have implicit/default exception handling around 99.999% of code in most applications. And in most applications, this exception handling will be around 100% of your own code - the 0.001% of code which is not wrapped in exception handling will be the automatically generated code.</p> <p>If there was a tool available to check this for you, you would need to rewrite Application.run() such that it does not include exception handling.</p> <p>(Previous answer: <em>The Application.OnException event handler can be assigned to catch all exceptions that aren't handled by other exception handlers. Whilst this is run-time, and thus perhaps not exactly what you are after (it sounds like you want to identify them at design time), it does allow you to trap any exception not handled elsewhere. In conjunction with tools such as the JCLDebug stuff in the <a href="http://sourceforge.net/projects/jcl/" rel="noreferrer">Jedi Code Library</a>, you could log a stack trace to find out where &amp; why an exception occurred, which would allow for further investigation and adding specific exception handling or prevention around the guilty code...</em>)</p>
<p>Finalization sections of units can raise exceptions too. These will slip by I think... and are also somewhat problematic.</p> <p>I think Delphi IDE has a build-in &quot;stack trace&quot; or &quot;stack tree&quot; something like.</p> <p>This question reminds me of Skybuck's TRussianRoulette game... google it, it's code and answer may help.</p>
9,817
<p>During my work with databases I noticed that I write query strings and in this strings I have to put several restrictions in the where-clause from a list/array/collection. Should look like this:</p> <pre><code>select * from customer where customer.id in (34, 26, ..., 2); </code></pre> <p>You can simplify this by reducing this to the question that you have collection of strings and want to create a comma-separated list of this strings in just one string.</p> <p>My approach I have used so far is something like that:</p> <pre><code>String result = ""; boolean first = true; for(String string : collectionOfStrings) { if(first) { result+=string; first=false; } else { result+=","+string; } } </code></pre> <p>But this is as you can see very ugly. You cannot see what happens there on the first look, especially when the constructed strings (like every SQL query) is getting complicated.</p> <p>What is your (more) elegant way?</p>
<p>Note: This answers was good when it was written 11 years ago, but now there are far better options to do this more cleanly in a single line, both using only Java built-in classes or using a utility library. See other answers below.</p> <hr> <p>Since strings are immutable, you may want to use the StringBuilder class if you're going to alter the String in the code.</p> <p>The StringBuilder class can be seen as a mutable String object which allocates more memory when its content is altered.</p> <p>The original suggestion in the question can be written even more clearly and efficiently, by taking care of the <em>redundant trailing comma</em>:</p> <pre><code> StringBuilder result = new StringBuilder(); for(String string : collectionOfStrings) { result.append(string); result.append(","); } return result.length() &gt; 0 ? result.substring(0, result.length() - 1): ""; </code></pre>
<p>You may be able to use LINQ (to SQL), and you may be able to make use of the Dynamic Query LINQ sample from MS. <a href="http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx" rel="nofollow noreferrer">http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx</a></p>
25,183
<p>I am writing a Firefox extension. I would like to search the current webpage for a set of words, and count how many times each occurs. This activity is only performed when the user asks, but it must still happen reasonably quickly.</p> <p>I am currently using indexOf on the BODY tag's innerHTML element, but am finding it too slow to run repeatedly in the following manner:</p> <pre><code>function wordcount(doc, match) { var count = 0; var pos = 0; for(;;) { len=doc.indexOf(match, pos); if(len == -1) { break; } pos = len + match.length; count++; } return count; } var html = content.document.body.innerHTML.toLowerCase() for(var i=0; i&lt;keywords.length; i++) { var kw = keywords[i]; myDump(kw + ": " + wordcount(html, kw)); } </code></pre> <p>With 100 keywords, this takes approximately 10 to 20 seconds to run. There is some scope to reduce the number of keywords, but it will still need to run much quicker.</p> <p>Is there a more obvious way to do this? What is the most efficient method? I have some ideas, but am reluctant to code each up without some idea of the performance I can expect:</p> <ul> <li>Navigate the DOM rather than using innerHTML. Will this be likely quicker or slower? It would have the benefit of only searching textual content.</li> <li>Loop through the document word by word, accumulating a count of each word's occurence simultaneously. With this method I would have to do a bit more work parsing the HTML.</li> </ul> <p><em>Edit: Turns out that the slowest part was the myDump function writing to the error console. Duh! Nevertheless, there some interesting more efficient alternatives have been presented, which I am intending to use.</em></p>
<p>I'm not sure if it is the fastest but the following worked pretty quickly for me.</p> <pre><code>var words = document.body.innerHTML.replace(/&lt;.*?&gt;/g,'').split(/\s+/); var i = words.length; var keywordCounts = {'keyword': 0, 'javascript': 0, 'today': 0}; var keywords = []; var keywordMatcher = ''; var word; for (word in keywordCounts) { keywords[keywords.length] = word ; keywordMatcher = keywordMatcher + '(' + word + ')?'; } var regex = new RegExp(keywordMatcher); var j = keywords.length; var matched, keyword; if (i &amp;&amp; j) { do { i = i - 1; matched = words[i].match(regex); if (!matched) continue; j = keywords.length; do { j = j - 1; if (matched[j + 1]) { keyword = keywords[j]; keywordCounts[keyword] = keywordCounts[keyword] + 1; } } while (j); } while (i); } </code></pre> <p>I'll definitely grant that from a Big(O) perspective it isn't the best because as i and j get big it still requires n squared time but I've found regular expression processing to generally be pretty fast.</p> <p>Basically I'm taking tvanfosson's idea and expanding on it, but rather than traversing the DOM I'm removing the tags with a regex (the first line) and then splitting the page into individual words. The keyword 'hash' is defined on the third line with initial counts (they should all start at zero obviously). From there I a new regular expression is constructed using each keyword as a group so when matched it returns an array of results that has (in my example) [fullMatch,keywordMatch,javascriptMatch,todayMatch]. I'm using decrementing do while loops because they've been shown in lots of places to be the fastest looping structure in JavaScript and since it doesn't matter in what order the words get processed loop speed is really the only consideration.</p> <p>I hope this is helpful, if not it was at least a fun exercise. :)</p>
<p>node.nodeType should work as well and maybe a little faster since it is integer. A value of 3 is for text nodes.</p>
45,316
<p>Given the Python function:</p> <pre><code>def a_method(arg1, arg2): pass </code></pre> <p>How can I extract the number and names of the arguments. I.e., given that I have a reference to <code>func</code>, I want the <code>func.[something]</code> to return <code>("arg1", "arg2")</code>.</p> <p>The usage scenario for this is that I have a decorator, and I wish to use the method arguments in the same order that they appear for the actual function as a key. I.e., how would the decorator look that printed <code>"a,b"</code> when I call <code>a_method("a", "b")</code>?</p>
<p>Take a look at the <a href="http://docs.python.org/library/inspect.html" rel="noreferrer"><code>inspect</code></a> module - this will do the inspection of the various code object properties for you.</p> <pre><code>&gt;&gt;&gt; inspect.getfullargspec(a_method) (['arg1', 'arg2'], None, None, None) </code></pre> <p>The other results are the name of the *args and **kwargs variables, and the defaults provided. ie.</p> <pre><code>&gt;&gt;&gt; def foo(a, b, c=4, *arglist, **keywords): pass &gt;&gt;&gt; inspect.getfullargspec(foo) (['a', 'b', 'c'], 'arglist', 'keywords', (4,)) </code></pre> <p>Note that some callables may not be introspectable in certain implementations of Python. For Example, in CPython, some built-in functions defined in C provide no metadata about their arguments. As a result, you will get a <code>ValueError</code> if you use <code>inspect.getfullargspec()</code> on a built-in function.</p> <p>Since Python 3.3, you can use <a href="https://docs.python.org/library/inspect.html#introspecting-callables-with-the-signature-object" rel="noreferrer"><code>inspect.signature()</code></a> to see the call signature of a callable object:</p> <pre><code>&gt;&gt;&gt; inspect.signature(foo) &lt;Signature (a, b, c=4, *arglist, **keywords)&gt; </code></pre>
<p>What about <code>dir()</code> and <code>vars()</code> now?</p> <p>Seems doing exactly what is being asked super simply…</p> <p><strong>Must be called from within the function scope.</strong></p> <p>But be wary that it will return <em>all</em> local variables so be sure to do it at the very beginning of the function if needed.</p> <p>Also note that, as pointed out in the comments, this doesn't allow it to be done from outside the scope. So not exactly OP's scenario but still matches the question title. Hence my answer.</p>
26,899
<p>Does anyone know of where to find unit testing guidelines and recommendations? I'd like to have something which addresses the following types of topics (for example):</p> <ul> <li>Should tests be in the same project as application logic?</li> <li>Should I have test classes to mirror my logic classes or should I have only as many test classes as I feel I need to have?</li> <li>How should I name my test classes, methods, and projects (if they go in different projects)</li> <li>Should private, protected, and internal methods be tested, or just those that are publicly accessible?</li> <li>Should unit and integration tests be separated?</li> <li>Is there a <strong>good</strong> reason not to have 100% test coverage?</li> </ul> <p>What am I not asking about that I should be?</p> <p>An online resource would be best.</p>
<p>I would recommend <a href="https://rads.stackoverflow.com/amzn/click/com/0321146530" rel="noreferrer" rel="nofollow noreferrer">Kent Beck's</a> book on TDD.</p> <p>Also, you need to go to <a href="http://martinfowler.com/articles/mocksArentStubs.html" rel="noreferrer">Martin Fowler's</a> site. He has a lot of good information about testing as well.</p> <p>We are pretty big on TDD so I will answer the questions in that light.</p> <blockquote> <p>Should tests be in the same project as application logic?</p> </blockquote> <p>Typically we keep our tests in the same solution, but we break tests into seperate DLL's/Projects that mirror the DLL's/Projects they are testing, but maintain namespaces with the tests being in a sub namespace. Example: Common / Common.Tests</p> <blockquote> <p>Should I have test classes to mirror my logic classes or should I have only as many test classes as I feel I need to have?</p> </blockquote> <p>Yes, your tests should be created before any classes are created, and by definition you should only test a single unit in isolation. Therefore you should have a test class for each class in your solution.</p> <blockquote> <p>How should I name my test classes, methods, and projects (if they go in different projects)</p> </blockquote> <p>I like to emphasize that behavior is what is being tested so I typically name test classes after the SUT. For example if I had a User class I would name the test class like so:</p> <pre><code>public class UserBehavior </code></pre> <p>Methods should be named to describe the behavior that you expect.</p> <pre><code>public void ShouldBeAbleToSetUserFirstName() </code></pre> <p>Projects can be named however you want but usually you want it to be fairly obvious which project it is testing. See previous answer about project organization.</p> <blockquote> <p>Should private, protected, and internal methods be tested, or just those that are publicly accessible?</p> </blockquote> <p>Again you want tests to assert expected behavior as if you were a 3rd party consumer of the objects being tested. If you test internal implementation details then your tests will be brittle. You want your test to give you the freedom to refactor without worrying about breaking existing functionality. If your test know about implementation details then you will have to change your tests if those details change.</p> <blockquote> <p>Should unit and integration tests be separated?</p> </blockquote> <p>Yes, unit tests need to be isolated from acceptance and integration tests. Separation of concerns applies to tests as well.</p> <blockquote> <p>Is there a good reason not to have 100% test coverage?</p> </blockquote> <p>I wouldn't get to hung up on the 100% code coverage thing. 100% code coverage tends to imply some level of quality in the tests, but that is a myth. You can have terrible tests and still get 100% coverage. I would instead rely on a good Test First mentality. If you always write a test before you write a line of code then you will ensure 100% coverage so it becomes a moot point.</p> <p>In general if you focus on describing the full behavioral scope of the class then you will have nothing to worry about. If you make code coverage a metric then lazy programmers will simply do just enough to meet that mark and you will still have crappy tests. Instead rely heavily on peer reviews where the tests are reviewed as well.</p>
<p>I insistently recommend you to read <a href="https://rads.stackoverflow.com/amzn/click/com/0321146530" rel="nofollow noreferrer" rel="nofollow noreferrer">Test Driven Development: By Example</a> and <a href="https://rads.stackoverflow.com/amzn/click/com/0131016490" rel="nofollow noreferrer" rel="nofollow noreferrer">Test-Driven Development: A Practical Guide</a> It's too much questions for single topic</p>
13,238
<p>Should I use a dedicated network channel between the database and the application server?</p> <p>...or... </p> <p>Connecting both in the switch along with all other computer nodes makes no diference at all?</p> <p>The matter is <strong>performance!</strong></p>
<p>Declare it like this:</p> <pre><code>&lt;bean id="doubleValue" class="java.lang.Double"&gt; &lt;constructor-arg index="0" value="3.7"/&gt; &lt;/bean&gt; </code></pre> <p>And use like this:</p> <pre><code>&lt;bean id="someOtherBean" ...&gt; &lt;property name="value" ref="doubleValue"/&gt; &lt;/bean&gt; </code></pre>
<p>Why don't you just use a <strong>Double</strong>? any reason?</p>
8,462
<p>I'm looking to add a tooltip to each row in a bound datagrid in vb.net winforms. How can this be done?</p>
<p>I haven't tried this myself but I would give it a shot:</p> <pre><code>System.Windows.Forms.ToolTip formToolTip = new System.Windows.Forms.ToolTip(); formToolTip .SetToolTip(item, "Row Tooltip"); </code></pre> <p>Where <code>item</code> corresponds to the cell you're setting the tool tip for.</p>
<pre><code>row.cells[indexof].ToolTipText= "tootip here". </code></pre> <p>In winforms, it doesn't look like you can do the whole row.</p> <p>if you NEED the whole row you can loop through the cells.</p> <pre><code> foreach (DataGridViewCell cell in row.Cells) { cell.ToolTipText = "tooltip here"; } </code></pre>
27,033
<p>I saw this quote on the question: <a href="https://stackoverflow.com/questions/105710">What is a good functional language on which to build a web service?</a></p> <blockquote> <p>Scala in particular doesn't support tail-call elimination except in self-recursive functions, which limits the kinds of composition you can do (this is a fundamental limitation of the JVM).</p> </blockquote> <p>Is this true? If so, what is it about the JVM that creates this fundamental limitation?</p>
<p>This post: <a href="https://stackoverflow.com/questions/72209/recursion-or-loop#72522">Recursion or Iteration?</a> might help.</p> <p>In short, tail call optimization is hard to do in the JVM because of the security model and the need to always have a stack trace available. These requirements could in theory be supported, but it would probably require a new bytecode (see <a href="https://blogs.oracle.com/jrose/entry/tail_calls_in_the_vm" rel="nofollow noreferrer">John Rose's informal proposal</a>).</p> <p>There is also more discussion in <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4726340" rel="nofollow noreferrer">Sun bug #4726340</a>, where the evaluation (from 2002) ends:</p> <blockquote> <p>I believe this could be done nonetheless, but it is not a small task.</p> </blockquote> <p>Currently, there is some work going on in the <a href="http://openjdk.java.net/projects/mlvm/subprojects.html" rel="nofollow noreferrer">Da Vinci Machine</a> project. The tail call subproject's status is listed as "proto 80%"; it is unlikely to make it into Java 7, but I think it has a very good chance at Java 8.</p>
<p>All sources point to the JVM being unable to optimize in the case of tail recursion, but upon reading <a href="http://books.google.ca/books?id=iPHtCfZQyqQC&amp;printsec=frontcover&amp;dq=java%20performance%20tuning&amp;hl=en&amp;ei=gGH2TOrfM4SKlwfT0ozVBQ&amp;sa=X&amp;oi=book_result&amp;ct=result&amp;resnum=1&amp;ved=0CDAQ6AEwAA#v=onepage&amp;q&amp;f=false" rel="nofollow">Java performance tuning</a> (2003, O'reilly) I found the author claiming he can achieve greater recursion performance by implementing tail recursion.</p> <p>You can find his claim on page 212 (search for 'tail recursion' it should be the second result). What gives?</p>
13,137
<p>I can't get the inner div (with Hello World) to fit inside the "box" div in this code example (also at <a href="http://www.toad-software.com/test.html" rel="nofollow noreferrer">http://www.toad-software.com/test.html</a>).</p> <p>Despite the body being set to 100%, the inner div will not be contained! This is a test case for a larger project in which a variable-width table exceeds the boundaries of its container. The table would be in the inner div and the container would the "box."</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;style type="text/css"&gt; /*html { width: 100%; height: 100%; position: relative; background: #c0c0c0; } body { position: absolute; width: 100%; height: 100%; background: #f9f9f9; }*/ body, html { margin: 0; padding: 0; } body { width: 100%; } div.box { padding: 10px; background: #ff33ff; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="box"&gt; &lt;div style="width: 1500px; height: 900px; background: #f12;"&gt;Hello World&lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>add <code>overflow:hidden;</code> to the container <code>&lt;div&gt;</code></p>
<p>add <code>overflow:hidden;</code> to the container <code>&lt;div&gt;</code></p>
32,456
<p>I've got a 1-based array of four items which I need to traverse. For a given index in the array, I need to work out the index of the next item, and the index of the previous item. This sounds simple but the array needs to wrap around. So when you are at the beginning of the array, the previous item is considered to be the last item. Likewise, if you are at the end of the array, the next item is considered to be the first item.</p> <p>I realise this can be solved by using conditional statements, but I wondered if it was possible to do it using mathematical equations. I've got one that works nicely for the next item</p> <pre><code>NextItem = Modulus(CurrentItem, 4) + 1 </code></pre> <p>(the modulus function returns the remainder of one number divided by another).</p> <p>Has anyone got any ideas as to how I can work out the previous item?</p>
<p>Since modulo always works better on 0-based ranges, you can turn it into one of these using <code>CurrentItem - 1</code>.</p> <p>Then, with modulo 4, adding 3 is the same as subtracting 1 but has the advantage of never going negative (some modulo operators may not like negatives).</p> <p>Then you once again add 1 to get back to a 1-based number.</p> <p>This gives:</p> <pre><code>PrevItem = Modulus(CurrentItem - 1 + 3, 4) + 1 </code></pre> <p>or, simplified:</p> <pre><code>PrevItem = Modulus(CurrentItem + 2, 4) + 1 </code></pre>
<p>It might depends on the properties of your Modulus against negative values, but in Lua the following works:</p> <pre><code>for i = 1, 8 do local idxF = i % 4 + 1 local idxB = (i - 2) % 4 + 1 print(i .. " " .. idxF .. " " .. idxB) end </code></pre> <p>Should be <code>PreviousItem = Modulus(CurrentItem - 2, 4) + 1</code> in your unspecified language.</p>
40,484
<p>I'm wondering if a Java library can be called from a VB.net application.</p> <p>(A Google search turns up lots of shady answers, but nothing definitive)</p>
<p>No, you can't. Unless you are willing to use some "J#" libraries (which is not nearly the same as Java) or <a href="http://www.ikvm.net/" rel="nofollow noreferrer">IKVM</a> which is a Java implementation that runs on top of .NET, but as their documentation says:</p> <blockquote> <p>IKVM.OpenJDK.ClassLibrary.dll: compiled version of the Java class libraries derived from the OpenJDK class library with some parts filled in with code from GNU Classpath and IcedTea, plus some additional IKVM.NET specific code. </p> </blockquote> <p>So it's not the real deal.</p>
<p>You could use JNI to instantiate a virtual machine and then use Java Classes. It will be some fun, though, because you would need to use C++ as a bridge between VB.Net and Java.</p> <p>This article in java world has a quick tutorial on how to use Java from C++ and viceversa.</p> <p><a href="http://www.javaworld.com/javaworld/javatips/jw-javatip17.html" rel="nofollow noreferrer">http://www.javaworld.com/javaworld/javatips/jw-javatip17.html</a></p>
18,454
<p>What are some important practices to follow when creating a .NET assembly that is going to be embedded to SQL Server 2005?</p> <p>I am brand new to this, and I've found that there are significant method attributes like:</p> <pre><code>[SqlFunction(FillRowMethodName = "FillRow", TableDefinition = "letter nchar(1)")] </code></pre> <p>I'm also looking for common pitfalls to avoid, etc.</p>
<p>Some that I remember:</p> <ul> <li>Keep its usage to a minimum, only use it when T-SQL proved too complex.</li> <li>Avoid pointers/cursors at all costs because a for loop is so easily abusable in CLR context.</li> <li>Only use the SQL-Server native data types unless totally necessary.</li> </ul> <p>Can't remember where I've found the information, but those are some that I do remember.</p> <p>Basically, only use it when declarative T-SQL is too complex or is impossible to do (such as registry editing etc.).</p>
<p>I would strongly advise against putting .net assemblies in your database server, think n-tier applications. Persistence &lt;- Business Logic &lt;-Presentation Logic &lt;- client Keep your Logic in your Business Logic layer. </p> <p>The only reason I can think of to put .net in your database would to add a new complex data type, I would strongly that this be a dumb class that only holds data and does no processing on it.</p> <p>Just because you can does not mean you should. Sorry for not directly answering your question.</p>
9,757
<p>In an information security lab I'm working on, I've been tasked with executing multiple commands with a single call to "system()" (written in C, running on Fedora). What is the syntax that will allow me to execute more than command through system()? (The idea being you could execute arbitrary commands through a program running on a remote computer, if the program interacts with the OS through the system() call.)</p> <p>I.e.:</p> <pre><code>char command[] = "????? \r\n"; system(command); </code></pre>
<p>That depends on the shell being invoked to execute the commands, but in general most shells use <code>;</code> to separate commands so something like this should work:</p> <pre><code>command1; command2; command3 </code></pre> <p>[EDIT]</p> <p>As @dicroce mentioned, you can use <code>&amp;&amp;</code> instead of <code>;</code> which will stop execution at the first command that returns a non-zero value. This may or may not be desired (and some commands may return non-zero on success) but if you are trying to handle commands that can fail you should probably not string multiple commands together in a system() call as you don't have any way of determining where the failure occured. In this case your best bet would either be to execute one command at a time or create a shell script that performs the appropriate error handling and call that instead.</p>
<p>One possibility comes immediately to mind. You could write all the commands to a script then run it with:</p> <pre><code>system ("cmd.exe /c \"x.cmd\""); </code></pre> <p>or, now that I've noticed you're running on Fedora:</p> <pre><code>system ("x.sh"); </code></pre>
30,467
<p>I would like to replicate this in python:</p> <pre><code>gvimdiff &lt;(hg cat file.txt) file.txt </code></pre> <p>(hg cat file.txt outputs the most recently committed version of file.txt)</p> <p>I know how to pipe the file to gvimdiff, but it won't accept another file:</p> <pre><code>$ hg cat file.txt | gvimdiff file.txt - Too many edit arguments: "-" </code></pre> <p>Getting to the python part...</p> <pre><code># hgdiff.py import subprocess import sys file = sys.argv[1] subprocess.call(["gvimdiff", "&lt;(hg cat %s)" % file, file]) </code></pre> <p>When subprocess is called it merely passes <code>&lt;(hg cat file)</code> onto <code>gvimdiff</code> as a filename.</p> <p>So, is there any way to redirect a command as bash does? For simplicity's sake just cat a file and redirect it to diff:</p> <pre><code>diff &lt;(cat file.txt) file.txt </code></pre>
<p>It can be done. As of Python 2.5, however, this mechanism is Linux-specific and not portable:</p> <pre><code>import subprocess import sys file = sys.argv[1] p1 = subprocess.Popen(['hg', 'cat', file], stdout=subprocess.PIPE) p2 = subprocess.Popen([ 'gvimdiff', '/proc/self/fd/%s' % p1.stdout.fileno(), file]) p2.wait() </code></pre> <p>That said, in the specific case of diff, you can simply take one of the files from stdin, and remove the need to use the bash-alike functionality in question:</p> <pre><code>file = sys.argv[1] p1 = subprocess.Popen(['hg', 'cat', file], stdout=subprocess.PIPE) p2 = subprocess.Popen(['diff', '-', file], stdin=p1.stdout) diff_text = p2.communicate()[0] </code></pre>
<p>It just dawned on me that you are probably looking for one of the popen functions.</p> <p>from: <a href="http://docs.python.org/lib/module-popen2.html" rel="nofollow noreferrer">http://docs.python.org/lib/module-popen2.html</a></p> <p>popen3(cmd[, bufsize[, mode]]) Executes cmd as a sub-process. Returns the file objects (child_stdout, child_stdin, child_stderr). </p> <p>namaste, Mark</p>
10,386
<p>I have an XML document which looks like this:</p> <pre><code>&lt;xconnect&gt; &lt;type&gt;OK&lt;/type&gt; &lt;response/&gt; &lt;report&gt; &lt;id&gt;suppressionlist_get&lt;/id&gt; &lt;name&gt;Suppression List Get&lt;/name&gt; &lt;timestamp&gt;24 Oct 08 @ 10:16AM&lt;/timestamp&gt; &lt;records type=\"user\"/&gt; &lt;records type=\"client\"/&gt; &lt;records type=\"group\"&gt; &lt;record&gt; &lt;email&gt;investorrelations@hfh.com&lt;/email&gt; &lt;type&gt;RECIPSELF&lt;/type&gt; &lt;long_type&gt;Recipient self suppressed&lt;/long_type&gt; &lt;created&gt;23 Oct 08 @ 8:53PM&lt;/created&gt; &lt;user&gt;facm&lt;/user&gt; &lt;/record&gt; </code></pre> <p>I have omitted the closing of the document for clarity and to keep this post short.</p> <p>Anyway, I have a GridView and I want to bind this XML to the GridView so I get table, like:</p> <pre><code>email | type | long | created | user ------------------------------------ data data data data data </code></pre> <p>And so forth.</p> <p>I was playing with DataSets and XMLDataDocuments and when stepping through, each attribute seemed to be represented as its own table in a data collection table.</p> <p>Any ideas on how to achieve the above? I thought it was as simple as just adding a GridView, and XML data source with the data file specified.</p> <p>Thanks</p>
<p>Try: </p> <pre><code>DataSet dataSet = new DataSet(); dataSet.ReadXML("Path to XML"); this.GridView1.DataMember = "record"; this.GridView1.DataSource = dataSet; this.GridView1.DataBind(); </code></pre>
<p>Create a test DataSet and write it out to Xml to get a feel for the Xml format used by a dataset, then either convert the Xml format to match this and then load it in to the Dataset using <code>DataSet.LoadXml()</code>. </p> <p>Or you could build a DataSet on the fly from your existing Xml format.</p>
28,830
<p>I was reading about refactoring a large slow SQL Query over <a href="https://stackoverflow.com/questions/320919/refactoring-extreme-sql-queries">here</a>, and the current highest response is from Mitch Wheat, who wants to make sure the query uses indexes for the major selects, and mentions:</p> <blockquote> <p>First thing I would do is check to make sure there is an active index maintenance job being run periodically. If not, get all existing indexs rebuilt or if not possible at least get statistics updated.</p> </blockquote> <p>I'm only am amateur DBA, and I've made a few programs freelance that are basically Java desktop clients and occasionally a MySQL backend. When I set up the system, I know to create an index on the columns that will be queried by, there's a varchar CaseID and a varchar CustName.</p> <p>However, I set this system up months ago and left the client operating it, and I believe the indexes should grow as data is entered and I believe everything is still working nicely. I'm worried though that the indexes should be rebuilt periodically, because today i have read that there should be an 'active maintenance job'. The only maintenance job I set on the thing was a nightly backup.</p> <p>I wanted to ask the community about regular maintenance that a database might require. Is it neccessary to rebuild indexes? Can I trust the MySQL backend to keep going so long as no one messes with it and the data stays under a few gigabytes?</p>
<p>There is no need to 'rebuild' an index. They are always kept up-to-date. Maybe he was referring to rebuilding the table. Depending on your usage patterns and schema, you can get fragmented pages in InnoDB, and I think in MyISAM also. Rebuilding the table can improve performance by getting rid of fragmentation of your data on disk. I don't use MyISAM tables regularly, but I believe it is recommended to run 'OPTIMIZE TABLE' with certain usage patterns. See the MySQL docs on <a href="http://dev.mysql.com/doc/refman/5.1/en/optimize-table.html" rel="noreferrer">OPTIMIZE TABLE</a> for some good info on both MyISAM and InnoDB.</p> <p>I'm not as familiar with MyISAM intricacies, but with InnoDB it is true that statistics can get out of date. The database keeps estimated statistics on how your data is distributed for a given index, and it's possible for those to get out-of-date, but MySQL/InnoDB has some built in functionality to try to keep statistics current. You usually don't have to worry about it.</p> <p>So if you are using InnoDB, the answer is no, you typically don't need to actively do anything to keep your indexes performing well. I'm not as sure with MyISAM, I think it's more common to need to optimize those tables regularly.</p>
<p>The answer you linked to about "regular maintenance" was in the specific context of a temporary table that gets truncated and repopulated regularly. You don't need to do this to the vast majority of MySQL database installs.</p>
41,607
<p>I am looking for a Windows based library which can be used for parsing a bunch of C files to list global and local variables. The global and local variables may be declared using typedef. The output (i.e. list of global and local variables) can then be used for post processing (e.g. replacing the variable names with a new name).</p> <p>Is such a library available?</p>
<p>Some of the methods available:</p> <ul> <li><a href="http://www.cs.berkeley.edu/~smcpeak/elkhound/sources/elsa/" rel="nofollow noreferrer">Elsa: The Elkhound-based C/C++ Parser</a></li> <li><a href="https://people.eecs.berkeley.edu/~necula/cil/" rel="nofollow noreferrer">CIL - Infrastructure for C Program Analysis and Transformation</a></li> <li><a href="http://kernel.org/pub/software/devel/sparse/" rel="nofollow noreferrer">Sparse - a Semantic Parser for C</a></li> <li><a href="http://clang.llvm.org/" rel="nofollow noreferrer">clang: a C language family frontend for LLVM</a></li> <li><a href="http://code.google.com/p/pycparser/" rel="nofollow noreferrer">pycparser: C parser and AST generator written in Python</a></li> </ul> <p>Alternately you could write your own using <a href="http://dinosaur.compilertools.net/" rel="nofollow noreferrer">lex and yacc</a> (or their kin- flex and bison) using a public <a href="http://www.lysator.liu.se/c/ANSI-C-grammar-l.html" rel="nofollow noreferrer">lex specification</a> and a <a href="http://www.lysator.liu.se/c/ANSI-C-grammar-y.html" rel="nofollow noreferrer">yacc grammar</a>.</p>
<p>If it is plain C, <code>lex</code> and <code>yacc</code> are your friends, but you need to take on account C preprocessor - source files with unexpanded macros typically are do not comply with C syntax so parser, written with K&amp;R grammar in mind, most likely will fail.</p> <p>If you decide to parse the output of preprocessor, be prepared that your parser will fail due to "extensions" of your particular compiler, because very likely standard library headers use them. At least this the the case with GCC.</p> <p>I had this with GCC and finally decided to achieve my goal using different approach. If you just need to change names for variables, regular expressions will do fine, and there is no need to build a full parser, IMHO. If your goal is just to collect data, the ultimate source of data is debug information. There are ways to get debug information out of binary - for ELF executables with DWARF there is libdwarf, for Windows-land (COFF ?) should be something as well. Probably you can use some existing tools to get debug information about binary - again, I know nothing about Windows, you need to investigate.</p>
37,883
<p>SVN in Eclipse is spread into two camps. The SVN people have developed a plugin called <a href="http://subclipse.tigris.org/" rel="noreferrer">Subclipse</a>. The Eclipse people have a plugin called <a href="http://www.eclipse.org/subversive/" rel="noreferrer">Subversive</a>. Broadly speaking they both do the same things. What are the advantages and disadvantages of each?</p>
<p>Both are very similar but Subversive is the "eclipse svn provider". I primarily use Subversive because of a few convenient features:</p> <p><strong>Grouping of history</strong></p> <p>When I'm browsing the history of a branch instead of just seeing a bunch of rows for every commit it can group commits by today, week, etc.</p> <p><strong>Mapping of trunk, branches, and tags</strong></p> <p>Subversive assumes the default svn layout: trunk, branches, tags (which you can change), so whenever you want to tag or branch it is one click and you provide the name of the tag or branch.</p> <p>Like I said these are minor differences that I just find convenient. Both work great with mylyn, but overall there really isn't a whole lot of differences with these two extensions.</p> <p>Merging with Subversive is a pain though (haven't tried Subclipse), I've never been able to successfully merge. The preview of the merge is great but it would never complete the merge or it will take way to long. Most of the time I complete merging through the command line without any issues.</p>
<p>If you are using Zend Studio 9, Zend's implementation of Eclipse, I recommend using Subclipse instead of Subversive which comes shipped with Zend Studio be default.</p> <p>I have posted a problem with Subversive and Zend Studio 9 and <a href="http://forums.zend.com/viewtopic.php?f=59&amp;t=42373&amp;p=98993#p98733" rel="nofollow noreferrer">my solution of using Subclipse instead on the Zend forums</a>.</p>
8,648
<p>We are working on designing an application that is typically OLTP (think: purchasing system). However, this one in particular has the need that some users will be offline, so they need to be able to download the DB to their machine, work on it, and then sync back once they're on the LAN.</p> <p>I would like to note that I know this has been done before, I just don't have experience with this particular model.</p> <p>One idea I thought about was using GUIDs as table keys. So for example, a Purchase Order would not have a number (auto-numeric) but a GUID instead, so that every offline client can generate those, and I don't have clashes when I connect back to the DB.</p> <p>Is this a bad idea for some reason? Will access to these tables through the GUID key be slow?</p> <p>Have you had experience with these type of systems? How have you solved this problem?</p> <p>Thanks!<br> Daniel</p>
<p>Using Guids as primary keys is acceptable and is considered a fairly standard practice for the same reasons that you are considering them. They can be overused which can make things a bit tedious to debug and manage, so try to keep them out of code tables and other reference data if at all possible.</p> <p>The thing that you have to concern yourself with is the human readable identifier. Guids cannot be exchanged by people - can you imagine trying to confirm your order number over the phone if it is a guid? So in an offline scenario you may still have to generate <strong>something</strong> - like a publisher (workstation/user) id and some sequence number, so the order number may be 123-5678 -. </p> <p>However this may not satisfy business requirements of having a sequential number. In fact regulatory requirements can be and influence - some regulations (SOX maybe) require that invoice numbers are sequential. In such cases it may be neccessary to generate a sort of proforma number which is fixed up later when the systems synchronise. You may land up with tables having OrderId (Guid), OrderNo (int), ProformaOrderNo (varchar) - some complexity may creep in.</p> <p>At least having guids as primary keys means that you don't have to do a whole lot of cascading updates when the sync does eventually happen - you simply update the human readable number.</p>
<p>Guids will certainly be slower (and use more memory) than standard integer keys, but whether or not that is an issue will depend on the type of load your system will see. Depending on your backend DB there may be issues with indexing guid fields.</p> <p>Using guids simplifies a whole class of problems, but you pay for it part will performance and also debuggability - typing guids into those test queries will get old real fast!</p>
6,144
<p>Sorry for the long question title.</p> <p>I guess I'm on to a loser on this one but on the off chance.</p> <p>Is it possible to make the calculation of a calculated field in a table the result of an aggregate function applied to a field in another table.</p> <p>i.e.</p> <p>You have a table called 'mug', this has a child called 'color' (which makes my UK head hurt but the vendor is from the US, what you going to do?) and this, in turn, has a child called 'size'. Each table has a field called sold.</p> <p>The size.sold increments by 1 for every mug of a particular colour and size sold.</p> <p>You want color.sold to be an aggregate of SUM size.sold WHERE size.colorid = color.colorid</p> <p>You want mug.sold to be an aggregate of SUM color.sold WHERE color.mugid = mug.mugid</p> <p>Is there anyway to make mug.sold and color.sold just work themselves out or am I going to have to go mucking about with triggers?</p>
<p>you can't have a computed column directly reference a different table, but you can have it reference a user defined function. here's a link to a example of implementing a solution like this.</p> <p><a href="http://www.sqlservercentral.com/articles/User-Defined+functions/complexcomputedcolumns/2397/" rel="noreferrer">http://www.sqlservercentral.com/articles/User-Defined+functions/complexcomputedcolumns/2397/</a></p>
<p>No, it is not possible to do this. A computed column can only be derived from the values of other fields on the same row. To calculate an aggregate off another table you need to create a view.</p> <p>If your application needs to show the statistics ask the following questions:</p> <ol> <li>Is it really necessary to show this in real time? If so, why? If it is really necesary to do this, then you would have to use triggers to update a table. <a href="http://en.wikipedia.org/wiki/Denormalization" rel="nofollow noreferrer">This</a> links to a short wikipedia article on denormalisation. Triggers will affect write performance on table updates and relies on the triggers being active.</li> <li>If it is only necessary for reporting purposes, you could do the calculation in a view or a report.</li> <li>If it is necessary to support frequent ad-hoc reports you may be into the realms of a data mart and overnight ETL process.</li> </ol>
20,114
<p>Is there a way to have a default parameter passed to a action in the case where the regex didnt match anything using django?</p> <pre><code> urlpatterns = patterns('',(r'^test/(?P&lt;name&gt;.*)?$','myview.displayName')) #myview.py def displayName(request,name): # write name to response or something </code></pre> <p>I have tried setting the third parameter in the urlpatterns to a dictionary containing ' and giving the name parameter a default value on the method, none of which worked. the name parameter always seems to be None. I really dont want to code a check for None if i could set a default value.</p> <p>Clarification: here is an example of what i was changing it to.</p> <pre><code> def displayName(request,name='Steve'): return HttpResponse(name) #i also tried urlpatterns = patterns('', (r'^test/(?P&lt;name&gt;.*)?$', 'myview.displayName', dict(name='Test') ) ) </code></pre> <p>when i point my browser at the view it displays the text 'None'</p> <p>Any ideas?</p>
<p>The problem is that when the pattern is matched against 'test/' the groupdict captured by the regex contains the mapping 'name' => None:</p> <pre><code>&gt;&gt;&gt; url.match("test/").groupdict() {'name': None} </code></pre> <p>This means that when the view is invoked, using something I expect that is similar to below:</p> <pre><code>view(request, *groups, **groupdict) </code></pre> <p>which is equivalent to:</p> <pre><code>view(request, name = None) </code></pre> <p>for 'test/', meaning that name is assigned None rather than not assigned.</p> <p>This leaves you with two options. You can:</p> <ol> <li>Explicitly check for None in the view code which is kind of hackish.</li> <li>Rewrite the url dispatch rule to make the name capture non-optional and introduce a second rule to capture when no name is provided. </li> </ol> <p>For example:</p> <pre><code>urlpatterns = patterns('', (r'^test/(?P&lt;name&gt;.+)$','myview.displayName'), # note the '+' instead of the '*' (r'^test/$','myview.displayName'), ) </code></pre> <p>When taking the second approach, you can simply call the method without the capture pattern, and let python handle the default parameter or you can call a different view which delegates.</p>
<p>I <em>thought</em> you could <code>def displayName(request, name=defaultObj)</code>; that's what I've done in the past, at least. What were you setting the default value to?</p>
29,048
<p>I thought people would be working on little code projects together, but I don't see them, so here's an easy one:</p> <p>Code that validates a valid US Zip Code. I know there are ZIP code databases out there, but there are still uses, like web pages, quick validation, and also the fact that zip codes keep getting issued, so you might want to use weak validation.</p> <p>I wrote a little bit about zip codes in a side project on my wiki/blog:</p> <p><a href="https://benc.fogbugz.com/default.asp?W24" rel="nofollow noreferrer">https://benc.fogbugz.com/default.asp?W24</a></p> <p>There is also a new, weird type of zip code. </p> <p><a href="https://benc.fogbugz.com/default.asp?W42" rel="nofollow noreferrer">https://benc.fogbugz.com/default.asp?W42</a></p> <p>I can do the javascript code, but it would be interesting to see how many languages we can get here.</p>
<p><strong>Javascript Regex Literal</strong>:</p> <p>US Zip Codes: <code>/(^\d{5}$)|(^\d{5}-\d{4}$)/</code></p> <pre><code>var isValidZip = /(^\d{5}$)|(^\d{5}-\d{4}$)/.test("90210"); </code></pre> <p>Some countries use <a href="http://en.wikipedia.org/wiki/Postal_code" rel="noreferrer">Postal Codes</a>, which would fail this pattern.</p>
<p>Are you referring to address validation? Like the previous answer by Mike, you need to cater for the othe 95%.</p> <p>What you can do is when the user select's their country, then enable validation. Address validation and zipcode validation are 2 different things. Validating the ZIP is just making sure its integer. Address validation is validating the actual address for accuracy, preferably for mailing.</p>
19,410
<p>Greetings, currently I am refactoring one of my programs, and I found an interesting problem.</p> <p>I have Transitions in an automata. Transitions always have a start-state and an end-state. Some Transitions have a label, which encodes a certain Action that must be performed upon traversal. No label means no action. Some transitions have a condition, which must be fulfilled in order to traverse this condition, if there is no condition, the transition is basically an epsilon-transition in an NFA and will be traversed without consuming an input symbol.</p> <p>I need the following operations: </p> <ul> <li>check if the transition has a label</li> <li>get this label</li> <li>add a label to a transition</li> <li>check if the transition has a condition </li> <li>get this condition</li> <li>check for equality</li> </ul> <p>Judging from the first five points, this sounds like a clear decorator, with a base transition and two decorators: Labeled and Condition. However, this approach has a problem: two transitions are considered equal if their start-state and end-state are the same, the labels at both transitions are equal (or not-existing) and both conditions are the same (or not existing). With a decorator, I might have two transitions Labeled("foo", Conditional("bar", Transition("baz", "qux"))) and Conditional("bar", Labeled("foo", Transition("baz", "qux"))) which need a non-local equality, that is, the decorators would need to collect all the data and the Transition must compare this collected data on a set-base:</p> <pre><code>class Transition(object): def __init__(self, start, end): self.start = start self.end = end def get_label(self): return None def has_label(self): return False def collect_decorations(self, decorations): return decorations def internal_equality(self, my_decorations, other): try: return (self.start == other.start and self.end == other.end and my_decorations = other.collect_decorations()) def __eq__(self, other): return self.internal_equality(self.collect_decorations({}), other) class Labeled(object): def __init__(self, label, base): self.base = base self.label = label def has_label(self): return True def get_label(self): return self.label def collect_decorations(self, decorations): assert 'label' not in decorations decorations['label'] = self.label return self.base.collect_decorations(decorations) def __getattr__(self, attribute): return self.base.__getattr(attribute) </code></pre> <p>Is this a clean approach? Am I missing something?</p> <p>I am mostly confused, because I can solve this - with longer class names - using cooperative multiple inheritance:</p> <pre><code>class Transition(object): def __init__(self, **kwargs): # init is pythons MI-madness ;-) super(Transition, self).__init__(**kwargs) self.start = kwargs['start'] self.end = kwargs['end'] def get_label(self): return None def get_condition(self): return None def __eq__(self, other): try: return self.start == other.start and self.end == other.end except AttributeError: return False class LabeledTransition(Transition): def __init__(self, **kwargs): super(LabeledTransition).__init__(**kwargs) self.label = kwargs['label'] def get_label(self): return self.label def __eq__(self): super_result = super(LabeledTransition, self).__eq__(other) try: return super_result and self.label == other.label except AttributeError: return False class ConditionalTransition(Transition): def __init__(self, **kwargs): super(ConditionalTransition, self).__init__(**kwargs) self.condition = kwargs['condition'] def get_condition(self): return self.condition def __eq__(self, other): super_result = super(ConditionalTransition, self).__eq__(other) try: return super_result and self.condition = other.condition except AttributeError: return False # ConditionalTransition about the same, with get_condition class LabeledConditionalTransition(LabeledTransition, ConditionalTransition): pass </code></pre> <p>the class LabledConditionalTransition behaves exactly as expected - and having no code in there is appealing and I do not thing MI is confusing at this size.</p> <p>Of course, the third option would be to just hammer everything into a single transition class with a bunch of in has_label/has_transition.</p> <p>So... I am confused. Am I missing something? Which implementation looks better? How do you handle similar cases, that is, objects which look like a Decorator could handle them, but then, such a non-local method comes around?</p> <p><em>EDIT</em>: Added the ConditionalTransition-class. Basically, this kinda behaves like the decorator, minus the order created by the order of creating the decorators, the transition checks for start and end being correct, the LabeledTransition-class checks for label being correct and ConditionalTransition checks for condition being correct.</p>
<p>I think its clear that nobody really understands your question. I would suggest putting it in context and making it shorter. As an example, here's one possible implementation of the state pattern in python, please study it to get an idea.</p> <pre><code>class State(object): def __init__(self, name): self.name = name def __repr__(self): return self.name class Automaton(object): def __init__(self, instance, start): self._state = start self.transitions = instance.transitions() def get_state(self): return self._state def set_state(self, target): transition = self.transitions.get((self.state, target)) if transition: action, condition = transition if condition: if condition(): if action: action() self._state = target else: self._state = target else: self._state = target state = property(get_state, set_state) class Door(object): open = State('open') closed = State('closed') def __init__(self, blocked=False): self.blocked = blocked def close(self): print 'closing door' def do_open(self): print 'opening door' def not_blocked(self): return not self.blocked def transitions(self): return { (self.open, self.closed):(self.close, self.not_blocked), (self.closed, self.open):(self.do_open, self.not_blocked), } if __name__ == '__main__': door = Door() automaton = Automaton(door, door.open) print 'door is', automaton.state automaton.state = door.closed print 'door is', automaton.state automaton.state = door.open print 'door is', automaton.state door.blocked = True automaton.state = door.closed print 'door is', automaton.state </code></pre> <p>the output of this programm would be:</p> <pre><code>door is open closing door door is closed opening door door is open door is open </code></pre>
<p>From the code that was posted, the only difference between Transition and Labeled Transition is the return of get_lable() and has_label(). In which case you can compress these two a single class that sets a label attribute to None and </p> <pre><code>return self.label is not None </code></pre> <p>in the has_label() function.</p> <p>Can you post the code for the <code>ConditionalTransition</code> class? I think this would make it clearer.</p>
15,548
<p>I need your advice regarding migration. I want to migrate existing project to ASP.NET MVC and I can figure out the proccess except of url rewriting issue:</p> <p>for example how can I make following route: </p> <p><a href="http://www.eireads.com/ireland/mayo/cars-3/1263-used-cars-citroen-c5-for-sale.aspx" rel="nofollow noreferrer">http://www.eireads.com/ireland/mayo/cars-3/1263-used-cars-citroen-c5-for-sale.aspx</a></p> <p>Or maybe I could somehow keep supporting legacy routes. </p>
<p>I think that migrating a web forms applicaiton to MVC is going to be very hard unless you have a clear seperation of concerns in your current applicaiton. If you have followed a design pattern like MVP then it might be easier, but if not then much of your business logic is likey going to have to be moved to controller classes and much of it re-written.</p> <p>I would start by extracting your model, this should be fairly easy, then identifying your controllers and actions and seeing how much code you can re-use. At this point you should be able to discern whether or not you can migrate or if you'll be better off re-writing portions of your applicaiton.</p> <p>Default URL patterns in ASP.NET MVC are http(s)://(appdomain)/(controller)/(action)/(par/ame/ters)</p> <p>So your url above should fit into that pattern. You can change the pattern to account for other things (like namespace for example). Your URL pattern might be:</p> <p><a href="http://www.eireads.com/cars/used/ireland/mayo/citreon" rel="nofollow noreferrer">http://www.eireads.com/cars/used/ireland/mayo/citreon</a></p> <p>where ireland, mayo and citreon are the in put parameters.</p>
<p>I think you should really re-write your question and try to detail exactly what you are attempting to accomplish here.</p> <p>If you are asking how to migrate an existing <strong>WebForm</strong> project into ASP.NET MVC keeping the same URL rewrite, the answer is; not easily. The models are too different.</p> <p>Yet, you mention "routes" in the end, which make me think you are speaking like those of the System.Web.Routing namespace. So are you dealing with an existing MVC app and want it too look like that URL path? I can't tell. I am confused.</p>
16,243