instruction
stringlengths
27
22.5k
chosen
stringlengths
27
28.2k
rejected
stringlengths
19
24.9k
__index_level_0__
int64
0
10k
<p>My company has developed a long standing product using MFC in Visual C++ as the defacto standard for UI development. Our codebase contains ALOT of legacy/archaic code which must be kept operational. Some of this code is older than me (originally written in the late 70s) and some members of our team are still on Visual Studio 6.</p> <p>However, a conclusion has thankfully been reached internally that our product is looking somewhat antiquated compared to our competitors', and that something needs to be done.</p> <p>I am currently working on a new area of the UI which is quite separate from the rest of the product. I have therefore been given the chance to try out 'new' technology stacks as a sort of proving ground before the long process of moving over the rest of the UI begins.</p> <p>I have been using C# with Windows Forms and the .net framework for a while in my spare time and enjoy it, but am somewhat worried about the headaches caused by interop. While this particular branch of the UI won't require much interop with the legacy C++ codebase, I can forsee this becoming an issue in the future.</p> <p>The alternative is just to continue with MFC, but try and take advantage of the new feature pack that shipped with VS2008. This I guess is the easiest option, but I worry about longevity and not taking advantage of the goodness that is .net...</p> <p>So, which do I pick? We're a small team so my recommendation will quite probably be accepted as a future direction for our development - I want to get it right.</p> <p>Is MFC dead? Is C#/Winforms the way forward? Is there anything else I'm totally missing? Help greatly appreciated!</p>
<p>I'm a developer on an app that has a ton of legacy MFC code, and we have all of your same concerns. A big driver for our strategy was to eliminate as much risk and uncertainty as we could, which meant avoiding The Big Rewrite. As we all know, TBR fails most of the time. So we chose an incremental approach that allows us to preserve modules that won't be changing in the current release, writing new features managed, andporting features that are getting enhancements to managed.</p> <p>You can do this several ways:</p> <ol> <li><p>Host WPF content on your MFC views (see <a href="http://www.codeguru.com/cpp/cpp/cpp_managed/interop/article.php/c14589" rel="nofollow noreferrer">here</a>)</p></li> <li><p>For MFC MDI apps, create a new WinForms framework and host your MFC MDI views (see <a href="http://www.codeproject.com/KB/miscctrl/HostMFC.aspx" rel="nofollow noreferrer">here</a>)</p></li> <li><p>Host WinForms user controls in MFC Dialogs and Views (see <a href="http://msdn.microsoft.com/en-us/library/ahdd1h97.aspx" rel="nofollow noreferrer">here</a>)</p></li> </ol> <p>The problem with adopting WPF (option 1) is that it will require you to rewrite all of your UI at once, otherwise it'll look pretty schizophrenic.</p> <p>The second approach looks viable but very complicated.</p> <p>The third approach is the one we selected and it's been working very well. It allows you to selectively refresh areas of your app while maintaining overall consistency and not touching things that aren't broken.</p> <p>The Visual C++ 2008 Feature Pack looks interesting, I haven't played with it though. Seems like it might help with your issue of outdated look. If the "ribbon" would be too jarring for your users you could look at third-party MFC and/or WinForms control vendors.</p> <p>My overall recommendation is that interop + incremental change is definitely preferable to sweeping changes.</p> <hr> <p>After reading your follow-up, I can definitely confirm that the productivity gains of the framework vastly outweigh the investment in learning it. Nobody on our team had used C# at the start of this effort and now we all prefer it.</p>
<p>I concur with the WPF sentiment. Tag/XML based UI would seem to be a bit more portable than WinForms.</p> <p>I guess too you have to consider your team, if there is not a lot of current C# skills, then that is a factor, but going forward the market for MFC developers is diminishing and C# is growing.</p> <p>Maybe some kind of piecemeal approach would be possible? I have been involved with recoding legacy applications to C# quite a bit, and it always takes a lot longer than you would estimate, especially if you are keeping some legacy code, or your team isn't that conversant with C#.</p>
3,209
<p>I have inherited some legacy PHP code what was written back when it was standard practice to use <a href="http://php.net/register_globals" rel="nofollow noreferrer"><code>register_globals</code></a> (As of PHP 4.2.0, this directive defaults to off, released 22. Apr 2002).</p> <p>We know now that it is bad for security to have it enabled. The problem is how do I find all the places in the code where I need to use <code>$_GET</code> or <code>$_POST</code>? My only thought was to set the error reporting to warn about uninitialized variables and then test each part of the site. Is there an easier way? Will I have to test each code path in the site or will PHP give a warning on a file basis?</p>
<p>If you set error reporting to E_ALL, it warns in the error log about undefined variables complete with filename and line number (assuming you are logging to a file). However, it will warn only if when it comes across an undefined variable, so I think you will have to test each code path. Running php from the command line doesn't seem to help also.</p> <p>There is a debugging tool named xdebug, haven't tried it, but maybe that can be useful?</p>
<p>I know that there's a way to set php.ini values for that script with a certain command, I thus went looking and found this too - <a href="http://forums.macosxhints.com/archive/index.php/t-8538.html" rel="nofollow noreferrer">Goto last post on page</a></p> <p>I also found the following post which may be of use - <a href="http://www.webmasterworld.com/forum88/1584.htm" rel="nofollow noreferrer">Goto last post on the page</a></p> <p>I will add to this more if nobody has found an answer but I must now catch a train.</p>
2,836
<p>I'm looking for something that can copy (preferably only changed) files from a development machine to a staging machine and finally to a set of production machines.</p> <p>A "what if" mode would be nice as would the capability to "rollback" the last deployment. Database migrations aren't a necessary feature.</p> <p>UPDATE: A free/low-cost tool would be great, but cost isn't the only concern. A tool that could actually manage deployment from one environment to the next (dev->staging->production instead of from a development machine to each environment) would also be ideal.</p> <p>The other big nice-to-have is the ability to only copy changed files - some of our older sites contain hundreds of .asp files.</p>
<p><strong>@Sean Carpenter</strong> can you tell us a little more about your environment? Should the solution be free? simple?</p> <p>I find robocopy to be pretty slick for this sort of thing. Wrap in up in a batch file and you are good to go. It's a glorified xcopy, but deploying my website isn't really hard. Just copy out the files.</p> <p>As far as rollbacks... You are using source control right? Just pull the old source out of there. Or, in your batch file, ALSO copy the deployment to another folder called website yyyy.mm.dd so you have a lovely folder ready to go in an emergency.</p> <p>look at the for command for details on how to get the parts of the date.</p> <pre><code>robocopy.exe for /? </code></pre> <p>Yeah, it's a total "hack" but it moves the files nicely.</p>
<p>We used <a href="http://www.eworldui.net/unleashit/" rel="nofollow noreferrer">UnleashIt</a> (unfortunate name I know) which was nicely customizable and allowed you to save profiles for deploying to different servers. It also has a "backup" feature which will backup your production files before deployment so rollback should be pretty easy.</p>
6,438
<p>This came up from <a href="https://stackoverflow.com/questions/55093/how-to-deal-with-arrays-declared-on-the-stack-in-c#55183">this answer to a previous question of mine</a>. Is it guaranteed for the compiler to treat <code>array[4][4]</code> the same as <code>array[16]</code>?</p> <p>For instance, would either of the below calls to <code>api_func()</code> be safe?</p> <pre><code>void api_func(const double matrix[4][4]); // ... { typedef double Matrix[4][4]; double* array1 = new double[16]; double array2[16]; // ... api_func(reinterpret_cast&lt;Matrix&amp;&gt;(array1)); api_func(reinterpret_cast&lt;Matrix&amp;&gt;(array2)); } </code></pre>
<p>From the C++ standard, referring to the <code>sizeof</code> operator:</p> <blockquote> <p>When applied to an array, the result is the total number of bytes in the array. This implies that the size of an array of <code>n</code> elements is <code>n</code> times the size of an element.</p> </blockquote> <p>From this, I'd say that <code>double[4][4]</code> and <code>double[16]</code> would have to have the same underlying representation. </p> <p>I.e., given </p> <pre><code>sizeof(double[4]) = 4*sizeof(double) </code></pre> <p>and</p> <pre><code>sizeof(double[4][4]) = 4*sizeof(double[4]) </code></pre> <p>then we have</p> <pre><code>sizeof(double[4][4]) = 4*4*sizeof(double) = 16*sizeof(double) = sizeof(double[16]) </code></pre> <p>I think a standards-compliant compiler would have to implement these the same, and I think that this isn't something that a compiler would accidentally break. The standard way of implementing multi-dimensional arrays works as expected. Breaking the standard would require extra work, for likely no benefit.</p> <p>The C++ standard also states that an array consists of contiguously-allocated elements, which eliminates the possibility of doing anything strange using pointers and padding.</p>
<p>I would be worried about padding being added for things like Matrix[5][5] to make each row word aligned, but that could be simply my own superstition.</p>
7,934
<p>We are a small team of 3 developers (2 experienced but new to this particular business sector) developing a functionally complex product. We're using Scrum and have a demo at the end of each sprint. Its clear that the functional team have plenty of ideas but these are not well communicated to the development team and the demo poses more questions than answers. </p> <p>Have you any recommendations for improving the the quality of input from the functional people?</p> <p><strong>Further info:</strong> I think part of the problem is that there are no <em>specs</em> or User Stories as such. Personally I think they need to be writing down some sort of requirements - what sort of things should they be writing down and to what complexity given its an agile process?</p>
<p>Have you tried working with your customer to define / formulate <strong>acceptance tests</strong>?<br> Using something like Fit to come up with these tests - would result in better specs as well as force the customer to think about what is really required. The icing on the cake is instant-doc-executable specs at the end of this process.</p> <p>That is of course, if your customers are available and open to this approach. Give it a try!</p> <p>If not (and that seems to be the majority - because it is less work) - calendar flash 'em - schedule meetings/telecons every week until they sing like canaries :) +1 to Dana </p>
<p>Are they participating in the stand-up meetings?</p> <p>You could propose to have a representative at each (or some) of them, to ask them for input before the end of the sprint</p>
4,849
<p>We’ve found that the unit tests we’ve written for our C#/C++ code have really paid off. But we still have thousands of lines of business logic in stored procedures, which only really get tested in anger when our product is rolled out to a large number of users. </p> <p>What makes this worse is that some of these stored procedures end up being very long, because of the performance hit when passing temporary tables between SPs. This has prevented us from refactoring to make the code simpler.</p> <p>We have made several attempts at building unit tests around some of our key stored procedures (primarily testing the performance), but have found that setting up the test data for these tests is really hard. For example, we end up copying around test databases. In addition to this, the tests end up being really sensitive to change, and even the smallest change to a stored proc. or table requires a large amount of changes to the tests. So after many builds breaking due to these database tests failing intermittently, we’ve just had to pull them out of the build process.</p> <p>So, the main part of my questions is: has anyone ever successfully written unit tests for their stored procedures?</p> <p>The second part of my questions is whether unit testing would be/is easier with linq? </p> <p>I was thinking that rather than having to set up tables of test data, you could simply create a collection of test objects, and test your linq code in a “linq to objects” situation? (I am a totally new to linq so don’t know if this would even work at all)</p>
<p>I ran into this same issue a while back and found that if I created a simple abstract base class for data access that allowed me to inject a connection and transaction, I could unit test my sprocs to see if they did the work in SQL that I asked them to do and then rollback so none of the test data is left in the db. </p> <p>This felt better than the usual "run a script to setup my test db, then after the tests run do a cleanup of the junk/test data". This also felt closer to unit testing because these tests could be run alone w/out having a great deal of "everything in the db needs to be 'just so' before I run these tests".</p> <p><strong>Here is a snippet of the abstract base class used for data access</strong></p> <pre><code>Public MustInherit Class Repository(Of T As Class) Implements IRepository(Of T) Private mConnectionString As String = ConfigurationManager.ConnectionStrings("Northwind.ConnectionString").ConnectionString Private mConnection As IDbConnection Private mTransaction As IDbTransaction Public Sub New() mConnection = Nothing mTransaction = Nothing End Sub Public Sub New(ByVal connection As IDbConnection, ByVal transaction As IDbTransaction) mConnection = connection mTransaction = transaction End Sub Public MustOverride Function BuildEntity(ByVal cmd As SqlCommand) As List(Of T) Public Function ExecuteReader(ByVal Parameter As Parameter) As List(Of T) Implements IRepository(Of T).ExecuteReader Dim entityList As List(Of T) If Not mConnection Is Nothing Then Using cmd As SqlCommand = mConnection.CreateCommand() cmd.Transaction = mTransaction cmd.CommandType = Parameter.Type cmd.CommandText = Parameter.Text If Not Parameter.Items Is Nothing Then For Each param As SqlParameter In Parameter.Items cmd.Parameters.Add(param) Next End If entityList = BuildEntity(cmd) If Not entityList Is Nothing Then Return entityList End If End Using Else Using conn As SqlConnection = New SqlConnection(mConnectionString) Using cmd As SqlCommand = conn.CreateCommand() cmd.CommandType = Parameter.Type cmd.CommandText = Parameter.Text If Not Parameter.Items Is Nothing Then For Each param As SqlParameter In Parameter.Items cmd.Parameters.Add(param) Next End If conn.Open() entityList = BuildEntity(cmd) If Not entityList Is Nothing Then Return entityList End If End Using End Using End If Return Nothing End Function End Class </code></pre> <p><strong>next you will see a sample data access class using the above base to get a list of products</strong></p> <pre><code>Public Class ProductRepository Inherits Repository(Of Product) Implements IProductRepository Private mCache As IHttpCache 'This const is what you will use in your app Public Sub New(ByVal cache As IHttpCache) MyBase.New() mCache = cache End Sub 'This const is only used for testing so we can inject a connectin/transaction and have them roll'd back after the test Public Sub New(ByVal cache As IHttpCache, ByVal connection As IDbConnection, ByVal transaction As IDbTransaction) MyBase.New(connection, transaction) mCache = cache End Sub Public Function GetProducts() As System.Collections.Generic.List(Of Product) Implements IProductRepository.GetProducts Dim Parameter As New Parameter() Parameter.Type = CommandType.StoredProcedure Parameter.Text = "spGetProducts" Dim productList As List(Of Product) productList = MyBase.ExecuteReader(Parameter) Return productList End Function 'This function is used in each class that inherits from the base data access class so we can keep all the boring left-right mapping code in 1 place per object Public Overrides Function BuildEntity(ByVal cmd As System.Data.SqlClient.SqlCommand) As System.Collections.Generic.List(Of Product) Dim productList As New List(Of Product) Using reader As SqlDataReader = cmd.ExecuteReader() Dim product As Product While reader.Read() product = New Product() product.ID = reader("ProductID") product.SupplierID = reader("SupplierID") product.CategoryID = reader("CategoryID") product.ProductName = reader("ProductName") product.QuantityPerUnit = reader("QuantityPerUnit") product.UnitPrice = reader("UnitPrice") product.UnitsInStock = reader("UnitsInStock") product.UnitsOnOrder = reader("UnitsOnOrder") product.ReorderLevel = reader("ReorderLevel") productList.Add(product) End While If productList.Count &gt; 0 Then Return productList End If End Using Return Nothing End Function End Class </code></pre> <p><strong>And now in your unit test you can also inherit from a very simple base class that does your setup / rollback work - or keep this on a per unit test basis</strong></p> <p><strong>below is the simple testing base class I used</strong></p> <pre><code>Imports System.Configuration Imports System.Data Imports System.Data.SqlClient Imports Microsoft.VisualStudio.TestTools.UnitTesting Public MustInherit Class TransactionFixture Protected mConnection As IDbConnection Protected mTransaction As IDbTransaction Private mConnectionString As String = ConfigurationManager.ConnectionStrings("Northwind.ConnectionString").ConnectionString &lt;TestInitialize()&gt; _ Public Sub CreateConnectionAndBeginTran() mConnection = New SqlConnection(mConnectionString) mConnection.Open() mTransaction = mConnection.BeginTransaction() End Sub &lt;TestCleanup()&gt; _ Public Sub RollbackTranAndCloseConnection() mTransaction.Rollback() mTransaction.Dispose() mConnection.Close() mConnection.Dispose() End Sub End Class </code></pre> <p><strong>and finally - the below is a simple test using that test base class that shows how to test the entire CRUD cycle to make sure all the sprocs do their job and that your ado.net code does the left-right mapping correctly</strong></p> <p><strong>I know this doesn't test the "spGetProducts" sproc used in the above data access sample, but you should see the power behind this approach to unit testing sprocs</strong></p> <pre><code>Imports SampleApplication.Library Imports System.Collections.Generic Imports Microsoft.VisualStudio.TestTools.UnitTesting &lt;TestClass()&gt; _ Public Class ProductRepositoryUnitTest Inherits TransactionFixture Private mRepository As ProductRepository &lt;TestMethod()&gt; _ Public Sub Should-Insert-Update-And-Delete-Product() mRepository = New ProductRepository(New HttpCache(), mConnection, mTransaction) '** Create a test product to manipulate throughout **' Dim Product As New Product() Product.ProductName = "TestProduct" Product.SupplierID = 1 Product.CategoryID = 2 Product.QuantityPerUnit = "10 boxes of stuff" Product.UnitPrice = 14.95 Product.UnitsInStock = 22 Product.UnitsOnOrder = 19 Product.ReorderLevel = 12 '** Insert the new product object into SQL using your insert sproc **' mRepository.InsertProduct(Product) '** Select the product object that was just inserted and verify it does exist **' '** Using your GetProductById sproc **' Dim Product2 As Product = mRepository.GetProduct(Product.ID) Assert.AreEqual("TestProduct", Product2.ProductName) Assert.AreEqual(1, Product2.SupplierID) Assert.AreEqual(2, Product2.CategoryID) Assert.AreEqual("10 boxes of stuff", Product2.QuantityPerUnit) Assert.AreEqual(14.95, Product2.UnitPrice) Assert.AreEqual(22, Product2.UnitsInStock) Assert.AreEqual(19, Product2.UnitsOnOrder) Assert.AreEqual(12, Product2.ReorderLevel) '** Update the product object **' Product2.ProductName = "UpdatedTestProduct" Product2.SupplierID = 2 Product2.CategoryID = 1 Product2.QuantityPerUnit = "a box of stuff" Product2.UnitPrice = 16.95 Product2.UnitsInStock = 10 Product2.UnitsOnOrder = 20 Product2.ReorderLevel = 8 mRepository.UpdateProduct(Product2) '**using your update sproc '** Select the product object that was just updated to verify it completed **' Dim Product3 As Product = mRepository.GetProduct(Product2.ID) Assert.AreEqual("UpdatedTestProduct", Product2.ProductName) Assert.AreEqual(2, Product2.SupplierID) Assert.AreEqual(1, Product2.CategoryID) Assert.AreEqual("a box of stuff", Product2.QuantityPerUnit) Assert.AreEqual(16.95, Product2.UnitPrice) Assert.AreEqual(10, Product2.UnitsInStock) Assert.AreEqual(20, Product2.UnitsOnOrder) Assert.AreEqual(8, Product2.ReorderLevel) '** Delete the product and verify it does not exist **' mRepository.DeleteProduct(Product3.ID) '** The above will use your delete product by id sproc **' Dim Product4 As Product = mRepository.GetProduct(Product3.ID) Assert.AreEqual(Nothing, Product4) End Sub End Class </code></pre> <p>I know this is a long example, but it helped to have a reusable class for the data access work, and yet another reusable class for my testing so I didn't have to do the setup/teardown work over and over again ;)</p>
<p>LINQ will simplify this only if you remove the logic from your stored procedures and reimplement it as linq queries. Which would be much more robust and easier to test, definitely. However, it sounds like your requirements would preclude this.</p> <p>TL;DR: Your design has issues. </p>
3,343
<p>I'm not sure I'm using all the correct terminology here so be forgiving.</p> <p>I just put up a site with a contact form that sends an email using the PHP mail() function. Simple enough. However the live site doesn't actually send the email, the test site does. So it's not my code. </p> <p>It's a shared host and we have another site that has the same function that works perfectly, so it's not the server. </p> <p>The only difference between the two is that the site that doesn't work just has the name server pointing to us and so the MX record never touches our server. </p> <p>So my question is, could some one please confirm that the mail() function wont work if we don't have the MX record pointing to our server. Thanks</p>
<p>Hey guys thanks for the answers, it is really appreciated.</p> <p>After ignoring the issue for a few months it has come up again, I did however find the answer to my problems.</p> <p>Firstly, as you answers suggested, PHP and the mail() function were working as expected. The mail was getting sent.</p> <p>The problem lies when the email is sent, it simply presumes that because its being sent from mydomain.com to *@mydomain.com email that the email itself is hosted on the same server, so it gets sent there instead and ignores the MX record. </p> <p>OK it's a bit more complicated than that, but that is the general jist.</p> <p>Edit: Found a better version of the topic <a href="https://stackoverflow.com/questions/322659/sendmail-and-mx-records-when-mail-server-is-not-on-web-host">sendmail and MX records when mail server is not on web host</a>.</p>
<p>Yes, you could put in what ever you want in the 'from' field and it would still work.</p>
5,960
<p>I am in need of a way to mute a specific application in Vista.</p> <p>Example: Mute just Firefox, but not all of the other application. Much similar to muting a specific program from within the volume mixer in vista. </p> <p>If there is a program that will do this, i would appreciate that. Otherwise if there is a way to do this, I will write a small app(Preferrably something .net).</p> <p>EDIT: I want to automate this procedure, possibly key-map it.</p>
<p>I suggest using the built in Mixer in Vista...</p> <p>Why do you want to use an 3rd party program?</p>
<p>Using AutoHotkey, this works even better than expected! Just a fast window flash and BOOM, done. Src: <a href="http://feebdack.com/knob/how_to_mute_a_single_application" rel="nofollow">http://feebdack.com/knob/how_to_mute_a_single_application</a></p> <pre><code>#NoEnv ;// Recommended for new scripts #Persistent ;// Recommended for new scripts SendMode Input ;// Recommended for new scripts SetTitleMatchMode 2 ;// Set VolumeMute to only silence Media Center $f3:: MuteMediaCenter() return MuteMediaCenter() { ;// Open mixer Run sndvol WinWait Volume Mixer ;// Mute Standard Media Center Process appName = Chrome MuteApp(appName) ;// Mute Netflix Media Center Process appName = Firefox MuteApp(appName) WinClose Volume Mixer } ;// Volume Mixer must exist MuteApp(appName) { ;// Find X position &amp; width of textblock with text matching our appName ControlGetPos, refX, , refW, , % appName, Volume Mixer ;// Find button with left side within the width of the textblock x = -1 while ( x != "") { ;// A_Index is current loop iteration→used to find id tbIDX := (A_Index * 2) ControlGetPos, x, , , , ToolbarWindow32%tbIDX%, Volume Mixer diff := x - refX if (diff &gt; 0 &amp;&amp; diff &lt; refW) { ;// msgbox diff: %diff% refX: %refX% tbIDX: %tbIDX% x: %x% A_Index: %A_Index% ControlClick, ToolbarWindow32%tbIDX%, Volume Mixer break } } } </code></pre>
6,297
<p>I'm going to guess that the answer is "no" based on the below error message (and <a href="http://archives.postgresql.org/pgsql-sql/2004-08/msg00076.php" rel="noreferrer">this Google result</a>), but is there anyway to perform a cross-database query using PostgreSQL?</p> <pre><code>databaseA=# select * from databaseB.public.someTableName; ERROR: cross-database references are not implemented: "databaseB.public.someTableName" </code></pre> <p>I'm working with some data that is partitioned across two databases although data is really shared between the two (userid columns in one database come from the <code>users</code> table in the other database). I have no idea why these are two separate databases instead of schema, but c'est la vie...</p>
<p><em>Note: As the original asker implied, if you are setting up two databases on the same machine you probably want to make two <a href="https://www.postgresql.org/docs/current/static/ddl-schemas.html" rel="noreferrer">schemas</a> instead - in that case you don't need anything special to query across them.</em></p> <h2><code>postgres_fdw</code></h2> <p>Use <a href="https://www.postgresql.org/docs/current/postgres-fdw.html" rel="noreferrer"><code>postgres_fdw</code></a> (foreign data wrapper) to connect to tables in any Postgres database - local or remote.</p> <p>Note that there are <a href="http://wiki.postgresql.org/wiki/Foreign_data_wrappers" rel="noreferrer">foreign data wrappers for other popular data sources</a>. At this time, only <code>postgres_fdw</code> and <code>file_fdw</code> are part of the official Postgres distribution.</p> <h3>For Postgres versions before 9.3</h3> <p>Versions this old are no longer supported, but if you need to do this in a pre-2013 Postgres installation, there is a function called <a href="https://www.postgresql.org/docs/current/dblink.html" rel="noreferrer"><code>dblink</code></a>.</p> <p>I've never used it, but it is maintained and distributed with the rest of PostgreSQL. If you're using the version of PostgreSQL that came with your Linux distro, you might need to install a package called postgresql-contrib.</p>
<p>In case someone needs a more involved example on how to do cross-database queries, here's an example that cleans up the <code>databasechangeloglock</code> table on every database that has it:</p> <pre><code>CREATE EXTENSION IF NOT EXISTS dblink; DO $$ DECLARE database_name TEXT; DECLARE conn_template TEXT; DECLARE conn_string TEXT; DECLARE table_exists Boolean; BEGIN conn_template = 'user=myuser password=mypass dbname='; FOR database_name IN SELECT datname FROM pg_database WHERE datistemplate = false LOOP conn_string = conn_template || database_name; table_exists = (select table_exists_ from dblink(conn_string, '(select Count(*) &gt; 0 from information_schema.tables where table_name = ''databasechangeloglock'')') as (table_exists_ Boolean)); IF table_exists THEN perform dblink_exec(conn_string, 'delete from databasechangeloglock'); END IF; END LOOP; END $$ </code></pre>
6,840
<p>Does emacs have something like vi's “set number”, so that each line starts with its line number?</p>
<p>Take a look at this article. It explains various ways to add line numbers to emacs:</p> <p><a href="http://www.emacswiki.org/cgi-bin/wiki/LineNumbers" rel="nofollow noreferrer">http://www.emacswiki.org/cgi-bin/wiki/LineNumbers</a></p>
<p>Try adding <a href="http://www.emacswiki.org/cgi-bin/wiki/LineNumbers" rel="nofollow noreferrer">linum.el</a> to your emacs dir / .emacs file.</p>
8,983
<p><code>Checkboxes</code> in <code>HTML</code> forms don't have implicit <em>labels</em> with them. Adding an explicit label (some text) next to it doesn't toggle the <code>checkbox</code>.</p> <p><strong>How do I make a checkbox toggle from clicking on the text label as well?</strong></p>
<p>If you correctly markup your HTML code, there is no need for javascript. The following code will allow the user to click on the label text to tick the checkbox.</p> <pre><code>&lt;label for="surname"&gt;Surname&lt;/label&gt; &lt;input type="checkbox" name="surname" id="surname" /&gt; </code></pre> <p>The <em>for</em> attribute on the label element links to the <em>id</em> attribute on the input element and the browser does the rest.</p> <p>This has been testing to work in:</p> <ul> <li>IE6</li> <li>IE7</li> <li>Firefox</li> </ul>
<p>Wrapping with the label still doesn't allow clicking 'anywhere in the box' - still just on the text! This does the job for me:</p> <pre><code>&lt;div onclick="dob.checked=!dob.checked" class="checkbox"&gt;&lt;input onclick="checked=!checked" id="dob" type="checkbox"/&gt;Date of birth entry must be completed&lt;/div&gt; </code></pre> <p>but unfortunately has lots of javascript that is effectively toggling twice.</p>
2,431
<p>I've had an Ender 5 Plus for a few weeks now. It's printing great and I've got my tuning pretty good at the moment. I've noticed some horizontal inconsistencies matching feature/geometry changes. It seems to be associated with maybe layer time(?) I only have a picture from two models, but the problem will appear in other places on different models, always matching some change in the layers.</p> <p>The problem is consistent all around the model and changes position with different prints, so I know it's not a mechanical problem. Say I printed a 2x2 cm tower 20 cm tall, it will not have any of these imperfections because every layer is identical.</p> <p>I highly suspect the layer time/temperature change, but I don't know how to fix this, I'm a bit stumped. They both were printed at 200 °C and I'm trying a new one at 210 °C (best temperature with the spool I have) and it has the same problem. All three models are from the same spool of PLA.</p> <p>Also, I use Cura with mostly default settings for the Ender 5+.</p> <p>Here are the pictures :</p> <p>I tried to highlight the idea, but every line matches with some change in the model <a href="https://i.stack.imgur.com/EwjN7.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EwjN7.jpg" alt="Model 1" /></a></p> <p>On the benchy it's harder to see, but the hull line match with the solid floor of the model, and the top ones match with the top window sill starting.</p> <p><a href="https://i.stack.imgur.com/STS4C.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/STS4C.jpg" alt="Benchy" /></a></p>
<p>This is varying underextrusion due to loss of material to oozing in the interior of the model.</p> <p>When printing the infill pattern, the nozzle doesn't follow a single continuous extrusion path, but moves from the end of one path to the beginning of the next, and under Cura defaults, <em>does this without retracting the filament</em>. This causes unpredictable amounts to ooze out during travel from one to the next, thereby desynchronizing the planned/intended amount of material extruded so far and the actual amount. This means, when the next outer-wall extrusion starts, there's an unpredictable deficiency between the amount of material at the nozzle to extrude, and the amount the slicer intended to extrude. The result is what you're seeing.</p> <p>To fix it, you need to eliminate oozing, not just outside the model where it appears as visible stringing, but inside too. Either disable &quot;Combing&quot; entirely in Cura, or set &quot;Max Comb Distance With No Retract&quot; to something very low (0.8 mm or less). Also set &quot;Minimum Extrusion Distance Window&quot; to 0 to ensure Cura doesn't skip retractions for other reasons.</p> <p>You may also want to play with extrusion length and speed. Too short or too long can be bad; 5-7 mm is the reasonable range for PLA with a bowden. Higher speed generally helps too; the printer should be able to handle 50 mm/s or faster.</p>
<p>If this matches the horizontal planes - like &quot;solid floor&quot; than I would advice to check overlap settings. My suspicion is slight overextrusion, which might be the reason of many small horizontal differences. Using 3 mm filament I often suffer of similar inconsistencies, until I find proper flowrate to avoid overextrusion. Adding first to second, the solid plane will push walls more to sides.</p> <p>Do you print &quot;Infill Before Walls&quot; (Cura setting)? You may try to disable this checkbox and observe if the result persisted. Also you may enable &quot;Outer Before Inner Walls&quot; - to ensure, that outer wall is printed first with least interference (though some other issues may appear after travel, layer change, etc.).</p> <ul> <li>So try print from outside to inside (outer walls &gt; inner walls &gt; infill).</li> <li>Then try to reduce &quot;Flow&quot; until you see no overextrusion (or even small gaps in the surface).</li> <li>Finally revert these settings (infill &gt; inner &gt; outer) and check again.</li> </ul>
1,834
<p>I've got a problem where incoming SOAP messages from one particular client are being marked as invalid and rejected by our XML firewall device. It appears extra payload data is being inserted by Visual Studio; we're thinking the extra data may be causing a problem b/c we're seeing "VsDebuggerCausalityData" in these messages but not in others sent from a different client who is not having a problem. It's a starting point, anyway.</p> <p>The question I have is how can the client remove this extra data and still run from VS? Why is VS putting it in there at all?</p> <p>Thanks.</p>
<p>A quick google reveals that this should get rid of it, get them to add it to the web.config or app.config for their application. </p> <pre><code>&lt;configuration&gt; &lt;system.diagnostics&gt; &lt;switches&gt; &lt;add name="Remote.Disable" value="1" /&gt; &lt;/switches&gt; &lt;/system.diagnostics&gt; &lt;/configuration&gt; </code></pre> <p>The information is debug information that the receiving service can use to help trace things back to the client. (maybe, I am guessing a little) </p> <ul> <li>I have proposed a follow up <a href="https://stackoverflow.com/questions/33334/how-do-you-find-what-debug-switches-are-available-or-given-a-switch-find-out-wh">question</a> to determine were the magic switch actually comes from.</li> </ul>
<p>Or use "Start without debugging" in Visual Studio.</p>
5,288
<p>I am writing a batch script in order to beautify JavaScript code. It needs to work on both <strong>Windows</strong> and <strong>Linux</strong>. </p> <p>How can I beautify JavaScript code using the command line tools? </p>
<p>First, pick your favorite Javascript based Pretty Print/Beautifier. I prefer the one at <a href="http://jsbeautifier.org/" rel="noreferrer"><a href="http://jsbeautifier.org/" rel="noreferrer">http://jsbeautifier.org/</a></a>, because it's what I found first. Downloads its file <a href="https://github.com/beautify-web/js-beautify/blob/master/js/lib/beautify.js" rel="noreferrer">https://github.com/beautify-web/js-beautify/blob/master/js/lib/beautify.js</a></p> <p>Second, download and install The Mozilla group's Java based Javascript engine, <a href="https://www.mozilla.org/rhino/" rel="noreferrer">Rhino</a>. "Install" is a little bit misleading; Download the zip file, extract everything, place js.jar in your Java classpath (or Library/Java/Extensions on OS X). You can then run scripts with an invocation similar to this </p> <pre><code>java -cp js.jar org.mozilla.javascript.tools.shell.Main name-of-script.js </code></pre> <p>Use the Pretty Print/Beautifier from step 1 to write a small shell script that will read in your javascript file and run it through the Pretty Print/Beautifier from step one. For example</p> <pre><code>//original code (function() { ... js_beautify code ... }()); //new code print(global.js_beautify(readFile(arguments[0]))); </code></pre> <p>Rhino gives javascript a few extra useful functions that don't necessarily make sense in a browser context, but do in a console context. The function print does what you'd expect, and prints out a string. The function readFile accepts a file path string as an argument and returns the contents of that file. </p> <p>You'd invoke the above something like </p> <pre><code>java -cp js.jar org.mozilla.javascript.tools.shell.Main beautify.js file-to-pp.js </code></pre> <p>You can mix and match Java and Javascript in your Rhino run scripts, so if you know a little Java it shouldn't be too hard to get this running with text-streams as well.</p>
<p>I've written an article explaining how to build a <a href="http://blog.shonzilla.com/post/1448821411/command-line-javascript-beautifier" rel="nofollow">command-line JavaScript beautifier implemented in JavaScript</a> in under 5 minutes. YMMV.</p> <blockquote> <ol> <li>Download the latest stable Rhino and unpack it somewhere, e.g. ~/dev/javascript/rhino</li> <li>Download beautify.js which is referenced from aforementioned jsbeautifier.org then copy it somewhere, e.g. ~/dev/javascript/bin/cli-beautifier.js</li> <li><p>Add this at the end of beautify.js (using some additional top-level properties to JavaScript):</p> <pre><code>// Run the beautifier on the file passed as the first argument. print( j23s_beautify( readFile( arguments[0] ))); </code></pre></li> <li><p>Copy-paste the following code in an executable file, e.g. ~/dev/javascript/bin/jsbeautifier.sh:</p> <pre><code>#!/bin/sh java -cp ~/dev/javascript/rhino/js.jar org.mozilla.javascript.tools.shell.Main ~/dev/web/javascript/bin/cli-beautifier.js $* </code></pre></li> <li><p>(optional) Add the folder with jsbeautifier.js to PATH or moving to some folder already there.</p></li> </ol> </blockquote>
3,950
<p>I made a print that involves joining two halves together to create the full model. I decided to use hot glue to bond the halves and on one model, the parts came together slightly skewed. Is there any way to ‘unbond’ the hot glue without ruining the model so I can realign the pieces? Touching the glue gun tip to the hot glue wouldn’t work, as the glue is <em>inside</em> the model.</p>
<p>it seems like retraction issue</p> <p>i would say you should experiment with </p> <ul> <li>retraction length - so it would retract more</li> <li>extra extrusion after retraction - so the printer could put some material before it will start your next hole :)</li> </ul> <p>unfortunately there is no good guide how much it should retract and how much it should additionally extrude as it depends on "all your printing circumstances" but here is my arbitrary list in order of importance</p> <ul> <li>filament (density - type and producer)</li> <li>temperature (viscosity - hotter filament flows easier)</li> <li>nozzle diam (as filament escapes easier through big hole ;)</li> <li>heat barrier (cooling efficiency - filament should be cool as long as possible up to (or down to) the nozzle)</li> <li>extruder gearing quality (good coupling makes precise retraction and extra-extrusion)</li> <li>cooling (fan and duct should cool your printing right after it sticks to the surface)</li> </ul> <p>and one more thing worth to mention</p> <p>usually the first layer is not cooled which makes whole system hotter (so filament flows easier)</p> <p>you could experiment with it too especially for big printouts </p> <p>so</p> <ul> <li>overextrude first layer AND </li> <li>turn on cooling first layer</li> </ul> <p>it seems like there is a bunch of things you can do to master it :)</p> <p>good luck - it's definitely manageable</p>
<p>Set <code>retraction_min_travel</code> to 0. The default value is 1.5 and skips retraction when moving less than 1.5 mm. This leads to serious oozing whenever your print has small travel, which seems likely between the hole walls and the supports inside the holes.</p> <p>Also, the "custom start gcode" in Cura's Ender 3 configuration seriously over-primes the extruder, possibly making retraction ineffective until the pressure drops. Lowering the <code>E15</code> and <code>E30</code> amounts to <code>E9</code> and <code>E18</code> improved things <strong>a lot</strong> for me, especially with flex filament, but also with normal PLA. Printing a skirt or brim would probably be an alternative if you don't feel up to editing that part of the config.</p> <p>Increasing the retraction amount could also help. You should <strong>not</strong> need extra prime after travel. It can only help if you've lost material to oozing during travel, and if you have oozing, that's a problem in itself that you need to solve, not paper over by extruding additional material.</p>
1,292
<p>I'd like to keep a "compile-counter" for one of my projects. I figured a quick and dirty way to do this would be to keep a text file with a plain number in it, and then simply call upon a small script to increment this each time I compile.</p> <p>How would I go about doing this using the regular Windows command line?</p> <p>I don't really feel like installing some extra shell to do this but if you have any other super simple suggestions that would accomplish just this, they're naturally appreciated as well.</p>
<p>You can try a plain old batchfile.</p> <pre><code>@echo off for /f " delims==" %%i in (counter.txt) do set /A temp_counter= %%i+1 echo %temp_counter% &gt; counter.txt </code></pre> <p>assuming the count.bat and counter.txt are located in the same directory.</p>
<p>If you don't mind running a Microscoft Windows Based Script then this jscript will work OK. just save it as a .js file and run it from dos with "wscript c:/script.js".</p> <pre><code>var fso, f, fileCount; var ForReading = 1, ForWriting = 2; var filename = "c:\\testfile.txt"; fso = new ActiveXObject("Scripting.FileSystemObject"); //create file if its not found if (! fso.FileExists(filename)) { f = fso.OpenTextFile(filename, ForWriting, true); f.Write("0"); f.Close(); } f = fso.OpenTextFile(filename, ForReading); fileCount = parseInt(f.ReadAll()); //make sure the input is a whole number if (isNaN(fileCount)) { fileCount = 0; } fileCount = fileCount + 1; f = fso.OpenTextFile(filename, ForWriting, true); f.Write(fileCount); f.Close(); </code></pre>
6,207
<p>I've been tasked (by my wife) with creating a program to allow her to track the family trees on both sides of our family.</p> <p>Does anyone know of a cost-effective (free) control to represent this type of information?</p> <p>What I'm looking for is a modified org-chart type chart/tree. The modification is that any node should have 2 parent nodes (E.G. a child should have a Mother/Father).</p> <p>The solution I've come up with so far is to have 2 trees, an ancestor tree and a descendants tree, with the individual being inspected as the root node for each tree. It works but is sort of clunky.</p> <p>I'm working primarily in c# WinForms, so .Net type controls or source code is preferable.</p>
<p><a href="http://www.geni.com/" rel="noreferrer">Geni</a> is probably what your looking for.</p>
<p>I haven't thought too hard about this, but I reckon you could get a Custom Treeview in WPF to do what you want. I was reading an <a href="http://www.codeproject.com/KB/WPF/CustomTreeViewLayout.aspx" rel="nofollow noreferrer">article on code project a while back that implemented an org chart</a> this way...</p>
2,776
<p>When I goto view the property page for my CSharp test application I get the following error.</p> <p>"An error occurred trying to load the page. COM object that has been seperated from its underlying RCW cannot be used."</p> <p>The only thing that seems to fix it is rebooting my PC!</p>
<p>This is usually caused by a 'rogue' add-in.</p> <p>Try disabling them all, and then re-enabling them checking for the error - so that you can narrow down the culprit.</p>
<p>It seems Microsoft Style Cop was causing the issue.</p> <p>It was not registered as an Add-in, but was integrated into VS2005 on some deeper level.</p>
3,749
<p>Are 3D printed gears applicable for industrial use? </p> <p>I want to print some gears with ABS. </p> <ul> <li>What will their lifespan be? How long will they last if I use them, for example, every day? </li> </ul>
<p>Well, to determine the time life of the gears you will need to do a test called ALT (Accelerated Life Time) but the parts should be last for a long time (not years) however this can be determined by thickness. </p> <p>The torque required is not than much like a tuning up the radio volume, so if you are going to create a gear box to increase torque, just grease the parts to reduce heating on friction.</p>
<p>Well, to determine the time life of the gears you will need to do a test called ALT (Accelerated Life Time) but the parts should be last for a long time (not years) however this can be determined by thickness. </p> <p>The torque required is not than much like a tuning up the radio volume, so if you are going to create a gear box to increase torque, just grease the parts to reduce heating on friction.</p>
766
<p>I need to programmatically determine out how many sectors, heads, and cylinders are on a physical disk from Windows XP. Does anyone know the API for determining this? Where might Windows expose this information?</p>
<p>Use <a href="http://msdn.microsoft.com/en-us/library/aa363216%28VS.85%29.aspx" rel="noreferrer">DeviceIoControl</a> with control code <a href="http://msdn.microsoft.com/en-us/library/aa365169%28VS.85%29.aspx" rel="noreferrer">IOCTL_DISK_GET_DRIVE_GEOMETRY</a> or <a href="http://msdn.microsoft.com/en-us/library/aa365171%28VS.85%29.aspx" rel="noreferrer">IOCTL_DISK_GET_DRIVE_GEOMETRY_EX</a>.</p> <p>There's sample code in MSDN to do this <a href="http://msdn.microsoft.com/en-us/library/aa363147%28VS.85%29.aspx" rel="noreferrer">here</a>.</p>
<p>There's a control code you can pass to <a href="http://msdn.microsoft.com/en-us/library/aa365171(VS.85).aspx" rel="nofollow noreferrer">DeviceIoControl</a> to get the physical disk geometry.</p>
7,353
<p>Is there any way to Write files to App_Data under medium trust hack?</p> <p>Im sure I've heard about some hack, is that true?</p>
<p>I don't think you are able to create new files, but you should be able to write to existing files in the App_Data folder. But I have honestly never experienced any problems with Medium Trust and writing to the App_Data folder. Are you sure it has the necessary permissions needed for writing files to the hard drive?</p>
<p>I don't think you are able to create new files, but you should be able to write to existing files in the App_Data folder. But I have honestly never experienced any problems with Medium Trust and writing to the App_Data folder. Are you sure it has the necessary permissions needed for writing files to the hard drive?</p>
5,245
<p>I see a similar question <a href="https://stackoverflow.com/questions/28588/how-do-you-set-up-an-openid-provider-server-in-ubuntu">for Ubuntu</a>, but I'm interested in hosting my own OpenID provider through my Rails-based site that already has an identity and authentication system in place.</p> <p>Note that I'm not looking for the delegate method to <a href="https://stackoverflow.com/questions/4661/can-you-apply-more-than-one-openid-to-a-stackoverflow-account#4777">use the site as an OpenID</a>.</p> <p>What's the best way to do this properly?</p>
<p>This "<a href="http://www.danwebb.net/2007/2/27/the-no-shit-guide-to-supporting-openid-in-your-applications" rel="nofollow noreferrer">No Shit Guide To Supporting OpenID In Your Applications</a>" seems to be a step-by-step tutorial for what you want to do.</p>
<p>This reminds me that <a href="http://trac.openidenabled.com/trac/ticket/267" rel="nofollow noreferrer">the overview docs for ruby-openid server are still missing</a>. But you can see <a href="http://openidenabled.com/files/ruby-openid/repos/2.x.x/examples/rails_openid/app/controllers/server_controller.rb" rel="nofollow noreferrer">the example</a>, and until the docs are ported over, see the <a href="http://openidenabled.com/files/python-openid/docs/2.2.1/openid.server.server-module.html" rel="nofollow noreferrer">docs for the python implementation</a> which follows the same object model.</p>
6,712
<p>Is there a better windows command line shell other than <code>cmd</code> which has better copy paste between Windows' windows and console windows?</p>
<p>Enable <strong>QuickEdit mode</strong>, under the <em>Options</em> tab of your shortcut to the command shell. Mark with the mouse, right-click to copy, right-click again to paste. </p> <p>While you're there, enable a hotkey (like <kbd>CTRL</kbd> + <kbd>ALT</kbd> + <kbd>C</kbd>) for lightning fast access to the shell. </p> <p>And no, you can't have <kbd>CTRL</kbd> + <kbd>C</kbd> for <strong>COPY</strong>, because <kbd>CTRL</kbd> + <kbd>C</kbd> means <strong>BREAK</strong>. </p> <p>On a related note, the Microsoftee who changed the default setting of <em>QuickEdit mode</em> between Windows Server 2000 and 2003 is an idiot and I heap curses upon him each workday. </p>
<p>@Chirs<br> I think you need to clarify shell vs host(emulator). To me it sounds like you need another interface to your existing shell that better supports copy and paste, not another shell that supports more/different features.</p> <p>I second Pat's suggestion of Console2, it is a very good application and OSS to boot.</p>
2,757
<p>I have a collection of STL files, each containing a separate moving part of an object I want to print. (Imagine a set of gears, or similar, that prints as a single object with multiple moving parts.)</p> <p>My plan was to import them all into Cura, then hit print, then take my fully assembled object off the build plate. However, Cura ignores the coordinate system in the STL files and automatically separates the components from each other on the build plate. This is usually helpful, but it isn't what I want in this case.</p> <p>So I'm looking for a quick and simple way to combine my multiple STL files into a single STL file. I know that the objects don't overlap, so I don't need to do a CSG union operation - it's enough just to concatenate the objects.</p> <p>I tried OpenSCAD, which works, but it takes a really long time, because the meshes are fairly complex and it does the full Boolean operation. Is there another quick and simple way to perform this task?</p> <p>I'd prefer a command line utility, but I'd also be happy if there's a quick and simple way to do it in some free graphical software. (However, I don't want to spend time manually positioning the objects - they're already in the right places in the STL files, so I just want to import them and go.)</p> <p><strong>Edit</strong> I've accepted Trish's answer (use Blender), but I'd still appreciate a command-line option if anyone knows one.</p>
<p>What you try to do is called "Print in Place". However, it is not done by importing several STLs one after another as cura does remove the origin and recenters each imported object upon importing. However, an STL file can contain more than one body.</p> <p>To generate a PiP model, you need to export your whole project as <strong>one</strong> STL file containing all the parts and then Cura not only doesn't rip the model apart, it <em>can't</em> do so.</p> <h2>Workaround</h2> <p>If you can't export the whole project in one piece from your design software, you could use a workaround by importing it into a software that can export as one item. Among these is blender, so importing all the parts into blender and then exporting the whole project as one STL is a simple fix. Other options would be TinkerCAD or Fusion360.</p> <p>The Step by step guide for blender is simple and the general idea of this workflow is the same for other options:</p> <ol> <li>Open blender</li> <li>New project</li> <li>delete the cube via <code>entf</code> + <code>enter</code></li> <li>Get the files into the workspace via either:<br> <ul> <li>Drag &amp; Drop <ol> <li><code>File &gt; Import &gt; Stl (.stl)</code></li> <li>select the file + <code>enter</code></li> </ol></li> </ul></li> <li>Possibly reposition the object, till it is in the right position</li> <li>Repeat 4. to 6. till all parts are imported</li> <li><code>File &gt; Export &gt; Stl (.stl)</code> + <code>enter</code></li> </ol>
<p>Import them to Tinkercad and then output your combined file from there. You can go into Tinkercad and on the top right side you will see "import", click that to import your file (you can repeat the process as desired) and it will put the files on the workspace .. on the screen. When you have your workspace all set the way you want select them all the click "export" and it will export all of them to one file for your use. </p>
1,485
<p>I have a core dump file from a process that has probably a file descriptor leak (it opens files and sockets but apparently sometimes forgets to close some of them). Is there a way to find out which files and sockets the process had opened before crashing? I can't easily reproduce the crash, so analyzing the core file seems to be the only way to get a hint on the bug.</p>
<p>If you have a core file and you have compiled the program with debugging options (-g), you can see where the core was dumped:</p> <pre><code>$ gcc -g -o something something.c $ ./something Segmentation fault (core dumped) $ gdb something core </code></pre> <p>You can use this to do some post-morten debugging. A few gdb commands: bt prints the stack, fr jumps to given stack frame (see the output of bt).</p> <p>Now if you want to see which files are opened at a segmentation fault, just handle the SIGSEGV signal, and in the handler, just dump the contents of the /proc/PID/fd directory (i.e. with system('ls -l /proc/PID/fs') or execv).</p> <p>With these information at hand you can easily find what caused the crash, which files are opened and if the crash and the file descriptor leak are connected.</p>
<p>Another way to find out what files a process has opened - again, only during runtime - is looking into /proc/PID/fd/ , which contains symlinks to open files.</p>
8,297
<p>We have a Windows Server Web Edition 2003 Web Farm. </p> <p>What can we use that handles replication across the servers for:</p> <p>Content &amp; IIS Configuration (App Pools, Virtual Directories, etc...)</p> <p>We will be moving to Windows 2008 in the near future, so I guess what options are there on Windows 2008 as well.</p>
<p>A short list might be:</p> <ul> <li>Avoid memory leaks through use shared pointers to manage memory allocation and cleanup</li> <li>Use the <a href="https://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization" rel="noreferrer">Resource Acquisition Is Initialization</a> (RAII) idiom to manage resource cleanup - especially in the presence of exceptions</li> <li>Avoid calling virtual functions in constructors</li> <li>Employ minimalist coding techniques where possible - for example, declaring variables only when needed, scoping variables, and early-out design where possible. </li> <li>Truly understand the exception handling in your code - both with regard to exceptions you throw, as well as ones thrown by classes you may be using indirectly. This is especially important in the presence of templates.</li> </ul> <p>RAII, shared pointers and minimalist coding are of course not specific to C++, but they help avoid problems that do frequently crop up when developing in the language. </p> <p>Some excellent books on this subject are:</p> <ul> <li>Effective C++ - Scott Meyers</li> <li>More Effective C++ - Scott Meyers</li> <li>C++ Coding Standards - Sutter &amp; Alexandrescu</li> <li>C++ FAQs - Cline</li> </ul> <p>Reading these books has helped me more than anything else to avoid the kind of pitfalls you are asking about.</p>
<pre><code>#include &lt;boost/shared_ptr.hpp&gt; class A { public: void nuke() { boost::shared_ptr&lt;A&gt; (this); } }; int main(int argc, char** argv) { A a; a.nuke(); return(0); } </code></pre>
5,030
<p>If I have a stl file is there a good way to estimate how long it will take to print on a given printer? I know there are a lot of things that go into print speed, such as the speed of the printer, the size of the print, etc. I was wondering if anyone knows of perhaps an application that you could enter your printer's specifications and the stl that you want to print, and it could calculate the print time?</p>
<p>All commonly used slicers (e.g., Cura, Slic3r, Simplify3D,...) give an estimation of the print time.</p> <p><a href="https://i.stack.imgur.com/cPaM6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cPaM6.png" alt="Example of print time estimation in Cura"></a></p> <p><a href="https://i.stack.imgur.com/2D5tZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2D5tZ.png" alt="Example of print time estimation in Simplify3D"></a></p>
<p>I use Repetier software with the Cura slicer and the print time estimate tends to be about 10&nbsp;% longer than the actual print.</p>
889
<p>This is something that I think would be very useful. Basically, I'd like there to be a way to edit Python source programmatically without requiring human intervention. There are a couple of things I would like to do with this:</p> <ol> <li><p>Edit the configuration of Python apps that use source modules for configuration.</p></li> <li><p>Set up a "template" so that I can customize a Python source file on the fly. This way, I can set up a "project" system on an open source app I'm working on and allow certain files to be customized.</p></li> </ol> <p>I could probably write something that can do this myself, but I can see that opening up a lot of "devil's in the details" type issues. Are there any ways to do this currently, or am I just going to have to bite the bullet and implement it myself?</p>
<p>Python's standard library provides pretty good facilities for working with Python source; note the <a href="https://docs.python.org/2/library/tokenize.html" rel="nofollow noreferrer">tokenize</a> and <a href="https://docs.python.org/2/library/parser.html" rel="nofollow noreferrer">parser</a> modules.</p>
<p>I had the same issue and I simply opened the file and did some replace: then reload the file in the Python interpreter. This works fine and is easy to do. </p> <p>Otherwise AFAIK you have to use some conf objects.</p>
5,231
<p>In simple terms, what are the reasons for, and what are the differences between the GPL v2 and GPL v3 open source licenses? Explanations and references to legal terms and further descriptions would be appreciated.</p>
<p>The page linked to in another answer is a good source, but a lot to read. Here is a short list of some the major differences:</p> <ul> <li><p>internationalization: they used new terminology, rather than using language tied to US legal concepts</p> </li> <li><p>patents: they specifically address patents (including the Microsoft/Novell issue noted in another answer)</p> </li> <li><p>“Tivo-ization”: they address the restrictions (like Tivo’s) in consumer products that take away, though hardware, the ability to modify the software</p> </li> <li><p>DRM: they address digital rights management (which they call digital restrictions management)</p> </li> <li><p>compatibility: they addressed compatibility with some other open source licenses</p> </li> <li><p>termination: they addressed specifically what happens if the license is violated and the cure of violations</p> </li> </ul> <p>I agree with the comment about consulting a lawyer (one who knows about software license issues, though). In doing these things (and more), they more than doubled the length of the GPL. GPL 3 is many things, and one of them is that it is a very complex, technical legal document.</p>
<p>In (not entirely) cynical terms, the reason for the v3 license was Microsoft's patent deal with Novell.</p> <p>In reality, you should always consult a lawyer when dealing with legal issues.</p>
6,276
<p>I have a string that is like below.</p> <pre><code>,liger, unicorn, snipe </code></pre> <p>in other languages I'm familiar with I can just do a string.trim(",") but how can I do that in c#?</p> <p>Thanks.</p> <hr> <p><em>There's been a lot of back and forth about the StartTrim function. As several have pointed out, the StartTrim doesn't affect the primary variable. However, given the construction of the data vs the question, I'm torn as to which answer to accept. True the question only wants the first character trimmed off not the last (if anny), however, there would never be a "," at the end of the data. So, with that said, I'm going to accept the first answer that that said to use StartTrim assigned to a new variable.</em></p>
<pre><code>string sample = ",liger, unicorn, snipe"; sample = sample.TrimStart(','); // to remove just the first comma </code></pre> <p>Or perhaps:</p> <pre><code>sample = sample.Trim().TrimStart(','); // to remove any whitespace and then the first comma </code></pre>
<pre><code>if (s.StartsWith(",")) { s = s.Substring(1, s.Length - 1); } </code></pre>
9,935
<p>Is there any way to tinker with the iPhone SDK on a Windows machine? Are there plans for an iPhone SDK version for Windows?</p> <p>The only other way I can think of doing this is to run a Mac VM image on a <strong>VMWare</strong> server running on Windows, although I'm not too sure how legal this is.</p>
<p>It's certainly possible to develop on a Windows machine, in fact, my first application was exclusively developed on the old Dell Precision I had at the time :)</p> <p>There are three routes;</p> <ol> <li>Install <a href="http://en.wikipedia.org/wiki/OSx86" rel="nofollow noreferrer">OSx86</a> (aka iATKOS / Kalyway) on a second partition/disk and dual boot.</li> <li>Run Mac OS X Server under VMWare (Mac OS X 10.7 (Lion) onwards, read the update below).</li> <li>Use a framework and/or toolset, which allows developing on Windows, like Delphi XE4 with the mac-in-cloud service, which can build without MacOS device need. This is a commercial toolset, but the component and lib support is growing. <blockquote> <p>Other honorable mentions are <a href="https://flutter.io/" rel="nofollow noreferrer">Flutter</a>, <a href="http://xamarin.com/" rel="nofollow noreferrer">Xamarin</a> and similar; which may at end need actual MacOS device for final build (but you can test on Android till then, as they're cross-platform).</p> </blockquote> </li> </ol> <p>The first route requires modifying (or using a pre-modified) image of Leopard that can be installed on a regular PC. This is not as hard as you would think, although your success/effort ratio will depend upon how closely the hardware in your PC matches that in Mac hardware - e.g. if you're running a Core 2 Duo on an Intel Motherboard, with an NVidia graphics card you are laughing. If you're running an AMD machine or something without SSE3 it gets a little more involved.</p> <p>If you purchase (or already own) a version of Leopard then this is a gray area since the Leopard EULA states you may only run it on an &quot;Apple Labeled&quot; machine. As many point out if you stick an Apple sticker on your PC you're probably covered.</p> <p>The second option is more costly. The EULA for the workstation version of Leopard prevents it from being run under emulation and as a result, there's no support in VMWare for this. Leopard server, however, CAN be run under emulation and can be used for desktop purposes. Leopard server and VMWare are expensive, however.</p> <p>If you're interested in option 1) I would suggest starting at <a href="http://www.insanelymac.com/forum/" rel="nofollow noreferrer">Insanelymac</a> and reading the OSx86 sections.</p> <p>I do think you should consider whether the time you will invest is going to be worth the money you will save though. It was for me because I enjoy tinkering with this type of stuff and I started during the early iPhone betas, months before their App Store became available.</p> <p>Alternatively, you could pick up a low-spec Mac Mini from eBay. You don't need much horsepower to run the SDK and you can always sell it on later if you decide to stop development or buy a better Mac.</p> <p>Update: You cannot create a Mac OS X Client virtual machine for OS X 10.6 and earlier. Apple does not allow these Client OSes to be virtualized. With Mac OS X 10.7 (Lion) onwards, Apple has changed its licensing agreement in regards to virtualization. Source: <a href="http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&amp;cmd=displayKC&amp;externalId=2005793" rel="nofollow noreferrer">VMWare KnowledgeBase</a></p>
<p>Just make a web app. iOS web apps are:</p> <ol> <li>Reliable. The amount of time it takes to make an update is far shorter than with XCode.</li> <li>Fast. JavaScript on iOS is, by nature, far faster than native apps.</li> <li>Free. You never have to pay Apple a cent, as Apple doesn't have any control over you.</li> <li>Safer. If a crash occurs with a native app, it can take down even the newest iOS devices for hours or even days, until the user can fix them. If a web app crashes, the user just has to close and reopen it, worst case scenario.</li> <li>Offline. You can easily create a service worker to handle your app.</li> <li>Secure. Because you do not have access to native APIs, a security breach will be significantly less dangerous.</li> <li>Easy to program. A basic iOS web app can be programmed from the Safari URL bar on an iPhone. Literally. I've done it myself.</li> </ol>
4,239
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions in this scenario?</p>
<p>The original answer below was written in 2008. Since then, Python 3.10 (2021) introduced the <a href="https://www.python.org/dev/peps/pep-0634/" rel="noreferrer"><code>match</code>-<code>case</code></a> statement which provides a first-class implementation of a &quot;switch&quot; for Python. For example:</p> <pre><code>def f(x): match x: case 'a': return 1 case 'b': return 2 case _: return 0 # 0 is the default case if x is not found </code></pre> <p>The <code>match</code>-<code>case</code> statement is considerably more powerful than this simple example.</p> <hr /> <p>You could use a dictionary:</p> <pre><code>def f(x): return { 'a': 1, 'b': 2, }[x] </code></pre>
<p>A switch statement is just syntactic sugar for if/elif/else. What any control statement is doing is delegating the job based on certain condition is being fulfilled - decision path. For wrapping that into a module and being able to call a job based on its unique id, one can use inheritance and the fact that any method in Python is virtual, to provide the derived class specific job implementation, as a specific &quot;case&quot; handler:</p> <pre><code>#!/usr/bin/python import sys class Case(object): &quot;&quot;&quot; Base class which specifies the interface for the &quot;case&quot; handler. The all required arbitrary arguments inside &quot;execute&quot; method will be provided through the derived class specific constructor @note in Python, all class methods are virtual &quot;&quot;&quot; def __init__(self, id): self.id = id def pair(self): &quot;&quot;&quot; Pairs the given id of the &quot;case&quot; with the instance on which &quot;execute&quot; will be called &quot;&quot;&quot; return (self.id, self) def execute(self): # Base class virtual method that needs to be overridden pass class Case1(Case): def __init__(self, id, msg): self.id = id self.msg = msg def execute(self): # Override the base class method print(&quot;&lt;Case1&gt; id={}, message: \&quot;{}\&quot;&quot;.format(str(self.id), self.msg)) class Case2(Case): def __init__(self, id, n): self.id = id self.n = n def execute(self): # Override the base class method print(&quot;&lt;Case2&gt; id={}, n={}.&quot;.format(str(self.id), str(self.n))) print(&quot;\n&quot;.join(map(str, range(self.n)))) class Switch(object): &quot;&quot;&quot; The class which delegates the jobs based on the given job id &quot;&quot;&quot; def __init__(self, cases): self.cases = cases # dictionary: time complexity for the access operation is 1 def resolve(self, id): try: cases[id].execute() except KeyError as e: print(&quot;Given id: {} is wrong!&quot;.format(str(id))) if __name__ == '__main__': # Cases cases=dict([Case1(0, &quot;switch&quot;).pair(), Case2(1, 5).pair()]) switch = Switch(cases) # id will be dynamically specified switch.resolve(0) switch.resolve(1) switch.resolve(2) </code></pre>
8,504
<p>I have a binary file that I have to parse and I'm using Python. Is there a way to take 4 bytes and convert it to a single precision floating point number?</p>
<pre><code>&gt;&gt;&gt; import struct &gt;&gt;&gt; struct.pack('f', 3.141592654) b'\xdb\x0fI@' &gt;&gt;&gt; struct.unpack('f', b'\xdb\x0fI@') (3.1415927410125732,) &gt;&gt;&gt; struct.pack('4f', 1.0, 2.0, 3.0, 4.0) '\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@' </code></pre>
<p>I would add a comment but I don't have enough reputation.</p> <p>Just to add some info. If you have a byte buffer containing X amount of floats, the syntax for unpacking would be:</p> <pre><code>struct.unpack('Xf', ...) </code></pre> <p>If the values are doubles the unpacking would be:</p> <pre><code>struct.unpack('Xd', ...) </code></pre>
2,731
<p>Is it possible to prevent an asp.net Hyperlink control from linking, i.e. so that it appears as a label, without actually having to replace the control with a label? Maybe using CSS or setting an attribute?</p> <p>I know that marking it as disabled works but then it gets displayed differently (greyed out).</p> <p>To clarify my point, I have a list of user names at the top of my page which are built dynamically using a user control. Most of the time these names are linkable to an email page. However if the user has been disabled the name is displayed in grey but currently still links to the email page. I want these disabled users to not link.</p> <p>I know that really I should be replacing them with a label but this does not seem quite as elegant as just removing the linking ability usings CSS say (if thats possible). They are already displayed in a different colour so its obvious that they are disabled users. I just need to switch off the link.</p>
<p>This sounds like a job for JQuery. Just give a specific class name to all of the HyperLink controls that you want the URLs removed and then apply the following JQuery snippet to the bottom of your page:</p> <pre><code>$(document).ready(function() { $('a.NoLink').removeAttr('href') }); </code></pre> <p>All of the HyperLink controls with the class name "NoLink" will automatically have all of their URLs removed and the link will appear to be nothing more than text.</p> <p>A single line of JQuery can solve your problem.</p>
<p>If you are using databind in asp.net handle the databinding event and just don't set the NavigateUrl if that users is disabled.</p>
7,186
<p>I'm not new to web publishing, BUT I am new to publishing against a web site that is frequently used. Previously, the apps on this server were not hit very often, but we're rolling out a high demand application. So, what is the best practice for publishing to a live web server?</p> <ol> <li>Is it best to wait until the middle of the night when people won't be on it (Yes, I can pretty much rely on that -- it's an intranet and therefore will have times of non-use)</li> <li>Publish when new updates are made to the trunk (dependent on build success of course)</li> <li>If 2 is true, then that seems bad if someone is using that specific page or DLL and it gets overwritten.</li> </ol> <p>...I'm sure there are lots of great places for this kind of thing, but I didn't use the right google search terms.</p>
<blockquote> <p><strong>@Nick DeVore wrote:</strong></p> <p>If 2 is true, then that seems bad if someone is using that specific page or DLL and it gets overwritten.</p> </blockquote> <p>It's not really an issue if you're using ASP.NET stack (Webforms, MVC or rolling your own) because all your aspx files get compiled and therefore not touched by webserver. /bin/ folder is completely shadowed somewhere else, so libraries inside are not used by webserver either.</p> <p>IIS will wait until all requests are done (however there is some timeout though) and then will proceed with compilation (if needed) and restart of AppDomain. If only a few files have changed, there won't even be AppDomain restart. IIS will load new assemblies (or compiled aspx/asmx/ascx files) into existing AppDomain.</p> <blockquote> <p><strong>@Nick DeVore wrote:</strong></p> <p>Help me understand this a little bit more. Point me to the place where this is explained from Microsoft. Thanks!</p> </blockquote> <p>Try google for &quot;IIS AppDomain&quot; keywords. I found <a href="http://www.odetocode.com/articles/305.aspx" rel="nofollow noreferrer">What ASP.NET Programmers Should Know About Application Domains</a>.</p>
<p>We do most of our updates in the wee small hours.</p> <p>Handy hint, if this is an ASP.NET site, whatever time of the day you roll out, drop in an App_Offline.htm file with a message explaining to users that the site is down for maintenance. </p> <p>Scott Guthrie has more info here:</p> <p><a href="http://weblogs.asp.net/scottgu/archive/2006/04/09/442332.aspx" rel="nofollow noreferrer">http://weblogs.asp.net/scottgu/archive/2006/04/09/442332.aspx</a></p>
3,286
<p>I have a Visual Studio Setup Project that I use to install a fairly simple WinForms application. At the end of the install I have a custom user interface page that shows a single check box which asks the user if they want to run the application. I've seen other installers do this quite often. But I cannot find a way to get the Setup Project to run an executable after the install finishes. An ideas?</p> <p>NOTE: You cannot use Custom Actions because these are used as part of the install process, I want to run my installed application once the user presses the 'Close' button at the end of the install.</p>
<p>I believe this is one of the real limitations of the Visual Studio installation project. You need to be able to modify the last page of the installation UI but VS.NET does not give you a way to do this. You could modify the tables in the .MSI after it has been built but VS.NET would probably overwrite these changes each time it is built. You may be able to override the last page using a merge module that you include in the installation project. Either way you will need to become familiar with how the UI dialogs are authored in an .MSI and this is not trivial.</p> <p>You may want to consider switching to a free script based installer or buy a commercial setup authoring application (just don't buy InstallShield for the love of Pete). Take a look at InstallAware (although I have not used it).</p>
<p>I managed it by doing invoking the Main method the assembly using the following line:</p> <pre><code>(typeof(ClassWithinAssemblyToExecute)).Assembly.EntryPoint.Invoke(null, new Object[] {} ) </code></pre>
8,546
<p>I am using the AJAX Control Toolkit Popup Calendar Control in a datagrid. When it is in the footer it looks fine. When it is in the edit side of the datagrid it is inheriting the style from the datagrid and looks completely different (i.e. too big). </p> <p>Is there a way to alter the CSS so that it does not inherit the style from the datagrid?</p>
<p>Open the page in firefox. However, first, download the firebug extension. Then, right click on the offending version and go down to inspect element.</p> <p>Firebug is awesome because it let's you navigate the css of any element. You have two options here:</p> <p>1) Assign the topmost element an css class and work it that way. or If that's not an option, you can use firebug to get the xpath to the offending element. Xpaths look like body/table/tr/td/table/tr[2]</p> <p>what you want to do with that in css is</p> <pre><code>body table tr td table tr { /*css goes here */ } </code></pre> <p>Option 1 is definitely the better pick. Option 2 is more of a dirty way of getting things done when things like asp.net doesn't let us have the fine grain of control we want.</p> <p>It would be really awesome if you used a pastebin and posted the link to your rendered page's html. </p>
<p>It uses the style from the grid, because it's in it. If you want to change it's style, change the style of the control. What do you want it to do?</p>
8,967
<p>I just bought an Ender 3 Max and from the start I knew something was wrong. I figured out the problem: it is with the first few millimeters of the Z axis movement.</p> <p>I turn on my 3D printer, go to prepare, move axis, move Z, move 1 mm.</p> <p>Then I tell the printer to move up 1 mm. But in reality it only moves up 0.3 mm. I then tell it to move up another millimeter, except it only moves up 0.4 mm. When I tell it to move up another millimeter, and it moves up only 0.45 mm. I then tell it to move up another millimeter and it moves up 0.6 mm. And then anytime after that when I say to move up a millimeter it actually moves up a millimeter. Below is a little chart to help you understand what is happening.</p> <pre><code>Set height | Actual height -------------------------- 0 | 0 1 | 0.3 2 | 0.7 3 | 1.15 4 | 1.75 5 | 2.75 6 | 3.75 7 | 4.75 8 | 5.75 9 | 6.75 10 | 7.75 </code></pre> <p>As a result of this error on my printer, the test prints I have run so far are splayed out and uneven at the bottom, making my prints warped at the first 5 mm and several millimeters shorter than they should be.</p>
<p>Your printer probably has an issue with binding in the lower region (binding means extra friction possibly causing the Z stepper to skip steps). Disconnect the lead screw an manually move the X gantry up and down. If there is binding, you need to find why this happens, with the unfortunate design of the Ender, many people experience issues when the rollers on both posts are not correctly installed.</p>
<p>The problem turned out to be that the two extruded pieces of aluminium on the z axis were too close together - I tightened the screws too tight. This made the gap between the z axis bars smaller than desired and the z movement only lifted one side of the bar in the beginning.</p> <p>After I loosed those screws holding the gantry crane on, everything works now!</p>
1,833
<p>I assume that you can't use a JavaScript code snippet to validate if the browser user has turned off JavaScript. So what can I use instead? Can someone offer a code sample?</p> <p>I'm looking to wrap an if/then statement around it.</p> <p>I often code in CFML, if that helps.</p>
<p>Use the &lt;noscript&gt; HTML tags.</p>
<p>You might have javascript execute some AJAX query and check to see if it has. Those that download the page and don't execute the query either have JS disabled or they're robots.</p>
6,691
<p><strong>Note:</strong> I <em>am</em> using SQL's Full-text search capabilities, CONTAINS clauses and all - the * is the wildcard in full-text, % is for LIKE clauses only.</p> <p>I've read in several places now that "leading wildcard" searches (e.g. using "*overflow" to match "stackoverflow") is not supported in MS SQL. I'm considering using a <a href="http://blogs.msdn.com/sqlclr/archive/2005/06/29/regex.aspx" rel="noreferrer" title="SQL CLR Blog">CLR function to add regex matching</a>, but I'm curious to see what other solutions people might have.</p> <p><strong>More Info</strong>: <a href="http://msdn.microsoft.com/en-us/library/ms552152.aspx" rel="noreferrer" title="MSDN">You can add the asterisk only at the end of the word or phrase.</a> - along with my empirical experience: When matching "myvalue", "my*" works, but "(asterisk)value" returns no match, when doing a query as simple as:</p> <pre><code>SELECT * FROM TABLENAME WHERE CONTAINS(TextColumn, '"*searchterm"'); </code></pre> <p>Thus, my need for a workaround. I'm only using search in my site on an actual search page - so it needs to work basically the same way that Google works (in the eyes on a Joe Sixpack-type user). Not nearly as complicated, but this sort of match really shouldn't fail.</p>
<p>Workaround only for leading wildcard:</p> <ul> <li>store the text reversed in a different field (or in materialised view)</li> <li>create a full text index on this column</li> <li><p>find the reversed text with an *</p> <pre><code>SELECT * FROM TABLENAME WHERE CONTAINS(TextColumnREV, '"mrethcraes*"'); </code></pre></li> </ul> <p>Of course there are many drawbacks, just for quick workaround...</p> <p>Not to mention CONTAINSTABLE...</p>
<p>% Matches any number of characters _ Matches a single character</p> <p>I've never used Full-Text indexing but you can accomplish rather complex and fast search queries with simply using the build in T-SQL string functions.</p>
2,552
<p>I have this <a href="http://www.thingiverse.com/thing:1381474" rel="noreferrer">GoPro mount for a quadcopter as STL file</a>. It looks as follows.</p> <p><a href="https://i.stack.imgur.com/qcZOR.png" rel="noreferrer"><img src="https://i.stack.imgur.com/qcZOR.png" alt="enter image description here"></a></p> <p>How do I modify it so that it is wider and longer by a few millimeters but the screw holes stay the exact same size? Additionally the angle of the upper surface must stay the same. Please suggest the easiest solution for someone like me who as no idea about CAD software.</p> <p>The perfect solution for me would be to just import it in Tinkercad and then modify it however I have no idea what the steps are.</p>
<p>Many resources are available for modification using 3D CAD (including learning a tool such as sketchup, which is VERY beginner friendly). The easiest and fastest solution to your particular problem may be the <a href="https://www.reddit.com/r/3Dprintmything/" rel="nofollow">reddit community "3D Print My Thing"</a> which was created for EXACTLY this type of situation (help with modelling parts which will be 3D printed.) Another potential useful reddit community is <a href="https://www.reddit.com/r/3Dmodeling" rel="nofollow">"3D Modelling"</a> which will have many people who are able to help you with this quadcopter/Go-Pro attachment 3D model.</p> <p>Third solution: Thingiverse has a customize option for 3D models (including this one). have you explored using this interface to edit the model? This is most likely the easiest DIY solution.</p>
<p>Well. I would cut it into two STLs, using netfabb slice / split tool.</p> <p>in 123d I would fill in the hole with the merge union (with a cylinder object), scale it, and either keep it unfilled and drill it, or do a subtraction union on where you want the holes. (again with a cylinder)</p> <p>Scaling otherwise you need the original model and solidworks.. </p> <p>Split in 2, scale the piece you want and re-add the other half is probably the best way.</p>
315
<p>Recently got an Anycubic I3 Mega Printer and I've been playing with what it can do, but after a model is done it leaves residue on the build plate behind that is bugging me. Do I NEED to remove it? If so, how? Thanks! (I'm using PLA if that matters)</p> <p>My Problem: </p> <p><a href="https://i.stack.imgur.com/pupIz.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pupIz.jpg" alt="Residue left on build plate"></a></p>
<p>You should remove it because it can and will affect the quality of future prints. Residue can mix up with new filament and create a ugly of colors and also prevent adhesion in places, thus potentially ruining your next print.</p> <p>You have several solutions to clean up the bed:</p> <ul> <li>Scrape it off: usually works, but you risk chipping the surface if you're not careful or if you stumble upon a bit of residue that is stubborn and you need to apply strength to get rid of it. I think a scraper is included with the printer.</li> <li>Sponge and soap: Since the bed cannot be removed, as far as I can tell, you'll need to make sure that the sponge isn't dripping or put towel paper around to avoid damaging the components below, including the heating unit. Rub it gently on the residue until it soften and detaches. It might take a bit to work.</li> <li><a href="https://www.kaercher.com/fr/home-garden/produits-de-nettoyage-et-d-entretien/reinigungs-pflegemittel/batterie-pour-nettoyeur-de-vitres/nettoyant-vitres/nettoyant-vitres-concentre-62953020.html" rel="nofollow noreferrer">Yellow glass cleaner from Karcher</a>: my favourite, the one I use on my printer and it never failed me. Spray it on a cloth or something, and rub it on the bed until the residue softens and detaches. It might take a bit to work, but you don't run the risk of dripping liquid on any component, and it works way better than soap and without the risk of chipping the bed like when you use a scraper.</li> </ul>
<p>I have had moderate success with a product called <a href="https://googone.com" rel="nofollow noreferrer">Goo Gone</a> (don't laugh). It quite remarkably lifts off any number of "sticky" items from various surfaces.</p> <p>I work with PLA filament that is very hard and stubborn to remove from any surface.</p> <p>I own a FlashForge Adventurer 3 that appears to have a carbon fiber build plate. Nothing, except a #11 XActo blade, can harm that. </p>
1,157
<p>I'm setting up a web application with a FreeBSD PostgreSQL back-end. I'm looking for some database performance optimization tool/technique.</p>
<p><a href="http://pgfouine.projects.postgresql.org/" rel="noreferrer">pgfouine</a> works fairly well for me. And it looks like there's a <a href="http://portsmon.freebsd.org/portoverview.py?category=databases&amp;portname=pgfouine" rel="noreferrer">FreeBSD port</a> for it.</p>
<p>DBTuna <a href="http://www.dbtuna.com/postgresql_monitor.php" rel="nofollow">http://www.dbtuna.com/postgresql_monitor.php</a> has recently started supporting PostgreSQL monitoring. We use it extensively for MySQL monitoring, so if it provides the same for Postgres then it should be a good fit for you too.</p>
5,771
<p>Right now, I keep all of my projects on my laptop. I'm thinking that I shouldn't do this, but instead use a version control system and check them in/out from an external hosting repository (Google Code, SourceForge, etc). I see several benefits here - first, I don't have to worry about losing my code if my computer crashes and burns or my external HDD crashes and burns; second, I can share my code with the world and perhaps even get more help when I need it.</p> <p>Is this a good idea? If so, what are some other project hosts that I should investigate (other than Google Code and SourceForge)?</p>
<p><strong><a href="http://www.assembla.com/" rel="nofollow noreferrer">Assembla</a></strong> is <em>awesome.</em></p> <hr> <p>EDIT: Yes, this is a good idea - I used to use a personal copy of <a href="http://www.sourcegear.com/vault/" rel="nofollow noreferrer">Vault</a> and found it was more than I cared to manage (in case my server went down or hard drive crashed - not only was it painful to worry about losing and backing up data, but the downtime). Of course, it doesn't hurt to have your own backup as well. Cover all your bases!</p>
<p>Online backup is cheap and easy. Why would you not?</p>
5,361
<p>I 3d-printed a key. <a href="https://i.stack.imgur.com/8sfuT.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/8sfuT.jpg" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/XoGY3.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/XoGY3.jpg" alt="enter image description here"></a> When I put it in the lock the pins move but, when I go to turn it the key rips and the lock doesn't turn. I compared it to the real key and it's identical. Is there something I can do to make it work and not rip? Is there some filament that I can print it out of? I used ABS.</p>
<p>I must admit, I've never printed a key...but I think I can help anyway:</p> <p><strong>Print method:</strong> Consider printing on side, solid concentric infill. Or, if you can't manipulate your infill pattern, just increase the perimeter so you get the same effect, several continuous perimeter layers around the outline of the key.</p> <p><strong>Print material:</strong></p> <ul> <li>Elongation before break is important here in addition to tensile strength...you need it to be stiff enough, but not brittle. </li> <li><strong>ABS, PLA, or HIPS:</strong> Not likely to be successful...but maybe.</li> <li><strong>PETG and PETG based filaments like T-Glase, N-Vent, nGen, INOVA-1800:</strong> A little better, but still likely to deform and/or break. <ul> <li><strong>Polycarbonate:</strong> Great for this, but is a fairly advanced material which tends to require pre-drying, enclosures, and PVA for hold down as well as a hot end that can handle at least 290C.</li> <li><strong>Nylons:</strong> Good, but most Nylons may be more "bendy" than you want for this.</li> <li><strong>Taulman's Alloy 910:</strong> Bingo. This should work nicely if you'd rather not struggle with printing polycarbonate. Alloy 910 prints near ABS settings, sticks well on a PVA-treated heated bed. (I use 85C for bed)</li> <li>I would not suggest a CF filled filament for this because they tend to be brittle. <strong>Matter Hacker's NylonX</strong> with CF is a possible exception since it's nylon based, but I haven't tested it...yet. </li> </ul></li> </ul>
<p>Which direction are the layers being printed? If the layers are printing top to bottom (in relation to your picture) there isn't a lot of sheer force required to break the key when turning. If you make the layers print from left to right you might have better luck.</p>
395
<p>I like to use static functions in C++ as a way to categorize them, like C# does.</p> <pre><code>Console::WriteLine("hello") </code></pre> <p>Is this good or bad? If the functions are used often I guess it doesn't matter, but if not do they put pressure on memory?</p> <p>What about <code>static const</code>?</p>
<blockquote> <p>but is it good or bad </p> </blockquote> <p>The first adjective that comes to mind is "unnecessary". C++ has free functions and namespaces, so why would you need to make them static functions in a class?</p> <p>The use of static methods in uninstantiable classes in C# and Java <em>is a workaround</em> because those languages don't have free functions (that is, functions that reside directly in the namespace, rather than as part of a class). C++ doesn't have that flaw. Just use a namespace.</p>
<p>For organization, use namespaces as already stated. </p> <p>For global data I like to use the <a href="http://en.wikipedia.org/wiki/Singleton_pattern" rel="nofollow noreferrer">singleton</a> pattern because it helps with the problem of the unknown initialization order of static objects. In other words, if you use the object as a singleton it is guaranteed to be initialized when its used.</p> <p>Also be sure that your static functions are stateless so that they are thread safe.</p>
5,086
<p>I have a Monoprice MP10 Mini, a cut-down Creality CR-10 with lobotomized firmware. Heated bed.</p> <p>I'm trying to do PLA prints, but have been unable to find a usable temperature.</p> <p>If I set the temperatures (either nozzle or bed) too low, the initial raft layers don't stick, the print shrivels up, and the result is a tangle.</p> <p>If I set the temperatures high enough to allow initial sticking, the raft prints okay, but after that the filament leaks out of the nozzle during long moves producing strings (only a little unsightly when outside the print area, but causing bumps when moves over the build and eventually the nozzle knocks into them) and all solid flat areas (ceilings/floors) warp.</p> <p>If I start with a high temp but reduce it during the print, the layers stop sticking to each other, solid areas still warp, and the printer eventually fails to extrude anything (presumably the filament congeals inside the extruder or tube, that's very unpleasant to recover from, fortunately I have some cleaning filament).</p> <p>Tried with multiple types of filament and multiple models (from thingiverse, converted into gcode using cura 3.6)</p> <p>What should I be trying?</p>
<p>Try bed at 50°C and hotend at 215°C, these are safe values.</p> <p>Enable retraction in the slicer, to avoid/reduce oozing during long moves, but with Bowden setups finding a good value is trickier. Try with 6 mm.</p> <p>Set the first layer height properly, but do it AFTER the bed has been heated for 5-10 minutes.</p>
<p>As @Fernando Balthazar had suggested, the z-offset was wrong. I needed to bring the nozzle and the bed closer together. The printer's default is -0.50 mm, I had to change to -0.78 mm or so to get it to stick. But then I need to reduce set it back to -0.50 or -0.40 during the print to avoid the nozzle banging into the model.</p> <p>I used 205C for nozzle and 35C for bed and it works great, virtually no warping.</p>
1,656
<p>It seems that it is impossible to capture the keyboard event normally used for copy when running a Flex application in the browser or as an AIR app, presumably because the browser or OS is intercepting it first.</p> <p>Is there a way to tell the browser or OS to let the event through?</p> <p>For example, on an AdvancedDataGrid I have set the keyUp event to handleCaseListKeyUp(event), which calls the following function:</p> <pre><code> private function handleCaseListKeyUp(event:KeyboardEvent):void { var char:String = String.fromCharCode(event.charCode).toUpperCase(); if (event.ctrlKey &amp;&amp; char == "C") { trace("Ctrl-C"); copyCasesToClipboard(); return; } if (!event.ctrlKey &amp;&amp; char == "C") { trace("C"); copyCasesToClipboard(); return; } // Didn't match event to capture, just drop out. trace("charCode: " + event.charCode); trace("char: " + char); trace("keyCode: " + event.keyCode); trace("ctrlKey: " + event.ctrlKey); trace("altKey: " + event.altKey); trace("shiftKey: " + event.shiftKey); } </code></pre> <p>When run, I can never get the release of the "C" key while also pressing the command key (which shows up as KeyboardEvent.ctrlKey). I get the following trace results:</p> <pre><code>charCode: 0 char: keyCode: 17 ctrlKey: false altKey: false shiftKey: false </code></pre> <p>As you can see, the only event I can capture is the release of the command key, the release of the "C" key while holding the command key isn't even sent.</p> <p>Has anyone successfully implemented standard copy and paste keyboard handling?</p> <p>Am I destined to just use the "C" key on it's own (as shown in the code example) or make a copy button available?</p> <p>Or do I need to create the listener manually at a higher level and pass the event down into my modular application's guts?</p>
<p>I did a test where I listened for key up events on the stage and noticed that (on my Mac) I could capture control-c, control-v, etc. just fine, but anything involving command (the  key) wasn't captured until I released the command key, and then ctrlKey was false (even though the docs says that ctrlKey should be true for the command key on the Mac), and the charCode was 0. Pretty useless, in short.</p>
<p>Another incredibly annoying thing that I just realized is that ctrl-c can't be captured by <code>event.ctrlKey &amp;&amp; event.keyCode = Keyboard.C</code> (or ...<code>event.charCode == 67</code>), instead you have to test for <code>charCode</code> or <code>keyCode</code> being <code>3</code>. It kind of makes sense for <code>charCode</code> since ctrl-c is <code>3</code> in the ASCII table, but it doesn't make sense for <code>keyCode</code>, which is supposed to represent the key on the keyboard, not the typed character. The same goes for all other key combos (because every ctrl combo has an ASCII equivalent).</p> <p><em>Edit</em> Found a bug in the Flex bug system about this: <a href="https://bugs.adobe.com/jira/browse/FP-375" rel="nofollow noreferrer">https://bugs.adobe.com/jira/browse/FP-375</a></p>
5,175
<p>I just added a fan to my printer because very small layers seem to come out very badly. For example, the 5mm PLA cube that's the top level of the test shape shown below. Watching closely, I can see that the newly-extruded fiber is pushing the previous layer(s?) around pretty freely. And when the object is finished, the little top cube is bulging, rounded, and still soft to the touch. </p> <p>The 2nd-to-top level of the object is also quite small and quick, but often comes out nicely (if anything, it was better before I added the fan).</p> <p>The fan is a squirrel-cage with about a 2.5cm square outlet, pointing at the nozzle from about 5cm away, running full speed. The extruder is a Mk9 from <a href="http://www.makergeeks.com/duexretopr.html" rel="noreferrer">http://www.makergeeks.com/duexretopr.html</a>.</p> <p>I also tried telling pronterface to wait if a level was too brief, but that setting seems not to do anything.</p> <p>What else can I try? It seems like this is a not-enough-cooling problem, but perhaps something else too?</p> <p><a href="https://i.stack.imgur.com/rKDz8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/rKDz8.png" alt="A sample step-cube"></a></p>
<h2>Layer Times</h2> <p>See my answer to <a href="https://3dprinting.stackexchange.com/questions/516/what-parameters-affect-cylinder-regularity">this question</a> and pay particular attention to my suggestion about a minimum layer print time. I'm not sure if all slicing engines provide this option, but I know MakerWare/MakerBot Desktop and (possibly) Slic3r allow this setting.</p> <p>Basically, when you're extruding smaller features like this, the previous layer(s) are still very hot and possibly very pliable. So, as your nozzle moves around above the previous layer, the nozzle may (and probably will) push some of this molten plastic around. Chances are you can see it to a certain degree while it's printing. You can definitely see this in a most drastic state if you print a tall and small diameter cylinder. You'll notice that the part will become almost exponentially unstable the higher it goes.</p> <p>By increasing the time your printer takes to print a single layer, you are allowing the previous layer(s) to cool closer to the ambient temperature of the build space, and hopefully not as molten.</p> <p>Please refer to <a href="http://www.abcgroup3.com/toolbox/mold_cooling_calc.htm" rel="nofollow noreferrer">this calculator</a> or a similar one for material cooling times. For a standard shell setting of about 2-3 (0.4mm nozzle) will yield about 130sec to cool down to room temperature. I would recommend (for ABS/PLA at least) about a 15second minimum for each layer, possibly longer depending on the size and spread out of the features.</p> <p>Also note that this can be cheated by simply printing multiple items in the same build plate with the same heights (ie. multiples of the same part). Naturally, it will take longer for the machine to print the rest of the parts and therefore allow each layer to cool slightly before being printed over.</p> <h2>Active Cooling</h2> <p>Again, some slicing engines have an Active Cooling setting. I don't personally have this option setup on my machine, but I believe it regulates the flow of air directed at your nozzle (usually by use of a mounted fan). This can help cool the layers a bit faster. With ABS, this might result in some pretty bad warping mid-print.</p> <h2>Feedrates</h2> <p>Try bringing down your feedrates to provide the printed portions of the current layer more time to cool if the above options aren't available. Note that you might also bring down your hotend temp to shorten the time it takes to cool the plastic.</p> <h2>All else fails</h2> <p>My only other suggestion is stated above, try printing duplicates on the same plate. My diagnosis is that the previous layers aren't cooling down enough before the next layer begins.</p>
<p>I believe you might be having an issue with insufficient cooling. Remember the suggestion to have wait times per layer to let the previous layer cool? Well, I think with your setup and print not only do individual layers overheat, but individual parts of each layer. You either need to try more direct or dual fan cooling or maybe use a nozzle with thinner outer diameter which will have less surface to heat the layed down plastic surrounding it.</p>
191
<p>Let's say I woke up today and wanted to create a clone of StackOverflow.com, and reap the financial windfall of millions $0.02 ad clicks. Where do I start?</p> <p>My understanding of web technologies are:</p> <ul> <li>HTML is what is ultimately displayed</li> <li>CSS is a mechanism for making HTML look pleasing </li> <li>ASP.NET lets you add functionality using .NET(?)</li> <li>JavaScript does stuff</li> <li>AJAX does asyncronous stuff</li> <li>... and the list goes on!</li> </ul> <p>To write a good website to I just need to buy seven books and read them all? Are Web 2.0 sites really the synergy of all these technologies? </p> <p>Where does someone go to get started down the path to creating professional-looking web sites, and what steps are there along the way. </p>
<p>While I have built my knowledge largely based on using the internet to search out what I want to know (w3schools.com helped a lot, as did A List Apart), a few good books have helped me along the way, though they have been platform/language-specific, so I'll avoid mentioning them unless someone is curious. For me, at least, having a book open so that I don't have to resize windows or switch between them is very valuable.</p> <p>The first part of your list is ok, but the last few items need tweaking. ASP.NET adds <em>server-side</em> functionality (for the most part) to your application. This lives outside of the browser and is thus quite powerful and easily shared with a variety of end-users.</p> <p>The problem (some say) with server-side processing is that your application must make a new HTTP request when you ask for an action to be performed. So if you click on a link to a page that yields a new set of data, you don't get instant results. The page reloads, or loads a separate page.</p> <p>Javascript solves this to a degree--it allows you to respond to user input instantaneously. Do you want to display the sum of two numbers when the user clicks a button? You can do it with Javascript.</p> <p>The problem with Javascript is that it can't talk directly to databases, or explore your server's file system, or other stuff like that. It lives in the browser--period.</p> <p>AJAX bridges the gap between your user's browser and your server. With AJAX, <em>Javascript</em> makes the HTTP request without refreshing your page or loading a new one. Javascript talks to a server-side script (not necessarily ASP, either--works with PHP, Rails, Coldfusion, etc.) and sends and receives information. And because Javascript isn't dependent on page loads, a quick, snappy AJAX script can almost give the feeling of a common desktop application, in which you don't have to wait for HTTP requests when performing simple actions on your application's data.</p>
<p>I would recommend this book:<br> <a href="https://rads.stackoverflow.com/amzn/click/com/0735623341" rel="nofollow noreferrer" rel="nofollow noreferrer">http://www.amazon.com/MCTS-Self-Paced-Training-Exam-70-528/dp/0735623341/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1218830714&amp;sr=8-1</a></p> <p>I have just read it to take the exam, and although I knew the web theory part, I found it to be of great value.<br> This of course is a ASP.NET specific book, but that is what I would recommend learning anyways. </p> <p>After you learn all the ASP.NET stuff, I would suggest reading up on <a href="http://jquery.com/" rel="nofollow noreferrer">JQuery</a>.</p> <p>Happy coding :)</p>
3,377
<p>Is there a good external merge tool for tortoisesvn (I don't particularly like the built in Merge tool). I use WinMerge for diffs, but it doesn't work with the three way merge (maybe a better question would be is there a way to force tortoisesvn to merge like tortoisecvs?)</p> <p>[Edit]</p> <p>After trying all of them, for me, the SourceGear is the one I prefer. The way to specify the DiffMerge from sourcegear is:</p> <blockquote> <p>C:\Program Files\SourceGear\DiffMerge\DiffMerge.exe /t1="My Working Version" /t2="Repository Version" /t3="Base" /r=%merged %mine %theirs %base</p> </blockquote>
<p><a href="https://www.perforce.com/product/components/perforce-visual-merge-and-diff-tools" rel="noreferrer">Perforce Merge Tool</a> </p> <p>Even though Perforce is obviously not free the merge tool is. It's 100x better than the default TortoiseSvn one. To integrate with TortoiseSvn set the merge tool to:</p> <blockquote> <p>C:\Path-To\P4Merge.exe %base %theirs %mine %merged</p> </blockquote>
<p>I like this one <a href="http://www.syntevo.com/smartsynchronize/index.html" rel="nofollow">SmartSynchronize</a> which is free for non-commercial use</p>
7,313
<p>If I pass PHP variables with <code>.</code> in their names via $_GET PHP auto-replaces them with <code>_</code> characters. For example:</p> <pre><code>&lt;?php echo "url is ".$_SERVER['REQUEST_URI']."&lt;p&gt;"; echo "x.y is ".$_GET['x.y'].".&lt;p&gt;"; echo "x_y is ".$_GET['x_y'].".&lt;p&gt;"; </code></pre> <p>... outputs the following:</p> <pre><code>url is /SpShipTool/php/testGetUrl.php?x.y=a.b x.y is . x_y is a.b. </code></pre> <p>... my question is this: is there <strong>any</strong> way I can get this to stop? Cannot for the life of me figure out what I've done to deserve this</p> <p>PHP version I'm running with is 5.2.4-2ubuntu5.3.</p>
<p>Here's PHP.net's explanation of why it does it:</p> <blockquote> <h3>Dots in incoming variable names</h3> <p>Typically, PHP does not alter the names of variables when they are passed into a script. However, it should be noted that the dot (period, full stop) is not a valid character in a PHP variable name. For the reason, look at it:</p> <pre><code>&lt;?php $varname.ext; /* invalid variable name */ ?&gt; </code></pre> <p>Now, what the parser sees is a variable named $varname, followed by the string concatenation operator, followed by the barestring (i.e. unquoted string which doesn't match any known key or reserved words) 'ext'. Obviously, this doesn't have the intended result.</p> <p>For this reason, it is important to note that PHP will automatically replace any dots in incoming variable names with underscores.</p> </blockquote> <p>That's from <a href="http://ca.php.net/variables.external" rel="noreferrer">http://ca.php.net/variables.external</a>.</p> <p>Also, according to <a href="http://ca.php.net/manual/en/language.variables.external.php#81080" rel="noreferrer">this comment</a> these other characters are converted to underscores:</p> <blockquote> <p>The full list of field-name characters that PHP converts to _ (underscore) is the following (not just dot):</p> <ul> <li>chr(32) ( ) (space)</li> <li>chr(46) (.) (dot)</li> <li>chr(91) ([) (open square bracket)</li> <li>chr(128) - chr(159) (various)</li> </ul> </blockquote> <p>So it looks like you're stuck with it, so you'll have to convert the underscores back to dots in your script using <a href="https://stackoverflow.com/questions/68651/can-i-get-php-to-stop-replacing-characters-in-get-or-post-arrays#68667">dawnerd's suggestion</a> (I'd just use <a href="http://php.net/str_replace" rel="noreferrer">str_replace</a> though.)</p>
<p>Well, the function I include below, "getRealPostArray()", isn't a pretty solution, but it handles arrays and supports both names: "alpha_beta" and "alpha.beta":</p> <pre><code> &lt;input type='text' value='First-.' name='alpha.beta[a.b][]' /&gt;&lt;br&gt; &lt;input type='text' value='Second-.' name='alpha.beta[a.b][]' /&gt;&lt;br&gt; &lt;input type='text' value='First-_' name='alpha_beta[a.b][]' /&gt;&lt;br&gt; &lt;input type='text' value='Second-_' name='alpha_beta[a.b][]' /&gt;&lt;br&gt; </code></pre> <p>whereas var_dump($_POST) produces:</p> <pre><code> 'alpha_beta' =&gt; array (size=1) 'a.b' =&gt; array (size=4) 0 =&gt; string 'First-.' (length=7) 1 =&gt; string 'Second-.' (length=8) 2 =&gt; string 'First-_' (length=7) 3 =&gt; string 'Second-_' (length=8) </code></pre> <p>var_dump( getRealPostArray()) produces:</p> <pre><code> 'alpha.beta' =&gt; array (size=1) 'a.b' =&gt; array (size=2) 0 =&gt; string 'First-.' (length=7) 1 =&gt; string 'Second-.' (length=8) 'alpha_beta' =&gt; array (size=1) 'a.b' =&gt; array (size=2) 0 =&gt; string 'First-_' (length=7) 1 =&gt; string 'Second-_' (length=8) </code></pre> <p>The function, for what it's worth:</p> <pre><code>function getRealPostArray() { if ($_SERVER['REQUEST_METHOD'] !== 'POST') {#Nothing to do return null; } $neverANamePart = '~#~'; #Any arbitrary string never expected in a 'name' $postdata = file_get_contents("php://input"); $post = []; $rebuiltpairs = []; $postraws = explode('&amp;', $postdata); foreach ($postraws as $postraw) { #Each is a string like: 'xxxx=yyyy' $keyvalpair = explode('=',$postraw); if (empty($keyvalpair[1])) { $keyvalpair[1] = ''; } $pos = strpos($keyvalpair[0],'%5B'); if ($pos !== false) { $str1 = substr($keyvalpair[0], 0, $pos); $str2 = substr($keyvalpair[0], $pos); $str1 = str_replace('.',$neverANamePart,$str1); $keyvalpair[0] = $str1.$str2; } else { $keyvalpair[0] = str_replace('.',$neverANamePart,$keyvalpair[0]); } $rebuiltpair = implode('=',$keyvalpair); $rebuiltpairs[]=$rebuiltpair; } $rebuiltpostdata = implode('&amp;',$rebuiltpairs); parse_str($rebuiltpostdata, $post); $fixedpost = []; foreach ($post as $key =&gt; $val) { $fixedpost[str_replace($neverANamePart,'.',$key)] = $val; } return $fixedpost; } </code></pre>
9,421
<p>As per <a href="https://stackoverflow.com/questions/41970/lightweight-fuzzy-search-library#41975">this</a> comment in a related thread, I'd like to know why Levenshtein distance based methods are better than Soundex.</p>
<p>Soundex is rather primitive - it was originally developed to be hand calculated. It results in a key that can be compared.</p> <p>Soundex works well with western names, as it was originally developed for US census data. It's intended for phonetic comparison.</p> <p>Levenshtein distance looks at two values and produces a value based on their similarity. It's looking for missing or substituted letters.</p> <p>Basically Soundex is better for finding that "Schmidt" and "Smith" might be the same surname.</p> <p>Levenshtein distance is better for spotting that the user has mistyped "Levnshtein" ;-)</p>
<p><a href="https://stackoverflow.com/questions/42013/levenshtein-distance-based-methods-vs-soundex#42025">@Keith</a>:</p> <p>As I posted on the other question, Daitch-Mokotoff is better for us Europeans (and I'd argue the US).</p> <p>I've also read the Wiki on Levenshtein. But I don't see why (in real life) it's <em>better</em> for the user than Soundex. </p>
6,341
<p>With all the fuss about opensource projects, how come there is still not a strong standard that enables you to make portable code (I mean in <code>C/C++</code> not <code>Java</code> or <code>C#</code>) Everyone is kind of making it's own soup.<br><br> There are even some third party libs like <code>Apache Portable Runtime</code>.</p>
<p>Yes, there is no standard but libraries like <strong>Qt</strong> and <strong>boost</strong> can make your life much easier when you do cross-platform development.</p>
<p>If you make sure it compiles cleanly with both GCC and MS VC++, it will be little extra effort to port to somewhere else.</p>
8,674
<p>When opening Adobe Acrobat Pro, whether it be through <strong>Applescript</strong> or finder, the introductory dialog is shown. Is there a way to not show this dialog without already having checked the "Don't Show Again" option when opening a document using <strong>Applescript</strong>? </p> <p>Photoshop and Illustrator <strong>Applescript</strong> libraries have ways of setting interaction levels and not showing dialogs, but I can't seem to find the option in Acrobat.</p>
<p>Copy any applicable preferences files in ~/Library/Preferences from a machine that you have checked "Don't show again" on.</p>
<p>If it's not in the dictionary, probably not.</p>
3,031
<p><strong>Disclaimer:</strong> I am not a professional 3D printer, so I'm not really familiar with how 3D printing works.</p> <p>I was thinking about trying to make a real life model of the atomic orbitals, to clearly see how the orbitals are really shaped. I thought about trying to 3D print a block, made up of colored transparent "ink", in such a way that the darkness of the color at a point in the block should be proportional to the ψ<sup>2</sup> value (probability of the electron cloud). This would print a block in which high density areas are darker than light intensity areas.</p> <p>My question is, would it be possible to design an algorithm to print a specific darkness of ink at a specific location based on the computed value of ψ<sup>2</sup>, which is obtained by solving Schrödinger's Equation. Also, would it be possible to have this fullfilled at a reasonable price to be afforded by a regular customer, such as an engineering employee?</p>
<p><strong>problem definition</strong></p> <p>I'm not quite sure if it's really question for this group. Looks like the problem itself is more for programming or physics group. Having requested calculations (electron cloud shape) resolved, there will be something to print but...</p> <p><strong>printing probability cloud</strong></p> <p>at first, please take a look for example <a href="http://3dprintingfromscratch.com/common/types-of-3d-printers-or-3d-printing-technologies-overview/" rel="nofollow noreferrer">here</a></p> <p>it's a review of 3d printing technologies. i think you should have clear picture if your idea is feasible or not.</p> <p>IMO it's not with todays technologies. in general (and deadly simlified) we have 3 main printing technics</p> <ul> <li>out of solid (or semi-solid) filaments - can be colorful and semi-transparent but it's not homogenous in terms of your needs</li> <li>out of solid powders - can be colorful but it cannot be transparent</li> <li>out of liquids - can be really transparent and color but unfortunately not colorful</li> </ul> <p>i'd say rendering but not printing is what you really need</p>
<p>I suggest you look into Polysher: <a href="http://www.polymaker.com/shop/polysmoothpolysher/" rel="nofollow noreferrer">http://www.polymaker.com/shop/polysmoothpolysher/</a> and e3D cyclops extruder <a href="https://e3d-online.com/Cyclops" rel="nofollow noreferrer">https://e3d-online.com/Cyclops</a> you can make gradients of color.</p> <p>But there might even be a smarter way to do alpha transparency than 100% infill with a transparent material:</p> <p>1) making a lattice of opaque material nodes (where bigger or closer together nodes mean more probability), and using air as the transparent medium</p> <p>2) dunking the 1) in resin</p> <p>3) making the afore-mentioned lattice with a partially transparent material and dunking it in a resin of the same refractive index as the transparent material.</p>
723
<blockquote> <h4>Moderator note:</h4> <p>This question is not a good fit for our question and answer format with the <a href="/help/on-topic">topicality rules</a> which currently apply for Stack Overflow. We normally use a &quot;historical lock&quot; for such questions where the content still has value. However, the answers on this question are actively maintained and a historical lock doesn't permit editing of the answers. As such, a &quot;wiki answer&quot; lock has been applied to allow the answers to be edited. You should assume the topicality issues which are normally handled by a historical lock are present (i.e. this question not a good example of an on-topic question for Stack Overflow).</p> </blockquote> <h2>Form-based authentication for websites</h2> <p>We believe that Stack Overflow should not just be a resource for very specific technical questions, but also for general guidelines on how to solve variations on common problems. &quot;Form based authentication for websites&quot; should be a fine topic for such an experiment.</p> <h3>It should include topics such as:</h3> <ul> <li>How to log in</li> <li>How to log out</li> <li>How to remain logged in</li> <li>Managing cookies (including recommended settings)</li> <li>SSL/HTTPS encryption</li> <li>How to store passwords</li> <li>Using secret questions</li> <li>Forgotten username/password functionality</li> <li>Use of <a href="https://en.wikipedia.org/wiki/Cryptographic_nonce" rel="nofollow noreferrer">nonces</a> to prevent <a href="https://en.wikipedia.org/wiki/Cross-site_request_forgery" rel="nofollow noreferrer">cross-site request forgeries (CSRF)</a></li> <li><a href="http://openid.net/" rel="nofollow noreferrer">OpenID</a></li> <li>&quot;Remember me&quot; checkbox</li> <li>Browser autocompletion of usernames and passwords</li> <li>Secret URLs (public <a href="https://en.wikipedia.org/wiki/Uniform_Resource_Locator" rel="nofollow noreferrer">URL</a> protected by digest)</li> <li>Checking password strength</li> <li>E-mail validation</li> <li><em>and much more about</em> <a href="http://en.wikipedia.org/wiki/Form-based_authentication" rel="nofollow noreferrer">form based authentication</a>...</li> </ul> <h3>It should not include things like:</h3> <ul> <li>Roles and authorization</li> <li>HTTP basic authentication</li> </ul> <h3>Please help us by:</h3> <ol> <li>Suggesting subtopics</li> <li>Submitting good articles about this subject</li> <li>Editing the official answer</li> </ol>
<h2>PART I: How To Log In</h2> <p>We'll assume you already know how to build a login+password HTML form which POSTs the values to a script on the server side for authentication. The sections below will deal with patterns for sound practical auth, and how to avoid the most common security pitfalls.</p> <p><strong>To HTTPS or not to HTTPS?</strong></p> <p>Unless the connection is already secure (that is, tunneled through HTTPS using SSL/TLS), your login form values will be sent in cleartext, which allows anyone eavesdropping on the line between browser and web server will be able to read logins as they pass through. This type of wiretapping is done routinely by governments, but in general, we won't address 'owned' wires other than to say this: Just use HTTPS.</p> <p>In essence, the only <strong>practical</strong> way to protect against wiretapping/packet sniffing during login is by using HTTPS or another certificate-based encryption scheme (for example, <a href="https://en.wikipedia.org/wiki/Transport_Layer_Security" rel="noreferrer">TLS</a>) or a proven &amp; tested challenge-response scheme (for example, the <a href="https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange" rel="noreferrer">Diffie-Hellman</a>-based SRP). <em>Any other method can be easily circumvented</em> by an eavesdropping attacker.</p> <p>Of course, if you are willing to get a little bit impractical, you could also employ some form of two-factor authentication scheme (e.g. the Google Authenticator app, a physical 'cold war style' codebook, or an RSA key generator dongle). If applied correctly, this could work even with an unsecured connection, but it's hard to imagine that a dev would be willing to implement two-factor auth but not SSL.</p> <p><strong>(Do not) Roll-your-own JavaScript encryption/hashing</strong></p> <p>Given the perceived (though now <a href="https://letsencrypt.org/" rel="noreferrer">avoidable</a>) cost and technical difficulty of setting up an SSL certificate on your website, some developers are tempted to roll their own in-browser hashing or encryption schemes in order to avoid passing cleartext logins over an unsecured wire.</p> <p>While this is a noble thought, it is essentially useless (and can be a <a href="https://stackoverflow.com/questions/1380168/does-it-make-security-sense-to-hash-password-on-client-end">security flaw</a>) unless it is combined with one of the above - that is, either securing the line with strong encryption or using a tried-and-tested challenge-response mechanism (if you don't know what that is, just know that it is one of the most difficult to prove, most difficult to design, and most difficult to implement concepts in digital security).</p> <p>While it is true that hashing the password <em>can be</em> effective against <strong>password disclosure</strong>, it is vulnerable to replay attacks, Man-In-The-Middle attacks / hijackings (if an attacker can inject a few bytes into your unsecured HTML page before it reaches your browser, they can simply comment out the hashing in the JavaScript), or brute-force attacks (since you are handing the attacker both username, salt and hashed password).</p> <p><strong>CAPTCHAS against humanity</strong></p> <p><a href="https://en.wikipedia.org/wiki/CAPTCHA" rel="noreferrer">CAPTCHA</a> is meant to thwart one specific category of attack: automated dictionary/brute force trial-and-error with no human operator. There is no doubt that this is a real threat, however, there are ways of dealing with it seamlessly that don't require a CAPTCHA, specifically properly designed server-side login throttling schemes - we'll discuss those later.</p> <p>Know that CAPTCHA implementations are not created alike; they often aren't human-solvable, most of them are actually ineffective against bots, all of them are ineffective against cheap third-world labor (according to <a href="https://en.wikipedia.org/wiki/OWASP" rel="noreferrer">OWASP</a>, the current sweatshop rate is $12 per 500 tests), and some implementations may be technically illegal in some countries (see <a href="https://www.owasp.org/index.php/Authentication_Cheat_Sheet" rel="noreferrer">OWASP Authentication Cheat Sheet</a>). If you must use a CAPTCHA, use Google's <a href="https://en.wikipedia.org/wiki/ReCAPTCHA" rel="noreferrer">reCAPTCHA</a>, since it is OCR-hard by definition (since it uses already OCR-misclassified book scans) and tries very hard to be user-friendly.</p> <p>Personally, I tend to find CAPTCHAS annoying, and use them only as a last resort when a user has failed to log in a number of times and throttling delays are maxed out. This will happen rarely enough to be acceptable, and it strengthens the system as a whole.</p> <p><strong>Storing Passwords / Verifying logins</strong></p> <p>This may finally be common knowledge after all the highly-publicized hacks and user data leaks we've seen in recent years, but it has to be said: Do not store passwords in cleartext in your database. User databases are routinely hacked, leaked or gleaned through SQL injection, and if you are storing raw, plaintext passwords, that is instant game over for your login security.</p> <p>So if you can't store the password, how do you check that the login+password combination POSTed from the login form is correct? The answer is hashing using a <a href="https://en.wikipedia.org/wiki/Key_derivation_function" rel="noreferrer">key derivation function</a>. Whenever a new user is created or a password is changed, you take the password and run it through a KDF, such as Argon2, bcrypt, scrypt or PBKDF2, turning the cleartext password (&quot;correcthorsebatterystaple&quot;) into a long, random-looking string, which is a lot safer to store in your database. To verify a login, you run the same hash function on the entered password, this time passing in the salt and compare the resulting hash string to the value stored in your database. Argon2, bcrypt and scrypt store the salt with the hash already. Check out this <a href="https://security.stackexchange.com/a/31846/8340">article</a> on sec.stackexchange for more detailed information.</p> <p>The reason a salt is used is that hashing in itself is not sufficient -- you'll want to add a so-called 'salt' to protect the hash against <a href="https://en.wikipedia.org/wiki/Rainbow_table" rel="noreferrer">rainbow tables</a>. A salt effectively prevents two passwords that exactly match from being stored as the same hash value, preventing the whole database being scanned in one run if an attacker is executing a password guessing attack.</p> <p>A cryptographic hash should not be used for password storage because user-selected passwords are not strong enough (i.e. do not usually contain enough entropy) and a password guessing attack could be completed in a relatively short time by an attacker with access to the hashes. This is why KDFs are used - these effectively <a href="https://en.wikipedia.org/wiki/Key_stretching" rel="noreferrer">&quot;stretch the key&quot;</a>, which means that every password guess an attacker makes causes multiple repetitions of the hash algorithm, for example 10,000 times, which causes the attacker to guess the password 10,000 times slower.</p> <p><strong>Session data - &quot;You are logged in as Spiderman69&quot;</strong></p> <p>Once the server has verified the login and password against your user database and found a match, the system needs a way to remember that the browser has been authenticated. This fact should only ever be stored server side in the session data.</p> <blockquote> <p>If you are unfamiliar with session data, here's how it works: A single randomly-generated string is stored in an expiring cookie and used to reference a collection of data - the session data - which is stored on the server. If you are using an MVC framework, this is undoubtedly handled already.</p> </blockquote> <p>If at all possible, make sure the session cookie has the secure and HTTP Only flags set when sent to the browser. The HttpOnly flag provides some protection against the cookie being read through XSS attack. The secure flag ensures that the cookie is only sent back via HTTPS, and therefore protects against network sniffing attacks. The value of the cookie should not be predictable. Where a cookie referencing a non-existent session is presented, its value should be replaced immediately to prevent <a href="https://owasp.org/www-community/attacks/Session_fixation" rel="noreferrer">session fixation</a>.</p> <p>Session state can also be maintained on the client side. This is achieved by using techniques like JWT (JSON Web Token).</p> <h2>PART II: How To Remain Logged In - The Infamous &quot;Remember Me&quot; Checkbox</h2> <p>Persistent Login Cookies (&quot;remember me&quot; functionality) are a danger zone; on the one hand, they are entirely as safe as conventional logins when users understand how to handle them; and on the other hand, they are an enormous security risk in the hands of careless users, who may use them on public computers and forget to log out, and who may not know what browser cookies are or how to delete them.</p> <p>Personally, I like persistent logins for the websites I visit on a regular basis, but I know how to handle them safely. If you are positive that your users know the same, you can use persistent logins with a clean conscience. If not - well, then you may subscribe to the philosophy that users who are careless with their login credentials brought it upon themselves if they get hacked. It's not like we go to our user's houses and tear off all those facepalm-inducing Post-It notes with passwords they have lined up on the edge of their monitors, either.</p> <p>Of course, some systems can't afford to have <em>any</em> accounts hacked; for such systems, there is no way you can justify having persistent logins.</p> <p><strong>If you DO decide to implement persistent login cookies, this is how you do it:</strong></p> <ol> <li><p>First, take some time to read <a href="https://paragonie.com/blog/2015/04/secure-authentication-php-with-long-term-persistence" rel="noreferrer">Paragon Initiative's article</a> on the subject. You'll need to get a bunch of elements right, and the article does a great job of explaining each.</p> </li> <li><p>And just to reiterate one of the most common pitfalls, <strong>DO NOT STORE THE PERSISTENT LOGIN COOKIE (TOKEN) IN YOUR DATABASE, ONLY A HASH OF IT!</strong> The login token is Password Equivalent, so if an attacker got their hands on your database, they could use the tokens to log in to any account, just as if they were cleartext login-password combinations. Therefore, use hashing (according to <a href="https://security.stackexchange.com/a/63438/5002">https://security.stackexchange.com/a/63438/5002</a> a weak hash will do just fine for this purpose) when storing persistent login tokens.</p> </li> </ol> <h2>PART III: Using Secret Questions</h2> <p><strong>Don't implement 'secret questions'</strong>. The 'secret questions' feature is a security anti-pattern. Read the paper from link number 4 from the MUST-READ list. You can ask Sarah Palin about that one, after her Yahoo! email account got hacked during a previous presidential campaign because the answer to her security question was... &quot;Wasilla High School&quot;!</p> <p>Even with user-specified questions, it is highly likely that most users will choose either:</p> <ul> <li><p>A 'standard' secret question like mother's maiden name or favorite pet</p> </li> <li><p>A simple piece of trivia that anyone could lift from their blog, LinkedIn profile, or similar</p> </li> <li><p>Any question that is easier to answer than guessing their password. Which, for any decent password, is every question you can imagine</p> </li> </ul> <p><strong>In conclusion, security questions are inherently insecure in virtually all their forms and variations, and should not be employed in an authentication scheme for any reason.</strong></p> <p>The true reason why security questions even exist in the wild is that they conveniently save the cost of a few support calls from users who can't access their email to get to a reactivation code. This at the expense of security and Sarah Palin's reputation. Worth it? Probably not.</p> <h2>PART IV: Forgotten Password Functionality</h2> <p>I already mentioned why you should <strong>never use security questions</strong> for handling forgotten/lost user passwords; it also goes without saying that you should never e-mail users their actual passwords. There are at least two more all-too-common pitfalls to avoid in this field:</p> <ol> <li><p>Don't <em>reset</em> a forgotten password to an autogenerated strong password - such passwords are notoriously hard to remember, which means the user must either change it or write it down - say, on a bright yellow Post-It on the edge of their monitor. Instead of setting a new password, just let users pick a new one right away - which is what they want to do anyway. (An exception to this might be if the users are universally using a password manager to store/manage passwords that would normally be impossible to remember without writing it down).</p> </li> <li><p>Always hash the lost password code/token in the database. <em><strong>AGAIN</strong></em>, this code is another example of a Password Equivalent, so it MUST be hashed in case an attacker got their hands on your database. When a lost password code is requested, send the plaintext code to the user's email address, then hash it, save the hash in your database -- and <em>throw away the original</em>. Just like a password or a persistent login token.</p> </li> </ol> <p>A final note: always make sure your interface for entering the 'lost password code' is at least as secure as your login form itself, or an attacker will simply use this to gain access instead. Making sure you generate very long 'lost password codes' (for example, 16 case-sensitive alphanumeric characters) is a good start, but consider adding the same throttling scheme that you do for the login form itself.</p> <h2>PART V: Checking Password Strength</h2> <p>First, you'll want to read this small article for a reality check: <a href="http://www.whatsmypass.com/?p=415" rel="noreferrer">The 500 most common passwords</a></p> <p>Okay, so maybe the list isn't the <em>canonical</em> list of most common passwords on <em>any</em> system <em>anywhere ever</em>, but it's a good indication of how poorly people will choose their passwords when there is no enforced policy in place. Plus, the list looks frighteningly close to home when you compare it to publicly available analyses of recently stolen passwords.</p> <p>So: With no minimum password strength requirements, 2% of users use one of the top 20 most common passwords. Meaning: if an attacker gets just 20 attempts, 1 in 50 accounts on your website will be crackable.</p> <p>Thwarting this requires calculating the entropy of a password and then applying a threshold. The National Institute of Standards and Technology (NIST) <a href="https://en.wikipedia.org/wiki/Password_strength#NIST_Special_Publication_800-63" rel="noreferrer">Special Publication 800-63</a> has a set of very good suggestions. That, when combined with a dictionary and keyboard layout analysis (for example, 'qwertyuiop' is a bad password), can <a href="https://cubicspot.blogspot.com/2012/01/how-to-calculate-password-strength-part.html" rel="noreferrer">reject 99% of all poorly selected passwords</a> at a level of 18 bits of entropy. Simply calculating password strength and <a href="https://blogs.dropbox.com/tech/2012/04/zxcvbn-realistic-password-strength-estimation/" rel="noreferrer">showing a visual strength meter</a> to a user is good, but insufficient. Unless it is enforced, a lot of users will most likely ignore it.</p> <p>And for a refreshing take on user-friendliness of high-entropy passwords, Randall Munroe's <a href="https://xkcd.com/936/" rel="noreferrer">Password Strength xkcd</a> is highly recommended.</p> <p>Utilize Troy Hunt's <a href="https://haveibeenpwned.com/API/" rel="noreferrer">Have I Been Pwned API</a> to check users passwords against passwords compromised in public data breaches.</p> <h2>PART VI: Much More - Or: Preventing Rapid-Fire Login Attempts</h2> <p>First, have a look at the numbers: <a href="https://www.lockdown.co.uk/?pg=combi&amp;s=articles" rel="noreferrer">Password Recovery Speeds - How long will your password stand up</a></p> <p>If you don't have the time to look through the tables in that link, here's the list of them:</p> <ol> <li><p>It takes <em>virtually no time</em> to crack a weak password, even if you're cracking it with an abacus</p> </li> <li><p>It takes <em>virtually no time</em> to crack an alphanumeric 9-character password if it is <strong>case insensitive</strong></p> </li> <li><p>It takes <em>virtually no time</em> to crack an intricate, symbols-and-letters-and-numbers, upper-and-lowercase password if it is <strong>less than 8 characters long</strong> (a desktop PC can search the entire keyspace up to 7 characters in a matter of days or even hours)</p> </li> <li><p><strong>It would, however, take an inordinate amount of time to crack even a 6-character password, <em>if you were limited to one attempt per second!</em></strong></p> </li> </ol> <p>So what can we learn from these numbers? Well, lots, but we can focus on the most important part: the fact that preventing large numbers of rapid-fire successive login attempts (ie. the <em>brute force</em> attack) really isn't that difficult. But preventing it <em>right</em> isn't as easy as it seems.</p> <p>Generally speaking, you have three choices that are all effective against brute-force attacks <em>(and dictionary attacks, but since you are already employing a strong passwords policy, they shouldn't be an issue)</em>:</p> <ul> <li><p>Present a <strong>CAPTCHA</strong> after N failed attempts (annoying as hell and often ineffective -- but I'm repeating myself here)</p> </li> <li><p><strong>Locking accounts</strong> and requiring email verification after N failed attempts (this is a <a href="https://en.wikipedia.org/wiki/Denial-of-service_attack" rel="noreferrer">DoS</a> attack waiting to happen)</p> </li> <li><p>And finally, <strong>login throttling</strong>: that is, setting a time delay between attempts after N failed attempts (yes, DoS attacks are still possible, but at least they are far less likely and a lot more complicated to pull off).</p> </li> </ul> <p><strong>Best practice #1:</strong> A short time delay that increases with the number of failed attempts, like:</p> <ul> <li>1 failed attempt = no delay</li> <li>2 failed attempts = 2 sec delay</li> <li>3 failed attempts = 4 sec delay</li> <li>4 failed attempts = 8 sec delay</li> <li>5 failed attempts = 16 sec delay</li> <li>etc.</li> </ul> <p>DoS attacking this scheme would be very impractical, since the resulting lockout time is slightly larger than the sum of the previous lockout times.</p> <blockquote> <p>To clarify: The delay is <em>not</em> a delay before returning the response to the browser. It is more like a timeout or refractory period during which login attempts to a specific account or from a specific IP address will not be accepted or evaluated at all. That is, correct credentials will not return in a successful login, and incorrect credentials will not trigger a delay increase.</p> </blockquote> <p><strong>Best practice #2:</strong> A medium length time delay that goes into effect after N failed attempts, like:</p> <ul> <li>1-4 failed attempts = no delay</li> <li>5 failed attempts = 15-30 min delay</li> </ul> <p>DoS attacking this scheme would be quite impractical, but certainly doable. Also, it might be relevant to note that such a long delay can be very annoying for a legitimate user. Forgetful users will dislike you.</p> <p><strong>Best practice #3:</strong> Combining the two approaches - either a fixed, short time delay that goes into effect after N failed attempts, like:</p> <ul> <li>1-4 failed attempts = no delay</li> <li>5+ failed attempts = 20 sec delay</li> </ul> <p>Or, an increasing delay with a fixed upper bound, like:</p> <ul> <li>1 failed attempt = 5 sec delay</li> <li>2 failed attempts = 15 sec delay</li> <li>3+ failed attempts = 45 sec delay</li> </ul> <p>This final scheme was taken from the OWASP best-practices suggestions (link 1 from the MUST-READ list) and should be considered best practice, even if it is admittedly on the restrictive side.</p> <blockquote> <p><em>As a rule of thumb, however, I would say: the stronger your password policy is, the less you have to bug users with delays. If you require strong (case-sensitive alphanumerics + required numbers and symbols) 9+ character passwords, you could give the users 2-4 non-delayed password attempts before activating the throttling.</em></p> </blockquote> <p>DoS attacking this final login throttling scheme would be <em><strong>very</strong></em> impractical. And as a final touch, always allow persistent (cookie) logins (and/or a CAPTCHA-verified login form) to pass through, so legitimate users won't even be delayed <em>while the attack is in progress</em>. That way, the very impractical DoS attack becomes an <em>extremely</em> impractical attack.</p> <p>Additionally, it makes sense to do more aggressive throttling on admin accounts, since those are the most attractive entry points</p> <h2>PART VII: Distributed Brute Force Attacks</h2> <p>Just as an aside, more advanced attackers will try to circumvent login throttling by 'spreading their activities':</p> <ul> <li><p>Distributing the attempts on a botnet to prevent IP address flagging</p> </li> <li><p>Rather than picking one user and trying the 50.000 most common passwords (which they can't, because of our throttling), they will pick THE most common password and try it against 50.000 users instead. That way, not only do they get around maximum-attempts measures like CAPTCHAs and login throttling, their chance of success increases as well, since the number 1 most common password is far more likely than number 49.995</p> </li> <li><p>Spacing the login requests for each user account, say, 30 seconds apart, to sneak under the radar</p> </li> </ul> <p>Here, the best practice would be <strong>logging the number of failed logins, system-wide</strong>, and using a running average of your site's bad-login frequency as the basis for an upper limit that you then impose on all users.</p> <p>Too abstract? Let me rephrase:</p> <p>Say your site has had an average of 120 bad logins per day over the past 3 months. Using that (running average), your system might set the global limit to 3 times that -- ie. 360 failed attempts over a 24 hour period. Then, if the total number of failed attempts across all accounts exceeds that number within one day (or even better, monitor the rate of acceleration and trigger on a calculated threshold), it activates system-wide login throttling - meaning short delays for ALL users (still, with the exception of cookie logins and/or backup CAPTCHA logins).</p> <p>I also posted a question with <a href="https://stackoverflow.com/questions/479233/what-is-the-best-distributed-brute-force-countermeasure">more details and a really good discussion of how to avoid tricky pitfals</a> in fending off distributed brute force attacks</p> <h2>PART VIII: Two-Factor Authentication and Authentication Providers</h2> <p>Credentials can be compromised, whether by exploits, passwords being written down and lost, laptops with keys being stolen, or users entering logins into phishing sites. Logins can be further protected with two-factor authentication, which uses out-of-band factors such as single-use codes received from a phone call, SMS message, app, or dongle. Several providers offer two-factor authentication services.</p> <p>Authentication can be completely delegated to a single-sign-on service, where another provider handles collecting credentials. This pushes the problem to a trusted third party. Google and Twitter both provide standards-based SSO services, while Facebook provides a similar proprietary solution.</p> <h2>MUST-READ LINKS About Web Authentication</h2> <ol> <li><a href="https://www.owasp.org/index.php/Authentication_Cheat_Sheet" rel="noreferrer">OWASP Guide To Authentication</a> / <a href="https://www.owasp.org/index.php/Authentication_Cheat_Sheet" rel="noreferrer">OWASP Authentication Cheat Sheet</a></li> <li><a href="https://pdos.csail.mit.edu/papers/webauth:sec10.pdf" rel="noreferrer">Dos and Don’ts of Client Authentication on the Web (very readable MIT research paper)</a></li> <li><a href="https://en.wikipedia.org/wiki/HTTP_cookie#Drawbacks_of_cookies" rel="noreferrer">Wikipedia: HTTP cookie</a></li> <li><a href="https://cups.cs.cmu.edu/soups/2008/proceedings/p13Rabkin.pdf" rel="noreferrer">Personal knowledge questions for fallback authentication: Security questions in the era of Facebook (very readable Berkeley research paper)</a></li> </ol>
<p>Use <a href="http://openid.net/connect/" rel="noreferrer">OpenID Connect</a> or <a href="https://kantarainitiative.org/confluence/display/uma/Home" rel="noreferrer">User-Managed Access</a>.</p> <p>As nothing is more efficient than not doing it at all.</p>
2,296
<p>We have a situation in our product where for a long time some data has been stored in the application's database as SQL string (choice of MS SQL server or sybase SQL anywhere) which was encrypted via the Windows API function <a href="http://msdn.microsoft.com/en-us/library/aa379924.aspx" rel="nofollow noreferrer">CryptEncrypt.</a> (direct and de-cryptable)</p> <p>The problem is that CryptEncrypt can produce NULL's in the output, meaning that when it's stored in the database, the string manipulations will at some point truncate the CipherText.</p> <p>Ideally we'd like to use an algo that will produce CipherText that doesn't contain NULLs as that will cause the least amount of change to the existing databases (changing a column from string to binary and code to deal with binary instead of strings) and just decrypt existing data and re-encrypt with the new algorithm at database upgrade time.</p> <p>The algorithm doesn't need to be the most secure, as the database is already in a reasonably secure environment (not an open network / the inter-webs) but does need to be better than ROT13 (which I can almost decrypt in my head now!)</p> <p>edit: btw, any particular reason for changing ciphertext to cyphertext? ciphertext seems more widely used...</p>
<p>Any semi-decent algorithm will end up with a strong chance of generating a NULL value somewhere in the resulting ciphertext.</p> <p>Why not do something like <a href="http://en.wikipedia.org/wiki/Base64" rel="nofollow noreferrer">base-64 encode</a> your resulting binary blob before persisting to the DB? (<a href="http://synesis.com.au/software/b64.html" rel="nofollow noreferrer">sample implementation in C++</a>).</p>
<p>That's an interesting route OJ. We're looking at the feasability of a non-reversable method (still making sure we don't explicitly retrieve the data to decrypt) e.g. just store a Hash to compare on a submission</p>
3,825
<p>Is there any <strong>simple algorithm</strong> to determine the likeliness of 2 names representing the same person? </p> <p>I'm not asking for something of the level that Custom department might be using. Just a simple algorithm that would tell me if 'James T. Clark' is most likely the same name as 'J. Thomas Clark' or 'James Clerk'.</p> <p>If there is an algorithm in <code>C#</code> that would be great, but I can translate from any language.</p>
<p>I've faced similar problem and tried to use Levenstein distance first, but it did not work well for me. I came up with an algorithm that gives you "similarity" value between two strings (higher value means more similar strings, "1" for identical strings). This value is not very meaningful by itself (if not "1", always 0.5 or less), but works quite well when you throw in Hungarian Matrix to find matching pairs from two lists of strings.</p> <p>Use like this:</p> <pre><code>PartialStringComparer cmp = new PartialStringComparer(); tbResult.Text = cmp.Compare(textBox1.Text, textBox2.Text).ToString(); </code></pre> <p>The code behind:</p> <pre><code>public class SubstringRange { string masterString; public string MasterString { get { return masterString; } set { masterString = value; } } int start; public int Start { get { return start; } set { start = value; } } int end; public int End { get { return end; } set { end = value; } } public int Length { get { return End - Start; } set { End = Start + value;} } public bool IsValid { get { return MasterString.Length &gt;= End &amp;&amp; End &gt;= Start &amp;&amp; Start &gt;= 0; } } public string Contents { get { if(IsValid) { return MasterString.Substring(Start, Length); } else { return ""; } } } public bool OverlapsRange(SubstringRange range) { return !(End &lt; range.Start || Start &gt; range.End); } public bool ContainsRange(SubstringRange range) { return range.Start &gt;= Start &amp;&amp; range.End &lt;= End; } public bool ExpandTo(string newContents) { if(MasterString.Substring(Start).StartsWith(newContents, StringComparison.InvariantCultureIgnoreCase) &amp;&amp; newContents.Length &gt; Length) { Length = newContents.Length; return true; } else { return false; } } } public class SubstringRangeList: List&lt;SubstringRange&gt; { string masterString; public string MasterString { get { return masterString; } set { masterString = value; } } public SubstringRangeList(string masterString) { this.MasterString = masterString; } public SubstringRange FindString(string s){ foreach(SubstringRange r in this){ if(r.Contents.Equals(s, StringComparison.InvariantCultureIgnoreCase)) return r; } return null; } public SubstringRange FindSubstring(string s){ foreach(SubstringRange r in this){ if(r.Contents.StartsWith(s, StringComparison.InvariantCultureIgnoreCase)) return r; } return null; } public bool ContainsRange(SubstringRange range) { foreach(SubstringRange r in this) { if(r.ContainsRange(range)) return true; } return false; } public bool AddSubstring(string substring) { bool result = false; foreach(SubstringRange r in this) { if(r.ExpandTo(substring)) { result = true; } } if(FindSubstring(substring) == null) { bool patternfound = true; int start = 0; while(patternfound){ patternfound = false; start = MasterString.IndexOf(substring, start, StringComparison.InvariantCultureIgnoreCase); patternfound = start != -1; if(patternfound) { SubstringRange r = new SubstringRange(); r.MasterString = this.MasterString; r.Start = start++; r.Length = substring.Length; if(!ContainsRange(r)) { this.Add(r); result = true; } } } } return result; } private static bool SubstringRangeMoreThanOneChar(SubstringRange range) { return range.Length &gt; 1; } public float Weight { get { if(MasterString.Length == 0 || Count == 0) return 0; float numerator = 0; int denominator = 0; foreach(SubstringRange r in this.FindAll(SubstringRangeMoreThanOneChar)) { numerator += r.Length; denominator++; } if(denominator == 0) return 0; return numerator / denominator / MasterString.Length; } } public void RemoveOverlappingRanges() { SubstringRangeList l = new SubstringRangeList(this.MasterString); l.AddRange(this);//create a copy of this list foreach(SubstringRange r in l) { if(this.Contains(r) &amp;&amp; this.ContainsRange(r)) { Remove(r);//try to remove the range if(!ContainsRange(r)) {//see if the list still contains "superset" of this range Add(r);//if not, add it back } } } } public void AddStringToCompare(string s) { for(int start = 0; start &lt; s.Length; start++) { for(int len = 1; start + len &lt;= s.Length; len++) { string part = s.Substring(start, len); if(!AddSubstring(part)) break; } } RemoveOverlappingRanges(); } } public class PartialStringComparer { public float Compare(string s1, string s2) { SubstringRangeList srl1 = new SubstringRangeList(s1); srl1.AddStringToCompare(s2); SubstringRangeList srl2 = new SubstringRangeList(s2); srl2.AddStringToCompare(s1); return (srl1.Weight + srl2.Weight) / 2; } } </code></pre> <p>Levenstein distance one is much simpler (adapted from <a href="http://www.merriampark.com/ld.htm" rel="nofollow noreferrer">http://www.merriampark.com/ld.htm</a>):</p> <pre><code>public class Distance { /// &lt;summary&gt; /// Compute Levenshtein distance /// &lt;/summary&gt; /// &lt;param name="s"&gt;String 1&lt;/param&gt; /// &lt;param name="t"&gt;String 2&lt;/param&gt; /// &lt;returns&gt;Distance between the two strings. /// The larger the number, the bigger the difference. /// &lt;/returns&gt; public static int LD(string s, string t) { int n = s.Length; //length of s int m = t.Length; //length of t int[,] d = new int[n + 1, m + 1]; // matrix int cost; // cost // Step 1 if(n == 0) return m; if(m == 0) return n; // Step 2 for(int i = 0; i &lt;= n; d[i, 0] = i++) ; for(int j = 0; j &lt;= m; d[0, j] = j++) ; // Step 3 for(int i = 1; i &lt;= n; i++) { //Step 4 for(int j = 1; j &lt;= m; j++) { // Step 5 cost = (t.Substring(j - 1, 1) == s.Substring(i - 1, 1) ? 0 : 1); // Step 6 d[i, j] = System.Math.Min(System.Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1), d[i - 1, j - 1] + cost); } } // Step 7 return d[n, m]; } } </code></pre>
<p>I doubt there is, considering even the <a href="http://www.upgradetravelbetter.com/2008/09/14/tired-of-secondary-screenings-change-your-name/" rel="nofollow noreferrer">Customs Department doesn't seem to have a satisfactory answer</a>...</p>
9,390
<p>Is there an equivalent of svn's blame for Perforce on the command line? <code>p4 annotate</code> doesn't display usernames -- only changeset numbers (without ancestor history!).</p> <p>I currently have to track code back through ancestors and compare against the filelog, and there just has to be an easier way -- maybe a F/OSS utility?</p>
<p>I'm not overly familiar with the blame command, but I assume that you are looking for who changes a particular line of code. The easiest way is to use Perforce's 'time lapse view' available from both p4win and p4v.</p> <p>This tool uses annotate and some other commands to give you a view of the code line over time. You can see who modified what code, when it was inserted or removed from the codeline, etc. </p> <p>It's not command line though. I checked briefly in the help and there doesnt' seem to be a way to launch the time lapse view directly from a p4win or p4v invocation. There might be though...I'll be checking further...</p> <p>Edit: I checked with support, and you can launch the timelapse view through p4v as follows:</p> <pre><code>p4v.exe -cmd "annotate //&lt;path/to/file&gt;" </code></pre> <p>HTH.</p>
<p>@alanw123: p4pr is close to what I'm looking for, but it doesn't cross branch boundaries:</p> <pre><code>last if $type eq 'branch'; </code></pre> <p>That was the main problem I had when I tried writing my own utility -- you can't (easily) tell how the lines map back to the file that was branched from.</p>
8,169
<p>I'm currently working on a parser for our internal log files (generated by log4php, log4net and log4j). So far I have a nice regular expression to parse the logs, except for one annoying bit: Some log messages span multiple lines, which I can't get to match properly. The regex I have now is this:</p> <pre><code>(?&lt;date&gt;\d{2}/\d{2}/\d{2})\s(?&lt;time&gt;\d{2}):\d{2}:\d{2}),\d{3})\s(?&lt;message&gt;.+) </code></pre> <p>The log format (which I use for testing the parser) is this:</p> <pre><code>07/23/08 14:17:31,321 log message spanning multiple lines 07/23/08 14:17:31,321 log message on one line </code></pre> <p>When I run the parser right now, I get only the line the log starts on. If I change it to span multiple lines, I get only one result (the whole log file).</p> <hr> <p>@samjudson:</p> <p><em>You need to pass the RegexOptions.Singleline flag in to the regular expression, so that "." matches all characters, not just all characters except new lines (which is the default).</em></p> <p>I tried that, but then it matches the whole file. I also tried to set the message-group to .+? (non-greedy), but then it matches a single character (which isn't what I'm looking for either).</p> <p>The problem is that the pattern for the message matches on the date-group as well, so when it doesn't break on a new-line it just goes on and on and on.</p> <hr> <p>I use this regex for the message group now. It works, unless there's a pattern IN the log message which is the same as the start of the log message.</p> <pre><code>(?&lt;message&gt;(.(?!\d{2}/\d{2}/\d{2}\s\d{2}:\d{2}:\d{2},\d{3}\s\[\d{4}\]))+) </code></pre>
<p>This will only work if the log message doesn't contain a date at the beginning of the line, but you could try adding a negative look-ahead assertion for a date in the "message" group:</p> <pre><code>(?&lt;date&gt;\d{2}/\d{2}/\d{2})\s(?&lt;time&gt;\d{2}:\d{2}:\d{2},\d{3})\s(?&lt;message&gt;(.(?!^\d{2}/\d{2}/ \d{2}))+) </code></pre> <p>Note that this requires the use of the RegexOptions.MultiLine flag.</p>
<p>You need to pass the <code>RegexOptions</code>. Singleline flag in to the regular expression, so that "." matches all characters, not just all characters except new lines (which is the default).</p>
6,270
<p>Python frameworks always provide ways to handle URLs that convey the data of the request in an elegant way, like for example <a href="http://somewhere.overtherainbow.com/userid/123424/" rel="noreferrer">http://somewhere.overtherainbow.com/userid/123424/</a></p> <p>I want you to notice the ending path <strong>/userid/123424/</strong></p> <p>How do you do this in ASP.NET?</p>
<p>This example uses ASP.NET Routing to implement friendly URLs. </p> <p>Examples of the mappings that the application handles are: </p> <p><a href="http://samplesite/userid/1234" rel="noreferrer">http://samplesite/userid/1234</a> - <a href="http://samplesite/users.aspx?userid=1234" rel="noreferrer">http://samplesite/users.aspx?userid=1234</a><br> <a href="http://samplesite/userid/1235" rel="noreferrer">http://samplesite/userid/1235</a> - <a href="http://samplesite/users.aspx?userid=1235" rel="noreferrer">http://samplesite/users.aspx?userid=1235</a> </p> <p>This example uses querystrings and avoids any requirement to modify the code on the aspx page. </p> <h1>Step 1 - add the necessary entries to web.config</h1> <pre><code>&lt;system.web&gt; &lt;compilation debug="true"&gt; &lt;assemblies&gt; … &lt;add assembly="System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/&gt; &lt;/assemblies&gt; &lt;/compilation&gt; … &lt;httpModules&gt; … &lt;add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /&gt; &lt;/httpModules&gt; &lt;/system.web&gt; &lt;system.webServer&gt; … &lt;modules&gt; … &lt;add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/&gt; &lt;/modules&gt; &lt;handlers … &lt;add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/&gt; &lt;/handlers&gt; &lt;/system.webServer&gt; </code></pre> <h1>Step 2 - add a routing table in global.asax</h1> <p>Define the mapping from the friendly URL to the aspx page, saving the requested userid for later use. </p> <pre><code>void Application_Start(object sender, EventArgs e) { RegisterRoutes(RouteTable.Routes); } public static void RegisterRoutes(RouteCollection routes) { routes.Add("UseridRoute", new Route ( "userid/{userid}", new CustomRouteHandler("~/users.aspx") )); } </code></pre> <h1>Step 3 - implement the route handler</h1> <p>Add the querystring to the current context before the routing takes place. </p> <pre><code>using System.Web.Compilation; using System.Web.UI; using System.Web; using System.Web.Routing; public class CustomRouteHandler : IRouteHandler { public CustomRouteHandler(string virtualPath) { this.VirtualPath = virtualPath; } public string VirtualPath { get; private set; } public IHttpHandler GetHttpHandler(RequestContext requestContext) { // Add the querystring to the URL in the current context string queryString = "?userid=" + requestContext.RouteData.Values["userid"]; HttpContext.Current.RewritePath( string.Concat( VirtualPath, queryString)); var page = BuildManager.CreateInstanceFromVirtualPath (VirtualPath, typeof(Page)) as IHttpHandler; return page; } } </code></pre> <h1>Code from users.aspx</h1> <p>The code on the aspx page for reference. </p> <pre><code>protected void Page_Load(object sender, EventArgs e) { string id = Page.Request.QueryString["userid"]; switch (id) { case "1234": lblUserId.Text = id; lblUserName.Text = "Bill"; break; case "1235": lblUserId.Text = id; lblUserName.Text = "Claire"; break; case "1236": lblUserId.Text = id; lblUserName.Text = "David"; break; default: lblUserId.Text = "0000"; lblUserName.Text = "Unknown"; break; } </code></pre>
<p>Also, check out ASP.NET MVC or if you're set on webforms, the new System.Web.Routing namespace in ASP.NET 3.5 SP1</p>
6,720
<p>What is the best solution for maintaining backup and revision control on live websites?</p> <p>As part of my job I work with several live websites. We need an efficient means of maintaining backups of the live folders over time. Additionally, updating these sites can be a pain, especially if a change happens to break in the live environment for whatever reason.</p> <p>What would be ideal would be hassle-free source control. I implemented SVN for a while which was great as a semi-solution for backup as well as revision control (easy reversion of temporary or breaking changes) etc.</p> <p>Unfortunately SVN places .SVN hidden directories everywhere which cause problems, especially when other developers make folder structure changes or copy/move website directories. I've heard the argument that this is a matter of education etc. but the approach taken by SVN is simply not a practical solution for us.</p> <p>I am thinking that maybe an incremental backup solution may be better.</p> <p>Other possibilities include:</p> <ol> <li><a href="http://svk.bestpractical.com/view/HomePage" rel="nofollow noreferrer">SVK</a>, which is command-line only which becomes a problem. Besides, I am unsure on how appropriate this would be.</li> <li><p><a href="http://www.selenic.com/mercurial/wiki/" rel="nofollow noreferrer">Mercurial</a>, perhaps with some triggers to hide the distributed component which is not required in this case and would be unnecessarily complicated for other developers. </p> <p>I experimented briefly with Mercurial but couldn't find a nice way to have the repository seperate and kept constantly in-sync with the live folder working copy. Maybe as a source control solution (making repository and live folder the same place) combined with another backup solution this could be the way to go. </p> <p>One downside of Mercurial is that it doesn't place empty folders under source control which is problematic for websites which often have empty folders as placeholder locations for file uploads etc.</p></li> <li><a href="http://samba.anu.edu.au/rsync/" rel="nofollow noreferrer">Rsync</a>, which I haven't really investigated.</li> </ol> <p>I'd really appreciate your advice on the best way to maintain backups of live websites, ideally with an easy means of retrieving past versions quickly.</p> <p><strong>Answer replies:</strong></p> <ul> <li><p><em>@Kibbee</em>: </p> <ul> <li><p>It's not so much about education as no familiarity with anything but VSS and a lack of time/effort to learn anything else. </p></li> <li><p>The xcopy/7-zip approach sounds reasonable I guess but it would quickly take up a lot of room right? </p></li> <li><p>As far as source control, I think I'd like the source control to just say that "this is the state of the folder now, I'll deal with that and if I can't match stuff up that's your fault, I'll just start new histories" rather than fail hard.</p></li> </ul></li> <li><p><em>@Steve M</em>: </p> <ul> <li>Yeah that's a nicer way of doing it but would require a significant cultural change. Having said that I very much like this approach. </li> </ul></li> <li><p><em>@mk</em>:</p> <ul> <li>Nice, I didn't think about using Rsync to deploy. Does this only upload the differences? Overwriting the entire live directory everytime we make a change would be problematic due to site downtime.</li> </ul></li> </ul> <p>I am still curious to see if there are any more traditional options</p>
<p>You can still use SVN, but instead of doing a checkout on your live environment, do an export, that way no .svn directories will be created. The downside, of course, is that no code changes on your live environment can take place. This is a good thing.</p> <p>As a general rule, code changes on production systems should never be allowed. The change should be made and tested in a development/test/UAT environment, then once confirmed as OK, you can tag that code in SVN with something like RELEASE-x-x-x. Then, on the live system, export the code with that tag.</p>
<p>Any source control solution you pick is going to have problems if people are moving, deleting, or adding files and not telling the source control system about it. I'm not aware of any source control item that could solve this problem. </p> <p>In the case where you just can't educate the people working on the project[1], then you may just have to go with daily snapshots. Something as simple as batch file using xcopy to a network drive, and possibly 7-zip on the command line to compress it so it doesn't take up too much space would probably be the simplest solution.</p> <p>[1] I would highly disbelieve this, probably just more a case of people being too stubborn and not willing to learn, or do "extra work". Nevermind how much time source control could save them when they have to go back to previous versions, or 2 people have edited the same file.</p>
4,695
<p>Google is not being my friend - it's been a long time since my stats class in college...I need to calculate the start and end points for a trendline on a graph - is there an easy way to do this? (working in C# but whatever language works for you)</p>
<p>OK, here's my best pseudo math:</p> <p>The equation for your line is:</p> <p>Y = a + bX</p> <p>Where:</p> <p>b = (sum(x*y) - sum(x)sum(y)/n) / (sum(x^2) - sum(x)^2/n)</p> <p>a = sum(y)/n - b(sum(x)/n)</p> <p>Where sum(xy) is the sum of all x*y etc. Not particularly clear I concede, but it's the best I can do without a sigma symbol :)</p> <p>... and now with added Sigma</p> <p>b = (&Sigma;(xy) - (&Sigma;x&Sigma;y)/n) / (&Sigma;(x^2) - (&Sigma;x)^2/n)</p> <p>a = (&Sigma;y)/n - b((&Sigma;x)/n)</p> <p>Where &Sigma;(xy) is the sum of all x*y etc. and n is the number of points</p>
<p>Thank You so much for the solution, I was scratching my head.<br> Here's how I applied the solution in Excel.<br> I successfully used the two functions given by MUHD in Excel:<br> a = (sum(x*y) - sum(x)sum(y)/n) / (sum(x^2) - sum(x)^2/n)<br> b = sum(y)/n - b(sum(x)/n)<br> (careful my a and b are the b and a in MUHD's solution).<br> <br> - Made 4 columns, for example:<br> NB: my values y values are in B3:B17, so I have n=15;<br> my x values are 1,2,3,4...15.<br> 1. Column B: Known x's<br> 2. Column C: Known y's<br> 3. Column D: The computed trend line<br> 4. Column E: B values * C values (E3=B3*C3, E4=B4*C4, ..., E17=B17*C17)<br> 5. Column F: x squared values<br> I then sum the columns B,C and E, the sums go in line 18 for me, so I have B18 as sum of Xs, C18 as sum of Ys, E18 as sum of X*Y, and F18 as sum of squares.<br> To compute a, enter the followin formula in any cell (F35 for me):<br> F35=(E18-(B18*C18)/15)/(F18-(B18*B18)/15)<br> To compute b (in F36 for me):<br> F36=C18/15-F35*(B18/15)<br> Column D values, computing the trend line according to the y = ax + b:<br> D3=$F$35*B3+$F$36, D4=$F$35*B4+$F$36 and so on (until D17 for me).<br> <br> Select the column datas (C2:D17) to make the graph.<br> HTH.</p>
6,483
<p>I have some code that gives a user id to a utility that then send email to that user.</p> <pre><code>emailUtil.sendEmail(userId, "foo"); public void sendEmail(String userId, String message) throws MailException { /* ... logic that could throw a MailException */ } </code></pre> <p><code>MailException</code> could be thrown for a number of reasons, problems with the email address, problems with the mail template etc.</p> <p>My question is this: do you create a new Exception type for every one of these exceptions and then deal with them individually or do you create one MailException and then store something in the exception (something computer-readable, not the description text) that allows us to do different things based on what actually happened.</p> <p><strong>Edit:</strong> As a clarification, the exceptions aren't for logs and what-not, this relates to how code reacts to them. To keep going with the mail example, let's say that when we send mail it could fail because you don't have an email address, or it could because you don't have a <strong>valid</strong> email address, or it could fail.. etc.</p> <p>My code would want to react differently to each of these issues (mostly by changing the message returned to the client, but actual logic as well).</p> <p>Would it be best to have an exception implementation for each one of these issues or one umbrella exception that had something internal to it (an enum say) that let the code distinguish what kind of issue it was.</p>
<p>I usually start with a general exception and subclass it as needed. I always can catch the general exception (and with it all subclassed exceptions) if needed, but also the specific.</p> <p>An example from the Java-API is IOException, that has subclasses like FileNotFoundException or EOFException (and much more).</p> <p>This way you get the advantages of both, you don't have throw-clauses like:</p> <pre><code>throws SpecificException1, SpecificException2, SpecificException3 ... </code></pre> <p>a general</p> <pre><code>throws GeneralException </code></pre> <p>is enough. But if you want to have a special reaction to special circumstances you can always catch the specific exception.</p>
<p>I would just go by</p> <pre><code>throw new exception("WhatCausedIt") </code></pre> <p>if you want to handle your exceptions, you could pass a code instead of "WhatCausedIt" an then react to the different answers with a switch statement. </p>
4,179
<p>This most be the second most simple rollover effect, still I don't find any simple solution.</p> <p><strong>Wanted:</strong> I have a list of items and a corresponding list of slides (DIVs). After loading, the first list item should be selected (bold) and the first slide should be visible. When the user hovers over another list item, that list item should be selected instead and the corresponding slide be shown.</p> <p>The following code works, but <em>is awful</em>. How can I get this behaviour in an elegant way? jquery has dozens of animated and complicated rollover effects, but I didn't come up with a clean way for this effect.</p> <pre><code>&lt;script type="text/javascript"&gt; function switchTo(id) { document.getElementById('slide1').style.display=(id==1)?'block':'none'; document.getElementById('slide2').style.display=(id==2)?'block':'none'; document.getElementById('slide3').style.display=(id==3)?'block':'none'; document.getElementById('slide4').style.display=(id==4)?'block':'none'; document.getElementById('switch1').style.fontWeight=(id==1)?'bold':'normal'; document.getElementById('switch2').style.fontWeight=(id==2)?'bold':'normal'; document.getElementById('switch3').style.fontWeight=(id==3)?'bold':'normal'; document.getElementById('switch4').style.fontWeight=(id==4)?'bold':'normal'; } &lt;/script&gt; &lt;ul id="switches"&gt; &lt;li id="switch1" onmouseover="switchTo(1);" style="font-weight:bold;"&gt;First slide&lt;/li&gt; &lt;li id="switch2" onmouseover="switchTo(2);"&gt;Second slide&lt;/li&gt; &lt;li id="switch3" onmouseover="switchTo(3);"&gt;Third slide&lt;/li&gt; &lt;li id="switch4" onmouseover="switchTo(4);"&gt;Fourth slide&lt;/li&gt; &lt;/ul&gt; &lt;div id="slides"&gt; &lt;div id="slide1"&gt;Well well.&lt;/div&gt; &lt;div id="slide2" style="display:none;"&gt;Oh no!&lt;/div&gt; &lt;div id="slide3" style="display:none;"&gt;You again?&lt;/div&gt; &lt;div id="slide4" style="display:none;"&gt;I'm gone!&lt;/div&gt; &lt;/div&gt; </code></pre>
<p>Rather than displaying all slides when JS is off (which would likely break the page layout) I would place inside the switch LIs real A links to server-side code which returns the page with the "active" class pre-set on the proper switch/slide.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() { switches = $('#switches &gt; li'); slides = $('#slides &gt; div'); switches.each(function(idx) { $(this).data('slide', slides.eq(idx)); }).hover( function() { switches.removeClass('active'); slides.removeClass('active'); $(this).addClass('active'); $(this).data('slide').addClass('active'); }); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#switches .active { font-weight: bold; } #slides div { display: none; } #slides div.active { display: block; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;test&lt;/title&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="switch.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;ul id="switches"&gt; &lt;li class="active"&gt;First slide&lt;/li&gt; &lt;li&gt;Second slide&lt;/li&gt; &lt;li&gt;Third slide&lt;/li&gt; &lt;li&gt;Fourth slide&lt;/li&gt; &lt;/ul&gt; &lt;div id="slides"&gt; &lt;div class="active"&gt;Well well.&lt;/div&gt; &lt;div&gt;Oh no!&lt;/div&gt; &lt;div&gt;You again?&lt;/div&gt; &lt;div&gt;I'm gone!&lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
<p>The only thing that's wrong with this code (at least to me) is that you're not using a loop to process all elements. Other than that, why not to it like that?</p> <p>And with loop, I mean grabbing the container element via a JQuery and iterating over all child elements – basically a one-liner.</p>
5,484
<p>I'm trying to get only the list of id of object bob for example instead of the list of bob. It's ok with a HQL request, but I would know if it's possible using criteria ?</p> <p>An example :</p> <pre><code>final StringBuilder hql = new StringBuilder(); hql.append( "select bob.id from " ) .append( bob.class.getName() ).append( " bob " ) .append( "where bob.id &gt; 10"); final Query query = session.createQuery( hql.toString() ); return query.list(); </code></pre>
<p>I think you could do that with Projections, something like</p> <pre><code>Criteria.forClass(bob.class.getName()) .add(Restrictions.gt("id", 10)) .setProjection(Projections.property("id")) ); </code></pre>
<p>You can do that like this</p> <pre><code> bob bb=null; Criteria criteria = session.createCriteria(bob.class); criteria.add(Restrictions.eq("id",id)); bb = (bob) criteria.uniqueResult(); </code></pre> <p>as Restrictions you can add your condition</p>
8,296
<p>How do I set, clear, and toggle a bit?</p>
<h1>Setting a bit</h1> <p>Use the bitwise OR operator (<code>|</code>) to set a bit.</p> <pre><code>number |= 1UL &lt;&lt; n; </code></pre> <p>That will set the <code>n</code>th bit of <code>number</code>. <code>n</code> should be zero, if you want to set the <code>1</code>st bit and so on upto <code>n-1</code>, if you want to set the <code>n</code>th bit.</p> <p>Use <code>1ULL</code> if <code>number</code> is wider than <code>unsigned long</code>; promotion of <code>1UL &lt;&lt; n</code> doesn't happen until after evaluating <code>1UL &lt;&lt; n</code> where it's undefined behaviour to shift by more than the width of a <code>long</code>. The same applies to all the rest of the examples.</p> <h1>Clearing a bit</h1> <p>Use the bitwise AND operator (<code>&amp;</code>) to clear a bit.</p> <pre><code>number &amp;= ~(1UL &lt;&lt; n); </code></pre> <p>That will clear the <code>n</code>th bit of <code>number</code>. You must invert the bit string with the bitwise NOT operator (<code>~</code>), then AND it.</p> <h1>Toggling a bit</h1> <p>The XOR operator (<code>^</code>) can be used to toggle a bit.</p> <pre><code>number ^= 1UL &lt;&lt; n; </code></pre> <p>That will toggle the <code>n</code>th bit of <code>number</code>.</p> <h1>Checking a bit</h1> <p>You didn't ask for this, but I might as well add it.</p> <p>To check a bit, shift the number n to the right, then bitwise AND it:</p> <pre><code>bit = (number &gt;&gt; n) &amp; 1U; </code></pre> <p>That will put the value of the <code>n</code>th bit of <code>number</code> into the variable <code>bit</code>.</p> <h1>Changing the <em>n</em>th bit to <em>x</em></h1> <p>Setting the <code>n</code>th bit to either <code>1</code> or <code>0</code> can be achieved with the following on a 2's complement C++ implementation:</p> <pre><code>number ^= (-x ^ number) &amp; (1UL &lt;&lt; n); </code></pre> <p>Bit <code>n</code> will be set if <code>x</code> is <code>1</code>, and cleared if <code>x</code> is <code>0</code>. If <code>x</code> has some other value, you get garbage. <code>x = !!x</code> will booleanize it to 0 or 1.</p> <p>To make this independent of 2's complement negation behaviour (where <code>-1</code> has all bits set, unlike on a 1's complement or sign/magnitude C++ implementation), use unsigned negation.</p> <pre><code>number ^= (-(unsigned long)x ^ number) &amp; (1UL &lt;&lt; n); </code></pre> <p>or</p> <pre><code>unsigned long newbit = !!x; // Also booleanize to force 0 or 1 number ^= (-newbit ^ number) &amp; (1UL &lt;&lt; n); </code></pre> <p>It's generally a good idea to use unsigned types for portable bit manipulation.</p> <p>or</p> <pre><code>number = (number &amp; ~(1UL &lt;&lt; n)) | (x &lt;&lt; n); </code></pre> <p><code>(number &amp; ~(1UL &lt;&lt; n))</code> will clear the <code>n</code>th bit and <code>(x &lt;&lt; n)</code> will set the <code>n</code>th bit to <code>x</code>.</p> <p>It's also generally a good idea to not to copy/paste code in general and so many people use preprocessor macros (like <a href="https://stackoverflow.com/a/263738/52074">the community wiki answer further down</a>) or some sort of encapsulation.</p>
<p>Try one of these functions in the C language to change n bit:</p> <pre><code>char bitfield; // Start at 0th position void chang_n_bit(int n, int value) { bitfield = (bitfield | (1 &lt;&lt; n)) &amp; (~( (1 &lt;&lt; n) ^ (value &lt;&lt; n) )); } </code></pre> <p>Or</p> <pre><code>void chang_n_bit(int n, int value) { bitfield = (bitfield | (1 &lt;&lt; n)) &amp; ((value &lt;&lt; n) | ((~0) ^ (1 &lt;&lt; n))); } </code></pre> <p>Or</p> <pre><code>void chang_n_bit(int n, int value) { if(value) bitfield |= 1 &lt;&lt; n; else bitfield &amp;= ~0 ^ (1 &lt;&lt; n); } char get_n_bit(int n) { return (bitfield &amp; (1 &lt;&lt; n)) ? 1 : 0; } </code></pre>
7,034
<p>Extreme Programming, Scrum and Test Driven Development definitely seem to be the most popular Agile methods at the moment. But someone recently suggested that I take a look at Feature Driven Development.</p> <p>Have you ever used this method with any success? What are the advantages of using it?</p>
<p>FDD is what I like to think of as a wrapper methodology, in that it allows you to apply a method to manage projects at a very high level, but it still allows you to use other methodologies at a lower level. </p> <p>FDD's focus is on being able to set estimates and schedules and to report on the status of a project as a whole, or at a very granular level, but it doesn't prescribe a specific method to apply in order to create the schedule, leaving that up to you to decide. The idea is that you can look at your project and state with some certainty what the project status is, whether you are on time, slipping, early and so on.</p> <p>I use FDD as a means to organise my projects into manageable stages, so that I know WHEN to sign off and commence any given stage. But by itself, FDD would be pretty useless. For example, I personally use Evidence Based Scheduling and a combined BDD/TDD as elements of a development processes that are managed under a kind of FDD umbrella. Personally, I couldn't do the full XP, or SCRUMM without running into problems because my projects and team would be hindered if they were forced to engage in practices from other methodologies that don't add value to our own unique circumstances.</p> <p>In any case, it is better not to fixate on any given methodology, because the needs/conditions of the company and project are likely to change regularly, and you need to be flexible in how you approach managing projects if you want them to be successful. No single methodology is a silver bullet, so the trick is to determine which methods work for you and tune your methodology to suit your individual needs. This is what being "Agile" is fundamentally about. </p>
<p>FDD is an older methodology. It has lot's of the ideas of other agile methodologies and misses some of them. Like Scrum it's a bit management-focussed and I think you need some elements from XP for practical implementations.</p> <p>FDD is certainly interesting to look into. But just like Scrum and XP I think you have to understand the mechanics and not just implement the practices to be succesful. If you just "do FDD" or "do Scrum" you're not as adaptive as you should be.</p> <p>The things I would look into if you want to understand agile would be</p> <p>Scrum or FDD to understand what management can get out of agile.<br> XP to understand how enable agile from a technology perspective.<br> Crystal Clear to understand the communications aspects.<br> Lean Agile to get a completely different perspective on agile methodologies<br></p> <p>I wouldn't call TDD an agile methodology by the way. It's an practice from XP but not a complete methodology per se.</p>
6,176
<p>I am printing minis and other very detailes stuff and I find that 0.04 mm layer height gives the best looking (smoothest) result. However it takes a long time, so I am looking for ways to speed it up. Is there any slicer which offers different layer heights for the outer perimiter? So you can print your model at 0.12 mm or so, but the outer layer gets printer first 3 times at 0.04 mm?</p>
<p>In Ultimaker Cura, unless you print a single perimeter outline and add extra wall infill support you are not going to have different outer perimeter layer heights.</p> <p>However, Cura is able to reduce the printing time, E.g. you can have fine layers for the wall (all perimeters), and coarse layers for the infill. The option is called <a href="https://ultimaker.com/en/resources/52670-infill" rel="nofollow noreferrer">"Infill Layer Thickness"</a>:</p> <blockquote> <h1>Infill layer thickness</h1> <p>Since the layer height of the infill is not important for visual quality, you can use thicker layers on the infill to reduce the print time. When adjusting this setting, always make sure that it is a multiple of the layer height, otherwise Ultimaker Cura will round it up to a multiple of the layer height. This means that you can, for example, print with an infill thickness of 0.2 mm while the layer height is 0.1 mm. The printer will first print the walls for two layers, and then it will print one thicker infill layer.</p> </blockquote> <p>Note that this is not a standard option, you need to put Cura in the "Custom" mode and filter/search for the option using the search bar. Below you'll find the upper right corner of the Cura Graphical User Interface where I searched for the option:</p> <p><a href="https://i.stack.imgur.com/wlRev.png" rel="nofollow noreferrer" title="Cura infill layer thickness"><img src="https://i.stack.imgur.com/wlRev.png" alt="Cura infill layer thickness" title="Cura infill layer thickness"></a></p> <p>Note that there are 2 options, one for regular infill of your product and one for infill of the support structures.</p> <hr> <p>An other department at work is working together with a start-up university company to 3D print PEEK molds (from pellets) using 2 nozzles/extruders (to create resin injection parts), one has a large nozzle, the other has a fine nozzle. They use their own developed slicer software to use the fine nozzle for the outer contours and the coarse nozzle for infill and support. It could be that they developed this because it was not available in commercial slicers. For the 2 most common free slicers, Cura and Slic3r, there is no option to have just the outer perimeter of different height than the inner perimeters. If you think of it, it is also pretty difficult to execute, you either get:</p> <p><a href="https://i.stack.imgur.com/g3q3h.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g3q3h.png" alt="enter image description here"></a></p> <p>(which does not improve the quality of the product, it will make the outside more coarse) or you'll get gaps:</p> <p><a href="https://i.stack.imgur.com/nmdR8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nmdR8.png" alt="enter image description here"></a></p> <p>Note that both upper images do not include infill, only 1 outer and 3 inner perimeters. The image below is probably what is possible with Cura, so all perimeters the same; green is infill now:</p> <p><a href="https://i.stack.imgur.com/ZopKY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZopKY.png" alt="enter image description here"></a></p>
<p>In Ultimaker Cura, unless you print a single perimeter outline and add extra wall infill support you are not going to have different outer perimeter layer heights.</p> <p>However, Cura is able to reduce the printing time, E.g. you can have fine layers for the wall (all perimeters), and coarse layers for the infill. The option is called <a href="https://ultimaker.com/en/resources/52670-infill" rel="nofollow noreferrer">"Infill Layer Thickness"</a>:</p> <blockquote> <h1>Infill layer thickness</h1> <p>Since the layer height of the infill is not important for visual quality, you can use thicker layers on the infill to reduce the print time. When adjusting this setting, always make sure that it is a multiple of the layer height, otherwise Ultimaker Cura will round it up to a multiple of the layer height. This means that you can, for example, print with an infill thickness of 0.2 mm while the layer height is 0.1 mm. The printer will first print the walls for two layers, and then it will print one thicker infill layer.</p> </blockquote> <p>Note that this is not a standard option, you need to put Cura in the "Custom" mode and filter/search for the option using the search bar. Below you'll find the upper right corner of the Cura Graphical User Interface where I searched for the option:</p> <p><a href="https://i.stack.imgur.com/wlRev.png" rel="nofollow noreferrer" title="Cura infill layer thickness"><img src="https://i.stack.imgur.com/wlRev.png" alt="Cura infill layer thickness" title="Cura infill layer thickness"></a></p> <p>Note that there are 2 options, one for regular infill of your product and one for infill of the support structures.</p> <hr> <p>An other department at work is working together with a start-up university company to 3D print PEEK molds (from pellets) using 2 nozzles/extruders (to create resin injection parts), one has a large nozzle, the other has a fine nozzle. They use their own developed slicer software to use the fine nozzle for the outer contours and the coarse nozzle for infill and support. It could be that they developed this because it was not available in commercial slicers. For the 2 most common free slicers, Cura and Slic3r, there is no option to have just the outer perimeter of different height than the inner perimeters. If you think of it, it is also pretty difficult to execute, you either get:</p> <p><a href="https://i.stack.imgur.com/g3q3h.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g3q3h.png" alt="enter image description here"></a></p> <p>(which does not improve the quality of the product, it will make the outside more coarse) or you'll get gaps:</p> <p><a href="https://i.stack.imgur.com/nmdR8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nmdR8.png" alt="enter image description here"></a></p> <p>Note that both upper images do not include infill, only 1 outer and 3 inner perimeters. The image below is probably what is possible with Cura, so all perimeters the same; green is infill now:</p> <p><a href="https://i.stack.imgur.com/ZopKY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZopKY.png" alt="enter image description here"></a></p>
1,528
<p>I upgraded my Ender 3 with a new Mobo, the 4.2.7 version.</p> <p>My current setup is:</p> <p>Printer Specifications:</p> <ul> <li>Ender 3</li> <li>Upgraded Motherboard 4.2.7 (Silent Stepper Drivers)</li> <li>Marlin FW Upgrade to Version 2.1.x</li> <li>New metal extruder handle</li> <li>Replacement bed springs</li> <li>New complete hot end</li> <li>Everything else is in stock</li> </ul> <p>Prior to the mobo upgrade, everything was working fine. Now I'm having problems with the extruder. I did use at first the Ender3 32bit 4.2.7 firmware, but it did happens too. The e-steps for the filament length have been adjusted. Once I start spinning the extruder, the extruder stepper starts grinding and jumping/rewinding the extruder wheel with the filament to the back; sometimes even 8-10 mm. Also, if I manually hold the filament back, it springs back. It seems that there is no power/power coming from the stepper motor.</p> <p>So I would like to check how much power the driver needs and gets. How or where can I find the required voltage for the drivers? How to adjust the drivers?</p> <p>Any tips or references are welcome.</p>
<p>There are different versions of the 4.2.7 main board. This is an excellent video made by <a href="https://www.youmaketech.com/how-to-adjust-stepper-motor-currents-on-ender-3-pro-v2/" rel="nofollow noreferrer">YouMakeTech</a>: <div class="youtube-embed"><div> <iframe width="640px" height="395px" src="https://www.youtube.com/embed/k2nm-WetPnU?start=0"></iframe> </div></div></p> <hr /> <p><em>To prevent the answer to become unusable due to <a href="https://en.wikipedia.org/wiki/Link_rot" rel="nofollow noreferrer">link rot</a>, a concise summary is shown below.</em></p> <p>The correct drivers can be &quot;read&quot; from the written letter on the card reader: <a href="https://i.stack.imgur.com/jwXQK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jwXQK.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/1gANf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1gANf.png" alt="enter image description here" /></a></p> <p>Depending on the driver, you need to find out what the maximum Vref for your stepper is (this depends on the maximum current rating of your stepper), e.g. for 2208, 2209 and 2225 drivers the Vref is calculated by the same equation: <a href="https://i.stack.imgur.com/lUWvp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lUWvp.png" alt="enter image description here" /></a></p> <p>The Imax (maximum curretn) is depending on the used stepper: <a href="https://i.stack.imgur.com/TUVYP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TUVYP.png" alt="enter image description here" /></a></p> <p>Use the nominal values to prevent the steppers to become too hot.</p> <p>The Vref can be adjusted by the screw potentiometers next to the drivers, use a voltmeter while adjusting:</p> <p><a href="https://i.stack.imgur.com/rONzE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rONzE.png" alt="enter image description here" /></a></p>
<p>I would try to reinstall the old board and see if the extruder still skips.</p> <p>If the extruder is not having an issue with the old board installed, you'll need to visit <a href="https://www.creality.com/pages/download-ender-3?spm=..page_1934481.products_display_1.1" rel="nofollow noreferrer">Creality's Updates page</a> and install the Marlin 2.0 firmware designed for the 4.2.7 board. Please use a how-to video on YouTube for installing your new board, you will need to calibrate E-Steps, calibrate PID Temperatures, etc. as outlined in the video.</p> <p>If the extruder continues its behavior, the extruder is under-extruding. Please check out <a href="https://www.3dsourced.com/rigid-ink/ultimate-3d-printing-troubleshooting-guide/#inconsistent-extrusion-under" rel="nofollow noreferrer">The Holy Bible of 3D Printing troubleshooting: Underextruding printer</a> to get to the bottom of it before you upgrade to your new silent board. Then I can pretty much guarantee you have either a clogged nozzle or a hotend that's too cold during printing to melt the plastic at a fast enough rate.</p> <p>The third thing is you need to upgrade the stock Ender 3 extruder because the stock black extruder bracket is absolute garbage, and it alone would cause a skipping and flaking extruder. Get the sweet stainless grey one for 15 USD on amazon. Blame Creality for that oversight.</p> <p>Please respond back if this didn't help.</p>
2,226
<p>I bought an Ender 3 v2 in January 2021 for my second printer. I have had an Ender 3 for two years and love the quality it prints. This new printer has been plagued with issues since day one. Creality sent me a new mainboard and fan due to issues. Even since then my printer will still not print consistently. I checked all my belts and made sure the bed is leveled.</p> <p>I print a test cube and it looks perfect. Then I will print a bigger longer print and sometimes it looks 100 % perfect with smooth layers and then I will print the exact same print from the same memory card and there will be ridges every couple of layers and the print turns out very rough.</p> <p>What would make this happen? I could understand if it always printed like this, but it is <em>completely random</em>. This is all from the same filament spool and I only use Hatchbox. My Ender 3 hasn't had a single problem in the two years I have owned it besides changing out the Bowden tube twice.</p> <p>I use Cura for slicing.</p> <p>The following pictures are of the same print on the same printer using the same filament from the same file.</p> <p><a href="https://i.stack.imgur.com/UJnPq.jpg" rel="nofollow noreferrer" title="Photo of print showing layers"><img src="https://i.stack.imgur.com/UJnPq.jpg" alt="Photo of print showing layers" title="Photo of print showing layers" /></a></p> <p><a href="https://i.stack.imgur.com/G34o9.jpg" rel="nofollow noreferrer" title="Close up photo of print showing layers"><img src="https://i.stack.imgur.com/G34o9.jpg" alt="Close up photo of print showing layers" title="Close up photo of print showing layers" /></a></p>
<p>First, check that your belts are tight, on the X-axis and the bed. If not, tighten them.</p> <p>Second, grab the hot end and wiggle the gantry, and make sure it is not loose. If there is any play at all, tighten the eccentric nuts.</p> <p>If this doesn't fix your problems, check out this playlist I put together for the Ender 3 V2, it should answer everything.</p> <p><a href="https://www.youtube.com/playlist?list=PLPb81Z-Cw4oheuYfZy9GHORyQOY0aDgod" rel="nofollow noreferrer">Ultimate Guide to the Ender 3 V2</a></p>
<p>If you have a 4.2.2 board, it may be a stepper driver problem. If this is the case, the only solution is to replace the board.</p>
1,916
<p>I'm not clear on the differences between the "current" version of Ruby (1.8) and the "new" version (1.9). Is there an "easy" or a "simple" explanation of the differences and why it is so different?</p>
<p>Sam Ruby has a <a href="http://slideshow.rubyforge.org/ruby19.html" rel="noreferrer">cool slideshow that outline the differences</a>.</p> <p>In the interest of bringing this information inline for easier reference, and in case the link goes dead in the abstract future, here's an overview of Sam's slides. The slideshow is less overwhelming to review, but having it all laid out in a list like this is also helpful.</p> <h1>Ruby 1.9 - Major Features</h1> <ul> <li>Performance</li> <li>Threads/Fibers</li> <li>Encoding/Unicode</li> <li>gems is (mostly) built-in now</li> <li>if statements do not introduce scope in Ruby.</li> </ul> <h1>What's changed?</h1> <h2>Single character strings.</h2> <p>Ruby 1.9</p> <pre><code>irb(main):001:0&gt; ?c =&gt; "c" </code></pre> <p>Ruby 1.8.6</p> <pre><code>irb(main):001:0&gt; ?c =&gt; 99 </code></pre> <hr> <h2>String index.</h2> <p>Ruby 1.9</p> <pre><code>irb(main):001:0&gt; "cat"[1] =&gt; "a" </code></pre> <p>Ruby 1.8.6</p> <pre><code>irb(main):001:0&gt; "cat"[1] =&gt; 97 </code></pre> <hr> <h2>{"a","b"} No Longer Supported</h2> <p>Ruby 1.9</p> <pre><code>irb(main):002:0&gt; {1,2} SyntaxError: (irb):2: syntax error, unexpected ',', expecting tASSOC </code></pre> <p>Ruby 1.8.6</p> <pre><code>irb(main):001:0&gt; {1,2} =&gt; {1=&gt;2} </code></pre> <p><strong>Action:</strong> Convert to {1 => 2}</p> <hr> <h2><code>Array.to_s</code> Now Contains Punctuation</h2> <p>Ruby 1.9</p> <pre><code>irb(main):001:0&gt; [1,2,3].to_s =&gt; "[1, 2, 3]" </code></pre> <p>Ruby 1.8.6</p> <pre><code>irb(main):001:0&gt; [1,2,3].to_s =&gt; "123" </code></pre> <p><strong>Action:</strong> Use .join instead</p> <hr> <h2>Colon No Longer Valid In When Statements</h2> <p>Ruby 1.9</p> <pre><code>irb(main):001:0&gt; case 'a'; when /\w/: puts 'word'; end SyntaxError: (irb):1: syntax error, unexpected ':', expecting keyword_then or ',' or ';' or '\n' </code></pre> <p>Ruby 1.8.6</p> <pre><code>irb(main):001:0&gt; case 'a'; when /\w/: puts 'word'; end word </code></pre> <p><strong>Action:</strong> Use semicolon, then, or newline</p> <hr> <h2>Block Variables Now Shadow Local Variables</h2> <p>Ruby 1.9</p> <pre><code>irb(main):001:0&gt; i=0; [1,2,3].each {|i|}; i =&gt; 0 irb(main):002:0&gt; i=0; for i in [1,2,3]; end; i =&gt; 3 </code></pre> <p>Ruby 1.8.6</p> <pre><code>irb(main):001:0&gt; i=0; [1,2,3].each {|i|}; i =&gt; 3 </code></pre> <hr> <h2><code>Hash.index</code> Deprecated</h2> <p>Ruby 1.9</p> <pre><code>irb(main):001:0&gt; {1=&gt;2}.index(2) (irb):18: warning: Hash#index is deprecated; use Hash#key =&gt; 1 irb(main):002:0&gt; {1=&gt;2}.key(2) =&gt; 1 </code></pre> <p>Ruby 1.8.6</p> <pre><code>irb(main):001:0&gt; {1=&gt;2}.index(2) =&gt; 1 </code></pre> <p><strong>Action:</strong> Use Hash.key</p> <hr> <h2><code>Fixnum.to_sym</code> Now Gone</h2> <p>Ruby 1.9</p> <pre><code>irb(main):001:0&gt; 5.to_sym NoMethodError: undefined method 'to_sym' for 5:Fixnum </code></pre> <p>Ruby 1.8.6</p> <pre><code>irb(main):001:0&gt; 5.to_sym =&gt; nil </code></pre> <p>(Cont'd) Ruby 1.9</p> <pre><code># Find an argument value by name or index. def [](index) lookup(index.to_sym) end </code></pre> <p>svn.ruby-lang.org/repos/ruby/trunk/lib/rake.rb</p> <hr> <h2>Hash Keys Now Unordered</h2> <p>Ruby 1.9</p> <pre><code>irb(main):001:0&gt; {:a=&gt;"a", :c=&gt;"c", :b=&gt;"b"} =&gt; {:a=&gt;"a", :c=&gt;"c", :b=&gt;"b"} </code></pre> <p>Ruby 1.8.6</p> <pre><code>irb(main):001:0&gt; {:a=&gt;"a", :c=&gt;"c", :b=&gt;"b"} =&gt; {:a=&gt;"a", :b=&gt;"b", :c=&gt;"c"} </code></pre> <p>Order is insertion order</p> <hr> <h2>Stricter Unicode Regular Expressions</h2> <p>Ruby 1.9</p> <pre><code>irb(main):001:0&gt; /\x80/u SyntaxError: (irb):2: invalid multibyte escape: /\x80/ </code></pre> <p>Ruby 1.8.6</p> <pre><code>irb(main):001:0&gt; /\x80/u =&gt; /\x80/u </code></pre> <hr> <h2><code>tr</code> and <code>Regexp</code> Now Understand Unicode</h2> <p>Ruby 1.9</p> <pre><code>unicode(string).tr(CP1252_DIFFERENCES, UNICODE_EQUIVALENT). gsub(INVALID_XML_CHAR, REPLACEMENT_CHAR). gsub(XML_PREDEFINED) {|c| PREDEFINED[c.ord]} </code></pre> <hr> <h2><code>pack</code> and <code>unpack</code></h2> <p>Ruby 1.8.6</p> <pre><code>def xchr(escape=true) n = XChar::CP1252[self] || self case n when *XChar::VALID XChar::PREDEFINED[n] or (n&gt;128 ? n.chr : (escape ? "&amp;##{n};" : [n].pack('U*'))) else Builder::XChar::REPLACEMENT_CHAR end end unpack('U*').map {|n| n.xchr(escape)}.join </code></pre> <hr> <h2><code>BasicObject</code> More Brutal Than <code>BlankSlate</code></h2> <p>Ruby 1.9</p> <pre><code>irb(main):001:0&gt; class C &lt; BasicObject; def f; Math::PI; end; end; C.new.f NameError: uninitialized constant C::Math </code></pre> <p>Ruby 1.8.6</p> <pre><code>irb(main):001:0&gt; require 'blankslate' =&gt; true irb(main):002:0&gt; class C &lt; BlankSlate; def f; Math::PI; end; end; C.new.f =&gt; 3.14159265358979 </code></pre> <p><strong>Action:</strong> Use ::Math::PI</p> <hr> <p><s></p> <h2>Delegation Changes</h2> <p>Ruby 1.9</p> <pre><code>irb(main):002:0&gt; class C &lt; SimpleDelegator; end =&gt; nil irb(main):003:0&gt; C.new('').class =&gt; String </code></pre> <p>Ruby 1.8.6</p> <pre><code>irb(main):002:0&gt; class C &lt; SimpleDelegator; end =&gt; nil irb(main):003:0&gt; C.new('').class =&gt; C irb(main):004:0&gt; </code></pre> <p><a href="http://rubyforge.org/tracker/index.php?func=detail&amp;aid=17700&amp;group_id=426&amp;atid=1698" rel="noreferrer">Defect 17700</a> </s></p> <hr> <h2>Use of $KCODE Produces Warnings</h2> <p>Ruby 1.9</p> <pre><code>irb(main):004:1&gt; $KCODE = 'UTF8' (irb):4: warning: variable $KCODE is no longer effective; ignored =&gt; "UTF8" </code></pre> <p>Ruby 1.8.6</p> <pre><code>irb(main):001:0&gt; $KCODE = 'UTF8' =&gt; "UTF8" </code></pre> <hr> <h2><code>instance_methods</code> Now an Array of Symbols</h2> <p>Ruby 1.9</p> <pre><code>irb(main):001:0&gt; {}.methods.sort.last =&gt; :zip </code></pre> <p>Ruby 1.8.6</p> <pre><code>irb(main):001:0&gt; {}.methods.sort.last =&gt; "zip" </code></pre> <p><strong>Action:</strong> Replace instance_methods.include? with method_defined?</p> <hr> <h2>Source File Encoding</h2> <h3>Basic</h3> <pre><code># coding: utf-8 </code></pre> <h3>Emacs</h3> <pre><code># -*- encoding: utf-8 -*- </code></pre> <h3>Shebang</h3> <pre><code>#!/usr/local/rubybook/bin/ruby # encoding: utf-8 </code></pre> <hr> <h2>Real Threading</h2> <ul> <li>Race Conditions</li> <li>Implicit Ordering Assumptions</li> <li>Test Code</li> </ul> <hr> <h1>What's New?</h1> <h2>Alternate Syntax for Symbol as Hash Keys</h2> <p>Ruby 1.9</p> <pre><code>{a: b} redirect_to action: show </code></pre> <p>Ruby 1.8.6</p> <pre><code>{:a =&gt; b} redirect_to :action =&gt; show </code></pre> <hr> <h2>Block Local Variables</h2> <p>Ruby 1.9</p> <pre><code>[1,2].each {|value; t| t=value*value} </code></pre> <hr> <h2>Inject Methods</h2> <p>Ruby 1.9</p> <pre><code>[1,2].inject(:+) </code></pre> <p>Ruby 1.8.6</p> <pre><code>[1,2].inject {|a,b| a+b} </code></pre> <hr> <h2><code>to_enum</code></h2> <p>Ruby 1.9</p> <pre><code>short_enum = [1, 2, 3].to_enum long_enum = ('a'..'z').to_enum loop do puts "#{short_enum.next} #{long_enum.next}" end </code></pre> <hr> <h2>No block? Enum!</h2> <p>Ruby 1.9</p> <pre><code>e = [1,2,3].each </code></pre> <hr> <h2>Lambda Shorthand</h2> <p>Ruby 1.9</p> <pre><code>p = -&gt; a,b,c {a+b+c} puts p.(1,2,3) puts p[1,2,3] </code></pre> <p>Ruby 1.8.6</p> <pre><code>p = lambda {|a,b,c| a+b+c} puts p.call(1,2,3) </code></pre> <hr> <h2>Complex Numbers</h2> <p>Ruby 1.9</p> <pre><code>Complex(3,4) == 3 + 4.im </code></pre> <hr> <h2>Decimal Is Still Not The Default</h2> <p>Ruby 1.9</p> <pre><code>irb(main):001:0&gt; 1.2-1.1 =&gt; 0.0999999999999999 </code></pre> <hr> <h2>Regex “Properties”</h2> <p>Ruby 1.9</p> <pre><code>/\p{Space}/ </code></pre> <p>Ruby 1.8.6</p> <pre><code>/[:space:]/ </code></pre> <hr> <h2>Splat in Middle</h2> <p>Ruby 1.9</p> <pre><code>def foo(first, *middle, last) (-&gt;a, *b, c {p a-c}).(*5.downto(1)) </code></pre> <hr> <h2>Fibers</h2> <p>Ruby 1.9</p> <pre><code>f = Fiber.new do a,b = 0,1 Fiber.yield a Fiber.yield b loop do a,b = b,a+b Fiber.yield b end end 10.times {puts f.resume} </code></pre> <hr> <h2>Break Values</h2> <p>Ruby 1.9</p> <pre><code>match = while line = gets next if line =~ /^#/ break line if line.find('ruby') end </code></pre> <hr> <h2>“Nested” Methods</h2> <p>Ruby 1.9</p> <pre><code>def toggle def toggle "subsequent times" end "first time" end </code></pre> <hr> <p>HTH!</p>
<p>Some more changes:</p> <p><strong>Returning a splat singleton array:</strong></p> <pre><code>def function return *[1] end a=function </code></pre> <ul> <li>ruby 1.9 : [1]</li> <li>ruby 1.8 : 1</li> </ul> <p><strong>array arguments</strong></p> <pre><code>def function(array) array.each { |v| p v } end function "1" </code></pre> <ul> <li>ruby 1.8: "1"</li> <li>ruby 1.9: undefined method `each' for "1":String</li> </ul>
4,171
<p>I have a simple WPF application which I am trying to start. I am following the Microsoft Patterns and Practices "Composite Application Guidance for WPF". I've followed their instructions however my WPF application fails immediately with a "TypeInitializationException".</p> <p>The InnerException property reveals that "The type initializer for 'System.Windows.Navigation.BaseUriHelper' threw an exception."</p> <p>Here is my app.xaml:</p> <pre><code>&lt;Application x:Class="MyNamespace.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt; &lt;Application.Resources&gt; &lt;/Application.Resources&gt; &lt;/Application&gt; </code></pre> <p>And here is my app.xaml.cs (exception thrown at "public App()"):</p> <pre><code>public partial class App : Application { public App() { Bootstrapper bootStrapper = new Bootstrapper(); bootStrapper.Run(); } } </code></pre> <p>I have set the "App" class as the startup object in the project.</p> <p>What is going astray?</p>
<p>Thanks @ima, your answer pointed me in the right direction. I was using an app.config file and it contained this:</p> <pre><code>&lt;configuration&gt; &lt;startup&gt; &lt;supportedRuntime version="v2.0.50727" sku="Client"/&gt; &lt;/startup&gt; &lt;configSections&gt; &lt;section name="modules" type="Microsoft.Practices.Composite.Modularity.ModulesConfigurationSection, Microsoft.Practices.Composite"/&gt; &lt;/configSections&gt; &lt;modules&gt; &lt;module assemblyFile="Modules/MyNamespace.Modules.ModuleName.dll" moduleType="MyNamespace.Modules.ModuleName.ModuleClass" moduleName="Name"/&gt; &lt;/modules&gt; &lt;/configuration&gt; </code></pre> <p>It seems the problem was the &lt;startup&gt; element because when I removed it the application ran fine. I was confused because Visual Studio 2008 added that when I checked the box to utilise the "Client Profile" available in 3.5 SP1.</p> <p>After some mucking about checking and un-checking the box I ended up with a configuration file like this:</p> <pre><code>&lt;configuration&gt; &lt;configSections&gt; &lt;section name="modules" type="Microsoft.Practices.Composite.Modularity.ModulesConfigurationSection, Microsoft.Practices.Composite"/&gt; &lt;/configSections&gt; &lt;modules&gt; &lt;module assemblyFile="Modules/MyNamespace.Modules.ModuleName.dll" moduleType="MyNamespace.Modules.ModuleName.ModuleClass" moduleName="Name"/&gt; &lt;/modules&gt; &lt;startup&gt; &lt;supportedRuntime version="v2.0.50727" sku="Client"/&gt; &lt;/startup&gt; &lt;/configuration&gt; </code></pre> <p>Which works!</p> <p>I'm not sure why the order of elements in the app.config is important - but it seems it is.</p>
<p>You have two sections named "modules". Place both module definitions in one section named "modules".</p>
8,276
<p>Does anybody know of a way to list up the "loaded plugins" in <strong>Vim</strong>? I know I should be keeping track of this kind of stuff myself but it would always be nice to be able to check the current status.</p>
<p>Not a VIM user myself, so forgive me if this is totally offbase. But according to what I gather from the following <a href="http://rayninfo.co.uk/vimtips.html" rel="noreferrer">VIM Tips</a> site: </p> <pre><code>" where was an option set :scriptnames : list all plugins, _vimrcs loaded (super) :verbose set history? : reveals value of history and where set :function : list functions :func SearchCompl : List particular function </code></pre>
<p>If you use <a href="https://github.com/junegunn/vim-plug" rel="noreferrer">vim-plug</a> (Plug), &quot; A minimalist Vim plugin manager.&quot;:</p> <pre><code>:PlugStatus </code></pre> <p>That will not only list your plugins but check their status.</p>
7,136
<p>I'm printing 6 separate parts in one go, after 4 hours of printing one part failed, but the other 5 are printing nicely.</p> <p>Is there a way to prevent the print from printing the failed part and continue printing the other 5 parts.</p> <p>I'm using Cura and an Ender 3 printer.</p>
<p>If you use the <a href="https://octoprint.org/" rel="noreferrer">OctoPrint</a> print manager, you can exclude regions to be printed using the <a href="https://plugins.octoprint.org/plugins/excluderegion/" rel="noreferrer">Exclude Region</a> plugin. The description states that it can be used to rescue partially-failed prints:</p> <blockquote> <p>The intent of this plugin is to provide a means to salvage multi-part prints where one (or more) of the parts has broken loose from the build plate or has otherwise become a worthless piece of failure. Instead of cancelling an entire job when only a portion is messed up, use this plugin to instruct OctoPrint to ignore any gcode commands executed within the area around the failure.</p> </blockquote> <p>Other print managers may provide similar facilities.</p> <p>I'm not sure if it will enable you to rescue your current print job.</p>
<p>No, once you sliced the 6 parts on the build plate in your slicer, the G-code is fixed and the printer will print as the sliced instructions. During printing it cannot skip the code of a part that failed along the way; there is no way to interfere with the printing other than stopping the print. For that reason, many people don't pack the build plate too full, the more parts, the higher the chance it fails. You could print the part one after each other. Packing the plate with multiple parts is usually not faster than printing one at a time (if it fails you have nothing, otherwise a single failed print).</p> <p>Depending on the size of the parts you can also tell the printer to print each part on the plate one after another in a single job; note that the printhead dimensions limit this. If one fails you stop the job, but the already printed parts are saved. You can then commence a new print of cut the G-code and reprint the shortened file.</p>
1,708
<p>I'm sick and tired of manually tracking my branches and merges across my repository! It's too error prone. In a world where everyone seems to get the idea of reducing duplication and automating everything, subversion branching/merging feels like it's left over from the 80's. What is a good alternative to subversion that has excellent branching and merging support without adding the complexity of a distributed SCM paradigm? Ideally it would be free, but if I have to shell out some cash I might be inclined if it's good enough.</p>
<p>Have you upgraded to Subversion 1.5? It includes automated merge tracking. This may address your issue. It sounds like you're already familiar with the tool itself and it's free. So, if you upgrade your current solution to 1.5 you'll have almost no learning curve and zero cost - plus you won't have to go through the pain of porting your existing code to a new source code control system.</p>
<p>git - <a href="http://git.or.cz/" rel="nofollow noreferrer">http://git.or.cz/</a> ( i am quite fond of git, great @ branching and distributed development) - <a href="http://github.com/" rel="nofollow noreferrer">http://github.com/</a> is a great working example.</p>
9,489
<p>I've heard of the idea of bootstrapping a language, that is, writing a compiler/interpreter for the language in itself. I was wondering how this could be accomplished and looked around a bit, and saw someone say that it could only be done by either</p> <ul> <li>writing an initial compiler in a different language.</li> <li>hand-coding an initial compiler in Assembly, which seems like a special case of the first</li> </ul> <p>To me, neither of these seem to actually be <em>bootstrapping</em> a language in the sense that they both require outside support. Is there a way to actually write a compiler in its own language?</p>
<blockquote> <p>Is there a way to actually write a compiler in its own language?</p> </blockquote> <p>You <em>have</em> to have some existing language to write your new compiler in. If you were writing a new, say, C++ compiler, you would just write it in C++ and compile it with an existing compiler first. On the other hand, if you were creating a compiler for a new language, let's call it Yazzleof, you would need to write the new compiler in another language first. Generally, this would be another programming language, but it doesn't have to be. It can be assembly, or if necessary, machine code.</p> <p>If you <em>were</em> going to bootstrap a compiler for Yazzleof, you generally wouldn't write a compiler for the full language initially. Instead you would write a compiler for Yazzle-lite, the smallest possible subset of the Yazzleof (well, a <em>pretty small</em> subset at least). Then in Yazzle-lite, you would write a compiler for the full language. (Obviously this can occur iteratively instead of in one jump.) Because Yazzle-lite is a proper subset of Yazzleof, you now have a compiler which can compile itself.</p> <p>There is a <em>really</em> good writeup about bootstrapping a compiler from the lowest possible level (which on a modern machine is basically a hex editor), titled <em>Bootstrapping a simple compiler from nothing</em>. It can be found at <a href="https://web.archive.org/web/20061108010907/http://www.rano.org/bcompiler.html" rel="noreferrer">https://web.archive.org/web/20061108010907/http://www.rano.org/bcompiler.html</a>.</p>
<p>Some bootstrapped compilers or systems keep both the source form and the object form in their repository:</p> <ul> <li><p><a href="http://ocaml.org/" rel="nofollow">ocaml</a> is a language which has both a bytecode interpreter (i.e. a compiler to Ocaml bytecode) and a native compiler (to x86-64 or ARM, etc... assembler). Its svn repository contains both the source code (files <code>*/*.{ml,mli}</code>) and the bytecode (file <code>boot/ocamlc</code>) form of the compiler. So when you build it is first using its bytecode (of a previous version of the compiler) to compile itself. Later the freshly compiled bytecode is able to compile the native compiler. So Ocaml svn repository contains both <code>*.ml[i]</code> source files and the <code>boot/ocamlc</code> bytecode file.</p></li> <li><p>The <a href="http://www.rust-lang.org/" rel="nofollow">rust</a> compiler downloads (using <code>wget</code>, so you need a working Internet connection) a previous version of its binary to compile itself.</p></li> <li><p><a href="http://gcc-melt.org/" rel="nofollow">MELT</a> is a Lisp-like language to customize and extend <a href="http://gcc.gnu.org/" rel="nofollow">GCC</a>. It is translated to C++ code by a bootstrapped translator. The generated C++ code of the translator is distributed, so the svn repository contains both <code>*.melt</code> source files and <code>melt/generated/*.cc</code> "object" files of the translator.</p></li> <li><p>J.Pitrat's <a href="http://bootstrappingartificialintelligence.fr/WordPress3/2014/04/caia-my-colleague/" rel="nofollow">CAIA</a> artificial intelligence system is entirely self-generating. It is available as a collection of thousands of <code>[A-Z]*.c</code> generated files (also with a generated <code>dx.h</code> header file) with a collection of thousands of <code>_[0-9]*</code> data files.</p></li> <li><p>Several Scheme compilers are also bootstrapped. Scheme48, Chicken Scheme, ...</p></li> </ul>
3,445
<p>In C++, can member function pointers be used to point to derived (or even base) class members? </p> <p>EDIT: Perhaps an example will help. Suppose we have a hierarchy of three classes <code>X</code>, <code>Y</code>, <code>Z</code> in order of inheritance. <code>Y</code> therefore has a base class <code>X</code> and a derived class <code>Z</code>.</p> <p>Now we can define a member function pointer <code>p</code> for class <code>Y</code>. This is written as:</p> <pre><code>void (Y::*p)(); </code></pre> <p>(For simplicity, I'll assume we're only interested in functions with the signature <code>void f()</code> ) </p> <p>This pointer <code>p</code> can now be used to point to member functions of class <code>Y</code>.</p> <p>This question (two questions, really) is then:</p> <ol> <li>Can <code>p</code> be used to point to a function in the derived class <code>Z</code>?</li> <li>Can <code>p</code> be used to point to a function in the base class <code>X</code>?</li> </ol>
<p>C++03 std, <a href="http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/conv.html#conv.mem" rel="noreferrer">§4.11 2 Pointer to member conversions</a>:</p> <blockquote> <p>An rvalue of type “pointer to member of B of type <i>cv</i> T,” where B is a class type, can be converted to an rvalue of type “pointer to member of D of type <i>cv</i> T,” where D is a derived class (clause 10) of B. If B is an inaccessible (clause 11), ambiguous (10.2) or virtual (10.1) base class of D, a program that necessitates this conversion is ill-formed. The result of the conversion refers to the same member as the pointer to member before the conversion took place, but it refers to the base class member as if it were a member of the derived class. The result refers to the member in D’s instance of B. Since the result has type “pointer to member of D of type <i>cv</i> T,” it can be dereferenced with a D object. The result is the same as if the pointer to member of B were dereferenced with the B sub-object of D. The null member pointer value is converted to the null member pointer value of the destination type. <sup>52)</sup></p> <p><sup>52)</sup>The rule for conversion of pointers to members (from pointer to member of base to pointer to member of derived) appears inverted compared to the rule for pointers to objects (from pointer to derived to pointer to base) (4.10, clause 10). This inversion is necessary to ensure type safety. Note that a pointer to member is not a pointer to object or a pointer to function and the rules for conversions of such pointers do not apply to pointers to members. In particular, a pointer to member cannot be converted to a void*.</p> </blockquote> <p>In short, you can convert a pointer to a member of an accessible, non-virtual base class to a pointer to a member of a derived class as long as the member isn't ambiguous. </p> <pre><code>class A { public: void foo(); }; class B : public A {}; class C { public: void bar(); }; class D { public: void baz(); }; class E : public A, public B, private C, public virtual D { public: typedef void (E::*member)(); }; class F:public E { public: void bam(); }; ... int main() { E::member mbr; mbr = &amp;A::foo; // invalid: ambiguous; E's A or B's A? mbr = &amp;C::bar; // invalid: C is private mbr = &amp;D::baz; // invalid: D is virtual mbr = &amp;F::bam; // invalid: conversion isn't defined by the standard ... </code></pre> <p>Conversion in the other direction (via <code>static_cast</code>) is governed by <a href="http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/expr.html#expr.static.cast" rel="noreferrer">§ 5.2.9</a> 9:</p> <blockquote> <p>An rvalue of type "pointer to member of D of type <i>cv1</i> T" can be converted to an rvalue of type "pointer to member of B of type <i>cv2</i> T", where B is a base class (clause <a href="http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/derived.html#class.derived" rel="noreferrer">10 class.derived</a>) of D, if a valid standard conversion from "pointer to member of B of type T" to "pointer to member of D of type T" exists (<a href="http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/conv.html#conv.mem" rel="noreferrer">4.11 conv.mem</a>), and <i>cv2</i> is the same cv-qualification as, or greater cv-qualification than, <i>cv1</i>.<sup>11)</sup> The null member pointer value (<a href="http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/conv.html#conv.mem" rel="noreferrer">4.11 conv.mem</a>) is converted to the null member pointer value of the destination type. If class B contains the original member, or is a base or derived class of the class containing the original member, the resulting pointer to member points to the original member. Otherwise, the result of the cast is undefined. [Note: although class B need not contain the original member, the dynamic type of the object on which the pointer to member is dereferenced must contain the original member; see <a href="http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/expr.html#expr.mptr.oper" rel="noreferrer">5.5 expr.mptr.oper</a>.]</p> <p><sup>11)</sup> Function types (including those used in pointer to member function types) are never cv-qualified; see <a href="http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/decl.html#dcl.fct" rel="noreferrer">8.3.5 dcl.fct</a>.</p> </blockquote> <p>In short, you can convert from a derived <code>D::*</code> to a base <code>B::*</code> if you can convert from a <code>B::*</code> to a <code>D::*</code>, though you can only use the <code>B::*</code> on objects that are of type D or are descended from D.</p>
<p>Here is an example of what works. You can override a method in derived class, and another method of base class that uses pointer to this overridden method indeed calls the derived class's method.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; using namespace std; class A { public: virtual void traverse(string arg) { find(&amp;A::visit, arg); } protected: virtual void find(void (A::*method)(string arg), string arg) { (this-&gt;*method)(arg); } virtual void visit(string arg) { cout &lt;&lt; "A::visit, arg:" &lt;&lt; arg &lt;&lt; endl; } }; class B : public A { protected: virtual void visit(string arg) { cout &lt;&lt; "B::visit, arg:" &lt;&lt; arg &lt;&lt; endl; } }; int main() { A a; B b; a.traverse("one"); b.traverse("two"); return 0; } </code></pre>
8,477
<p>exact code will be helpful. I assume the DirectoryServices namespace does it but I can't find the method that does it.</p> <hr> <p>I need actual C# code. All the samples I found so far are VB or VBScript. The C# examples I found are for reading/setting ADSI properties. A command like backup seems to have a certain .NET syntax which I am not clear how to use. In VB there's a straightforward backup command. Need an equivalent in .NET.</p>
<p>You'll need to use ADSI objects. The <a href="http://msdn.microsoft.com/en-us/library/ms525753.aspx" rel="nofollow noreferrer">IIsComputer.Backup</a> method is what you want.</p> <p>As far as how to access ADSI objects from C#, check out this <a href="http://support.microsoft.com/kb/315716" rel="nofollow noreferrer">MSDN page</a>.</p> <p><strong>EDIT:</strong> Here's a <a href="http://www.vbforums.com/archive/index.php/t-470587.html" rel="nofollow noreferrer">sample implementation in C#</a>.</p>
<p>I found it:</p> <p>DirectoryEntry de = new DirectoryEntry("IIS://localhost"); de.Invoke("Backup", new object[0] );</p> <p>new object needs to be set to hold proper arguments like overwriting current backup</p>
7,270
<p>Can Repetier host run a multi-material printer such as the Prusa i3 MK2S?</p>
<p>Yes, it can. I have configured it for as many as four extruders. The problem may be in the slicing, as the slicer is responsible for generating the tool change commands.</p> <p>One problem with the Repetier multi-extruder support is that, although the temperature of each extruder is reported by the RepRap firmware response, only the selected extruder is updated, and only one extruder is shown in the temperature graph.</p>
<p>Yes, you can add a second extruder to it.</p>
760
<p>I have a ASP.NET 1.1 application, and I'm trying to find out why when I change a ComboBox which value is used to fill another one (parent-child relation), two postbacks are produced.</p> <p>I have checked and checked the code, and I can't find the cause.</p> <p>Here are both call stacks which end in a page_load</p> <p>First postback (generated by teh ComboBox's autopostback)</p> <p><a href="http://www.juanformoso.com.ar/images/callstack1.jpg" rel="nofollow noreferrer">Postback call stack</a> (broken)</p> <p>Second postback (this is what I want to find why it's happening)</p> <p><a href="http://www.juanformoso.com.ar/images/callstack2.jpg" rel="nofollow noreferrer">alt text</a> (broken)</p> <p>Any suggestion? What can I check?</p>
<p>It's a very specific problem with this code, I doubt it will be useful for someone else, but here it goes:</p> <p>A check was added to the combo's <code>onchange</code> with an if, if the condition was met, an explicit call to the postback function was made. If the combo was set to <code>AutoPostback</code>, asp.net added the postback call again, producing the two postbacks...</p> <p>The generated html was like this:</p> <pre><code>[select onchange="javascript: if (CustomFunction()){__doPostBack('name','')}; __doPostBack('name','')"] </code></pre>
<p>First thing I would look for is that you don't have the second ComboBox's AutoPostBack property set to true. If you change the value in the second combo with that property set true, I believe it will generate a postback on that control.</p>
4,070
<p>How can I present a control to the user that allows him/her to select a directory?</p> <p>There doesn't seem to be any native .net controls which do this?</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.folderbrowserdialog.aspx" rel="noreferrer">FolderBrowserDialog class</a> is the best option.</p>
<p>or even more better, you can put this code in a class file</p> <pre><code>using System; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows.Forms; internal class OpenFolderDialog : IDisposable { /// &lt;summary&gt; /// Gets/sets folder in which dialog will be open. /// &lt;/summary&gt; public string InitialFolder { get; set; } /// &lt;summary&gt; /// Gets/sets directory in which dialog will be open if there is no recent directory available. /// &lt;/summary&gt; public string DefaultFolder { get; set; } /// &lt;summary&gt; /// Gets selected folder. /// &lt;/summary&gt; public string Folder { get; private set; } internal DialogResult ShowDialog(IWin32Window owner) { if (Environment.OSVersion.Version.Major &gt;= 6) { return ShowVistaDialog(owner); } else { return ShowLegacyDialog(owner); } } private DialogResult ShowVistaDialog(IWin32Window owner) { var frm = (NativeMethods.IFileDialog)(new NativeMethods.FileOpenDialogRCW()); uint options; frm.GetOptions(out options); options |= NativeMethods.FOS_PICKFOLDERS | NativeMethods.FOS_FORCEFILESYSTEM | NativeMethods.FOS_NOVALIDATE | NativeMethods.FOS_NOTESTFILECREATE | NativeMethods.FOS_DONTADDTORECENT; frm.SetOptions(options); if (this.InitialFolder != null) { NativeMethods.IShellItem directoryShellItem; var riid = new Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"); //IShellItem if (NativeMethods.SHCreateItemFromParsingName(this.InitialFolder, IntPtr.Zero, ref riid, out directoryShellItem) == NativeMethods.S_OK) { frm.SetFolder(directoryShellItem); } } if (this.DefaultFolder != null) { NativeMethods.IShellItem directoryShellItem; var riid = new Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"); //IShellItem if (NativeMethods.SHCreateItemFromParsingName(this.DefaultFolder, IntPtr.Zero, ref riid, out directoryShellItem) == NativeMethods.S_OK) { frm.SetDefaultFolder(directoryShellItem); } } if (frm.Show(owner.Handle) == NativeMethods.S_OK) { NativeMethods.IShellItem shellItem; if (frm.GetResult(out shellItem) == NativeMethods.S_OK) { IntPtr pszString; if (shellItem.GetDisplayName(NativeMethods.SIGDN_FILESYSPATH, out pszString) == NativeMethods.S_OK) { if (pszString != IntPtr.Zero) { try { this.Folder = Marshal.PtrToStringAuto(pszString); return DialogResult.OK; } finally { Marshal.FreeCoTaskMem(pszString); } } } } } return DialogResult.Cancel; } private DialogResult ShowLegacyDialog(IWin32Window owner) { using (var frm = new SaveFileDialog()) { frm.CheckFileExists = false; frm.CheckPathExists = true; frm.CreatePrompt = false; frm.Filter = "|" + Guid.Empty.ToString(); frm.FileName = "any"; if (this.InitialFolder != null) { frm.InitialDirectory = this.InitialFolder; } frm.OverwritePrompt = false; frm.Title = "Select Folder"; frm.ValidateNames = false; if (frm.ShowDialog(owner) == DialogResult.OK) { this.Folder = Path.GetDirectoryName(frm.FileName); return DialogResult.OK; } else { return DialogResult.Cancel; } } } public void Dispose() { } //just to have possibility of Using statement. } internal static class NativeMethods { #region Constants public const uint FOS_PICKFOLDERS = 0x00000020; public const uint FOS_FORCEFILESYSTEM = 0x00000040; public const uint FOS_NOVALIDATE = 0x00000100; public const uint FOS_NOTESTFILECREATE = 0x00010000; public const uint FOS_DONTADDTORECENT = 0x02000000; public const uint S_OK = 0x0000; public const uint SIGDN_FILESYSPATH = 0x80058000; #endregion #region COM [ComImport, ClassInterface(ClassInterfaceType.None), TypeLibType(TypeLibTypeFlags.FCanCreate), Guid("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7")] internal class FileOpenDialogRCW { } [ComImport(), Guid("42F85136-DB7E-439C-85F1-E4075D135FC8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IFileDialog { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] [PreserveSig()] uint Show([In, Optional] IntPtr hwndOwner); //IModalWindow [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] uint SetFileTypes([In] uint cFileTypes, [In, MarshalAs(UnmanagedType.LPArray)] IntPtr rgFilterSpec); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] uint SetFileTypeIndex([In] uint iFileType); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] uint GetFileTypeIndex(out uint piFileType); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] uint Advise([In, MarshalAs(UnmanagedType.Interface)] IntPtr pfde, out uint pdwCookie); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] uint Unadvise([In] uint dwCookie); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] uint SetOptions([In] uint fos); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] uint GetOptions(out uint fos); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void SetDefaultFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] uint SetFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] uint GetFolder([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] uint GetCurrentSelection([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] uint SetFileName([In, MarshalAs(UnmanagedType.LPWStr)] string pszName); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] uint GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] uint SetTitle([In, MarshalAs(UnmanagedType.LPWStr)] string pszTitle); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] uint SetOkButtonLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszText); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] uint SetFileNameLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszLabel); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] uint GetResult([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] uint AddPlace([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, uint fdap); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] uint SetDefaultExtension([In, MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] uint Close([MarshalAs(UnmanagedType.Error)] uint hr); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] uint SetClientGuid([In] ref Guid guid); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] uint ClearClientData(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] uint SetFilter([MarshalAs(UnmanagedType.Interface)] IntPtr pFilter); } [ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IShellItem { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] uint BindToHandler([In] IntPtr pbc, [In] ref Guid rbhid, [In] ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out IntPtr ppvOut); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] uint GetParent([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] uint GetDisplayName([In] uint sigdnName, out IntPtr ppszName); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] uint GetAttributes([In] uint sfgaoMask, out uint psfgaoAttribs); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] uint Compare([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, [In] uint hint, out int piOrder); } #endregion [DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern int SHCreateItemFromParsingName([MarshalAs(UnmanagedType.LPWStr)] string pszPath, IntPtr pbc, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IShellItem ppv); } </code></pre> <p>And use it like this</p> <pre><code>using (var frm = new OpenFolderDialog()) { if (frm.ShowDialog(this)== DialogResult.OK) { MessageBox.Show(this, frm.Folder); } } </code></pre>
3,287
<p>I've been wondering, what is the point of clog? As near as I can tell, clog is the same as cerr but with buffering so it is more efficient. Usually stderr is the same as stdout, so clog is the same as cout. This seems pretty lame to me, so I figure I must be misunderstanding it. If I have log messages going out to the same place I have error messages going out to (perhaps something in /var/log/messages), then I probably am not writing too much out (so there isn't much lost by using non-buffered cerr). In my experience, I want my log messages up to date (not buffered) so I can help find a crash (so I don't want to be using the buffered clog). Apparently I should always be using cerr.</p> <p>I'd like to be able to redirect clog inside my program. It would be useful to redirect cerr so that when I call a library routine I can control where cerr and clog go to. Can some compilers support this? I just checked DJGPP and stdout is defined as the address of a FILE struct, so it is illegal to do something like "stdout = freopen(...)".</p> <ul> <li>Is it possible to redirect clog, cerr, cout, stdin, stdout, and/or stderr?</li> <li>Is the only difference between clog and cerr the buffering?</li> <li>How should I implement (or find) a more robust logging facility (links please)?</li> </ul>
<blockquote> <p>Is it possible to redirect clog, cerr, cout, stdin, stdout, and/or stderr?</p> </blockquote> <p>Yes. You want the <a href="http://www.cplusplus.com/reference/iostream/ios/rdbuf.html" rel="noreferrer"><code>rdbuf</code></a> function.</p> <pre><code>ofstream ofs("logfile"); cout.rdbuf(ofs.rdbuf()); cout &lt;&lt; "Goes to file." &lt;&lt; endl; </code></pre> <blockquote> <p>Is the only difference between clog and cerr the buffering?</p> </blockquote> <p>As far as I know, yes.</p>
<h2>Basic Logger</h2> <pre><code>#define myerr(e) {CriticalSectionLocker crit; std::cerr &lt;&lt; e &lt;&lt; std::endl;} </code></pre> <p>Used as <code>myerr("ERR: " &lt;&lt; message);</code> or <code>myerr("WARN: " &lt;&lt; message &lt;&lt; code &lt;&lt; etc);</code></p> <p>Is very effective.</p> <p>Then do:</p> <pre><code>./programname.exe 2&gt; ./stderr.log perl parsestderr.pl stderr.log </code></pre> <p><strong>or just parse stderr.log by hand</strong></p> <p>I admit this is not for <em>extremely</em> performance critical code. But who writes that anyway.</p>
7,562
<p>Semantically speaking, is there an appropriate place in today's websites (late 2008+) where using the bold <code>&lt;b&gt;</code> and italic <code>&lt;i&gt;</code> tags are more useful than the more widely used <code>&lt;strong&gt;</code> and <code>&lt;em&gt;</code> tags?</p>
<p>Never. They are removed in XHTML 2.0 as they are presentational tags. CSS should be used to bold/italicise content.</p> <p><strong>edit:</strong> If you're looking for a purely presentational tag, that's what the <code>SPAN</code> tag with a class and a little CSS is for.</p>
<p><strong>When writing websites for mobile devices</strong>. They don't always support the 'latest and greatest' standards, are depreciated but not deleted from all modern browsers, and simply take up less space and bandwidth (though in theory the streams are compressed by either the websites or the wireless browser, it can't be counted on).</p> <p>-Adam</p>
8,916
<p>Say you have a shipment. It needs to go from point A to point B, point B to point C and finally point C to point D. You need it to get there in five days for the least amount of money possible. There are three possible shippers for each leg, each with their own different time and cost for each leg:</p> <pre><code>Array ( [leg0] =&gt; Array ( [UPS] =&gt; Array ( [days] =&gt; 1 [cost] =&gt; 5000 ) [FedEx] =&gt; Array ( [days] =&gt; 2 [cost] =&gt; 3000 ) [Conway] =&gt; Array ( [days] =&gt; 5 [cost] =&gt; 1000 ) ) [leg1] =&gt; Array ( [UPS] =&gt; Array ( [days] =&gt; 1 [cost] =&gt; 3000 ) [FedEx] =&gt; Array ( [days] =&gt; 2 [cost] =&gt; 3000 ) [Conway] =&gt; Array ( [days] =&gt; 3 [cost] =&gt; 1000 ) ) [leg2] =&gt; Array ( [UPS] =&gt; Array ( [days] =&gt; 1 [cost] =&gt; 4000 ) [FedEx] =&gt; Array ( [days] =&gt; 1 [cost] =&gt; 3000 ) [Conway] =&gt; Array ( [days] =&gt; 2 [cost] =&gt; 5000 ) ) ) </code></pre> <p>How would you go about finding the best combination programmatically?</p> <p>My best attempt so far (third or fourth algorithm) is:</p> <ol> <li>Find the longest shipper for each leg</li> <li>Eliminate the most "expensive" one</li> <li>Find the cheapest shipper for each leg</li> <li>Calculate the total cost &amp; days</li> <li>If days are acceptable, finish, else, goto 1</li> </ol> <p>Quickly mocked-up in PHP (note that the test array below works swimmingly, but if you try it with the test array from above, it does not find the correct combination):</p> <pre><code>$shippers["leg1"] = array( "UPS" =&gt; array("days" =&gt; 1, "cost" =&gt; 4000), "Conway" =&gt; array("days" =&gt; 3, "cost" =&gt; 3200), "FedEx" =&gt; array("days" =&gt; 8, "cost" =&gt; 1000) ); $shippers["leg2"] = array( "UPS" =&gt; array("days" =&gt; 1, "cost" =&gt; 3500), "Conway" =&gt; array("days" =&gt; 2, "cost" =&gt; 2800), "FedEx" =&gt; array("days" =&gt; 4, "cost" =&gt; 900) ); $shippers["leg3"] = array( "UPS" =&gt; array("days" =&gt; 1, "cost" =&gt; 3500), "Conway" =&gt; array("days" =&gt; 2, "cost" =&gt; 2800), "FedEx" =&gt; array("days" =&gt; 4, "cost" =&gt; 900) ); $times = 0; $totalDays = 9999999; print "&lt;h1&gt;Shippers to Choose From:&lt;/h1&gt;&lt;pre&gt;"; print_r($shippers); print "&lt;/pre&gt;&lt;br /&gt;"; while($totalDays &gt; $maxDays &amp;&amp; $times &lt; 500){ $totalDays = 0; $times++; $worstShipper = null; $longestShippers = null; $cheapestShippers = null; foreach($shippers as $legName =&gt; $leg){ //find longest shipment for each leg (in terms of days) unset($longestShippers[$legName]); $longestDays = null; if(count($leg) &gt; 1){ foreach($leg as $shipperName =&gt; $shipper){ if(empty($longestDays) || $shipper["days"] &gt; $longestDays){ $longestShippers[$legName]["days"] = $shipper["days"]; $longestShippers[$legName]["cost"] = $shipper["cost"]; $longestShippers[$legName]["name"] = $shipperName; $longestDays = $shipper["days"]; } } } } foreach($longestShippers as $leg =&gt; $shipper){ $shipper["totalCost"] = $shipper["days"] * $shipper["cost"]; //print $shipper["totalCost"] . " &amp;lt;?&amp;gt; " . $worstShipper["totalCost"] . ";"; if(empty($worstShipper) || $shipper["totalCost"] &gt; $worstShipper["totalCost"]){ $worstShipper = $shipper; $worstShipperLeg = $leg; } } //print "worst shipper is: shippers[$worstShipperLeg][{$worstShipper['name']}]" . $shippers[$worstShipperLeg][$worstShipper["name"]]["days"]; unset($shippers[$worstShipperLeg][$worstShipper["name"]]); print "&lt;h1&gt;Next:&lt;/h1&gt;&lt;pre&gt;"; print_r($shippers); print "&lt;/pre&gt;&lt;br /&gt;"; foreach($shippers as $legName =&gt; $leg){ //find cheapest shipment for each leg (in terms of cost) unset($cheapestShippers[$legName]); $lowestCost = null; foreach($leg as $shipperName =&gt; $shipper){ if(empty($lowestCost) || $shipper["cost"] &lt; $lowestCost){ $cheapestShippers[$legName]["days"] = $shipper["days"]; $cheapestShippers[$legName]["cost"] = $shipper["cost"]; $cheapestShippers[$legName]["name"] = $shipperName; $lowestCost = $shipper["cost"]; } } //recalculate days and see if we are under max days... $totalDays += $cheapestShippers[$legName]['days']; } //print "&lt;h2&gt;totalDays: $totalDays&lt;/h2&gt;"; } print "&lt;h1&gt;Chosen Shippers:&lt;/h1&gt;&lt;pre&gt;"; print_r($cheapestShippers); print "&lt;/pre&gt;"; </code></pre> <p>I think I may have to actually do some sort of thing where I literally make each combination one by one (with a series of loops) and add up the total "score" of each, and find the best one....</p> <p>EDIT: To clarify, this isn't a "homework" assignment (I'm not in school). It is part of my current project at work.</p> <p>The requirements (as always) have been constantly changing. If I were given the current constraints at the time I began working on this problem, I would be using some variant of the A* algorithm (or Dijkstra's or shortest path or simplex or something). But everything has been morphing and changing, and that brings me to where I'm at right now.</p> <p>So I guess that means I need to forget about all the crap I've done to this point and just go with what I know I should go with, which is a path finding algorithm.</p>
<p>Could alter some of the <a href="http://en.wikipedia.org/wiki/Shortest_path_problem" rel="noreferrer">shortest path algorithms</a>, like Dijkstra's, to weight each path by cost but also keep track of time and stop going along a certain path if the time exceeds your threshold. Should find the cheapest that gets you in under your threshold that way</p>
<p>I think that Dijkstra's algorithm is for finding a shortest path. </p> <p><strong>cmcculloh</strong> is looking for the minimal cost subject to the constraint that he gets it there in 5 days. </p> <p>So, merely finding the quickest way won't get him there cheapest, and getting there for the cheapest, won't get it there in the required amount of time. </p>
3,567
<p>I've read that Lambda Expressions are an incredibly powerful addition to C#, yet I find myself mystified by them. How can they improve my life or make my code better? Can anyone point to a good resource for learning such expressions?</p> <p>They seem cool as hell, but how do they relate to my day-to-day life as an asp.net developer?</p> <p>Edit: Thanks for the examples, and thanks for the link to Eric White's articles. I'm still digesting those now. One quick question: are lambda expressions useful for anything other than querying? Every example I've seen has been a query construct.</p>
<blockquote> <p>: are lambda expressions useful for anything other than querying</p> </blockquote> <p>Lamba expressions are nothing much other than a convenient way of writing a function 'in-line'.</p> <p>So they're useful any place you wanted a bit of code which can be called as though it's a separate function but which is actually written inside its caller. (In addition to keeping related code in the same location in a file, this also allows you to play fun games with variable scoping - see 'closures' for a reference.)</p> <p>An example of a non-query-related use of a lamba might be a bit of code which does something asynchronously that you start with ThreadPool.QueueUserWorkItem. The important point is that you could also write this using anonymous delegates (which were a C#2 introduction), or just a plain separate class member function.</p> <p>This <a href="http://blogs.msdn.com/jomo_fisher/archive/2005/09/13/464884.aspx" rel="noreferrer">http://blogs.msdn.com/jomo_fisher/archive/2005/09/13/464884.aspx</a> is a superb step-by-step introduction into all this stuff, which might help you.</p>
<p>Lambdas bring functional programing to C#. They are anonymous functions that can be passed as values to certain other functions. Used most in LINQ.</p> <p>Here is a contrived example:</p> <pre><code>List&lt;int&gt; myInts = GetAll(); IEnumerable&lt;int&gt; evenNumbers = myInts.Where(x =&gt; x % 2 == 0); </code></pre> <p>Now when you foreach through evenNumbers the lamda </p> <pre><code>x=&gt; x % 2 == 0 </code></pre> <p>is then applied as a filter to myInts.</p> <p>They become really useful in increasing readability to complicated algorithms that would have many nested IF conditionals and loops. </p>
4,503
<p>Trying to setup an SSH server on Windows Server 2003. What are some good ones? Preferably open source. I plan on using WinSCP as a client so a server which supports the advanced features implemented by that client would be great.</p>
<p>I've been using <a href="http://www.bitvise.com/winsshd" rel="nofollow noreferrer">Bitvise SSH Server</a> and it's really great. From install to administration it does it all through a GUI so you won't be putting together a sshd_config file. Plus if you use their client, <a href="http://www.bitvise.com/tunnelier" rel="nofollow noreferrer">Tunnelier</a>, you get some bonus features (like mapping shares, port forwarding setup up server side, etc.) If you don't use their client it will still work with the Open Source SSH clients.</p> <p>It's not Open Source and it costs $39.95, but I think it's worth it.</p> <p><strong>UPDATE</strong> <em>2009-05-21 11:10</em>: The pricing has changed. The current price is $99.95 per install for commercial, but now free for non-commercial/personal use. Here is the current <a href="http://www.bitvise.com/winsshd-pricing" rel="nofollow noreferrer">pricing</a>.</p>
<p>You can run OpenSSH on Cygwin, and even install it as a Windows service.</p> <p>I once used it this way to easily add backups of a Unix system - it would rsync a bunch of files onto the Windows server, and the Windows server had full tape backups.</p>
3,891
<p>Is there a definitive scalable 3D printer? </p> <p>I've seen examples of Chinese companies printing entire houses, and I'm curious as to printers / filaments that are intended (or at least able) be scaled up for (very) large print jobs. </p> <p>Since most hobby printers can take hundreds of hours for something that can still be held in our hands, so I'm curious if there are any designs for printers that are meant to extrude material efficiently with a easily scalable printing area. </p> <p>Open sourced / free is preferable; though I'm interested in <strong>any</strong> designs that exist, commercial included.</p>
<p>One big challenge with scaling anything up (or down), is that not all properties or characteristics scale linearly.</p> <p>Consider a trivial case: a small cube. If you double the size, you've quadrupled the surface area and octupled the weight.</p> <p>If you take a desktop-sized 3d printer design, and just double the size, it will weigh 8 times as much. But all the bolts holding it together are only 4 times as strong. So weight-bearing bolts are effectively under twice the strain (per unit of cross-sectional area); the exact factor depends of lots of things (orientation, leverage, etc).</p> <p>If you scale up by 10x, they'll potentially be under 10 times greater stress, and probably snap.</p> <p>Many, many parts will have similar issues: Drive belts that are twice as wide and twice as thick will still have 1/2 the (relative) strength -- and stiffness for the motors to overcome. </p> <p>The stepper motors have to move 8 times the weight, <em>and</em> you'll want them to move far, far faster. But steppers lose torque when you spin them faster.</p> <p>My main printer is pretty much a MendelMax 2, but the Y axis is about 6 times bigger (X and Z are normal). On MM2 the whole build platform moves along Y -- on my printer it weighs far more than on a regular-size MM2 -- it's 6 times the mass just because of size, besides that it has to be much stiffer to avoid sagging over that distance. I went to a larger motor, but it could still barely move the axis. I eventually got it to move at pretty normal speed, but to print long objects it really should be 6 times faster or so.</p> <p>That would require an amazing motor -- and really big electronics to drive it.</p> <p>Another challenge is the printing material -- 20mm diameter PLA fiber would be really impressive, but a little hard to find, and a spool would be hard to lift. The power needed to melt it fast enough would be impressive, too. Bridge and house printers I've seen in reports, use pumped concrete through about a 100mm wide nozzle (I have no idea what the nozzle is made of, to stand up to the abrasion). See <a href="http://www.wired.co.uk/news/archive/2015-09/21/giant-3d-printer-builds-houses" rel="nofollow noreferrer">Watch this giant 3D printer build a house</a> for some cool pictures and video.</p> <p>Scaling up is a fascinating project -- but it's harder than it looks.</p>
<p>As far as I know, right now, all the "3D printers" that can print houses, bridges, etc. are experimental models (and sometimes, vey elaborate art projects) - they just don't exist except as one-off creations designed as a proof-of-concept showing this can be done.</p> <p>Maybe some of those project published their plans and code but they are not designed for mass production or general use, even if you manage to build another copy of one of them it will probably be able to print just the same project the original printed. </p> <p>You specifically asked about speed, material and build area:</p> <p><strong>Speed:</strong> the speed really depends on the size of the printer's nozzle, the typical desktop printer has a 0.4mm nozzle, if you replace it with a 1mm nozzle the printer will be approximately twice as fast (1.25 nozzle area vs 3.14 nozzle area, assuming you have an hotend designed for larger nozzles that can melt the plastic fast enough).</p> <p>Now, the "house printer" does not use a standard desktop hotend (see material below) and buildings don't have fine details so you can make the head much larger.</p> <p>However, as far as I know the early prototypes are still much slower then conventional construction methods.</p> <p><strong>Material:</strong> houses are typically not made of plastic, the printers I know of have welding equipment instead of an hotend and extrude steel</p> <p>There are probably other methods but I bet all of them use typical construction materials such as steel and not thermoplastic.</p> <p><strong>Size:</strong> and last but not least, it's obviously not practical to build a printer with as house sized platform, the house printers are actually relatively small robots that travel across the construction project, leaving material behind them and then climb over the previous layer to print the next part.</p>
200
<p>I had this idea for bulky parts for just printing the shell (PLA) then pouring in some kind of filler in to make up the bulk/strength.</p> <p>Printing bulk .2mm at a time line by line is slow and subject to warping!</p> <p>So I though precision print a shell and fill it with 'something' - has this been done by anyone? What is a good something to use?</p> <p>Yours hopefully!</p>
<p>I've looked into doing something similar to this before and love the idea, never had the chance to follow through on it yet. This is sort of a hybrid method between cast molding and 3D printing. </p> <p>The accepted answer to a question I had a while back had some very good points by fred_dot_u</p> <p><a href="https://3dprinting.stackexchange.com/questions/3720/post-processing-fdm-for-strengrh">Post processing FDM for strengrh</a></p> <p>Short version, Epoxy is a good option but you may have to consider heat generated from it. Urethane is another really good option (cast urethane is a pretty standard process). Chem-Eng isn't my area of expertise but there is a huge range of material options out there that can be mixed as two parts. I think there are enough options out there right now that you can choose your material properties you need and then select the material from there.</p> <p>You could also consider going the chopped-fiber composite route. (carbon, glass, etc) and then combine with whatever the appropriate resin is for those materials. </p> <p>I see the most difficult part of this is getting the shells to print properly. When I had looked into doing this, I considered modeling my part then hollowing it out completely. Then going back into the hollow part and designing in minimal internal structures for the purpose of supporting the thin-walled shell model. Printing that, and then drilling and filling the part after the fact. This approach I see as being a good option however the location of the drill points would be critical otherwise you could get voids as your fill material is injected in. And, the additional modeling time wouldn't be insignificant, however the saving I expected would come from having a ridiculously strong part, with complex geometry and be significantly cheaper than even a cast-urethane part.</p> <p>If you get some good results, please post a link to them! This is a huge interest of mine!</p>
<p>Not exactly the same, but MakerBot Industries is making improvements to their programs by allowing users to do away with standard infill practices (patterned infill). Their approach is to treat infill similarly to how they treat outer support structures, the "infill" only exists in the interest of supporting roofs.</p> <p><a href="https://www.makerbot.com/media-center/2017/03/20/introducing-makerbot-minfill" rel="nofollow noreferrer">Check out MakerBot's article about it</a>.</p> <p>This method achieves the same time-savings that you describe in your question, but will not necessarily provide as much structural integrity, depending on your approach.</p>
573
<p>Currently I know of only two ways to cache data (I use PHP but I assume that the same will apply to most languages).</p> <ol> <li>Save the cache to a file</li> <li>Save the cache to a large DB field</li> </ol> <p>Are there any other (perhaps better) ways of caching or is it really just this simple?</p>
<p>Maybe you want to explicit more precisely what you want to cache. You have all this opportunities to cache: </p> <ul> <li><b>Accessing the Data Base</b> where you cache the data first correctly tuning your RDBMS, then using a layer to delegate the decision to detect multiple queries for the same data (with <a href="http://adodb.sourceforge.net/" rel="nofollow noreferrer">AdoDB</a> for example.)</li> <li><b>Extracting calculations from loops in the code</b> so you don't compute the same value multiple times. <i>Here your third way: storing results in the session for the user.</i></li> <li><b>Precompiling the PHP code</b> with an extension like <a href="http://pecl.php.net/package/APC" rel="nofollow noreferrer">APC Cache</a>. This way you don't have to compile the same PHP code for every request.</li> <li><b>The page sent to the user</b> making sure you're setting the right META tags (do a good thing for the world and don't use ETL at least absolutly necessary); or maybe making dynamic pages completely static (having a batch process that generates .html pages); or by using a proxy cache like <a href="http://www.squid-cache.org/" rel="nofollow noreferrer">Squid</a>.</li> <li><b>Prefetching</b> and by this I refer all those opportunities you have to improve the user experience just by doing things while the user don't look your way. For example, preloading IMG tags in the HTML file, tunning the RDBMS for prefectching, precomputing results storing complex computations in the database, etc. </li> </ul> <p>From my experience, I'd bet you that your code can be improved a lot before we start to talk about caching things. Consider, for example, how well structured is the navigation of your site and how well you control the user experience. Then check your code with a tool like <a href="http://xdebug.org/" rel="nofollow noreferrer">XDebug</a>. </p> <p>Verify also how well are you making your SQL queries and how well are you indexing your tables. Then check your code again to look for opportunities to apply the rule "read many times but write just once"</p> <p>Use a simple tool like <a href="http://developer.yahoo.com/yslow/" rel="nofollow noreferrer">YSlow</a> to hint other simple things to improve. Check your code again looking for opportunities to put logic in the browser (via JavaScript)</p>
<p>Seconding memcached, does the simple stuff well and can go distributive and all that jazz if you need it too</p>
2,608
<p>Why prefer composition over inheritance? What trade-offs are there for each approach? When should you choose inheritance over composition?</p>
<p><em>Prefer composition over inheritance as it is more malleable / easy to modify later, but do not use a compose-always approach.</em> With composition, it's easy to change behavior on the fly with Dependency Injection / Setters. Inheritance is more rigid as most languages do not allow you to derive from more than one type. So the goose is more or less cooked once you derive from TypeA.</p> <p>My acid test for the above is: </p> <ul> <li><p>Does TypeB want to expose the complete interface (all public methods no less) of TypeA such that TypeB can be used where TypeA is expected? Indicates <strong>Inheritance</strong>. </p> <ul> <li>e.g. A Cessna biplane will expose the complete interface of an airplane, if not more. So that makes it fit to derive from Airplane. </li> </ul></li> <li><p>Does TypeB want only some/part of the behavior exposed by TypeA? Indicates need for <strong>Composition.</strong> </p> <ul> <li>e.g. A Bird may need only the fly behavior of an Airplane. In this case, it makes sense to extract it out as an interface / class / both and make it a member of both classes.</li> </ul></li> </ul> <p><strong>Update:</strong> Just came back to my answer and it seems now that it is incomplete without a specific mention of Barbara Liskov's <a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle" rel="noreferrer">Liskov Substitution Principle</a> as a test for 'Should I be inheriting from this type?'</p>
<p>What do you want to force yourself (or another programmer) to adhere to and when do you want to allow yourself (or another programmer) more freedom. It has been argued that inheritance is helpful when you want to force someone into a way of dealing with/solving a particular problem so they can't head off in the wrong direction.</p> <p><code>Is-a</code> and <code>Has-a</code> is a helpful rule of thumb.</p>
7,143
<p>Here is one trivial question, that I am not sure how to handle. I need to display list of categories on every page, and to be able to choose items from a specific category to be displayed. I use asp.net MVC, and have chosen to create a user control that will display categories. My question is: what is the best approach to pass data to a user control. I already found some information in these blog posts:</p> <p><a href="http://weblogs.asp.net/stephenwalther/archive/2008/08/12/asp-net-mvc-tip-31-passing-data-to-master-pages-and-user-controls.aspx" rel="nofollow noreferrer">http://weblogs.asp.net/stephenwalther/archive/2008/08/12/asp-net-mvc-tip-31-passing-data-to-master-pages-and-user-controls.aspx</a></p> <p><a href="http://blog.matthidinger.com/2008/02/21/ASPNETMVCUserControlsStartToFinish.aspx" rel="nofollow noreferrer">http://blog.matthidinger.com/2008/02/21/ASPNETMVCUserControlsStartToFinish.aspx</a></p> <p>I would like also to hear your opinion.</p> <p>PS. I'd like to hear Jeff's opinion, especially because of his experience with UC's on Stackoverflow</p>
<p>I'm using mvc components, which replaced ascx user controls in preview 4.<br> Example: <a href="http://blog.wekeroad.com/blog/asp-net-mvc-preview-4-componentcontroller-is-now-renderaction/" rel="nofollow noreferrer">http://blog.wekeroad.com/blog/asp-net-mvc-preview-4-componentcontroller-is-now-renderaction/</a><br> So, you call components action from View, which then choose View to render. You can pass data in this call also. </p>
<p>it is the mvc futures project. i will probably try this <a href="http://forums.asp.net/t/1303328.aspx" rel="nofollow noreferrer">http://forums.asp.net/t/1303328.aspx</a>. I need to render menu with categories.</p>
3,449
<p>Help! I have an Axis web service that is being consumed by a C# application. Everything works great, except that arrays of long values always come across as [0,0,0,0] - the right length, but the values aren't deserialized. I have tried with other primitives (ints, doubles) and the same thing happens. What do I do? I don't want to change the semantics of my service.</p>
<p>Here's what I ended up with. I have never found another solution out there for this, so if you have something better, by all means, contribute.</p> <p>First, the long array definition in the wsdl:types area:</p> <pre><code> &lt;xsd:complexType name="ArrayOf_xsd_long"&gt; &lt;xsd:complexContent mixed="false"&gt; &lt;xsd:restriction base="soapenc:Array"&gt; &lt;xsd:attribute wsdl:arrayType="soapenc:long[]" ref="soapenc:arrayType" /&gt; &lt;/xsd:restriction&gt; &lt;/xsd:complexContent&gt; &lt;/xsd:complexType&gt; </code></pre> <p>Next, we create a SoapExtensionAttribute that will perform the fix. It seems that the problem was that .NET wasn't following the multiref id to the element containing the double value. So, we process the array item, go find the value, and then insert it the value into the element:</p> <pre><code>[AttributeUsage(AttributeTargets.Method)] public class LongArrayHelperAttribute : SoapExtensionAttribute { private int priority = 0; public override Type ExtensionType { get { return typeof (LongArrayHelper); } } public override int Priority { get { return priority; } set { priority = value; } } } public class LongArrayHelper : SoapExtension { private static ILog log = LogManager.GetLogger(typeof (LongArrayHelper)); public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute) { return null; } public override object GetInitializer(Type serviceType) { return null; } public override void Initialize(object initializer) { } private Stream originalStream; private Stream newStream; public override void ProcessMessage(SoapMessage m) { switch (m.Stage) { case SoapMessageStage.AfterSerialize: newStream.Position = 0; //need to reset stream CopyStream(newStream, originalStream); break; case SoapMessageStage.BeforeDeserialize: XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = false; settings.NewLineOnAttributes = false; settings.NewLineHandling = NewLineHandling.None; settings.NewLineChars = ""; XmlWriter writer = XmlWriter.Create(newStream, settings); XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(originalStream); List&lt;XmlElement&gt; longArrayItems = new List&lt;XmlElement&gt;(); Dictionary&lt;string, XmlElement&gt; multiRefs = new Dictionary&lt;string, XmlElement&gt;(); FindImportantNodes(xmlDocument.DocumentElement, longArrayItems, multiRefs); FixLongArrays(longArrayItems, multiRefs); xmlDocument.Save(writer); newStream.Position = 0; break; } } private static void FindImportantNodes(XmlElement element, List&lt;XmlElement&gt; longArrayItems, Dictionary&lt;string, XmlElement&gt; multiRefs) { string val = element.GetAttribute("soapenc:arrayType"); if (val != null &amp;&amp; val.Contains(":long[")) { longArrayItems.Add(element); } if (element.Name == "multiRef") { multiRefs[element.GetAttribute("id")] = element; } foreach (XmlNode node in element.ChildNodes) { XmlElement child = node as XmlElement; if (child != null) { FindImportantNodes(child, longArrayItems, multiRefs); } } } private static void FixLongArrays(List&lt;XmlElement&gt; longArrayItems, Dictionary&lt;string, XmlElement&gt; multiRefs) { foreach (XmlElement element in longArrayItems) { foreach (XmlNode node in element.ChildNodes) { XmlElement child = node as XmlElement; if (child != null) { string href = child.GetAttribute("href"); if (href == null || href.Length == 0) { continue; } if (href.StartsWith("#")) { href = href.Remove(0, 1); } XmlElement multiRef = multiRefs[href]; if (multiRef == null) { continue; } child.RemoveAttribute("href"); child.InnerXml = multiRef.InnerXml; if (log.IsDebugEnabled) { log.Debug("Replaced multiRef id '" + href + "' with value: " + multiRef.InnerXml); } } } } } public override Stream ChainStream(Stream s) { originalStream = s; newStream = new MemoryStream(); return newStream; } private static void CopyStream(Stream from, Stream to) { TextReader reader = new StreamReader(from); TextWriter writer = new StreamWriter(to); writer.WriteLine(reader.ReadToEnd()); writer.Flush(); } } </code></pre> <p>Finally, we tag all methods in the Reference.cs file that will be deserializing a long array with our attribute:</p> <pre><code> [SoapRpcMethod("", RequestNamespace="http://some.service.provider", ResponseNamespace="http://some.service.provider")] [return : SoapElement("getFooReturn")] [LongArrayHelper] public Foo getFoo() { object[] results = Invoke("getFoo", new object[0]); return ((Foo) (results[0])); } </code></pre> <p>This fix is long-specific, but it could probably be generalized to handle any primitive type having this problem.</p>
<p>Found this link that may offer a better alternative: <a href="http://www.tomergabel.com/GettingWCFAndApacheAxisToBeFriendly.aspx" rel="nofollow noreferrer">http://www.tomergabel.com/GettingWCFAndApacheAxisToBeFriendly.aspx</a></p>
5,005
<p>I have a bunch of latitude/longitude pairs that map to known x/y coordinates on a (geographically distorted) map.</p> <p>Then I have one more latitude/longitude pair. I want to plot it on the map as best is possible. How do I go about doing this?</p> <p>At first I decided to create a system of linear equations for the three nearest lat/long points and compute a transformation from these, but this doesn't work well at all. Since that's a linear system, I can't use more nearby points either.</p> <p>You can't assume North is up: all you have is the existing lat/long->x/y mappings.</p> <p>EDIT: it's not a Mercator projection, or anything like that. It's arbitrarily distorted for readability (think subway map). I want to use only the nearest 5 to 10 mappings so that distortion on other parts of the map doesn't affect the mapping I'm trying to compute.</p> <p>Further, the entire map is in a very small geographical area so there's no need to worry about the globe--flat-earth assumptions are good enough.</p>
<p>Are there any more specific details on the kind of distortion? If, for example, your latitudes and longitudes are "distorted" onto your 2D map using a Mercator projection, the conversion math is <a href="http://www.wikipedia.org/wiki/Mercator_projection" rel="noreferrer">readily available</a>.</p> <p>If the map is distorted truly arbitrarily, there are lots of things you could try, but the simplest would probably be to compute a <a href="http://www.wikipedia.org/wiki/Weighted_mean" rel="noreferrer">weighted average</a> from your existing point mappings. Your weights could be the squared inverse of the x/y distance from your new point to each of your existing points.</p> <p>Some pseudocode:</p> <pre><code>estimate-latitude-longitude (x, y) numerator-latitude := 0 numerator-longitude := 0 denominator := 0 for each point, deltaX := x - point.x deltaY := y - point.y distSq := deltaX * deltaX + deltaY * deltaY weight := 1 / distSq numerator-latitude += weight * point.latitude numerator-longitude += weight * point.longitude denominator += weight return (numerator-latitude / denominator, numerator-longitude / denominator) </code></pre> <p>This code will give a relatively simple approximation. If you can be more precise about the way the projection distorts the geographical coordinates, you can probably do much better.</p>
<p>the problem is that the sphere can be distorted a number of ways, and having all those points known on the equator, lets say, wont help you map points further away.</p> <p>You need better 'close' points, then you can assume these three points are on a plane with the fourth and do the interpolation --knowing that the distance of longitudes is a function, not a constant.</p>
2,415
<p>Whenever it start printing the extruder starts clicking, I tried adjusting the voltage with no luck, it's still clicking. And it doesn't extrude a lot of plastic sometimes it even stops extruding but the extruder is still turning. Can someone help?</p>
<p>The clicking you are hearing is either the stepper motor skipping steps or the hobbed gear losing grip on the filament.</p> <p>Either way, it means that the filament opposes an unusually high resistence to be pushed forward.</p> <p>A key information to be able to diagnose your problem is whether the clicking is on the firsts couple of layers or throughout the print.</p> <p><strong>If it is only for the first 1-3 layers the problem is likely to be the printing bed too high</strong> (or deformed), so that the nozzle touches it and the bed acts a "lid" on the nozzle preventing the molten plastic to get out. If this is the case, adjust the printing bed to be flat and level (and the nozzle at the right height when homed on the Z axis.</p> <p><strong>If the problem persists throughout the full print</strong> the problem is likely to be related to one of the following:</p> <ul> <li><strong>the extruder not managing to get a firm grip</strong> on the filament (worn teeth, slack spring, ...)</li> <li><strong>the stepper motor being underpowered</strong> (this seems not to be your case, given that you have already adjusted the voltage)</li> <li><strong>a clog, adhesion, or restriction in either the bowden tube or the extruder</strong>, for which the best solution is disassemble, inspect and clean (eventually changing the bowden tube if it has been deformed).</li> </ul>
<p>I have an X5S and quite frankly, I never got it print properly because of these persistent issues. Thank you for the most excellent comments and suggestions. Lots to investigate.</p> <p>I added an anycubic glass table but that takes longer to heat up. But i am unable to get adhesion on the first layers and the clicking kicks in shortly thereafter. I wonder if this thermal latency might imply a colder bed on first layers. I have tweaked the leveling so many times it is not funny. This is pointing to friction in the Bowden delivery system and the extruder itself.</p> <p>I got an E3D that I must adapt. Too bad i cannot print those parts!</p> <p>I have noted also a great variety of results from different printer filaments brands as well.</p>
857
<p>I already tried a lot settings in Cura and try to search for a solution but without success. Maybe someone got this issue and solved it.</p> <p>I want to prevent Cura from printing such gaps at the wings to make it in one run. With ironing one run would (hopefully) bring better results. See the animation for what I mean.</p> <p><a href="https://i.stack.imgur.com/4C91H.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4C91H.gif" alt="enter image description here" /></a></p> <p>Why want to do this? I hope to prevent thes ironing issues shown in the following pic.</p> <p><a href="https://i.stack.imgur.com/Tq5vX.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Tq5vX.jpg" alt="enter image description here" /></a></p>
<p>That depends very much on what your goal is with the box. If it needs to be hollow and you don't need any access to the inside (and also prefer it to be printed in one piece) than the answer provided by user77232 would probably be the best.</p> <p>Alternatively, if you need access to the inside of the box you would probably be best off printing the box in two pieces. A box and a lid. This way you can print the box without support and also save on material that would otherwise be used as infill.</p> <p>The amount of light coming into your box also depends on the translucency of your material and brightness of the light source. To find the required wall thickness would be a matter of testing with the desired material.</p>
<ol> <li>Print it as a whole object</li> <li>Use 20% infill.</li> <li>Profit!</li> </ol>
1,740
<p>I've been using PHP &amp; MySQL for ages and am about to start using PostgreSQL instead.</p> <p>What's the preferred method? </p> <p>Is it via the PDO objects or is there something better?</p>
<p>PDO objects are the new hotness. I'd recommend that as long as you can ensure that your target platform will always be running PHP 5.2+.</p> <p>There are many other database abstraction layers that support PostgreSQL that are compatible with older versions of PHP; I'd recommend <a href="http://adodb.sourceforge.net/" rel="noreferrer">ADODB</a>.</p> <p>You should really be using PDO or a different abstraction layer even for your MySQL work; that way you won't have this problem again!</p>
<p>I would also suggest creating an inherited PDO class or a wrapper class if you decide not to use PDO. This would provide you with a lot more flexibility in the future. ie. Calculating query execution time.</p>
3,173
<p>We are trying to create a web-service that we plan to pass a variable amount of variables to it.</p> <p>Can this be done?</p> <p>Basically instead of pass all possible parameters we wish to pass only the set values and use the defaults set in the web-service.</p> <p>Here is an example of the XML we are looking to send, we would sent an unknown amount of functions depending on the needed return.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"&gt; &lt;soap:Body&gt; &lt;WebMethod xmlns="http://tempuri.org/"&gt; &lt;domains&gt; &lt;function1&gt; &lt;title&gt;Some Title&lt;/title&gt; &lt;type&gt;25&lt;/type&gt; &lt;/function1&gt; &lt;function2 /&gt; &lt;function3&gt; &lt;param&gt;13&lt;/param&gt; &lt;/function3&gt; &lt;/domains&gt; &lt;/WebMethod&gt; &lt;/soap:Body&gt; &lt;/soap:Envelope&gt; </code></pre> <p>Will this work or should we do a different way?</p>
<p>I would pass in an xml document instead of doing concreate functions for this. </p> <p>The webservice in your example is leaky - the consumer needs to know too much about this interface and the implementation of the webservice internally. </p> <p>XML Document and then tie that with an XSD. That way you can prevalidte the input to the webservice. </p> <p>Take a look at these</p> <p><a href="http://www.ibm.com/developerworks/webservices/library/ws-docstyle.html" rel="nofollow noreferrer">IBM Developer</a> <a href="http://forums.asp.net/p/1253455/2323689.aspx#2323689" rel="nofollow noreferrer">ASP.NET Forum</a></p> <p>I would also recommend using this for testing webservices and its free <a href="http://www.codeplex.com/wsstudioexpress" rel="nofollow noreferrer">WSStudio</a></p>
<p>You can simply pass a variable-length array as a parameter.</p>
5,431
<p>I made a few successful prints since I got my CR-10 two weeks ago and I didn't run into any major trouble. The printer is new.</p> <p>Today I set it to "preheat" mode while I was preparing the SD card with the settings being 210°C for the nozzle and 60°C for the bed. When I wanted to start the print I noticed that the temperature showed as "actual temperature" on the printer's screen showed 233°C and it was going up steadily while the "requested" temperature was still 210°C.</p> <p>Thiking it might be a mis-manipulation on my part I powered it down for a few minutes (I got scared by the high-temp) and then powered it back on. I then immediately requested the print to start. The CR-10 heated up to the proper value, started printing and kept heating the nozzle. I stopped it at 217°C.</p> <p>I looked for an answer on the internet but all I could find is people having trouble with the nozzle not heating at all ...</p>
<p>This is not an easy one to solve, the firmware of the printer should be keeping the printer at a certain temperature depending on the temperature setting and the current value. If the firmware is not able to keep the temperature at the requested level, but goes beyond that level, that could be considered "strange". As it measures the temperature (and reports it on your display) it must know that it is over the limit and thus should not power the hotend.</p> <p>In this process there are a few possible candidates for you to look at:</p> <ul> <li>Check for a faulty <a href="https://en.wikipedia.org/wiki/MOSFET" rel="nofollow noreferrer">MOSFET</a> (sort of an electronic switch) on your controller board (is it leaking current to the hotend?). </li> <li>Check and or update the current settings for the <a href="https://en.wikipedia.org/wiki/PID_controller" rel="nofollow noreferrer">PID</a> values (settings for the control loop of the hotend). The PID values control the overshoot of the temperature. E.g. is this is very large overshoot? When incorrectly configured the temperature can get higher, but normally should never increase to infinity, are you sure it keeps rising? The determination of the new values is called <a href="https://reprap.org/wiki/PID_Tuning" rel="nofollow noreferrer">PID tuning</a>. Important commands (that need to be send over a USB connected printer with a 3D printer terminal application like Repetier Host, OctoPrint or Pronterface): <ul> <li>The <a href="https://reprap.org/wiki/G-code#M503:_Print_settings" rel="nofollow noreferrer">M503</a> <a href="https://reprap.org/wiki/G-code" rel="nofollow noreferrer">G-code</a> command shows the current settings (somewhere in the heap of all settings).</li> <li>The <a href="https://reprap.org/wiki/G-code#M303:_Run_PID_tuning" rel="nofollow noreferrer">M303</a> <a href="https://reprap.org/wiki/G-code" rel="nofollow noreferrer">G-code</a> command can determine the values.</li> </ul></li> <li>Reflash the firmware</li> <li>Replace the printer controller board</li> </ul> <p>You could replace the thermistor and the heater cartridge (just to be sure, most definitely not the problem, but they are really cheap to replace). The thermistor works as it reports the temperature, and the heater element doesn't get powered by itself. </p> <p>As suggested below <strong>the most likely candidate for your problem is the MOSFET</strong>. These are pretty easy to replace (depending on your board) or replaceable by an external MOSFET module (if you happen to have one lying around).</p>
<p>A similar condition occurred in my 3D printer. I solved the same. I checked all my connection and I came to know that I connected the thermistor of the extruder in the wrong port. So just check the connection of your thermistor.</p> <hr> <p>Actually my 3D printer circuit board frequently failed because of over current. I then added a multimeter in series with my power supply and the load, also a voltmeter across the voltage regulator. I then corrected every motor driver DRV8825 to a reference voltage of 0.6&nbsp;V so that the maximum current supplied to each of the motor will be less than 1&nbsp;A. All these made my circuit checked ok. Then I uploaded the G-code, but I couldn't print because my extruder gets heated about 280 °C and got reset and suddenly shut down the extruder supply. This continues to happen.</p> <p>Then I reinstalled the Marlin firmware and I also changed the port of my thermistor. Now my 3D printer is ok and prints nicely. I also faced another problem while I gave the print command - it showed that the extruder and bed had started heating but it actually was not heating. So I reinstalled the firmware again and this fixed it. Now my 3D printer works OK. You just try for these steps:</p> <ol> <li>Check the connection.</li> <li>Reinstall the firmware.</li> <li>Try manually preheat the extruder, and just see whether it heats to infinity.</li> </ol> <p>These are my working experience please try for these, I think it will help you. Just don't leave it you will get the solution. Keep on trying.</p>
968