instruction
stringlengths 27
22.5k
| chosen
stringlengths 27
28.2k
| rejected
stringlengths 19
24.9k
| __index_level_0__
int64 0
10k
|
---|---|---|---|
<p>Doug McCune had created something that was exactly what I needed (<a href="http://dougmccune.com/blog/2007/05/10/analyze-your-actionscript-code-with-this-apollo-app/" rel="nofollow noreferrer">http://dougmccune.com/blog/2007/05/10/analyze-your-actionscript-code-with-this-apollo-app/</a>) but alas - it was for AIR beta 2. I just would like some tool that I can run that would provide some decent metrics...any idea's?</p>
| <p>There is a Code Metrics Explorer in the Enterprise Flex Plug-in below:</p>
<p><a href="http://www.deitte.com/archives/2008/09/flex_builder_pl.htm" rel="nofollow noreferrer">http://www.deitte.com/archives/2008/09/flex_builder_pl.htm</a></p>
| <p>To get a rough estimate, you could always run <code>find . -type f -exec cat {} \; | wc -l</code> in the project directory if you're using Mac OS X. </p>
| 5,607 |
<p>Does anybody have experience working with PHP accelerators such as <a href="http://turck-mmcache.sourceforge.net/" rel="noreferrer">MMCache</a> or <a href="http://www.zend.com/en/" rel="noreferrer">Zend Accelerator</a>? I'd like to know if using either of these makes PHP comparable to <em>faster</em> web-technologies. Also, are there trade offs for using these?</p>
| <p>Note that Zend Optimizer and MMCache (or similar applications) are totally different things. While Zend Optimizer tries to optimize the program opcode MMCache will cache the scripts in memory and reuse the precompiled code.</p>
<p>I did some benchmarks some time ago and you can find the <a href="http://blogs.interdose.com/dominik/2008/04/11/benchmarking-php-eaccelerator-und-andere-opcode-caches/" rel="nofollow noreferrer">results</a> in my blog (in German though). The basic results:</p>
<p>Zend Optimizer alone didn't help at all. Actually my scripts were slower than without optimizer.</p>
<p>When it comes to caches:
* fastest: <a href="http://eaccelerator.net/" rel="nofollow noreferrer">eAccelerator</a>
* <a href="http://xcache.lighttpd.net/" rel="nofollow noreferrer">XCache</a>
* <a href="http://www.php.net/manual/en/book.apc.php" rel="nofollow noreferrer">APC</a></p>
<p>And: You DO want to install a opcode cache!</p>
<p>For example:
<a href="http://blogs.interdose.com/dominik/wp-content/uploads/2008/04/opcode_wordpress.png" rel="nofollow noreferrer">alt text http://blogs.interdose.com/dominik/wp-content/uploads/2008/04/opcode_wordpress.png</a></p>
<p>This is the duration it took to call the wordpress homepage 10.000 times.</p>
<p><em>Edit:</em> BTW, eAccelerator contains an optimizer itself.</p>
| <p>Have you checked out Phalanger? It compiles PHP to .NET code. Here are <a href="http://web.archive.org/web/20101126094453/http://php-compiler.net/doku.php?id=core%3abenchmarks" rel="nofollow noreferrer">some benchmarks</a> which show that it can dramatically improve performance.</p>
| 3,402 |
<p>In Tomcat 5.5 the server.xml can have many connectors, typically port only 8080, but for my application a user might configure their servlet.xml to also have other ports open (say 8081-8088). I would like for my servlet to figure out what socket connections ports will be vaild (During the Servlet.init() tomcat has not yet started the connectors.) </p>
<p>I could find and parse the server.xml myself (grotty), I could look at the thread names (after tomcat starts up - but how would I know when a good time to do that is? ) But I would prefer a solution that can execute in my servlet.init() and determine what will be the valid port range. Any ideas? A solution can be tightly bound to Tomcat for my application that's ok.</p>
| <p>In Tomcat 6.0 it should be something like:</p>
<pre><code>org.apache.catalina.ServerFactory.getServer().getServices
</code></pre>
<p>to get the services. After that you might use </p>
<pre><code>Service.findConnectors
</code></pre>
<p>which returns a Connector which finally has the method</p>
<pre><code>Connector.getPort
</code></pre>
<p>See the <a href="http://tomcat.apache.org/tomcat-6.0-doc/api/org/apache/catalina/connector/Connector.html" rel="nofollow noreferrer">JavaDocs</a> for the details.</p>
| <p>Why?</p>
<p>If you need during page generation for a image or css file URL, what's wrong with <a href="http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletRequest.html#getLocalPort()" rel="nofollow noreferrer">ServletRequest.getLocalPort()</a> or, better yet, <a href="http://java.sun.com/javaee/5/docs/api/javax/servlet/http/HttpServletRequest.html#getContextPath()" rel="nofollow noreferrer">HttpServletRequest.getContextPath()</a> for the whole shebang?</p>
| 9,128 |
<p>I'm currently writing an ASP.Net app from the UI down. I'm implementing an MVP architecture because I'm sick of Winforms and wanted something that had a better separation of concerns.</p>
<p>So with MVP, the Presenter handles events raised by the View. Here's some code that I have in place to deal with the creation of users:</p>
<pre><code>public class CreateMemberPresenter
{
private ICreateMemberView view;
private IMemberTasks tasks;
public CreateMemberPresenter(ICreateMemberView view)
: this(view, new StubMemberTasks())
{
}
public CreateMemberPresenter(ICreateMemberView view, IMemberTasks tasks)
{
this.view = view;
this.tasks = tasks;
HookupEventHandlersTo(view);
}
private void HookupEventHandlersTo(ICreateMemberView view)
{
view.CreateMember += delegate { CreateMember(); };
}
private void CreateMember()
{
if (!view.IsValid)
return;
try
{
int newUserId;
tasks.CreateMember(view.NewMember, out newUserId);
view.NewUserCode = newUserId;
view.Notify(new NotificationDTO() { Type = NotificationType.Success });
}
catch(Exception e)
{
this.LogA().Message(string.Format("Error Creating User: {0}", e.Message));
view.Notify(new NotificationDTO() { Type = NotificationType.Failure, Message = "There was an error creating a new member" });
}
}
}
</code></pre>
<p>I have my main form validation done using the built in .Net Validation Controls, but now I need to verify that the data sufficiently satisfies the criteria for the Service Layer.</p>
<p>Let's say the following Service Layer messages can show up:</p>
<ul>
<li>E-mail account already exists (failure)</li>
<li>Refering user entered does not exist (failure)</li>
<li>Password length exceeds datastore allowed length (failure)</li>
<li>Member created successfully (success)</li>
</ul>
<p>Let's also say that more rules will be in the service layer that the UI cannot anticipate.</p>
<p>Currently I'm having the service layer throw an exception if things didn't go as planned. Is that a sufficent strategy? Does this code smell to you guys? If I wrote a service layer like this would you be annoyed at having to write Presenters that use it in this way? Return codes seem too old school and a bool is just not informative enough.</p>
<hr>
<blockquote>
<p><strong>Edit not by OP: merging in follow-up comments that were posted as answers by the OP</strong></p>
</blockquote>
<hr>
<p>Cheekysoft, I like the concept of a ServiceLayerException. I already have a global exception module for the exceptions that I don't anticipate. Do you find making all these custom exceptions tedious? I was thinking that catching base Exception class was a bit smelly but wasn't exactly sure how progress from there.</p>
<p>tgmdbm, I like the clever use of the lambda expression there!</p>
<hr>
<p>Thanks Cheekysoft for the follow-up. So I'm guessing that would be the strategy if you don't mind the user being displayed a separate page (I'm primarily a web developer) if the Exception is not handled.</p>
<p>However, if I want to return the error message in the same view where the user submitted the data that caused the error, I would then have to catch the Exception in the Presenter?</p>
<p>Here's what the CreateUserView looks like when the Presenter has handled the ServiceLayerException:</p>
<p><img src="https://i.stack.imgur.com/HOJU7.png" alt="Create a user"></p>
<p>For this kind of error, it's nice to report it to the same view. </p>
<p>Anyways, I think we're going beyond the scope of my original question now. I'll play around with what you've posted and if I need further details I'll post a new question.</p>
| <p>That sounds just right to me. Exceptions are preferable as they can be thrown up to the top of the service layer from anywhere inside the service layer, no matter how deeply nested inside the service method implementation it is. This keeps the service code clean as you know the calling presenter will always get notification of the problem.</p>
<p><strong>Don't catch Exception</strong></p>
<p>However, <a href="https://stackoverflow.com/questions/21938/is-it-really-that-bad-to-catch-a-general-exception">don't catch Exception</a> in the presenter, I know its tempting because it keeps the code shorter, but you need to catch specific exceptions to avoid catching the system-level exceptions. </p>
<p><strong>Plan a Simple Exception Hierarchy</strong></p>
<p>If you are going to use exceptions in this way, you should design an exception hierarchy for your own exception classes.
At a minumum create a ServiceLayerException class and throw one of these in your service methods when a problem occurs. Then if you need to throw an exception that should/could be handled differently by the presenter, you can throw a specific subclass of ServiceLayerException: say, AccountAlreadyExistsException.</p>
<p>Your presenter then has the option of doing</p>
<pre><code>try {
// call service etc.
// handle success to view
}
catch (AccountAlreadyExistsException) {
// set the message and some other unique data in the view
}
catch (ServiceLayerException) {
// set the message in the view
}
// system exceptions, and unrecoverable exceptions are allowed to bubble
// up the call stack so a general error can be shown to the user, rather
// than showing the form again.
</code></pre>
<p>Using inheritance in your own exception classes means you are not required to catch multipile exceptions in your presenter -- you can if there's a need to -- and you don't end up accidentally catching exceptions you can't handle. If your presenter is already at the top of the call stack, add a catch( Exception ) block to handle the system errors with a different view.</p>
<p>I always try and think of my service layer as a seperate distributable library, and throw as specific an exception as makes sense. It is then up to the presenter/controller/remote-service implementation to decide if it needs to worry about the specific details or just to treat problems as a generic error.</p>
| <p>In reply to the follow-up question:</p>
<p>As for creating exceptions becoming tedious, you kinda get used to it. Use of a good code generator or template can create the exception class with minimal hand editing within about 5 or 10 seconds. </p>
<p>However, in many real world applications, error handling can be 70% of the work, so it's all just part of the game really. </p>
<p>As tgmdbm suggests, in MVC/MVP applications I let all my unhandlable exceptions bubble up to the top and get caught by the dispatcher which delegates to an ExceptionHandler. I set it up so that it uses an ExceptionResolver that looks in the config file to choose an appropriate view to show the user. Java's Spring MVC library does this very well. Here's a snippet from a config file for Spring MVC's Exception resolver - its for Java/Spring but you'll get the idea.</p>
<p>This takes a huge amount of exception handling out of your presenters/controllers altogether.</p>
<pre><code><bean id="exceptionResolver"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="UserNotFoundException">
rescues/UserNotFound
</prop>
<prop key="HibernateJdbcException">
rescues/databaseProblem
</prop>
<prop key="java.net.ConnectException">
rescues/networkTimeout
</prop>
<prop key="ValidationException">
rescues/validationError
</prop>
<prop key="EnvironmentNotConfiguredException">
rescues/environmentNotConfigured
</prop>
<prop key="MessageRejectedPleaseRetryException">
rescues/messageRejected
</prop>
</props>
</property>
<property name="defaultErrorView" value="rescues/general" />
</bean>
</code></pre>
| 4,181 |
<p>I have CruiseControl.NET Version 1.4 set up on my development server. Whenever a developer checks in code, it makes a compile. </p>
<p>Now we're at a place where we can start giving our application to the testers. We'd like to use ClickOnce to distribute the application, with the idea being that when a tester goes to test the application, they have the latest build. </p>
<p>I can't find a way to make that happen with CruiseControl.NET. We're using MSBUILD to perform the builds.</p>
| <p>We've done this and can give you some pointers to start.</p>
<p>2 things you should be aware of:</p>
<ul>
<li>MSBuild can generate the necessary deployment files for you.</li>
<li>MSBuild won't deploy the files to the FTP or UNC share. You'll need a separate step for this.</li>
</ul>
<p>To use MSBuild to generate the ClickOnce manifests, here's the command you'll need to issue:</p>
<pre><code>msbuild /target:publish /p:Configuration=Release /p:Platform=AnyCPU; "c:\yourProject.csproj"
</code></pre>
<p>That will tell MSBuild to build your project and generate ClickOnce deployment files inside the <em>bin\Release\YourProject.publish</em> directory.</p>
<p>All that's left is to copy those files to the FTP/UNC share/wherever, and you're all set.</p>
<p>You can tell CruiseControl.NET to build using those MSBuild parameters.</p>
<p>You'll then need a CruiseControl.NET build task to take the generated deployment files and copy them to the FTP or UNC share. We use a custom little C# console program for this, but you could just as easily use a Powershell script.</p>
| <p>You want to use the ClickOnce manifest generation tasks in msbuild. The process is a little long winded, so I am just going to point you to a couple of links. Here is the <a href="http://msdn.microsoft.com/en-us/library/6wc2ccdc.aspx" rel="nofollow noreferrer">reference on msdn</a> and a <a href="http://windowsclient.net/articles/ClickOnce_MsBuild.aspx" rel="nofollow noreferrer">sample article</a> to hopefully get you started.</p>
| 3,349 |
<p>I've got an MS-Access app (1/10th MS-Acccess, 9/10ths MS-SQL) that needs to display photographs of some assets along with their specifications. Currently the images are stored in an MS-Access table as an OLE Object (and copy-n-pasted into the field by the users).</p>
<p>For various reasons, I would like to do is store the original .jpgs in a folder on the network drive, and reference them from the application portion. I have considered moving into MS-SQL's image data type (and its replacement varbinary), but I think my user population will more easily grasp the concept of the network folder.</p>
<p>How can I get MS Access to display the contents of a .jpg?</p>
| <p>Another option is to put an image control on your form. There is a property of that control (Picture) that is simply the path to the image. Here is a short example in VBA of how you might use it.</p>
<p>txtPhoto would be a text box bound to the database field with the path to the image
imgPicture is the image control
The example is a click event for a button that would advance to the next record.</p>
<pre><code>Private Sub cmdNextClick()
DoCmd.GoToRecord , , acNext
txtPhoto.SetFocus
imgPicture.Picture = txtPhoto.Text
Exit Sub
End Sub
</code></pre>
| <p>The easiest way is probably to plop an Internet Explorer onto one of your forms. Check out this site: <a href="http://www.acky.net/tutorials/vb/wbrowser/" rel="nofollow noreferrer">http://www.acky.net/tutorials/vb/wbrowser/</a></p>
<p>Since you can reference that object in Access, you will only need to point the webbrowser control to the path of the .jpg (NavigateTo() if I remember correctly).</p>
<p><strong>EDIT:</strong> The above link was just googled and picked from the results (first one that opened quickly). I do not think it is a very good tutorial, it just has all the pointers you need... Check out msdn etc. if you need more information!</p>
| 6,130 |
<p>I have a class with a bunch of properties that look like this:</p>
<pre><code>public string Name
{
get { return _name; }
set { IsDirty = true; _name = value; }
}
</code></pre>
<p>It would be a lot easier if I could rely on C# 3.0 to generate the backing store for these, but is there any way to factor out the IsDirty=true; so that I can write my properties something like this and still get the same behaviour:</p>
<pre><code>[MakesDirty]
public string Name { get; set; }
</code></pre>
| <p><strong>No. Not without writing considerably more (arcane?) code than the original version</strong> (You'd have to use reflection to check for the attribute on the property and what not.. did I mention it being 'slower').. This is the kind of duplication I can live with.</p>
<p>MS has the same need for <a href="http://msdn.microsoft.com/en-us/library/ms229614.aspx" rel="nofollow noreferrer">raising events when a property is changed</a>. INotifyPropertyChanged that is a vital interface for change notifications. Every implementation I've seen yet
does</p>
<pre><code>set
{
_name = value;
NotifyPropertyChanged("Name");
}
</code></pre>
<p>If it was possible, I'd figure those smart guys at MS would already have something like that in place.. </p>
| <p>The other alternative might be a code generator such as codesmith to automate creating the properties. This would be especially useful if the properties you are creating are columns in a database table</p>
| 8,899 |
<p>Is there a risk of legal trouble if you include GPL or LGPL licensed icons in a closed source software? </p>
<p>Would it force it to become open source just to include the icon?</p>
<p>Does it matter if the icon is compiled as a resource?</p>
<p>Are the creative common licensed icons safe to use if you follow the attribution rules specified by the license?</p>
| <p>For GPL, yes. Any GPL Code/Content that's compiled into your Application or the Package will make it GPL. (Edit: What could be safe is if the Icon is a separate file and is used. That could be a grey area, as you are not using GPL Code to access it. But any attempt to embed it will force your program to GPL, it's one of the most restrictive licenses out there)</p>
<p>LGPL is fine: Any modification to LGPL Content has to be released under LGPL, but using the Code/Content is safe.</p>
<p>Addition: Like LGPL, CreativeCommons usually only affects the Content you're using. So if you're using a CC Icon and modify it, you will have to give out the modified item under CreativeCommons, but your Application is not affected. Just mind the "Non-Commercial" Clause if it exists.</p>
| <p>It's a tricky area, at a minimum you should probably arrange for the icons to be loaded at run time so that they can be replaced with other versions, this is at least the spirit of the GPL. </p>
<p>An article discusses this at <a href="http://www.linux.com/feature/119212" rel="nofollow noreferrer">http://www.linux.com/feature/119212</a></p>
| 7,035 |
<p>My current view is no, prefer Transact SQL stored procedures because they are a lighter weight and (possibly) higher performing option, while CLR procedures allow developers to get up to all sorts of mischief.</p>
<p>However recently I have needed to debug some very poorly written TSQL stored procs. As usual I found many of the problems due to the original developer developer having no real TSQL experience, they were ASP.NET / C# focused.</p>
<p>So, using CLR procedures would firstly provide a much more familiar toolset to this type of developer, and secondly, the debugging and testing facilities are more powerful (ie Visual Studio instead of SQL Management Studio). </p>
<p>I'd be very interested in hearing your experience as it's seems it is not a simple choice. </p>
| <p>There are places for both well-written, well-thought-out T-SQL and CLR. If some function is not called frequently and if it required extended procedures in SQL Server 2000, CLR may be an option. Also running things like calculation right next to the data may be appealing. But solving bad programmers by throwing in new technology sounds like a bad idea.</p>
| <p>I would add a couple of reasons to use CLR that may not have been mentioned.</p>
<ul>
<li>Replace and extend basic query, non-query, and scalar sql functions.<br>
A) Error reporting and alerts can be integrated based upon defined requirements.
B) Easily define debugging levels.
C) Enable an easier way to interact with foreign SQL servers </li>
<li>Move legacy code to a managed environment.</li>
</ul>
| 8,259 |
<p>Hopefully, I can get answers for each database server.</p>
<p>For an outline of how indexing works check out: <a href="https://stackoverflow.com/questions/1108/how-does-database-indexing-work">How does database indexing work?</a></p>
| <p>The following is SQL92 standard so should be supported by the majority of RDMBS that use SQL:</p>
<pre><code>CREATE INDEX [index name] ON [table name] ( [column name] )
</code></pre>
| <p>Since most of the answers are given for SQL databases, I am writing this for NOSQL databases, specifically for MongoDB.</p>
<p>Below is the syntax to create an index in the MongoDB using mongo shell.</p>
<pre><code>db.collection.createIndex( <key and index type specification>, <options> )
</code></pre>
<p>example - <code>db.collection.createIndex( { name: -1 } )</code></p>
<p>In the above example an single key descending index is created on the name
field. </p>
<p>Keep in mind MongoDB indexes uses B-tree data structure.</p>
<p>There are multiple types of indexes we can create in mongodb, for more information refer to below link - <a href="https://docs.mongodb.com/manual/indexes/" rel="nofollow noreferrer">https://docs.mongodb.com/manual/indexes/</a></p>
| 2,357 |
<p>If you were to self-fund a software project which tools, frameworks, components would you employ to ensure maximum productivity for the dev team and that the "real" problem is being worked on.</p>
<p>What I'm looking for are low friction tools which get the job done with a minimum of fuss. Tools I'd characterize as such are SVN/TortioseSVN, ReSharper, VS itself. I'm looking for frameworks which solve the problems inherient in all software projects like ORM, logging, UI frameworks/components. An example on the UI side would be ASP.NET MVC vs WebForms vs MonoRail.</p>
| <ul>
<li><strong>Versioning.</strong> <em>Subversion</em> is the popular choice. If you can afford it, <em>Team Foundation Server</em> offers some benefits. If you want to be super-modern, consider a distributed versioning system, such as <em>git</em>, <em>bazaar</em> or <em>Mercurial</em>. Whatever you do, don't use SourceSafe or other lock-based tools, but rather merge-baseed ones. Consider installing both a Windows Explorer client (such as <em>TortoiseSVN</em>) as well as a Visual Studio add-in (such as <em>AnkhSVN</em> or <em>VisualSVN</em>).</li>
<li><strong>Issue tracking.</strong> Given that Joel Spolsky is on this site's staff, <em>FogBugz</em> deserves a mention. <em>Trac</em>, <em>Mantis</em> and <em>BugZilla</em> are widespread open-source choices.</li>
<li><strong>Continuous integration.</strong> <em>CruiseControl.NET</em> is a popular and open-source choice. There's also <em>Draco.NET</em>.</li>
<li><strong>Unit testing.</strong> <em>NUnit</em> is the popular open-source choice. Does the job. Consider installing the <em>TestDriven.NET</em> Visual Studio add-in.</li>
</ul>
<p>That said, you want to look at the answers to <a href="https://stackoverflow.com/questions/2187/essential-programming-tools">Essential Programming Tools</a> and <a href="https://stackoverflow.com/questions/23490/what-is-your-best-list-of-must-have-development-tools">What is your best list of ‘must have’ development tools?</a>; while not .NET-specific, they should apply anyway.</p>
| <p>I'd definitely recommend Coderush+Refactor or Resharper (Coderush being my personal favourite), these tools dramatically reduce the time to go from code in your head to code on the page.</p>
<p>For quick development the UI component sets from the likes of Telerik/DevExpress/Infragistics can be good, but in my experience can cause pain further out in the project when you want to refine things more precisely.</p>
<p>Regarding frameworks etc I think you'd need to be a bit more specific about the project itself to get any meaningful suggestions.</p>
| 8,633 |
<p>How do you back up your development machine so that in the event of a catastrophic hardware malfunction, you are up and running in the least amount of time possible?</p>
| <p>There's an important distinction between backing up your development machine and backing up your work.</p>
<p>For a development machine your best bet is an imaging solution that offers as near a "one-click-restore" process as possible. TimeMachine (Mac) and Windows Home Server (Windows) are both excellent for this purpose. Not only can you have your entire machine restored in 1-2 hours (depending on HDD size), but both run automatically and store deltas so you can have months of backups in relatively little space. There are also numerous "ghosting" packages, though they usually do not offer incremental/delta backups so take more time/space to backup your machine.</p>
<p>Less good are products such as Carbonite/Mozy/JungleDisk/RSync. These products WILL allow you to retrieve your data, but you will still have to reinstall the OS and programs. Some have limited/no histories either.</p>
<p>In terms of backing up your code and data then I would recommend a sourcecode control product like SVN. While a general backup solution will protect your data, it does not offer the labeling/branching/history functionality that SCC packages do. These functions are invaluable for any type of project with a shelf-life.</p>
<p>You can easily run a SVN server on your local machine. If your machine is backed up then your SVN database will be also. This IMO is the best solution for a home developer and is how I keep things.</p>
| <p>Maybe just a simple hardware hard disk raid would be a good start. This way if one drive fails, you still have the other drive in the raid. If something other than the drives fail you can pop these drives into another system and get your files quickly.</p>
| 4,638 |
<p>Are there any <strong>tools</strong> to facilitate a migration from <a href="http://www.sourcegear.com/vault/index.html" rel="noreferrer">Sourcegear's Vault</a> to <a href="http://subversion.tigris.org/" rel="noreferrer">Subversion</a>?</p>
<p>I'd really prefer an existing tool or project (I'll buy!).</p>
<p><strong>Requirements:</strong></p>
<ol>
<li>One-time migration only</li>
<li>Full history with comments</li>
</ol>
<p><strong>Optional:</strong></p>
<ol>
<li>Some support for labels/branches/tags</li>
<li>Relatively speedy. It can take hours but not days.</li>
<li>Cost if available</li>
</ol>
<p>Bonus points if you can share personal experience related to this process.</p>
<hr>
<p>One of the reasons I'd like to do this is because we have lots of projects spread between Vault and Subversion (we're finally away from sourcesafe). It'd be helpful in some situations to be able to consolidate a particular customer's repos to SVN.</p>
<p>Additionally, SVN is better supported among third party tools. For example, <a href="http://hudson.dev.java.net/" rel="noreferrer">Hudson</a> and <a href="http://www.redmine.org/" rel="noreferrer">Redmine</a>.</p>
<p>Again, though: we're not abandoning vault altogether.</p>
| <p>We are thinking about migrating from vault to git. I wrote vault2git converter that takes care of history and removes vault bindings from *.sln, *.csproj files.</p>
<p>Once you have git repo, there is git2svn.</p>
<p>I know it sounds like going rounds, but it might be faster than writing vault2svn from scratch.</p>
| <p>Free. The vault user license costs have tripled since we went to it.</p>
| 8,181 |
<p>I am writing a Java utility that helps me to generate loads of data for performance testing. It would be <em>really</em> cool to be able to specify a regex for Strings so that my generator spits out things that match this.</p>
<p>Is something out there already baked that I can use to do this? Or is there a library that gets me most of the way there?</p>
| <p><strong>Edit:</strong></p>
<p>Complete list of suggested libraries on this question:</p>
<ol>
<li><a href="https://code.google.com/archive/p/xeger/" rel="noreferrer">Xeger</a>* - Java</li>
<li><a href="https://github.com/mifmif/Generex" rel="noreferrer">Generex</a>* - Java</li>
<li><a href="https://github.com/curious-odd-man/RgxGen" rel="noreferrer">Rgxgen</a> - Java</li>
<li><a href="https://github.com/GoranSiska/rxrdg" rel="noreferrer">rxrdg</a> - C#</li>
</ol>
<p>* - Depends on <code>dk.brics.automaton</code></p>
<p><strong>Edit:</strong>
As mentioned in the comments, there is a library available at Google Code to achieve this:
<a href="https://code.google.com/archive/p/xeger/" rel="noreferrer">https://code.google.com/archive/p/xeger/</a></p>
<p>See also <a href="https://github.com/mifmif/Generex" rel="noreferrer">https://github.com/mifmif/Generex</a> as suggested by <a href="https://stackoverflow.com/a/24659605/1820">Mifmif</a></p>
<p><strong>Original message:</strong></p>
<p>Firstly, with a complex enough regexp, I believe this can be impossible. But you should be able to put something together for simple regexps.</p>
<p>If you take a look at the source code of the class java.util.regex.Pattern, you'll see that it uses an internal representation of Node instances. Each of the different pattern components have their own implementation of a Node subclass. These Nodes are organised into a tree.</p>
<p>By producing a visitor that traverses this tree, you should be able to call an overloaded generator method or some kind of Builder that cobbles something together.</p>
| <p>If you want to generate "critical" strings, you may want to consider:</p>
<p>EGRET <a href="http://elarson.pythonanywhere.com/" rel="nofollow noreferrer">http://elarson.pythonanywhere.com/</a>
that generates "evil" strings covering your regular expressions</p>
<p>MUTREX <a href="http://cs.unibg.it/mutrex/" rel="nofollow noreferrer">http://cs.unibg.it/mutrex/</a>
that generates fault-detecting strings by regex mutation</p>
<p>Both are academic tools (I am one of the authors of the latter) and work reasonably well.</p>
| 4,211 |
<p>Laboratory centrifuges have buckets that hold the sample tubes in inserts.</p>
<p>The buckets are the black things on the rotor in the upper left corner holding the bottles. Examples of inserts are shown below (the colorful containers with slots for tubes). These fit into the buckets and I'd like to print them since these are expensive.</p>
<p>Is it safe to 3d print these using a makerbot given the g-forces these rotor inserts will be subjected to (potentially 150g's under our settings), or will the inserts deform and unbalance the rotors under the stress? </p>
<p>Additionally, is the precision of the printing good enough that the inserts can be expected to be well-balanced (the correct weight, with a symetric design having even weight distribution)?</p>
<p>We have a basic makerbot that makes little plastic robots.</p>
<p><a href="https://i.stack.imgur.com/VVFZg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VVFZg.png" alt="enter image description here"></a></p>
| <p>It's difficult to determine if the buckets are fully enclosed, but I suspect that they are. The enclosure into which the inserts are placed will provide some structural support. </p>
<p>3D printed objects have relatively low torsion strength, but a reasonable compression strength, especially with high infill levels. One could consider that the item placed into the insert will transmit force to the bucket, but likely not compress to the point of destruction.</p>
<p>Allowing also that the forces on a swinging bucket centrifuge are "downward" or when in use, "outward," the primary location of force will be the bottom of the insert you create. It appears that the main function of the insert is to keep the tubes separated, rather than to keep them supported.</p>
<p>Create your inserts, but leave an open bottom. Attach a suitably strong panel to the bottom of your created model with epoxy.</p>
<p>Another thing to consider in this project is the mode of failure. What can go wrong? The tubes in the insert should not explode, but if they do, is it merely cleaning up that follows? I suppose one aspect of the inserts is to keep the tube walls in column, to keep all forces linear to the tube cylinder, rather than out of line. It's easy to keep pennies in a stack under pressure, but don't push on them edgewise.</p>
<p>You can and should perform a test on a 3D printed insert. Make one that is relatively flimsy, say a six-tube unit and spin it without tubes in place. Test it prior to the spin for tube fit, then test it after the spin. If there is deformation, you would not be able to insert the tubes after the spin.</p>
| <p>The primary printer I use is a makerbot, and my gut is saying no. </p>
<p>150G's of loading even in the XY axis seems pretty excessive for a part made on a Makerbot. Also, given that this is a rotational, the weight and balance will need to be held to a pretty high tolerance otherwise you'll end up having an off-balance centrifuge which could damage a pretty expensive piece of equipment. Admittedly I haven't checked the reliability for weight and balance of a part I've made for the loading condition you'd be going through but I'd be pretty hesitant about trying to run any FDM printed part under a loading case like that Makerbot or a high end printer given the speeds you'll be at. </p>
<p>If it's your only option though, I'd suggest running your centrifuge at a very low speed first with the part in it and check it to see if you're picking up any transient vibration from it. Increasing the speed as you feel comfortable. My gut says that it'll fail before getting up to full speed from out of balance CofG of the part and the centrifuge starting to shake. Sounds terrifyingly fun to try though. IF you do try and run it,c an you post what happens? I'd be very interested in hearing the results.</p>
| 551 |
<p>I'm not sure whether I'm asking the question correctly, but I've been told SQL Server cannot run on a Novell server. Is this true? If yes, why not?</p>
| <p>NOW I see your problem! Sorry dude!</p>
<p>Yes, VERY easy. Kinda.</p>
<p>SQL Server used to be able to talk IPX (the netware protocol) but I think Netware will now talk TCPIP, and you can run IPX and TCP/IP on the same network without an issue - windows clients can run both at the same time, 99% of routers handle all protocols etc.</p>
<p>Windows (XP/2003/etc) can run the netware client, so it can talk to shares etc. </p>
<p>Use the SQL Server logins (rather than windows integrated logins), and it'll work from anything - we have Java on Linux talking to SQL Server on windows just fine :) It's all in the connection string: userid=username;pwd=whatever;server=yourserverhere; etc. But you MUST use the SQL Server Configuration Manager to set these up - the default is shared memory, so you have to enable TCPIP etc.</p>
| <p>The core issue is how are you authenticating to the SQL database. If you have an Active Directory tree, and an eDirectory you can easily link the two via Novell Identity Manager, which will synchronize users, groups, etc (any object you care to map between the two systems) as well as passwords.</p>
<p>Thus the same object exists in both locations so each system can use it as much it needs too. The license for Identity Manager is included with the Open Enterprise Server license (OES can run on Netware or on SUSE Linux Enterprise Server (SLES)).</p>
<p>Then you could use the Active Directory integrated authentication.</p>
<p>Beyond that, your Netware server likely does not need to connect to the database directly. If it does, you will be writing or using an application that includes the database connectivity. At which point it becomes a question of is there a client for this OS or not.</p>
| 5,206 |
<p>Any good suggestions? Input will be the name of a header file and output should be a list (preferably a tree) of all files including it directly or indirectly.</p>
| <p>If you have access to GCC/G++, then the <a href="http://gcc.gnu.org/onlinedocs/gcc/Preprocessor-Options.html#Preprocessor-Options" rel="noreferrer"><code>-M</code> option</a> will output the dependency list. It doesn't do any of the extra stuff that the other tools do, but since it is coming from the compiler, there is no chance that it will pick up files from the "wrong" place.</p>
| <p><a href="http://www.scitools.com/products/understand/" rel="nofollow noreferrer">Understand for C++</a> should be able to help you: it builds a database that you can access from Perl.</p>
| 6,375 |
<p>I have always wondered how people update a previous line in a command line. a great example of this is when using the wget command in linux. It creates an ASCII loading bar of sorts that looks like this:</p>
<blockquote>
<p>[======> ] 37%</p>
</blockquote>
<p>and of course the loading bar moves and the percent changes, But it doesn't make a new line. I cannot figure out how to do this. Can someone point me in the right direction?</p>
| <p>There are two ways I know of to do this:</p>
<ul>
<li>Use the backspace escape character ('\b') to erase your line</li>
<li>Use the <code>curses</code> package, if your programming language of choice has bindings for it.</li>
</ul>
<p>And a Google revealed <a href="http://en.wikipedia.org/wiki/ANSI_escape_code" rel="noreferrer">ANSI Escape Codes</a>, which appear to be a good way. For reference, here is a function in C++ to do this:</p>
<pre><code>void DrawProgressBar(int len, double percent) {
cout << "\x1B[2K"; // Erase the entire current line.
cout << "\x1B[0E"; // Move to the beginning of the current line.
string progress;
for (int i = 0; i < len; ++i) {
if (i < static_cast<int>(len * percent)) {
progress += "=";
} else {
progress += " ";
}
}
cout << "[" << progress << "] " << (static_cast<int>(100 * percent)) << "%";
flush(cout); // Required.
}
</code></pre>
| <p>If your using a scripting language you could use the "tput cup" command to get this done...
P.S. This is a Linux/Unix thing only as far as I know...</p>
| 8,506 |
<p>I'm trying to serialize a Type object in the following way:</p>
<pre><code>Type myType = typeof (StringBuilder);
var serializer = new XmlSerializer(typeof(Type));
TextWriter writer = new StringWriter();
serializer.Serialize(writer, myType);
</code></pre>
<p>When I do this, the call to Serialize throws the following exception: </p>
<blockquote>
<p>"The type System.Text.StringBuilder was not expected. Use the
XmlInclude or SoapInclude attribute to specify types that are not
known statically."</p>
</blockquote>
<p>Is there a way for me to serialize the <code>Type</code> object? Note that I am not trying to serialize the <code>StringBuilder</code> itself, but the <code>Type</code> object containing the metadata about the <code>StringBuilder</code> class.</p>
| <p>I wasn't aware that a Type object could be created with only a string containing the fully-qualified name. To get the fully qualified name, you can use the following:</p>
<pre><code>string typeName = typeof (StringBuilder).FullName;
</code></pre>
<p>You can then persist this string however needed, then reconstruct the type like this:</p>
<pre><code>Type t = Type.GetType(typeName);
</code></pre>
<p>If you need to create an instance of the type, you can do this:</p>
<pre><code>object o = Activator.CreateInstance(t);
</code></pre>
<p>If you check the value of o.GetType(), it will be StringBuilder, just as you would expect.</p>
| <p>Just looked at its definition, it is not marked as Serializable. If you really need this data to be serialize, then you may have to convert it to a custom class that is marked as such.</p>
<pre><code>public abstract class Type : System.Reflection.MemberInfo
Member of System
Summary:
Represents type declarations: class types, interface types, array types, value types, enumeration types, type parameters, generic type definitions, and open or closed constructed generic types.
Attributes:
[System.Runtime.InteropServices.ClassInterfaceAttribute(0),
System.Runtime.InteropServices.ComDefaultInterfaceAttribute(System.Runtime.InteropServices._Type),
System.Runtime.InteropServices.ComVisibleAttribute(true)]
</code></pre>
| 3,336 |
<p>I have a new Creality Ender 3.</p>
<p>I suspect that I have not adjusted the eccentric nuts correctly, on the X-axis head carriage mounts. </p>
<p>Even after a glass bed upgrade, using the Level Corners routine of the TH3D firmware, I can get the head to scrape a sheet of paper all 4 corners but that same sheet of paper does not then scrape the head in the center, unless I fold that paper in half.</p>
<p>I could understand this if the rail on which the hot end travels is very slightly higher at the side opposite the extruder. I have tried turning the eccentric nut on that side until the head does trap the paper, but when I then repeat the Level Corners routine, the gap at the center has come right back.</p>
<p>I already adjusted the eccentric nut on the extruder end because the wheels on the hot end carriage were showing an accumulation of brown dust in a ring around each wheel, which I heard was likely a sign that the carriage was "too tight."
So basically, I am messing around with the eccentric nuts at both ends of the X-axis rail, chasing two problems at the same time, but I don't really know what I am doing.</p>
<p>Recommendations?</p>
| <p>This seems to be a common problem with ender-3 and cr-10 printers from Creality. Mine is the same way but not enough to keep prints from adhering. </p>
<p>Typically the aluminum bed is not perfectly flat. If it’s not the glass may be able to flex enough that it can make a difference. There are a few ways to try to fix it. </p>
<ol>
<li><p>Shim the low spots in the aluminum bed with aluminum foil or another thin material. Then the glass will sit on a flatter more well supported surface. </p></li>
<li><p>Bend the aluminum bed until it is flat.</p></li>
<li>Add a 5th leveling point under the middle of the bed. You could either make it adjustable which would be tricky to get to or create a support piece accurately or get one close and shim it. </li>
</ol>
<p>The shimming process is probably the easiest and the one I may end up doing. But whether you shim it or do the other trick you need to measure for points that are out of flat. </p>
<p>If you get a decent straightedge and some feeler gauges and/or or shine a bright light from the other side and look for spots of light between the straightedge and the aluminum bed you can see where you need to shim or otherwise adjust it. You’ll need to move it at various angles through the center and other spots on the bed. That way you can see whether it is just the middle or if the edges are an issue too. </p>
<p>Also, once you check the aluminum bed, check the glass as it may not be flat either.</p>
<p>There was a YouTube video on the cr-10 I think that showed part of the shimming process and checking for level. I’ll try to see if I can find it to add a link here. </p>
<p>I still didn't find the video I was looking for, but here is a useful related one that talks about tramming the bed (what 3d printing people call leveling)
<a href="https://www.youtube.com/watch?v=CcAmZqb-ZEE" rel="noreferrer">https://www.youtube.com/watch?v=CcAmZqb-ZEE</a></p>
<p>And here's a reddit thread about the issue. Someone incorrectly says the glass plate can't flex that much but it certainly can. We're talking small tolerances. Even granite slabs flex small amounts.
<a href="https://www.reddit.com/r/CR10/comments/7d7gyh/aluminum_bed_warped_cant_get_it_to_do_anything/" rel="noreferrer">https://www.reddit.com/r/CR10/comments/7d7gyh/aluminum_bed_warped_cant_get_it_to_do_anything/</a></p>
| <p>I had the same exact issue, you have to make sure all of your printer is leveled, start with the base, than the poles that hold your x axis gantry. there are numerous youtube videos on how to do that.. make sure it's all leveled and try again.. this tip helped a few people already</p>
| 1,317 |
<p>I drew a fairly simple model in Google SketchUp. I exported it as an STL. I imported it into Cura and exported as gcode. Then I printed the model.</p>
<p>All of the bottom layers of the model cover the entire space instead of leaving the two open gaps that should exist. I don't know why it's happening. Do I have some weird setting in Cura? </p>
<p>The section that is filled, but shouldn't be, isn't a raft. I printed without a raft because my model goes to the max extent that my printer can print and I don't have room for a raft around the edges. </p>
<p>Here is what it looks like in SketchUp:</p>
<p><a href="https://i.stack.imgur.com/EumMr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EumMr.png" alt="SketchUp model"></a></p>
<p>Here is what it looks like in Cura. The two empty areas are shaded darker than the other empty areas of the build plate. Is that an indication of my problem?</p>
<p><a href="https://i.stack.imgur.com/GGgFE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GGgFE.png" alt="Cura Build Plate"></a></p>
<p>Here is what was printed. The empty areas are solid and filled in as if the center piece extended to the inner edges of that area. (The jacked up corners are due to the model warping a bit and no longer being in the right position for subsequent layers.)</p>
<p><a href="https://i.stack.imgur.com/4nQbY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4nQbY.jpg" alt="enter image description here"></a></p>
<p>Here is a video of the layers according to Cura, and Cura clearly knows the gaps should be there:</p>
<p><a href="https://youtu.be/r0a9gGFerHI" rel="nofollow noreferrer">https://youtu.be/r0a9gGFerHI</a></p>
| <p>I suspect, as I am wont to do, that your problem lies in the STL created by SketchUp. It's an unfortunate aspect of that program that it creates non-manifold models which creates troubles such as this. </p>
<p>Consider to load your STL file into a program suitable for showing flaws (and repairing them) to determine where the failure points lie. I'm fond of Meshmixer, but there are many others such as Netfabb with which I am less familiar.</p>
<p>If you don't want to check your STL file, attach it to your post and I'll take a shot at it. </p>
<p>You would also want to consider to learn a new program if you intend to perform such 3D modeling. Fusion 360 has a popular following. I'm a fan of OpenScad, but use Fusion 360, Meshmixer, Blender (only a tiny amount) and anything else I can utilize for model repair, creation and editing. Build a large repetoire of different programs and get the best of all worlds.</p>
<p>SketchUp has a strong following primarily because it's rather easy to use. The same can be said of a few other programs, but SketchUp really generates trouble when it comes to 3D models.</p>
<p>TinkerCAD is very much like SketchUp and will give you better final results. OnShape is another popular modeling program, but I have zero exposure to that one.</p>
<p>It's not out of the question that there's a bug in Cura that's causing this problem. You are not limited to one slicer program, and you can check the results of another slicer such as Slic3r, Craftware or others.</p>
| <p>You have a problem with your STL file. Check the orientation of the faces of your 3D model, if that is not the problem, search for a software to fix your stl file. Just a tip, give Fusion360 a try, it is the best!</p>
| 758 |
<p>Given the following:</p>
<pre><code>List<List<Option>> optionLists;
</code></pre>
<p>what would be a quick way to determine the subset of Option objects that appear in all N lists? Equality is determined through some string property such as option1.Value == option2.Value.</p>
<p>So we should end up with <code>List<Option></code> where each item appears only once.</p>
| <p>Ok, this will find the list of Option objects that have a Value appearing in <em>every</em> list.</p>
<pre><code>var x = from list in optionLists
from option in list
where optionLists.All(l => l.Any(o => o.Value == option.Value))
orderby option.Value
select option;
</code></pre>
<p>It doesn't do a "distinct" select so it'll return multiple Option objects, some of them with the same Value.</p>
| <p>Sort, then do something akin to a merge-sort.</p>
<p>Basically you would do this:</p>
<ol>
<li>Retrieve the first item from each list</li>
<li>Compare the items, if equal, output</li>
<li>If any of the items are before the others, sort-wise, retrieve a new item from the corresponding list to replace it, otherwise, retrieve new items to replace them all, from all the list</li>
<li>As long as you still got items, go back to 2.</li>
</ol>
| 6,242 |
<p>Say I have:</p>
<pre><code><ul>
<li id="x">
<a href="x">x</a>
</li>
<li id="y">
<a href="y">y</a>
<ul>
<li id="z">
<a href="z">z</a>
</li>
</ul>
</li>
</ul>
</code></pre>
<p>I want to add a class value to all the list items that are the parents of z. So, I want to modify y but not x.</p>
<p>Obviously, I can parse this into some kind of associative array and then recurse backwards. Any ideas how I can do it with just text processing (string replacing, regular expression, etc)?</p>
<p>Thanks!</p>
| <p>I would use XSLT. You can specify to search for nodes that are ancestors of z .</p>
| <p>I suggest you parse it into a DOM and recurse backwards like you were thinking. Regular expressions don't work very well for nested structures with arbitrary nesting levels.</p>
| 8,110 |
<p>Things like <code>$log$</code> and <code>$version$</code> which add data upon check-in to the file. I'm interested in seeing the other ones and what information they can provide, but I can't get much info unless I know what they are called.</p>
| <p>Both Subversion and CVS call them <code>Keywords</code>.</p>
<p><a href="http://svnbook.red-bean.com/en/1.0/ch07s02.html#svn-ch-7-sect-2.3" rel="nofollow noreferrer">Have a look in the SVN manual here</a> (scroll down to <strong>svn:keywords</strong>) or <a href="http://badgertronics.com/writings/cvs/keywords.html" rel="nofollow noreferrer">here for CVS</a>.</p>
| <p>These are Keyword substitutions. The link to SVNBook 1.8 is here: <a href="http://svnbook.red-bean.com/en/1.8/svn.advanced.props.special.keywords.html" rel="nofollow noreferrer" title="Subversion Keywords">http://svnbook.red-bean.com/en/1.8/svn.advanced.props.special.keywords.html</a>.</p>
<p>Subversion's built-in keywords are:</p>
<ul>
<li>Date / LastChangedDate</li>
<li>Revision / Rev / LastChangedRevision</li>
<li>Author / LastChangedBy</li>
<li>HeadURL / URL</li>
<li>Id</li>
</ul>
<p>The keywords are case sensitive, and remember to surround them with $.</p>
| 6,092 |
<p>I found some informations about controlling IIS 5.1 from command line via adsutil.vbs (<a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/d3df4bc9-0954-459a-b5e6-7a8bc462960c.mspx?mfr=true" rel="nofollow noreferrer">http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/d3df4bc9-0954-459a-b5e6-7a8bc462960c.mspx?mfr=true</a>). The utility is available at c:\InetPub\AdminScripts.</p>
<p>The utility throw only errors like the following:
ErrNumber: -2147463164 (0x80005004)
Error Trying To GET the Schema of the property: IIS://localhost/Schema/ROOT</p>
<p>Can you tell me, how to check if there exists a virtual directory and create it, if it does not exist?</p>
| <p>The microsoft official way is just to copy them into the relevant folders (as seen by downloading their template packs). However, you could also create your own site definition and add the items to the correct libraries and lists in the same way that the master pages are added.</p>
<p>If you are going to deploy CSS and Master Pages through features remember you will have to activate your the publishing infrastructure on the site collection and the publishing feature on the site.</p>
<p>To deploy a master page/page layout as a feature you should follow the steps at the site below, you can use the "fileurl" element to specify your CSS and place it into the correct folder (style library, for example):
<a href="http://www.sharepointnutsandbolts.com/2007/04/deploying-master-pages-and-page-layouts.html" rel="nofollow noreferrer">http://www.sharepointnutsandbolts.com/2007/04/deploying-master-pages-and-page-layouts.html</a></p>
| <p>Consider uploading them to "Style Library" in the root of the site collection.
<p>If you don't have a "Style Library" at the root, consider making one -- it's just a document library.
<p>Make sure the permissions are set correctly so everyone who needs to read it can.
<p>You can reference them using "/Style%20Library/my.css" but this won't work on site collections that don't live at the root of the domain.</p>
| 7,713 |
<p>For a typical business application, should the focus be on client processing via AJAX i.e. pull the data from the server and process it on the client or would you suggest a more classic ASP.Net approach with the server being responsible for handling most of the UI events? I find it hard to come up with a good 'default architecture' from which to start. Maybe someone has an open source example application which they could recommend.</p>
| <p>It really depends on the application and the situation, but just keep in mind that every hit to the server is costly, both in adding load (perhaps minimally), but also in terms of UI responsiveness. I am of the mind that doing things in JavaScript when possible is a good idea, if it can make your UI feel snappier.</p>
<p>Of course, it all depends on what you are trying to do, and whether it matters if the UI is snappy (an internal web app probably doesn't NEED extra development to make the UI more attractive and quicker/easier to use, whereas something that is used by the general public by a mass audience probably needs to be as polished and tuned as possible).</p>
| <p>Do you need to trust the data? If so, be aware that it's trivial to tamper with client-processed data in nasty and malicious ways. If that's the case, you'll want to process info on the server.</p>
<p>Also, be aware that it can be a lot harder to code javascript apps so they are stable, reliable, and bug free. Can you lock down your users so they only use one particular browser?</p>
| 6,198 |
<p>I am using xampp on Windows, but I would like to use something closer to my server setup.</p>
<p><a href="http://phpimpact.wordpress.com/2008/05/24/virtual-appliances-lamp-development-made-easy/" rel="nofollow noreferrer">Federico Cargnelutti tutorial</a> explains how to setup LAMP VMWARE appliance; it is a great introduction to VMware appliances, but one of the commands was not working and it doesn't describe how to change the keyboard layout and the timezone.</p>
<p>ps: the commands are easy to find but I don't want to look for them each time I reinstall the server. I am using this question as a reminder.</p>
| <p>This is my install scrpt, I use it on debian servers, but it will work in Ubuntu (Ubuntu is built on Debian)</p>
<pre><code>apt-get -yq update
apt-get -yq upgrade
apt-get -yq install sudo
apt-get -yq install gcc
apt-get -yq install g++
apt-get -yq install make
apt-get -yq install apache2
apt-get -yq install php5
apt-get -yq install php5-curl
apt-get -yq install php5-mysql
apt-get -yq install php5-gd
apt-get -yq install mysql-common
apt-get -yq install mysql-client
apt-get -yq install mysql-server
apt-get -yq install phpmyadmin
apt-get -yq install samba
echo '[global]
workgroup = workgroup
server string = %h server
dns proxy = no
log file = /var/log/samba/log.%m
max log size = 1000
syslog = 0
panic action = /usr/share/samba/panic-action %d
encrypt passwords = true
passdb backend = tdbsam
obey pam restrictions = yes
;invalid users = root
unix password sync = no
passwd program = /usr/bin/passwd %u
passwd chat = *Enter\snew\sUNIX\spassword:* %n\n *Retype\snew\sUNIX\spassword:* %n\n *password\supdated\ssuccessfully* .
socket options = TCP_NODELAY
[homes]
comment = Home Directories
browseable = no
writable = no
create mask = 0700
directory mask = 0700
valid users = %S
[www]
comment = WWW
writable = yes
locking = no
path = /var/www
public = yes' > /etc/samba/smb.conf
(echo SAMBAPASSWORD; echo SAMBAPASSWORD) | smbpasswd -sa root
echo 'NameVirtualHost *
<VirtualHost *>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
ErrorLog /var/log/apache2/error.log
LogLevel warn
CustomLog /var/log/apache2/access.log combined
ServerSignature On
</VirtualHost>' > /etc/apache2/sites-enabled/000-default
/etc/init.d/apache2 stop
/etc/init.d/samba stop
/etc/init.d/apache2 start
/etc/init.d/samba start
</code></pre>
<p>edit: add this to set your MySQL password</p>
<pre><code>/etc/init.d/mysql stop
echo "UPDATE mysql.user SET Password=PASSWORD('MySQLPasswrod') WHERE User='root'; FLUSH PRIVILEGES;" > /root/MySQLPassword
mysqld_safe --init-file=/root/MySQLPassword &
sleep 1
/etc/init.d/mysql stop
sleep 1
/etc/init.d/mysql start
</code></pre>
<p>end edit</p>
<p>This is a bit specailised but you get the idea, if you save this to a file ('install' for example) all you have to do is:</p>
<pre><code>chmod +x install
./install
</code></pre>
<p>Some of my apt-get commands are not necessary, because apt will automatically get the dependencies but I prefer to be specific, for my installs.</p>
| <p>I don't really understand your question because i really didn't see one. But i'll do my best to infer two: to change your keyboard layout, check this <a href="http://ubuntuforums.org/showthread.php?t=884533&highlight=change+keyboard+layout" rel="nofollow noreferrer">forum post</a> on ubuntu forums and to change the timezone, check this <a href="http://ubuntuforums.org/showthread.php?t=665255&highlight=change+time+zone" rel="nofollow noreferrer">forum post</a>.</p>
| 3,581 |
<p>Since the keyboard is <strong>the</strong> interface we use to the computer, I've always thought touch typing should be something I should learn, but I've always been, well, lazy is the word. So, anyone recommend any good touch typing software?</p>
<p>It's easy enough to google, but I'ld like to hear recommendations.</p>
| <p><a href="http://en.wikipedia.org/wiki/Typing_of_the_Dead" rel="nofollow noreferrer">Typing of the Dead!</a></p>
<p>It's a good few years old so you may have to hunt around, but it's a lot of fun and as well as the main game there are numerous minigames to practice specific areas you may be weak on.</p>
<p><img src="https://i.stack.imgur.com/wM9Cv.jpg" alt="alt text"></p>
| <p>I've been using <a href="http://www.typefastertypingtutor.com/" rel="nofollow noreferrer">TypeFaster</a>. It's not pretty, but one nice feature is that it can load lessons in different keyboard layouts, like Colemak (<a href="http://colemak.com/Learn" rel="nofollow noreferrer">layout files here</a>) or Dvorak.</p>
| 3,165 |
<p>I've heard that using hairspray is useful for keeping the 3D objects from peeling off of the bed, but every example I have seen where someone uses hairspray, they use it on a glass bed.</p>
<p>Is it okay to use it on a metal bed as well?</p>
| <p>I have been using a sort of a very strong hairspray called 3DLAC for about 2 years directly onto the aluminium heat bed of the Anet A8 printer I have.</p>
<p>Basically, all those sprays contain copolymer constituents, PVA (PolyVinyl Alcohol), Vinyl or Acetate. These are also found in certain glue sticks or wood glues. For me this spray works perfectly! On day one I assembled the printer, the paper tape tore and I was too anxious to wait for new tape to arrive. This worked so well that I have not changed it for that printer.</p>
<p>Cleaning is very easy as PVA or any of those constituents are solvable in water, so a moist cloth or paper towel over the plate is all to clean it. Furthermore, you do not require to spray before every print. </p>
<p>To answer your question if you <strong>should</strong> use a PVA based spray like hairspray directly onto the metal build plate is a matter of preference, but you definitely <strong>could</strong> use it as I have been doing it for about 2 years.</p>
<hr>
<p><strong>To address the comments</strong>:<br>
I spray the heat bed platform whilst it is attached to the printer. I do pull it forward and gently spray the bed or just the location where the print is going to be build. Note that you do not need to do that for every print. I recently did notice very little spray on the X guide rods (maybe I have been careless once or twice), but that has not been a problem for my Chinesium iGus ripoff plastic bearings. It is very easy to clean with a damp cloth. It also works great on the glass bed of my Ultimaker 3E, but I usually (unless when I'm lazy ;) ) remove the slate of glass before printing. You could consider shielding the rods with a piece of paper, but it has not been necessary for 2 years.</p>
| <p>Do you mean bare metal or metal with some film on top? You can apply hair spray to bare metal, but you will have troubles cleaning it off. Solvents do not evaporate hair spray, they only turn it into thick sticky goo you will need to clean off. I recommend that you try glue stick or even beer (seriously) before hair spray.<br>
You should also know that <em>any</em> adhesive is required only when your printer has bed leveling issues. After I finally dealt with bed leveling, I print ABS, and even ABS/PC mix (nasty) without any adhesive, on a bare kapton film over a metal bed. I rub it with alcohol before printing. </p>
| 541 |
<p>We need to build an administration portal website to support our client/server application. Since we're a .Net shop the obvious traditional way would be to do that in ASP.Net. But Silverlight 2 will be coming out of beta a good while before our release date. Should we consider building the whole website in silverlight instead, with a supporting WCF backend?</p>
<p>The main function of the portal will be: users, groups and permissions configuration; user profile settings configuration; file upload and download for files needed to support the application.</p>
<p>I think the main reason for taking this approach would be that we have good experience with WPF and WCF, but little experience in ASP.Net. Either way we would have to learn ASP.Net or Silverlight, and learning Silverlight seems a more natural extension of our current skills.</p>
<p>Are there any big no-nos from the experience of StackOverflowers? What are the big positives?</p>
| <p>I would recommend against building a pure Silverlight site.</p>
<p>Silverlight suffers from the same issues as Flash does: Unintuitive Bookmarking, issues with printing, accessibility issues, not working back buttons and so on.</p>
<p>Also, you would require your users to have Silverlight installed or at least to have the ability to install it. </p>
<p>In controlled environements (eg. in large companies or health care) or on mobile devices, this might not be the case.</p>
| <p>There are some <a href="https://stackoverflow.com/questions/56266/using-silverlight-for-an-entire-website#56302">downsides</a> with developing a site completely in Flash / Silverlight, but if those downsides won't matter to you or won't have an impact then there is nothing stopping you. Choose whatever tool you think meets your needs more fully. I wouldn't be put off creating a site purely in Silverlight based on the downsides, because it brings a lot more positives to the user experience.</p>
| 8,015 |
<p>Is there a way to hide radio buttons inside a RadioButtonList control programmatically?</p>
| <p>Under the hood, you can access the attributes of the item and assign it a CSS style.</p>
<p>So you should be able to then programmatically assign it by specifying:</p>
<pre><code>RadioButtonList.Items(1).CssClass.Add("visibility", "hidden")
</code></pre>
<p>and get the job done.</p>
| <p>If you mean with JavaScript, and if I remember correctly, you've got to dig out the ClientID properties of each <input type="radio" ...> tag.</p>
| 5,338 |
<p>Is there a one statement or one line way to accomplish something like this, where the string s is declared AND assigned the first non-null value in the expression?</p>
<pre><code>//pseudo-codeish
string s = Coalesce(string1, string2, string3);
</code></pre>
<p>or, more generally,</p>
<pre><code>object obj = Coalesce(obj1, obj2, obj3, ...objx);
</code></pre>
| <p>As Darren Kopp said.</p>
<p>Your statement</p>
<pre><code>object obj = Coalesce(obj1, obj2, obj3, ...objx);
</code></pre>
<p>Can be written like this:</p>
<pre><code>object obj = obj1 ?? obj2 ?? obj3 ?? ... objx;
</code></pre>
<p>to put it in other words:</p>
<pre><code>var a = b ?? c;
</code></pre>
<p>is equivalent to</p>
<pre><code>var a = b != null ? b : c;
</code></pre>
| <p>the <strong>??</strong> operator.</p>
<pre><code>string a = nullstring ?? "empty!";
</code></pre>
| 6,383 |
<p>Since the WMI class Win32_OperatingSystem only includes OSArchitecture in Windows Vista, I quickly wrote up a method using the registry to try and determine whether or not the current system is a 32 or 64bit system.</p>
<pre><code>private Boolean is64BitOperatingSystem()
{
RegistryKey localEnvironment = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment");
String processorArchitecture = (String) localEnvironment.GetValue("PROCESSOR_ARCHITECTURE");
if (processorArchitecture.Equals("x86")) {
return false;
}
else {
return true;
}
}
</code></pre>
<p>It's worked out pretty well for us so far, but I'm not sure how much I like looking through the registry. Is this a pretty standard practice or is there a better method?</p>
<p><strong>Edit</strong>: Wow, that code looks a lot prettier in the preview. I'll consider linking to a pastebin or something, next time.</p>
| <p>Take a look at Raymond Chens solution:</p>
<p><a href="http://blogs.msdn.com/oldnewthing/archive/2005/02/01/364563.aspx" rel="nofollow noreferrer">How to detect programmatically whether you are running on 64-bit Windows</a></p>
<p>and here's the PINVOKE for .NET:</p>
<p><a href="http://www.pinvoke.net/default.aspx/kernel32/IsWow64Process.html?diff=y" rel="nofollow noreferrer">IsWow64Process (kernel32)</a></p>
<p><strong>Update:</strong> I'd take issue with checking for 'x86'. Who's to say what intel's or AMD's next 32 bit processor may be designated as. The probability is low but it is a risk. You should ask the OS to determine this via the correct API's, not by querying what could be a OS version/platform specific value that may be considered opaque to the outside world. Ask yourself the questions, 1 - is the registry entry concerned properly documented by MS, 2 - If it is do they provide a definitive list of possible values that is guaranteed to permit you as a developer to make the informed decision between whether you are running 32 bit or 64 bit. If the answer is no, then call the API's, yeah it's a but more long winded but it is documented and definitive. </p>
| <p>Looking into the registry is perfectly valid, so long as you can be sure that the user of the application will always have access to what you need.</p>
| 2,595 |
<p>I have a site, which contains several ashx handlers, on a couple of the handlers I want to reject non-SSL requests. Is there a way that I can do this in code?</p>
| <p>If you must do it programmatically, a way I've done it in the past is to inspect the url and look for "https" in it. Redirect if you don't see that. Request.IsSecureConnection should be the preferred method, however. You may have to add additional logic to handle a loopback address.</p>
| <p>I think the proper way is to check the Request.IsSecureConnection property and redirect or throw if it's false</p>
| 8,345 |
<p>I have a table with a structure like the following:</p>
<hr />
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>LocationID</th>
<th>AccountNumber</th>
</tr>
</thead>
<tbody>
<tr>
<td>long-guid-here</td>
<td>12345</td>
</tr>
<tr>
<td>long-guid-here</td>
<td>54321</td>
</tr>
</tbody>
</table>
</div>
<p>To pass into another stored procedure, I need the XML to look like this:</p>
<pre><code><root>
<clientID>12345</clientID>
<clientID>54321</clientID>
</root>
</code></pre>
<p>The best I've been able to do so far was getting it like this:</p>
<pre><code><root clientID="10705"/>
</code></pre>
<p>I'm using this SQL statement:</p>
<pre><code>SELECT
1 as tag,
null as parent,
AccountNumber as 'root!1!clientID'
FROM
Location.LocationMDAccount
WHERE
locationid = 'long-guid-here'
FOR XML EXPLICIT
</code></pre>
<p>So far, I've looked at the documentation on <a href="http://msdn.microsoft.com/en-us/library/ms345137.aspx" rel="nofollow noreferrer">the MSDN page</a>, but I've not come out with the desired results.</p>
<hr />
<p>@KG,</p>
<p>Yours gave me this output actually:</p>
<pre><code><root>
<Location.LocationMDAccount>
<clientId>10705</clientId>
</Location.LocationMDAccount>
</root>
</code></pre>
<p>I'm going to stick with the <code>FOR XML EXPLICIT</code> from Chris Leon for now.</p>
| <p>try</p>
<pre><code>SELECT
1 AS Tag,
0 AS Parent,
AccountNumber AS [Root!1!AccountNumber!element]
FROM
Location.LocationMDAccount
WHERE
LocationID = 'long-guid-here'
FOR XML EXPLICIT
</code></pre>
| <p>Try this, Chris:</p>
<pre><code>SELECT
AccountNumber as [clientId]
FROM
Location.Location root
WHERE
LocationId = 'long-guid-here'
FOR
XML AUTO, ELEMENTS
</code></pre>
<p>TERRIBLY SORRY! I mixed up what you were asking for. I prefer the XML AUTO just for ease of maintainance, but I believe either one is effective. My apologies for the oversight ;-)</p>
| 2,496 |
<p>In what scenarios is it better to use a <code>struct</code> vs a <code>class</code> in C++?</p>
| <p>The differences between a <code>class</code> and a <code>struct</code> in C++ are:</p>
<ul>
<li><code>struct</code> members and base classes/structs are <code>public</code> by default.</li>
<li><code>class</code> members and base classes/structs are <code>private</code> by default.</li>
</ul>
<p>Both classes and structs can have a mixture of <code>public</code>, <code>protected</code> and <code>private</code> members, can use inheritance, and can have member functions.</p>
<p>I would recommend you:</p>
<ul>
<li>use <code>struct</code> for plain-old-data structures without any class-like features;</li>
<li>use <code>class</code> when you make use of features such as <code>private</code> or <code>protected</code> members, non-default constructors and operators, etc.</li>
</ul>
| <p>I never use "struct" in C++. </p>
<p>I can't ever imagine a scenario where you would use a struct when you want private members, unless you're willfully trying to be confusing. </p>
<p>It seems that using structs is more of a syntactic indication of how the data will be used, but I'd rather just make a class and try to make that explicit in the name of the class, or through comments. </p>
<p>E.g.</p>
<pre><code>class PublicInputData {
//data members
};
</code></pre>
| 7,821 |
<p>I'm new to 3D printing and I noticed some problems with my print.</p>
<p>I've printed it 3 times and releveled the bed. Now, I found that the right lower corner always has holes,</p>
<p><a href="https://i.stack.imgur.com/ZK0WA.jpg" rel="nofollow noreferrer" title="Printed model on bed shows incomplete coverage during initial layers"><img src="https://i.stack.imgur.com/ZK0WA.jpg" alt="Printed model on bed shows incomplete coverage during initial layers" title="Printed model on bed shows incomplete coverage during initial layers" /></a></p>
<p>and some stringing problems</p>
<p><a href="https://i.stack.imgur.com/FpjYF.jpg" rel="nofollow noreferrer" title="Printed model on bed shows stringing"><img src="https://i.stack.imgur.com/FpjYF.jpg" alt="Printed model on bed shows stringing" title="Printed model on bed shows stringing" /></a></p>
<p>Lastly, the place where there should be a full line suddenly becomes string-like, and it always happens at the same place.</p>
<p><a href="https://i.stack.imgur.com/1Fr55.jpg" rel="nofollow noreferrer" title="Printed model has individual lines are thin and string-like"><img src="https://i.stack.imgur.com/1Fr55.jpg" alt="Printed model has individual lines are thin and string-like" title="Printed model has individual lines are thin and string-like" /></a></p>
<p><a href="https://i.stack.imgur.com/HZz3J.jpg" rel="nofollow noreferrer" title="Another printed model has individual lines are thin and string-like"><img src="https://i.stack.imgur.com/HZz3J.jpg" alt="Another printed model has individual lines are thin and string-like" title="Another printed model has individual lines are thin and string-like" /></a></p>
<p>It's like my extruder pulls out the filament or fails to create filament in the area that should be filled with filament. Is it normal or did I set my printer wrong? I'm afraid it might cause holes in my new print.</p>
<p>There's also some stringing problem that causes the layer to be uneven.</p>
<p>Slicer: Cura 4.6</p>
<p>Settings:</p>
<p><a href="https://i.stack.imgur.com/jQYf9.png" rel="nofollow noreferrer" title="Cura Speed settings"><img src="https://i.stack.imgur.com/jQYf9.png" alt="Cura Speed settings" title="Cura Speed settings" /></a></p>
<p><a href="https://i.stack.imgur.com/84ZNv.png" rel="nofollow noreferrer" title="Cura Travel settings"><img src="https://i.stack.imgur.com/84ZNv.png" alt="Cura Travel settings" title="Cura Travel settings" /></a></p>
<p><a href="https://i.stack.imgur.com/cbboi.png" rel="nofollow noreferrer" title="Cura Material settings"><img src="https://i.stack.imgur.com/cbboi.png" alt="Cura Material settings" title="Cura Material settings" /></a></p>
<p><a href="https://i.stack.imgur.com/cdrDd.png" rel="nofollow noreferrer" title="Cura Cooling settings"><img src="https://i.stack.imgur.com/cdrDd.png" alt="Cura Cooling settings" title="Cura Cooling settings" /></a></p>
<p>My printer is Anycubic 4Max Pro</p>
| <p>Anycubic 4Max Pro appears to be a direct drive printer (extruder motor is right on top of hotend). The 6.5 mm retraction on in your slicer settings is more typical of a Bowden setup, where the extruder motor lives off of the moving carriage, and has to move extra to compensate for slack in the tube to the hotend. Direct drive retraction distance is typically 1 mm to 3 mm. I bet you can retract faster than 25 mm/s- the speed matters. Also, 60 mm/s travel speed is quite slow. 150 mm/s is typical. Faster travel means less time to ooze.</p>
<p>Your initial layer print speed of 20mm/s is good, slow slow makes the first layer stick better. I don’t see your 1st layer thickness setting, but I have had good success with using a thick first layer with a chunky, wide line width (like 150% of nozzle size), even if the following layers are fine. The idea being that more plastic and height in the initial layer makes it less temperamental as far as bed leveling goes, and it holds together nicely.</p>
<p>The cobweb-like lines are from the Combing Mode setting in Cura, that ignores the retraction when traveling through infill. Unfortunately there is a setting that also ignores retraction on the bottom layer, you want to change that under “combing mode” it is set to “not in skin”, or combing is set to off.</p>
| <p>From the wispy horizontal lines within the perimeters in your second image, it appears that the nozzle is still oozing material during the travel moves. This is likely causing the hole in the corner and the wispy perimeters too. When the extruder reinserts the filament into the hotend after a travel move, it expects the same amount of material to be in the nozzle as when it extracted the filament, but some material has oozed out during the travel move so that is not the case. I had a similar issue with my printer, and was able to mitigate the problem by increasing the <em>retraction extra prime amount</em> in the material section of Cura. This should compensate for the material loss during the travel move by reinserting the filament slightly farther when starting the extrusion. This solution is not perfect as different lengths of travel allow different volumes of filament to ooze from the nozzle. If you want perfect prints, you may have to tune this to the model you are printing: larger models usually require larger travel moves which would allow more time for plastic to ooze from the nozzle.</p>
<p>If you try this, make sure to look for blobs at the start of extrude moves. If the prime amount is set to high, it can create blobs on the side of the model (or inside depending on which perimeter is extruded first) which could cause tolerance issues on more complex parts.</p>
<p>Personally, I have also added a small coast distance to the end of each extrusion (located in Cura's experimental section). This allows the nozzle to ooze into the perimeter of the part which should decrease the stringing on travel moves, and thus loss of material on travel moves.</p>
| 1,667 |
<ol>
<li>Video podcast</li>
<li>???</li>
<li>Audio only mp3 player</li>
</ol>
<p>I'm looking for somewhere which will extract audio from video, but instead of a single file, for an on going video podcast.</p>
<p>I would most like a website which would suck in the RSS and spit out an RSS (I'm thinking of something like Feedburner), though would settle for something on my own machine.</p>
<p>If it must be on my machine, it should be quick, transparent, and automatic when I download each episode. </p>
<p>What would you use?</p>
<p><b>Edit:</b> I'm on an Ubuntu 8.04 machine; so running ffmpeg is no problem; however, I'm looking for automation and feed awareness.</p>
<p>Here's my use case: I want to listen to <a href="http://video.google.com/videosearch?q=google+techtalks&so=1&output=rss" rel="nofollow noreferrer">lectures</a> at Google Video, or <a href="http://groups.csail.mit.edu/mac/classes/6.001/abelson-sussman-lectures/" rel="nofollow noreferrer">Structure and Interpretation of Computer Programs</a>. These videos come out fairly often, so anything that's needed to be done manually will also be done fairly often. </p>
<p>Here's one approach I'd thought of:</p>
<ul>
<li>download the RSS</li>
<li>parse the RSS for enclosures, </li>
<li>download the enclosures, keeping a track what has already been downloaded previously</li>
<li>transcode the files, but not the ones done already</li>
<li>reconstruct an RSS with the audio files, remembering to change the metadata.</li>
<li>schedule to be run periodically</li>
<li>point podcatcher at new RSS feed.</li>
</ul>
<p>I also liked the approach of gPodder of using a <a href="http://wiki.gpodder.org/wiki/Time_stretching#Using_the_post-download_script_hook" rel="nofollow noreferrer">post-download script</a>.</p>
<p>I wish the <a href="http://www.openp2p.com/pub/a/p2p/2003/01/07/lazyweb.html" rel="nofollow noreferrer">Lazy Web</a> still worked.</p>
| <p>You could automate this using the open source command line tool ffmpeg. Parse the RSS to get the video files, fetch them over the net if needed, then spit each one out to a command line like this:</p>
<pre><code>ffmpeg -i episode1.mov -ab 128000 episode1.mp3
</code></pre>
<p>The -ab switch sets the output bit rate to 128 kbits/s on the audio file, adjust as needed. </p>
<p>Once you have the audio files you can reconstruct the RSS feed to link to the audio files if so desired.</p>
| <p>How to extract audio from video to MP3:</p>
<p><a href="http://www.dvdvideosoft.com/guides/dvd/extract-audio-from-video-to-mp3.htm" rel="nofollow noreferrer">http://www.dvdvideosoft.com/guides/dvd/extract-audio-from-video-to-mp3.htm</a></p>
<p>How to Convert a Video Podcast to Audio Only:</p>
<p><a href="http://www.legalandrew.com/2007/03/10/how-to-convert-a-video-podcast-to-audio-only/" rel="nofollow noreferrer">http://www.legalandrew.com/2007/03/10/how-to-convert-a-video-podcast-to-audio-only/</a></p>
| 6,781 |
<p>What could be the problem with reversing the array of DOM objects as in the following code:</p>
<pre><code>var imagesArr = new Array();
imagesArr = document.getElementById("myDivHolderId").getElementsByTagName("img");
imagesArr.reverse();
</code></pre>
<p>In Firefox 3, when I call the <code>reverse()</code> method the script stops executing and shows the following error in the console of the Web Developer Toolbar:</p>
<pre class="lang-none prettyprint-override"><code>imagesArr.reverse is not a function
</code></pre>
<p>The <code>imagesArr</code> variable can be iterated through with a for loop and elements like <code>imagesArr[i]</code> can be accessed, so why is it not seen as an array when calling the <code>reverse()</code> method?</p>
| <p>Because getElementsByTag name actually returns a NodeList structure. It has similar array like indexing properties for syntactic convenience, but it is <em>not</em> an array. For example, the set of entries is actually constantly being dynamically updated - if you add a new img tag under myDivHolderId, it will automatically appear in imagesArr.</p>
<p>See <a href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-536297177" rel="noreferrer">http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-536297177</a> for more.</p>
| <p>This worked for me, I did a reverse for loop and allocated the nodes to an array</p>
<pre><code>var Slides = document.getElementById("slideshow").querySelectorAll('li');
var TempArr = [];
for (var x = Slides.length; x--;) {
TempArr.push(Slides[x]);
}
Slides = TempArr;
</code></pre>
| 6,755 |
<p>I'm building a basic search functionality, using LIKE (I'd be using fulltext but can't at the moment) and I'm wondering if MySQL can, on searching for a keyword (e.g. WHERE field LIKE '%word%') return 20 words either side of the keyword, as well?</p>
| <p>You can do it all in the query using SUBSTRING_INDEX</p>
<pre><code>CONCAT_WS(
' ',
-- 20 words before
TRIM(
SUBSTRING_INDEX(
SUBSTRING(field, 1, INSTR(field, 'word') - 1 ),
' ',
-20
)
),
-- your word
'word',
-- 20 words after
TRIM(
SUBSTRING_INDEX(
SUBSTRING(field, INSTR(field, 'word') + LENGTH('word') ),
' ',
20
)
)
</code></pre>
<p>)</p>
| <p>Use the INSTR() function to find the position of the word in the string, and then use SUBSTRING() function to select a portion of characters before and after the position.</p>
<p>You'd have to look out that your SUBSTRING instruction don't use negative values or you'll get weird results.</p>
<p>Try that, and report back.</p>
| 5,895 |
<p>I recently bought a 3d printer and right now i am printing a normal cube just to try it out. However I was wondering, when it has the last part left of the printing where it needs to create the roof, how will the filament stay there and not just fall down as there is nothing underneath?</p>
<p>Will I need to check the "Support" function in the print-settings before hand or is there something else i need to do?</p>
<p>Thanks a lot for the help/tips!</p>
| <p>If you are printing a solid cube with infill, then the infill will support the "roof".</p>
<p>If you are printing a hollow cube, then indeed, you should enable "support" to print a support structure under any overhangs.</p>
<p>Depending on the angle, you may not need supports. Generally, FDM printers can print overhanging structures up to 45 degrees without the need for supports. The steeper (i.e. further from parallel with the print bed) the angle, the better the result.</p>
| <p>If you are printing a solid cube with infill, then the infill will support the "roof".</p>
<p>If you are printing a hollow cube, then indeed, you should enable "support" to print a support structure under any overhangs.</p>
<p>Depending on the angle, you may not need supports. Generally, FDM printers can print overhanging structures up to 45 degrees without the need for supports. The steeper (i.e. further from parallel with the print bed) the angle, the better the result.</p>
| 543 |
<p>We have a 42U rack which is getting a load of new 1U and 2U servers real soon. One of the guys here reckons that you need to leave a gap between the servers (of 1U) to aid cooling.</p>
<p>Question is, do you? When looking around the datacenter, no-one else seems to be, and it also diminishes how much we can fit in. We're using Dell 1850 and 2950 hardware.</p>
| <p>Simply NO, the servers and switches, and KVMs, and PSUs are all designed to be on the rack stacked on top of eachother. I'm basing this on a few years building, COs and Data centers for AT&T.</p>
| <p>The last two places I worked have large datacenters and they stack all their servers and appliances with no gaps. The servers have plenty of cooling with their internal fans. It is also recommended to run the rack on a raised floor with perforated tiles in the front of the rack and A/C air return above the rear of the racks for circulation.</p>
| 8,088 |
<p>I have a situation where I might have multiple instances of a program running at once, and it's important that just one specific function not be executing in more than one of these instances at once.</p>
<p>Is this the proper way to use a mutex to prevent this from happening?</p>
<pre><code>lock (this.GetType()) {
_log.Info("Doing Sync");
DoSync();
_log.Info("Sync Completed");
}
</code></pre>
| <p>You said multiple instances of one application, so we're talking about two program.exe's running, right? The lock statement won't lock across multiple programs, just within the program. If you want a true Mutex, look at the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.mutex" rel="nofollow noreferrer">System.Threading.Mutex</a> object.</p>
<p>Here is a usage example:</p>
<pre><code>bool createdNew;
using (Mutex mtx = new Mutex(false, "MyAwesomeMutex", out createdNew))
{
try
{
mtx.WaitOne();
MessageBox.Show("Click OK to release the mutex.");
}
finally
{
mtx.ReleaseMutex();
}
}
</code></pre>
<p>The createdNew variable will let you know whether or not it was created the first time. It only tells you if it has been created, though. If you want to acquire the lock, you need to call WaitOne and then call ReleaseMutex to release it. If you just want to see if you created a Mutex, just constructing it is fine.</p>
| <p>TheSeeker is correct.</p>
<p>Jeff Richter's advice in <a href="http://books.google.com/books?id=C-V_AAAACAAJ&dq=clr+via+c%23&ei=k6TBSPjYOomUzATIs8WIDg" rel="nofollow noreferrer">Clr Via C#</a> (p638-9) on locking is to create a private object specifically for the purpose of being locked.</p>
<pre><code>private Object _lock = new Object();
// usage
lock( _lock )
{
// thread-safe code here..
}
</code></pre>
<p>This works because _lock cannot be locked by anything outside the current class.</p>
<p>EDIT: this is applicable to threads executing within a single process. @David Mohundro's answer is correct for inter-process locking.</p>
| 6,908 |
<p>Programming languages had several (r)evolutionary steps in their history. Some people argue that model-driven approaches will be The Next Big Thing. There are tools like openArchitectureWare, AndroMDA, Sculptor/Fornax Platform etc. that promise incredible productivity boosts. However, I made the experience that it is either rather easy in the beginning to get started but as well to get stuck at some point when you try something that was unanticipated or pretty hard to find enough information that tells you how to start your project because there may be a lot of things to consider.</p>
<p>I think an important insight to get anything out of model-driven something is to understand that the model is not necessarily a set of nice pictures or tree model or UML, but may as well be a textual description (e.g. a state machine, business rules etc.).</p>
<p>What do you think and what does your experience tell you? Is there a future for model-driven development (or whatever you may want to call it)?</p>
<p><strong>Update:</strong> There does not seem to be a lot of interest in this topic. Please let me know, if you have any (good or bad) experience with model-driven approaches or why you think it's not interesting at all.</p>
| <p>I think, it will take time, till the tools get more refined, more people gain experience with MDD. At the moment if you want to get something out of MDD you have to invest quite a lot, so its use remains limited.</p>
<p>Looking at openArchitectureWare for example: While it is quite robust and basic documentation exists, documentation on the inner workings are missing and there are still problems with scalability, that are undocumented - maybe that will get better when Xtext and Xpand get rewritten. </p>
<p>But despise those limitations the generation itself is quite easy with oAW, you can navigate your models like a charm in Xtend and Xpand and by combining several workflows into bigger workflows, you can also do very complex things. If needed you can resort to Java, so you have a very big flexibility in what you can do with your models. Writing your own DSL with Xtext in oAW, too, is quickly done, yet you get your meta-model, a parser and a very nice editor basically for free. Also you can get your models basically from everywhere, e.g. a component that can convert a database into a meta-model and corresponding models can be written without big effort.</p>
<p>So I would say, MDD is still building up, as tools and experience with it increases. It can already used successfully, if you have the necessary expertise and are ready to push it within your company. In the end, I think, it is a very good thing, because a lot of glue code (aka copy paste) can and should be generated. Doing that with MDD is a very nice and structured way of doing this, that facilitates reusability, in my opinion.</p>
| <p>This is a very late reply, but I am currently searching for MDD tools to replace Rose RT, which is unfortunately being supplanted by Rhapsody. We are in the real-time, embedded and distributed C++ space and we get a LOT out of MDD. We are trying to move on to a better tool and get more widespread use of the tool in our very large company. It is an uphill battle because of some of the fine reasons mentioned here.</p>
<p>I think of MDD as just one level above the compiler, just as the compiler is above assembly. I want a tool that lets me, as the architect, develop the application framework, and extensively edit the code generation (scripts) to use that framework and whatever middleware we are using for message passing. I want the developers making complete UML classes and state diagrams that include all the code needed to generate the application and/or library.</p>
<p>It is true that you can do anything with code, but I would roughly summarize the benefits of MDD as this:</p>
<ol>
<li>A few people make the application framework, middleware adapters and glue that to the MDD tool. They build the "house".</li>
<li>Other people create complete classes, diagrams, and state machine transition code. This lets them focus on the application in stead fo the "house".</li>
<li>Its easy to see when peopel have wierd design since the diagram is the code. We don't have all expert developers and its nice to bring junior people up this way.</li>
<li>Mostly its the nasty state machine code that can happen in something like a mobile robotics project. I want people making state diagrams that I can understand, criticize and work on them with.</li>
<li>You can also have nice refactoring like dragging operation and attributes up inheritence chains or to other classes, etc. I like that better than digging in files.</li>
</ol>
<p>Even as I type this I realize that you can do everything in code. I like a thin tool jsut on top of the code to enforce uniformity, document the design, and allow a bit easier refactoring.</p>
<p>The main problem I encounter that I don't have a good answer for is that there is no standard set of functionality and file format for such models. People worry about the vendor going away and then being stuck. (We bascially had that happen with Rose RT.) You don't have that with source code. However, you would have the latest version of the tool and the course code that you generated last :). I'm willing to bet that the benefit outweighs the risk.</p>
<p>I have yet to find the tool like this, but I am trying to get a few vendors to listen to me and maybe accept money to make this happen.</p>
| 4,141 |
<p>I don't know how to say this but during the print, the printer will randomly have difficulty extruding the filament. I will have to give the filament a <em>boost</em> for it to keep going. Once I done the <em>boost</em>, the extruder keeps going perfectly fine for a while.</p>
<p>I am using a Prusa I3 clone bought second hand. I am using the settings that the previous owner gave me (I personally know him). He previously printed a lot of stuff with those settings and they seem to work well. I also bought the brand of same filament as he did for my first roll.</p>
<p>My question is:</p>
<p><strong>Has anyone had this problem or anything similar and if they did, how did they resolve it?</strong></p>
<p>If anymore precision or clarification is needed, please ask.</p>
<p><strong>EDIT</strong></p>
<p>When I say <code>boost</code> I mean that I have to push it down a bit more for it to countinue extruding.</p>
<p>I am using 3D branche filament (it's a local store in Montreal).</p>
<p>I do sometime hear it click before the print. When it does that. I stop the print and restart it.</p>
| <p>If you have <a href="http://www.openscad.org" rel="noreferrer">OpenSCAD</a> installed, this shell script will generate 100x100 pixel PNG images for each STL file in your current directory.</p>
<pre><code>for i in *.stl; do
T=__tmp__<span class="math-container">$i
b=`basename $</span>i`
echo import\(\"<span class="math-container">$i\"\)\; >$</span>T
/Applications/OpenSCAD.app/Contents/MacOS/OpenSCAD -o <span class="math-container">$b.png --imgsize=100,100 $</span>T
rm $T
done
</code></pre>
<p>Credit to <a href="https://3dprinting.stackexchange.com/users/5740/0scar">0scar</a> for pointing out STL files can be imported into OpenSCAD.</p>
<p>Update: This code does the same, and generates an html file with annotated images of the files rendered. When I printed a batch of spare parts for my 3D printer I made a hardcopy and stuck it in the box so I could identify the parts later.</p>
<pre><code>n=-1
H=00-catalog.html
echo ><span class="math-container">$H '<table>'
echo >>$</span>H ' <tr>'
for i in <span class="math-container">$*; do
n=`expr $</span>n + 1`
if test $n = 4; then
n=0
echo >>$H ' </tr>'
echo >>$H ' <tr>'
fi
echo $i
T=__tmp__$i
B=`basename <span class="math-container">$i .stl`
echo import\(\"$</span>i\"\)\; ><span class="math-container">$T
/Applications/OpenSCAD.app//Contents/MacOS/OpenSCAD -o $</span>B.png --imgsize=200,200 <span class="math-container">$T
echo >>$</span>H
echo >><span class="math-container">$H ' <td>'$</span>i'<br><img src="'$B'.png"></td>'
rm <span class="math-container">$T
done
echo >>$</span>H ' </tr>'
echo >>$H '</table>'
</code></pre>
| <p>You can use OpenSCAD, as stated in the accepted answer.
Here is a version of that script that works for Windows for anyone who needs it, as I did.</p>
<pre><code># Change height and width to the desired output image dimensions, in pixels.
# The path to openscad.exe may also have to be adjusted based on your installation.
height=1080
width=1080
for i in *.stl; do
T=__tmp__<span class="math-container">$i
b=`basename "$</span>i"`
echo import\(\"./<span class="math-container">$i\"\)\; > "$</span>T"
C:/'Program Files'/OpenSCAD/openscad.exe -o "<span class="math-container">$b".png --autocenter --viewall --imgsize=$</span>width,<span class="math-container">$height "$</span>T"
rm "$T"
done
</code></pre>
| 916 |
<p>I want to merge two dictionaries into a new dictionary.</p>
<pre><code>x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = merge(x, y)
>>> z
{'a': 1, 'b': 3, 'c': 4}
</code></pre>
<p>Whenever a key <code>k</code> is present in both dictionaries, only the value <code>y[k]</code> should be kept.</p>
| <h2>How can I merge two Python dictionaries in a single expression?</h2>
<p>For dictionaries <code>x</code> and <code>y</code>, their shallowly-merged dictionary <code>z</code> takes values from <code>y</code>, replacing those from <code>x</code>.</p>
<ul>
<li><p>In Python 3.9.0 or greater (released 17 October 2020, <a href="https://www.python.org/dev/peps/pep-0584/" rel="noreferrer"><code>PEP-584</code></a>, <a href="https://bugs.python.org/issue36144" rel="noreferrer">discussed here</a>):</p>
<pre class="lang-py prettyprint-override"><code>z = x | y
</code></pre>
</li>
<li><p>In Python 3.5 or greater:</p>
<pre class="lang-py prettyprint-override"><code>z = {**x, **y}
</code></pre>
</li>
<li><p>In Python 2, (or 3.4 or lower) write a function:</p>
<pre class="lang-py prettyprint-override"><code>def merge_two_dicts(x, y):
z = x.copy() # start with keys and values of x
z.update(y) # modifies z with keys and values of y
return z
</code></pre>
<p>and now:</p>
<pre class="lang-py prettyprint-override"><code>z = merge_two_dicts(x, y)
</code></pre>
</li>
</ul>
<h3>Explanation</h3>
<p>Say you have two dictionaries and you want to merge them into a new dictionary without altering the original dictionaries:</p>
<pre class="lang-py prettyprint-override"><code>x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
</code></pre>
<p>The desired result is to get a new dictionary (<code>z</code>) with the values merged, and the second dictionary's values overwriting those from the first.</p>
<pre class="lang-py prettyprint-override"><code>>>> z
{'a': 1, 'b': 3, 'c': 4}
</code></pre>
<p>A new syntax for this, proposed in <a href="https://www.python.org/dev/peps/pep-0448" rel="noreferrer">PEP 448</a> and <a href="https://mail.python.org/pipermail/python-dev/2015-February/138564.html" rel="noreferrer">available as of Python 3.5</a>, is</p>
<pre class="lang-py prettyprint-override"><code>z = {**x, **y}
</code></pre>
<p>And it is indeed a single expression.</p>
<p>Note that we can merge in with literal notation as well:</p>
<pre class="lang-py prettyprint-override"><code>z = {**x, 'foo': 1, 'bar': 2, **y}
</code></pre>
<p>and now:</p>
<pre class="lang-py prettyprint-override"><code>>>> z
{'a': 1, 'b': 3, 'foo': 1, 'bar': 2, 'c': 4}
</code></pre>
<p>It is now showing as implemented in the <a href="https://www.python.org/dev/peps/pep-0478/#features-for-3-5" rel="noreferrer">release schedule for 3.5, PEP 478</a>, and it has now made its way into the <a href="https://docs.python.org/dev/whatsnew/3.5.html#pep-448-additional-unpacking-generalizations" rel="noreferrer">What's New in Python 3.5</a> document.</p>
<p>However, since many organizations are still on Python 2, you may wish to do this in a backward-compatible way. The classically Pythonic way, available in Python 2 and Python 3.0-3.4, is to do this as a two-step process:</p>
<pre class="lang-py prettyprint-override"><code>z = x.copy()
z.update(y) # which returns None since it mutates z
</code></pre>
<p>In both approaches, <code>y</code> will come second and its values will replace <code>x</code>'s values, thus <code>b</code> will point to <code>3</code> in our final result.</p>
<h2>Not yet on Python 3.5, but want a <em>single expression</em></h2>
<p>If you are not yet on Python 3.5 or need to write backward-compatible code, and you want this in a <em>single expression</em>, the most performant while the correct approach is to put it in a function:</p>
<pre class="lang-py prettyprint-override"><code>def merge_two_dicts(x, y):
"""Given two dictionaries, merge them into a new dict as a shallow copy."""
z = x.copy()
z.update(y)
return z
</code></pre>
<p>and then you have a single expression:</p>
<pre class="lang-py prettyprint-override"><code>z = merge_two_dicts(x, y)
</code></pre>
<p>You can also make a function to merge an arbitrary number of dictionaries, from zero to a very large number:</p>
<pre class="lang-py prettyprint-override"><code>def merge_dicts(*dict_args):
"""
Given any number of dictionaries, shallow copy and merge into a new dict,
precedence goes to key-value pairs in latter dictionaries.
"""
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result
</code></pre>
<p>This function will work in Python 2 and 3 for all dictionaries. e.g. given dictionaries <code>a</code> to <code>g</code>:</p>
<pre class="lang-py prettyprint-override"><code>z = merge_dicts(a, b, c, d, e, f, g)
</code></pre>
<p>and key-value pairs in <code>g</code> will take precedence over dictionaries <code>a</code> to <code>f</code>, and so on.</p>
<h2>Critiques of Other Answers</h2>
<p>Don't use what you see in the formerly accepted answer:</p>
<pre class="lang-py prettyprint-override"><code>z = dict(x.items() + y.items())
</code></pre>
<p>In Python 2, you create two lists in memory for each dict, create a third list in memory with length equal to the length of the first two put together, and then discard all three lists to create the dict. <strong>In Python 3, this will fail</strong> because you're adding two <code>dict_items</code> objects together, not two lists -</p>
<pre class="lang-py prettyprint-override"><code>>>> c = dict(a.items() + b.items())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items'
</code></pre>
<p>and you would have to explicitly create them as lists, e.g. <code>z = dict(list(x.items()) + list(y.items()))</code>. This is a waste of resources and computation power.</p>
<p>Similarly, taking the union of <code>items()</code> in Python 3 (<code>viewitems()</code> in Python 2.7) will also fail when values are unhashable objects (like lists, for example). Even if your values are hashable, <strong>since sets are semantically unordered, the behavior is undefined in regards to precedence. So don't do this:</strong></p>
<pre class="lang-py prettyprint-override"><code>>>> c = dict(a.items() | b.items())
</code></pre>
<p>This example demonstrates what happens when values are unhashable:</p>
<pre class="lang-py prettyprint-override"><code>>>> x = {'a': []}
>>> y = {'b': []}
>>> dict(x.items() | y.items())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
</code></pre>
<p>Here's an example where <code>y</code> should have precedence, but instead the value from <code>x</code> is retained due to the arbitrary order of sets:</p>
<pre class="lang-py prettyprint-override"><code>>>> x = {'a': 2}
>>> y = {'a': 1}
>>> dict(x.items() | y.items())
{'a': 2}
</code></pre>
<p>Another hack you should not use:</p>
<pre class="lang-py prettyprint-override"><code>z = dict(x, **y)
</code></pre>
<p>This uses the <code>dict</code> constructor and is very fast and memory-efficient (even slightly more so than our two-step process) but unless you know precisely what is happening here (that is, the second dict is being passed as keyword arguments to the dict constructor), it's difficult to read, it's not the intended usage, and so it is not Pythonic.</p>
<p>Here's an example of the usage being <a href="https://code.djangoproject.com/attachment/ticket/13357/django-pypy.2.diff" rel="noreferrer">remediated in django</a>.</p>
<p>Dictionaries are intended to take hashable keys (e.g. <code>frozenset</code>s or tuples), but <strong>this method fails in Python 3 when keys are not strings.</strong></p>
<pre class="lang-py prettyprint-override"><code>>>> c = dict(a, **b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: keyword arguments must be strings
</code></pre>
<p>From the <a href="https://mail.python.org/pipermail/python-dev/2010-April/099459.html" rel="noreferrer">mailing list</a>, Guido van Rossum, the creator of the language, wrote:</p>
<blockquote>
<p>I am fine with
declaring dict({}, **{1:3}) illegal, since after all it is abuse of
the ** mechanism.</p>
</blockquote>
<p>and</p>
<blockquote>
<p>Apparently dict(x, **y) is going around as "cool hack" for "call
x.update(y) and return x". Personally, I find it more despicable than
cool.</p>
</blockquote>
<p>It is my understanding (as well as the understanding of the <a href="https://mail.python.org/pipermail/python-dev/2010-April/099485.html" rel="noreferrer">creator of the language</a>) that the intended usage for <code>dict(**y)</code> is for creating dictionaries for readability purposes, e.g.:</p>
<pre class="lang-py prettyprint-override"><code>dict(a=1, b=10, c=11)
</code></pre>
<p>instead of</p>
<pre class="lang-py prettyprint-override"><code>{'a': 1, 'b': 10, 'c': 11}
</code></pre>
<h2>Response to comments</h2>
<blockquote>
<p>Despite what Guido says, <code>dict(x, **y)</code> is in line with the dict specification, which btw. works for both Python 2 and 3. The fact that this only works for string keys is a direct consequence of how keyword parameters work and not a short-coming of dict. Nor is using the ** operator in this place an abuse of the mechanism, in fact, ** was designed precisely to pass dictionaries as keywords.</p>
</blockquote>
<p>Again, it doesn't work for 3 when keys are not strings. The implicit calling contract is that namespaces take ordinary dictionaries, while users must only pass keyword arguments that are strings. All other callables enforced it. <code>dict</code> broke this consistency in Python 2:</p>
<pre><code>>>> foo(**{('a', 'b'): None})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() keywords must be strings
>>> dict(**{('a', 'b'): None})
{('a', 'b'): None}
</code></pre>
<p>This inconsistency was bad given other implementations of Python (PyPy, Jython, IronPython). Thus it was fixed in Python 3, as this usage could be a breaking change.</p>
<p>I submit to you that it is malicious incompetence to intentionally write code that only works in one version of a language or that only works given certain arbitrary constraints.</p>
<p>More comments:</p>
<blockquote>
<p><code>dict(x.items() + y.items())</code> is still the most readable solution for Python 2. Readability counts.</p>
</blockquote>
<p>My response: <code>merge_two_dicts(x, y)</code> actually seems much clearer to me, if we're actually concerned about readability. And it is not forward compatible, as Python 2 is increasingly deprecated.</p>
<blockquote>
<p><code>{**x, **y}</code> does not seem to handle nested dictionaries. the contents of nested keys are simply overwritten, not merged [...] I ended up being burnt by these answers that do not merge recursively and I was surprised no one mentioned it. In my interpretation of the word "merging" these answers describe "updating one dict with another", and not merging.</p>
</blockquote>
<p>Yes. I must refer you back to the question, which is asking for a <em>shallow</em> merge of <em><strong>two</strong></em> dictionaries, with the first's values being overwritten by the second's - in a single expression.</p>
<p>Assuming two dictionaries of dictionaries, one might recursively merge them in a single function, but you should be careful not to modify the dictionaries from either source, and the surest way to avoid that is to make a copy when assigning values. As keys must be hashable and are usually therefore immutable, it is pointless to copy them:</p>
<pre class="lang-py prettyprint-override"><code>from copy import deepcopy
def dict_of_dicts_merge(x, y):
z = {}
overlapping_keys = x.keys() & y.keys()
for key in overlapping_keys:
z[key] = dict_of_dicts_merge(x[key], y[key])
for key in x.keys() - overlapping_keys:
z[key] = deepcopy(x[key])
for key in y.keys() - overlapping_keys:
z[key] = deepcopy(y[key])
return z
</code></pre>
<p>Usage:</p>
<pre class="lang-py prettyprint-override"><code>>>> x = {'a':{1:{}}, 'b': {2:{}}}
>>> y = {'b':{10:{}}, 'c': {11:{}}}
>>> dict_of_dicts_merge(x, y)
{'b': {2: {}, 10: {}}, 'a': {1: {}}, 'c': {11: {}}}
</code></pre>
<p>Coming up with contingencies for other value types is far beyond the scope of this question, so I will point you at <a href="https://stackoverflow.com/a/24088493/541136">my answer to the canonical question on a "Dictionaries of dictionaries merge"</a>.</p>
<h2>Less Performant But Correct Ad-hocs</h2>
<p>These approaches are less performant, but they will provide correct behavior.
They will be <em>much less</em> performant than <code>copy</code> and <code>update</code> or the new unpacking because they iterate through each key-value pair at a higher level of abstraction, but they <em>do</em> respect the order of precedence (latter dictionaries have precedence)</p>
<p>You can also chain the dictionaries manually inside a <a href="https://www.python.org/dev/peps/pep-0274/" rel="noreferrer">dict comprehension</a>:</p>
<pre class="lang-py prettyprint-override"><code>{k: v for d in dicts for k, v in d.items()} # iteritems in Python 2.7
</code></pre>
<p>or in Python 2.6 (and perhaps as early as 2.4 when generator expressions were introduced):</p>
<pre class="lang-py prettyprint-override"><code>dict((k, v) for d in dicts for k, v in d.items()) # iteritems in Python 2
</code></pre>
<p><code>itertools.chain</code> will chain the iterators over the key-value pairs in the correct order:</p>
<pre class="lang-py prettyprint-override"><code>from itertools import chain
z = dict(chain(x.items(), y.items())) # iteritems in Python 2
</code></pre>
<h2>Performance Analysis</h2>
<p>I'm only going to do the performance analysis of the usages known to behave correctly. (Self-contained so you can copy and paste yourself.)</p>
<pre class="lang-py prettyprint-override"><code>from timeit import repeat
from itertools import chain
x = dict.fromkeys('abcdefg')
y = dict.fromkeys('efghijk')
def merge_two_dicts(x, y):
z = x.copy()
z.update(y)
return z
min(repeat(lambda: {**x, **y}))
min(repeat(lambda: merge_two_dicts(x, y)))
min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()}))
min(repeat(lambda: dict(chain(x.items(), y.items()))))
min(repeat(lambda: dict(item for d in (x, y) for item in d.items())))
</code></pre>
<p>In Python 3.8.1, NixOS:</p>
<pre class="lang-py prettyprint-override"><code>>>> min(repeat(lambda: {**x, **y}))
1.0804965235292912
>>> min(repeat(lambda: merge_two_dicts(x, y)))
1.636518670246005
>>> min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()}))
3.1779992282390594
>>> min(repeat(lambda: dict(chain(x.items(), y.items()))))
2.740647904574871
>>> min(repeat(lambda: dict(item for d in (x, y) for item in d.items())))
4.266070580109954
</code></pre>
<pre class="lang-sh prettyprint-override"><code>$ uname -a
Linux nixos 4.19.113 #1-NixOS SMP Wed Mar 25 07:06:15 UTC 2020 x86_64 GNU/Linux
</code></pre>
<h2>Resources on Dictionaries</h2>
<ul>
<li><a href="https://stackoverflow.com/questions/327311/how-are-pythons-built-in-dictionaries-implemented/44509302#44509302">My explanation of Python's <strong>dictionary implementation</strong>, updated for 3.6.</a></li>
<li><a href="https://stackoverflow.com/questions/1024847/add-new-keys-to-a-dictionary/27208535#27208535">Answer on how to add new keys to a dictionary</a></li>
<li><a href="https://stackoverflow.com/questions/209840/map-two-lists-into-a-dictionary-in-python/33737067#33737067">Mapping two lists into a dictionary</a></li>
<li><a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries" rel="noreferrer">The official Python docs on dictionaries</a></li>
<li><a href="https://www.youtube.com/watch?v=66P5FMkWoVU" rel="noreferrer">The Dictionary Even Mightier</a> - talk by Brandon Rhodes at Pycon 2017</li>
<li><a href="https://www.youtube.com/watch?v=npw4s1QTmPg" rel="noreferrer">Modern Python Dictionaries, A Confluence of Great Ideas</a> - talk by Raymond Hettinger at Pycon 2017</li>
</ul>
| <p>The question is tagged <code>python-3x</code> but, taking into account that it's a relatively recent addition and that the most voted, accepted answer deals extensively with a Python 2.x solution, I dare add a one liner that draws on an irritating feature of Python 2.x list comprehension, that is <em>name leaking</em>...</p>
<pre><code>$ python2
Python 2.7.13 (default, Jan 19 2017, 14:48:08)
[GCC 6.3.0 20170118] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> [z.update(d) for z in [{}] for d in (x, y)]
[None, None]
>>> z
{'a': 1, 'c': 11, 'b': 10}
>>> ...
</code></pre>
<p>I'm happy to say that the above doesn't work any more on any version of Python 3.</p>
| 5,999 |
<p>For some reason, I can't seem to get CruiseControl.net to checkout code to anywhere but the starteam working folder for a specificed view.</p>
<p>I've tried both overrideViewWorkingDir and overrideFolderWorkingDir, and neither seem to work.</p>
<p>Has anyone been able to do this?</p>
| <p>Are you looking for the project's <a href="http://confluence.public.thoughtworks.org/display/CCNET/Project+Configuration+Block" rel="nofollow noreferrer">workingDirectory element</a> instead of the <a href="http://confluence.public.thoughtworks.org/display/CCNET/StarTeam+Source+Control+Block" rel="nofollow noreferrer">starteam override</a>?</p>
| <pre><code><sourcecontrol type="starteam">
<executable>C:\Program Files\starbase\StarTeam 5.4\stcmd.exe</executable>
<project>ProjectName/ViewName</project>
<username>UserName</username>
<password>Password</password>
<host>127.0.0.1</host>
<port>49201</port>
<autoGetSource>true</autoGetSource>
<overrideViewWorkingDir>C:\temp\ProjectName</overrideViewWorkingDir>
</sourcecontrol>
</code></pre>
| 6,428 |
<p>This is an adapted version of a question from someone in my office. She's trying to determine how to tell what ports MSDE is running on for an application we have in the field.</p>
<p>Answers to that narrower question would be greatly appreciated. I'm also interested in a broader answer that could be applied to any networked applications.</p>
| <pre><code>netstat -b
</code></pre>
<p>from the command line will display the application name, process owner, address, and port number used for all running applications.</p>
| <p>Download currports from <a href="http://www.nirsoft.net/utils/cports.html" rel="nofollow noreferrer">here</a>.</p>
<p>It will show you which ports are open and which processes are associated with each port.</p>
<p>Scroll down to:
Download CurrPorts</p>
| 6,354 |
<p>I got this error today when trying to open a Visual Studio 2008 <strong>project</strong> in Visual Studio 2005:</p>
<blockquote>
<p>The imported project "C:\Microsoft.CSharp.targets" was not found.</p>
</blockquote>
| <p>Open your csproj file in notepad (or notepad++)
Find the line: </p>
<pre><code><Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</code></pre>
<p>and change it to</p>
<pre><code><Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</code></pre>
| <p>I deleted the obj folder and then the project loaded as expected.</p>
| 2,755 |
<p>I hope this qualifies as a programming question, as in any programming tutorial, you eventually come across 'foo' in the code examples. (yeah, right?)</p>
<p>what does 'foo' really mean?</p>
<p>If it is meant to mean <strong>nothing</strong>, when did it begin to be used so?</p>
| <p>See: <a href="https://www.rfc-editor.org/rfc/rfc3092" rel="nofollow noreferrer">RFC 3092: Etymology of "Foo", D. Eastlake 3rd et al.</a></p>
<p>Quoting only the relevant definitions from that RFC for brevity:</p>
<blockquote>
<ol start="2">
<li>Used very generally as a sample name for absolutely anything, esp.
programs and files (esp. scratch files).</li>
</ol>
</blockquote>
<blockquote>
<ol start="3">
<li>First on the standard list of metasyntactic variables used in
syntax examples (bar, baz, qux, quux, corge, grault, garply,
waldo, fred, plugh, xyzzy, thud). [JARGON]</li>
</ol>
</blockquote>
| <p>In my opinion every programmer has his or her own "words" that is used every time you need an arbitrary word when programming.
For some people it's the first words from a childs song, for other it's names and for other its something completely different.
Now for the programmer community there are these "words" as well, and these words are 'foo' and 'bar'.
The use of this is that if you have to communicate publicly about programming you don't have to say that you would use arbitratry words, you would simply write 'foo' or 'bar' and every programmer knows that this is just arbitrary words.</p>
| 7,711 |
<p>I am trying to build an website for my college's magazine. I used the "views" module to show a block of static content I created on the front page.</p>
<p>My question is: how can I edit the theme's css so it changes the way that block of static content is displayed?</p>
<p>For reference, <a href="http://www.historia.uff.br/aroda/" rel="noreferrer">here's the link</a> to the site (in portuguese, and with almost zero content for now).</p>
| <p>The main css file that drives your content is the styles.css file located in your currently selected theme. In your case that means that most of your site styling is driven by this file: /aroda/roda/themes/garland/style.css with basic coloring effects handled by this file:
/aroda/roda/files/color/garland-d3985506/style.css</p>
<p>You're currently using Garland, the default Drupal theme included with the core download, so for best practices you shouldn't edit the included style.css file directly. Instead, you should, as Daniel James said, create a subdirectory in /sites/all called "themes".</p>
<p>If you're using Drupal 6, I'd follow Daniel James directions from there. If you're using Drupal 5, I'd go ahead and copy the garland directory into the themes directory and rename it for something specific to your site (aroda_v1) so you would have something like /sites/all/themes/aroda_v1 which would contain styles.css. At that point, you can edit the styles.css file directly to make any changes you see fit. Hope that helps!</p>
| <p>It looks like most of your CSS info is in some *.css files. There is also some inline Style info on the page. Your style for the static info comes from the in-line stuff. I am not sure how Drupal generates the page but the place to start looking is for any properties for "ultima-edicao". That is what the surrounding DIV is called.</p>
| 5,584 |
<p>I've been making my way through <em>The Little Schemer</em> and I was wondering what environment, IDE or interpreter would be best to use in order to test any of the Scheme code I jot down for myself.</p>
| <p><a href="http://racket-lang.org/" rel="noreferrer">Racket</a> (<a href="http://racket-lang.org/new-name.html" rel="noreferrer">formerly Dr Scheme</a>) has a nice editor, several different Scheme dialects, an attempt at visual debugging, lots of libraries, and can run on most platforms. It even has some modes specifically geared around learning the language.</p>
| <p>LispMe works on a Palm Pilot, take it anywhere, and scheme on the go. GREAT way to learn scheme.</p>
| 8,402 |
<p>I'm trying to write a query that extracts and transforms data from a table and then insert those data into another table. Yes, this is a data warehousing query and I'm doing it in MS Access. So basically I want some query like this:</p>
<pre><code>INSERT INTO Table2(LongIntColumn2, CurrencyColumn2) VALUES
(SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1);
</code></pre>
<p>I tried but get a syntax error message.</p>
<p>What would you do if you want to do this?</p>
| <p>No "VALUES", no parenthesis:</p>
<pre><code>INSERT INTO Table2(LongIntColumn2, CurrencyColumn2)
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1;
</code></pre>
| <p>Do you want to insert extraction in an existing table? </p>
<p>If it does not matter then you can try the below query:</p>
<pre><code>SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 INTO T1 FROM Table1
GROUP BY LongIntColumn1);
</code></pre>
<p>It will create a new table -> T1 with the extracted information</p>
| 9,985 |
<p>Does anybody have useful example of <code>this</code> assignment inside a C# method? I have been asked for it once during job interview, and I am still interested in answer myself. </p>
| <p>The other answers are incorrect when they say you cannot assign to 'this'. True, you can't for a class type, but you <em>can</em> for a struct type:</p>
<pre><code>public struct MyValueType
{
public int Id;
public void Swap(ref MyValueType other)
{
MyValueType temp = this;
this = other;
other = temp;
}
}
</code></pre>
<p>At any point a struct can alter itself by assigning to 'this' like so.</p>
| <p>You cannot overwrite "this". It points to the current object instance.</p>
| 9,524 |
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/2213205/configure-eclipse-to-use-vs-net-shortcuts">Configure Eclipse to use VS.Net shortcuts?</a> </p>
</blockquote>
<p>I mostly work in VS2008 but I need to do some java work in Eclipse. Is there an easy and fast way to map the VS2008 keyboard shortcuts to Eclipse?</p>
<p>For example, I want to map F11 in Eclipse to "step info" instead of its default of F5 but don't want to have to map each and every shortcut manually...</p>
| <p>How are the Eclipse settings saved? Perhaps you could simply adapt <a href="http://xona.com/2005/08/02.html" rel="nofollow noreferrer">this macro</a> and load the resulting file into Eclipse?</p>
| <p>Doesn't Eclipse have a predefined keyboard setup for Visual Studio?</p>
| 3,740 |
<p>I've recently inherited a internationalized and text-heavy Struts 1.1 web application. Many of the JSP files look like:</p>
<pre class="lang-jsp prettyprint-override"><code><p>
<bean:message key="alert" />
</p>
</code></pre>
<p>and the properties files look like:</p>
<pre><code>messages.properties
alert=Please update your <a href="/address.do">address</a> and <a href="/contact.do">contact information</a>.
</code></pre>
<p>with the appropriate translations in N other languages (messages_fr.properties, etc).</p>
<p>Problems:</p>
<ol>
<li><em><strong>DRY violation</strong></em> - I have N references to my Struts action URLs instead of 1, which makes refactoring action URLs error-prone.</li>
<li><em><strong>Mixed concerns</strong></em> - My application's markup is now in more than just my JSP files, making it difficult for a web specialist to tweak the markup (using CSS, etc).</li>
<li><em><strong>Post-translation markup</strong></em> - Anytime I receive newly-translated text, I must decide what to surround with the <code><a>...</a></code> markup. Easy for English but less so for unfamiliar languages.</li>
</ol>
<p>I've considered adding placeholders in the messages file, like:</p>
<pre><code>alert=Please update your {0} and {1}.
</code></pre>
<p>but then the words "address" and "contact information" would somehow need to be localized, wrapped with markup, and passed to my message tag - and I can't see an easy way to do it.</p>
<p>What can I do to improve this?</p>
| <blockquote>
<p>Avoid creating links within long
blocks of text. Prefer shorter text
that can act as a logically complete
and independent link.</p>
</blockquote>
<p>Generally, it will lead to fewer problems. Sometimes you have to compromise your UI design to accommodate localization; sometimes you need to compromise your localization process to accommodate the UI.</p>
<p>Any time a developer manually manipulates post-translation strings is a source of potentially expensive bugs. Cutting/pasting or string editing can result in character corruption, misplaced strings, etc. A translation defect needs the participation of outside parties to fix which involves cost and takes time.</p>
<p>Thinking on it, something like this might be less ugly:</p>
<pre class="lang-html prettyprint-override"><code><p>Please update your address and contact information.
<br />
<a href="/address.do">update address</a>
<br />
<a href="/contact.do">update contact information</a></p>
</code></pre>
<p>...but I'm no UI designer.</p>
| <p>Perhaps:</p>
<pre><code>#
alert=Please update your {0}address{1} and {2}contact information{3}.
</code></pre>
| 3,423 |
<p>I've been having trouble getting my ASP.NET application to automatically log users into the Intranet site I'm building. No matter the googling or the experimentation I applied, there is always a login box displayed by IE7.</p>
<p>I've got Windows authentication mode set in the Web.config, disabled anonymous access and configured the correct default domain in IIS, but it's still asking the user to log in and, more annoyingly, the user is required to provide the domain too (<em>DOMAIN\auser</em>), which is causing problems with non-technical visitors. Thank Zeus for password remembering functionality.</p>
<p>I'm not the network administrator so it's possible that something about Active Directory is set up incorrectly, or it could just be me missing something very simple. Please note that I don't want to impersonate the user, I just need to know that the IPrincipal.Name property matches that of a valid record in my user database, hence authenticating the user to my application.</p>
<p>To this end, it would be very useful to have a checklist of all configuration requirements for AD, ASP.NET and IIS to work together in this manner as a reference for debugging and hopefully reducing some user friction.</p>
| <p>It sounds like you've covered all the server-side bases--maybe it's a client issue? I assume your users have integrated authentication enabled in IE7? (Tools -> Internet Options -> Advanced -> Security). This is enabled by default.</p>
<p>Also, is your site correctly recognized by IE7 as being in the Local Intranet zone? The IE7 default is to allow automatic logon only in that zone, so users would be prompted if IE thinks your site is on the internet. I believe using a hostname with a dot in it causes IE to place the site into the Internet zone.</p>
| <p>In IIS, enable annonymous access and allow the web.config to handle user authentication.</p>
| 2,308 |
<p>I am running a number of SSL-encrypted websites, and need to generate certificates to run on these. They are all internal applications, so I don't need to purchase a certificate, I can create my own.</p>
<p>I have found it quite tedious to do everything using openssl all the time, and figure this is the kind of thing that has probably been done before and software exists for it.</p>
<p>My preference is for linux-based systems, and I would prefer a command-line system rather than a GUI.</p>
<p>Does anyone have some suggestions?</p>
| <p>An option that doesn't require your own CA is to get certificates from <a href="http://www.cacert.org/" rel="noreferrer">CAcert</a> (they're free).</p>
<p>I find it convenient to add the two CAcert root certificates to my client machines, then I can manage all the SSL certificates through CAcert.</p>
| <p>I created <a href="https://github.com/brianclements/pkictl" rel="nofollow">a wrapper script</a>, written in Bash, for OpenSSL that might be useful to you here. To me, the easiest sources of user error when using OpenSSL were:</p>
<ol>
<li>Keeping a consistent and logical naming scheme for configuration/certs/keys so that I can see how every artifact fits into the entire PKI by just looking at the file name/extension</li>
<li>Enforcing a folder structure thats consistent across all CA machines that use the script.</li>
<li>Specifying too many configuration options via CLI and loosing track of some of the details</li>
</ol>
<p>The strategy is to push all configuration into their own files, saving only execution of a particular action for the CLI. The script also strongly enforces the use of a particular naming scheme for folders/files here which is helpful when looking at any single file.</p>
<p>Use/Fork/PR away! Hope it helps.</p>
| 3,836 |
<p>How to restrict the maximum number of characters that can be entered into an HTML <code><textarea></code>? I'm looking for a cross-browser solution.</p>
| <p>The <code>TEXTAREA</code> tag does not have a <code>MAXLENGTH</code> attribute the way that an
<code>INPUT</code> tag does, at least not in most standard browsers. A very simple and effective way to limit the number of characters that can be <em>typed</em> into a <code>TEXTAREA</code> tag is:</p>
<pre><code><textarea onKeyPress="return ( this.value.length < 50 );"></textarea>
</code></pre>
<p><strong>Note:</strong> <code>onKeyPress</code>, is going to prevent any button press, <strong>any button</strong> <em>including</em> the backspace key.</p>
<p>This works because the Boolean expression compares the field's length
before the new character is added to the maximum length you want (50 in this example, use your own here), and returns true if there is room for one more, <code>false</code> if not. Returning false from most events cancels the default action.
So if the current length is already 50 (or more), the handler returns false,
the <code>KeyPress</code> action is cancelled, and the character is not added.</p>
<p>One fly in the ointment is the possibility of pasting into a <code>TEXTAREA</code>,
which does not cause the <code>KeyPress</code> event to fire, circumventing this check.
Internet Explorer 5+ contains an <code>onPaste</code> event whose handler can contain the
check. However, note that you must also take into account how many
characters are waiting in the clipboard to know if the total is going to
take you over the limit or not. Fortunately, IE also contains a clipboard
object from the window object.<a href="http://lists.evolt.org/archive/Week-of-Mon-20040315/156773.html" rel="nofollow noreferrer">1</a> Thus:</p>
<pre><code><textarea onKeyPress="return ( this.value.length < 50 );"
onPaste="return (( this.value.length +
window.clipboardData.getData('Text').length) < 50 );"></textarea>
</code></pre>
<p>Again, the <code>onPaste</code> event and <code>clipboardData</code> object are IE 5+ only. For a cross-browser solution, you will just have to use an <code>OnChange</code> or <code>OnBlur</code> handler to check the length, and handle it however you want (truncate the value silently, notify the user, etc.). Unfortunately, this doesn't catch the error as it's happening, only when the user attempts to leave the field, which is not quite as friendly.</p>
<p><a href="http://lists.evolt.org/archive/Week-of-Mon-20040315/156773.html" rel="nofollow noreferrer">Source</a></p>
<p>Also, there is another way here, including a finished script you could include in your page:</p>
<p><a href="http://cf-bill.blogspot.com/2005/05/textarea-maxlength-revisited.html" rel="nofollow noreferrer">http://cf-bill.blogspot.com/2005/05/textarea-maxlength-revisited.html</a></p>
| <pre><code>$(function(){
$("#id").keypress(function() {
var maxlen = 100;
if ($(this).val().length > maxlen) {
return false;
}
})
});
</code></pre>
<p>Reference <a href="https://stackoverflow.com/questions/4459610/set-maxlength-in-html-textarea">Set maxlength in Html Textarea</a></p>
| 6,517 |
<p>We've occasionally been getting problems whereby our long-running server processes (running on Windows Server 2003) have thrown an exception due to a memory allocation failure. Our suspicion is these allocations are failing due to memory fragmentation.</p>
<p>Therefore, we've been looking at some alternative memory allocation mechanisms that may help us and I'm hoping someone can tell me the best one:</p>
<p>1) Use Windows <a href="http://msdn.microsoft.com/en-us/library/aa366750.aspx" rel="noreferrer">Low-fragmentation Heap</a></p>
<p>2) jemalloc - as used in <a href="http://en.wikipedia.org/wiki/Mozilla_Firefox_3" rel="noreferrer">Firefox 3</a></p>
<p>3) Doug Lea's <a href="http://g.oswego.edu/" rel="noreferrer">malloc</a> </p>
<p>Our server process is developed using cross-platform C++ code, so any solution would be ideally cross-platform also (do *nix operating systems suffer from this type of memory fragmentation?). </p>
<p>Also, am I right in thinking that LFH is now the default memory allocation mechanism for Windows Server 2008 / Vista?... Will my current problems "go away" if our customers simply upgrade their server os?</p>
| <p>First, I agree with the other posters who suggested a resource leak. You really want to rule that out first.</p>
<p>Hopefully, the heap manager you are currently using has a way to dump out the actual total free space available in the heap (across all <strong>free</strong> blocks) and also the total number of blocks that it is divided over. If the average free block size is relatively small compared to the total free space in the heap, then you do have a fragmentation problem. Alternatively, if you can dump the size of the largest free block and compare that to the total free space, that will accomplish the same thing. The largest free block would be small relative to the total <strong><em>free</em></strong> space available across all blocks if you are running into fragmentation.</p>
<p>To be very clear about the above, in all cases we are talking about <strong><em>free</em></strong> blocks in the heap, not the allocated blocks in the heap. In any case, if the above conditions are not met, then you <em>do</em> have a leak situation of some sort.</p>
<p>So, once you have ruled out a leak, you could consider using a better allocator. <strong><em>Doug Lea's malloc</em></strong> suggested in the question is a very good allocator for general use applications and very robust <em>most</em> of the time. Put another way, it has been time tested to work very well for most any application. However, no algorithm is ideal for <em>all</em> applications and any management algorithm approach can be broken by the right pathelogical conditions against it's design.</p>
<p><em>Why are you having a fragmentation problem?</em> - Sources of fragmentation problems are <em>caused</em> by the behavior of an application and have to do with greatly different allocation lifetimes in the same memory arena. That is, some objects are allocated and freed regularly while other types of objects persist for extended periods of time all in the same heap.....think of the longer lifetime ones as poking holes into larger areas of the arena and thereby preventing the coalesce of adjacent blocks that have been freed.</p>
<p>To address this type of problem, the best thing you can do is logically divide the heap into sub arenas where the lifetimes are more similar. In effect, you want a transient heap and a persistent heap or heaps that group things of similar lifetimes.</p>
<p>Some others have suggested another approach to solve the problem which is to attempt to make the allocation sizes more similar or identical, but this is less ideal because it creates a different type of fragmentation called internal fragmentation - which is in effect the wasted space you have by allocating more memory in the block than you need. </p>
<p>Additionally, with a good heap allocator, like Doug Lea's, making the block sizes more similar is unnecessary because the allocator will already be doing a power of two size bucketing scheme that will make it completely unnecessary to artificially adjust the allocation sizes passed to malloc() - in effect, his heap manager does that for you automatically much more robustly than the application will be able to make adjustments.</p>
| <p>if you talking about Win32 - you can try to squeeze something by using LARGEADDRESSAWARE. You'll have ~1Gb extra defragmented memory so your application will fragment it longer.</p>
| 8,591 |
<p>For a while now, I have been thinking about designing things such as small bedside tables, game/dvd/bluray racks for 3d printing. I've always thought that making them modular would be a good way to go about doing this as well.</p>
<p>Modular design would help to create an end result that is vastly larger than the print volume of my 3d printer. I might even be able to recycle models for use in other projects. However, I'm not sure of what I need to think about if I decide to go ahead with these ideas I have floating around in my head.</p>
<p>I'm assuming that certain joints (dovetail, etc), tolerances for different types of plastic due to shrinkage, and print settings (% infill, in particular) would be important to have thought about and evaluated to some extent, but I'm not sure about what else I might be missing.</p>
<p>So my question is to anyone who has designed anything to be modularly printed. Have you really had to think carefully about the engineering side of the print? Or am I simply overthinking this? Should I just design what I want and give it reasonable infill, walls and whatnot, and just go for a trial and error approach? I'm sure there is a method to this madness, but is a concrete understanding of this type of engineering absolutely paramount when it comes to this sort of stuff?</p>
<hr>
<p>EDIT: Although I've marked darth pixel's answer as accepted, I'm still going to follow JKEngineer's advise and check out that book as well since I feel as though proper engineering techniques alongside a good mentality towards how I would tackle the problem (as outlined in darth pixel's answer) would prove to yield better results in the long run.</p>
| <p>All printers are designed with an idea of <a href="https://en.wikipedia.org/wiki/WYSIWYG" rel="nofollow">WYSIWYG</a> for sure. Depending on:</p>
<ul>
<li>printer - type/quality/settings/configuration/assembly precission</li>
<li>filament - type/quality/shrinkage</li>
<li>user skills - manual/using app proficiency</li>
<li>model complexity</li>
<li>environment conditions and so on</li>
</ul>
<p>you can get different results.</p>
<p>I venture to say users know their printers (after some time and by trials and errors) so they know how to manage dimensions to compensate all above so you will get this knowledge too.</p>
<p>Mathematical formula can describe shrinkage of the material, all other elements are very hard to describe (mathematically) in a general way.</p>
<p>Of course someone can simplify it and say: more money you spend better effects you'll get. It's sometimes true ;)</p>
<p>So all your modular things will be better and better if you will increase (what is to be increased) in above points especially "user skills".</p>
<p>Is engineering paramount? It depends of whay you gonna create. If your modular things have to lock itself, have to have threads, screws and such stuff then this is engineering. Is it the most important part of the design? Not necessarily.</p>
<p>I would say 3D printing moved engineering to next level. I'm talking about <a href="http://www.thingiverse.com/thing:258201" rel="nofollow">this</a> or <a href="http://www.thingiverse.com/thing:249341" rel="nofollow">this</a>. Is it still art or engineering? :)</p>
<p>This is my receipt:</p>
<p><em>think > imagine > design > rethink > redesign > give it a try > get back to thinking</em></p>
<p>good luck</p>
| <p>A book you would benefit from reading is "Functional Design for 3D Printing...Designing 3D Printed things for everyday use - 2nd Edition" by Clifford Smyth. </p>
<p>It deals with FDM printing only. It deals with considerations of orientation of the parts being printed to address required strength in the 3 directions (x, y, z), tolerances, and designing parts in such a way that they can be assembled, have the strength needed, have flexibility, etc. In some instances he shows how to split a single functional part into multiple parts so that, when assembled, it actually performs as required. </p>
<p>It's available from Amazon at <a href="http://rads.stackoverflow.com/amzn/click/1511572027" rel="nofollow">Book on Amazon</a>. I received it as a present and have no commercial interest in it. </p>
<p>Here's a review: <a href="http://3dprintingforbeginners.com/book-review-functional-design-for-3d-printing/" rel="nofollow">Book Review on 3D Printing for Beginners</a></p>
| 369 |
<p>I am building a web page to show a customer what software they purchased and to give them a link to download said software. Unfortunately, the data on what was purchased and the download information are in separate databases so I can't just take care of it with joins in an SQL query.</p>
<p>The common item is SKU. I'll be pulling a list of SKUs from the customer purchases database and on the download table is a comma delineated list of SKUs associated with that download. My intention, at the moment, is to create from this one datatable to populate a <code>GridView</code>.</p>
<p>Any suggestions on how to do this efficiently would be appreciated. If it helps, I can pretty easily pull back the data as a <code>DataSet</code> or a <code>DataReader</code>, if either one would be better for this purpose.</p>
| <p>As long as the two databases are on the same physical server (assuming MSSQL) and the username/password being used in the connection string has rights to both DBs, then you should be able to perform a join across the two databases. Example: </p>
<pre><code>select p.Date,
p.Amount,
d.SoftwareName,
d.DownloadLink
from PurchaseDB.dbo.Purchases as p
join ProductDB.dbo.Products as d on d.sku = p.sku
where p.UserID = 12345
</code></pre>
| <p>I am thinking off the top of my head here. If you load both as Data Tables in the same Data Sets, and define a relation between the two over SKU, and then run a query on the Data Set which produces the desired result.</p>
| 2,445 |
<p>I was reading a research paper about Haskell and how HList is implemented and wondering when the techniques described are and are not decidable for the type checker. Also, because you can do similar things with GADTs, I was wondering if GADT type checking is always decidable.</p>
<p>I would prefer citations if you have them so I can read/understand the explanations.</p>
<p>Thanks!</p>
| <p>I believe GADT type checking is always decidable; it's inference which is undecidable, as it requires higher order unification. But a GADT type checker is a restricted form of the proof checkers you see in eg. Coq, where the constructors build up the proof term. For example, the classic example of embedding lambda calculus into GADTs has a constructor for each <em>reduction rule</em>, so if you want to find the normal form of a term, you have to tell it which constructors will get you to it. The halting problem has been moved into the user's hands :-)</p>
| <p>You've probably already seen this but there are a collection of papers on this issue at Microsoft research: <a href="http://research.microsoft.com/~simonpj/papers/assoc-types/" rel="nofollow noreferrer">Type Checking papers</a>. The first one describes the decidable algorithm actually used in the Glasgow Haskell compiler.</p>
| 7,131 |
<p>We have a requirement in project to store all the revisions(Change History) for the entities in the database. Currently we have 2 designed proposals for this:</p>
<p>e.g. for "Employee" Entity</p>
<p><strong>Design 1:</strong></p>
<pre><code>-- Holds Employee Entity
"Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)"
-- Holds the Employee Revisions in Xml. The RevisionXML will contain
-- all data of that particular EmployeeId
"EmployeeHistories (EmployeeId, DateModified, RevisionXML)"
</code></pre>
<p><strong>Design 2:</strong></p>
<pre><code>-- Holds Employee Entity
"Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)"
-- In this approach we have basically duplicated all the fields on Employees
-- in the EmployeeHistories and storing the revision data.
"EmployeeHistories (EmployeeId, RevisionId, DateModified, FirstName,
LastName, DepartmentId, .., ..)"
</code></pre>
<p>Is there any other way of doing this thing? </p>
<p>The problem with the "Design 1" is that we have to parse XML each time when you need to access data. This will slow the process and also add some limitations like we cannot add joins on the revisions data fields.</p>
<p>And the problem with the "Design 2" is that we have to duplicate each and every field on all entities (We have around 70-80 entities for which we want to maintain revisions).</p>
| <p>I think the key question to ask here is 'Who / What is going to be using the history'?</p>
<p>If it's going to be mostly for reporting / human readable history, we've implemented this scheme in the past...</p>
<p>Create a table called 'AuditTrail' or something that has the following fields...</p>
<pre><code>[ID] [int] IDENTITY(1,1) NOT NULL,
[UserID] [int] NULL,
[EventDate] [datetime] NOT NULL,
[TableName] [varchar](50) NOT NULL,
[RecordID] [varchar](20) NOT NULL,
[FieldName] [varchar](50) NULL,
[OldValue] [varchar](5000) NULL,
[NewValue] [varchar](5000) NULL
</code></pre>
<p>You can then add a 'LastUpdatedByUserID' column to all of your tables which should be set every time you do an update / insert on the table.</p>
<p>You can then add a trigger to every table to catch any insert / update that happens and creates an entry in this table for each field that's changed. Because the table is also being supplied with the 'LastUpdateByUserID' for each update / insert, you can access this value in the trigger and use it when adding to the audit table.</p>
<p>We use the RecordID field to store the value of the key field of the table being updated. If it's a combined key, we just do a string concatenation with a '~' between the fields.</p>
<p>I'm sure this system may have drawbacks - for heavily updated databases the performance may be hit, but for my web-app, we get many more reads than writes and it seems to be performing pretty well. We even wrote a little VB.NET utility to automatically write the triggers based on the table definitions.</p>
<p>Just a thought!</p>
| <p>It sounds like you want to track changes to specific entities over time, e.g. ID 3, "bob", "123 main street", then another ID 3, "bob" "234 elm st", and so on, in essence being able to puke out a revision history showing every address "bob" has been at.</p>
<p>The best way to do this is to have an "is current" field on each record, and (probably) a timestamp or FK to a date/time table.</p>
<p>Inserts have to then set the "is current" and also unset the "is current" on the previous "is current" record. Queries have to specify the "is current", unless you want all of the history.</p>
<p>There are further tweaks to this if it's a very large table, or a large number of revisions are expected, but this is a fairly standard approach.</p>
| 6,033 |
<p>I'm used to the Vi(m) editor and am using MS Visual Studio 2005 at work. I couldn't find a free Vi add-in (there's only one for the 2003 version). I googled a bit, saw that there was a 'Google summer of code' project this year to write such an add-in, and am eagerly awaiting the result. I've also heard of ViEmu (not free, and I can't test it at work).</p>
<p>Has anyone in my situation has found a solution (and/or tested ViEmu)?</p>
<p>Edit: I can't test ViEmu at work because they are paranoid about what we install on our boxes: it has to go through required channels, and for 30 days I don't reckon it's worth it (and I have no Windows box at home).</p>
<p>Edit: Since both answers were equivalent, I ended up accepting the first one that came in.</p>
| <p>ViEmu works great with Visual Studio. I used Vi(m) strictly in Linux, but I was turned on to bringing the Vi(m) editing process into the Windows world by <a href="http://www.jpboodhoo.com/" rel="noreferrer">JP Boodhoo</a>. JP <a href="http://blog.jpboodhoo.com/HookedOnVIM.aspx" rel="noreferrer">praises</a> about it also.</p>
| <p><a href="http://www.viemu.com/" rel="nofollow noreferrer">ViEmu</a> works great. I've been using it for about a year now and couldn't imagine coding in Visual Studio without it.</p>
<p>Why can't you test it at work? It has a 30 day free trial.</p>
| 4,425 |
<p>Does anyone know of a way to force a nolock hint on all transactions issued by a certain user? I'd like to provide a login for a support team to query the production system, but I want to protect it by forcing a nolock on everything they do. I'm using SQL Server 2005.</p>
| <p>You could configure your support staff's SQL Management Studio to set the default transaction isolation level to READ UNCOMMITTED (Tools->Options->Query Execution->SQL Server->Advanced). This is functionally the same as having NOLOCK hints on everything.</p>
<p>The downsides are that you'd have to do this for each member of your support team, and they'd have the ability to change the configuration on their SQL Management Studio.</p>
| <p>You could create a limited user for the support team, and then either write stored procedures or views with the nolock-hint. Then only give access to those and not direct table select access.</p>
| 8,971 |
<p>TL;DR - For a given Kossel frame size (w.r.t. the vertical and horizontal frame lengths of the aluminium extrusion), what would the length of the carbon fibre rods be?</p>
<hr>
<p>A case in point, from <a href="http://reprap.org/wiki/Kossel" rel="nofollow noreferrer">RepRapWiki - Kossel</a>, there is an intriguing note about a scaled down Kossel:</p>
<blockquote>
<p>Optionally scale down to a Traveling RepRap that fits within IATA hand
luggage size limit (see transportation):</p>
<ul>
<li>Frame height: 550 mm.</li>
<li>Footprint: triangle, 270 mm width, 250 mm across (210 mm 15 x 15 mm aluminium extrusion like OpenBeam + printed corners).</li>
</ul>
</blockquote>
<p>However, there is no mention of the length of the carbon fibre rods (carbon tubes).</p>
<p>Now, as per my previous question, <a href="https://3dprinting.stackexchange.com/questions/3965/for-a-larger-build-volume-what-lengths-of-2020-aluminium-do-i-need">For a larger build volume, what lengths of 2020 aluminium do I need?</a>, is there a formula or ratio by which one needs to abide? Whereas in my previous question, the answer was along the lines of: <em>Not really, you can use any lengths, within reason, and account for it later in the firmware</em>, I would imagine that the Delta aspect of the printer is somewhat more exacting.</p>
<p>I have tried googling for further information on this Travelling Kossel, but found nothing, except for the information of RepRapWiki.</p>
<p>Looking at the corresponding lengths (vertical/horizontal) of the aluminium versus those of the carbon fibre rods for the Mini and XL:</p>
<ul>
<li>600/240 mm versus 180 mm</li>
<li>750/360 mm versus 300 mm</li>
</ul>
<p>I really can not see what the (trigonometric) relationship is, and therefore can not deduce the lengths of the carbon rods for the Travelling Kossel. </p>
<p>Unless it is simply that the carbon rods are 60 mm shorter than the aluminium horizontals? Is it really as simple as that, or is this just a coincidence? In which case, would the carbon rods be (210 - 60 =) 150 mm?</p>
<p>By extension, imagine if you wanted to build a Kossel XXXL, with a horizontal aluminium extrusion length of, let's say, 1000 mm, would the length of the carbon rods be 940 mm?</p>
<p>Any ideas?</p>
| <p>I had the same problem, and I solved it by changing the <em>Z-Axis Feed Rate</em> to a much higher value (1000 mm/min.) in Repetier Host via <em>Config -> Printer Settings -> Printer</em>.</p>
| <p>Try changing the travel speed in you r slicer, if that doesn't work , try changing out the motors for newer ones.</p>
| 589 |
<p>I have the following <code>textarea</code> in a <code>table</code>:</p>
<pre><code><table width="300"><tr><td>
<textarea style="width:100%">
longstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstring
</textarea>
</td></tr></table>
</code></pre>
<p>With a long string in the textarea, the textarea stretches out to accommodate it in one line in IE7, but retains its 300px width in other browsers.</p>
<p>Any ideas as to how to fix this in IE?</p>
| <p>Apply the width to the <code>td</code>, not the <code>table</code>.</p>
<p>EDIT: @Emmett - the width could just as easily be applied via CSS.</p>
<pre class="lang-css prettyprint-override"><code>td {
width: 300px;
}
</code></pre>
<p>produces the desired result. Or, if you're using jQuery, you could add the width through script:</p>
<pre><code>$('textarea[width=100%]').parent('td').css('width', '300px');
</code></pre>
<p>Point being, there's more than one way to apply a width to a table cell, if development constraints prevent you from applying it directly.</p>
| <p>did you try...</p>
<p><code>overflow: hidden;</code></p>
<p>??</p>
<p>I'm not sure if it should be in the table of the textarea... experiment a bit</p>
| 5,406 |
<p>What is the best full text search alternative to Microsoft SQL? (which works with MS SQL)</p>
<p>I'm looking for something similar to <a href="http://lucene.apache.org/java/docs/index.html" rel="nofollow noreferrer">Lucene</a> and <a href="http://incubator.apache.org/lucene.net/" rel="nofollow noreferrer">Lucene.NET</a> but without the .NET and Java requirements. I would also like to find a solution that is usable in commercial applications.</p>
| <p>Take a look at <a href="http://clucene.wiki.sourceforge.net/" rel="nofollow noreferrer">CLucene</a> - It's a well maintained C++ port of java Lucene. It's currently licenced under LGPL and we use it in our commercial application.</p>
<p>Performance is incredible, however you do have to get your head around some of the strange API conventions.</p>
| <p>I second Sphinx, but <a href="http://lucene.apache.org/" rel="nofollow noreferrer">Lucene</a> is also not so bad despite the Java. :) If you are not dealing with too much data spread out etc., then also look into MySQL's <a href="http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html" rel="nofollow noreferrer">FULLTEXT</a>. We are using it to search across a 20 GB database.</p>
| 5,979 |
<p>I was wondering if there is any good and clean object-oriented programming (OOP) implementation of Bayesian filtering for spam and text classification? This is just for learning purposes.</p>
| <p>I definitely recommend <a href="http://www.cs.waikato.ac.nz/ml/weka/" rel="noreferrer">Weka</a> which is an <em>Open Source Data Mining Software</em> written in Java:</p>
<blockquote>
<p>Weka is a collection of machine learning algorithms for data mining tasks. The algorithms can either be applied directly to a dataset or called from your own Java code. Weka contains tools for data pre-processing, classification, regression, clustering, association rules, and visualization. It is also well-suited for developing new machine learning schemes.</p>
</blockquote>
<p>As mentioned above, it ships with a bunch of different classifiers like <a href="http://en.wikipedia.org/wiki/Support_vector_machine" rel="noreferrer">SVM</a>, <a href="http://en.wikipedia.org/wiki/Winnow_%28algorithm%29" rel="noreferrer">Winnow</a>, <a href="http://en.wikipedia.org/wiki/C4.5_algorithm" rel="noreferrer">C4.5</a>, Naive Bayes (of course) and many more (see the <a href="http://weka.sourceforge.net/doc/" rel="noreferrer">API doc</a>).
Note that a lot of classifiers are known to have <strong>much better perfomance than Naive Bayes</strong> in the field of spam detection or text classification.</p>
<p>Furthermore Weka brings you a very <a href="http://www.cs.waikato.ac.nz/~ml/weka/gui_explorer.html" rel="noreferrer">powerful GUI</a>…</p>
| <p>In French, but you should be able to find the download link :)
<a href="http://xhtml.net/scripts/PHPNaiveBayesianFilter" rel="nofollow noreferrer">PHP Naive Bayesian Filter</a></p>
| 2,352 |
<p>As part of my integration strategy, I have a few SQL scripts that run in order to update the database. The first thing all of these scripts do is check to see if they need to run, e.g.:</p>
<pre><code>if @version <> @expects
begin
declare @error varchar(100);
set @error = 'Invalid version. Your version is ' + convert(varchar, @version) + '. This script expects version ' + convert(varchar, @expects) + '.';
raiserror(@error, 10, 1);
end
else
begin
...sql statements here...
end
</code></pre>
<p>Works great! Except if I need to add a stored procedure. The "create proc" command must be the only command in a batch of sql commands. Putting a "create proc" in my IF statement causes this error:</p>
<pre>
'CREATE/ALTER PROCEDURE' must be the first statement in a query batch.
</pre>
<p>Ouch! How do I put the CREATE PROC command in my script, and have it only execute if it needs to?</p>
| <p>Here's what I came up with:</p>
<p>Wrap it in an EXEC(), like so:</p>
<pre><code>if @version <> @expects
begin
...snip...
end
else
begin
exec('CREATE PROC MyProc AS SELECT ''Victory!''');
end
</code></pre>
<p>Works like a charm!</p>
| <pre><code>IF NOT EXISTS(SELECT * FROM sys.procedures WHERE name = 'pr_MyStoredProc')
BEGIN
CREATE PROCEDURE pr_MyStoredProc AS .....
SET NOCOUNT ON
END
ALTER PROC pr_MyStoredProc
AS
SELECT * FROM tb_MyTable
</code></pre>
| 7,930 |
<p>At work, we have multiple branches that we may be working on at any time.
Our solution so far as been to create multiple web-sites but you can only run one web-site at a time. This makes switching between branches more of a pain that in should be. </p>
<p>I just want to go to the URL, mapped in my hosts file, for that branch and it just work. </p>
<p>Our client machines are XP machines with IIS 5.1. Is there any way to make IIS 5.1 run more than one web-site simultaneously?</p>
| <p>Yes, it is a restriction and this one website can have only 10 simultanious connections.</p>
<p>Buy a Windows 2003 or 2008 Small Business Edition, it is quite cost-effective in this scenario.</p>
| <p>One way you could solve this without reinstalling your computer is to create each branch in a virtual subdirectory under you current web-root. Then at the top-level website, create a default.asp(x) the reads <code>Request.ServerVariables["SERVER-NAME"]</code> (should be underscore) and redirects the browser to whatever virtual directory/application you want to access. That way you can create all the "virtual" domains you want in your hosts file.</p>
| 5,450 |
<p>I read something the other day about a guy who found a way to knock over completed prints with the printer head itself, then slide them to the edge of the build plate, where they fall into a box/basket. This allows printing several Eiffel Towers while you sleep for example. It doesn't work with skirts (duh), and the adhesion has to be just right not to wake up with a pile of spaghetti, but it still sounds useful.</p>
<p>Well, now I cannot re-find the description I read; does anyone know what this process is called? Is there an easy way I can perform such an end-of-print action on my CR-10 with a cura plugin? If such a thing takes a touch of end-time custom gcode, is there a proof of concept rough draft or demo I can start tinkering with? Any more info is helpful.</p>
| <p>You could cool down the heated bed (with e.g. <code>[M109][1] R28</code>) and cool down the hotend (with e.g. <code>[M190][1] R40</code>). This will usually release the print from the plate, perform the actions to move the head (e.g. go to the largest X, Y position <code>G1 X{max} Y{max}</code>, move down <code>G1 Z10</code> to then move to minimum X, Y <code>G1 X0 Y0</code> position such that it sweeps the print to the origin) that it knocks it into the basket and start printing again by copy pasting the whole G-code beforehand a couple of times. Note that this all depends on the product you are printing. You should at least use the end code scripts for the specific tasks to cool down, and start scripts to heat up again.</p>
<p>You can write a Cura plugin to implement a new GUI item to copy the G-code multiple times or create a post processing plugin.</p>
| <p>For fun, from Thingiverse - <a href="https://www.thingiverse.com/thing:872617" rel="nofollow noreferrer">Automatic Print Ejector - The Punching Machine</a>. </p>
<p>There's even a video: <a href="https://www.youtube.com/watch?v=Viy928RLsdU" rel="nofollow noreferrer">MatterHackers Punch-Out!</a></p>
<p><sub>Hover for a (slightly annoying) image:</sub></p>
<blockquote class="spoiler">
<p> <a href="https://i.stack.imgur.com/BerJJ.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BerJJ.gif" alt="Punch-Out"></a></p>
</blockquote>
| 961 |
<p>Stack exchange isn't a good platform for product recommendations in general, but a few sites allow it with a tight focus and control. Some that have allowed it in the past have decided to discontinue it for a variety of reasons.</p>
<p>I expect at the start we are going to get a lot of "What specific machine should I use" or "is there a 3D model of item X I can print".</p>
<ol>
<li>Should we allow product or part recommendations?</li>
<li>If we do, what can we do to make sure they are limited, rather than open ended questions where dozens or hundreds of answers would be different but correct?</li>
</ol>
| <p>I agree with Jeff's blog post: <a href="https://blog.stackoverflow.com/2010/11/qa-is-hard-lets-go-shopping/">https://blog.stackoverflow.com/2010/11/qa-is-hard-lets-go-shopping/</a></p>
<blockquote>
<p>don't ask us what you should buy -- ask us <em>what you need to learn</em> to tell what you should buy.</p>
</blockquote>
| <p>I think that hardware recommendations are ok, but in a <strong>limited</strong> and <strong>specific</strong> scope:</p>
<p>Bad:</p>
<blockquote>
<p>Can you recommend a cheap printer with a heated bed that's at least 8"*8"*8".</p>
<p>Which is better? Printer X or printer Y?</p>
</blockquote>
<p>Good:</p>
<blockquote>
<p>What hotend can I use to print at 300+C?</p>
<p>What are the advantages of borosilicate glass over picture frame glass?</p>
</blockquote>
| 2 |
<p>I'm working on moving a client/server application created with C# and WinForms into the SOA/WPF/Silverlight world. One of the big hurdles is the design of the UI. My current UI is MDI driven and users rely heavily on child windows, having many open at the same time and toggling back and forth between them. </p>
<p>What might be the best way to recreate the UI functionality in an MDI-less environment? (I've no desire to create MDI functionality on my own in WPF). Tabs? A list panel that toggles different controls? </p>
| <p>I think the answer is really going to be up to your users -- I'd set up some prototypes with multiple paradigms and let them provide some input. The last thing you want to do is introduce a new UI paradigm without having any end-user input.</p>
<p>Tabs are really popular now, but don't allow side-by-side viewing, so if that is a requirement you may want to go with more of an outlook-style setup, with multiple panels that can be activated, hidden and resized.</p>
<p>One thing that you might want to do is to code your app as a composite UI, where each view is built independently from its container (be it a child window, tab or accordion, etc.), and is just "dropped in" in the designer. That will protect you from when the users change their minds about the navigation paradigm in the future.</p>
| <p>Did you try <a href="http://www.netikatech.com/products/default.aspx" rel="nofollow noreferrer">GOA WinForms</a>?</p>
| 7,328 |
<p>Before you answer this I have never developed anything popular enough to attain high server loads. Treat me as (sigh) an alien that has just landed on the planet, albeit one that knows PHP and a few optimisation techniques.</p>
<hr>
<p>I'm developing a tool in <strong>PHP</strong> that could attain quite a lot of users, if it works out right. However while I'm fully capable of developing the program I'm pretty much clueless when it comes to making something that can deal with huge traffic. So here's a few questions on it (feel free to turn this question into a resource thread as well).</p>
<h2>Databases</h2>
<p>At the moment I plan to use the MySQLi features in PHP5. However how should I setup the databases in relation to users and content? Do I actually <em>need</em> multiple databases? At the moment everything's jumbled into one database - although I've been considering spreading user data to one, actual content to another and finally core site content (template masters etc.) to another. My reasoning behind this is that sending queries to different databases will ease up the load on them as one database = 3 load sources. Also would this still be effective if they were all on the same server?</p>
<h2>Caching</h2>
<p>I have a template system that is used to build the pages and swap out variables. Master templates are stored in the database and each time a template is called it's cached copy (a html document) is called. At the moment I have two types of variable in these templates - a static var and a dynamic var. Static vars are usually things like page names, the name of the site - things that don't change often; dynamic vars are things that change on each page load.</p>
<p>My question on this:</p>
<p>Say I have comments on different articles. Which is a better solution: store the simple comment template and render comments (from a DB call) each time the page is loaded or store a cached copy of the comments page as a html page - each time a comment is added/edited/deleted the page is recached.</p>
<h2>Finally</h2>
<p>Does anyone have any tips/pointers for running a high load site on PHP. I'm pretty sure it's a workable language to use - Facebook and Yahoo! give it great precedence - but are there any experiences I should watch out for?</p>
| <p>No two sites are alike. You really need to get a tool like <a href="http://jakarta.apache.org/jmeter/" rel="noreferrer">jmeter</a> and benchmark to see where your problem points will be. You can spend a lot of time guessing and improving, but you won't see real results until you measure and compare your changes. </p>
<p>For example, for many years, the MySQL query cache was the solution to all of our performance problems. If your site was slow, MySQL experts suggested turning the query cache on. It turns out that if you have a high write load, the cache is actually crippling. If you turned it on without testing, you'd never know.</p>
<p>And don't forget that you are never done scaling. A site that handles 10req/s will need changes to support 1000req/s. And if you're lucking enough to need to support 10,000req/s, your architecture will probably look completely different as well.</p>
<h1>Databases</h1>
<ul>
<li>Don't use MySQLi -- <a href="http://ca.php.net/pdo" rel="noreferrer">PDO</a> is the 'modern' OO database access layer. The most important feature to use is placeholders in your queries. It's smart enough to use server side prepares and other optimizations for you as well.</li>
<li>You probably don't want to break your database up at this point. If you do find that one database isn't cutting, there are several techniques to scale up, depending on your app. Replicating to additional servers typically works well if you have more reads than writes. Sharding is a technique to split your data over many machines.</li>
</ul>
<h1>Caching</h1>
<ul>
<li>You probably don't want to cache in your database. The database is typically your bottleneck, so adding more IO's to it is typically a bad thing. There are several PHP caches out there that accomplish similar things like <a href="http://ca.php.net/apc" rel="noreferrer">APC</a> and Zend. </li>
<li>Measure your system with caching on and off. I bet your cache is heavier than serving the pages straight. </li>
<li>If it takes a long time to build your comments and article data from the db, integrate <a href="http://www.danga.com/memcached/" rel="noreferrer">memcache</a> into your system. You can cache the query results and store them in a memcached instance. It's important to remember that retrieving the data from memcache must be faster than assembling it from the database to see any benefit.</li>
<li>If your articles aren't dynamic, or you have simple dynamic changes after it's generated, consider writing out html or php to the disk. You could have an index.php page that looks on disk for the article, if it's there, it streams it to the client. If it isn't, it generates the article, writes it to the disk and sends it to the client. Deleting files from the disk would cause pages to be re-written. If a comment is added to an article, delete the cached copy -- it would be regenerated.</li>
</ul>
| <p>@<a href="https://stackoverflow.com/questions/24675/tactics-for-using-php-in-a-high-load-site#24689">Gary</a></p>
<blockquote>
<p>Don't use MySQLi -- PDO is the 'modern' OO database access layer. The most important feature to use is placeholders in your queries. It's smart enough to use server side prepares and other optimizations for you as well.</p>
</blockquote>
<p>I'm loking over PDO at the moment and it looks like you're right - however I know that MySQL are developing the MySQLd extension for PHP - I think to succeed either MySQL or MySQLi - what do you think about that?</p>
<hr>
<p>@<a href="https://stackoverflow.com/questions/24675/tactics-for-using-php-in-a-high-load-site#24685">Ryan</a>, <a href="https://stackoverflow.com/questions/24675/tactics-for-using-php-in-a-high-load-site#24681">Eric</a>, <a href="https://stackoverflow.com/questions/24675/tactics-for-using-php-in-a-high-load-site#24679">tj9991</a></p>
<p>Thanks for the advice on PHP's caching extensions - could you explain reasons for using one over another? I've heard great things about memcached through IRC but have never heard of APC - what are your opinions on them? I assume using multiple caching systems is pretty counter-effective.</p>
<p>I will definitely be sorting out some profiling testers - thank you very much for your recommendations on those.</p>
| 4,432 |
<p>I'm using an Ubuntu 8.04 (x86_64) machine to connect to my employer's Cisco VPN. (The client didn't compile out of the box, but I found <a href="http://projects.tuxx-home.at/?id=cisco_vpn_client" rel="nofollow noreferrer">patches to update the client to compile on kernels released in the last two years</a>.) This all works great, until my DHCP client decides to renew its lease and updates /etc/resolv.conf, replacing the VPN-specific name servers with my general network servers.</p>
<p>Is there a good way to prevent my DHCP client from updating /etc/resolv.conf while my VPN is active?</p>
| <p>If you are running without NetworkManager handling the connections, use the resolvconf package to act as an intermediary to programs tweaking /etc/resolv.conf: <strong><code>sudo apt-get install resolvconf</code></strong></p>
<p>If you are using NetworkManager it will handle this for you, so get rid of the resolvconf package: <strong><code>sudo apt-get remove resolvconf</code></strong></p>
<p>I found out about this when setting up vpnc on Ubuntu last week. A search for <strong><code>vpn resolv.conf</code></strong> on ubuntuforums.org has 250 results, many of which are very related!</p>
| <p>vpnc seems to be doing the right thing for my employer's cisco concentrator. I jump on and off the vpn, and it seems to update everything smoothly.</p>
| 7,047 |
<p>Whenever I design a database, I always wonder if there is a best way of naming an item in my database. Quite often I ask myself the following questions:</p>
<ol>
<li>Should table names be plural?</li>
<li>Should column names be singular?</li>
<li>Should I prefix tables or columns?</li>
<li>Should I use any case in naming items?</li>
</ol>
<p>Are there any recommended guidelines out there for naming items in a database?</p>
| <p>I recommend checking out Microsoft's SQL Server sample databases:
<a href="https://github.com/Microsoft/sql-server-samples/releases/tag/adventureworks" rel="noreferrer">https://github.com/Microsoft/sql-server-samples/releases/tag/adventureworks</a></p>
<p>The AdventureWorks sample uses a very clear and consistent naming convention that uses schema names for the organization of database objects.</p>
<ol>
<li>Singular names for tables</li>
<li>Singular names for columns</li>
<li>Schema name for tables prefix (E.g.: SchemeName.TableName)</li>
<li>Pascal casing (a.k.a. upper camel case)</li>
</ol>
| <pre><code>
--Example SQL
CREATE TABLE D001_Students
(
StudentID INTEGER CONSTRAINT nnD001_STID NOT NULL,
ChristianName NVARCHAR(255) CONSTRAINT nnD001_CHNA NOT NULL,
Surname NVARCHAR(255) CONSTRAINT nnD001_SURN NOT NULL,
CONSTRAINT pkD001 PRIMARY KEY(StudentID)
);
CREATE INDEX idxD001_STID on D001_Students;
CREATE TABLE D002_Classes
(
ClassID INTEGER CONSTRAINT nnD002_CLID NOT NULL,
StudentID INTEGER CONSTRAINT nnD002_STID NOT NULL,
ClassName NVARCHAR(255) CONSTRAINT nnD002_CLNA NOT NULL,
CONSTRAINT pkD001 PRIMARY KEY(ClassID, StudentID),
CONSTRAINT fkD001_STID FOREIGN KEY(StudentID)
REFERENCES D001_Students(StudentID)
);
CREATE INDEX idxD002_CLID on D002_Classes;
CREATE VIEW V001_StudentClasses
(
SELECT
D001.ChristianName,
D001.Surname,
D002.ClassName
FROM
D001_Students D001
INNER JOIN
D002_Classes D002
ON
D001.StudentID = D002.StudentID
);
</code></pre>
<p>These are the conventions I was taught, but you should adapt to whatever you developement hose uses.</p>
<ol>
<li>Plural. It is a collection of entities.</li>
<li>Yes. The attribute is a representation of singular property of an entity.</li>
<li>Yes, prefix table name allows easily trackable naming of all constraints indexes and table aliases.</li>
<li>Pascal Case for table and column names, prefix + ALL caps for indexes and constraints.</li>
</ol>
| 2,923 |
<p>How do you pass <code>$_POST</code> values to a page using <code>cURL</code>?</p>
| <p>Should work fine.</p>
<pre><code>$data = array('name' => 'Ross', 'php_master' => true);
// You can POST a file by prefixing with an @ (for <input type="file"> fields)
$data['file'] = '@/home/user/world.jpg';
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
curl_exec($handle);
curl_close($handle)
</code></pre>
<p>We have two options here, <code>CURLOPT_POST</code> which turns HTTP POST on, and <code>CURLOPT_POSTFIELDS</code> which contains an array of our post data to submit. This can be used to submit data to <code>POST</code> <code><form></code>s.</p>
<hr>
<p>It is important to note that <code>curl_setopt($handle, CURLOPT_POSTFIELDS, $data);</code> takes the $data in two formats, and that this determines how the post data will be encoded.</p>
<ol>
<li><p><code>$data</code> as an <code>array()</code>: The data will be sent as <code>multipart/form-data</code> which is not always accepted by the server.</p>
<pre><code>$data = array('name' => 'Ross', 'php_master' => true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
</code></pre></li>
<li><p><code>$data</code> as url encoded string: The data will be sent as <code>application/x-www-form-urlencoded</code>, which is the default encoding for submitted html form data.</p>
<pre><code>$data = array('name' => 'Ross', 'php_master' => true);
curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($data));
</code></pre></li>
</ol>
<p>I hope this will help others save their time.</p>
<p>See: </p>
<ul>
<li><a href="http://www.php.net/manual/en/function.curl-init.php" rel="noreferrer"><code>curl_init</code></a></li>
<li><a href="http://www.php.net/manual/en/function.curl-setopt.php" rel="noreferrer"><code>curl_setopt</code></a></li>
</ul>
| <pre><code><?php
function executeCurl($arrOptions) {
$mixCH = curl_init();
foreach ($arrOptions as $strCurlOpt => $mixCurlOptValue) {
curl_setopt($mixCH, $strCurlOpt, $mixCurlOptValue);
}
$mixResponse = curl_exec($mixCH);
curl_close($mixCH);
return $mixResponse;
}
// If any HTTP authentication is needed.
$username = 'http-auth-username';
$password = 'http-auth-password';
$requestType = 'POST'; // This can be PUT or POST
// This is a sample array. You can use $arrPostData = $_POST
$arrPostData = array(
'key1' => 'value-1-for-k1y-1',
'key2' => 'value-2-for-key-2',
'key3' => array(
'key31' => 'value-for-key-3-1',
'key32' => array(
'key321' => 'value-for-key321'
)
),
'key4' => array(
'key' => 'value'
)
);
// You can set your post data
$postData = http_build_query($arrPostData); // Raw PHP array
$postData = json_encode($arrPostData); // Only USE this when request JSON data.
$mixResponse = executeCurl(array(
CURLOPT_URL => 'http://whatever-your-request-url.com/xyz/yii',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPGET => true,
CURLOPT_VERBOSE => true,
CURLOPT_AUTOREFERER => true,
CURLOPT_CUSTOMREQUEST => $requestType,
CURLOPT_POSTFIELDS => $postData,
CURLOPT_HTTPHEADER => array(
"X-HTTP-Method-Override: " . $requestType,
'Content-Type: application/json', // Only USE this when requesting JSON data
),
// If HTTP authentication is required, use the below lines.
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => $username. ':' . $password
));
// $mixResponse contains your server response.
</code></pre>
| 4,806 |
<p>I'd like to convert a Parallels Virtual Machine image on my mac into an image usable by Virtual PC 2007. Does anyone know how to do that, or if it is possible?</p>
| <p>It looks like qemu-img from <a href="http://bellard.org/qemu/" rel="nofollow noreferrer">qemu</a> can do this, at least looking at its commandline help on a Ubuntu 8.04 machine where it claims support for, among others, the "parallels" and the "vpc" format.</p>
<p>Have not tried myself, though. Hope this helps.</p>
| <p>If it's a Windows image, I would mount the VM using a tool like <a href="http://www.prowesscorp.com/support/help/smartdeploy_vdc/Welcome_to_SmartVDK_v1.0.htm" rel="nofollow noreferrer">SmartVDK</a>, then capture the VM with ImageX to a WIM file. You can then mount a blank VHD with SmartVDK and apply the image using ImageX /APPLY.</p>
<p>The qemu-img tool is better if you're performing the conversion on a Mac or Linux machine.</p>
<p>Keep in mind that you will probably encounter difficulties booting the drive if the drive serials have changed. Also, the hardware will be different. It is often better to build a new image and then to mount the converted drive, copying over anything else you need.</p>
| 8,998 |
<p>I am looking for any strategies people use when implementing server applications that service client TCP (or UDP) requests: design patterns, implementation techniques, best practices, etc.</p>
<p>Let's assume for the purposes of this question that the requests are relatively long-lived (several minutes) and that the traffic is time sensitive, so no delays are acceptable in responding to messages. Also, we are both servicing requests from clients and making our own connections to other servers.</p>
<p>My platform is .NET, but since the underlying technology is the same regardless of platform, I'm interested to see answers for any language.</p>
| <p>The modern approach is to make use of the operating system to multiplex many network sockets for you, freeing your application to only processing active connections with traffic.</p>
<p>Whenever you open a socket it's associated it with a selector. You use a single thread to poll that selector. Whenever data arrives, the selector will indicate the socket which is active, you hand off that operation to a child thread and continue polling.</p>
<p>This way you only need a thread for each concurrent operation. Sockets which are open but idle will not tie up a thread.</p>
<ul>
<li><a href="http://www.techrepublic.com/article/using-the-select-and-poll-methods/" rel="nofollow noreferrer">Using the select() and poll() methods</a></li>
<li><a href="http://www.onjava.com/pub/a/onjava/2004/09/01/nio.html" rel="nofollow noreferrer">Building Highly Scalable Servers with Java NIO</a></li>
</ul>
| <p>G'day,</p>
<p>I'd start by looking at the metaphor you want to use for your thread framework.</p>
<p>Maybe "leader follower" where a thread is listening for incoming requests and when a new request comes in it does the work and the next thread in the pool starts listening for incoming requests.</p>
<p>Or thread pool where the same thread is always listening for incoming requests and then passing the requests over to the next available thread in the thread pool.</p>
<p>You might like to visit the <a href="http://www.cs.wustl.edu/~schmidt/ACE-papers.html#reactor" rel="nofollow noreferrer">Reactor</a> section of the Ace Components to get some ideas.</p>
<p>HTH.</p>
<p>cheers,
Rob</p>
| 5,213 |
<p>In order to fully use LinqToSql in an ASP.net 3.5 application, it is necessary to create <a href="http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.aspx" rel="noreferrer">DataContext</a> <a href="http://dotnetslackers.com/articles/csharp/InsideTheLINQToSQLDataContextClass.aspx" rel="noreferrer">classes</a> (which is usually done using the designer in VS 2008). From the UI perspective, the DataContext is a design of the sections of your database that you would like to expose to through LinqToSql and is integral in setting up the ORM features of LinqToSql.</p>
<p>My question is: I am setting up a project that uses a large database where all tables are interconnected in some way through Foreign Keys. My first inclination is to make one huge DataContext class that models the entire database. That way I could in theory (though I don't know if this would be needed in practice) use the Foreign Key connections that are generated through LinqToSql to easily go between related objects in my code, insert related objects, etc.</p>
<p>However, after giving it some thought, I am now thinking that it may make more sense to create multiple DataContext classes, each one relating to a specific namespace or logical interrelated section within my database. My main concern is that instantiating and disposing one huge DataContext class all the time for individual operations that relate to specific areas of the Database would be impose an unnecessary imposition on application resources. Additionally, it is easier to create and manage smaller DataContext files than one big one. The thing that I would lose is that there would be some distant sections of the database that would not be navigable through LinqToSql (even though a chain of relationships connects them in the actual database). Additionally, there would be some table classes that would exist in more than one DataContext.</p>
<p>Any thoughts or experience on whether multiple DataContexts (corresponding to DB namespaces) are appropriate in place of (or in addition to) one very large DataContext class (corresponding to the whole DB)?</p>
| <p>I disagree with John's answer. The DataContext (or Linq to Entities ObjectContext) is more of a "unit of work" than a connection. It manages change tracking, etc. See this blog post for a description:</p>
<p><a href="http://blogs.msdn.com/dinesh.kulkarni/archive/2008/04/27/lifetime-of-a-linq-to-sql-datacontext.aspx" rel="noreferrer">Lifetime of a LINQ to SQL DataContext</a></p>
<p>The four main points of this blog post are that DataContext:</p>
<ol>
<li>Is ideally suited
for a "unit of work" approach </li>
<li>Is also designed for
"stateless" server operation</li>
<li>Is not designed for
Long-lived usage</li>
<li><pre><code>Should be used very carefully after
any SumbitChanges() operation.
</code></pre></li>
</ol>
<p>Considering that, I don't think using more than one DataContext would do any harm- in fact, creating different DataContexts for different types of work would help make your LinqToSql impelmentation more usuable and organized. The only downside is you wouldn't be able to use sqlmetal to auto-generate your dmbl. </p>
| <p>In my experience with LINQ to SQL and LINQ to Entities a DataContext is synonymous to a connection to the database. So if you were to use multiple data stores you would need to use multiple DataContexts. My gut reaction is you wouldn't notice to much of a slow down with a DataContext that encompasses a large number of tables. If you did however you could always split the database logically at points where you can isolate tables that don't have any relationship to other sets of tables and create multiple contexts.</p>
| 2,417 |
<p>I'm working with a support person who is supposed to be able to install SSL certs on a web server he maintains. He has local admin rights to the server via a domain security group. He also has permissions on our internal CA running Windows 2003 Server Certificate Authority: "Request cert" and "Issue and Manage certs".</p>
<p>The server he's working with is running Windows 2000 SP4 / IIS 5. When he attempts to create an online server cert the IIS wizard ends with "Failed to install. Access is Denied.". The event viewer is not working properly, so I can't find any details there. I suspect the permission issue is locally and not with the CA.</p>
<p>My account is a domain admin account and I know I am able to do this operation, however I need to make this work for others that are not domain admins.</p>
<p>Any ideas why he can't perform this operation?</p>
| <p>I had this exact same issue a few months ago when I was setting up a cert for a client.</p>
<p>There's a MachineKeys folder that the Administrator need rights -</p>
<pre><code>\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys
</code></pre>
<p>give <strong>Administrator</strong> (or the Administrator group) <strong>Full Control</strong> over this directory. I don't think you have to restart IIS, but it never hurts .</p>
<p>I have no idea why Admin doesn't control this as default.
Once this is changed, the Certificate Creation Wizard will successfully generate the certificate request.</p>
<p>I think there's even a Microsoft KB article about it somewhere.</p>
<p>EDIT: Here's the KB article : <a href="http://support.microsoft.com/kb/908572" rel="noreferrer">http://support.microsoft.com/kb/908572</a></p>
<p>-Jon</p>
| <p>If you're renewing a certificate, then it's possible that you imported your new intermediate certificate (.pb7) before removing your existing (expired) certificate from IIS. You would get an access denied error because both the old and new certificates are for the same domain.</p>
<p>So by the time you get this access denied error, there are three things you must do.</p>
<ol>
<li>Remove all certificates for this domain name from IIS, including the new one you just imported..</li>
<li>Go back to Console1, and remove the certificate for your domain name from Local Computer\Certificate Enrollment Requests\Certificates.</li>
<li>Start over.</li>
</ol>
| 9,067 |
<p>So I bought a Lulzbot Mini a couple months ago and finally downloaded Ultimaker's version of Cura... Boy... have I been missing out...</p>
<p>One feature Ultimaker Cura implemented that I've been looking for is a "pause at z-height" feature ("post-processing tool"). I'm building prototypes of an electronics device, and creating two pieces that snap together looks a lot worse than printing a single piece. If I could pause my print, insert my electronics, and continue printing, my device would look a lot more professional (even if it took longer to make).</p>
<p>My one concern is the lithium ion battery. Right now I'm printing in TPU. With a heated bed of 40 degrees Celsius, and a heated extruder at 240 degrees Celsius, there seems to be a significant risk that the lithium ion battery reaches a temperature above 60 degrees Celsius (damaging the cell, causing a potential explosion). Granted, I am not sure what "60 degrees Celsius" actually means. It could mean only one part of the packaging needs to reach this temperature, or it could mean the entire LiPo's internal temperature would need to reach this. In either case, the numbers don't look good.</p>
<p>On the other hand, the heated bed surely doesn't need to remain heated beyond the first few layers? Additionally, I can create a "roof" for the LiIon battery that I can slip it under, providing some insulative TPU before the rest of the device. I think the print would happen safely like this, but obviously, an explosion would be really really bad. Like it would probably burn my house down, and I would be asleep when it happened.</p>
<p><strong>Does anyone have any experience doing this?
Is there a way to turn off the heated bed mid-print? I guess I can insert a g-code line during the pause? Will this affect the remainder of the print you think?
Am I being paranoid? Can the extruder actually pass heat through a 1–2 mm of insulation and cause an explosion?
Anyone know how heat travels from the initial, liquid print material through the rest of the structure?</strong></p>
<p>Any more advice or things I should consider before pursuing this?</p>
<p>A more specific pause type might be helpful, if anyone knows of any.</p>
| <p>There is an option to directly insert extra commands at a specific Z height, no need to enter them manually.</p>
<p>That said, it is a bad idea to turn off the heated bed while printing, because this will often detach the object from the bed completely (that's kind of the point of having the heated bed in the first place: better adhesion while printing, and easier removal afterwards).</p>
<p>I wouldn't print over a battery to enclose it, not just because it is likely to damage the battery, but also to keep the battery exchangeable. Enclosing the rest of the design in a case is possible, but normally it is easier to print two separate parts that can be screwed together through a hole in the PCB.</p>
<p>So, experience: it's not worth it usually.</p>
| <p>Discharge the battery entirely, then there is no danger of ignition if the membrane breaks. The battery cells are usually protected by Kapton tape (LiPo) or maybe even metal (LiIon). Both will withstand the temperature of 240°C. The downside is that the cells are damaged after a deep discharge. You should discard the battery afterwards. </p>
<p><strong>What I would expect when you do that:</strong></p>
<p>A deeply discharged battery will bloat up because the solvents will gas out. This will also happen if you heat up the battery enough (>>60 degree). The gases themselves can be ignited again but are captured in our air sealed Kapton envelope :) Igniting these gases will be comparable to a short flash with a spray can. </p>
<p>The temperature is not enough to damage the envelope. The solvents will be also not very dangerous in that temperature range. In case of mechanical breakdown of the membrane nothing will happen anymore. </p>
<p>From <a href="https://www.sigmaaldrich.com/materials-science/material-science-products.html?TablePage=107476223" rel="nofollow noreferrer">Solvents and Additives</a>:</p>
<blockquote>
<p><a href="https://i.stack.imgur.com/HgIFF.png" rel="nofollow noreferrer" title="Solvents and Additives"><img src="https://i.stack.imgur.com/HgIFF.png" alt="Solvents and Additives" title="Solvents and Additives"></a></p>
</blockquote>
| 883 |
<p>I've been doing some HTML scraping in PHP using regular expressions. This works, but the result is finicky and fragile. Has anyone used any packages that provide a more robust solution? A config driven solution would be ideal, but I'm not picky.</p>
| <p>I would recomend <a href="https://sourceforge.net/projects/simplehtmldom/" rel="noreferrer">PHP Simple HTML DOM Parser</a> after you have scraped the HTML from the page. It supports invalid HTML, and provides a very easy way to handle HTML elements. </p>
| <p>I've had very good with results with the <a href="https://sourceforge.net/projects/simplehtmldom/" rel="nofollow noreferrer">Simple Html DOM Parser</a> mentioned above as well. And then there's the <a href="http://www.php.net/tidy" rel="nofollow noreferrer">tidy Extension for PHP</a> as well which works really well too.</p>
| 5,428 |
<p>I want to automate a Windows 2000+ server reboot process using Task Scheduler or similar tool to remotely reboot a server and wait for it to come back up. I can issue <code>shutdown</code> or <code>psshutdown</code> to remotely reboot, but I want something better than <code>sleep</code> to wait for it to come back. I need to verify it is back online within <code>n</code> minutes or throw an error.</p>
<p>By 'back online', I would like to verify more than just that it can be pinged, but perhaps its RFC service is responding or some other determinate vital sign.</p>
<p>I'd prefer an NT script approach, but I'm not ruling out writing a custom tool to do this.</p>
<p>Any ideas?</p>
| <p>Your remote restart script could start the server, wait n minutes, then query your RFC service. You could also have a local script on the server do the same thing.</p>
| <p>You can poll some core service to see if it has started:</p>
<pre><code>sc "\\server_name" query EventSystem
</code></pre>
| 8,062 |
<p>Does anyone know of a good way to convert a 3D print file, like STL, to STEP - a useable file format for plastic injection molding companies? </p>
<p>I have tried to convert the files through a couple of programs without success. The most requested file is a STP or STEP file. If there’s no easy way to convert it, which I don’t think there is, does anyone know someone good at re-creating CAD files?</p>
| <blockquote>
<p>a good way to convert a 3D print file like STL to STEP a useable file format for plastic injection molding companies</p>
</blockquote>
<p>I don't know much about plastic injection molding companies, but I do manipulate a lot STEP, STL files and I do know that it is possible to achieve <em>"a good way to convert […] STL to STEP file format […]"</em>. For the record, the manufacturing process isn't recorded within these files format (at least not yet) so you don't have to specify the final use.</p>
<p>However, this is a delicate process which isn't easy for beginners in CAD engineering.</p>
<p>As said before, the <a href="https://en.wikipedia.org/wiki/STL_(file_format)" rel="nofollow noreferrer">STL</a> files is a tessellation of a surface with triangles, while <a href="https://en.wikipedia.org/wiki/ISO_10303-21" rel="nofollow noreferrer">STEP</a> defines precisely the surface with curves. It's basically the difference between <a href="https://en.wikipedia.org/wiki/Raster_graphics" rel="nofollow noreferrer">raster graphics</a> and <a href="https://en.wikipedia.org/wiki/Vector_graphics" rel="nofollow noreferrer">vector graphics</a>: most fully automatic reconversions programs (such as Inkscape in case of images), would create something quite approximate to the real shape. Manual programs would require time and knowledge of the needed tools (Inkscape can do it too, in case of images). </p>
<p>For the record, asking for a STEP file to be a STL file is as easy as transforming a vector graphic to a raster graphic, it's a one-click transformation. What you are asking, the reversed, is complicated.</p>
<p>What will be done if you import a STL file to a standard CAD program, it will consider each triangle as a defined unique surface, and in most cases, the standard CAD program will have a lot of difficulties to handle the STL. It could then export it to a STEP file, but this will make a huge, incredibly heavy file difficult to handle (I've seen STEP files over 300 MB while the STL was less than 10 MB).</p>
<p>The <strong>good way</strong> to do so, is to go through a reverse engineering program that handles better these troubles. I don't know any being free, and they all require extensive experience, expansive licenses and a bunch of time generally. For instance, I know that <a href="https://www.youtube.com/watch?v=Se2GUfs_TI8" rel="nofollow noreferrer">Catia</a>, <a href="https://www.youtube.com/watch?v=E8RDOfXEh-o" rel="nofollow noreferrer">SpaceClaim</a> or <a href="https://www.youtube.com/watch?v=BT1vj4l155E" rel="nofollow noreferrer">3-Matic</a> are programs that work very well for your issue, but they are both very far from affordable or easy to handle if you aren't a CAD designer.</p>
<p>Another <strong>bad way</strong> would be to pass through a 100% automatic reconstruction/conversion to STEP, but it would make something not exactly accurate to the original part, and may not be of any use depending of your application.</p>
<p>My best advice for this would be to find someone or some enterprise that can practice the <strong>good way</strong> from your STL to have the STEP file you want. You should also very much specify for what use your file is, because as a design engineer I wouldn't generate the same STEP file depending of the use of each surface.</p>
<p>I hope this answer isn't too much a disappointment for you, I know it won't solve your problem but it can help you understand why it is such a hard problem.</p>
| <p>Converting mesh files to solid formats is a complex task.
While converting files from mesh to solid you should look for accuracy, number of patches, nurbs pattern, file size and many other variables that should be taken in consideration based on the use you will give for the solid file.
I have compiled some thoughts as a starting point for your research. Make sure your STL/OBJ/PLY (mesh) file has a decent quality. You can use free software to validate your file such as Meshmixer and MeshLab.
You will CONSIDERABLY increase your chances by having a watertight model. If the model does not have a closed mesh, you will most likely have a hard time/fail converting it.</p>
<p>There are 4 ways to do it:</p>
<p>1 – Using a free software
This is a valid solution for a simple shape models.
The best tutorials are posted here on GrabCAD.
Here are some tutorials available on internet:
<a href="https://grabcad.com/tutorials/how-do-i-convert-stl-graphics-to-a-solid-model" rel="nofollow noreferrer">https://grabcad.com/tutorials/how-do-i-convert-stl-graphics-to-a-solid-model</a>
Convert STL (or OBJ) Mesh to SOLIDWORKS Model (NURBS)
How to convert STL to STEP using FreeCAD
<a href="https://blog.bantamtools.com/convert-stl-to-step" rel="nofollow noreferrer">https://blog.bantamtools.com/convert-stl-to-step</a></p>
<p>2 - Professional software solution
This is probably the best solution for companies with a high conversion volume on CAD/CAM demand.
Some of these companies offer a free software version for students.
The best solutions I have found:
- 3D Systems Geomagic Wrap
- Fusion 360
- Power Surfacing (SolidWorks plugin)
- TransMagic</p>
<p>3 - Hiring a professional freelancer
This is the best option for a one-time project, higher chance to get a decent converted file for an affordable price. Try to look for the feedback/customer review before hiring someone.
I have seen professionals charging as cheap as US$25 per model/conversion.
You can check on these options (there are many others):
<a href="https://www.upwork.com" rel="nofollow noreferrer">https://www.upwork.com</a>
<a href="https://www.fiverr.com" rel="nofollow noreferrer">https://www.fiverr.com</a>
<a href="https://www.freelancer.com" rel="nofollow noreferrer">https://www.freelancer.com</a></p>
<p>4 - Online conversion platform
There are solutions with instant delivery/conversion, and others that take some hours to send you the file. I found solutions varying from free online conversion to pricy service.
There are prices as low as US$1 per model/conversion.
You may need to do some touch up on the files converted from automated platform before you send it to a CNC or other CAD/CAM machine.
You can check on these platforms:
<a href="http://cadmesh.com" rel="nofollow noreferrer">http://cadmesh.com</a>
<a href="https://www.convertcadfiles.com/" rel="nofollow noreferrer">https://www.convertcadfiles.com/</a></p>
<p>Have in mind that, the higher is the model complexity (shape) the harder is to convert the model.
If trying to convert a 3D scanned model, make sure to have a closed mesh and a high-density mesh definition.</p>
<p>During your Google research, you can also use the term “model surfacing”.</p>
<p>Good luck!</p>
| 833 |
<p>This question is slightly related to <a href="https://stackoverflow.com/questions/61354/how-to-get-entire-chain-of-exceptions-in-applicationthreadexception-event-handl">this question about exception handling</a>. The workaround I found there consists of rolling my own message loop.</p>
<p>So my Main method now looks basically like this:</p>
<pre><code>[STAThread]
static void Main() {
// this is needed so there'll actually an exception be thrown by
// Application.Run/Application.DoEvents, instead of the ThreadException
// event being raised.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form form = new MainForm();
form.Show();
// the loop is here to keep app running if non-fatal exception is caught.
do {
try {
Application.DoEvents();
Thread.Sleep(100);
}
catch (Exception ex) {
ExceptionHandler.ConsumeException(ex);
}
}
while (!form.IsDisposed);
}
</code></pre>
<p>What I'm wondering though, <strong>is this a safe/decent way to replace the more typical
'Application.Run(new MainForm());'</strong>, whether it's used for exception handling or for whatever else, or should I always stick to using Application.Run?</p>
<p>On another app that's in testing now a similar approach is used for both loading (splashscreen) and exception handling, and I don't think it has caused any troubles (yet :-))</p>
| <p>Pitfall 1: </p>
<pre><code>Thread.Sleep(100);
</code></pre>
<p>Never. Use WaitMessage().</p>
<p>Otherwise, it is possible roll out your own message loop, but in your scenario it seems somewhat pointless.</p>
<p>You may also want to examine Application.Run() code (with .Net Reflector, for instance).</p>
| <p>Yes... I think some components wont work with that code. Some of them require to live in a thread that has an Application.Run in it to effectively pick up their messages.</p>
| 8,655 |
<p>Do any of you know of a tool that will search for .class files and then display their compiled versions?</p>
<p>I know you can look at them individually in a hex editor but I have a lot of class files to look over (something in my giant application is compiling to Java6 for some reason).</p>
| <p>Use the <a href="http://java.sun.com/javase/6/docs/technotes/tools/solaris/javap.html" rel="noreferrer">javap</a> tool that comes with the JDK. The <code>-verbose</code> option will print the version number of the class file.</p>
<pre><code>> javap -verbose MyClass
Compiled from "MyClass.java"
public class MyClass
SourceFile: "MyClass.java"
minor version: 0
major version: 46
...
</code></pre>
<p>To only show the version:</p>
<pre><code>WINDOWS> javap -verbose MyClass | find "version"
LINUX > javap -verbose MyClass | grep version
</code></pre>
| <p>The simplest way is to scan a class file using many of the answers here which read the class file magic bytes.</p>
<p>However some code is packaged in jars or other archive formats like WAR and EAR, some of which contain other archives or class files, plus you now have multi-release JAR files - see <a href="https://openjdk.java.net/jeps/238" rel="nofollow noreferrer">JEP-238</a> which use different JDK compilers per JAR.</p>
<p>This program scans classes from a list of files + folders and prints summary of java class file versions for each component including each JAR within WAR/EARs:</p>
<pre><code>public static void main(String[] args) throws IOException {
var files = Arrays.stream(args).map(Path::of).collect(Collectors.toList());
ShowClassVersions v = new ShowClassVersions();
for (var f : files) {
v.scan(f);
}
v.print();
}
</code></pre>
<p>Example output from a scan:</p>
<pre><code>Version: 49.0 ~ JDK-5
C:\jars\junit-platform-console-standalone-1.7.1.jar
Version: 50.0 ~ JDK-6
C:\jars\junit-platform-console-standalone-1.7.1.jar
Version: 52.0 ~ JDK-8
C:\java\apache-tomcat-10.0.12\lib\catalina.jar
C:\jars\junit-platform-console-standalone-1.7.1.jar
Version: 53.0 ~ JDK-9
C:\java\apache-tomcat-10.0.12\lib\catalina.jar
C:\jars\junit-platform-console-standalone-1.7.1.jar
</code></pre>
<p>The scanner:</p>
<pre><code>public class ShowClassVersions {
private TreeMap<String, ArrayList<String>> vers = new TreeMap<>();
private static final byte[] CLASS_MAGIC = new byte[] { (byte) 0xca, (byte) 0xfe, (byte) 0xba, (byte) 0xbe };
private final byte[] bytes = new byte[8];
private String versionOfClass(InputStream in) throws IOException {
int c = in.readNBytes(bytes, 0, bytes.length);
if (c == bytes.length && Arrays.mismatch(bytes, CLASS_MAGIC) == CLASS_MAGIC.length) {
int minorVersion = (bytes[4] << 8) + (bytes[4] << 0);
int majorVersion = (bytes[6] << 8) + (bytes[7] << 0);
return ""+ majorVersion + "." + minorVersion;
}
return "Unknown";
}
private Matcher classes = Pattern.compile("\\.(class|ear|war|jar)$").matcher("");
// This code scans any path (dir or file):
public void scan(Path f) throws IOException {
try (var stream = Files.find(f, Integer.MAX_VALUE,
(p, a) -> a.isRegularFile() && classes.reset(p.toString()).find())) {
stream.forEach(this::scanFile);
}
}
private void scanFile(Path f) {
String fn = f.getFileName().toString();
try {
if (fn.endsWith(".ear") || fn.endsWith(".war") || fn.endsWith(".jar"))
scanArchive(f);
else if (fn.endsWith(".class"))
store(f.toAbsolutePath().toString(), versionOfClass(f));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private void scanArchive(Path p) throws IOException {
try (InputStream in = Files.newInputStream(p)) {
scanArchive(p.toAbsolutePath().toString(), Files.newInputStream(p));
}
}
private void scanArchive(String desc, InputStream in) throws IOException {
HashSet<String> versions = new HashSet<>();
ZipInputStream zip = new ZipInputStream(in);
for (ZipEntry entry = null; (entry = zip.getNextEntry()) != null; ) {
String name = entry.getName();
// There could be different compiler versions per class in one jar
if (name.endsWith(".class")) {
versions.add(versionOfClass(zip));
} else if (name.endsWith(".jar") || name.endsWith(".war")) {
scanArchive(desc + " => " + name, zip);
}
}
if (versions.size() > 1)
System.out.println("Warn: "+desc+" contains multiple versions: "+versions);
for (String version : versions)
store(desc, version);
}
private String versionOfClass(Path p) throws IOException {
try (InputStream in = Files.newInputStream(p)) {
return versionOfClass(in);
}
}
private void store(String path, String jdkVer) {
vers.computeIfAbsent(jdkVer, k -> new ArrayList<>()).add(path);
}
// Could add a mapping table for JDK names, this guesses based on (JDK17 = 61.0)
public void print() {
for (var ver : vers.keySet()) {
System.out.println("Version: " + ver + " ~ " +jdkOf(ver));
for (var p : vers.get(ver)) {
System.out.println(" " + p);
}
}
}
private static String jdkOf(String ver) {
try {
return "JDK-"+((int)Float.parseFloat(ver)-44);
}
catch(NumberFormatException nfe)
{
return "JDK-??";
}
}
}
</code></pre>
| 4,671 |
<p>I have a Tronxy X3 (i3 Clone) running Repetier firmware on a Melzi board.</p>
<p>I would like to share the printer over my home network so that:</p>
<ol>
<li>Both my boys and I can use the printer. (We have separate Windows 10 PCs)</li>
<li>I can initiate a print from my computer upstairs</li>
<li>I can monitor the print progress remotely</li>
</ol>
<p>I have (and could use)</p>
<ul>
<li>A RAMPS board set that I could use to run Marlin.</li>
<li>A Raspberrry Pi 1B </li>
<li>An idle laptop I (might) be willing to use</li>
</ul>
<p>What I want to know:</p>
<ul>
<li>Are you sharing your printer on a network, and if so, how long</li>
<li>What Hardware and Software are you using</li>
<li>What do you like most</li>
<li>What do you find most annoying</li>
<li>What do you want to change</li>
<li>What is the interface (web interface, print driver, etc.)</li>
<li>What services are provided (printing, slicing, monitoring, etc.)</li>
<li>Can two computers access it at the same time
Ex: To monitor, or still print if my sons forgot to disconnect</li>
<li>What sort of monitoring is supported? Ex: camera?</li>
<li>What runs the print job (G-code)</li>
</ul>
| <p><strong>NOTE</strong>: This is not from personal experience, but I thought it was worth mentioning:</p>
<h3>Microsoft</h3>
<p>You've probably seen this already - I am not a fan at all of M$, but... <a href="https://all3dp.com/microsoft-network-3d-printer/" rel="nofollow noreferrer">Microsoft Plus Raspberry Pi Equals Network 3D Printer</a>.</p>
<p>Here is another link to the same, <a href="https://developer.microsoft.com/en-us/windows/iot/docs/3dprintserver" rel="nofollow noreferrer">Network 3D Printer with Windows 10 IoT Core</a>, but, unfortunately, your printer is apparently <em>not</em> supported.</p>
<h3>OctoPi</h3>
<p>However, closed source M$ seem to be playing catch up, whilst the Open Source <a href="https://octopi.octoprint.org/" rel="nofollow noreferrer">OctoPi</a> has been about for a while, indeed there have been a <a href="https://3dprinting.stackexchange.com/search?q=octopi">few questions on SE 3D Printing</a> about it. From the blurb:</p>
<blockquote>
<p>OctoPi is a <a href="http://www.raspberrypi.org/" rel="nofollow noreferrer">Raspberry Pi</a> distribution for 3d printers. Out of the box it includes:</p>
<ul>
<li><p>the <a href="http://octoprint.org/" rel="nofollow noreferrer">OctoPrint</a> host software including all its dependencies and preconfigured with webcam and slicing support,</p>
</li>
<li><p><a href="https://github.com/jacksonliam/mjpg-streamer" rel="nofollow noreferrer">mjpg-streamer</a> for live viewing of prints and timelapse video creation with support for USB webcams and the Raspberry Pi camera and</p>
</li>
<li><p><a href="https://github.com/Ultimaker/CuraEngine" rel="nofollow noreferrer">CuraEngine 15.04</a> for direct slicing on your Raspberry Pi.</p>
</li>
</ul>
</blockquote>
<p>See <a href="https://makerhacks.com/octoprint-raspberrypi-3dprinter/" rel="nofollow noreferrer">How to Install and Set Up Octopi for Remote Raspberry Pi 3D Printer Control with Octoprint</a>.</p>
<p>A few of its features:</p>
<ul>
<li>It also supports monitoring via a camera.</li>
<li>The G-code is sent over the serial to the printer.</li>
<li>You can use OctoPi to control multiple printers as well, as it isn't particularly resource intensive, see <a href="http://blog.patshead.com/2016/02/control-multiple-3d-printers-using-a-single-raspberry-pi-with-octoprint.html" rel="nofollow noreferrer">Control Multiple 3D Printers Using A Single Raspberry Pi and Octoprint</a>].</li>
<li>You can <a href="https://github.com/foosel/OctoPrint/wiki/Configuring-Access-Control" rel="nofollow noreferrer">configure access control</a> for multiple users, or for a better presented version, see <a href="http://docs.octoprint.org/en/master/features/accesscontrol.html" rel="nofollow noreferrer">Access control</a>.</li>
</ul>
<hr />
<p>As an aside, you could put Pronterface on the Pi too: <a href="http://www.instructables.com/id/How-to-Control-a-3D-Printer-Via-Raspbery-Pi2/" rel="nofollow noreferrer">How to Install Pronterface on Raspberry Pi - Instructables</a>. I wasn't aware of this.</p>
| <p>You can use Windows IoT Core to do it, see -<br>
<a href="https://developer.microsoft.com/en-us/windows/iot/docs/3dprintserver" rel="nofollow noreferrer">https://developer.microsoft.com/en-us/windows/iot/docs/3dprintserver</a></p>
| 623 |
<p>I am having an issue where several prints I downloaded from thingiverse causing my printer to freeze in the first minute of the print. The print head stops, pushes out a small amount of PLA and then does nothing. The control board continues to show the print progress bar continuing.</p>
<p>One thing that could be possible is I am using the wrong G-code flavor. I am running Cura 3.4.1 and I set the printer to use RepRap. I also tried Marlin. Which one of those is right for my printer? Could it be something else?</p>
<p>My MonoPrice printer firmware version is v35.110.2. The item I tried to print has the gcode from this page. <a href="https://www.thingiverse.com/thing:2221657" rel="nofollow noreferrer">https://www.thingiverse.com/thing:2221657</a>.</p>
| <p>If you go to the Monoprice website you will find a dedicated page for <a href="https://www.mpselectmini.com/slicers/cura" rel="nofollow noreferrer">Ultimaker Cura</a>. </p>
<p>From the page you can read that:</p>
<blockquote>
<p>Cura now includes profiles for the MP Select Mini V1 and V2. Go to
“Settings”, “Printer”, “Add Printer…”, “Other”. Select the radio
button next to the printer, then “Add Printer”.</p>
</blockquote>
<p>So you must be able to configure it correctly for your printer (this must include the G-code flavor for your printer). Do note that Monoprice does nothing with the Ultimaker Cura installers, they simply link directly to the source at Ultimaker. Also note all the problems related to specific versions and how to fix them.</p>
<p>You write that the:</p>
<blockquote>
<p>The control board continues to show the print progress bar continuing.</p>
</blockquote>
<p>This I have experiences myself (on a different printer with Marlin 1.1.8), so a non-printing printer while the progressbar progresses. I solved this myself by flashing to a newer firmware version. It appears to be a <a href="https://github.com/MarlinFirmware/Marlin/issues/9636" rel="nofollow noreferrer">bug in the firmware</a>.</p>
<p>You might want to explore whether it is feasible for you to update, I read that there are issues with this printer concerning firmware updating (it appears that there are different hardware versions of this printer).</p>
<p>E.g. <a href="https://www.thingiverse.com/groups/monoprice-select-mini-owners/forums/general/topic:19510" rel="nofollow noreferrer">from this reference</a>:</p>
<blockquote>
<ul>
<li>If your MPSM V2 currently has Motion Controller v34 or higher
installed then you can update with this firmware. </li>
<li>If your MPSM V2 currently has Motion Controller v30 or lower, do NOT update with this firmware. </li>
<li>If you have Motion Controller versions 31, 32, or 33 please
ask before updating with this firmware.</li>
</ul>
</blockquote>
<p>Although the changelog does not mention your problems, you may benefit from a firmware update. Please do this at your own risk, take precautions and read in the matter if your printer is able to be updated. It is best to first look into your settings how the printer is configured in Ultimaker Cura. Preferably, delete the current printer configuration and add a new configuration as described <a href="https://www.mpselectmini.com/slicers/cura" rel="nofollow noreferrer">here</a>.</p>
| <p>The source of the files (thingiverse) is irrelevant -- what matters is what the slicing software creates for gcode. Since you're using Cura,go to <a href="https://www.mpselectmini.com/slicers/cura" rel="nofollow noreferrer">monoprice</a> for their advice.</p>
<p>There are a number of Cura + monoprice instructional vids on youtube as well.</p>
<p>not to mention several reddit channels. </p>
| 1,112 |
<p>What is the syntax for placing constraints on multiple types? The basic example:</p>
<pre><code>class Animal<SpeciesType> where SpeciesType : Species
</code></pre>
<p>I would like to place constraints on both types in the following definition such that <code>SpeciesType</code> must inherit from <code>Species</code> and <code>OrderType</code> must inherit from <code>Order</code>:</p>
<pre><code>class Animal<SpeciesType, OrderType>
</code></pre>
| <pre><code>public class Animal<SpeciesType,OrderType>
where SpeciesType : Species
where OrderType : Order
{
}
</code></pre>
| <p>You should be able to go :</p>
<pre><code>class Animal<SpeciesType, OrderType>
where SpeciesType : Species
where OrderType : Order {
}
</code></pre>
| 6,849 |
<p>I need to design a small project for generating excel reports in .NET, which will be sent to users to use.</p>
<p>The excel reports will contain PivotTables.</p>
<p>I don't have much experience with them, but I can think of three implementation alternatives:</p>
<ol>
<li>Set a query for it, populate it, send it disconnected. This way the user will be able to group values and play a little, but he will not be able to refresh the data.</li>
<li>Generate a small access database and send it along with the excel file, connect to it.</li>
<li>Copy the data to the excel (perhaps in some other sheet) and connect to the data there. This will make the excel file very large I think.</li>
</ol>
<p>What would be the best alternative in regards to performance vs usability? Is there another alternative I don't know about?</p>
| <p><strong>PHP sample</strong>:</p>
<pre><code>$string = "A man, a plan, a canal, Panama";
function is_palindrome($string)
{
$a = strtolower(preg_replace("/[^A-Za-z0-9]/","",$string));
return $a==strrev($a);
}
</code></pre>
<p>Removes any non-alphanumeric characters (spaces, commas, exclamation points, etc.) to allow for full sentences as above, as well as simple words.</p>
| <p>Another one from Delphi, which I think is a little more rigorous than the other Delphi example submitted. This can easily turn into a golfing match, but I've tried to make mine readable.</p>
<p><em>Edit0: I was curious about the performance characteristics, so I did a little test. On my machine, I ran this function against a 60 character string 50 million times, and it took 5 seconds.</em></p>
<pre><code>function TForm1.IsPalindrome(txt: string): boolean;
var
i, halfway, len : integer;
begin
Result := True;
len := Length(txt);
{
special cases:
an empty string is *never* a palindrome
a 1-character string is *always* a palindrome
}
case len of
0 : Result := False;
1 : Result := True;
else begin
halfway := Round((len/2) - (1/2)); //if odd, round down to get 1/2way pt
//scan half of our string, make sure it is mirrored on the other half
for i := 1 to halfway do begin
if txt[i] <> txt[len-(i-1)] then begin
Result := False;
Break;
end; //if we found a non-mirrored character
end; //for 1st half of string
end; //else not a special case
end; //case
end;
</code></pre>
<p>And here is the same thing, in C#, except that I've left it with multiple exit points, which I don't like.</p>
<pre><code>private bool IsPalindrome(string txt) {
int len = txt.Length;
/*
Special cases:
An empty string is *never* a palindrome
A 1-character string is *always* a palindrome
*/
switch (len) {
case 0: return false;
case 1: return true;
} //switch
int halfway = (len / 2);
//scan half of our string, make sure it is mirrored on the other half
for (int i = 0; i < halfway; ++i) {
if (txt.Substring(i,1) != txt.Substring(len - i - 1,1)) {
return false;
} //if
} //for
return true;
}
</code></pre>
| 7,524 |
<p>I just wonder what the best approach is to have multiple users work on a Project in Visual Studio 2005 Professional.</p>
<p>We got a Solution with multiple Class Libraries, but when everyone opens the solution, we keep getting the "X was modified, Reload/Discard?" prompt all the time. Just opening one project is an obvious alternative, but I find it harder to use as you can't just see some of the other classes in other projects that way.</p>
<p>Are there any Guidelines for Team Development with VS2005 Pro?</p>
<p>Edit: Thanks. The current environment is a bit limited in the sense there is only 1 PC with RDP Connection, but that will change in the future. Marking the first answer as Accepted, but they are all good :)</p>
| <p>Use source control to keep a central repository of all your code. Then each user checks out their own copy of the source code and works locally. Then submits only the code that changed.</p>
<p><a href="https://en.wikipedia.org/wiki/Version_control" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Version_control</a></p>
| <p>This might sound snide, but if you're opening up the solution from a shared location then you're doing something wrong. If that's the case then you should start using source control (something like Subversion) and have everyone check out a copy of the project to work on. </p>
<p>However if you're already using source control, then it might be a symptom of having the wrong things checked in. I find that you only need the sln, and the vcproj under source control.</p>
<p>Otherwise I don't know...</p>
| 6,262 |
<p>I've got a whole directory of dll's I need to register to the GAC. I'd like to avoid registering each file explicitly- but it appears that gacutil has no "register directory" option. Anyone have a fast/simple solution?</p>
| <p>GACUTIL doesn't register DLLs -- not in the "COM" sense. Unlike in COM, GACUTIL copies the file to an opaque directory under %SYSTEMROOT%\assembly and that's where they run from. It wouldn't make sense to ask GACUTIL "register a folder" (not that you can do that with RegSvr32 either).</p>
<p>You can use a batch FOR command such as:</p>
<pre><code>FOR %a IN (C:\MyFolderWithAssemblies\*.dll) DO GACUTIL /i %a
</code></pre>
<p>If you place that in a batch file, you must replace %a with %%a</p>
| <p>Use </p>
<blockquote>
<p>gacutil /il YourPathTo_A_TextFile.txt</p>
</blockquote>
<p>switch, if you have dlls in multiple different folders. Otherwise go with the <code>for ... in</code> loop mentioned by Euro.</p>
<p>The text file should contain a list of assembly paths (one path per line) which should be installed. The paths can also be different folders all over the system.
Run the command line as an administrator!</p>
<p><strong>Here an example of the YourPathTo_A_TextFile.txt:</strong></p>
<blockquote>
<p>C:\...Microsoft.Practices.EnterpriseLibrary.Common.dll
C:\...Microsoft.Practices.EnterpriseLibrary.Configuration.Design.HostAdapter.dll
C:\...Microsoft.Practices.EnterpriseLibrary.Configuration.Design.HostAdapterV5.dll
C:\...Microsoft.Practices.EnterpriseLibrary.Configuration.DesignTime.dll
C:\...Microsoft.Practices.EnterpriseLibrary.Configuration.EnvironmentalOverrides.dll
C:\...Microsoft.Practices.EnterpriseLibrary.Data.dll</p>
</blockquote>
| 5,544 |
<p>Does anyone know a way to auto-generate database tables for a given class? I'm not looking for an entire persistence layer - I already have a data access solution I'm using, but I suddenly have to store a lot of information from a large number of classes and I really don't want to have to create all these tables by hand. For example, given the following class:</p>
<pre><code>class Foo
{
private string property1;
public string Property1
{
get { return property1; }
set { property1 = value; }
}
private int property2;
public int Property2
{
get { return property2; }
set { property2 = value; }
}
}
</code></pre>
<p>I'd expect the following SQL:</p>
<pre><code>CREATE TABLE Foo
(
Property1 VARCHAR(500),
Property2 INT
)
</code></pre>
<p>I'm also wondering how you could handle complex types. For example, in the previously cited class, if we changed that to be :</p>
<pre><code>class Foo
{
private string property1;
public string Property1
{
get { return property1; }
set { property1 = value; }
}
private System.Management.ManagementObject property2;
public System.Management.ManagementObject Property2
{
get { return property2; }
set { property2 = value; }
}
}
</code></pre>
<p></p>
<p>How could I handle this?</p>
<p>I've looked at trying to auto-generate the database scripts by myself using reflection to enumerate through each class' properties, but it's clunky and the complex data types have me stumped.</p>
| <p>It's really late, and I only spent about 10 minutes on this, so its extremely sloppy, however it does work and will give you a good jumping off point:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace TableGenerator
{
class Program
{
static void Main(string[] args)
{
List<TableClass> tables = new List<TableClass>();
// Pass assembly name via argument
Assembly a = Assembly.LoadFile(args[0]);
Type[] types = a.GetTypes();
// Get Types in the assembly.
foreach (Type t in types)
{
TableClass tc = new TableClass(t);
tables.Add(tc);
}
// Create SQL for each table
foreach (TableClass table in tables)
{
Console.WriteLine(table.CreateTableScript());
Console.WriteLine();
}
// Total Hacked way to find FK relationships! Too lazy to fix right now
foreach (TableClass table in tables)
{
foreach (KeyValuePair<String, Type> field in table.Fields)
{
foreach (TableClass t2 in tables)
{
if (field.Value.Name == t2.ClassName)
{
// We have a FK Relationship!
Console.WriteLine("GO");
Console.WriteLine("ALTER TABLE " + table.ClassName + " WITH NOCHECK");
Console.WriteLine("ADD CONSTRAINT FK_" + field.Key + " FOREIGN KEY (" + field.Key + ") REFERENCES " + t2.ClassName + "(ID)");
Console.WriteLine("GO");
}
}
}
}
}
}
public class TableClass
{
private List<KeyValuePair<String, Type>> _fieldInfo = new List<KeyValuePair<String, Type>>();
private string _className = String.Empty;
private Dictionary<Type, String> dataMapper
{
get
{
// Add the rest of your CLR Types to SQL Types mapping here
Dictionary<Type, String> dataMapper = new Dictionary<Type, string>();
dataMapper.Add(typeof(int), "BIGINT");
dataMapper.Add(typeof(string), "NVARCHAR(500)");
dataMapper.Add(typeof(bool), "BIT");
dataMapper.Add(typeof(DateTime), "DATETIME");
dataMapper.Add(typeof(float), "FLOAT");
dataMapper.Add(typeof(decimal), "DECIMAL(18,0)");
dataMapper.Add(typeof(Guid), "UNIQUEIDENTIFIER");
return dataMapper;
}
}
public List<KeyValuePair<String, Type>> Fields
{
get { return this._fieldInfo; }
set { this._fieldInfo = value; }
}
public string ClassName
{
get { return this._className; }
set { this._className = value; }
}
public TableClass(Type t)
{
this._className = t.Name;
foreach (PropertyInfo p in t.GetProperties())
{
KeyValuePair<String, Type> field = new KeyValuePair<String, Type>(p.Name, p.PropertyType);
this.Fields.Add(field);
}
}
public string CreateTableScript()
{
System.Text.StringBuilder script = new StringBuilder();
script.AppendLine("CREATE TABLE " + this.ClassName);
script.AppendLine("(");
script.AppendLine("\t ID BIGINT,");
for (int i = 0; i < this.Fields.Count; i++)
{
KeyValuePair<String, Type> field = this.Fields[i];
if (dataMapper.ContainsKey(field.Value))
{
script.Append("\t " + field.Key + " " + dataMapper[field.Value]);
}
else
{
// Complex Type?
script.Append("\t " + field.Key + " BIGINT");
}
if (i != this.Fields.Count - 1)
{
script.Append(",");
}
script.Append(Environment.NewLine);
}
script.AppendLine(")");
return script.ToString();
}
}
}
</code></pre>
<p>I put these classes in an assembly to test it:</p>
<pre><code>public class FakeDataClass
{
public int AnInt
{
get;
set;
}
public string AString
{
get;
set;
}
public float AFloat
{
get;
set;
}
public FKClass AFKReference
{
get;
set;
}
}
public class FKClass
{
public int AFKInt
{
get;
set;
}
}
</code></pre>
<p>And it generated the following SQL:</p>
<pre><code>CREATE TABLE FakeDataClass
(
ID BIGINT,
AnInt BIGINT,
AString NVARCHAR(255),
AFloat FLOAT,
AFKReference BIGINT
)
CREATE TABLE FKClass
(
ID BIGINT,
AFKInt BIGINT
)
GO
ALTER TABLE FakeDataClass WITH NOCHECK
ADD CONSTRAINT FK_AFKReference FOREIGN KEY (AFKReference) REFERENCES FKClass(ID)
GO
</code></pre>
<p>Some further thoughts...I'd consider adding an attribute such as [SqlTable] to your classes, that way it only generates tables for the classes you want. Also, this can be cleaned up a ton, bugs fixed, optimized (the FK Checker is a joke) etc etc...Just to get you started.</p>
| <p>Try DaoliteMappingTool for .net. It can help you generate the classes.
Download form <a href="http://www.idevlite.com/download/daolitemappingtool(net).zip" rel="nofollow noreferrer">Here</a></p>
| 6,946 |
<p>What is the best way to go about upgrading TFS 2005 to 2008? Also, what about the Team Build scripts ("Build Types"), are those compatible with Team Build 2008 or do they need converted/migrated somehow?</p>
| <p>First and foremost - backup everything! The databases, the machine itself... You can never be too careful.</p>
<p>I was able to upgrade the TFS installation at my company by using these resources:</p>
<p><a href="http://olausson.net/blog/CommentView,guid,6f97b619-a5ac-41af-a908-f099d49a3b16.aspx" rel="nofollow noreferrer">http://olausson.net/blog/CommentView,guid,6f97b619-a5ac-41af-a908-f099d49a3b16.aspx</a>
<a href="http://blogs.msdn.com/sudhir/archive/2007/05/31/upgrade-2005-with-wss2-0-to-orcas-wss3-0.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/sudhir/archive/2007/05/31/upgrade-2005-with-wss2-0-to-orcas-wss3-0.aspx</a>
<a href="http://weblogs.asp.net/dmckinstry/archive/2007/08/27/considerations-on-using-tfs-2008-with-visual-studio-2005.aspx" rel="nofollow noreferrer">http://weblogs.asp.net/dmckinstry/archive/2007/08/27/considerations-on-using-tfs-2008-with-visual-studio-2005.aspx</a></p>
<p>It's not that hard and can in fact be done in a couple of hours, with better luck.</p>
| <p>Simply, follow the guidance in the Install document for TFS 2008 - It has an upgrade section. It talks about backing up databases and so on already. The instructions are clear and layed out well. </p>
| 6,084 |
<p>I am not concerned about other kinds of attacks. Just want to know whether HTML Encode can prevent all kinds of XSS attacks.</p>
<p>Is there some way to do an XSS attack even if HTML Encode is used?</p>
| <p>No.</p>
<p>Putting aside the subject of allowing some tags (not really the point of the question), HtmlEncode simply does NOT cover all XSS attacks.</p>
<p>For instance, consider server-generated client-side javascript - the server dynamically outputs htmlencoded values directly into the client-side javascript, htmlencode will <strong>not stop</strong> injected script from executing.</p>
<p>Next, consider the following pseudocode:</p>
<pre><code><input value=<%= HtmlEncode(somevar) %> id=textbox>
</code></pre>
<p>Now, in case its not immediately obvious, if somevar (sent by the user, of course) is set for example to</p>
<pre><code>a onclick=alert(document.cookie)
</code></pre>
<p>the resulting output is</p>
<pre><code><input value=a onclick=alert(document.cookie) id=textbox>
</code></pre>
<p>which would clearly work. Obviously, this can be (almost) any other script... and HtmlEncode would not help much.</p>
<p>There are a few additional vectors to be considered... including the third flavor of XSS, called DOM-based XSS (wherein the malicious script is generated dynamically on the client, e.g. based on # values).</p>
<p>Also don't forget about UTF-7 type attacks - where the attack looks like </p>
<pre><code>+ADw-script+AD4-alert(document.cookie)+ADw-/script+AD4-
</code></pre>
<p>Nothing much to encode there...</p>
<p>The solution, of course (in addition to proper and restrictive white-list input validation), is to perform <strong>context-sensitive</strong> encoding: HtmlEncoding is great IF you're output context IS HTML, or maybe you need JavaScriptEncoding, or VBScriptEncoding, or AttributeValueEncoding, or... etc.</p>
<p>If you're using MS ASP.NET, you can use their Anti-XSS Library, which provides all of the necessary context-encoding methods.</p>
<p>Note that all encoding should not be restricted to user input, but also stored values from the database, text files, etc.</p>
<p>Oh, and don't forget to explicitly set the charset, both in the HTTP header AND the META tag, otherwise you'll still have UTF-7 vulnerabilities...</p>
<p>Some more information, and a pretty definitive list (constantly updated), check out RSnake's Cheat Sheet: <a href="http://ha.ckers.org/xss.html" rel="noreferrer">http://ha.ckers.org/xss.html</a></p>
| <p>I don't believe so. Html Encode converts all functional characters (characters which could be interpreted by the browser as code) in to entity references which cannot be parsed by the browser and thus, cannot be executed.</p>
<pre><code>&lt;script/&gt;
</code></pre>
<p>There is no way that the above can be executed by the browser.</p>
<p>**Unless their is a bug in the browser ofcourse.*</p>
| 7,727 |
<p>I'm trying to find a simple way to change the colour of the text and background in <code>listview</code> and <code>treeview</code> controls in WTL or plain Win32 code.</p>
<p>I really don't want to have to implement full owner drawing for these controls, simply change the colours used.</p>
<p>I want to make sure that the images are still drawn with proper transparency.</p>
<p>Any suggestions?</p>
| <p>Have a look at the following macros:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/bb775063%28VS.85%29.aspx" rel="nofollow noreferrer">ListView_SetBkColor</a><br>
<a href="http://msdn.microsoft.com/en-us/library/bb775116%28VS.85%29.aspx>" rel="nofollow noreferrer">ListView_SetTextColor</a> </p>
<p><a href="http://msdn.microsoft.com/en-us/library/bb760036%28VS.85%29.aspx" rel="nofollow noreferrer">TreeView_SetBkColor</a><br>
<a href="http://msdn.microsoft.com/en-us/library/bb760131%28VS.85%29.aspx" rel="nofollow noreferrer">TreeView_SetTextColor</a></p>
| <p>It's been a while since I've use the win32 API directly, but I believe that if you handle the WM_ERASEBACKGROUND message for your control, you can use FillRect() in your handler to paint the background using whatever color you like.</p>
| 6,742 |
<p>I'm working on a website that will switch to a new style on a set date. The site's built-in semantic HTML and CSS, so the change should just require a CSS reference change. I'm working with a designer who will need to be able to see how it's looking, as well as a client who will need to be able to review content updates in the current look as well as design progress on the new look.</p>
<p>I'm planning to use a magic querystring value and/or a javascript link in the footer which writes out a cookie to select the new CSS page. We're working in ASP.NET 3.5. Any recommendations?</p>
<p>I should mention that we're using IE Conditional Comments for IE8, 7, and 6 support. I may create a function that does a replacement:</p>
<pre><code><link href="Style/<% GetCssRoot() %>.css" rel="stylesheet" type="text/css" />
<!--[if lte IE 8]>
<link type="text/css" href="Style/<% GetCssRoot() %>-ie8.css" rel="stylesheet" />
<![endif]-->
<!--[if lte IE 7]>
<link type="text/css" href="Style/<% GetCssRoot() %>-ie7.css" rel="stylesheet" />
<![endif]-->
<!--[if lte IE 6]>
<link type="text/css" href="Style/<% GetCssRoot() %>-ie6.css" rel="stylesheet" />
<![endif]-->
</code></pre>
| <p>In Asp.net 3.5, you should be able to set up the Link tag in the header as a server tag. Then in the codebehind you can set the href property for the link element, based on a cookie value, querystring, date, etc.</p>
<p>In your aspx file:</p>
<pre><code><head>
<link id="linkStyles" rel="stylesheet" type="text/css" runat="server" />
</head>
</code></pre>
<p>And in the Code behind:</p>
<pre><code>protected void Page_Load(object sender, EventArgs e) {
string stylesheetAddress = // logic to determine stylesheet
linkStyles.Href = stylesheetAddress;
}
</code></pre>
| <p>I would do the following:</p>
<p><a href="http://www.website.com/?stylesheet=new.css" rel="nofollow noreferrer">www.website.com/?stylesheet=new.css</a></p>
<p>Then in your ASP.NET code:</p>
<pre><code>if (Request.Querystring["stylesheet"] != null) {
Response.Cookies["stylesheet"].Value = Request.QueryString["stylesheet"];
Response.Redirect(<Current Page>);
}
</code></pre>
<p>Then where you define your stylesheets:</p>
<pre><code>if (Request.Cookies["stylesheet"] != null) {
// New Stylesheet
} else {
// Default
}
</code></pre>
| 2,710 |