instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>Is there an easy way write to a file asynchronously in Python?</p> <p>I know the <a href="https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files" rel="noreferrer">file io that comes with Python</a> is blocking; which is fine in most cases. For this particular case, I need writes not to block the application at all, or at least as minimally as possible.</p>
<p>Twisted has <a href="http://twistedmatrix.com/documents/8.1.0/api/twisted.internet.fdesc.html" rel="noreferrer">non-blocking writes on file descriptors</a>. If you're writing async code, I'd expect you to be using twisted, anyway. :)</p>
<p>Python 3 seems to have such functionality. See <a href="http://www.python.org/dev/peps/pep-3116/" rel="nofollow">PEP 3116</a>.</p>
41,256
<p>I hear logarithms mentioned quite a lot in the programming context. They seem to be the solution to many problems and yet I can't seem to find a real-world way of making use of them. I've read the <a href="http://en.wikipedia.org/wiki/Logarithms" rel="noreferrer">Wikipedia entry</a> and that, quite frankly, leaves me none the wiser.</p> <p><strong>So, where can I learn about the real-world programming problems that logarithms solve?</strong> Has anyone got any examples of problems they faced that were solved by implementing a logarithm?</p>
<p>Say you've got $1000, and it's in a savings account with 2.4% interest.</p> <p>How many years do you have to wait until you have $2000 to buy a new laptop?</p> <p>1000 &times; 1.024<sup>x</sup> = 2000</p> <p>1.024<sup>x</sup> = 2</p> <p>x = log <sub>1.024</sub> 2 = 29.23 years</p>
<p><strong>Demystifying the Natural Logarithm (ln)</strong> at BetterExplained is the best i have found. It clears the concepts from the base and help you understand the underlying concepts. After that everything seems a cakewalk.</p>
14,820
<p>I'm wondering if there's a way to do what I can do below with Python, in Ruby:</p> <pre><code>sum = reduce(lambda x, y: x + y, map(lambda x, y: x * y, weights, data)) </code></pre> <p>I have two arrays of equal sizes with the weights and data but I can't seem to find a function similar to map in Ruby, reduce I have working.</p>
<p>@Michiel de Mare</p> <p>Your Ruby 1.9 example can be shortened a bit further:</p> <pre><code>weights.zip(data).map(:*).reduce(:+) </code></pre> <p>Also note that in Ruby 1.8, if you require ActiveSupport (from Rails) you can use:</p> <pre><code>weights.zip(data).map(&amp;:*).reduce(&amp;:+) </code></pre>
<p>An alternative for the map that works for more than 2 arrays as well:</p> <pre><code>def dot(*arrays) arrays.transpose.map {|vals| yield vals} end dot(weights,data) {|a,b| a*b} # OR, if you have a third array dot(weights,data,offsets) {|a,b,c| (a*b)+c} </code></pre> <p>This could also be added to Array:</p> <pre><code>class Array def dot self.transpose.map{|vals| yield vals} end end [weights,data].dot {|a,b| a*b} #OR [weights,data,offsets].dot {|a,b,c| (a*b)+c} </code></pre>
2,546
<p>I've encountered the following problem pattern frequently over the years:</p> <ul> <li><p>I'm writing complex code for a package comprised of a standalone application and also a library version of the core that people can use from inside other apps.</p></li> <li><p>Both our own app and presumably ones that users create with the core library are likely to be run both in batch mode (off-line, scripted, remote, and/or from command line), as well as interactively.</p></li> <li><p>The library/app takes complex and large runtime input and there may be a variety of error-like outputs including severe error messages, input syntax warnings, status messages, and run statistics. Note that these are all <em>incidental</em> outputs, not the primary purpose of the application which would be displayed or saved elsewhere and using different methods.</p></li> <li><p>Some of these (probably only the very severe ones) might require a dialog box if run interactively; but it needs to log without stalling for user input if run in batch mode; and if run as a library the client program obviously wants to intercept and/or examine the errors as they occur.</p></li> <li><p>It all needs to be cross-platform: Linux, Windows, OSX. And we want the solution to not be weird on any platform. For example, output to stderr is fine for Linux, but won't work on Windows when linked to a GUI app.</p></li> <li><p>Client programs of the library may create multiple instances of the main class, and it would be nice if the client app could distinguish a separate error stream with each instance.</p></li> <li><p>Let's assume everybody agrees it's good enough for the library methods to log errors via a simple call (error code and/or severity, then printf-like arguments giving an error message). The contentious part is how this is recorded or retrieved by the client app.</p></li> </ul> <p>I've done this many times over the years, and am never fully satisfied with the solution. Furthermore, it's the kind of subproblem that's actually not very important to users (they want to see the error log if something goes wrong, but they don't really care about our technique for implementing it), but the topic gets the programmers fired up and they invariably waste inordinate time on this detail and are never quite happy.</p> <p>Anybody have any wisdom for how to integrate this functionality into a C++ API, or is there an accepted paradigm or a good open source solution (not GPL, please, I'd like a solution I can use in commercial closed apps as well as OSS projects)?</p>
<p>"isn't that [text manipulation] more of something that should be programmed into the application?"</p> <p>Usually, yes. The generally accepted "<a href="http://en.wikipedia.org/wiki/Multitier_architecture" rel="nofollow noreferrer">three-tier</a>" application design for databases says that your logic should be in the middle tier, between the client and the database. However, sometimes you need some logic in a trigger or need to index on a function, requiring that some code be placed into the database. In that case all the usual "which language should I use?" questions come up.</p> <p>If you only need a little logic, the most-portable language should probably be used (pl/pgSQL). If you need to do some serious programming though, you might be better off using a more expressive language (maybe pl/ruby). This will always be a judgment call.</p> <p>"is there any valid reason to use an untrusted language?"</p> <p>As above, yes. Again, putting direct file access (for example) into your middle tier is best when possible, but if you need to fire things off based on triggers (that might need access to data not available directly to your middle tier), then you need untrusted languages. It's not ideal, and should generally be avoided. And you definitely need to guard access to it.</p>
<p>I think most additional languages are offered so that if you develop in that language on a regular basis, you can feel comfortable writing db functions, triggers, etc. The usefulness of these features is to provide a control over data as close to the data as possible.</p>
6,060
<p>What are best practices with regards to C and C++ coding standards? Should developers be allowed to willy-nilly mix them together. Are there any complications when linking C and C++ object files.</p> <p>Should things like socket libraries that traditionally is written in C remain in C and kept in seperate source files? That is keeping c code in .c files and c++ code in .cpp files. When mixing c and C++ after being parsed with g++ will there be any performance penalties, since typesafe checks are not done in C? but are in C++. Would would be the best way to link C and C++ source code files.</p>
<p>The biggest issue is calling a C function from C++ code or vice versa. In that case, you want to make sure you mark the function as having "C" linkage using <code>extern "C"</code>. You can do this in the header file directly using:</p> <pre><code>#if defined( __cplusplus ) extern "C" { #endif extern int myfunc( const char *param, int another_one ); #if defined( __cplusplus ) } #endif </code></pre> <p>You need the <code>#if</code>s because C code that includes it won't understand <code>extern "C"</code>.</p> <p>If you don't want to (or can't) change the header file, you can do it in the C++ code:</p> <pre><code>extern "C" { #include "myfuncheader.h" } </code></pre> <p>You can mark a C++ function as having C linkage the same way, and then you can call it from C code. You can't do this for overloaded functions or C++ classes.</p> <p>Other than that, there should be no problem mixing C and C++. We have a number of decades-old C functions that are still being used by our C++ code.</p>
<p>If you compile all your source with g++ then it is all compiled in C++ object files (i.e. with the appropriate name mangling and the C++ ABI).</p> <p>You will only need to use the extern "C" trick if you are building libraries that need to be used by explicitly C applications that need to use the C ABI.</p> <p>If everything is being compiled into a single executable then use g++ and treat everything as C++</p>
35,976
<p>Years ago I created a programming collaboratory in Diversity University MOO -- a room written in MOOcode that used TCP/IP to communicate with a perl server back at my campus to compile and execute C, Perl, Bash and other programs and return results to the MOO collaboratory -- all for demonstrating programming languages in a MOO teaching environment. The application is usually a romp in five or six languages and fun to play with. Now I'd like to do the same thing in SecondLife using LSL. The only suggestion I've gotten so far from that crowd is to use a WWW request, presumeably constructing an http POST message to a CGI process. I never cared much for html forms so I'd rather use TCP/IP or some other communications protocol. Has anyone tried this who'd care to provide a few hints? There are several good LSL demo sites in SecondLife but I'd like to demo other compiler and script languages, maybe even PowerShell. Dick S.</p>
<p><a href="http://en.wikipedia.org/wiki/Representational_State_Transfer" rel="noreferrer">REST</a> is now in fashion for web services. There is no real reason to get down to TCP/IP layer for something which from your description does not require super performance or response times. LSL HTTP support is quite good so you should not have any problems.</p> <p>Of course it is not ideal to get the output of your programs back in real-time - for that you would need to open http connection on the server and constantly write to the body of the page (while the client would read that). But even with going back and forth between the server and the client you should get moderately good experience.</p>
<p>As Ilya said, REST and LSL-HTTP would be the way to go.</p> <p>The <strong>new implementation of JSON</strong> within the Linden Scripting Language should help with that. You might want to start with reading the <a href="http://wiki.secondlife.com/wiki/Json_usage_in_LSL" rel="nofollow">Json usage in LSL</a> page on the official wiki.</p>
12,901
<p>Is it possible in plain JPA or JPA+Hibernate extensions to declare a composite key, where an element of the composite key is a sequence?</p> <p>This is my composite class:</p> <pre><code>@Embeddable public class IntegrationEJBPk implements Serializable { //... @ManyToOne(cascade = {}, fetch = FetchType.EAGER) @JoinColumn(name = "APPLICATION") public ApplicationEJB getApplication() { return application; } @Column(name = "ENTITY", unique = false, nullable = false, insertable = true, updatable = true) public String getEntity() { return entity; } @GeneratedValue(strategy = GenerationType.AUTO, generator = "INTEGRATION_ID_GEN") @SequenceGenerator(name = "INTEGRATION_ID_GEN", sequenceName = "OMP_INTEGRATION_CANONICAL_SEQ") @Column(name = "CANONICAL_ID", unique = false, nullable = false, insertable = true, updatable = true) public String getCanonicalId() { return canonicalId; } @Column(name = "NATIVE_ID", unique = false, nullable = false, insertable = true, updatable = true) public String getNativeId() { return nativeId; } @Column(name = "NATIVE_KEY", unique = false, nullable = false, insertable = true, updatable = true) public String getNativeKey() { return nativeKey; } //... } </code></pre> <p>I already supply the values for <code>application</code>, <code>entity</code>, <code>nativeId</code> and <code>nativeKey</code>. I want to construct an entity like the one below:</p> <pre><code>IntegrationEJB i1 = new IntegrationEJB(); i1.setIntegrationId(new IntegrationEJBPk()); i1.getIntegrationId().setApplication(app1); i1.getIntegrationId().setEntity("Entity"); i1.getIntegrationId().setNativeId("Nid"); i1.getIntegrationId().setNativeKey("NK"); </code></pre> <p>And when I call <code>em.persist(i1</code>), I want that the <code>canonicalId</code> is generated and the integration is inserted.</p> <p>Is this possible? If so, what's the simple way? (I prefer not to use application-provided keys or native sql).</p>
<p>I believe that this is not possible with plain JPA.</p>
<p>Try like this:</p> <pre><code>@TableGenerator(name = "canonicalKeys", allocationSize = 1, initialValue = 1) @GeneratedValue(strategy = GenerationType.TABLE, generator = "canonicalKeys") @Column(name = "CANONICAL_ID", unique = false, nullable = false, insertable = true, updatable = true) public String getCanonicalId() { return canonicalId; } </code></pre> <p>In this way instead of using a sequence you can use a table.</p>
30,084
<p>We're working on an application that displays information through a Direct3D visualisation. A late client request is the ability to view this application via some Remote Desktop solution.</p> <p>Has anyone done anything similar? What options are available / unavailable? I'm thinking RDC, VNC, Citrix...</p> <p>Any advice?</p>
<p>I think you can still use all of the normal D3D tools, but you won't be able to render to a surface associated with the screen. You'll have to render to a DIB (or some such) and Blt it with GDI to a normal window HDC. RDC/VNC/Citrix should all work with this technique.</p> <p>Performance will definitely suffer - but that's going to be the case over remote desktop anyway. In fact, if I were you, I would mock up a VERY simple prototype and demonstrate the performance before committing to it. </p> <p>Good luck!</p>
<p>The build-in remote desktop works. (You don't have to do anything special)</p> <p>But it is extremely slow, because when in doubt, it just sends the contents of a window as a bitmap.</p>
5,720
<p>I have noticed that some apps like Safari and Mail show a loading indicator in the status bar (the bar at the very top of the phone) when they are accessing the network. Is there a way to do the same thing in SDK apps, or is this an Apple only thing?</p>
<p>It's in UIApplication:</p> <p><strong>For Objective C:</strong></p> <p>Start:</p> <pre><code>[UIApplication sharedApplication].networkActivityIndicatorVisible = YES; </code></pre> <p>End:</p> <pre><code>[UIApplication sharedApplication].networkActivityIndicatorVisible = NO; </code></pre> <p><strong>For swift :</strong></p> <p>Start</p> <pre><code>UIApplication.shared.isNetworkActivityIndicatorVisible = true </code></pre> <p>End</p> <pre><code>UIApplication.shared.isNetworkActivityIndicatorVisible = false </code></pre>
<p>It might also be helpful to make sure you are running it on the main thread as it is UI related. </p> <pre><code>dispatch_async(dispatch_get_main_queue(), ^{ [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; }); </code></pre>
20,135
<p>I have a Monoprice Maker Select Plus (Wanhao Duplicator i3 clone) and I'm having issued with the top layer of my prints. The bottom surface and the sides always come out perfect but my top layer is left with gaps in it. I have tried adjusting the print temperature, flow rate, print speed and layer height all with no success. I use Cura for my slicing software. If anyone knows how to help it'd be much appreciated</p> <p><a href="https://i.stack.imgur.com/MZFpf.jpg" rel="nofollow noreferrer" title="Closeup of failed print"><img src="https://i.stack.imgur.com/MZFpf.jpg" alt="Closeup of failed print" title="Closeup of failed print" /></a></p> <p><a href="https://i.stack.imgur.com/45rzs.jpg" rel="nofollow noreferrer" title="Failed print"><img src="https://i.stack.imgur.com/45rzs.jpg" alt="Failed print" title="Failed print" /></a></p>
<p>This is probably caused by too few top layers in combination with a too low infill percentage. Increase skin layers and increase infill percentage.</p> <p>If you have multiple layers already (at least about 4 for 0.2 mm layer height, for smaller layer heights even more), you might be printing at a too high temperature and or too few part cooling percentage and a too low infill percentage.</p>
<p>To combat the bad top layers, I usually use usually 5 top layers for any model of layer height 0.1 to 0.3 mm. I generally don't print with less than 9 % infill for PLA, which I have found sufficient to support even complex geometry on top.</p> <p>Also, I generally use a mixed setup of layers: the outermost layers I demand as concentric because this is the most beautiful setup, while the lower levels are Zig-Zag patterned, as this gives the best layer-to-wall connection.</p>
1,813
<p>How can I delete all the tables in a web page? The tables don't have any ids associated with them.</p>
<p>Very simple version:</p> <pre><code>var tables = document.getElementsByTagName("TABLE"); for (var i=tables.length-1; i&gt;=0;i-=1) if (tables[i]) tables[i].parentNode.removeChild(tables[i]); </code></pre>
<p>Or:</p> <pre><code>function myF() { this.checkChild = function(tagN, node) { if (node.tagName.toLower() == tagN.toLower()) { node.parentNode.removeChild(node); } else { var i; for(i = 0; i &lt; node.childNodes.length; i++) this.checkChild(tagN, node.childNodes[i]); } } } </code></pre> <p>Usage:</p> <pre><code> var m = new myF(); m.checkChild("The name of the tagname. This case: table", document.body); </code> </pre> <p>Good luck!</p>
37,266
<p>I have a huge database with 100's of tables and stored procedures. Using SQL Server 2005, how can I get a list of stored procedures that are doing an insert or update operation on a given table.</p>
<pre><code>select so.name, sc.text from sysobjects so inner join syscomments sc on so.id = sc.id where sc.text like '%INSERT INTO xyz%' or sc.text like '%UPDATE xyz%' </code></pre> <p>This will give you a list of all stored procedure contents with INSERT or UPDATE in them for a particular table (you can obviously tweak the query to suit). Also longer procedures will be broken across multiple rows in the returned recordset so you may need to do a bit of manual sifting through the results.</p> <p><strong>Edit</strong>: Tweaked query to return SP name as well. Also, note the above query will return any UDFs as well as SPs.</p>
<pre><code>SELECT Distinct SO.Name FROM sysobjects SO (NOLOCK) INNER JOIN syscomments SC (NOLOCK) on SO.Id = SC.ID AND SO.Type = 'P' AND (SC.Text LIKE '%UPDATE%' OR SC.Text LIKE '%INSERT%') ORDER BY SO.Name </code></pre> <p><a href="http://www.knowdotnet.com/articles/storedprocfinds.html" rel="nofollow noreferrer">This link</a> was used as a resource for the SP search.</p>
14,550
<p>I'm using GNU autotools for the build system on a particular project. I want to start writing automated tests for verifcation. I would like to just type "make check" to have it automatically run these. My project is in C++, although I am still curious about writing automated tests for other languages as well.</p> <p><em>Is this compatible with pretty much every unit testing framework out there (I was thinking of using cppunit)? How do I hook these unit testing frameworks into make check? Can I make sure that I don't require the unit test software to be installed to be able to configure and build the rest of the project?</em></p>
<p>To make test run when you issue <code>make check</code>, you need to add them to the <code>TESTS</code> variable</p> <p>Assuming you've already built the executable that runs the unit tests, you just add the name of the executable to the TESTS variable like this:</p> <pre><code>TESTS=my-test-executable </code></pre> <p>It should then be automatically run when you <code>make check</code>, and if the executable returns a non-zero value, it will report that as a test failure. If you have multiple unit test executables, just list them all in the <code>TESTS</code> variable:</p> <pre><code>TESTS=my-first-test my-second-test my-third-test </code></pre> <p>and they will all get run.</p>
<p>You can use Automake's <code>TESTS</code> to run programs generated with <code>check_PROGRAMS</code> but this will assume that you are using a log driver and a compiler for the output. It is probably easier to still use <code>check_PROGRAMS</code> but to invoke the test suite using a local rule in the Makefile:</p> <pre><code>check_PROGRAMS=testsuite testsuite_SOURCES=... testsuite_CFLAGS=... testsuite_LDADD=... check-local: ./testsuite </code></pre>
15,888
<p>I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don't really know how to call it properly. All the tutorials I've found are essentially "inline", i.e. they walk through using SQLite in a linear fashion rather than how to actually use it in production.</p> <p>What I'm trying to do is have a method check to see if the database is already created. If so, then I can use it. If not, an exception is raised and the program will create the database. (Or use if/else statements, whichever is better).</p> <p>I created a test script to see if my logic is correct but it's not working. When I create the try statement, it just creates a new database rather than checking if one already exists. The next time I run the script, I get an error that the table already exists, even if I tried catching the exception. (I haven't used try/except before but figured this is a good time to learn).</p> <p>Are there any good tutorials for using SQLite operationally or any suggestions on how to code this? I've looked through the pysqlite tutorial and others I found but they don't address this.</p>
<p>AFAIK an SQLITE database is just a file. To check if the database exists, check for file existence.</p> <p>When you open a SQLITE database it will automatically create one if the file that backs it up is not in place.</p> <p>If you try and open a file as a sqlite3 database that is NOT a database, you will get this:</p> <p>"sqlite3.DatabaseError: file is encrypted or is not a database"</p> <p>so check to see if the file exists and also make sure to try and catch the exception in case the file is not a sqlite3 database</p>
<p>Yes, I was nuking out the problem. All I needed to do was check for the file and catch the IOError if it didn't exist.</p> <p>Thanks for all the other answers. They may come in handy in the future.</p>
25,995
<p>We have an advanced webpage (ASP.NET, C#), and a application which needs to be installed on the client computer in order to utilize the webpage to its fullest. The application is a tray app, and has primarily two tasks. Detect when certain events happen on the webserver (for instance invited to a meeting, or notify of an upcoming meeting). The other task the trayapp has is to use a custom protocol (trayapp://) to perform some ajax calls back to the server.</p> <p>One problem we have is how to determine if the application is installed on the local machine or not. Now the user has to tick a checkbox to inform the website that the application is installed, and that it's safe to call the trayapp:// url calls.</p> <p>Is there any way, for instance through a JavaScript or similar to detect if our application is installed on the local machine?</p> <p>The check needs to work for IE, FF and Opera browsers.</p>
<p>If you want to detect with javascript inside the browser, you can probably use the collection "navigator.plugins". It works with Firefox, Opera and Chrome but unfortunately not with IE. </p> <p>Update: In FF, Opera and Chrome you can test it easily like this:</p> <pre><code>if (navigator.plugins["Adobe Acrobat"]) { // do some stuff if it is installed } else { // do some other stuff if its not installed } </code></pre> <p>Update #2: If it is an ActiveX object in IE you can test if it exists by using something like this:</p> <pre><code>function getActiveXObject(name){ try{ return new ActiveXObject(name); } catch(err){ return undefined; } }; </code></pre> <p>Another approach for IE is something similar to what JohnFx suggested (I found it <a href="http://bytes.com/forum/thread145239.html" rel="nofollow noreferrer">here</a> and have not tested it):</p> <pre><code>HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Curr entVersion\Internet Settings\User Agent\Post Platform </code></pre>
<p>Expose the trayapp (assuming this as a Managed app) as COM object. You could then use the tag with the GUID and trap errors when not found or use the ActiveXobject with the progid to detect if it's installed.</p>
37,207
<p>I am on Windows XP.</p> <p>I am using ImageMagick (MagickNet) to convert PDF's to TIF's. </p> <p>My problem is that when I load a PDF in the MagicNet.Image object, it doesn't throw an error, but when I look at the properties, it is obvious it didn't load the PDF (it doesn't contain any data).</p> <p>My guess is that ImageMagick isn't talking to Ghostscript.</p> <p>Any ideas?</p> <p>--I forgot to mention, I did install Ghost Script, and I added its bin folder to the PATH</p>
<p>One thing you could try (although I haven't tried it, so I can't say how effective this method would be) to <em>immediately</em> try to search the memory space of the browser for the text - maybe it was not deallocated, or even if it was deallocated, maybe it wasn't overwritten by other data.</p> <p>You can do this on Windows for example with with the <a href="http://mh-nexus.de/en/hxd/" rel="nofollow noreferrer">HXD Hex Editor</a>, which can open the address space of other processes and you can use to search for strings.</p> <p>A final note: you should also try to search for Unicode variants of the strings, since it is entirely possible that the browser keeps it internally as Unicode.</p>
<p>Whenever I type something really long, I always copy it to my clipboard before submitting the form in case something happens. Or, sometimes I type it in Notepad and copy it over when I'm done. That may not be the answer you're looking for, but it might help.</p>
15,635
<p>I have a control, VideoControl, which displays video using DirectShow - it's set as the owner of an IVideoWindow. I have another control, AreaControl, which is supposed to show a dashed rectangle over the video control. AreaControl is set to be transparent using SetStyle(ControlStyles.SupportsTransparentBackColor, true). If I place AreaControl over any other control, it works as expected, showing a dashed rectangle over the controls behind it. But when I place the dashed rectangle control over the video control, the AreaControl is filled in with the VideoControl's BackColor.</p> <p>What do I need to do to get the video to display through the AreaControl, with the dashed rectangle overlaid on it? Is there a way to get the VideoControl to paint itself with the video, rather than just drawing its BackColor?</p>
<p>As far as I know, there is no way of doing, what you want to do directly. The problem is, the implementation of the transparent style of a control. A control with this style attribute basically just draws, what is behind it making it appear transparent. (In reality it isn't really transparent at all). </p> <p>The only solution that comes to my mind is to use a window (Form) and put the control in that. A Form can be made transparent by setting its Opacity property to something less than 1.0. A value of 0.0 will be totally transparent (read: Invisible). The dashed border should be totally black. With a opacity of f.e. 0.4 it will appear gray. </p> <p>Alternatively, you may have some luck with TransparencyKey Property of the Form. Setting this to white may have the desired effect, but I haven't tested this one. </p> <p>In either case the Form should be completely borderless. You may have to add some code to reposition the form, when the video form moves. </p>
<p>As far as I know, there is no way of doing, what you want to do directly. The problem is, the implementation of the transparent style of a control. A control with this style attribute basically just draws, what is behind it making it appear transparent. (In reality it isn't really transparent at all). </p> <p>The only solution that comes to my mind is to use a window (Form) and put the control in that. A Form can be made transparent by setting its Opacity property to something less than 1.0. A value of 0.0 will be totally transparent (read: Invisible). The dashed border should be totally black. With a opacity of f.e. 0.4 it will appear gray. </p> <p>Alternatively, you may have some luck with TransparencyKey Property of the Form. Setting this to white may have the desired effect, but I haven't tested this one. </p> <p>In either case the Form should be completely borderless. You may have to add some code to reposition the form, when the video form moves. </p>
39,360
<p><strong>Update</strong></p> <p><em>Got it! See my solution (fifth comment)</em></p> <p>Here is my problem:</p> <p>I have created a small binary called "jail" and in /etc/password I have made it the default shell for a test user.</p> <p>Here is the -- simplified -- source code:</p> <pre><code>#define HOME "/home/user" #define SHELL "/bin/bash" ... if(chdir(HOME) || chroot(HOME)) return -1; ... char *shellargv[] = { SHELL, "-login", "-rcfile", "/bin/myscript", 0 }; execvp(SHELL, shellargv); </code></pre> <p>Well, no matter how hard I try, it seems that, when my test user logs in, <em>/bin/myscript</em> will never be sourced. Similarly, if I drop a <code>.bashrc</code> file in user's home directory, it will be ignored as well.</p> <p>Why would bash snob these guys?</p> <p>--</p> <p>Some precisions, not necessarily relevant, but to clear out some of the points made in the comments:</p> <ul> <li>The 'jail' binary is actually suid, thus allowing it to chroot() successfully. </li> <li>I have used 'ln' to make the appropriate binaries available - my jail cell is nicely padded :)</li> <li>The issue does not seem to be with chrooting the user...something else is remiss.</li> </ul>
<p>The shell isn't interactive. Try adding -i to the list of arguments.</p>
<p>By the time your user is logging in and their shell tries to source this file, it's running under their UID. The <code>chroot()</code> system call is only usable by root -- you'll need to be cleverer than this.</p> <p>Also, chrooting to a user's home directory will make their shell useless, as (unless they have a lot of stuff in there) they won't have access to any binaries. Useful things like <code>ls</code>, for instance.</p>
31,745
<p>I'm new to mock objects, but I understand that I need to have my classes implement interfaces in order to mock them.</p> <p>The problem I'm having is that in my data access layer, I want to have static methods, but I can't put a static method in an interface. </p> <p>What's the best way around this? Should I just use instance methods (which seems wrong) or is there another solution?</p>
<p>I would use a method object pattern. Have a static instance of this, and call it in the static method. It should be possible to subclass for testing, depending on your mocking framework.</p> <p>i.e. in your class with the static method have:</p> <pre class="lang-cs prettyprint-override"><code>private static final MethodObject methodObject = new MethodObject(); public static void doSomething(){ methodObject.doSomething(); } </code></pre> <p>and your method object can be a very simple, easily-tested:</p> <pre class="lang-cs prettyprint-override"><code>public class MethodObject { public void doSomething() { // do your thang } } </code></pre>
<p>A simple solution is to allow to change the static class's implementation via a setter:</p> <pre><code>class ClassWithStatics { private IClassWithStaticsImpl implementation = new DefaultClassWithStaticsImpl(); // Should only be invoked for testing purposes public static void overrideImplementation(IClassWithStaticsImpl implementation) { ClassWithStatics.implementation = implementation; } public static Foo someMethod() { return implementation.someMethod(); } } </code></pre> <p>So in the setup of your tests, you call <code>overrideImplementation</code> with some mocked interface. The benefit is that you don't need to change clients of your static class. The downside is that you probably will have a little duplicated code, because you'll have to repeat the methods of the static class and it's implementation. But some times the static methods can use a ligther interface which provide base funcionality.</p>
18,466
<p>Vista's Resource Monitor includes a reading for "Hard Faults/sec". Is there an equivalent performance counter I can use in C# to get this reading? I've tried the "Page Faults/sec" under the memory category, but that appears to be something different.</p>
<p>A hard fault is the same as a page fault.</p> <p>Source: "<a href="http://technet.microsoft.com/en-us/library/cc722173(WS.10,printer).aspx" rel="nofollow noreferrer">Windows Vista Performance and Reliability Monitoring Step-by-Step Guide</a>".</p> <p>See section <em>Resource View details</em>, Label Memory (the 4th table):</p> <blockquote> <p>A hard fault (also known as a page fault) occurs when the page of the referenced address is no longer in physical memory and has been swapped out or is available from a backing file on disk.</p> </blockquote>
<p>Page faults/sec measures both Hard Faults and Soft Faults. The counter named Transition Faults/sec measures Soft Faults. Thus, to get the Hard Faults you should subtract Transition Faults/sec from Page Faults/sec</p>
32,886
<p>Are all these types of sites just illegally scraping Google or another search engine?<br> As far as I can tell ther is no 'legal' way to get this data for a commercial site.. The Yahoo! api ( <a href="http://developer.yahoo.com/search/siteexplorer/V1/inlinkData.html" rel="nofollow noreferrer">http://developer.yahoo.com/search/siteexplorer/V1/inlinkData.html</a> ) is only for noncommercial use, Yahoo! Boss does not allow automated queries etc.<br> Any ideas?</p>
<p>For example, if you wanted to find all the links to Google's homepage, search for</p> <pre><code>link:http://www.google.com </code></pre> <p>So if you want to find all the inbound links, you can simply traverse your website's tree, and for each item it finds, build a URL. Then query Google for:</p> <pre><code>link:URL </code></pre> <p>And you'll get a collection of all the links that Google has from other websites into your website.</p> <p>As for the legality of such harvesting, I'm sure it's not-exactly-legal to make a profit from it, but that's never stopped anyone before, has it? </p> <p>(So I wouldn't bother wondering whether they did it or not. Just assume they do.)</p>
<p>For example, if you wanted to find all the links to Google's homepage, search for</p> <pre><code>link:http://www.google.com </code></pre> <p>So if you want to find all the inbound links, you can simply traverse your website's tree, and for each item it finds, build a URL. Then query Google for:</p> <pre><code>link:URL </code></pre> <p>And you'll get a collection of all the links that Google has from other websites into your website.</p> <p>As for the legality of such harvesting, I'm sure it's not-exactly-legal to make a profit from it, but that's never stopped anyone before, has it? </p> <p>(So I wouldn't bother wondering whether they did it or not. Just assume they do.)</p>
47,240
<p>I'm talking about this:</p> <p>If we have the letter 'A' which is 77 in decimal and 4D in Hex. I am looking for the fastest way to get D.</p> <p>I thought about two ways:</p> <p>Given x is a byte.</p> <ol> <li><p><code>x &lt;&lt; 4; x &gt;&gt; 4</code></p></li> <li><p><code>x %= 16</code></p></li> </ol> <p>Any other ways? Which one is faster?</p>
<p>I always use <code>x &amp;= 0x0f</code></p>
<p>x = x &amp; 15</p>
37,728
<p>When you're doing a usual gdb session on an executable file on the same computer, you can give the run command and it will start the program over again.</p> <p>When you're running gdb on an embedded system, as with the command <code>target localhost:3210</code>, how do you start the program over again without quitting and restarting your gdb session?</p>
<p>You are looking for <a href="http://sourceware.org/gdb/onlinedocs/gdb/Server.html" rel="noreferrer">Multi-Process Mode for gdbserver</a> and <a href="http://sourceware.org/gdb/onlinedocs/gdb/Remote-Configuration.html" rel="noreferrer"><code>set remote exec-file filename</code></a></p>
<p>On EFM32 Happy Gecko none of the suggestions would work for me, so here is what I have learned from the documentation on integrating GDB into the Eclipse environment.</p> <pre><code>(gdb) mon reset 0 (gdb) continue (gdb) continue </code></pre> <p>This puts me in the state that I would have expected when hitting reset from the IDE.</p>
10,088
<p>I have an old Borland project which I would like to port to <a href="http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2008" rel="nofollow noreferrer">Visual&nbsp;Studio&nbsp;2008</a>. Is there a way to dump, in a human-readable format, the source file, compile options and dependency information from a .ide file?</p> <p>I'd like something a bit more comprehensive than the 'Generate Makefile' option.</p>
<p>If this is a <a href="https://en.wikipedia.org/wiki/Visual_Component_Library" rel="nofollow noreferrer">VCL</a> application, options and settings are the least of your concerns, since the VCL API is completely different from <a href="http://en.wikipedia.org/wiki/Microsoft_Foundation_Class_Library" rel="nofollow noreferrer">MFC</a>. A lot of the Borland compiler options are actually to provide compatibility with MFC. Other than that there isn't actually much overlap in the compiler options.</p> <p>I occasionally provide Visual Studio 'solution' versions of my Borland projects to colleagues, and normally is simply a matter of selection the .cpp files in the solution and setting any global defines (these is console mode programs mind you, no GUI).</p> <p>The greater issue is minor inconsistencies in stream classes, values.h and deprecated functions that Microsoft has dropped. That is, _stricmp(), _chdir(), _mkdir() _getcwd() instead of stricmp() chdir() mkdir() getcwd(), etc...</p> <p>I have generally not found the various Borland generated makefiles very compatible with any other compiler (or even with the Borland compiler for that matter).</p>
<p>I don't know about Borland 5, 6 or latest compilers (latest version I've used is Borland C++ 3.1 back in 1994/95 ...), but if you have the chance to generate a Makefile maybe the best solution is to use that Borland makefile to write a NMAKE compatible makefile by hand, if it's not too large. </p> <p>Another option is to manually import the header, source files and edit the project (compatibilize source and compilation settings) until the build is successful. I think this can be achieved in a short time. </p> <p>To what dependencies is your project tied to? VCL? MFC? Just standard libs?</p>
49,887
<p>How to enforce that developers writing XAML in Visual Studio should follow certain standards and validations need to be run and if invalid compile time errors are thrown.</p> <p>For example, making sure that all the databinding expressions (some are real long) are written correctly as per 'a custom validation' I would like implement, during design time. Like, </p> <pre><code>&lt;TextBox Text="{Binding Source={StaticResource CALCULATED}, Converter={StaticResource XPathConverter}, ConverterParameter=@FIRSTNAME_STRING, XPath=@FIRSTNAME}"/&gt; </code></pre> <p>In the above sample if the <strong>binding expression in the Text property is not in that format</strong>, there should be a <strong>compilation error</strong>.</p> <p>Is there a way to do this?</p>
<p>There is no built-in way to do this. The best way you will be able to get this result is to run a custom tool on the input. This will require a lot of leg work on your part because it will involve parsing the file yourself but you should be able to get this scenario working.</p> <p>Example site for creating a custom generator</p> <p><a href="http://www.drewnoakes.com/snippets/WritingACustomCodeGeneratorToolForVisualStudio/" rel="nofollow noreferrer">http://www.drewnoakes.com/snippets/WritingACustomCodeGeneratorToolForVisualStudio/</a></p>
<p>Sorry, the XAML language service can’t be extended this way either. The best way to do this today is to author a build task. I think you can hook it into the MarkupCompilePass1DependsOn target and it will be invoked automatically when the user saves or changes a XAML file. You still have to scan the file redundantly from us, but you don’t have to wait for an actual build to make this work. This is a direct quote from one of the Microsoft architects who currently is working on the WPF designers.</p>
43,541
<p>I'm having a problem where the relative dimensional error of cylinders is rapidly increasing as the absolute size decreases. Printing a calibration stack of cylinders of diameters 8, 7, 6, 5, 4, and 3 mm, they come out undersized by 5%, 5.3%, 7%, 8%, 10%, and 13%, respectively, as measured by a digital caliper. Cubes exhibit a less severe version of the same pattern: 2.5%, 3%, 5%, 4%, 5%, 7%. The cylinders are generated with OpenSCAD using <code>$fn=180</code>, i.e. they're actually extrusions of 180-gons, so the error should not be caused by poor chord approximation; indeed, measuring projections of the model, or reading the gcode and accounting for nozzle width, everything looks right.</p> <p>Printer is Ender 3, using PLA at 210. Slicing with CuraEngine.</p> <p>Could this be caused by underextrusion or print speed issues - or some effect where the material pulls itself together under tight curvature? What techniques might be able to compensate for it, short of fudging the model?</p> <p>Some additional information: As noted by Trish in the comments, the consistency of the absolute error, which is 0.4 for cylinders and 0.2 for cubes, is likely important. I've also subsequently tested with 110% extrusion rate and the errors for the cylinders dropped to consistently 0.2 mm (still a significant increasing relative error), but the skin layers at the top of the 3 mm cylinder bulged, suggesting the increased extrusion is wrong - an excessive total volume of material.</p>
<p>You should not look at the relative dimensional differences, you should be looking at the absolute differences. Multiplying the undersized dimensions in percentage with the cylinder diameter gives you a value of 0.4 &nbsp;mm for each cylinder give or take a few hundreds. So, basically your printer works very consistent it is just suffering from a systematic offset.</p> <p>Basically, the printing process needs to adjust the X-Y dimensions to compensate for plastic flow effects. An option or setting in Ultimaker Cura to counteract this is called <code>Horizontal Expansion</code>. Slic3r and Simplify3d have similar settings. In Slic3r it is called <code>XY size compensation</code>. </p>
<p>This problem seems to have mostly gone away - at least any remaining error is within a margin explainable by my cheap/low-quality digital caliper. Since asking the question, I've made a lot of changes that could contribute, but the biggest factor was probably the loose X-axis timing belt and <a href="https://3dprinting.stackexchange.com/a/10137/11157">misaligned X-axis</a>.</p> <p>Slicer options may also have been involved. For example, Cura's Ender 3 profile attempts to set limits on acceleration speeds, but does so in a way that requires the GUI to compute derived accelerations; if you're using the command line CuraEngine (which I am), all the derived settings are left at the very high defaults.</p>
1,266
<p>I'm encountering a strange memory read/write error while calling a compiled DLL from C#. I use DllImport to get a handle to the function we need, which writes a return value to a parametric pointer to an int (i.e., int* out). This function is called multiple times within a thread, and runs successfully over the execution life of the first thread. However, if one launches another thread after the first has completed, the call to the external dll throws an AccessViolationException. Since the multiple calls from the first thread execute successfully, I'm thinking this is somehow related to the first thread not releasing the pointers to the relevant integer parameters(?). If so, how can I explicitly release that memory? Or, perhaps someone has a different insight into what might be going on here? Thank you very much.</p> <p>EDIT: Danny has requested more specifics, and I'm happy to oblige. Here is where the external routine is invoked:</p> <pre><code> int success = -1; unsafe { int res = 0; int* res_ptr = &amp;res; int len = cmd.ToCharArray().Length; int* len_ptr = &amp;len; CmdInterpreter(ref cmd, len_ptr, res_ptr); success = *res_ptr; } </code></pre> <p>Where CmdInterpreter is defined as:</p> <pre><code> [DllImport("brugs.dll", EntryPoint="CmdInterpreter", ExactSpelling=false, CallingConvention = CallingConvention.StdCall)] public static unsafe extern void CmdInterpreter(ref string cmd, int *len, int *res); </code></pre> <p>Please let me know if there is any additional info that would be helpful. Thank you!</p>
<p>Given that the problem only occurs when multiple threads are involved, it may be that the command interpreter DLL is using some sort of thread-local storage and doing it incorrectly. It could also have to do with the COM initialization state of the second thread (the one that generates the error).</p> <p>It would be interesting to know what happens if you launch your new thread and have it call into the DLL <em>before</em> making any calls into the DLL on your first/main thread. If it works, that might support the thread-local storage theory. If it fails, that would support the COM state theory.</p>
<p>It may be the [DllImport]. If you post the [DllImport] signature, and the DLL's ptototype, maybe we can spot a problem.</p> <p>I read that the Managed, Native, and COM Interop Team released the PInvoke Interop Assistant on CodePlex. <a href="http://www.codeplex.com/clrinterop/Release/ProjectReleases.aspx?ReleaseId=14120" rel="nofollow noreferrer">http://www.codeplex.com/clrinterop/Release/ProjectReleases.aspx?ReleaseId=14120</a></p>
26,075
<p>I am currently trying to make a <code>navigation-menu</code> where an <code>active-class</code> is applied to the anchors whose <code>href</code> attributes that match the current URL, so I can style that anchor in a way that makes it stand out from the rest of the menu.</p> <p>This is my mark-up:</p> <pre><code>&lt;div id="sidebar"&gt; &lt;h2&gt;Navigation menu&lt;/h2&gt; &lt;h2 class="subnav"&gt;&lt;a href="menu1/menu_item1"&gt;Menu item 1&lt;/a&gt;&lt;/h2&gt; &lt;h2 class="subnav"&gt;&lt;a href="menu1/menu_item2"&gt;Menu item 2&lt;/a&gt;&lt;/h2&gt; &lt;h2 class="subnav"&gt;&lt;a href="menu1/menu_item3"&gt;Menu item 3&lt;/a&gt;&lt;/h2&gt; &lt;h2 class="subnav"&gt;&lt;a href="menu1/menu_item4"&gt;Menu item 4&lt;/a&gt;&lt;/h2&gt; &lt;h2 class="subnav"&gt;&lt;a href="menu1/menu_item5"&gt;Menu item 5&lt;/a&gt;&lt;/h2&gt; &lt;/div&gt; </code></pre> <p>This is the jQuery:</p> <pre><code> jQuery(function($) { // get the current url var path = location.pathname.substring(1); // defining the top subnav anchor var $top_item = $('#sidebar h2:nth-child(2) a'); // defining all subnav anchors var $all_items = $('#sidebar h2.subnav a'); // defining the anchors with a href that matches the current url var $selected_item = $('#sidebar h2 a[@href$="' + path + '"]'); // setting the selected menu item'class as active $selected_item.addClass('active'); // THIS IS WHERE I THINK THE ERROR IS // if none of the h2.subnav's has a url that matches // the current location then assume that it's the top one that's active: if ($all_items("href") !== path) $top_item.addClass('active'); }); </code></pre> <p>I am applying the active-class with jQuery, it works fine as long as there is a match between an anchors href and the location url. If the url don't match any of the anchors I want the active-class to be applied to the <code>$top_item</code>. That part of my jQuery doesn't work.</p> <p>I can't see what the error is, but then again I'm somewhat of a Javascript/jQuery n00b. Any help would be appreciated.</p>
<p>This should do want you want: <strong>mark the matching link, and failing that, mark your default one.</strong></p> <pre><code>function markActiveLink() { //Look through all the links in the sidebar $("div#sidebar a").filter(function() { //Take the current URL and split it into chunks at each slash var currentURL = window.location.toString().split("/"); //return true if the bit after the last slash is the current page name return $(this).attr("href") == currentURL[currentURL.length-1]; //when the filter function is done, you're left with the links that match. }).addClass("active"); //Afterwards, look back through the links. If none of them were marked, //mark your default one. if($("div#sidebar a").hasClass("active") == false) { $("div#sidebar h2:nth-child(2) a").addClass("active"); } } markActiveLink(); </code></pre> <p>Also, I found an official tutorial on this <a href="http://docs.jquery.com/Tutorials:Auto-Selecting_Navigation" rel="nofollow noreferrer">on the jQuery Docs site</a> - scroll to the bottom to see the jQuery code. It's tighter than mine, although it's not tailored to your situation.</p>
<p>I think you can simplify this a bit:</p> <pre><code>function highlightSelected() { $("h2.subnav a").each( function() { if (location.pathname.indexOf(this.href) &gt; -1) { $(this).addClass("selected"); } } ); } </code></pre>
38,914
<p>I am using Flex to connect to a Rest service. To access order #32, for instance, I can call the URL <a href="http://[service]/orders/32" rel="nofollow noreferrer">http://[service]/orders/32</a>. The URL <em>must</em> be configured as a destination - since the client will connect to different instances of the service. All of this is using the Blaze Proxy, since it involves GET, PUT, DELETE and POST calls. The problem is:- how do I append the "32" to the end of a destination when using HttpService? All I do is set the destination, and at some point this is converted into a URL. I have traced the code, but I don't know where this is done, so can't replace it.</p> <p>Options are: 1. Resolve the destination to a URL within the Flex client, and then set the URL (with the appended data) as the URL. 2. Write my own java Flex Adapter that overrides the standard Proxy, and map parameters to the url like the following: <a href="http://[service]/order/" rel="nofollow noreferrer">http://[service]/order/</a>{id}?id=32 to <a href="http://[service]/order/32" rel="nofollow noreferrer">http://[service]/order/32</a></p> <p>Has anyone come across this problem before, and are there any simple ways to resolve this?</p>
<p>Just so everyone knows, this is how I resolved this issue:</p> <p>I created a custom HTTPProxyAdapter on the server</p> <pre><code>public MyHTTPProxyAdapter extends flex.messaging.services.http.HTTPProxyAdapter { public Object invoke(Message message) { // modify the message - if required process(message); return super.invoke(message); } private void process(Message message) { HTTPMessage http = (HTTPMessage)message; if(http != null) { String url = http.getUrl(); ASObject o = (ASObject)http.getBody(); if(o != null) { Set keys = o.keySet(); Iterator it = keys.iterator(); while(it.hasNext()) { String key = (String)it.next(); String token = "[" + key +"]"; if(url.contains(token)) { url = url.replace(token, o.get(key).toString()); o.remove(key); } } http.setUrl(url); } } } } </code></pre> <p>Then replaced the destination adapter to my adapter. I can now use the following URL in the config.xml and anything in square brackets will be replaced by the Query string:</p> <pre><code>&lt;destination id="user-getbytoken"&gt; &lt;properties&gt; &lt;url&gt;http://localhost:8080/myapp/public/client/users/token/[id]&lt;/url&gt; &lt;/properties&gt; &lt;/destination&gt; </code></pre> <p>In this example, setting the destination to user-getbytoken and the parameters {id:123} will result in the url of <a href="http://localhost:8080/myapp/public/client/users/token/123" rel="nofollow noreferrer">http://localhost:8080/myapp/public/client/users/token/123</a></p>
<p>Here's a simple way to resolve the url to the HTTPService within Flex via the click event's handler.</p> <p>here's a service:</p> <pre><code>&lt;mx:HTTPService id="UCService" result="UCServiceHandler(event)" showBusyCursor="true" resultFormat="e4x" /&gt; </code></pre> <p>Then here's the handler:</p> <pre><code> private function UCmainHandler(UCurl:String) { UCService.url = UCurl; UCService.send(); } </code></pre> <p>And here's a sample click event:</p> <pre><code>&lt;mx:Button label="add to cart" click="UCmainHandler('http://sampleurl.com/cart/add/p18_q1?destination=cart')" /&gt; </code></pre> <p>Of course you could pass other values to the click handler, or even have the handler add things to the url based on other current settings etc...</p> <p>Hope that helps!</p>
16,107
<p>I opened up my compiled Hello World Obj-C application in a text editor and, to my surprise, I found about 8 kilobytes of 00 00 00 00 00 00 00 00 ....</p> <p>Why are these here? Is there a way to clear out these zeroes (which I doubt have <em>too</em> much function)?</p> <p>Obviously it's not so important in <em>this</em> file, seeing as it's only 16kB to begin with, but I'd like to know anyway.</p>
<p>It's most likely padding between code, data, relocation or other sections of the executable format you use.</p> <p>Linkers like to pad such sections on a 4k or 8k boundary. This improves loading time for the price of a bit of memory-waste.</p> <p>For a simple hello world it's significant, but for a large application the extra memory used for the padding is neglible.</p>
<p>Maybe it's a static variable? I know in many C-like languages, the initial value of a variable that is declared static is embedded in the code emitted by the compiler. At runtime this initial value is mapped to the memory of the process. Maybe you (or some code you're including or linking against) defines an 8 KB zero-initialized array.</p>
17,595
<p>Is there any easy way to create a class that uses <strong>IFormatProvider</strong> that writes out a user-friendly file-size?</p> <pre><code>public static string GetFileSizeString(string filePath) { FileInfo info = new FileInfo(@"c:\windows\notepad.exe"); long size = info.Length; string sizeString = size.ToString(FileSizeFormatProvider); // This is where the class does its magic... } </code></pre> <p>It should result in strings formatted something like "<em>2,5 MB</em>", "<em>3,9 GB</em>", "<em>670 bytes</em>" and so on.</p>
<p>I use this one, I get it from the web</p> <pre><code>public class FileSizeFormatProvider : IFormatProvider, ICustomFormatter { public object GetFormat(Type formatType) { if (formatType == typeof(ICustomFormatter)) return this; return null; } private const string fileSizeFormat = "fs"; private const Decimal OneKiloByte = 1024M; private const Decimal OneMegaByte = OneKiloByte * 1024M; private const Decimal OneGigaByte = OneMegaByte * 1024M; public string Format(string format, object arg, IFormatProvider formatProvider) { if (format == null || !format.StartsWith(fileSizeFormat)) { return defaultFormat(format, arg, formatProvider); } if (arg is string) { return defaultFormat(format, arg, formatProvider); } Decimal size; try { size = Convert.ToDecimal(arg); } catch (InvalidCastException) { return defaultFormat(format, arg, formatProvider); } string suffix; if (size &gt; OneGigaByte) { size /= OneGigaByte; suffix = "GB"; } else if (size &gt; OneMegaByte) { size /= OneMegaByte; suffix = "MB"; } else if (size &gt; OneKiloByte) { size /= OneKiloByte; suffix = "kB"; } else { suffix = " B"; } string precision = format.Substring(2); if (String.IsNullOrEmpty(precision)) precision = "2"; return String.Format("{0:N" + precision + "}{1}", size, suffix); } private static string defaultFormat(string format, object arg, IFormatProvider formatProvider) { IFormattable formattableArg = arg as IFormattable; if (formattableArg != null) { return formattableArg.ToString(format, formatProvider); } return arg.ToString(); } } </code></pre> <p>an example of use would be:</p> <pre><code>Console.WriteLine(String.Format(new FileSizeFormatProvider(), "File size: {0:fs}", 100)); Console.WriteLine(String.Format(new FileSizeFormatProvider(), "File size: {0:fs}", 10000)); </code></pre> <p>Credits for <a href="http://flimflan.com/blog/FileSizeFormatProvider.aspx" rel="noreferrer">http://flimflan.com/blog/FileSizeFormatProvider.aspx</a></p> <p>There is a problem with ToString(), it's expecting a NumberFormatInfo type that implements IFormatProvider but the NumberFormatInfo class is sealed :( </p> <p>If you're using C# 3.0 you can use an extension method to get the result you want:</p> <pre><code>public static class ExtensionMethods { public static string ToFileSize(this long l) { return String.Format(new FileSizeFormatProvider(), "{0:fs}", l); } } </code></pre> <p>You can use it like this.</p> <pre><code>long l = 100000000; Console.WriteLine(l.ToFileSize()); </code></pre> <p>Hope this helps.</p>
<p>using C# 9.0 syntax can be written like this:</p> <pre class="lang-cs prettyprint-override"><code>public static string ToFormatSize(ulong size) { return size switch { ulong s when s &lt; 1024 =&gt; $&quot;{size} bytes&quot;, ulong s when s &lt; (1024 &lt;&lt; 10) =&gt; $&quot;{Math.Round(size / 1024D, 2)} KB&quot;, ulong s when s &lt; (1024 &lt;&lt; 20) =&gt; $&quot;{Math.Round(size * 1D / (1024 &lt;&lt; 10), 2)} MB&quot;, ulong s when s &lt; (1024 &lt;&lt; 30) =&gt; $&quot;{Math.Round(size * 1D / (1024L &lt;&lt; 20), 2)} GB&quot;, ulong s when s &lt; (1024 &lt;&lt; 40) =&gt; $&quot;{Math.Round(size * 1D / (1024L &lt;&lt; 30), 2)} TB&quot;, ulong s when s &lt; (1024 &lt;&lt; 50) =&gt; $&quot;{Math.Round(size * 1D / (1024L &lt;&lt; 40), 2)} PB&quot;, ulong s when s &lt; (1024 &lt;&lt; 60) =&gt; $&quot;{Math.Round(size * 1D / (1024L &lt;&lt; 50), 2)} EB&quot;, _ =&gt; $&quot;{size} bytes&quot; }; } </code></pre>
15,651
<p>Imagine you got an entity in the Google App Engine datastore, storing links for anonymous users. You would like to perform the following SQL query, which is not supported:</p> <pre><code>SELECT DISTINCT user_hash FROM links </code></pre> <p>Instead you could use:</p> <pre><code>user = db.GqlQuery("SELECT user_hash FROM links") </code></pre> <p>How to use Python <strong>most efficiently</strong> to filter the result, so it returns a DISTINCT result set? How to count the DISTINCT result set?</p>
<p>A set is good way to deal with that:</p> <pre><code>&gt;&gt;&gt; a = ['google.com', 'livejournal.com', 'livejournal.com', 'google.com', 'stackoverflow.com'] &gt;&gt;&gt; b = set(a) &gt;&gt;&gt; b set(['livejournal.com', 'google.com', 'stackoverflow.com']) &gt;&gt;&gt; </code></pre> <p>One suggestion w/r/t the first answer, is that sets and dicts are better at retrieving unique results quickly, membership in lists is O(n) versus O(1) for the other types, so if you want to store additional data, or do something like create the mentioned <code>unique_results</code> list, it may be better to do something like:</p> <pre><code>unique_results = {} &gt;&gt;&gt; for item in a: unique_results[item] = '' &gt;&gt;&gt; unique_results {'livejournal.com': '', 'google.com': '', 'stackoverflow.com': ''} </code></pre>
<p>Sorry to dig this question up but in GAE I cannot compare objects like that, I must use .key() for comparison like that:</p> <p>Beware, this is very inefficient :</p> <pre><code>def unique_result(array): urk={} #unique results with key for c in array: if c.key() not in urwk: urk[str(c.key())]=c return urk.values() </code></pre> <p>If anyone has a better solution, please share.</p>
29,598
<p>I have built a windows service application in VB.net 2008, and used the Setup Wizard to add an installation process.</p> <p>The installer works, in that it adds the app to add/remove programs and copies all of the files etc, but it's missing the final (required) step of actually installing the service.</p> <p>I have added the primary output of the Project as a custom action for Install and Uninstall, without success.</p> <p>what's the secret?</p>
<p>You need to create a custom install task; MSDN has <a href="http://msdn.microsoft.com/en-us/library/zt39148a(VS.80).aspx" rel="nofollow noreferrer">everything you need to know</a></p>
<p>You can do two things: </p> <p>1) Use custom actions in your setup project to register the service using the "installutil" .Net Framework command line utility, or simply register it yourself using installutil.</p> <p>2) Add an Installer class to your Windows service. This <a href="http://www.codeproject.com/KB/dotnet/simplewindowsservice.aspx" rel="nofollow noreferrer">link</a> should give you all of the information you need, just skip past the beginning parts about creating the service. This is the way I recommend.</p>
25,591
<p>I have a fresh install of django 1.0 and a simple page served from it takes 5 secs to load. On my colleague's computer it takes almost no time.</p> <p>I start the server using </p> <pre> python manage.py testserver </pre> <p>I can see each GET request (PNGs and style sheets) take about half a second.</p> <p>Another weird thing, which I think is related, is that the functional tests for the app run much slower on my machine with MySQL (on order of 100 times slower than on my colleague's machine). When I set the app to use sqlite, they run pretty quickly. I would like to exclaim that sqlite doesn't much change the time it takes to load a page, but it does speed up server startup.</p> <p>It looks like IO problem, but I don't see general performance problems on my machine, apart from django at least.</p> <p>Django runs on python2.4, I'm running Vista. I have also checked python2.5.</p> <p>Thanks ΤΖΩΤΖΙΟΥ, It must totaly be a DNS problem, because the page loads up quickly as soon as instead of <a href="http://localhost:8000/app" rel="noreferrer">http://localhost:8000/app</a> I go to <a href="http://127.0.0.1:8000/app" rel="noreferrer">http://127.0.0.1:8000/app</a>.</p> <p>But what could it be caused by? My host file has only two entries:</p> <pre> 127.0.0.1 localhost ::1 localhost </pre>
<p>Firefox has a problem browsing to localhost on some Windows machines. You can solve it by switching off ipv6, which isn't really recommended. Using 127.0.0.1 directly is another way round the problem.</p>
<p>Disable AV Scanning &amp; see if that makes a difference. It could also be caused by Vista. Upgrade to the latest service pack and try again. </p>
47,358
<p>I think this is specific to IE 6.0 but...</p> <p>In JavaScript I add a <code>div</code> to the DOM. I assign an <code>id</code> attribute. When I later try to pick up the <code>div</code> by the <code>id</code> all I get is <code>null</code>.</p> <p>Any suggestions?</p> <p>Example:</p> <pre><code>var newDiv = document.createElement("DIV"); newDiv.setAttribute("ID", "obj_1000"); document.appendChild(newDiv); alert("Added:" + newDiv.getAttribute("ID") + ":" + newDiv.id + ":" + document.getElementById("obj_1000") ); </code></pre> <p>Alert prints <code>"::null"</code></p> <p>Seems to work fine in Firefox 2.0+</p>
<p>In addition to what the other answers suggest (that you need to actually insert the element into the DOM for it to be found via <code>getElementById()</code>), you also need to use a lower-case attribute name in order for IE6 to recognize it as the <code>id</code>:</p> <pre><code>var newDiv = document.createElement("DIV"); newDiv.setAttribute("id", "obj_1000"); document.body.appendChild(newDiv); alert("Added:" + newDiv.getAttribute("id") + ":" + newDiv.id + ":" + document.getElementById("obj_1000") ); </code></pre> <p>...responds as expected:</p> <pre><code>Added:obj_1000:obj_1000:[object] </code></pre> <hr> <p>According to the <a href="http://msdn.microsoft.com/en-us/library/ms536739(VS.85).aspx" rel="noreferrer">MSDN documentation</a> for <code>setAttribute()</code>, up to IE8 there is an optional <em>third parameter</em> that controls whether or not it is case sensitive with regard to the attribute name. Guess what the default is...</p>
<p>newDiv.setAttribute( "ID", "obj_1000" );</p> <p>should be</p> <p>newDiv.id = "obj_1000";</p>
7,609
<p>I am trying to create a couple of holders for my ultrasonic cleaners. They are supposed to be used for parts that don't fit in the holder that came with the cleaners. I was wondering what material is best to use for this.</p> <p>My initial thoughts are:</p> <ul> <li>Material should hold up to the cleaning solution, I have a wide range of them from degreaser, deruster, and so on. I would say PETG or PLA should be a safe bet as it reacts with almost nothing</li> <li>Material should not have issues with warm (not hot) water, I'd say something along the lines of 60-80 °C. This already eliminates PLA, but I think PETG should still be OK-ish (I am aiming more towards 60 °C than 80 °C).</li> </ul> <p>Is there something I am missing? Does anyone have any input? I am anyway just going to do a few tests, but I assume starting with PETG is a good start.</p>
<p>This is going to be hard. Even holding a vacuum is hard (I've tried it and not succeeded). I'm not sure what the mechanism of air molecules getting thru the print is - whether it's defects in inter-layer bonding, defects at seams, imperfect mating with the fitting, or even permeability of the plastic itself. It might not actually be existing flaws in the print, but rather the high pressure being a stronger force than the bonded layers can withstand, essentially ripping the layers apart from the weakest point until the pressure can discharge through the opening produced.</p> <p>If using ABS, you might try an acetone bath followed by a long period of trying or use of vacuum chamber to quickly remove the solvent, if you can stand some possible part deformation. This would tend to fill any gaps. Coating with low-viscosity CA glue (Loctite 420 or equivalent) might be a better version of this approach, as the solvent will both attack the ABS and deliver fill material.</p> <p>In principle PET (maybe also PETG, but PET is preferable anyway if you can get it) should be a suitable material for pressure vessels, as it's what's used for soda bottles at comparable pressure, but those are blown from a single piece, not fused together with seams.</p> <p>At some point I will attempt this again, and will update my answer if I have any findings that contribute to your question.</p>
<h2>Not without postprocessing</h2> <p>FDM is pretty much welding plastic to plastic. Many many layers. Each of them is a potential breaking point, a corner for stress to arise and break the print.</p> <h2>Easy with a hollow body</h2> <p>Printing a hollow item that can be filled with resin is comparatively easy. Once filled with a monolithic curing resin (epoxy), that will take the pressure much better and seal it fully.</p>
2,199
<p>I'm doing some Objective-C programming that involves parsing an NSXmlDocument and populating an objects properties from the result.</p> <p>First version looked like this:</p> <pre><code>if([elementName compare:@"companyName"] == 0) [character setCorporationName:currentElementText]; else if([elementName compare:@"corporationID"] == 0) [character setCorporationID:currentElementText]; else if([elementName compare:@"name"] == 0) ... </code></pre> <p>But I don't like the <code>if-else-if-else</code> pattern this produces. Looking at the <code>switch</code> statement I see that i can only handle <code>ints</code>, <code>chars</code> etc and not objects... so is there a better implementation pattern I'm not aware of?</p> <p>BTW I did actually come up with a better solution for setting the object's properties, but I want to know specifically about the <code>if</code>-<code>else</code> vs <code>switch</code> pattern in Objective-C</p>
<p>I hope you'll all forgive me for going out on a limb here, but I would like to address the more general question of parsing XML documents in Cocoa without the need of if-else statements. The question as originally stated assigns the current element text to an instance variable of the character object. As jmah pointed out, this can be solved using key-value coding. However, in a more complex XML document this might not be possible. Consider for example the following.</p> <pre><code>&lt;xmlroot&gt; &lt;corporationID&gt; &lt;stockSymbol&gt;EXAM&lt;/stockSymbol&gt; &lt;uuid&gt;31337&lt;/uuid&gt; &lt;/corporationID&gt; &lt;companyName&gt;Example Inc.&lt;/companyName&gt; &lt;/xmlroot&gt; </code></pre> <p>There are multiple approaches to dealing with this. Off of the top of my head, I can think of two using NSXMLDocument. The first uses NSXMLElement. It is fairly straightforward and does not involve the if-else issue at all. You simply get the root element and go through its named elements one by one.</p> <pre><code>NSXMLElement* root = [xmlDocument rootElement]; // Assuming that we only have one of each element. [character setCorperationName:[[[root elementsForName:@"companyName"] objectAtIndex:0] stringValue]]; NSXMLElement* corperationId = [root elementsForName:@"corporationID"]; [character setCorperationStockSymbol:[[[corperationId elementsForName:@"stockSymbol"] objectAtIndex:0] stringValue]]; [character setCorperationUUID:[[[corperationId elementsForName:@"uuid"] objectAtIndex:0] stringValue]]; </code></pre> <p>The next one uses the more general NSXMLNode, walks through the tree, and directly uses the if-else structure.</p> <pre><code>// The first line is the same as the last example, because NSXMLElement inherits from NSXMLNode NSXMLNode* aNode = [xmlDocument rootElement]; while(aNode = [aNode nextNode]){ if([[aNode name] isEqualToString:@"companyName"]){ [character setCorperationName:[aNode stringValue]]; }else if([[aNode name] isEqualToString:@"corporationID"]){ NSXMLNode* correctParent = aNode; while((aNode = [aNode nextNode]) == nil &amp;&amp; [aNode parent != correctParent){ if([[aNode name] isEqualToString:@"stockSymbol"]){ [character setCorperationStockSymbol:[aNode stringValue]]; }else if([[aNode name] isEqualToString:@"uuid"]){ [character setCorperationUUID:[aNode stringValue]]; } } } } </code></pre> <p>This is a good candidate for eliminating the if-else structure, but like the original problem, we can't simply use switch-case here. However, we can still eliminate if-else by using performSelector. The first step is to define the a method for each element.</p> <pre><code>- (NSNode*)parse_companyName:(NSNode*)aNode { [character setCorperationName:[aNode stringValue]]; return aNode; } - (NSNode*)parse_corporationID:(NSNode*)aNode { NSXMLNode* correctParent = aNode; while((aNode = [aNode nextNode]) == nil &amp;&amp; [aNode parent != correctParent){ [self invokeMethodForNode:aNode prefix:@"parse_corporationID_"]; } return [aNode previousNode]; } - (NSNode*)parse_corporationID_stockSymbol:(NSNode*)aNode { [character setCorperationStockSymbol:[aNode stringValue]]; return aNode; } - (NSNode*)parse_corporationID_uuid:(NSNode*)aNode { [character setCorperationUUID:[aNode stringValue]]; return aNode; } </code></pre> <p>The magic happens in the invokeMethodForNode:prefix: method. We generate the selector based on the name of the element, and perform that selector with aNode as the only parameter. Presto bango, we've eliminated the need for an if-else statement. Here's the code for that method.</p> <pre><code>- (NSNode*)invokeMethodForNode:(NSNode*)aNode prefix:(NSString*)aPrefix { NSNode* ret = nil; NSString* methodName = [NSString stringWithFormat:@"%@%@:", prefix, [aNode name]]; SEL selector = NSSelectorFromString(methodName); if([self respondsToSelector:selector]) ret = [self performSelector:selector withObject:aNode]; return ret; } </code></pre> <p>Now, instead of our larger if-else statement (the one that differentiated between companyName and corporationID), we can simply write one line of code</p> <pre><code>NSXMLNode* aNode = [xmlDocument rootElement]; while(aNode = [aNode nextNode]){ aNode = [self invokeMethodForNode:aNode prefix:@"parse_"]; } </code></pre> <p>Now I apologize if I got any of this wrong, it's been a while since I've written anything with NSXMLDocument, it's late at night and I didn't actually test this code. So if you see anything wrong, please leave a comment or edit this answer.</p> <p>However, I believe I have just shown how properly-named selectors can be used in Cocoa to completely eliminate if-else statements in cases like this. There are a few gotchas and corner cases. The performSelector: family of methods only takes 0, 1, or 2 argument methods whose arguments and return types are objects, so if the types of the arguments and return type are not objects, or if there are more than two arguments, then you would have to use an NSInvocation to invoke it. You have to make sure that the method names you generate aren't going to call other methods, especially if the target of the call is another object, and this particular method naming scheme won't work on elements with non-alphanumeric characters. You could get around that by escaping the XML element names in your method names somehow, or by building an NSDictionary using the method names as the keys and the selectors as the values. This can get pretty memory intensive and end up taking a longer time. performSelector dispatch like I described is pretty fast. For very large if-else statements, this method may even be faster than an if-else statement.</p>
<p>Similar to Lvsti I am using blocks to perform a switching pattern on objects.</p> <p>I wrote a very simple filter block based chain, that takes n filter blocks and performs each filter on the object.<br> Each filter can alter the object, but must return it. No matter what.</p> <p>NSObject+Functional.h</p> <pre><code>#import &lt;Foundation/Foundation.h&gt; typedef id(^FilterBlock)(id element, NSUInteger idx, BOOL *stop); @interface NSObject (Functional) -(id)processByPerformingFilterBlocks:(NSArray *)filterBlocks; @end </code></pre> <p>NSObject+Functional.m</p> <pre><code>@implementation NSObject (Functional) -(id)processByPerformingFilterBlocks:(NSArray *)filterBlocks { __block id blockSelf = self; [filterBlocks enumerateObjectsUsingBlock:^( id (^block)(id,NSUInteger idx, BOOL*) , NSUInteger idx, BOOL *stop) { blockSelf = block(blockSelf, idx, stop); }]; return blockSelf; } @end </code></pre> <p>Now we can set up <code>n</code> FilterBlocks to test for the different cases.</p> <pre><code>FilterBlock caseYES = ^id(id element, NSUInteger idx, BOOL *breakAfter){ if ([element isEqualToString:@"YES"]) { NSLog(@"You did it"); *breakAfter = YES; } return element; }; FilterBlock caseNO = ^id(id element, NSUInteger idx, BOOL *breakAfter){ if ([element isEqualToString:@"NO"] ) { NSLog(@"Nope"); *breakAfter = YES; } return element; }; </code></pre> <p>Now we stick those block we want to test as a filter chain in an array:</p> <pre><code>NSArray *filters = @[caseYES, caseNO]; </code></pre> <p>and can perform it on an object</p> <pre><code>id obj1 = @"YES"; id obj2 = @"NO"; [obj1 processByPerformingFilterBlocks:filters]; [obj2 processByPerformingFilterBlocks:filters]; </code></pre> <p>This approach can be used for switching but also for any (conditional) filter chain application, as the blocks can edit the element and pass it on.</p>
12,993
<p>How can I create an instance of the following annotation (with all fields set to their default value).</p> <pre><code> @Retention( RetentionPolicy.RUNTIME ) public @interface Settings { String a() default "AAA"; String b() default "BBB"; String c() default "CCC"; } </code></pre> <p>I tried <code>new Settings()</code>, but that does not seem to work...</p>
<p>You cannot create an instance, but at least get the default values</p> <pre><code>Settings.class.getMethod("a").getDefaultValue() Settings.class.getMethod("b").getDefaultValue() Settings.class.getMethod("c").getDefaultValue() </code></pre> <p>And then, a dynamic proxy could be used to return the default values. Which is, as far as I can tell, the way annotations are handled by Java itself also.</p> <pre><code>class Defaults implements InvocationHandler { public static &lt;A extends Annotation&gt; A of(Class&lt;A&gt; annotation) { return (A) Proxy.newProxyInstance(annotation.getClassLoader(), new Class[] {annotation}, new Defaults()); } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return method.getDefaultValue(); } } Settings s = Defaults.of(Settings.class); System.out.printf("%s\n%s\n%s\n", s.a(), s.b(), s.c()); </code></pre>
<p>This works with Sun/Oracle Java 5,6,7,8: (but could potentially break with Java 9 due to the sun classes involved). //edit Just verified that this still works with OpenJDK 9b59.</p> <pre><code>package demo; import sun.reflect.annotation.AnnotationParser; import java.lang.annotation.*; import java.lang.reflect.Method; import java.util.Collections; import java.util.HashMap; import java.util.Map; public class AnnotationProxyExample { public static void main(String[] args) { System.out.printf("Custom annotation creation: %s%n", createAnnotationInstance(Collections.singletonMap("value", "required"), Example.class)); System.out.printf("Traditional annotation creation: %s%n", X.class.getAnnotation(Example.class)); } private static &lt;A extends Annotation&gt; A createAnnotationInstance(Map&lt;String, Object&gt; customValues, Class&lt;A&gt; annotationType) { Map&lt;String, Object&gt; values = new HashMap&lt;&gt;(); //Extract default values from annotation for (Method method : annotationType.getDeclaredMethods()) { values.put(method.getName(), method.getDefaultValue()); } //Populate required values values.putAll(customValues); return (A) AnnotationParser.annotationForMap(annotationType, values); } @Example("required") static class X { } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @interface Example { String value(); int foo() default 42; boolean bar() default true; } } </code></pre> <p>Output:</p> <pre><code>Custom annotation creation: @demo.AnnotationProxyExample$Example(bar=true, foo=42, value=required) Traditional annotation creation: @demo.AnnotationProxyExample$Example(bar=true, foo=42, value=required) </code></pre>
33,466
<p>What is the difference between the <code>EXISTS</code> and <code>IN</code> clause in SQL?</p> <p>When should we use <code>EXISTS</code>, and when should we use <code>IN</code>?</p>
<p>The <code>exists</code> keyword can be used in that way, but really it's intended as a way to avoid counting:</p> <pre class="lang-sql prettyprint-override"><code>--this statement needs to check the entire table select count(*) from [table] where ... --this statement is true as soon as one match is found exists ( select * from [table] where ... ) </code></pre> <p>This is most useful where you have <code>if</code> conditional statements, as <code>exists</code> can be a lot quicker than <code>count</code>.</p> <p>The <code>in</code> is best used where you have a static list to pass:</p> <pre class="lang-sql prettyprint-override"><code> select * from [table] where [field] in (1, 2, 3) </code></pre> <p>When you have a table in an <code>in</code> statement it makes more sense to use a <code>join</code>, but mostly it shouldn't matter. The query optimiser should return the same plan either way. In some implementations (mostly older, such as Microsoft SQL Server 2000) <code>in</code> queries will always get a <a href="https://technet.microsoft.com/en-us/library/ms191318(v=sql.105).aspx" rel="noreferrer">nested join</a> plan, while <code>join</code> queries will use nested, <a href="https://technet.microsoft.com/en-us/library/ms190967(v=sql.105).aspx" rel="noreferrer">merge</a> or <a href="https://technet.microsoft.com/en-us/library/ms189313(v=sql.105).aspx" rel="noreferrer">hash</a> as appropriate. More modern implementations are smarter and can adjust the plan even when <code>in</code> is used.</p>
<p>If you are using the IN operator, the SQL engine will scan all records fetched from the inner query. On the other hand if we are using EXISTS, the SQL engine will stop the scanning process as soon as it found a match. </p>
4,456
<p>I know about the <a href="http://developer.apple.com/library/mac/#documentation/UserExperience/Conceptual/AppleHIGuidelines/Intro/Intro.html" rel="noreferrer">HIG</a> (which is quite handy!), but what programming practices do you use when writing Objective-C, and more specifically when using Cocoa (or CocoaTouch).</p>
<p>There are a few things I have started to do that I do not think are standard:</p> <p>1) With the advent of properties, I no longer use "_" to prefix "private" class variables. After all, if a variable can be accessed by other classes shouldn't there be a property for it? I always disliked the "_" prefix for making code uglier, and now I can leave it out.</p> <p>2) Speaking of private things, I prefer to place private method definitions within the .m file in a class extension like so:</p> <pre><code>#import "MyClass.h" @interface MyClass () - (void) someMethod; - (void) someOtherMethod; @end @implementation MyClass </code></pre> <p>Why clutter up the .h file with things outsiders should not care about? The empty () works for private categories in the .m file, and issues compile warnings if you do not implement the methods declared.</p> <p>3) I have taken to putting dealloc at the top of the .m file, just below the @synthesize directives. Shouldn't what you dealloc be at the top of the list of things you want to think about in a class? That is especially true in an environment like the iPhone.</p> <p>3.5) In table cells, make every element (including the cell itself) opaque for performance. That means setting the appropriate background color in everything.</p> <p>3.6) When using an NSURLConnection, as a rule you may well want to implement the delegate method:</p> <pre><code>- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse { return nil; } </code></pre> <p>I find most web calls are very singular and it's more the exception than the rule you'll be wanting responses cached, especially for web service calls. Implementing the method as shown disables caching of responses.</p> <p>Also of interest, are some good iPhone specific tips from Joseph Mattiello (received in an iPhone mailing list). There are more, but these were the most generally useful I thought (note that a few bits have now been slightly edited from the original to include details offered in responses):</p> <p>4) Only use double precision if you have to, such as when working with CoreLocation. Make sure you end your constants in 'f' to make gcc store them as floats.</p> <pre><code>float val = someFloat * 2.2f; </code></pre> <p>This is mostly important when <code>someFloat</code> may actually be a double, you don't need the mixed-mode math, since you're losing precision in 'val' on storage. While floating-point numbers are supported in hardware on iPhones, it may still take more time to do double-precision arithmetic as opposed to single precision. References:</p> <ul> <li><a href="https://stackoverflow.com/questions/1622729/double-vs-float-on-the-iphone">Double vs float on the iPhone</a></li> <li><a href="https://stackoverflow.com/questions/8854001/iphone-ipad-double-precision-math">iPhone/iPad double precision math</a></li> </ul> <p>On the older phones supposedly calculations operate at the same speed but you can have more single precision components in registers than doubles, so for many calculations single precision will end up being faster.</p> <p>5) Set your properties as <code>nonatomic</code>. They're <code>atomic</code> by default and upon synthesis, semaphore code will be created to prevent multi-threading problems. 99% of you probably don't need to worry about this and the code is much less bloated and more memory-efficient when set to nonatomic.</p> <p>6) SQLite can be a very, very fast way to cache large data sets. A map application for instance can cache its tiles into SQLite files. The most expensive part is disk I/O. Avoid many small writes by sending <code>BEGIN;</code> and <code>COMMIT;</code> between large blocks. We use a 2 second timer for instance that resets on each new submit. When it expires, we send COMMIT; , which causes all your writes to go in one large chunk. SQLite stores transaction data to disk and doing this Begin/End wrapping avoids creation of many transaction files, grouping all of the transactions into one file.</p> <p>Also, SQL will block your GUI if it's on your main thread. If you have a very long query, It's a good idea to store your queries as static objects, and run your SQL on a separate thread. Make sure to wrap anything that modifies the database for query strings in <code>@synchronize() {}</code> blocks. For short queries just leave things on the main thread for easier convenience.</p> <p>More SQLite optimization tips are here, though the document appears out of date many of the points are probably still good;</p> <p><a href="http://web.utk.edu/~jplyon/sqlite/SQLite_optimization_FAQ.html" rel="nofollow noreferrer">http://web.utk.edu/~jplyon/sqlite/SQLite_optimization_FAQ.html</a></p>
<pre><code>#import "MyClass.h" @interface MyClass () - (void) someMethod; - (void) someOtherMethod; @end @implementation MyClass </code></pre>
18,870
<p>We have a large OpenWiki powered wiki. OpenWiki appears to be a dead project, and ScrewTurn the next best option.</p> <p>Is anyone aware of a data migration route to move our content from the OpenWiki SQL Server format to the ScrewTurn wiki SQL Server format?</p> <p>We may end up creating our own (and sharing it) but we'd rather not re-invent the wheel.</p> <p>Regards,</p> <p>Mike</p>
<p>Are you sure about the "dead" status?</p> <p><a href="http://www.facebook.com/pages/OpenWiki-The-Post-It-Note-of-the-Web/145492998806288" rel="nofollow noreferrer">http://www.facebook.com/pages/OpenWiki-The-Post-It-Note-of-the-Web/145492998806288</a></p>
<p>Are you sure about the "dead" status?</p> <p><a href="http://www.facebook.com/pages/OpenWiki-The-Post-It-Note-of-the-Web/145492998806288" rel="nofollow noreferrer">http://www.facebook.com/pages/OpenWiki-The-Post-It-Note-of-the-Web/145492998806288</a></p>
34,342
<p>My code needs to run all networking routines in a separate NSThread. I have got a library, which I pass a callback routine for communication:</p> <pre><code>my thread code library my callback (networking) library my thread code </code></pre> <p>My callback routine must POST some data to an HTTP server (NSURLConnection), wait for the answer (start a NSRunLoop?), then return to the library.<br> The library then processes the data. After the library returns to my thread, I can then post a notification to the main thread which handles drawing and user input.</p> <p>Is there any sample code covering how to use NSURLConnection in a NSThread?</p>
<p>If you need to block until you've done the work and you're already on a separate thread, you could use <code>+[NSURLConnection sendSynchronousRequest:returningResponse:error:]</code>. It's a bit blunt though, so if you need more control you'll have to switch to an asynchronous <code>NSURLRequest</code> with delegate methods (i.e. callbacks) scheduled in the current <code>NSRunLoop</code>. In that case, one approach might be to let your delegate flag when it's done, and allow the run loop to process events until either the flag is set or a timeout is exceeded.</p>
<p>To answer your mini-question "start an NSRunLoop?":</p> <p>I'm not sure I understand, but it sounds like you are saying your pseudocode above is all being executed on a secondary thread (i.e., not the main event processing thread). If that's the case, there probably isn't any point in creating an NSRunLoop, because you can't do any useful work while waiting for the HTTP server to respond. Just let the thread block.</p>
19,083
<p>My friends and I are starting a game like Pokemon and we wanted to know how will we add monsters to the game? We're using VisualBasic because my friend's brother said it would be easier.</p> <p>So far we can put pictures of the monsters on the screen and you can click to attack and stuff.</p> <p>Right now when we want to add a monster we have to make a new window. This will take us a long time to make all the windows for each type of monster. Is there a tool or something to make this go faster? How do game companies do this?</p>
<p>I think the best solution would be to make a generic window which can take a few parameters which describe the monster. </p> <p>Im not entirely up-to-date with VB, but in an OO language we would have a Monster base class, and inheritance to create a Pikachu. The base class would define basic things a monster has (like a picture and a name and a type) and things a monster could do (like attack, run away etc). You could even use a second level, and have base classes for each type (like ElectricMonster which inherits from Monster, and Pikachu inherits from ElectricMonster).</p> <p>It then becomes really easy to pass a Monster object to a window, and have the window know how to pull out all the relevant information.</p>
<p>Once you have created your artwork, I would load it dynamically from the hard disk rather than compile it into one big EXE. You can use the PictureBox control's LoadPicture method.</p>
10,548
<p>I've been hearing about triggers, and I have a few questions.<br /> What are triggers?<br /> How do I set them up?<br /> Are there any precautions, aside from typical SQL stuff, that should be taken?</p>
<p>Triggers allow you to perform a function in the database as certain events happen (eg, an insert into a table). </p> <p>I can't comment on mysql specifically.</p> <p>Precaution: Triggers can be very alluring, when you first start using them they seem like a magic bullet to all kinds of problems. But, they make "magic" stuff happen, if you don't know the database inside out, it can seem like really strange things happen (such as inserts into other tables, input data changing, etc). Before implementing things as a trigger I'd seriously consider instead enforcing the use of an API around the schema (preferably in the database, but outside if you can't).</p> <p>Some things I'd still use triggers for</p> <ul> <li>Keeping track of "date_created" and "date_last_edited" fields</li> <li>Inserting "ID"'s (in oracle, where there is no auto id field)</li> <li>Keeping change history</li> </ul> <p>Things you wouldn't want to use triggers for</p> <ul> <li>business rules/logic</li> <li>anything which connects outside of the database (eg a webservice call)</li> <li>Access control</li> <li>Anything which isn't transactional ( anything you do in the trigger MUST be able to rollback with the transaction )</li> </ul>
<p>A trigger is a named database object that is associated with a table and that is activated when a particular event occurs for the table.<br /> <br />To create a trigger:<br /></p> <pre><code>CREATE TRIGGER triggerName [BEFORE|AFTER] [INSERT|UPDATE|DELETE|REPLACE] ON tableName FOR EACH ROW SET stuffToDoHERE; </code></pre> <p><br />Even though I answered this part the other question still stands.</p>
6,961
<p>I am trying to do some prime factorisation with my VBA excel and I am hitting the limit of the <code>long</code> data type - </p> <blockquote> <p>Runtime Error 6 Overflow </p> </blockquote> <p>Is there any way to get around this and still stay within VBA? I am aware that the obvious one would be to use another more appropriate programming language.</p> <hr> <p><a href="https://stackoverflow.com/a/297480/1146308">Lance's solution</a> works in so far that I am able to get the big numbers into the variables now. However, when I try to apply the <code>MOD</code> function - bignumber <code>MOD 2</code>, for example - it still fails with error message </p> <blockquote> <p>Runtime Error 6 Overflow</p> </blockquote>
<p>You can use Decimal data type. Quick hint from google: <a href="http://www.ozgrid.com/VBA/convert-to-decimal.htm" rel="nofollow noreferrer">http://www.ozgrid.com/VBA/convert-to-decimal.htm</a></p>
<p>You can use Decimal data type. Quick hint from google: <a href="http://www.ozgrid.com/VBA/convert-to-decimal.htm" rel="nofollow noreferrer">http://www.ozgrid.com/VBA/convert-to-decimal.htm</a></p>
38,030
<p>What are the biggest pros and cons of <a href="http://incubator.apache.org/thrift/" rel="noreferrer">Apache Thrift</a> vs <a href="http://code.google.com/apis/protocolbuffers/" rel="noreferrer">Google's Protocol Buffers</a>?</p>
<p>They both offer many of the same features; however, there are some differences:</p> <ul> <li>Thrift supports 'exceptions'</li> <li>Protocol Buffers have much better documentation/examples</li> <li>Thrift has a builtin <code>Set</code> type</li> <li>Protocol Buffers allow "extensions" - you can extend an external proto to add extra fields, while still allowing external code to operate on the values. There is no way to do this in Thrift</li> <li>I find Protocol Buffers much easier to read</li> </ul> <p>Basically, they are fairly equivalent (with Protocol Buffers slightly more efficient from what I have read).</p>
<p>It's also important to note that not all supported languages compair consistently with thrift or protobuf. At this point it's a matter of the modules implementation in addition to the underlying serialization. Take care to check benchmarks for whatever language you plan to use.</p>
9,472
<p>When I call the connect function of the Paramiko <code>SSHClient</code> class, it outputs some log data about establishing the connection, which I would like to suppress.</p> <p>Is there a way to do this either through Paramiko itself, or Python in general?</p>
<p>Paramiko doesn't output anything by default. You probably have a call to the logging module, setting a loglevel that's inherited when paramiko sets up it's own logging.</p> <p>If you want to get at the paramiko logger to override the settings:</p> <pre><code>logger = paramiko.util.logging.getLogger() </code></pre> <p>There's also a convenience function to log everything to a file:</p> <pre><code>paramiko.util.log_to_file('filename.log') </code></pre>
<p>I don't know what Paramiko is, and there must be a log level setting for sure, but if you are desperate and looking for a temporary solution and if your app is single threaded</p> <pre><code>import sys dev_null = sys.stdout = sys.stderr = open('/dev/null', 'w') try: . . connect() . finally: dev_null.close() </code></pre> <p>you can use StringIO for output also, if you are on an OS not have a '/dev/null'</p>
44,215
<p>I'm currently looking to perform some headless HTML rendering to essentially create resources off screen and persist the result as an image. The purpose is to take a subset of the HTML language and apply it to small screen devices (like PocketPCs) because our users know HTML and the transition from Photoshop to HTML markup would be acceptable.</p> <p>I am also considering using WPF Imaging so if anyone can weigh in comments about its use (particularly tools you would point your users to for creating WPF layouts you can convert into images and how well it performs) it would be appreciated.</p> <p>My order of preference is:</p> <ol> <li>open source</li> <li>high performance</li> <li>native C# or C# wrapper</li> <li>lowest complexity for implementation on Windows</li> </ol> <p>I'm not very worried about how feature rich the headless rendering is since we won't make big use of JavaScript, Flash, nor other embedded objects aside from images. I'd be fine with anything that uses IE, Firefox, webkit, or even a custom rendering implementation so long as its implementation is close to standards compliant.</p>
<p><a href="http://www.phantomjs.org/">http://www.phantomjs.org/</a></p> <p><strong>Full web stack</strong></p> <p>PhantomJS is a headless WebKit with JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG.</p>
<p><a href="http://code.google.com/p/flying-saucer//" rel="nofollow noreferrer">Flying Saucer</a> is a Java-based XHTML &amp; CSS2.1 renderer that passess ACID2 with some error caveats. Its downside is that it has no error handling. It is not really designed to be a browser, but rather to be a component used to display HTML content (help files, etc.) within an application.</p>
11,296
<p>I've noticed that SQL Server 2005 x64 does not seem to lock pages into memory the same way SQL Server 2000 did. In 2000 I could easily see from task manager that SQL had locked 8GB of ram with AWE. I'm fairly certain I've got 2005 setup in an equivalent way.</p> <p>Is this a normal x64 difference or am I forgetting a crucial setup option?</p>
<p>SQL Server 2005 x64 certainly doesn't need, or use, AWE; AWE is only to allow it to use > 4GB on 32 bit systems.</p> <p>You <em>can</em> use the old lock-pages-in-memory trick, but as this KB shows (<a href="http://support.microsoft.com/kb/918483" rel="nofollow noreferrer">http://support.microsoft.com/kb/918483</a>): "Note For 64-bit editions of SQL Server 2005, only SQL Server 2005 Enterprise Edition can use the Lock pages in memory user right."</p>
<p>I've seen permissions problems crop up a lot too - if the account you're using for the SQL Server service doesn't have the right permissions, it can't lock pages in memory even if you're running Enterprise Edition. This blog entry by the PSS SQL Server Engineers is really helpful:</p> <p><a href="http://blogs.msdn.com/psssql/archive/2007/10/18/do-i-have-to-assign-the-lock-privilege-for-local-system.aspx" rel="nofollow noreferrer">PSS Engineers: Do I have to assign the Lock Pages in Memory privilege for Local System?</a></p>
7,542
<p>Backstory: I'm using <a href="http://logging.apache.org/log4net/index.html" rel="noreferrer">log4net</a> to handle all logging for a project I'm working on. One particular method can be called under several different circumstances -- some that warrant the log messages to be errors and others that warrant the log messages to be warnings.</p> <p>So, as an example, how could I turn</p> <pre><code>Public Sub CheckDifference(ByVal A As Integer, ByVal B As Integer) If (B - A) &gt; 5 Then log.ErrorFormat("Difference ({0}) is outside of acceptable range.", (B - A)) End If End Sub </code></pre> <p>Into something more along the lines of:</p> <pre><code>Public Sub CheckDifference(ByVal A As Integer, ByVal B As Integer, "Some delegate info here") If (B - A) &gt; 5 Then **delegateinfo**.Invoke("Difference ({0}) is outside of acceptable range.", (B - A)) End If End Sub </code></pre> <p>So that I could call it and pass either log.ErrorFormat or log.WarnFormat as the delegate?</p> <p>I'm using VB.NET with VS 2008 and .NET 3.5 SP1. Also, I'm fairly new to delegates in general, so if this question should be worded differently to remove any ambiguities, let me know.</p> <p>EDIT: Also, how could I initialize the delegate to either the ErrorFormat or the WarnFormat in the class constructor? Would it be as easy as <code>myDelegate = log.ErrorFormat</code>? I would imagine there is more to it than that (pardon my ignorance on the subject -- delegates are really something I want to learn more about, but so far they have eluded my understanding).</p>
<p>Declare your delegate signature:</p> <pre><code>Public Delegate Sub Format(ByVal value As String) </code></pre> <p>Define your Test function:</p> <pre><code>Public Sub CheckDifference(ByVal A As Integer, _ ByVal B As Integer, _ ByVal format As Format) If (B - A) &gt; 5 Then format.Invoke(String.Format( _ "Difference ({0}) is outside of acceptable range.", (B - A))) End If End Sub </code></pre> <p>Somewhere in your code call your Test function:</p> <pre><code>CheckDifference(Foo, Bar, AddressOf log.WriteWarn) </code></pre> <p>Or </p> <pre><code>CheckDifference(Foo, Bar, AddressOf log.WriteError) </code></pre>
<pre><code>Public Delegate errorCall(ByVal error As String, Params objs As Objects()) CheckDifference(10, 0, AddressOf log.ErrorFormat) </code></pre> <p>Please forgive the formatting :P</p> <p>Basically though, create the delegate that you want, with the correct signature, and pass the address of it to the method.</p>
14,325
<p>I have a .NET <strong>2.0</strong> WebBrowser control used to navigate some pages with no user interaction (don't ask...long story). Because of the user-less nature of this application, I have set the WebBrowser control's ScriptErrorsSuppressed property to true, which the documentation included with VS 2005 states will [...]"hide all its dialog boxes that originate from the underlying ActiveX control, not just script errors." The <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.scripterrorssuppressed(VS.80).aspx" rel="noreferrer">MSDN article</a> doesn't mention this, however. I have managed to cancel the NewWindow event, which prevents popups, so that's taken care of.</p> <p>Anyone have any experience using one of these and successfully blocking <strong>all</strong> dialogs, script errors, etc?</p> <p><strong>EDIT</strong></p> <p>This isn't a standalone instance of IE, but an instance of a WebBrowser control living on a Windows Form application. Anyone have any experience with this control, or the underlying one, <strong>AxSHDocVW</strong>?</p> <p><strong>EDIT again</strong></p> <p>Sorry I forgot to mention this... I'm trying to block a <strong>JavaScript alert()</strong>, with just an OK button. Maybe I can cast into an IHTMLDocument2 object and access the scripts that way, I've used MSHTML a little bit, anyone know?</p>
<p>This is most definitely hacky, but if you do any work with the WebBrowser control, you'll find yourself doing a lot of hacky stuff.</p> <p>This is the easiest way that I know of to do this. You need to inject JavaScript to override the alert function... something along the lines of injecting this JavaScript function:</p> <pre><code>window.alert = function () { } </code></pre> <p>There are <em>many ways to do this</em>, but it is very possible to do. One possibility is to hook an implementation of the <a href="http://msdn.microsoft.com/en-us/library/aa768283.aspx" rel="noreferrer">DWebBrowserEvents2</a> interface. Once this is done, you can then plug into the NavigateComplete, the DownloadComplete, or the DocumentComplete (or, as we do, some variation thereof) and then call an InjectJavaScript method that you've implemented that performs this overriding of the window.alert method.</p> <p>Like I said, hacky, but it works :)</p> <p>I can go into more details if I need to.</p>
<p>Are you trying to implement a web robot? I have little experience in using the hosted IE control but I did completed a few Win32 projects tried to use the IE control. Disabling the popups should be done via the event handlers of the control as you already did, but I found that you also need to change the 'Disable script debugging xxxx' in the IE options (or you could modify the registry in your codes) as cjheath already pointed out. However I also found that extra steps needed to be done on checking the navigating url for any downloadable contents to prevent those open/save dialogs. But I do not know how to deal with streaming files since I cannot skip them by looking at the urls alone and in the end I turned to the Indy library saving me all the troubles in dealing with IE. Finally, I remember Microsoft did mention something online that IE is not designed to be used as an OLE control. According to my own experience, every time the control navigates to a new page did introduce memory leaks for the programs!</p>
10,312
<p>I'm trying to get the contents of a XML document element, but the element has a colon in it's name.</p> <p>This line works for every element but the ones with a colon in the name:</p> <pre><code>$(this).find("geo:lat").text(); </code></pre> <p>I assume that the colon needs escaping. How do I fix this?</p>
<p>Use a backslash, which itself should be escaped so JavaScript doesn't eat it:</p> <pre><code>$(this).find("geo\\:lat").text(); </code></pre>
<p>if you have a <strong>jquery selector problem with chrome or webkit</strong> not selecting it try </p> <pre><code>$(this).find('[nodeName=geo:lat]').text(); </code></pre> <p>this way it works in all browsers</p>
15,647
<p>Is there a way to set a maximum size for files that can be check in into source control under Team Foundation Server 2005 or 2008?</p> <p>In the past, when we worked with SourceSafe there were several cases were developers decided to checkin a 500mb data file to source control. </p> <p>I don't know what such a thing will do to TFS - and actually, I don't want to find out.</p> <p><strong>Edit:</strong> Custom checkin policy is not a viable solution for two reasons:</p> <ol> <li><p>it is done in the client side - I want the server to protect itself from such an abuse</p></li> <li><p>custom checkin policy can be overridden by the user.</p></li> </ol>
<p>I'm a little confused by the question, but here are some thoughts:</p> <ol> <li><code>DataGridView</code> has an <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.autogeneratecolumns.aspx" rel="nofollow noreferrer"><code>AutoGenerateColumn</code>s</a> property; if you don't want it to create its own columns, set this to false</li> <li>To bind to existing columns, the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumn.datapropertyname.aspx" rel="nofollow noreferrer"><code>DataPropertyName</code></a> must be set on each</li> <li><code>DataGridView</code> (in cmomon with any list control using <code>TypeDescriptor</code>) will hugely prefer <code>List&lt;T&gt;</code> (for some <code>T</code> != <code>object</code>) to <code>ArrayList</code>, since it can get meta-data even for an empty list. In general, in 2.0 using <code>ArrayList</code> is a mistake.</li> </ol>
<p>I can only give a partial answer but I think the reason that </p> <pre><code>public void tabControl1_SelectedIndexChanged(object sender, EventArgs e) { libDataGrid.DataSource = this.manager.Lib.LibList; libDataGrid.Refresh(); } </code></pre> <p>isn't working, is because you need to add this line where tabControl1 is being initialized. I've had this problem where VS won't do this itself.</p> <pre><code>tabControl1.SelectedIndexChanged += new EventHandler(tabControl1_SelectedIndexChanged); </code></pre>
41,230
<p>How can I get a user-defined function to re-evaluate itself based on changed data in the spreadsheet?</p> <p>I tried <strong><kbd>F9</kbd></strong> and <strong><kbd>Shift</kbd>+<kbd>F9</kbd></strong>.</p> <p>The only thing that seems to work is editing the cell with the function call and then pressing Enter.</p>
<p>You should use <code>Application.Volatile</code> in the top of your function:</p> <pre><code>Function doubleMe(d) Application.Volatile doubleMe = d * 2 End Function </code></pre> <p>It will then reevaluate whenever the workbook changes (if your calculation is set to automatic).</p>
<pre><code>Public Sub UpdateMyFunctions() Dim myRange As Range Dim rng As Range 'Considering The Functions are in Range A1:B10 Set myRange = ActiveSheet.Range("A1:B10") For Each rng In myRange rng.Formula = rng.Formula Next End Sub </code></pre>
3,223
<p>I am using xsl to control the output of my xml file, but the BOM character is being added.</p>
<pre><code># vim file.xml :set nobomb :wq </code></pre>
<p>I was under the impression that XML is encouraged to be written in Unicode, in some Unicode encoding, and that certain Unicode encodings are specified to contain an initial byte-order mark. Without that byte-order mark, your file is no longer correctly encoded in a Unicode encoding and therefore no longer correct XML. XML processors are encouraged to be unforgiving, to fail immediately on the slightest error (such as an incorrect Unicode encoding). What kinds of XML processors are you looking to break?</p> <p>Obviously, stripping a byte-order mark from a UTF-8 encoded document makes that document appear to be ASCII encoded (not Unicode), and some text processors are capable only of using ASCII encoded documents. Is this what you're working with?</p>
37,763
<p>What are your opinions on developing for the command line first, then adding a GUI on after the fact by simply calling the command line methods?</p> <p>eg.</p> <blockquote> <p>W:\ todo AddTask "meeting with John, re: login peer review" "John's office" "2008-08-22" "14:00" </p> </blockquote> <p>loads <code>todo.exe</code> and calls a function called <code>AddTask</code> that does some validation and throws the meeting in a database. </p> <p>Eventually you add in a screen for this: </p> <pre> ============================================================ Event: [meeting with John, re: login peer review] Location: [John's office] Date: [Fri. Aug. 22, 2008] Time: [ 2:00 PM] [Clear] [Submit] ============================================================ </pre> <p>When you click submit, it calls the same AddTask function.</p> <p>Is this considered: </p> <ul> <li>a good way to code</li> <li>just for the newbies</li> <li>horrendous!.</li> </ul> <p><strong>Addendum:</strong> </p> <p>I'm noticing a trend here for "shared library called by both the GUI and CLI executables." Is there some compelling reason why they would have to be separated, other than maybe the size of the binaries themselves? </p> <p>Why not just call the same executable in different ways:</p> <ul> <li><code>"todo /G"</code> when you want the full-on graphical interface</li> <li><code>"todo /I"</code> for an interactive prompt <em>within</em> <code>todo.exe</code> (scripting, etc)</li> <li>plain old <code>"todo &lt;function&gt;"</code> when you just want to do one thing and be done with it.</li> </ul> <p><strong>Addendum 2:</strong> </p> <p>It was mentioned that "the way [I've] described things, you [would] need to spawn an executable every time the GUI needs to do something." </p> <p>Again, this wasn't my intent. When I mentioned that the example GUI called "the same <code>AddTask</code> function," I didn't mean the GUI called the command line program each time. I agree that would be totally nasty. I had intended (see first addendum) that this all be held in a single executable, since it was a tiny example, but I don't think my phrasing necessarily precluded a shared library.</p> <p>Also, I'd like to thank all of you for your input. This is something that keeps popping back in my mind and I appreciate the wisdom of your experience.</p>
<p>I would go with building a library with a command line application that links to it. Afterwards, you can create a GUI that links to the same library. Calling a command line from a GUI spawns external processes for each command and is more disruptive to the OS.</p> <p>Also, with a library you can easily do unit tests for the functionality.</p> <p>But even as long as your functional code is separate from your command line interpreter, then you can just re-use the source for a GUI without having the two kinds at once to perform an operation.</p>
<p><strike>Command line tools generate less events then GUI apps and usually check all the params before starting. This will limit your gui because for a gui, it could make more sense to ask for the params as your program works or afterwards. </p> <p>If you don't care about the GUI then don't worry about it. If the end result will be a gui, make the gui first, then do the command line version. Or you could work on both at the same time.</strike></p> <p>--Massive edit--</p> <p>After spending some time on my current project, I feel as though I have come full circle from my previous answer. I think it is better to do the command line first and then wrap a gui on it. If you need to, I think you can make a great gui afterwards. By doing the command line first, you get all of the arguments down first so there is no surprises (until the requirements change) when you are doing the UI/UX. </p>
3,949
<p>I would like to change the name of my SQL Server instance. Is there a simple way of doing this or is a significant effort required? Note, this is a named instance - not the default instance.</p>
<p>The only way is a reinstall. See this similar thread for more info: <a href="https://stackoverflow.com/questions/35026/sql-server-convert-a-named-instance-to-default-instance#35641">SQL Server, convert a named instance to default instance?</a></p>
<p>Renaming does't work well on the registry. Install a new isntance.</p>
18,875
<p>I have an application that we're trying to migrate to 64bit from 32bit. It's .NET, compiled using the x64 flags. However, we have a large number of DLLs written in FORTRAN 90 compiled for 32bit. The functions in the FORTRAN DLLs are fairly simple: you put data in, you pull data out; no state of any sort. We also don't spend a lot of time there, a total of maybe 3%, but the calculation logic it performs is invaluable.</p> <p>Can I somehow call the 32bit DLLs from 64bit code? MSDN suggests that I can't, period. I've done some simple hacking and verified this. Everything throws an invalid entry point exception. The only possible solution i've found so far is to create COM+ wrappers for all of the 32bit DLL functions and invoke COM from the 64bit process. This seems like quite a headache. We can also run the process in WoW emulation, but then the memory ceiling wouldn't be increased, capping at around 1.6gb.</p> <p>Is there any other way to call the 32bit DLLs from a 64bit CLR process?</p>
<p>You'll need to have the 32-bit dll loaded into a separate 32-bit process, and have your 64 bit process communicate with it via interprocess communication. I don't think there is any way a 32-bit dll can be loaded into a 64 bit process otherwise.</p> <p>There is a pretty good article here:</p> <p><a href="http://blog.mattmags.com/2007/06/30/accessing-32-bit-dlls-from-64-bit-code/" rel="noreferrer">Accessing 32-bit DLLs from 64-bit code</a></p>
<p>John's answer is correct if you don't want to recompile your existing dlls; however that might be an option for you as well. </p> <p>Our team is currently migrating our x86 FORTRAN code to x64 to increase the memory ceiling.</p>
15,628
<p>I'm trying to click on a link using jquery. There only appears to be a click event that replicates "onclick" (i.e user input). Is it possible to use jquery to actually click a link?</p>
<p>From your answer: </p> <pre><code>$("a[0]") </code></pre> <p>is not a valid selector. to get the first a on the page use: </p> <pre><code>$("a:first") </code></pre> <p>or </p> <pre><code>$("a").eq(0). </code></pre> <p>So for the selector in your answer:</p> <pre><code>$("table[1]/tr[1]/td[1]/a").trigger('click'); </code></pre> <p>write </p> <pre><code>$("table").eq(1).children("tr").eq(1).children('td').eq(1).children('a').click(); </code></pre> <p>Note how this will click all the links in the second table cell of the second table row in the second table on your page.<br> If you use this method to redirect the page to the href of the a the following method is slightly nicer:</p> <pre><code>document.location = $("table").eq(1).children("tr").eq(1).children('td').eq(1).children('a').attr('href'); </code></pre> <p>Note how this will set the document location to the href of the first a found in the second table cell of the second table row found in the second table on the page.<br> If you want to match the first elements use eq(0) instead of eq(1). </p> <p><B>EDIT</B><br> If you really want to do this 1337-haxxor</p> <pre><code>$("table:eq(1) &gt; tr:eq(1) &gt; td:eq(1) &gt; a").click(); </code></pre> <p>however I think the other method is more readible.</p> <p><b>EDIT</b></p> <p>Okay, from you next answer/question thingie<br> How about not actually clicking on the link but just setting the document.location string to it:</p> <pre><code>document.location = $("table").eq(0).children("tr").eq(0).children('td').eq(0).children('a').eq(0).attr('href'); </code></pre>
<p>Try it this way:</p> <pre><code>$("table:first").find("tr:first").find("td:first").find("a:first").click(); </code></pre> <p>That will trigger the onclick event of the the first a in the first cell of the first row in the first table...and its very readable in itself.</p>
44,715
<p>how do I get information about a photo like the author, the license using PHP?</p>
<p>This information is all available through the <a href="http://www.flickr.com/services/api/" rel="nofollow noreferrer">Flickr API</a>, if you poke around their docs you may find what you're looking for.</p>
<p>This information is all available through the <a href="http://www.flickr.com/services/api/" rel="nofollow noreferrer">Flickr API</a>, if you poke around their docs you may find what you're looking for.</p>
38,626
<p>I have created a pretty basic Flash website for a client and am having an issue programming a Client Login feature that he would like. Currently, if I navigate to the site and click Client Login, it takes me to a login page. The way I need this to work is -- within the Flash, using ActionScript 2.0 -- have the user enter their UserID and Password and click to login, which submits POST vars to the form action of the Client Login website.</p> <p>Is this possible/legal to do from a different domain? How would I go about doing this, assuming it's possible?</p>
<p>Try this:</p> <pre><code>myVars = new LoadVars(); myVars.username = username.text; myVars.password = pwd.text; myVars.onLoad = function(success) { trace("yay!"); else { trace("try again"); } } myVars.sendAndLoad("login.php", myVars, "POST"); </code></pre>
<p>So, I get "yay!" with the code provided below (yours had an error in it). However, I need to be redirected to the resulting "logged-in" page. How do I do that?</p> <pre> myVars = new LoadVars(); myVars.txtUserID = "some_user"; myVars.txtPassword = "some_password"; myVars.__VIEWSTATE = "dDw3MTcxMTg3ODM7dDw7bDxpPDM+O2k8NT47PjtsPHQ8cDxsPFRleHQ7PjtsPGRlbW87Pj47Oz47dDw7bDxpPDE+O2k8Mz47aTw1Pjs+O2w8dDxwPGw8VGV4dDs+O2w8YmFja2dyb3VuZC1jb2xvcjojZjZmNmY2XDtjb2xvcjojMzMzMzMzXDs7Pj47Oz47dDxwPDtwPGw8c3R5bGU7PjtsPHdpZHRoOjEwMHB4XDs7Pj4+Ozs+O3Q8cDw7cDxsPHN0eWxlOz47bDx3aWR0aDoxMDBweFw7Oz4+Pjs7Pjs+Pjs+Pjs+56k0UDxn5ED61lGLjP0fIkStm6o="; myVars.onLoad = function(success) { if (success) { trace("yay!"); } else { trace("try again"); } } myVars.sendAndLoad("http://www.buildertrend.net/loginFrame.aspx?builderID=35&amp;bgcolor=%23f6f6f6&amp;fcolor=%23333333&amp;uwidth=100&amp;pwidth=100", myVars, "POST"); </pre>
28,680
<p>I've got a bunch of properties which I am going to use read/write locks on. I can implement them either with a <code>try finally</code> or a <code>using</code> clause.</p> <p>In the <code>try finally</code> I would acquire the lock before the <code>try</code>, and release in the <code>finally</code>. In the <code>using</code> clause, I would create a class which acquires the lock in its constructor, and releases in its Dispose method.</p> <p>I'm using read/write locks in a lot of places, so I've been looking for ways that might be more concise than <code>try finally</code>. I'm interested in hearing some ideas on why one way may not be recommended, or why one might be better than another.</p> <p>Method 1 (<code>try finally</code>):</p> <pre><code>static ReaderWriterLock rwlMyLock_m = new ReaderWriterLock(); private DateTime dtMyDateTime_m public DateTime MyDateTime { get { rwlMyLock_m .AcquireReaderLock(0); try { return dtMyDateTime_m } finally { rwlMyLock_m .ReleaseReaderLock(); } } set { rwlMyLock_m .AcquireWriterLock(0); try { dtMyDateTime_m = value; } finally { rwlMyLock_m .ReleaseWriterLock(); } } } </code></pre> <p>Method 2:</p> <pre><code>static ReaderWriterLock rwlMyLock_m = new ReaderWriterLock(); private DateTime dtMyDateTime_m public DateTime MyDateTime { get { using (new ReadLock(rwlMyLock_m)) { return dtMyDateTime_m; } } set { using (new WriteLock(rwlMyLock_m)) { dtMyDateTime_m = value; } } } public class ReadLock : IDisposable { private ReaderWriterLock rwl; public ReadLock(ReaderWriterLock rwl) { this.rwl = rwl; rwl.AcquireReaderLock(0); } public void Dispose() { rwl.ReleaseReaderLock(); } } public class WriteLock : IDisposable { private ReaderWriterLock rwl; public WriteLock(ReaderWriterLock rwl) { this.rwl = rwl; rwl.AcquireWriterLock(0); } public void Dispose() { rwl.ReleaseWriterLock(); } } </code></pre>
<p>From MSDN, <a href="http://msdn.microsoft.com/en-us/library/yh598w02.aspx" rel="noreferrer">using Statement (C# Reference)</a></p> <blockquote> <p>The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler. The code example earlier expands to the following code at compile time (note the extra curly braces to create the limited scope for the object):</p> </blockquote> <pre><code>{ Font font1 = new Font("Arial", 10.0f); try { byte charset = font1.GdiCharSet; } finally { if (font1 != null) ((IDisposable)font1).Dispose(); } } </code></pre> <p>So basically, <strong>it is the same code but with a nice automatic null-checks and an extra scope for your variable</strong>. The documentation also states that it "ensures the correct use of IDisposable object" so you might as well gets even better framework support for any obscure cases in the future.</p> <p>So go with option 2.</p> <p>Having the variable <em>inside a scope</em> that ends immediately after it's no longer needed is also a plus.</p>
<p>Silly me. There's a way to make that even simpler by making the locked methods part of each instance (instead of static like in my previous post). Now I really prefer this because there's no need to pass `rwlMyLock_m' off to some other class or method.</p> <pre><code>class StackOTest { private delegate DateTime ReadLockMethod(); private delegate void WriteLockMethod(); static ReaderWriterLock rwlMyLock_m = new ReaderWriterLock(); private DateTime dtMyDateTime_m; public DateTime MyDateTime { get { return ReadLockedMethod( delegate () { return dtMyDateTime_m; } ); } set { WriteLockedMethod( delegate () { dtMyDateTime_m = value; } ); } } private DateTime ReadLockedMethod(ReadLockMethod method) { rwlMyLock_m.AcquireReaderLock(0); try { return method(); } finally { rwlMyLock_m.ReleaseReaderLock(); } } private void WriteLockedMethod(WriteLockMethod method) { rwlMyLock_m.AcquireWriterLock(0); try { method(); } finally { rwlMyLock_m.ReleaseWriterLock(); } } } </code></pre>
35,220
<p>Are any of you aware of a library that helps you build/manipulate SQL queries, that supports JOIN's?</p> <p>It would give a lot of flexibility i'd think if you have something where you could return an object, that has some query set, and still be able to apply JOIN's to it, subqueries and such.</p> <p>I've search around, and have only found SQL Builder, which seems very basic, and doesn't support joins. Which would be a major feature that would really make it useful.</p>
<p>Maybe you can try an <a href="http://en.wikipedia.org/wiki/Object-relational_mapping" rel="noreferrer">ORM</a>, like <a href="http://propel.phpdb.org/trac/" rel="noreferrer">Propel</a> or <a href="http://www.doctrine-project.org/" rel="noreferrer">Doctrine</a>, they have a nice programmatic query language, and they return you arrays of objects that represent rows in your database...</p> <p>For example with Doctrine you can do joins like this:</p> <pre><code>$q = Doctrine_Query::create(); $q-&gt;from('User u') -&gt;leftJoin('u.Group g') -&gt;innerJoin('u.Phonenumber p WITH u.id &gt; 3') -&gt;leftJoin('u.Email e'); $users = $q-&gt;execute(); </code></pre> <p>And with Propel:</p> <pre><code>$c = new Criteria(AuthorPeer::DATABASE_NAME); $c-&gt;addJoin(AuthorPeer::ID, BookPeer::AUTHOR_ID, Criteria::INNER_JOIN); $c-&gt;addJoin(BookPeer::PUBLISHER_ID, PublisherPeer::ID, Criteria::INNER_JOIN); $c-&gt;add(PublisherPeer::NAME, 'Some Name'); $authors = AuthorPeer::doSelect($c); </code></pre> <p>and you can do a lot more with both...</p>
<p>You can use lenkorm it's very easy:</p> <p>select('contents)->left('categories ON categories.category.id = contents.category_id)->where('content_id = 1')->result();</p> <p>or you can use as: </p> <p>select('contents)->left('categories->using(categoru_id)->where('content_id = 1')->result();</p> <p><a href="https://github.com/guncebektas/lenkorm" rel="nofollow">Download it from github</a></p>
26,573
<p>I have a basic model in which i have specified some of the fields to validate the presence of. in the create action in the controller i do the standard:</p> <pre><code>@obj = SomeObject.new(params[:some_obj]) if @obj.save flash[:notice] = "ok" redirect... else flash[:error] = @obj.errors.full_messages.collect { |msg| msg + "&lt;br/&gt;" } redirect to new form end </code></pre> <p>however when i redirect to the new form, the errors show, but the fields are empty. is there a way to repopulate the fields with the entered values so the errors can be corrected easily?</p>
<p>You <code>render :action =&gt; :new</code> rather than redirecting.</p>
<p>Capture <code>@obj</code> in the flash hash as well, and then check for it in the <code>new</code> action.</p> <pre><code>@obj = SomeObject.new(params[:some_obj]) if @obj.save flash[:notice] = "ok" # success else flash[:error] = @obj.errors.full_messages.collect { |msg| msg + "&lt;br/&gt;" } flash[:obj] = @obj # redirect to new form end </code></pre> <p>In <code>new</code>:</p> <pre><code>@obj = flash[:obj] || MyClass.new </code></pre>
19,141
<p><strike>All of the errors are on auto-generated files, not within the files that were created by me. Here are a few of them:</p> <pre><code>'Context' is not a member of 'auth_cookies' 'ProcessRequest' cannot be declared 'Overrides' because it does not override a sub in a base class 'Server' is not a member of 'ASP.auth_cookies_aspx' Class 'auth_cookies_aspx' must implement 'Sub ProcessRequest(context As HttpContext)' for interface 'System.Web.IHttpHandler' </code></pre> <p>Any help would be appreciated.</strike></p> <p>EDIT: found out that the file it was looking for wasn't there, fixed that problem and that eliminated all the errors except one:</p> <pre><code> Error-5: There can be only one 'page' directive. &gt;&gt; C:\Users\darren\Documents\Visual Studio 2008\WebSites\gs_ontheweb\auth\cookies.aspx </code></pre> <p>This is the contents of the <strong><code>cookies.aspx</code></strong> page:</p> <pre><code>&lt;%@ Page Language="VB" MasterPageFile="~/theMaster.master" AutoEventWireup="false" CodeFile="cookies.aspx.vb" Inherits="auth_cookies" title="NOM COOKIES" %&gt; </code></pre> <p>UPDATE: Turns out one of linked files had a link to another .aspx page, causing 2 page directives to be loaded.</p>
<p>Did you put a <code>&lt;%@Page%&gt;</code> directive in your Master page? It should only have a <code>&lt;%@Master%&gt;</code> directive.</p>
<p>No, the header of my MasterPage is:</p> <pre><code>&lt;%@ Master Language="VB" CodeFile="theMaster.master.vb" Inherits="theMaster" %&gt; </code></pre> <p>There is no <code>&lt;%@Page%&gt;</code> directive on the MasterPage.</p>
35,137
<p>We would like to give access to some of our EJBs from Excel. The goal is to give an API usable from VBA.</p> <p>Our EJBs are mostly Stateless Session Beans that do simple CRUD operations with POJOs.</p> <p>Some possible solutions: </p> <ul> <li>Exposing the EJBs as WebServices and create a VB/C# dll wrapping them,</li> <li>Using Corba to access the EJBs from C#,</li> <li>Creating a COM Library that uses Java to access the EJBs,</li> </ul> <p>Pointers to frameworks for these solution or other ideas are welcome.</p>
<p>You could take a look at <a href="http://www.codeproject.com/KB/cs/iiop_net_and_ejb.aspx" rel="nofollow noreferrer">IIOP.NET</a>, which addresses this issue.</p>
<p>I highly recommend <a href="http://www.ikvm.net/" rel="nofollow noreferrer">IKVM</a>. It is a java byte code to .NET assembly compiler (i.e. JAR --> DLL) and I have used it to create live JMX links and listeners in an Excel automation server. It should not be difficult for you to create a .NET assembly of your EJB client stubs and supporting libraries.</p> <p>//Nicholas</p>
11,668
<p>I am working on a legacy project in <code>VC++/Win32/MFC</code>. Recently it became a requirement that the application work on a <strong>tablet pc</strong>, and this ushered in a host of new issues. I have been able to work with, and around these issues, <strong>but am left with one wherein I could use some expert suggestions.</strong></p> <p>I have a particular bug that is induced by the "lift" of the stylus off of the active surface. Basically the mouse cursor disappears and then reappears when you "press" it back onto the screen.</p> <p>It makes sense that this is unaccounted for in the application. you can't <strong>lift</strong> the cursor on a desktop pc. So what I am looking for is a good overview on what happens (in terms of windows messages, etc.) when the lift occurs. Does this translate to just focus changes and mouseover events? My bug seems to also involve cursor changes (may not be lift related though). Certainly the unexpected "lift" is breaking the state of the application's tool processing.</p> <p><strong>So the tangible questions are:</strong></p> <ol> <li>What happens when a stylus "lift" occurs? A press?</li> <li>What API calls can be used to detect this? Does it just translate into standard messages with flags/values set?</li> <li>Whats a good way to test/emulate this when your development pc is a desktop? Am I just flying blind here? (I only have periodic access to a tablet pc)</li> <li>What represents correct behavior or best practice for tablet stylus awareness?</li> </ol> <p>Thanks for your consideration, ee</p>
<p>As a tablet user I can answer a few of your questions.</p> <p>First:</p> <blockquote> <p>You cannot very easily keep a "keyboard focus" on a window when the stylus has to trail out of the focused window to push a key on the virtual keyboard.</p> </blockquote> <p>Most of the virtual keyboards I've used (The windows tablet input panel and one under ubuntu) allow the program they are typing in to keep "keyboard focus."</p> <blockquote> <p>What happens when a stylus "lift" occurs? A press?</p> </blockquote> <p>Under Windows, the pressure value drops, but outside of that, there is no event. (I don't know about linux.)</p> <blockquote> <p>What API calls can be used to detect this? Does it just translate into standard messages with flags/values set?</p> </blockquote> <p>As mentioned above, if you can get the pressure value, you can use that.</p> <blockquote> <p>Whats a good way to test/emulate this when your development pc is a desktop? Am I just flying blind here? (I only have periodic access to a tablet pc)</p> </blockquote> <p>When the stylus is placed down elsewhere, the global coordinates of the pointer change, so, you can emulate the sudden pointer move with anything that allows you to change the global pointer values. (The Robot class in Java makes this fairly easy.)</p> <blockquote> <p>What represents correct behavior or best practice for tablet stylus awareness?</p> </blockquote> <p>I'd recommend you read what Microsoft has to say, the MSDN website has a number of excellent articles. (<a href="http://msdn.microsoft.com/en-us/library/ms704849(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms704849(VS.85).aspx</a>) I'll point out that the size of the buttons on your applications makes a HUGE difference.</p> <p>Hope this was of help.</p>
<p>As I understand it, there is no "lift" event -- the only event happens when the stylus is brought back to the screen later. Of course, this depends on your specific driver and so on.</p> <p>Worse, the bug you describe might be reproducible with just a typical mouse. Try moving the mouse as fast as you can -- it will almost certainly jump several pixels at once. Or even dozens or hundreds, if you have the mouse settings configured for the highest pointer speed. One update, the mouse might be at 100,100. The very next update, it could be at 200,300.</p>
10,598
<p>Is there an intuitive way, or a good mnemonic, for understanding the correspondence between colors and their hexadecimal values?</p>
<p>You just have to remember that the scale is 00 (no color effect) through FF (full color effect) and the three parts of the triplet are red, green and blue.</p> <p>000000 is black (i.e., no color) and FFFFFF is white (mixing all three primary colors).</p> <p>The hard bit is remembering the mixtures, which I use the following mnemonics for:</p> <ul> <li><strong>Really good yams</strong>: Red + Green = Yellow (potatoes are my favorite food).</li> <li><strong>Really bad prunes</strong>: Red + Blue = Purple (I really hate prunes).</li> <li><strong>Good/bad apples</strong>: Green + Blue = Aqua (I'm indifferent about apples).</li> </ul> <p>Obviously, you may have to come up with your own mnemonics if you food tastes differ from mine. But I find that's the easiest way for me.</p> <p>Then it's just a matter of varying the quantities to add a little more red or little less blue and so on. I generally only use values of 00, 40, 80, C0 and FF since that gives you a 125-color palette to choose from and I don't want an abundance of choices to slow me down.</p>
<p>Well, monitors use an 'RGB' colorscheme. The order of the colors in the hexadecimal number is RRGGBB. So just remembering the name of the colorscheme tells you what goes where. Then you can parse the #RRGGBB as three numbers RR, GG and BB.</p> <p>The higher the number the brighter that particular component.</p> <p>Then you just need to remember the additive color wheel from grade school. ;)</p>
34,592
<p>When a web site is licensed under Creative Commons, I use the <a href="http://microformats.org/wiki/rel-license" rel="noreferrer">rel-license microformat</a>. When a web site is licensed under regular copyright, I have a boring paragraph element.</p> <pre><code>&lt;p id="copyright"&gt;&amp;copy; 2008 Example Corporation&lt;/p&gt; </code></pre> <p>That id attribute on there is just for CSS styling purposes. I'm wondering if there's some better way to markup a copyright notice that is more semantic. Is this a job for Dublin Core metadata? If so, how do I go about it? (I've never used Dublin Core before.)</p> <p>Some web sites advocate using a meta tag in the head element:</p> <pre><code>&lt;meta name="copyright" content="name of owner"&gt; </code></pre> <p>Which might be seen by search engines, but doesn't replace the user-visible notice on the page itself.</p>
<p>Thanks to Owen for pointing me in the direction of RDFa, I think I've got the solution now:</p> <pre><code>&lt;div id="footer" xmlns:dc="http://purl.org/dc/elements/1.1/"&gt; &lt;p id="copyright" property="dc:rights"&gt;&amp;copy; &lt;span property="dc:dateCopyrighted"&gt;2008&lt;/span&gt; &lt;span property="dc:publisher"&gt;Example Corporation&lt;/span&gt; &lt;/p&gt; &lt;/div&gt; </code></pre> <p>Depending on the situation, it might be better to use dc:creator instead of dc:publisher. From the Dublin Core web site:</p> <blockquote>If the Creator and Publisher are the same, do not repeat the name in the Publisher area. If the nature of the responsibility is ambiguous, the recommended practice is to use Publisher for organizations, and Creator for individuals. In cases of lesser or ambiguous responsibility, other than creation, use Contributor.</blockquote> <p>I will also be adding a meta tag to my head element for search engines that don't support RDFa yet.</p> <pre><code>&lt;meta name="copyright" content="&amp;copy; 2008 Example Corporation" /&gt; </code></pre>
<p>Why not use the CC format, but indicate that no rights are granted?</p> <p>In any case, the main problem with the use of the CC formats is that people do not clearly identify which elements of the webpage that they appear on they apply to.</p>
31,762
<p>I'm interested in developing applications on the iPhone and being a .NET &amp; ActionScript developer I'm a bit scared from the learning curve of Objective-C Cocoa Touch programming. I know that Adobe has Flash player ready for iPhone and I think that Apple doesn't want it just for political reason. Is there any easy alternative to build applications that access the internal GPS, phone etc. without using Objective-C and Cocoa Touch?</p>
<p>Currently there is no other way. As a long time Apple Fanboy I've learnt one thing time and time again "It's Steve's way or the highway". If Steve says no Flash then you can bet your sweet little bippy that there will be no Flash. So either develop a web app, or learn Objective-C. I'm a JAVA head and I learnt all I needed to know in about a month, in my spare time, so it's not as bad as it first seems.</p>
<p>Flash is a proprietary runtime. Why would apple want this on their device?</p> <p>Not to mention the fact that Flash developers routinely hog CPU cycles on the web. Ever have your fan spin up while on a web page with heavy flash objects hogging your cpu?</p> <p>I don't see Apple ever supporting Flash and I am glad they won't. The web is open standards, and Flash is owned by one company.</p>
47,690
<p>I would like to inject binary data into an object in JavaScript. Is there a way to do this? </p> <p>i.e.</p> <pre><code>var binObj = new BinaryObject('101010100101011'); </code></pre> <p>Something to that effect. Any help would be great.</p>
<p>You can use parseInt:</p> <p><code>var bin = parseInt('10101010', 2);</code></p> <p>The second argument (the radix) is the base of the input.</p>
<p>Javascript doesn't provide a mechanism to load an object in any form other than simple strings.</p> <p>Closest you can do is serializing the object to a string, optionally encrypting/compressing it, sending it to the browser, and decrypting/decompressing if necessary, checking for sanity, eval() and pray().</p> <p>Instead of using eval (which is not quite safe), you can use your own format (alternatively, xml or json for which there are plenty of libs) and parse it yourself.</p> <p>As a side note, if you want this for obfuscation after the browser gets the usable data (after decrypting/decompressing), it is too easy to circumvent.</p>
42,475
<p>Please tell me if it is possible to do the following:</p> <ul> <li>create an instance of a specific class in Java</li> <li>pass it to JRuby to do something with it</li> <li>continue using the "modified" version in Java</li> </ul> <p>May you provide a small working example?</p> <p>EDIT: It turns out that embedding was the simplest way to achieve this. More information is available on <a href="http://github.com/jruby/jruby/wiki/RedBridge" rel="nofollow noreferrer">Embedding JRuby</a>.</p>
<p>Yes it's possible. <a href="https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby" rel="nofollow noreferrer">This page</a> on the JRuby wiki should get you started.</p>
<p>It depends on what you mean by "do something". If you mean "redefine a method", then the answer is no, not really. The new method will be used by jruby, but any calls to the method in java will continue to invoke the old method.</p>
39,393
<p>I'm getting a pet bird soon, and I know that off-gassing from heating PTFE above 300&nbsp;°C creates noxious fumes, which are bird-killer<sup>1</sup>. To try to prevent even the chance of that I'm replacing my hotend with an all-metal one. I have an E3D v6 1.75&nbsp;mm, which I noticed still uses a PTFE tube at the cold side (the 3&nbsp;mm version apparently doesn't, but 1.75&nbsp;mm filament is what my printer uses, so there we are).</p> <p>If I'm reading the instructions correctly, it sounds like the heatsink shouldn't even get warm to the touch, and if that's the case I'm not worried as long as things go well. What I'm still worried about is what happens if the heatsink cooling fan fails. I plan to plug the fan into the always-on 12&nbsp;V port on my board (SKR 1.3): if I do, then is it possible to set my firmware (currently Marlin 2.0.4.4) to stop a print if the fan fails?</p> <p>If I can't get the firmware to stop on fan failure, then is there a 1.75&nbsp;mm all-metal hotend out there that doesn't require the use of PTFE on the cold side?</p> <hr> <p>1- <a href="http://healthline.com/nutrition/nonstick-cookware-safety" rel="nofollow noreferrer">Here:</a> "at temperatures above 570°F (300°C), Teflon [PTFE] coatings on nonstick cookware start to break down, releasing toxic chemicals into the air <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3276392/" rel="nofollow noreferrer">(14)</a>"</p>
<p>First of all, we need to discuss the failure mode and what can be done. LEt's do a</p> <h2>Failure mode 1: coolend-fan stops working.</h2> <p>Let's assume the coolend-fan for whatever reason (cut cable, defect fan, burnt board...) stops working. As a result, the coolend starts to rise in temperature, as it doesn't drain as much heat into the room air as before. This directly leads to an increase of the hotend temperature, which results in a case differentiation:</p> <ul> <li>The hotend does not cope well with the loss of the heatsink and it triggers Thermal Runaway protection as for a given voltage bump the heating gets too high - the print gets aborted before the hotend reaches a temperature above 275 °C.</li> <li>The hotend does not trigger Thermal Runaway Protection but the controller alters its heating behavior and works the heater on a lower duty cycle. As long as the hotend temperature is ordered to stay low enough, we will get a lot of extrusion problems from heat-creep, but the PTFE seated into the heatbreak stays below the heater break's temperature, as the thermal mass of the coolend alone draws away thermal energy into the room, even without the fan that keeps it at room temperature. As long as you don't print at above 300 °C and the thermosensor is intact, the failure mode does not release any fumes that could result in Polytetrafluoroethylene Toxicosis.</li> </ul> <h2>Failure Mode 2: coolend fan stops Working, no TRP, Thermosensor OK</h2> <p>But what if TRP is off? Let's look at this Double Failure: The hotend does not trigger Thermal Runaway Protection (or it was turned off to begin with) and the temperature increases due to the lack of cooling from the coolend.</p> <p>As the hotend reaches 275 °C (few printers print that hot, and they use specialized setups), it should trigger the next safety line: a MaxTemp error and cut power. Heating stops before the coolend gets to the dangerous zone of 300 °C, as the coolend always is less hot than the heater block.</p> <h2>Failure Mode 3: no TRP, Thermosensor broken</h2> <p>We are getting desperate and turn off TRP, <em>then</em> break or disconnect the thermosensor to get a static low temperature. NOW we are getting serious, as only with such a failure we can trick our controller to continuously heat the heater cartridge and not trigger any of the error conditions. Only now there is the mere possibility to heat the coolend over 300 °C.</p> <p>Marlin Firmware is designed to carefully work with checks and balances to keep the heater block in the wanted margin, and it would need a <strong>deliberate manipulation</strong> of the software to <strong>disable</strong> all safety features <strong>in conjunction</strong> with the failure of the thermosensor for the printer to go into Thermal runaway in such a degree that the coolend goes over 300 °C. And then you have different problems: your printer surely is turning into a molten pile in that failure mode. The presence or absence of the coolend fan would just delay the inevitable, should you run such a fire hazard-machine</p> <h1>Conclusion</h1> <p><a href="https://3dprinting.stackexchange.com/questions/12153/updating-marlin-firmware-step-by-step-guide">Configure and install a recent firmware distribution</a> (Marlin 1.1.9 and Marlin 2.x come with TRP enabled by default) and be sure to have MaxTemp enabled at 275 °C and Thermal Runaway Protection on, and you have a 3-layer safety against PTFE-fumes.</p> <p>Adding more layers surely is possible, but the cost-effect calculation gets worse starting there.</p>
<p>It is doubtful that small PTFE inside hotend could produce that kind of dangerous gas leak. But another thing should be considered: the PTFE tube inside hotend WILL degrade over time and will need replacement.</p> <p>For last several years I had numerous experiments with all kind of solutions including my own designs made. And recently I found the best and all metal solution: Volcano 20mm heater + M6 stainless throat + normal SHORT E3D nozzle (not the Volcano nozzle but the normal one). Basically this solution put the problematic gap (merge of nozzle with throat) deep into hotter zone, you just need longer throat. So far I have best quality and speed with this approach.</p> <p>The most important thing for the all metal hotend is to have fast retracts.</p> <p>For the FAN I recommend to use double deck, that is to put one fan on top of another and connect them in parallel. I found this solution in some server power supplies. And indeed two fans produce really good flow to cool heatsink at higher temperatures (before I was considering water cooling but two fans much cheaper and do the job very good). Also the probability that two fans will fail is very low.</p>
1,607
<p>I have a simple app loading a site optimized for the iPhone in a <code>UIWebView</code>.</p> <p>Problem is, caching does not seem to work:</p> <pre><code>[webView loadRequest: [NSURLRequest requestWithURL: [NSURL URLWithString: url] cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 60.0]]; </code></pre> <p>Any things referenced in this remote page (css, images, external javascript files) never get cached (the requests never send a If-Modified-Since header or anything else in the way of cache control.)</p> <p>Is it possible? It seems with a regular Cocoa WebView there a delegate methods that get called for each resource request and post load (<code>-didFinishLoadingFromDataSource:</code>) which you could use to roll your own caching.. but that does not seem applicable here.</p> <p>My entire page (page and its referenced resources) is around 89K compressed.. which is slow over 3G in some spots and even worse over EDGE. Incoming requests are at least indicating that it accepts compression (<code>accept-encoding=gzip, deflate</code>), so that's good I suppose.</p> <p>I read <a href="http://yuiblog.com/blog/2008/02/06/iphone-cacheability/" rel="nofollow noreferrer">this yui study</a>, which seems to indicate that the iPhone will cache 25k per item. The only thing referenced that is over 25k uncompressed is jquery (packed but uncompressed - it is 30k). Everything else should be cacheable. No request for anything referenced in the page fetched is triggering a 304 on the server side.</p> <p>That yui study was from almost a year ago, and I am guessing with mobile safari only. </p> <p>This is using a <code>UIWebView</code> in a native iPhone app.</p>
<p>One workaround of this problem as I see is to </p> <p>1) download HTML code</p> <p>2) store it in the string</p> <p>3) find all external links in it like</p> <pre><code>&lt;img src="img.gif" width="..." height="..." /&gt; </code></pre> <p>4) download them all</p> <p>5) replace them with embedded Base64-encoded version</p> <pre><code>&lt;img src="data:image/gif;base64,R0lGODlhUAAPA...JADs= " width="..." height="..." /&gt; </code></pre> <p>6) finally store complete HTML with embedded images as you want.</p>
<p>You should be able to subclass <code>NSURLCache</code> and substitute it for the shared cache used by the <code>UIWebView</code> as described in this Cocoa with Love article: <a href="http://www.cocoawithlove.com/2010/09/substituting-local-data-for-remote.html" rel="nofollow">Substituting local data for remote UIWebView requests</a></p> <p>For another approach have a look at <a href="http://robnapier.net/blog/offline-uiwebview-nsurlprotocol-588" rel="nofollow">Drop-in offline caching for UIWebView (and NSURLProtocol)</a>.</p>
44,947
<p>Windows has its 3D Builder software which upon importing an image, converts it to a heightmap of the image, aka turning it to a 3D model that can be saved as an stl.</p> <p>Does Linux have software with similar properties that takes a black and white image and turning it into a 3D heightmap model?</p>
<p>The OpenSCAD <code>surface</code> function will do this. You can feed it a greyscale image or a textfile containing a matrix. Documentation and examples can be found at <a href="https://en.wikibooks.org/wiki/OpenSCAD_User_Manual/Other_Language_Features#Surface" rel="nofollow noreferrer">https://en.wikibooks.org/wiki/OpenSCAD_User_Manual/Other_Language_Features#Surface</a></p> <p>OpenSCAD is a cross platform free open source cad package.</p>
<p>FreeCAD can import JPG (and IIRC TIFF and PNG as well) image files and produce a lithophane type height-map based on the brightness of each pixel. I'd be rather surprised if other 3D CAD software aimed at the 3D printing user base couldn't do the same. Most of the common free-to-use 3D CAD packages have Linux versions; FreeCAD certainly does (I use it on Kubuntu 20.04, and it should work on any recent version of any flavor of Debian-based Linux, if your hardware meets it requirements).</p>
1,954
<p>I am reading an XML file into a DataSet and need to get the data out of the DataSet. Since it is a user-editable config file the fields may or may not be there. To handle missing fields well I'd like to make sure each column in the DataRow exists and is not DBNull. </p> <p>I already check for DBNull but I don't know how to make sure the column exists without having it throw an exception or using a function that loops over all the column names. What is the best method to do this?</p>
<p>DataRow's are nice in the way that they have their underlying table linked to them. With the underlying table you can verify that a specific row has a specific column in it.</p> <pre><code> If DataRow.Table.Columns.Contains("column") Then MsgBox("YAY") End If </code></pre>
<p>You can encapsulate your block of code with a try ... catch statement, and when you run your code, if the column doesn't exist it will throw an exception. You can then figure out what specific exception it throws and have it handle that specific exception in a different way if you so desire, such as returning "Column Not Found".</p>
21,543
<p>When writing the string "¿" out using</p> <pre><code>System.out.println(new String("¿".getBytes("UTF-8"))); </code></pre> <p>¿ is written instead of just ¿.</p> <p>WHY? And how do we fix it?</p>
<p>You don't have to use UTF-16 to solve this:</p> <pre><code>new String("¿".getBytes("UTF-8"), "UTF-8"); </code></pre> <p>works just fine. As long as the encoding given to the <code>getBytes()</code> method is the same as the encoding you pass to the String constructor, you should be fine!</p>
<p>Sounds like the system console isn't in UTF-8</p>
21,212
<p>Does anyone know the query the last synchronization date from sql server (2008).</p> <p>It is the same information displayed in replication monitor, but I want to be able to get that date from a query.</p>
<p>You can see a lot of info about merge sessions by using the system table msMerge_sessions:</p> <pre><code>select * from msMerge_sessions </code></pre> <p>Depending on the info you need, use the other system tables available in your database.</p>
<p>For Answered Number 3 </p> <p>Great Effort but there're some modification On view for ability running Query </p> <p>---- Create View LastSync as below </p> <pre><code>Create View LastSync As select subscriber_name, max(start_time) as last_sync, ID, creation_date from msMerge_sessions inner join msMerge_agents on msmerge_agents.id = msmerge_sessions.agent_id group by subscriber_name, ID, creation_date Go </code></pre> <p>---- Run Below Query </p> <blockquote> <p>SELECT dbo.LastSync.id, dbo.LastSync.subscriber_name, dbo.LastSync.creation_date, dbo.LastSync.last_sync, distribution.dbo.MSmerge_sessions.estimated_upload_changes + distribution.dbo.MSmerge_sessions.estimated_download_changes AS estimate_rows, distribution.dbo.MSmerge_sessions.upload_inserts + distribution.dbo.MSmerge_sessions.upload_updates + distribution.dbo.MSmerge_sessions.upload_deletes + distribution.dbo.MSmerge_sessions.download_inserts + distribution.dbo.MSmerge_sessions.download_updates + distribution.dbo.MSmerge_sessions.download_deletes AS actual_rows, distribution.dbo.MSmerge_sessions.duration AS total_seconds, distribution.dbo.MSmerge_sessions.percent_complete, distribution.dbo.MSmerge_sessions.delivery_rate, CASE (runstatus) WHEN 1 THEN 'Start' WHEN 2 THEN 'Succeed' WHEN 3 THEN 'In Progress' WHEN 4 THEN 'Idle' WHEN 5 THEN 'Retry' WHEN 6 THEN 'Fail' END AS Status FROM distribution.dbo.MSmerge_sessions INNER JOIN dbo.LastSync ON dbo.LastSync.id = distribution.dbo.MSmerge_sessions.agent_id AND distribution.dbo.MSmerge_sessions.start_time = dbo.LastSync.last_sync</p> </blockquote> <p>-- Good Luck </p>
49,358
<p>I have a form in C# that has a button that, when clicked, I want the background image to cycle through a set of images (which I have as resources to the project). The images are named '_1', '_2', etc. and each time I click the button I want its background image to increment to the next one and go back to "_1" when it gets to the highest. Is there a way to do this?</p> <p>I tried getting <code>button1.BackgroundImage.ToString()</code> but that yields <code>System.Drawing.Bitmap</code> instead of <code>Resources._1</code> like I was thinking it would (in which case I could just get the last character and switch on that to change the background to the appropriate new image).</p> <p>Thanks for your help.</p>
<p>Why don't you just put the images in an array?</p>
<p>You could subclass Button and override the BackgroundImage property so you can better keep track of the current resource that represents the image. You might also override the onclick method to internally handle cycling to the next image, though that might be a little weird if the resources are handled outside of your derived button class.</p>
3,587
<p>I have a simple question and wish to hear others' experiences regarding which is the best way to replicate images across multiple hosts.</p> <p>I have determined that storing images in the database and then using database replication over multiple hosts would result in maximum availability.</p> <p>The worry I have with the filesystem is the difficulty synchronising the images (e.g I don't want 5 servers all hitting the same server for images!).</p> <p>Now, the only concerns I have with storing images in the database is the extra queries hitting the database and the extra handling i'd have to put in place in apache if I wanted 'virtual' image links to point to database entries. (e.g AddHandler)</p> <p>As far as my understanding goes:</p> <ul> <li>If you have a script serving up the images: Each image would require a database call.</li> <li>If you display the images inline as binary data: Which could be done in a single database call.</li> <li>To provide external / linkable images you would have to add a addHandler for the extension you wish to 'fake' and point it to your scripting language (e.g php, asp).</li> </ul> <p>I might have missed something, but I'm curious if anyone has any better ideas?</p> <hr> <p>Edit: Tom has suggested using mod_rewrite to save using an AddHandler, I have accepted as a proposed solution to the AddHandler issue; however I don't yet feel like I have a complete solution yet so please, please, keep answering ;)</p> <p>A few have suggested using lighttpd over Apache. How different are the ISAPI modules for lighttpd?</p>
<p>If you store images in the database, you take an extra database hit <em>plus</em> you lose the innate caching/file serving optimizations in your web server. Apache will serve a static image much faster than PHP can manage it.</p> <p>In our large app environments, we use up to 4 clusters:</p> <ul> <li>App server cluster</li> <li>Web service/data service cluster</li> <li>Static resource (image, documents, multi-media) cluster</li> <li>Database cluster</li> </ul> <p>You'd be surprised how much traffic a static resource server can handle. Since it's not really computing (no app logic), a response can be optimized like crazy. If you go with a separate static resource cluster, you also leave yourself open to change just that portion of your architecture. For instance, in some benchmarks <a href="http://www.lighttpd.net/" rel="nofollow noreferrer">lighttpd</a> is even faster at serving static resources than apache. If you have a separate cluster, you can change your http server there without changing anything else in your app environment.</p> <p>I'd start with a 2-machine static resource cluster and see how that performs. That's another benefit of separating functions - you can scale out only where you need it. As far as synchronizing files, take a look at existing <a href="http://en.wikipedia.org/wiki/File_synchronization" rel="nofollow noreferrer">file synchronization</a> tools versus rolling your own. You may find something that does what you need without having to write a line of code.</p>
<p>Having your images in a database doesn't necessarily mean a database call for each one; you could cache these separately on each host (e.g. in temporary files) when they are retrieved. The source images would still be in the database and easy to synchronise across servers.</p> <p>You also don't really need to add Apache handlers to serve an image through a PHP script whilst maintaining nice urls- you can make urls like <a href="http://server/image.php/param1/param2/param3.JPG" rel="nofollow noreferrer">http://server/image.php/param1/param2/param3.JPG</a> and read the parameters through <code>$_SERVER['PATH_INFO']</code> . You could also remove the 'image.php' portion of the URL (if you needed to) using mod_rewrite.</p>
48,586
<p>I'm building a Thunderbird extension and would like to add my own header to all outgoing email (e.g. &lt;myext-version: 1.0&gt; ). Any idea how to do this? I know it's possible since this is done in the OpenPGP Enigmail extension. Thanks!</p>
<p>Here is the code from one extension I'm working on:</p> <pre><code>function SendObserver() { this.register(); } SendObserver.prototype = { observe: function(subject, topic, data) { /* thunderbird sends a notification even when it's only saving the message as a draft. * We examine the caller chain to check for valid send notifications */ var f = this.observe; while (f) { if(/Save/.test(f.name)) { print("Ignoring send notification because we're probably autosaving or saving as a draft/template"); return; } f = f.caller; } // add your headers here, separated by \r\n subject.gMsgCompose.compFields.otherRandomHeaders += "x-test: test\r\n"; } }, register: function() { var observerService = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); observerService.addObserver(this, "mail:composeOnSend", false); }, unregister: function() { var observerService = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); observerService.removeObserver(this, "mail:composeOnSend"); } }; /* * Register observer for send events. Check for event target to ensure that the * compose window is loaded/unloaded (and not the content of the editor). * * Unregister to prevent memory leaks (as per MDC documentation). */ var sendObserver; window.addEventListener('load', function (e) {if (e.target == document) sendObserver = new SendObserver(); }, true); window.addEventListener('unload', function (e) { if (e.target == document) sendObserver.unregister();}, true); </code></pre> <p>Put this inside a .js file that is loaded by the compose window (for example by overlaying <code>chrome://messenger/content/messengercompose/messengercompose.xul)</code>.</p> <p>The check in SendObserver.observe was necessary in my case because I wanted to do a user interaction, but you could probably leave it out.</p>
<p>I don't know the answer but just some thoughts...</p> <p>I think thunderbird extensions are usually just xul and js. From the enigmail site:</p> <blockquote> <p>Unlike most Mozilla AddOns, Enigmail contains platform dependent parts: it depends on the CPU, the compiler, libraries of the operating system and the email application it shall integrate into.</p> </blockquote> <p>Looking at the Enigmail source code, <a href="http://www.mozdev.org/source/browse/enigmail/src/src/mimehdrs2.cpp?rev=1.3;content-type=text%2Fx-cvsweb-markup" rel="nofollow noreferrer">this might be the relevant section</a> (written in c++)</p> <p>So you might need to either translate what they've done into js(!) or keep looking for a different example.</p> <p><a href="http://email.about.com/cs/mozillatips/qt/et030604.htm" rel="nofollow noreferrer">Here's another link that might be helpful</a></p>
19,600
<p>What interrupt would you hook from DOS to get the real-time clock?</p>
<p>The realtime clock cannot generate interrupts. It was (maybe still is) coupled with the cmos-ram because it was buffered by the battery. It can only be accessed via the ports 0x70 and 0x71.</p> <p>You can however hook the interrupt of the PIT (programmable interrupt timer). That's interrupt 0x08 (e.g. hardware IRQ0). As far as I remember that interrupt was configured by dos to be called about 27 times per second. You can program it to other frequencies as well but that will mess up the dos-clock a bit (port 0x40 an 0x43).</p>
<p>Read up on the <a href="http://en.wikipedia.org/wiki/Intel_8259" rel="nofollow noreferrer">Intel 8259</a> family of Programmable Interrupt Controllers. According to this, it's interrupts 8 (master) and 112 (slave). Here's a very technical document on the 8259A: <a href="http://pdos.csail.mit.edu/6.828/2008/readings/hardware/8259A.pdf" rel="nofollow noreferrer"><a href="http://pdos.csail.mit.edu/6.828/2008/readings/hardware/8259A.pdf" rel="nofollow noreferrer">http://pdos.csail.mit.edu/6.828/2008/readings/hardware/8259A.pdf</a></a></p>
10,929
<p>ModRewrite can easily handle stripping the www off the front of my domain.<br> In .htaccess:</p> <pre><code>RewriteEngine On RewriteCond %{HTTPS} on RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^(.*)$ https://%1/$1 [R=301,L] RewriteCond %{HTTPS} off RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301,L] </code></pre> <p>But with SSL, the certificate check comes before the .htaccess rewrite, causing certificate error.<br> I would rather not buy an SSL certificate for the www only to redirect it.<br> Can you offer me a smarter solution? (btw EV Certificates are not available as wildcards)</p>
<p>You can get certificates with multiple domain names in them. Get one with <code>mydomain.com</code> and <code>www.mydomain.com</code>. I think it's also possible to buy "wildcard" certificates that will match any subdomain, but they cost much more.</p>
<p>What you are trying to do is impossible. If a user accesses www.domain.cc over SSL, then you will get a certificate error if you do not have a valid SSL certificate - even if all you want to do is redirect them to the correct site. </p> <p>You will either need a new certificate for www.domain.cc, or convince your registrar to give you a wildcard certificate for *.domain.cc, or one with multiple subjectAltName properties. See <a href="http://www.crsr.net/Notes/Apache-HTTPS-virtual-host.html" rel="nofollow">http://www.crsr.net/Notes/Apache-HTTPS-virtual-host.html</a> </p>
22,017
<p>Say I have an array that represents a set of points:</p> <pre><code>x = [2, 5, 8, 33, 58] </code></pre> <p>How do I generate an array of all the pairwise distances? </p>
<pre><code>x = [2, 5, 8, 33, 58] print x.collect {|n| x.collect {|i| (n-i).abs}}.flatten </code></pre> <p>I think that would do it.</p>
<p>If you really do want an array instead of a matrix, this is O(n^2/2) instead of O(n^2).</p> <pre><code>result=[] x.each_index{|i| (i+1).upto(x.size-1){|j| result&lt;&lt;(x[i]-x[j]).abs}} </code></pre>
15,161
<p>Before I do this I figured I would ask if it was the best way. Each "Vendor" object has a "Bucket" object. In my repeater I need to display some properties from Vendor and some from Bucket, also some images populated by FileSystem that are linked to the vendor. I figured the best way to do this is bind the repeater with the vendor object, then on ItemDataBound I would populate the images and the buckets based on the vendor that is bound to that particular Items[e.Item.ItemIndex]. </p> <p>Is this the best way to go about this? </p>
<p>Haven't heard of it before, but I can't wait to see if you can make it useful!</p> <p>You can assign Visual Studio functions to "chords" of key combinations, right? So maybe you could play shave-and-a-haircut to start a build.</p>
<p>Yeah, I was thinking about doing something similiar to that myself. I'm pretty sure you'd have to write your own driver for it though.</p>
13,285
<p>I would like to make my web control more readable in design mode, basically I want the tag declaration to look like:</p> <pre><code>&lt;cc1:Ctrl ID="Value1" runat="server"&gt; &lt;Values&gt;string value 1&lt;/Value&gt; &lt;Values&gt;string value 2&lt;/Value&gt; &lt;/cc1:Ctrl&gt; </code></pre> <p>Lets say I have a private variable in the code behind:</p> <pre><code>List&lt;string&gt; values = new List&lt;string&gt;(); </code></pre> <p>So how can I make my user control fill out the private variable with the values that are declared in the markup?</p> <hr> <p>Sorry I should have been more explicit. Basically I like the functionality that the ITemplate provides (<a href="http://msdn.microsoft.com/en-us/library/aa719834.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa719834.aspx</a>)</p> <p>But in this case you need to know at runtime how many templates can be instansitated, i.e.</p> <pre><code>void Page_Init() { if (messageTemplate != null) { for (int i=0; i&lt;5; i++) { MessageContainer container = new MessageContainer(i); messageTemplate.InstantiateIn(container); msgholder.Controls.Add(container); } } </code></pre> <p>}</p> <p>In the given example the markup looks like:</p> <pre><code>&lt;acme:test runat=server&gt; &lt;MessageTemplate&gt; Hello #&lt;%# Container.Index %&gt;.&lt;br&gt; &lt;/MessageTemplate&gt; &lt;/acme:test&gt; </code></pre> <p>Which is nice and clean, it does not have any tag prefixes etc. I really want the nice clean tags.</p> <p>I'm probably being silly in wanting the markup to be clean, I'm just wondering if there is something simple that I'm missing.</p>
<p>I think what you are searching for is the attribute:</p> <pre><code>[PersistenceMode(PersistenceMode.InnerProperty)] </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.persistencemode.aspx" rel="nofollow noreferrer">Persistence Mode</a></p> <p>Remember that you have to register your namespace and prefix with:</p> <pre><code>&lt;%@ Register Namespace="MyNamespace" TagPrefix="Pref" %&gt; </code></pre>
<p>I see two options, but both depend on your web control implementing some sort of collection for your values. The first option is to just use the control's collection instead of your private variable. The other option is to copy the control's collection to your private variable at run-time (maybe in the Page_Load event handler, for example).</p> <p>Say you have web control that implements a collection of items, like a listbox. The tag looks like this in the source view:</p> <pre><code> &lt;asp:ListBox ID="ListBox1" runat="server"&gt; &lt;asp:ListItem&gt;String 1&lt;/asp:ListItem&gt; &lt;asp:ListItem&gt;String 2&lt;/asp:ListItem&gt; &lt;asp:ListItem&gt;String 3&lt;/asp:ListItem&gt; &lt;/asp:ListBox&gt;&lt;br /&gt; </code></pre> <p>Then you might use code like this to load your private variable:</p> <pre><code> List&lt;String&gt; values = new List&lt;String&gt;(); foreach (ListItem item in ListBox1.Items) { values.Add(item.Value.ToString()); } </code></pre> <p>If you do this in Page_Load you'll probably want to only execute on the initial load (i.e. not on postbacks). On the other hand, depending on how you use it, you could just use the ListBox1.Items collection instead of declaring and initializing the values variable.</p> <p>I can think of no way to do this declaratively (since your list won't be instantiated until run-time anyway).</p>
8,717
<p>I have a list string tag.</p> <p>I am trying to initialize a dictionary with the key as the tag string and values as the array index.</p> <pre><code>for i, ithTag in enumerate(tag): tagDict.update(ithTag=i) </code></pre> <p>The above returns me {'ithTag': 608} <em>608 is the 608th index</em></p> <p>My problem is that while the i is being interpreted as a variable, Python is treating the "ithTag" as a string instead of a variable.</p> <p>I'm confused, it is kind of hard to google these kind of specific questions. I hope I worded the title of this question correctly,</p> <p>Thanks!</p>
<p>You actually want to do this:</p> <pre><code>for i, tag in enumerate(tag): tagDict[tag] = i </code></pre> <p>The .update() method is used for updating a dictionary using another dictionary, not for changing a single key/value pair.</p>
<p>I think this is what you want to do:</p> <pre><code>d = {} for i, tag in enumerate(ithTag): d[tag] = i </code></pre>
20,878
<p>I am putting together a build system and wanted to know if there is a reliable way to find out if a checked out SVN folder needs updating (i.e. is it out of sync with the repository). I want to avoid a nightly build unless something has changed. I could write a script that parses the results of the <code>svn update</code> command I guess, but I wondered if there as a command that would tell me if an update is actually required?</p>
<p>Use the <a href="http://www.visualsvn.com/support/svnbook/ref/svn/#svn.ref.svn.sw.show_updates" rel="noreferrer">show updates option</a> of the status command: </p> <pre><code>svn status -u </code></pre> <p>or</p> <pre><code>svn status --show-updates </code></pre>
<p>The <a href="https://stackoverflow.com/a/305294/1184842">answer of flolo</a> does not work good for subversion externals (which is also discussed in <a href="https://stackoverflow.com/questions/2789344/dont-show-svnexternals-in-svn-status">Don&#39;t show svn:externals in svn status</a>). A better solution if you only need the information that the current folder needs a update (not exactly which files itself), <a href="http://beerpla.net/2008/07/23/how-to-check-if-the-local-svn-revision-is-up-to-date/" rel="nofollow noreferrer">this solution</a> is better:</p> <pre><code>cd somedir; svn info -r HEAD | grep -i "Last Changed Rev" Last Changed Rev: 8544 svn info | grep -i "Last Changed Rev" Last Changed Rev: 8531 </code></pre> <p>If these numbers are not the same, an update is needed.</p>
39,254
<p>How can I write a scheduler application in C# .NET?</p>
<p>You could also try <a href="http://quartznet.sourceforge.net/index.html" rel="nofollow noreferrer">Quartz.Net</a>.</p>
<p>You can also use the timer control to have the program fire of whatever event you want every X ticks, or even just one. The best solution really depends on what you're tring to accomplish though.</p>
18,549
<p>I have a C# .NET web project that I'm currently working on. What I'm trying to do is read some files that I dropped into a dir which is at the same level as fileReader.cs which is attempting to read them. On a normal desktop app the following would work:</p> <pre><code>DirectoryInfo di = new DirectoryInfo(./myDir); </code></pre> <p>However because it's a web project the execution context is different, and I don't know how to access these files?</p> <p>Eventually fileReader will be called in an installation routine. I intend to override one of the Installer.cs' abstract methods so will this affect the execution context?</p>
<p>Use <a href="http://msdn.microsoft.com/library/ms178116.aspx" rel="nofollow noreferrer"><code>Server.MapPath</code></a> to get the local path for the currently executing page.</p>
<p>Use <a href="http://msdn.microsoft.com/library/ms178116.aspx" rel="nofollow noreferrer"><code>Server.MapPath</code></a> to get the local path for the currently executing page.</p>
32,984
<p>I am using a new Prusa i3 MK3S 3D printer kit. I print lots of things using PLA and PETG. </p> <p>After a week of great performance I noticed that when printing some objects with PETG filament I often encountered a problem when there's <strong>intense stringing, infill gaps, artifacts, the object sometimes detaches from the plate.</strong> I use the Prusa Slicer and Cura and print with the temperature 230/90&nbsp;°C, speed max. 300&nbsp;%.This problem occurs rather regardless of which infill methods I choose. I see this problem more often when printing models sliced with Cura. Sometimes everything goes fine, but most of the time I need to stop the print due to the model collapsing, detaching from the surface, its parts collapsing due to infill gaps. The printer sometimes makes some 'clicking, cracking' sounds when printing with PETG. <em>My filaments come from Fiberology</em>.</p> <p>Surprisingly, I have run the selftest, XYZ, Z calibrations and all the other ones without any errors. The wizard told me that the axes are perpendicular and it gave me congratulations. All the other tests went nearly perfect as well. </p> <p>I do not encounter any problems using PLA, just with PETG. I try to maintain the filament properly (keep it away from moisture, in a closed box). Sometimes (rarely) <strong>I get crashes. The filament often builds up on the hotend and I remove it.</strong></p> <p>I do not know what to do, the build went very well and there are no errors, even though I am a new user and this is my very first 3D printer. I have searched the web and I haven't found people reporting this exact same thing.</p> <p>Could You help me? What can I do to improve the quality of the prints, perhaps maintain PETG better <strong>(maybe I'm doing something wrong) and most importantly, solve the problem</strong>? </p>
<p>230&nbsp;°C is way too cool for PETG and will result in underextrusion unless you print really slow, and poor bonding. Underextrusion in turn leads to stringing because of pressure build-up. I print PETG at 250&nbsp;°C.</p>
<p>You might try printing with Prusa's recommended settings. They tend to be hotter and slower than I expected.</p> <p>I have made several pet-G prints with the same machine you have. </p>
1,373
<p>Is there a way to create an html link using h:outputLink, other JSF tag or code to create a non faces request (HTTP GET) with request parameters?</p> <p>For example I have the following navigation-rule</p> <pre><code>&lt;navigation-rule&gt; &lt;navigation-case&gt; &lt;from-outcome&gt;showMessage&lt;/from-outcome&gt; &lt;to-view-id&gt;/showMessage.jsf&lt;/to-view-id&gt; &lt;redirect/&gt; &lt;/navigation-case&gt; &lt;/navigation-rule&gt; </code></pre> <p>In my page I would like to output the following html code:</p> <pre><code>&lt;a href="/showMessage.jsf?msg=23"&gt;click to see the message&lt;/a&gt; </code></pre> <p>I could just write the html code in the page, but I want to use the navigation rule in order to have all the urls defined in a single configurable file.</p>
<p>This is an interesting idea. I'd be curious to know how it pans out in practice.</p> <p><strong>Getting the navigation rules</strong></p> <p>Navigation is handled by the <a href="http://java.sun.com/javaee/javaserverfaces/1.1_01/docs/api/javax/faces/application/NavigationHandler.html" rel="noreferrer">NavigationHandler</a>. Getting hold of the NavigationHandler isn't difficult, but the API does not expose the rules it uses.</p> <p>As I see it, you can:</p> <ol> <li>parse faces-config.xml on initialization and store the rules in the application context (<em>easy</em>)</li> <li>implement your own NavigationHandler that ignores the rules in faces-config.xml or supplements them with your own rules file and exposes its ruleset somehow (<em>workable, but takes a bit of work</em>)</li> <li>mock your own <a href="http://java.sun.com/javaee/javaserverfaces/1.1_01/docs/api/javax/faces/context/FacesContext.html" rel="noreferrer">FacesContext</a> and pass it to the existing navigation handler (<em>really difficult to make two FacesContext object coexist in same thread and extremely inefficient</em>)</li> </ol> <p>Now, you have another problem too. Where are you going to keep the mappings to look up the views? Hard-code them in the beans?</p> <p><strong>Using the navigation rules</strong></p> <p>Off hand, I can think of two ways you could construct parameter-containing URLs from the back-end. Both involve defining a bean of some kind.</p> <pre><code>&lt;managed-bean&gt; &lt;managed-bean-name&gt;navBean&lt;/managed-bean-name&gt; &lt;managed-bean-class&gt;foo.NavBean&lt;/managed-bean-class&gt; &lt;managed-bean-scope&gt;application&lt;/managed-bean-scope&gt; &lt;/managed-bean&gt; </code></pre> <p>Source:</p> <pre><code>package foo; import java.io.IOException; import java.io.Serializable; import java.net.URLEncoder; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; public class NavBean implements Serializable { private String getView() { String viewId = "/showMessage.faces"; // or look this up somewhere return viewId; } /** * Regular link to page */ public String getUrlLink() { FacesContext context = FacesContext.getCurrentInstance(); ExternalContext extContext = context.getExternalContext(); String viewId = getView(); String navUrl = context.getExternalContext().encodeActionURL( extContext.getRequestContextPath() + viewId); return navUrl; } /** * Just some value */ public String getValue() { return "" + System.currentTimeMillis(); } /** * Invoked by action */ public String invokeRedirect() { FacesContext context = FacesContext.getCurrentInstance(); ExternalContext extContext = context.getExternalContext(); String viewId = getView(); try { String charEncoding = extContext.getRequestCharacterEncoding(); String name = URLEncoder.encode("foo", charEncoding); String value = URLEncoder.encode(getValue(), charEncoding); viewId = extContext.getRequestContextPath() + viewId + '?' + name + "=" + value; String urlLink = context.getExternalContext().encodeActionURL( viewId); extContext.redirect(urlLink); } catch (IOException e) { extContext.log(getClass().getName() + ".invokeRedirect", e); } return null; } } </code></pre> <p><strong>GET</strong></p> <p>For a GET request, you can use the UIParameters to set the values and let the renderer build the parameter list.</p> <pre><code>&lt;h:outputLink value="#{navBean.urlLink}"&gt; &lt;f:param name="foo" value="#{navBean.value}" /&gt; &lt;h:outputText value="get" /&gt; &lt;/h:outputLink&gt; </code></pre> <p><strong>POST</strong></p> <p>If you want to set the URL to a view during a POST action, you can do it using a redirect in an action (invoked by a button or commandLink).</p> <pre><code>&lt;h:commandLink id="myCommandLink" action="#{navBean.invokeRedirect}"&gt; &lt;h:outputText value="post" /&gt; &lt;/h:commandLink&gt; </code></pre> <p><strong>Notes</strong></p> <p>Note that <a href="http://java.sun.com/javaee/javaserverfaces/1.1_01/docs/api/javax/faces/context/ExternalContext.html#encodeActionURL(java.lang.String)" rel="noreferrer">ExternalContext.encodeActionURL</a> is used to encode the string. This is good practice for producing code that is portable across contexts (portlets, etcetera). You would use <em>encodeResourceURL</em> if you were encoding a link to an image or download file.</p>
<p>Have you considered a form?</p> <pre><code>&lt;h:form&gt; &lt;h:commandLink value="Click to see the message" action="#{handler.outcome}" /&gt; &lt;h:inputHidden id="msgId" value="#{bean.msgId}"/&gt; &lt;/h:form&gt; </code></pre>
16,791
<p>How do you repopulate a form in ASP.NET MVC that contains a DropDownList?</p>
<p>I believe you are asking how to maintain the value for a dropdown list after a form is submitted and re-displayed. If so, please see below for a <strong>VERY SIMPLE</strong> example:</p> <p>Create a new MVC app (using MVC beta) and place the following in HomeController:</p> <pre><code>private Dictionary&lt;string, string&gt; getListItems() { Dictionary&lt;string, string&gt; d = new Dictionary&lt;string, string&gt;(); d.Add("Apple", "APPL"); d.Add("Orange", "ORNG"); d.Add("Banana", "BNA"); return d; } public ActionResult Index() { Dictionary&lt;string, string&gt; listItems = getListItems(); SelectList selectList = new SelectList(listItems, "Value", "Key"); ViewData["FruitDropDown"] = selectList; return View(); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Index(FormCollection form) { string selectedItem = form["FruitDropDown"]; Dictionary&lt;string, string&gt; listItems = getListItems(); SelectList selectList = new SelectList(listItems, "Value", "Key", selectedItem); ViewData["FruitDropDown"] = selectList; ViewData["Message"] = "You selected ID:" + selectedItem; return View(); } </code></pre> <p>And place this in Home\Index.aspx in between the MainContent tags:</p> <pre><code>&lt;div&gt;&lt;strong&gt;&lt;%= ViewData["Message"] %&gt;&lt;/strong&gt;&lt;/div&gt; &lt;% using (Html.BeginForm()) { %&gt; &lt;%= Html.DropDownList("FruitDropDown","(select a fruit)") %&gt; &lt;input type="submit" value="Submit" /&gt; &lt;% } %&gt; </code></pre>
<p>I just wanted to add the BigJoe714 has it right except the ...new SelectList(listItems, "Value", "Key", selectedItem) has the key / value switched</p> <p>The constructor takes these params for this overload</p> <pre><code>public SelectList( IEnumerable items, string dataValueField, string dataTextField, object selectedValue ); </code></pre> <p>The data value should be the key while the data text should be the value. </p> <p>But otherwise, thanks so much! Another kicka$$ feature of asp.net mvc</p>
38,024
<p>I'm looking for patterns that concern coding parts of a GUI. <strong>Not</strong> as global as <strong>MVC</strong>, that I'm quite familiar with, but patterns and good ideas and best practices concerning single controls and inputs.</p> <p>Let say I want to make a control that display some objects that may overlap. Now if I click on an object, I need to find out what to do (Just finding the object I can do in several ways, such as an quad-tree and Z-order, thats not the problem). And also I might hold down a modifier key, or some object is active from the beginning, making the selection or whatever a bit more complicated. Should I have an object instance representing a screen object, handle the user-action when clicked, or a master class. etc.. What kind of patterns or solutions are there for problems like this? </p>
<p>I think to be honest you a better just boning up on your standard design patterns and applying them to the individual problems that you face in developing your UI.</p> <p>While there are common UI &quot;themes&quot; (such as dealing with modifier keys) the actual implementation may vary widely.</p> <p>I have O'Reilly's <a href="http://www.amazon.co.uk/gp/redirect.html?ie=UTF8&amp;location=http%3A%2F%2Fwww.amazon.co.uk%2FHead-First-Design-Patterns%2Fdp%2F0596007124%2Fref%3Dpd_bbs_sr_1%3Fie%3DUTF8%26s%3Dbooks%26qid%3D1218730650%26sr%3D1-1&amp;tag=robcthegeek-21&amp;linkCode=ur2&amp;camp=1634&amp;creative=6738" rel="nofollow noreferrer">Head First Design Patterns</a> and <a href="http://www.amazon.co.uk/gp/redirect.html?ie=UTF8&amp;location=http%3A%2F%2Fwww.amazon.co.uk%2FHead-First-Design-Patterns-Poster%2Fdp%2F0596102143%2Fref%3Dpd_bbs_sr_3%3Fie%3DUTF8%26s%3Dbooks%26qid%3D1218730650%26sr%3D1-3&amp;tag=robcthegeek-21&amp;linkCode=ur2&amp;camp=1634&amp;creative=6738" rel="nofollow noreferrer">The Poster</a>, which I have found invaluable!</p> <h3>Shameless Plug : These links are using my associates ID.</h3>
<p>I don't think the that benefit of design patterns come from trying to find a design pattern to fit a problem. You can however use some heuristics to help clean up your design in this quite a bit, like keeping the UI as decoupled as possible from the rest of the objects in your system.</p> <p>There is a pattern that might help out in this case, the <a href="http://en.wikipedia.org/wiki/Observer_pattern" rel="nofollow noreferrer">Observer Pattern</a>.</p>
3,239
<p>Specifically using stainless steel nozzles, but I guess it's worth knowing about brass too. Is there any reason to be concerned about dimensional accuracy of the nozzle or anything like that as a result of repeated heating with a butane torch? </p>
<p>If you carbonize the filament or other particles that are clogging the nozzle, then you will never get them clean. In my experience, it's not worth cleaning the nozzle with anything other than cleaning filament. If that doesn't work then change the nozzle. Heating the metal nozzle with a torch will change the temper of the material. I used to try cleaning with a soldering iron; which was to no avail.</p> <p>Purchase a dozen brass nozzles and save your self the headache. Either that or a good quality set of stainless steel ones. They are easier to clean with the cleaning filament and aren't ablated by the filament as quickly, allowing for better dimensional accuracy over multiple prints.</p> <p><a href="https://i.stack.imgur.com/2OhXB.jpg" rel="nofollow noreferrer">https://www.amazon.com/eSUN-CLEANING-Filament-Printers-Cleaning/dp/B00MVIYNFW/</a></p> <p><a href="https://i.stack.imgur.com/2OhXB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2OhXB.jpg" alt="eSun Cleaning Filament"></a></p>
<p>If you can get the torch hot enough and you carbonise/burn the filament properly, it may work. You still need to do a cold pull to remove as many residues as you can, but if you heated it enough, the residuals maybe won't stick too much to the nozzle.</p> <p>You already have the butane, try and tell us.</p>
1,628
<p>I want to embed a wikipedia article into a page but I don't want all the wrapper (navigation, etc.) that sits around the articles. I saw it done here: <a href="http://www.dayah.com/periodic/" rel="nofollow noreferrer">http://www.dayah.com/periodic/</a>. Click on an element and the iframe is displayed and links to the article only (no wrapper). So how'd they do that? Seems like JavaScript handles showing the iframe and constructing the href but after browsing the pages javascript (<a href="http://www.dayah.com/periodic/Script/interactivity.js" rel="nofollow noreferrer">http://www.dayah.com/periodic/Script/interactivity.js</a>) I still can't figure out how the url is built. Thanks.</p>
<p>The periodic table example loads the printer-friendly version of the wiki artice into an iframe. <a href="http://en.wikipedia.org/wiki/Potasium" rel="noreferrer">http://en.wikipedia.org/wiki/Potasium</a>?<b>printable=yes</b></p> <p>it's done in <i>function click_wiki(e)</i> (line 534, interactivity.js)</p> <blockquote><pre> var article = el.childNodes[0].childNodes[n_name].innerHTML; ... window.frames["WikiFrame"].location.replace("http://" + language + ".wikipedia.org/w/index.php?title=" + encodeURIComponent(article) + "&printable=yes"); </pre></blockquote>
<p>You could always download the site and scrap it. I think everything inside <code>&lt;div id="bodyContent"&gt;</code> is the content of the article - sans navigation, header, footer, etc..</p> <p>Don't forget to credit. ;)</p>
8,723
<p>Can I rename a folder in Perforce from <em>//depot/FooBar/</em> to <em>//depot/Foobar/</em>?</p> <p>I've tried this by renaming from <em>//depot/FooBar/</em> to <em>//depot/Temp/</em> to <em>//Depot/Foobar/</em> but the end result ends up the same as <em>//depot/FooBar/</em>.</p>
<p>Once it is in Perforce, the case remains set. As mentioned by Johan you can obliterate, set the name up correctly, and add it in again. However, there is a slight gotcha....</p> <p>If anyone else (running Windows) has already synced the wrong-cased version, then when they sync again the right one, it will not change the case on their PC. This is a peculiarity of the Windows file system acknowledging case but still being fundamentally case-independent.</p> <p>If a number of users have synced, and it is not convenient to get them to remove-from-client too (and blasting the folders from their machines), then you can resort to a dark and dirty Perforce technique called "Checkpoint surgery". It's not for the fainthearted, but you do this:</p> <ol> <li>Stop your server, take a checkpoint.</li> <li>Using your favourite text editor that can handle multi-megabyte files, search &amp; replace all occurances of the old case name with the new. You could of course use a script too.</li> <li>Replay your checkpoint file to recreate the Perforce database meta data.</li> <li>Restart your server.</li> </ol> <p>This will affect all user client specs transparently, and so when they sync they will get the right case as if by magic.</p> <p>It sounds hairy, but I've had to do it before and as long as you take care, backup, do a trial run etc, then all should be OK.</p>
<p>The question is over 3 years old, but I ran into an issue like this while doing a Subversion import into Perforce and figured the info I got could be useful to some. It's similar to the obliterate method, but helps you retain history. You use the duplicate command that may not have been available back then to retain the history. The process basically being:</p> <ol> <li>Duplicate to temporary location.</li> <li>Obliterate the location you just duplicated.</li> <li>Duplicate from the temporary location to the renamed case location.</li> <li>Obliterate the temporary location.</li> </ol> <p>Through this you retain the history of file changes, but get them all in the new path as well. Unfortunately there will be no history of the path case change, but that seems to be unavoidable. Similar to other methods mentioned here, users will need to either manually rename the directories in their workspace or delete and re-sync to get the new path name.</p> <p>Also, P4V caches the paths it shows in the tree so after doing this it may still show up as the old name. a p4 dirs command however will show the new case.</p>
16,139
<p>I Use Jacob (JAVA COM Bridge) on a 64 Bit Machine and want to load COM Objects from a 32 bit DLL. How can I do that?</p>
<p>You will need to host the 32 bit COM object in a 32bit process. So either your entire app will have to run 32bit or youll need to place the COM object in something like COM+ and use cross process calls.</p>
<p>You will need to host the 32 bit COM object in a 32bit process. So either your entire app will have to run 32bit or youll need to place the COM object in something like COM+ and use cross process calls.</p>
46,943
<p>I think everyone would agree that the MATLAB language is not pretty, or particularly consistent. But nevermind! We still have to use it to get things done.</p> <p>What are your favourite tricks for making things easier? Let's have one per answer so people can vote them up if they agree. Also, try to illustrate your answer with an example.</p>
<p>Turn a matrix into a vector using a single colon.</p> <pre><code>x = rand(4,4); x(:) </code></pre>
<p>Using ismember() to merge data organized by text identfiers. Useful when you are analyzing differing periods when entries, in my case company symbols, come and go.</p> <pre><code>%Merge B into A based on Text identifiers UniverseA = {'A','B','C','D'}; UniverseB = {'A','C','D'}; DataA = [20 40 60 80]; DataB = [30 50 70]; MergeData = NaN(length(UniverseA),2); MergeData(:,1) = DataA; [tf, loc] = ismember(UniverseA, UniverseB); MergeData(tf,2) = DataB(loc(tf)); MergeData = 20 30 40 NaN 60 50 80 70 </code></pre>
16,015
<p>I have a directory with several subdirectories with files.<br> How can I copy all files in the subdirectories to a new location?<br></p> <p><strong>Edit:</strong> I do not want to copy the directories, just the files...</p> <p>As this is still on XP, I chose the below solution:</p> <pre><code> for /D %S IN ("src\*.*") DO @COPY "%S\" "dest\" </code></pre> <p>Thanks!</p>
<p>Ok. With your edit that says you don't want the directory structure, i think you're going to want to use something like this:</p> <pre><code>for /F "usebackq" %s IN (`DIR /B /S /A-D SrcDir`) DO @( XCOPY %s DestDir\%~nxs ) </code></pre>
<p>If you want to keep the same folder structure on the other end, sounds as simple as XCOPY</p> <blockquote> <p>xcopy c:\old\*.* d:\new\ /s</p> </blockquote> <p>Use /e instead of /s if you want empty directories copied too.</p>
22,468